1. 程式人生 > >演算法 | 0-1揹包

演算法 | 0-1揹包

  

#include<stdio.h>
#include<string.h>

#define MaxN  10000
#define MaxC  10000

int Val[MaxN][MaxN];

double binaryKnapsack(int numItems, int *w,int *v, int capacity)
{
	
    int i, j;
    
    
    for(i = 1; i <= numItems; ++i) {
    
    	for(j = 1; j <= capacity; j++) {
    		if(j < w[i-1]) {
    			Val[i][j] = Val[i-1][j];
				continue;
			}
			
			if( (Val[i-1][j-w[i-1]] + v[i-1]) >Val[i-1][j]) {
		
				Val[i][j] = (Val[i-1][j-w[i-1]] + v[i-1]);
			} else {
				Val[i][j] =  Val[i-1][j];
			}
		
		}
	
	}
	/**
    for (i = 0; i < numItems; ++i)
        for (j = capacity; j >= 0; j--)
            if (j >= w[i] && Val[j] < Val[j - w[i]] + v[i])
                Val[j] = Val[j - w[i]] + v[i];
    return Val[capacity]; **/
    
    return Val[numItems][capacity];
}

int main()
{
    int i, n, C, w[MaxN];
    int v[MaxN];
    int flag[MaxN];
    int ans;
    while (scanf("%d%d", &C, &n) != EOF)
    {
        for (i = 0; i < n; ++i)
            scanf("%d", &w[i]);
        for (i = 0; i < n; ++i)
            scanf("%d", &v[i]);
             
        ans = binaryKnapsack(n, w, v, C);
       printf("%d", ans);
        
        int j = C;
        memset(flag, 0, sizeof(flag));
        
        for(int i = n; i > 0; i-- ) {
        	if(Val[i][j] > Val[i-1][j]) {
        		flag[i] = 1;
        		j = j - w[i-1];
        		if(j < 0) break;
			}
		}
		
		for(int i = 1; i <= n; i++) {
			
				printf(" %d",flag[i]);
			
		}
		printf("\n");
    }

    return 0;
}