使用C ++合并重叠间隔。
问题陈述
给定一组任意时间间隔的时间,将所有重叠的时间间隔合并为一个并输出结果,该结果应仅具有互斥的时间间隔
给定间隔集为{{12,14},{11,13},{20,22},{21,23}},则
间隔{12,14}和{11,13}彼此重叠,因此将它们合并为{11,14}
间隔{20,22}和{21,23}彼此重叠,因此将它们合并为{20,23}
算法
1. Sort the intervals based on increasing order of starting time 2. Push the first interval on to a stack 3. For each interval perform below steps: 3.1. If the current interval does not overlap with the top of the stack, push it. 3.2. If the current interval overlaps with top of the stack and ending time of current interval is more than that of top of stack, update stack top with the ending time of current interval. 4. Finally, stack contains the merged intervals.
示例
#include <iostream>
#include <algorithm>
#include <stack>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
struct interval{
int start;
int end;
};
bool compareInterval(interval i1, interval i2){
return (i1.start < i2.start);
}
void mergeOverlappingIntervals(interval *arr, int n){
if (n <= 0) {
return;
}
stack<interval> s;
sort(arr, arr + n, compareInterval);
s.push(arr[0]);
for (int i = 1; i < n; ++i) {
interval top = s.top();
if (top.end < arr[i].start) {
s.push(arr[i]);
} else if(top.end < arr[i].end) {
top.end = arr[i].end;
s.pop();
s.push(top);
}
}
cout << "Merged intervals: " << endl;
while (!s.empty()) {
interval i = s.top();
cout << "{" << i.start << ", " << i.end << "}" << " ";
s.pop();
}
cout << endl;
}
int main(){
interval arr[] = {{12, 14}, {11, 13}, {20, 22}, {21, 23}};
mergeOverlappingIntervals(arr, SIZE(arr));
return 0;
}输出结果
当您编译并执行上述程序时。它生成以下输出-
Merged intervals:
{20, 23} {11, 14}热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短