区间合并

题目链接:https://www.acwing.com/problem/content/805/

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef pair<int,int> PII;
 4 vector<PII> vec,ans;
 5 int main()
 6 {
 7     int n;
 8     cin>>n;
 9     while(n--){
10         int l,r;
11         cin>>l>>r;
12         vec.push_back({l,r});
13     }
14     if(vec.size()==1){
15         cout<<1<<endl;
16         return 0;
17     }
18     sort(vec.begin(),vec.end());
19     int l=vec[0].first,r=vec[0].second;
20     for(int i=1;i<vec.size();i++){
21         if(vec[i].first<=r){
22             if(vec[i].second>r){
23                 r=vec[i].second;
24             }
25         }else{
26             ans.push_back({l,r});
27             l=vec[i].first;
28             r=vec[i].second;
29         }
30     }
31     ans.push_back({l,r});
32     cout<<ans.size()<<endl;
33     return 0;
34 }

 

posted @ 2022-01-11 22:59  wydxry  阅读(45)  评论(0编辑  收藏  举报
Live2D