多段图动态规划
1 //多段图的问题--动态规划
2 #define N 5
3 #define K 3
4 #define MAX 10000
5 int node[5][5] = { { -1, 1, 2, 3, -1 }, { -1, -1, -1, -1, 4 }, { -1, -1, -1,
6 -1, 1 }, { -1, -1, -1, -1, 3 }, { -1, -1, -1, -1, -1 } };
7 int cost[N];
8 int path[K];
9 void produreFGraph() {
10 cost[N-1] = 0;
11 for (int i = N - 2; i >= 0; i--) {
12 //寻找第i个个结点,到目的节点的最小cost
13 int len = MAX;
14 for (int j = i + 1; j < N; j++) {
15 if (node[i][j] != -1 && (node[i][j] + cost[j] < len)) {
16 cost[i] = node[i][j] + cost[j];
17 len = cost[i];
18 path[i] = j;
19 }
20 }
21 cout << "cost[" << i << "]:" << cost[i] << endl;
22 }
23 cout<<"path:"<<0<<"--";
24 for (int i = 0; i != N-1; i=path[i]) {
25 cout << path[i] << "--";
26 }
27 cout<<endl;
28
29 }
30 int main() {
31 produreFGraph();
32 cout << cost[0] << endl;
33 return 0;
34 }
2 #define N 5
3 #define K 3
4 #define MAX 10000
5 int node[5][5] = { { -1, 1, 2, 3, -1 }, { -1, -1, -1, -1, 4 }, { -1, -1, -1,
6 -1, 1 }, { -1, -1, -1, -1, 3 }, { -1, -1, -1, -1, -1 } };
7 int cost[N];
8 int path[K];
9 void produreFGraph() {
10 cost[N-1] = 0;
11 for (int i = N - 2; i >= 0; i--) {
12 //寻找第i个个结点,到目的节点的最小cost
13 int len = MAX;
14 for (int j = i + 1; j < N; j++) {
15 if (node[i][j] != -1 && (node[i][j] + cost[j] < len)) {
16 cost[i] = node[i][j] + cost[j];
17 len = cost[i];
18 path[i] = j;
19 }
20 }
21 cout << "cost[" << i << "]:" << cost[i] << endl;
22 }
23 cout<<"path:"<<0<<"--";
24 for (int i = 0; i != N-1; i=path[i]) {
25 cout << path[i] << "--";
26 }
27 cout<<endl;
28
29 }
30 int main() {
31 produreFGraph();
32 cout << cost[0] << endl;
33 return 0;
34 }