poj 2376 Cleaning Shifts(贪心 区间覆盖)
Input
* Line 1: Two space-separated integers: N and T
* Lines 2..N+1: Each line contains the start and end times of the interval during which a cow can work. A cow starts work at the start time and finishes after the end time.
* Lines 2..N+1: Each line contains the start and end times of the interval during which a cow can work. A cow starts work at the start time and finishes after the end time.
Output
* Line 1: The minimum number of cows Farmer John needs to hire or -1 if it is not possible to assign a cow to each shift.
Sample Input
3 10 1 7 3 6 6 10
Sample Output
2
这道题就是找出能覆盖该区间的最小组数。
自己的思路一开始是找出离两端最近的排序然后做错了。然后接下来就是换了种思路。
就是按一般的大小排序小的在前面。
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 #include <cmath> 5 #include <algorithm> 6 using namespace std; 7 int n,t; 8 typedef struct 9 { 10 int x; 11 int y; 12 } P; 13 bool cmp(P p1,P p2) 14 { 15 if(p1.x<p2.x) return true; 16 else if(p1.x==p2.x) 17 { 18 if(p1.y<p2.y) return true; 19 } 20 return false; 21 } 22 int main() 23 { 24 int i; 25 cin>>n>>t; 26 P p[n]; 27 for(int i=0; i<n; i++) 28 { 29 scanf("%d%d",&p[i].x,&p[i].y); 30 } 31 sort(p,p+n,cmp); 32 33 int s=0,k=0; 34 for(i=0; i<t;)//要覆盖[i,t] //要改的话这里加个k<n应该就可以了 35 { 36 int m=-1; 37 int c=0; 38 while(p[k].x<=i+1) //找下一个p[k].x<=i+1且p[k].y的值最大的m 39 { 40 c=1; 41 if(p[k].y>m) m=p[k].y; 42 k++; 43 if(k==n)break; 44 } 45 if(c) 46 { 47 s++; 48 i=m; //更新i值 49 // printf("i:%d\n",i); 50 } 51 else 52 { 53 break; //没有 54 } 55 } 56 // printf("i:%d,n:%d\n",i,n); 57 if(i!=t)printf("-1\n"); 58 else printf("%d\n",s); 59 return 0; 60 }
先在纸上写了伪代码,这样真的很有帮助。但是上面的应该还有一些错误,但是过了,例如数据 3 10
1 6
2 5
3 4
这样的话最后数组会越界
自己又重新改了改,但是没过。。
我想写代码的难度也在这里体现了吧,难就难在拿到一个任务的时候需要不断生成自己的思路,不断有思维漏洞不断地改,再改的过程中若是没理解好题意又不断的理解正确,在思维漏洞的那片代码不断捉摸如何才能实现那个功能,如何准确无误,变量间如何互相合作如何慢慢构建框架等等,而最开始一遍是很难把所有的东西都弄的准确无误的。
#include <cstdio> #include <cstring> #include <iostream> #include <cmath> #include <algorithm> using namespace std; int n,t; typedef struct { int x; int y; } P; bool cmp(P p1,P p2) { if(p1.x<p2.x) return true; else if(p1.x==p2.x) { if(p1.y<p2.y) return true; } return false; } int main() { int i; cin>>n>>t; P p[n]; for(int i=0; i<n; i++) { scanf("%d%d",&p[i].x,&p[i].y); } sort(p,p+n,cmp); int s=0,k=0; for(i=0; i<t&&k<n;)//要覆盖[i,t] { int m=i; int c=0; while(p[k].x<=i+1&&p[k].y>i) //找下一个p[k].x<=i+1且p[k].y的值最大的m { // printf("k:%d\n",k); c=1; if(p[k].y>m) m=p[k].y; k++; if(k==n)break; } if(c) //可以更新m { if(m==i) break; //更新不了 s++; i=m; //更新i值 // printf("i:%d\n",i); } else if(k>=n-1) //不可以更新m且没机会了 { break; } else k++; //不可以更新m还有机会 } // printf("i:%d,n:%d\n",i,n); if(i!=t)printf("-1\n"); else printf("%d\n",s); return 0; }

浙公网安备 33010602011771号