题目:
区间长度8,可选的覆盖线段[2,6],[1,4],[3,6],[3,7],[6,8],[2,4],[3,5],求最小的能覆盖全部区间的段数.
自己写的代码:
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
const int maxn = 1000;
struct point
{
int start;
int end;
}a[maxn];
bool cmp(struct point a,struct point b)
{
if(a.start != b.start)
return a.start < b.start;
else
return a.end < b.end;
}
int init(int m)
{
int i;
int cur;
int cnt;
for(i=0;i<m;i++)
{
cin>>a[i].start>>a[i].end;
}
sort(a,a+m,cmp);
cur = a[0].end;
cout<<a[0].start<<" "<<a[0].end<<endl;
cnt = 1;
i = 1;
while(i < m)
{
if(a[i].start <= cur)
{
i++;
}
else
{
i--;
cnt++;
cur = a[i].end;
cout<<a[i].start<<" "<<a[i].end<<endl;
}
}
if(a[m-1].start <= a[m-2].end && a[m-1].end != a[m-2].end)
{
cnt++;
cout<<a[m-1].start<<" "<<a[m-1].end<<endl;
}
return cnt;
}
int main()
{
int m;
freopen("111","r",stdin);
cin>>m;
cout<<init(m)<<endl;
return 0;
}
运行截图:
PS:本题测试过几个样例都没有问题,如果读者发现bug请留言。