bool compare(const A & lhs, const A & rhs) {
return std::tie(lhs.x, lhs.y) < std::tie(rhs.x, rhs.y);
}
std::sort(v.begin(), v.end(), compare);
for (auto first = v.begin(), last = {}; it != v.end(); it = last) {
A result = *first;
last = std::upper_bound(first++, v.end(), result, compare);
for (; first != last; ++first) {
if (first->z) {
result.z = first->z;
}
// this is an in-place set_union
std::merge(result.w.begin(), result.w.end(), first->w.begin(), first->w.end());
auto unique_end = std::unique(result.w.begin(), result.w.end());
result.w.erase(unique_end, result.w.end());
}
merged.push_back(result);
}
You can do it in O(NlogN * MlogM) if you sort the input, and then do a linear pass to merge.
N is the length of v, and M is the length of the A::ws.
bool compare(const A & lhs, const A & rhs) {
return std::tie(lhs.x, lhs.y) < std::tie(rhs.x, rhs.y);
}
std::sort(v.begin(), v.end(), compare);
for (auto first = v.begin(), last = {}; it != v.end(); it = last) {
A result = *first;
last = std::upper_bound(first++, v.end(), result, compare);
for (; first != last; ++first) {
if (first->z) {
result.z = first->z;
}
// this is an in-place set_union
std::merge(result.w.begin(), result.w.end(), first->w.begin(), first->w.end());
auto unique_end = std::unique(result.w.begin(), result.w.end());
result.w.erase(unique_end, result.w.end());
}
merged.push_back(result);
}
发布评论
评论(2)
如果您对输入进行排序,则可以在O(nlogn * mlogm)中执行此操作,然后进行线性通过以合并。
n是
v
的长度,m是a :: W
s的长度。You can do it in O(NlogN * MlogM) if you sort the input, and then do a linear pass to merge.
N is the length of
v
, and M is the length of theA::w
s.最好的方法是使用
std :: unordered_map
这将允许在恒定时间内找到匹配项,因此最终的时间复杂性将为o(n)
:https://godbolt.org/z/wz8vbz4h1
The best way is to use
std::unordered_map
this will allow to find matching item in constant time, so final time complexity will beO(n)
:https://godbolt.org/z/Wz8vbz4h1