贪心算法——初级
#include<iostream>
#include<algorithm>
using namespace std;
struct Act
{
int start;
int end;
}activity[100];
int N;
bool cmp(Act a,Act b)
{
return a.end<b.end;
}
int greedy()
{
int num=0;
for(int i=0,j=i+1;i<N;++j)
{
if(activity[j].start > activity[i].end)
{
i=j;
num++;
}
}
return num;
}
int main(int argc,char** argv)
{
cout<<"The total num of activities:";
cin>>N;
cout<<"Please input the start and end time of each activity:";
for (int i=0;i<N;++i)
{
cin>>activity[i].start;
cin>>activity[i].end;
}
sort(activity,activity+N,cmp);
int res=greedy();
cout<<"The maximum activities can be hold is "<<res;
system("pause");
return 0;
}
本文介绍如何使用贪心算法解决活动调度问题,通过C++代码实现,展示了如何根据结束时间对活动进行排序并找到可以同时进行的最大活动数。
236

被折叠的 条评论
为什么被折叠?



