4-1活动安排问题
一、问题描述
二、问题分析
按结束时间递增排序,使用贪心策略,每次选择相容的且结束时间最早的活动,即a[i].end>a[j].start。
三、代码实现
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
int n,cnt=0;
struct time{
int start;
int end;
};
struct time t[100];
queue<struct time>q;
int cmp(time a,time b){
return a.end<b.end;
}
void Greedy(){
int i,j;
q.push(t[0]);
cnt++;
i=0;
for(j=1;j<n;j++){
if(t[i].end<t[j].start ){
cnt++;
q.push(t[j]);
i=j;
}
}
}
int main(){
cin>>n;
for(int i=0;i<n;i++){
cin>>t[i].start >>t[i].end;
}
sort(t,t+n,cmp);//结构体调用sort函数
cout<<"结构体排序:按end从小到大排序\n";
for(int i=0;i<n;i++){
cout<<t[i].start <<" "<<t[i].end<<" \n";
}
Greedy();
cout<<"共安排了"<<cnt<<"个活动\n";
cout<<"输出选择的活动\n";
while(!q.empty()){
cout<<q.front().start<<" "<<q.front().end<<endl;
q.pop();
}
return 0;
}
/*
9
9 12
8 10
20 23
8 15
11 14
12 16
15 17
18 21
16 18
*/