最大不相交区间数

# 题意
N个闭区间[ai,bi],请你在数轴上选择若干区间,使得选中的区间之间互不相交(包括端点)。
输出可选取区间的最大数量。

# 题解
1.将每个区间按照右端点从小到大排序
2.从前往后依次枚举每个区间
如果当前区间已经包含点pass
否则选择当前区间的右端点
因为是右端点从小到大易知正确

 1 #include <bits/stdc++.h>
 2 #define PII pair<int,int>
 3 using namespace std;
 4 const int N=1e5+10;
 5 PII a[N];
 6 int main(){
 7     int n,ans=1;
 8     scanf("%d",&n);
 9     for(int i=0;i<n;i++)
10         scanf("%d%d",&a[i].second,&a[i].first);
11     sort(a,a+n);
12     int loca=a[0].first;
13     for(int i=1;i<n;i++){
14         if(a[i].second<=loca&&loca<=a[i].first) continue;
15         else{
16             ans++;
17             loca=a[i].first;
18         }
19     }
20     printf("%d\n",ans);
21 }

猜你喜欢

转载自www.cnblogs.com/hhyx/p/12543588.html