活动选择的贪心算法与动态规划(未完成)
Posted lineaar
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了活动选择的贪心算法与动态规划(未完成)相关的知识,希望对你有一定的参考价值。
// greedy_algorithm.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include<iostream> #include<queue> using namespace std; #define NofActivity 11 int c[NofActivity + 1][NofActivity + 1]; int reme[NofActivity + 1][NofActivity + 1]; //活动的结构///////////////////////////////////////// struct Activity { int num; int start; int finish; }; Activity Act[12] = { {0,0,0},{ 1,1,4 },{2,3,5 },{3, 0,6 },{4, 5,7 },{5, 3,9 },{6, 5,9 },{7, 6,10 },{8, 8,11 },{9, 8,12 },{10, 2,14 },{11, 12,16 }}; ///用队列来存储符合条件的活动,递归版本 queue<Activity> select; void Recursive_activity_selector(Activity* Act, int k, int n) { int m = k + 1; while (m <= n&&Act[m].start < Act[k].finish) m++; if (m <= n) { select.push(Act[m]); Recursive_activity_selector(Act, m, n); } } ///活动选择的迭代版本////////////////////// void Greedy_activity_selector(Activity* Act) { int n = NofActivity; while (!select.empty())select.pop(); select.push(Act[1]); int k = 1; for (int i = 2; i <= n; i++) { if (Act[i].start > Act[k].finish) { select.push(Act[i]); k = i; } } } /////活动选择的动态规划版本////////////////////////////////// void activity_selector(Activity* Act) { queue<int> que; for (int i = 0; i <= NofActivity; i++) { c[i][i] = 0; c[0][i] = 0; c[i][0] = 0; } for(int l=2;l<=NofActivity;l++) for (int i = 1; i <= NofActivity-l+1; i++) { int j = i + l - 1; int m = i + 1; while (m <= j&&Act[m].start < Act[i].finish) m++; if (m > j)c[i][j] = 0; else { int temp = c[i][i]; reme[i][j] = i; for(int k=i+1;k<=j;k++) if (c[i][k] + c[k][j] + 1 > temp) { temp = c[i][k] + c[k][j] + 1; reme[i][j] = k; } c[i][j] = temp; } } } int main() { //Recursive_activity_selector(Act, 0, NofActivity); /* Greedy_activity_selector(Act); while (!select.empty()) { cout << select.front().num<< ‘\t‘; select.pop(); } */ activity_selector(Act); for (int i = 1; i <= NofActivity; i++) { for (int j = 1; j <= NofActivity; j++) cout << c[i][j] << ‘ ‘; cout << endl; } while (1); return 0; }
以上是关于活动选择的贪心算法与动态规划(未完成)的主要内容,如果未能解决你的问题,请参考以下文章