Usually root_regions size is small so unlikey
this change will provide a noticable difference.
However it's easy to make sure that even with
large number of root_regions it works reasonably
fast.
Differential D151781
[NFC][lsan] Avoid O(N^2) algorithm vitalybuka on May 30 2023, 11:02 PM. Authored by
Details
Usually root_regions size is small so unlikey However it's easy to make sure that even with
Diff Detail
Event TimelineComment Actions D151779 added an interaction algorithm of two region lists using a scan line algorithm. The algorithm needs to maintain a sorted event array. This problem has a property that the second region list (mapped_regions) is sorted and the first region list (root_regions) can be sorted in place. Comment Actions I don't realy concerned with space complexity here. Comment Actions Yes, it's simple enough, but a merge style algorithm for intersection will be simpler :) #include <algorithm> #include <cassert> #include <cstdio> #include <utility> #include <vector> using namespace std; vector<pair<int, int>> intersect(vector<pair<int, int>> &a, const vector<pair<int, int>> &b) { assert(is_sorted(a.begin(), a.end())); assert(is_sorted(b.begin(), b.end())); vector<pair<int, int>> ret; auto ia = a.begin(); auto ib = b.begin(); while (ia != a.end() && ib != b.end()) { // We don't merge [10,12) [12,14) into [10,14), but ScanRangeForPointers is happy with that. auto l = max(ia->first, ib->first); auto r = min(ia->second, ib->second); if (l < r) ret.emplace_back(l, r); if (ia->second < ib->second) ++ia; else ++ib; } return ret; } int main() { vector<pair<int, int>> a{{1,2}, {2,4}, {5,8}, {10,12}, {12,14}, {14, 16}}; vector<pair<int, int>> b{{1,5}, {6,7}, {7,9}, {10,12}, {12,14}, {14, 16}}; for (auto x : intersect(a, b)) printf("[%d, %d)\n", x.first, x.second); } Comment Actions This is not general^, and unnecessary rely on user behavior.
It's not complicated, but it need some time to realize if this will handled overlapping regions in one of inputs (seems it will not). also it's going to be annoying to templatize to support XOR or AND version if needed. |