標籤:c++ 動態
#include<iostream>#include<cstdlib>#include<vector>using namespace std;int num_of_st;void getdata(vector<int> & v, int n){if (!v.empty()) throw runtime_error("v empty");int t;for (int i = 0; i < n; ++i) {cin >> t;v.push_back(t);}return;}int main(void){try{cin >> num_of_st;int e1, x1, e2, x2;cin >> e1 >> x1 >> e2 >> x2;vector<int> a1, t1, a2, t2;cout << "st 1: " << endl;getdata(a1, num_of_st);getdata(t1, num_of_st-1);cout << "st 2: " << endl;getdata(a2,num_of_st);getdata(t2, num_of_st-1);//init;vector<int> way1 , way2;int f1 = e1+a1[0], f2 = e2 + a2[0];way1.push_back(1); way2.push_back(2);for (int i = 1; i < num_of_st; ++i) {//get new f1;int nf1;vector<int> nway1(way1);if (f1 + a1[i] > f2 + t2[i - 1] + a1[i]) {nf1 = f2 + t2[i - 1] + a1[i];vector<int>(way2).swap(nway1);}else nf1 = f1 + a1[i];nway1.push_back(1);//get new f2;int nf2;vector<int> nway2(way2);if (f2 + a2[i] > f1 + t1[i - 1] + a2[i]) {nf2 = f1 + t1[i - 1] + a2[i];vector<int>(way1).swap(nway2);}else nf2 = f2 + a2[i];nway2.push_back(2);//renew data.f1 = nf1; f2 = nf2;way1.swap(nway1); way2.swap(nway2);}bool from1 = f1 + x1 > f2 + x2 ? false : true;int minT = from1 ? f1 + x1 : f2 + x2;cout << "Min time used: " << minT << endl;cout << "The way is: " << endl;if (from1) {for (vector<int>::iterator it = way1.begin();it != way1.end(); ++it) {cout << "Line: " << *it << ' ' << "Station " << it - way1.begin() + 1 << endl;}cout << endl;}else{for (vector<int>::iterator it = way2.begin();it != way2.end(); ++it) {cout << "Line: " << *it << ' ' << "Station: " << it - way2.begin() + 1 << endl;}cout << endl;}}catch (exception e) {cout << e.what() << endl;}cout << "Done." << endl;system("pause");return 0;}
動態規劃最短路徑問題:
Assembly-Line scheduling------code in c++