HDU 2037 - 今年暑假不AC - [经典 选择不相交区间 问题]

是一道很经典的选择不相交区间的问题。

关于选择不相交区间,可以参考刘汝佳。也可以参考:http://blog.csdn.net/dgq8211/article/details/7534488

以及模板代码:

 1 #include <stdio.h>
 2 #include <algorithm>
 3 using namespace std;
 4 struct Extent
 5 {
 6     int a,b;
 7     bool operator < (const Extent& S)const
 8     {
 9         return b < S.b;
10     }
11 }A[10002];
12 int main()
13 {
14     int z,n,cnt,end;
15     scanf("%d",&z);
16     while(z--)
17     {
18         cnt = 0;
19         end = -1;
20         scanf("%d",&n);
21         for(int i=0;i<n;i++)
22             scanf("%d%d",&A[i].a,&A[i].b);
23         sort(A,A+n);
24         for(int i=0;i<n;i++)
25         {
26             if(end < A[i].a)
27             {
28                 end = A[i].b;
29                 cnt++;
30             }
31         }
32         printf("%d\n",cnt);
33     }
34     return 0;
35 }

 

 

所以关于本题,我们也可以设两个变量:count和now_end,表示贪心过程的计数器与每一步贪心时end位置。

当然需要注意的是,这题里,两个区间可以的端点可以共用,所以 if(end<a[i].a) 这句判断语句要多加一个“=”

 1 #include<cstdio>
 2 #include<algorithm>
 3 #define INF 0x3f3f3f3f 
 4 using namespace std;
 5 struct Sect{
 6     int l,r;
 7 }sect[105];
 8 int n,ne,cnt;
 9 bool cmp(Sect a,Sect b)
10 {
11     if(a.r==b.r) return a.l<b.l;
12     return a.r<b.r;
13 }
14 int main()
15 {
16     while(scanf("%d",&n) && n!=0)
17     {
18         for(int i=1;i<=n;i++) scanf("%d%d",&sect[i].l,&sect[i].r);
19         sort(sect+1,sect+n+1,cmp);
20         //printf("\n"); for(int i=1;i<=n;i++) printf("%d %d\n",sect[i].l,sect[i].r);
21         cnt=0;
22         ne=-INF;
23         for(int i=1;i<=n;i++)
24         {
25             if(ne<=sect[i].l)
26             {
27                 ne=sect[i].r;
28                 cnt++;
29             }
30         }
31         printf("%d\n",cnt);
32     }
33 }

 

那个时候刚入ACM大坑的时候,比较懵逼,学贪心感觉没学到家,趁现在赶快复习巩固一下(逃

posted @ 2017-07-28 09:12  Dilthey  阅读(769)  评论(0编辑  收藏  举报