在 C++ 中合并范围

2022-01-24 00:00:00 merge algorithm range c++

我有一个随机排序的唯一封闭范围列表 R0...Rn-1 其中

I have a list of randomly ordered unique closed-end ranges R0...Rn-1 where

Ri = [r1i, r2i] (r1i <= r2i)

Ri = [r1i, r2i] (r1i <= r2i)

随后一些范围重叠(部分或完全),因此需要合并.

Subsequently some of the ranges overlap (partially or completely) and hence require merging.

我的问题是,用于合并这些范围的最佳算法或技术是什么.此类算法的示例或执行此类合并操作的库的链接会很棒.

My question is, what are the best-of-breed algorithms or techniques used for merging such ranges. Examples of such algorithms or links to libraries that perform such a merging operation would be great.

推荐答案

你需要做的是:

  1. 按字典顺序对范围键为 [r_start,r_end] 的项目进行排序

  1. Sort items lexicographically where range key is [r_start,r_end]

迭代排序列表并检查当前项是否与下一项重叠.如果它确实将当前项目扩展为 r[i].start,r[i+1].end,然后转到下一个项目.如果不重叠,则将当前添加到结果列表并移至下一项.

Iterate the sorted list and check if current item overlaps with next. If it does extend current item to be r[i].start,r[i+1].end, and goto next item. If it doesn't overlap add current to result list and move to next item.

这里是示例代码:

    vector<pair<int, int> > ranges;
    vector<pair<int, int> > result;
    sort(ranges.begin(),ranges.end());
    vector<pair<int, int> >::iterator it = ranges.begin();
    pair<int,int> current = *(it)++;
    while (it != ranges.end()){
       if (current.second > it->first){ // you might want to change it to >=
           current.second = std::max(current.second, it->second); 
       } else {
           result.push_back(current);
           current = *(it);
       }
       it++;
    }
    result.push_back(current);

相关文章