https://vjudge.net/problem/HDU-2037
思路:各个区间段可能会重复,优先选最短时间的话,(0,3)(2,4)(3,6)三个会优先选中间那个,明显答案是错的,如果优先选最早开始的,(0,15)(1,2)(3,4)明显出错,如果优先选最少重叠的也会出错,反例如下:(时间从左到右增加)
............... ...........
............... ...........
............... ................ ...........
............ ............. .............. .............. 按照这个优先选法,也会出错。正确的选法是,优先选结束时间最早的。
AC代码:
#include<stdio.h> #include<math.h> #include<string.h> #include<algorithm> #include<string> #include<iostream> using namespace std; #define ll long long struct node { int sta; int over; }; node a[105]; bool cmp(node p1,node p2) { if(p1.over<p2.over) return true; return false; } int main() { int n,t,num; while(scanf("%d",&n)!=EOF && n) { for(int i=0;i<n;i++) scanf("%d%d",&a[i].sta,&a[i].over); sort(a,a+n,cmp);///自定义函数排序,结束时间早的排在前面 t=num=0;///t为节目的结束时间 for(int i=0;i<n;i++) { if(a[i].sta>=t)///如果下一个节目开始时间在上一个结束时间之后,就可以优先选择 { t=a[i].over; num++; } } printf("%d ",num); } }