题意:给定n个区间[pi.s,pi.t],现要选出一个数据集合S,使得每个区间至少有两个元素在S中。求集合S的最小元素个数。
思路:贪心,按照区间的末端排序。设置两个游标表示当前取得的两个数a和b。对p[i]分三种情况讨论:
1、p[i].s<=a,则不需要改变a和b,因为a和b能够覆盖p[i].a~p[i].b;
2、p[i].s>a && p[i].s<=b。b保留,再加入p[i].b。即a = b,b = p[i].t;
3、p[i].s>b。ab均不能覆盖p[i],所以更新a=p[i].t-1,b=p[i].t;
#include <stdio.h>
#include <stdlib.h>
#define N 10005
struct node{
int s,t;
}p[N];
int n;
int cmp(const void *a,const void *b){
return (*(struct node*)a).t - (*(struct node*)b).t;
}
int main(){
freopen("a.txt","r",stdin);
while(scanf("%d",&n)!=EOF){
int i,a,b,res=2;
for(i = 0;i<n;i++)
scanf("%d %d",&p[i].s,&p[i].t);
qsort(p,n,sizeof(struct node),cmp);
a = p[0].t-1;
b = p[0].t;
for(i = 1;i<n;i++){
if(p[i].s <= a)
continue;
if(p[i].s <= b){
a = b;
b = p[i].t;
res++;
}
else if(p[i].s > b){
a = p[i].t-1;
b = p[i].t;
res += 2;
}
}
printf("%d\n",res);
}
return 0;
}