|
| 1 | +/* |
| 2 | +Given a collection of Intervals,merge all the overlapping Intervals. |
| 3 | +For example: |
| 4 | +
|
| 5 | +Given [1,3], [2,6], [8,10], [15,18], |
| 6 | +
|
| 7 | +return [1,6], [8,10], [15,18]. |
| 8 | +
|
| 9 | +Make sure the returned intervals are sorted. |
| 10 | +
|
| 11 | +
|
| 12 | +
|
| 13 | +Input: |
| 14 | +
|
| 15 | +The first line contains an integer T, depicting total number of test cases. |
| 16 | +Then following T lines contains an integer N depicting the number of Intervals and next line followed by the intervals starting and ending positions 'x' and 'y' respectively. |
| 17 | +
|
| 18 | +
|
| 19 | +Output: |
| 20 | +
|
| 21 | +Print the intervals after overlapping in sorted manner. There should be a newline at the end of output of every test case. |
| 22 | +
|
| 23 | +Constraints: |
| 24 | +
|
| 25 | +1 ≤ T ≤ 50 |
| 26 | +1 ≤ N ≤ 100 |
| 27 | +0 ≤ x ≤ y ≤ 100 |
| 28 | +
|
| 29 | +
|
| 30 | +Example: |
| 31 | +
|
| 32 | +Input |
| 33 | +2 |
| 34 | +4 |
| 35 | +1 3 2 4 6 8 9 10 |
| 36 | +4 |
| 37 | +6 8 1 9 2 4 4 7 |
| 38 | +
|
| 39 | +Output |
| 40 | +1 4 6 8 9 10 |
| 41 | +1 9 |
| 42 | +*/ |
| 43 | + |
| 44 | + |
| 45 | + |
| 46 | + |
| 47 | + |
| 48 | + |
| 49 | + |
| 50 | +#include<bits/stdc++.h> |
| 51 | +using namespace std; |
| 52 | + |
| 53 | +bool comp(vector<int> i1, vector<int> i2){ |
| 54 | + return i1[0] < i2[0]; |
| 55 | + } |
| 56 | + |
| 57 | + vector<vector<int>> merge(vector<vector<int>>& intervals) { |
| 58 | + vector<vector<int> > res; |
| 59 | + if(intervals.size()<=1) return intervals; |
| 60 | + sort(intervals.begin(), intervals.end(), comp); |
| 61 | + pair<int, int> tmp; |
| 62 | + tmp.first=intervals[0][0]; |
| 63 | + tmp.second=intervals[0][1]; |
| 64 | + for(int i=1;i<intervals.size();i++){ |
| 65 | + if(tmp.second>=intervals[i][0]){ |
| 66 | + tmp.second=max(tmp.second, intervals[i][1]); |
| 67 | + } else{ |
| 68 | + res.push_back({tmp.first, tmp.second}); |
| 69 | + tmp.first=intervals[i][0]; |
| 70 | + tmp.second=intervals[i][1]; |
| 71 | + } |
| 72 | + } |
| 73 | + res.push_back({tmp.first, tmp.second}); // adding last interva; |
| 74 | + return res; |
| 75 | + } |
| 76 | + |
| 77 | +int main(){ |
| 78 | + ios_base::sync_with_stdio(false); |
| 79 | + cin.tie(NULL); |
| 80 | + cout.tie(NULL); |
| 81 | + int t; |
| 82 | + cin>>t; |
| 83 | + while(t--){ |
| 84 | + int n; |
| 85 | + cin>>n; |
| 86 | + vector<vector<int> > intervals, res; |
| 87 | + for(int i=0;i<n;i++){ |
| 88 | + int s, e; |
| 89 | + cin>>s>>e; |
| 90 | + intervals.push_back({s, e}); |
| 91 | + } |
| 92 | + |
| 93 | + res=merge(intervals); |
| 94 | + |
| 95 | + for(int i=0;i<res.size();i++){ |
| 96 | + cout<<res[i][0]<<" "<<res[i][1]<<" "; |
| 97 | + } |
| 98 | + cout<<endl; |
| 99 | + } |
| 100 | + |
| 101 | +return 0; |
| 102 | +} |
0 commit comments