【算法导论】动态规划实现

对于 line[6][2]的记录机制还有疑问,等下细细看来,再补上解答 1 #include<iostream>
 2 using namespace std;
 3 //==========================================================================
 4 int a[2][100];
 5 int f[2][100];
 6 int t[2][100];
 7 int line[2][100];
 8 int e[2];
 9 int x[2];
10 int lend,fend;
11 //==========================================================================
12 void  FastWay(int a[2][6],int t[2][5],int e[2],int x[2],int n,int &fend,int &lend)
13 {
14      f[0][0] = e[0] + a[0][0];
15     f[1][0] = e[1] + a[1][0];
16     cout << a[0][1] << endl;
17     cout << a[1][1] << endl;
18     for (int j = 1; j < n; j++)
19     {
20         if (f[0][j-1] + a[0][j] <= f[1][j-1] + t[1][j-1] + a[0][j])
21         {
22             f[0][j] = f[0][j-1] + a[0][j];
23             line[0][j] = 0;
24         }
25         else
26         {
27             f[0][j] = f[1][j-1] + t[1][j-1] + a[0][j];
28             line[0][j] = 1;
29         }
30         if (f[1][j-1] + a[1][j] <= f[0][j-1] + t[0][j-1] + a[1][j])
31         {
32             f[1][j] = f[1][j-1] + a[1][j];
33             line[1][j] = 1;
34         }
35         else
36         {
37             f[1][j] = f[0][j-1] + t[0][j-1] + a[1][j];
38             line[1][j] = 0;
39         }
40     }
41     if (f[0][n-1] + x[0] <= f[1][n-1] + x[1])
42     {
43         fend = f[0][n-1] + x[0];
44         lend = 0;
45     }
46     else
47     {
48         fend = f[1][n-1] + x[1];
49         lend = 1;
50     }
51 
52 }
53 
54 //===============================================================================================
55 void PrintStations(int line[2][6],int lend, int n)
56 {
57     int i=lend;
58     cout<<"Line "<<i<<" Station "<<n<<endl; 
59     for(int j=n-1;j>=2;j--)
60     {
61         i=line[i][j];//?????????????????/
62         cout<<"Line "<<i<<" Station "<<j-1<<endl; 
63     }
64 }
65 //===============================================================================================
66 int main()
67 {
68     int n=6;
69     int e[3]={2,4};
70     int x[3]={3,2};
71     int a[2][6]={7,9,3,4,8,4,8,5,6,4,5,7};
72     int t[2][5]={2,3,1,3,4,2,1,2,2,1};
73 
74     int Line[2][6];
75     int LastFlag;
76     int fend;
77 
78      FastWay(a, t, e, x, n,fend,LastFlag);
79     printf("fast = %d;\n", fend);
80     
81     PrintStations(Line, LastFlag, n);
82     return 0;
83 
84 }

posted on 2012-05-06 21:15 四也 阅读(202) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

导航

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜