If the segments do not change dynamically, this is a simple problem. Just sort all the segments to the left, then scan the sorted items:
struct Seg {int L,R;}; int cmp(Seg a, Seg b) {return aL < bL;} int union_segs(int n, Seg *segs, Segs *output) { sort(segs, segs + n, cmp); int right_most = -1; int cnt = 0; for (int i = 0 ; i < n ; i++) { if (segs[i].L > right_most) { right_most = segs[i].R; ++cnt; output[cnt].L = segs[i].L; output[cnt].R = segs[i].R; } if (segs[i].R > right_most) { right_most = segs[i].R; output[cnt].R = segs[i].R; } } return cnt+1; }
The complexity of the time is O (nlogn) (sorting) + O (n) (scanning).
If segments are inserted and deleted dynamically, and you want to request a join at any time, you will need more complex data structures, such as a range tree .
source share