Current location - Plastic Surgery and Aesthetics Network - Jewelry brand - C++ knapsack problem
C++ knapsack problem
# include & ltstdio.h & gt

int? n,W[ 1000],T,b[ 1000];

Invalid? f(int? t,int? Sum)

{

int? Me;

if(t & gt; n+ 1)

Return;

if(sum & gt; t)

Return;

Or what? if(sum==T){

for(I = 1; I & ltt;; i++){

if(b[i]== 1)

printf("W%d=%d?" ,I,W[I]);

}

printf(" \ n ");

Return;

}

b[t]= 1;

f(t+ 1,sum+W[t]);

b[t]= 0;

f(t+ 1,sum);

}

int? Master ()

{

int? P[ 1000],a[ 100000][2],I,j;

while(scanf("%d%d ",& ampn & amp; t)! =EOF){

/* Enter data */

for(I = 1; I < = n; i++)

scanf("%d%d ",& ampW[i],& ampp[I]);

for(I = 0; I<= T;; i++)

a[I][0]= a[I][ 1]= 0;

/************************************/

f( 1,0); //Call a function to solve the problem 1

/*0- 1 knapsack algorithm */

for(I = 1; I < = n; i++){

for(j = 0; j & ltw[I]& amp; & ampj & lt= T; j++)

a[j][I % 2]= a[j][(I+ 1)% 2];

for(; j & lt= T; j++)

if(a[j-W[I]][(I+ 1)% 2]+P[I]& gt; a[j][(i+ 1)%2])

a[j][I % 2]= a[j-W[I]][(I+ 1)% 2]+P[I];

other

a[j][I % 2]= a[j][(I+ 1)% 2];

}

printf("max=%d.\n\n ",a[T][n % 2]);

/***********************************/

}

Return? 0;

}

The input format is:

n? T

W 1? P 1

W2? P2

..

..

..

Wn? promissory note

Result output:

Wk 1? Wk2 ...

Wk 1? Wk2 ...

Max= maximum total price.

Example:

Input:

5? 10

1? 1

2? 2

3? three

4? four

5? five

Output:

W 1= 1? W2=2? W3=3? W4=4

W 1= 1? W4=4? W5=5

W2=2? W3=3? W5=5

max= 10。