-
Notifications
You must be signed in to change notification settings - Fork 2
/
mergeoverlaping.cpp
73 lines (63 loc) · 1.63 KB
/
mergeoverlaping.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// A C++ program for merging overlapping intervals
#include<bits/stdc++.h>
using namespace std;
// An interval has start time and end time
struct Interval
{
int start, end;
};
// Compares two intervals according to their staring time.
// This is needed for sorting the intervals using library
// function std::sort(). See http://goo.gl/iGspV
bool compareInterval(Interval i1, Interval i2)
{
return (i1.start < i2.start);
}
// The main function that takes a set of intervals, merges
// overlapping intervals and prints the result
void mergeIntervals(Interval arr[], int n)
{
// Test if the given set has at least one interval
if (n <= 0)
return;
// Create an empty stack of intervals
stack<Interval> s;
// sort the intervals in increasing order of start time
sort(arr, arr+n, compareInterval);
// push the first interval to stack
s.push(arr[0]);
// Start from the next interval and merge if necessary
for (int i = 1 ; i < n; i++)
{
// get interval from stack top
Interval top = s.top();
// if current interval is not overlapping with stack top,
// push it to the stack
if (top.end < arr[i].start)
s.push(arr[i]);
// Otherwise update the ending time of top if ending of current
// interval is more
else if (top.end < arr[i].end)
{
top.end = arr[i].end;
s.pop();
s.push(top);
}
}
// Print contents of stack
cout << "\n The Merged Intervals are: ";
while (!s.empty())
{
Interval t = s.top();
cout << "[" << t.start << "," << t.end << "] ";
s.pop();
}
return;
}
int main()
{
Interval arr[] = { {6,8}, {1,9}, {2,4}, {4,7} };
int n = sizeof(arr)/sizeof(arr[0]);
mergeIntervals(arr, n);
return 0;
}