这是一个大佬的代码及解释。。。
https://blog.csdn.net/wuxiushu/article/details/47009023
点击打开链接(就是上面这个网页,我也不知道这样算不算侵权,emmmm,侵删)
有几点需要注意的事情
1.这个区间啊,左右区间的大小没有确定,也就是说(1,5)这个区间是合理的,(9,3)这个区间也是合理的
所以说,我们在用贪心时,得先把区间变成左小右大,!!!!!!
这个一定要记住(以后当题目中说的是“区间时”就一定一定要小心啊!!!!)
2.贪心思想就是把各个区间按照左边界进行由小到大的排序,其目的是越早结束给以后的时间分配起冲突的可能性更小
3.这道题啊,除了有Case n:外,答案输出部分还有个. ,这道题真的是,哎。。。。
然后这个是我的AC的代码
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
struct section//区间: section
{
int l,r;
};
bool cmp(section a,section b)
{
return a.r<=b.r;
}
section a[1005];
int main()
{
int n;
int right;
int ans;
int order=0;
while(~scanf("%d",&n))
{
order++;
ans=1;
int L,R,temp;
for(int i=0;i<n;i++)
{
scanf("%d%d",&L,&R);
if(L>R)//因为这道题给的是区间,简直有毒,所以得把左右区间弄成左小右大,,,
{
temp=L;
L=R;
R=temp;
}
a[i].l=L;
a[i].r=R;
}
sort(a,a+n,cmp);
right=a[0].r;
for(int i=1;i<n;i++)
{
if(a[i].l>right)
{
ans++;
right=a[i].r;
}
}
printf("Case %d:\n%d.\n",order,ans);
}
return 0;
}