求区间交集与并集

Posted on 2023-02-19 16:21  lyc2002  阅读(27)  评论(0编辑  收藏  举报

代码

求区间交集

void get_intersection(vector<PII> &segs)
{
    vector<PII> res;
    
    sort(segs.begin(), segs.end());
    int l = -2e9, r = 2e9;
    for (auto seg : segs) {
        if (seg.first > r) {
            if (l != -2e9) res.push_back({l, r});
            l = seg.first;
            r = seg.second;
		} else {
            l = max(l, seg.first);
            r = min(r, seg.second);
        }
    }
    if (l != -2e9) res.push_back({l, r});
    
    segs = res;
}

求区间并集

void get_union(vector<PII> &segs)
{
    vector<PII> res;
    
    sort(segs.begin(), segs.end());
    int l = -2e9, r = 2e9;
    for (auto seg : segs) {
        if (seg.first > r) {
            if (l != -2e9) res.push_back({l, r});
            l = seg.first;
            r = seg.second;
		} else {
            r = max(r, seg.second);
        }
    }
    if (l != -2e9) res.push_back({l, r});
    
    segs = res;
}