121 33 40 73 815 1915 2010 158 186 125 104 142 90Sample Output5題解:先把每一段時間用結構體記錄下來,然后根據結束的時間進行排序,如果遇到結束時間相同的,就把開始時間按照升序進行排列。排列完后把結束的時間和后一段開始的時間進行比較,如果后一段開始的時間在前一段結束的時間之后,就選擇這一段進行觀看。
我的代碼:
#include<iostream>#include<stdio.h>#include<algorithm>#include<cmath>#include<iomanip>#include<string.h>using namespace std;struct TM{ //注意這里不能用time作結構體名字,因為time本身是個函數。 int s, e;}t[110];int cmp(TM a, TM b){ if (a.e == b.e) return a.s > b.s;//如果結束時間相同,開始時間越大的,觀看時間越短,越看更多的節目 return a.e < b.e;//第一約束條件還是結束時間,因為節目結束時間決定了最終觀看結束時間}int main(){ int n, i; while(scanf("%d", &n),n) { int k = 1, exa; for (i = 0; i < n; i++) scanf ("%d %d", &t[i].s, &t[i].e); sort(t, t+n, cmp); exa = t[0].e; for (i = 0; i < n; i++) { if(t[i].s >= exa)//如果節目的開頭大于前一段的結尾,則選擇這一個節目。 { exa = t[i].e; k++; } } cout << k << endl; } return 0;}
新聞熱點
疑難解答