las和回溯結合的解01揹包的程式碼
阿新 • • 發佈:2019-01-02
測試資料 1 19 12#include<iostream> #include<fstream> #include<vector> #include<string> #include<bitset> #include<algorithm> #include<ctime> using namespace std; const int N=50;//the number of the item const int max_w=1000;//max weight int best_solution=0; bitset<N> b; vector<int> v,v_best; vector<int> w; int lcw=0; // be used to translate the weight from las to trace int lcv=0; int final_v=0; void las_packing(int); void trace_back(int,int,int); int main(){ v.reserve(N); v_best.reserve(N); w.reserve(N); cout<<"input the weight and value of each item"; freopen("test.txt","r",stdin); for(int i=0;i<N;i++){ int x=0; int y=0; cin>>x; v.push_back(x); cin>>y; w.push_back(y); } cout<<"done"<<endl; for(int i=0;i<10;i++){ las_packing(30); trace_back(31,lcw,lcv); if(best_solution>final_v) final_v = best_solution; lcw=0; lcv=0; } cout<<final_v<<endl; } void trace_back(int i,int cw, int cv){ int j; if(i>=N){ if(cv>best_solution) { best_solution=cv; v_best.assign(v.begin(),v.end()); } } else{ for(j=0;j<=1;j++){ b.flip(i); if( cw + (int)b[i] * w[i] <= max_w){ cw += w[i]*(int)b[i]; cv += v[i]*(int)b[i]; trace_back(i+1,cv,cw); cw -= w[i]*(int)b[i]; cv -= v[i]*(int)b[i]; } } } } void las_packing(int n){ srand(unsigned(time(0))); for(int i=0;i<n;i++){ if(rand()/(RAND_MAX+1.0)>0.5) b.flip(i); if(lcw+(int)b[i]*w[i]<=max_w){ lcw += w[i]*(int)b[i]; lcv += v[i]*(int)b[i]; } else b.flip(i); } }
2 53 61
3 61 63
4 74 78
5 98 49
6 70 46
7 15 44
8 59 36
9 64 37
10 29 66
11 98 43
12 79 16
13 74 14
14 85 73
15 52 72
16 70 72
17 84 83
18 91 15
19 84 83
20 75 65
21 78 21
22 72 49
23 5 36
24 46 20
25 26 22
26 95 80
27 38 94
28 79 3
29 28 73
30 92 1
31 12 91
32 37 62
33 37 8
34 58 58
35 94 79
36 44 67
37 25 53
38 3 8
39 12 85
40 67 82
41 2 70
42 98 43
43 12 22
44 2 53
45 34 22
46 68 14
47 68 41
48 81 41
49 92 77
50 16 75