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
| #include <iostream> #include<cstdio> #include<string.h> #include<algorithm>
using namespace std;
#define N 100
struct goods{ int wight; int value; };
int n,bestValue,cv,cw,C; int X[N],cx[N]; struct goods goods[N];
int BackTrack(int i){ if(i > n-1){ if(bestValue < cv){ for(int k = 0; k < n; k++) X[k] = cx[k]; bestValue = cv; } return bestValue; } if(cw + goods[i].wight <= C){ cw += goods[i].wight; cv += goods[i].value; cx[i] = 1; BackTrack(i+1); cw -= goods[i].wight; cv -= goods[i].value; } cx[i] = 0; BackTrack(i+1); return bestValue; }
bool m(struct goods a, struct goods b){ return (a.value/a.wight) > (b.value/b.wight); }
int KnapSack3(int n, struct goods a[], int C,int x[N]){ memset(x,0,sizeof(x)); sort(a,a+n,m); BackTrack(0); return bestValue; } int main() { printf("n:"); scanf("%d",&n); printf("C:"); scanf("%d",&C); for(int i = 0; i < n; i++){ printf("weight and value:",i+1,i+1,i+1); scanf("%d%d",&goods[i].wight,&goods[i].value); } int sum3 = KnapSack3(n,goods,C,X); printf("The answer\nX=["); for(int i = 0; i < n; i++) cout << X[i] <<" "; printf("] The value%d\n",sum3); return 0; }
|