algorithm ch15 FastWay
这是DP最基础的一个问题,刚开始学习这一块,实现了一下,不要黑我巨长的参数表,新手。
代码如下:
void FastWay(int l1[], int l2[], int e1, int e2, int x1, int x2, int t1[], int t2[], int n) { int f1[6] ={0}; int f2[6] ={0}; int l[12] = {0}; f1[0] = e1 + l1[0]; f2[0] = e2 + l2[0]; int lres = 0; int fres = 0; int offset = 0; for(int i = 1; i < n; ++i) { if((f1[i-1] + l1[i]) <= (f2[i-1] + t2[i-1] + l1[i])) { l[i] = 1; f1[i] = f1[i-1] + l1[i]; } else { f1[i] = f2[i-1] + t2[i-1] + l1[i]; l[i] = 2; } if(f2[i-1] + l2[i] <= f1[i-1] + t1[i-1] + l2[i]) { l[i+6] = 2; f2[i] = f2[i-1] + l2[i]; } else { l[i+6] = 1; f2[i] = f1[i-1] + t1[i-1] + l2[i]; } } if(f1[n-1] + x1 <= f2[n-1] + x2) { lres = 1; fres = f1[n-1] + x1; } else { lres = 2; fres = f2[n-1] + x2; offset = 6; } PrintWayRecurse(l, lres, n); } void PrintWayRecurse(int l[], int lres, int n) { if(n == 0) return; int offset = 0; if(lres == 2) { offset = 6; } else { offset = 0; } PrintWayRecurse(l, l[n -1 +offset], n-1 ); cout << "line " << lres << " station " << n << endl; }
这里是迭代输出的,当时教c语言的老湿真的是极力的反对我们用迭代,所有的迭代都可以用顺序语句实现,可是现在看算法这块好多将迭代的,感觉思维有点跟不上,困惑。
然后写了个顺序执行的:
void PrintWay(int l[], int lres, int offset, int n) { if(offset == 6) { cout << "line " << 2 << " station" << n << endl; } else { cout << "line " << 1 << " station" << n << endl; } for(int i = n-1; i> 0; --i) { cout << "line " << l[i + offset] << " station" << i << endl; if(l[i+offset] == 1) offset = 0; else offset = 6; } cout << "test" ; }
代码有点乱,新手。。。
learn++