AcWing 905. 区间选点
原题链接
样例解释
选择1, 4 即可
算法标签
贪心
思路
1.将每个区间按右端点从小到大排序
2.从前往后依次枚举每个区间
如果当前区间中已经包含点,则直接pass ;
否则,选择当前区间的右端点
证明
设每个区间内至少包含一个选出的点。选择的点的数量所组成集合为
c
n
t
cnt
cnt
选择的点的最小数量为
a
n
s
ans
ans
则
a
n
s
<
=
c
n
t
ans<=cnt
ans<=cnt
根据选择策略 – 如果当前区间中已经包含点,则直接pass ;否则,选择当前区间的右端点
因此 所得cnt值实际为相互之间没有交集的区间个数。依题意,使得每个区间内至少包含一个选出的点,至少需要cnt个点。
则
a
n
s
>
=
c
n
t
ans>=cnt
ans>=cnt
因此
a
n
s
=
c
n
t
ans=cnt
ans=cnt
代码
#include<bits/stdc++.h>
#define int long long
#define rep(i, a, b) for(int i=a;i<b;++i)
#define Rep(i, a, b) for(int i=a;i>b;--i)
using namespace std;
const int N = 100005;
inline int read(){
int s=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
return s*w;
}
void put(int x) {
if(x<0) putchar('-'),x=-x;
if(x>=10) put(x/10);
putchar(x%10^48);
}
struct sec{
int l, r;
}ses[N];
bool cmp(sec A, sec B){
return A.r<B.r;
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n=read();
rep(i, 0, n){
ses[i].l=read(), ses[i].r=read();
}
sort(ses, ses+n,cmp);
int ans=1;
int t=0;
rep(i, 1, n){
if(ses[t].r>=ses[i].l&&ses[t].r<=ses[i].r){
continue;
}else{
t=i;
ans++;
}
}
printf("%lld\n", ans);
return 0;
}
由于cnt值实际为相互之间没有交集的区间个数
因此该题与下题所求一致
AcWing 908.最大不相交区间数量
原题链接
Acwing908. 最大不相交区间数量
代码一致
原创不易
转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈