码迷,mamicode.com
首页 > 编程语言 > 详细

算法导论 16.1-1

时间:2016-07-17 21:03:21      阅读:315      评论:0      收藏:0      [点我收藏+]

标签:

用动态规划方法求解活动选择问题,与贪心算法相比,显然是庞然大物,大材小用了,贪心算法可以非常简洁的求解活动选择问题

动态规划:

 1 #include <iostream>
 2 #include <vector>
 3 #include <limits>
 4 #define INF numeric_limits<int>::max()
 5 using namespace std;
 6 int act_select(int s[],int f[],int n,int **c,int **r);
 7 void print_res(int **r,int start,int end);
 8 int main(){
 9     int s[]={-1,1,3,0,5,3,5,6,8,8,2,12,INF};
10     int f[]={-1,4,5,6,7,9,9,10,11,12,14,16,INF};
11     int n=11;
12     int **c=new int*[n+2];
13     int **r=new int*[n+2];
14     for(int i=0;i<n+2;++i){
15         c[i]=new int[n+2];
16         r[i]=new int[n+2];
17         for(int j=0;j<n+2;++j){
18             c[i][j]=0;
19             r[i][j]=-1;
20         }
21     }
22     cout<<"The max length of the bcs is "<<act_select(s,f,n,c,r)<<endl;
23     print_res(r,0,n+1);
24     cout<<endl;
25     for(int i=0;i<n+2;++i){
26         delete[] c[i];
27         delete[] r[i];
28     }
29     delete[] c;
30     delete[] r;
31     return 0;
32 }
35 
36 int act_select(int s[],int f[],int n,int **c,int **r){
37     vector<int> v;
38     v.reserve(n);
39     for(int l=1;l<=n;++l){
40         for(int i=0;i<=n-l;++i){
41             int j=i+l+1;
42             v.resize(0);
43             for(int k=i+1;k<=j;++k)
44                 if(s[k]>f[i]&&f[k]<s[j])
45                     v.push_back(k);
46             for(vector<int>::iterator p=v.begin();p!=v.end();++p){
47                 int temp=c[i][*p]+1+c[*p][j];
48                 if(temp>c[i][j]){
49                     c[i][j]=temp;
50                     r[i][j]=*p;
51                 }
52             }
53         }
54     }
55     return c[0][n+1];
56 }
57 
58 void print_res(int **r,int start,int end){
59     int m=r[start][end];
60     if(m==-1)
61         return;
62     print_res(r,start,m);
63     cout<<m<<" ";
64     print_res(r,m,end);
65 }

代码中添加了a0和a12作为伪活动,辅助问题求解!

算法导论 16.1-1

标签:

原文地址:http://www.cnblogs.com/cq-shihao/p/5679311.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!