回溯法 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172#include<iostream>#define N 10010using namespace std;double c;//背包容量int n;//物品数量double w[N];//物品重量数组double v[N];//物品价值数组double cw;//当前重量double cv;//当前价值double bestv;//当前最优价值double best_x[N];//记录最好的情况int x[N];//记录回溯的情况double Bound(int i);void BackTrack(int i);int main(void) { double weight_sum=0, best_value=0; cout<<"Please input the number of goods:"; cin >> n; cout<<"Please input the capacity of bag:"; cin >> c; cout<<"Please input the weight and value of each goods:"<<endl; for (int i = 0; i < n; i++) { cin >> w[i] >> v[i]; weight_sum += w[i]; best_value += v[i]; } if (weight_sum <= c) cout << "All goods can be put into the bag\n" << "The best value is" << best_value << endl; else { BackTrack(0); cout << "The best_x is : "; for (int i = 0; i < n; i++) { cout << best_x[i] << " "; } cout << endl << "The bestv is :"; cout << bestv << endl; } return 0;}double Bound(int i) { double cleft_value=0; double cleft = c - cw; while (i <=n-1&&w[i]<=cleft) { cleft_value += v[i]; cleft -= w[i]; i++; } if(i<n) cleft_value += v[i] / w[i] * cleft; return (cleft_value + cv);}void BackTrack(int i) { if (i > n-1) {//只要能到达叶子节点,一定是最好的情况 for (int t = 0; t < n; t++) { best_x[t] = x[t];//记录解向量 } bestv = cv; return; } if (cw + w[i] <= c) { x[i] = 1; cw += w[i]; cv += v[i]; BackTrack(i+1); cw -= w[i];//回溯, cv -= v[i]; } if (Bound(i + 1) >bestv) { x[i] = 0; BackTrack(i + 1); }} 分支限界法