活动选择问题(贪心)

来源:互联网 发布:网络利大于弊的事例 编辑:程序博客网 时间:2024/05/03 11:24

假设有n个活动,每个活动有一个起始时间和一个结束时间,现在想在一段固定时间内安排最多的活动数。这个问题是典型的贪心问题,我们把所有的活动按结束时间从小到大排序,这样可以知道最小的那个活动a1一定在最优集合里,因为假设最优结构中没有a1,而是它的最小活动为另一个数假设ax,因为a1是所有活动中最小的,所以如果我们把ax换成a1,最优集合里所有的活动还是兼容的,所以a1一定在最优集合中。这样我们只要先选出a1,然后再对除去a1后所有起始时间大于等于a1结束时间的活动进行贪心即可,每次选择当前集合中结束时间最小的活动就可以得到最大的活动数。

#include<iostream>#include<algorithm>#include<vector>using namespace std;struct node{int s, f;};vector<int> time;bool cmp(const node a, const node b){return a.f<b.f;}int main(){int n;cout << "Enter all intervals of time can be chosen" << endl;cin >> n;node *p = new node[n+1];cout << "Enter the start and end of time intervals" << endl;for (int i = 1; i <= n; i++)cin >> p[i].s >> p[i].f;sort(p+1, p + n + 1, cmp);//先按照结束时间从小到大排序int k = 1;time.push_back(1);for (int m = 2; m <= n; m++){if (p[m].s >= p[k].f)//找到最小的比上一个结束时间大的开始时间,就选它作为下一个时间段{time.push_back(m);k = m;}}cout << "There are most "<<time.size()<<": ";int temp = time.size();for (int i = 0; i < temp; i++)//倒序输出{cout << time.back() << "  ";time.pop_back();}cout << endl;delete[] p;return 0;}


0 0