比方有5個活動,開始與截止時刻分別爲:
最佳安排序列爲:1,4,5。php
6 8 10 9 16 11 16 14 15 10 14 7 11
1,5,4
很是經典的貪心題,首先把這一系列活動的起始時間與結束時間按結束時間升序排序,首先把第一個活動(排完序以後)歸入決策之中,而後往下掃,每當下一個活動的開始時間大於等於上一個活動的結束時間時,就將次活動歸入決策之中。掃一遍,ok 貪心完畢
#include <stdio.h> #include <stdlib.h> #include <iostream> #include <algorithm> using namespace std; struct select { int tag; int begin; int end; }; struct select act[111]; int res[111]; bool cmp(struct select x,struct select y) { return x.end<y.end; } int main() { int n,i,j; cin>>n; for(i=0;i<n;i++) { cin>>act[i].begin>>act[i].end; act[i].tag=i+1; } sort(act,act+n,cmp); j=0; bool a[100]; a[0]=true; for(i=1;i<n;i++) { if(act[i].begin>=act[j].end)//貪心核心算法 { j=i; a[i]=true; } else a[i]=false; } int p=0; for(i=0;i<n;i++) if(a[i]) res[p++]=act[i].tag; for(i=0;i<p;i++) if(i!=p-1) cout<<res[i]<<","; else cout<<res[i]<<endl; return 0; }