POJ 1276 full backpack

Sample Input

735 3  4 125  6 5  3 350
633 4  500 30  6 100  1 5  0 1
735 0
0 3  10 100  10 50  10 10

Sample Output

735 
630 
0 
0 

meaning of the questions: Do you have a bank card yuan cash, and ATM machines, there are n denominations of money, money n rows of each number and face value.
  This is the most asked how much money from the ATM machine inside out.

The backpack is completely naked
but I actually wrong. . . .
When the current number of items of value greater than or equal backpack * capacity, it can be regarded as an infinite number of current items, for loop when he traversed the positive sequence from small to large.
When less than or equal to the number of articles 01 will convert the binary knapsack backpack 01 is here! ! !

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

int cash, n;
int c[15],w[15];
int dp[100005];

void CompletePack(int c,int w){
    if(c*w>=cash){ // 完全背包
        for(int j=w;j<=cash;j++)
            dp[j] = max(dp[j],dp[j-w]+w);
    }else {  // 多次01背包
        int k = 1;
        while(k<c){
            for(int j=cash;j>=w*k;j--)
                dp[j] = max(dp[j],dp[j-w*k]+w*k);
            c -= k;
            k <<= 1;
        }
        for(int j=cash;j>=w*c;j--)
            dp[j] = max(dp[j],dp[j-w*c]+w*c);
    }
}
int main(){
    while(scanf("%d%d",&cash,&n)!=EOF){
        memset(dp,0,sizeof(dp));
        for(int i=0;i<n;i++){
            scanf("%d%d",&c[i],&w[i]);
        }
        for(int i=0;i<n;i++){
            CompletePack(c[i],w[i]);
        }
        printf("%d\n",dp[cash]);
    }
    return 0;
}
View Code

 




Guess you like

Origin www.cnblogs.com/kongbb/p/10939431.html