回溯法

image-20230404082340474

image-20230404083209585

image-20230404083723988

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include<iostream>
#define N 10010
using 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);
}
}

分支限界法