首页 > 编程语言 > 详细

算法 | 0-1背包

时间:2018-11-07 23:55:04      阅读:245      评论:0      收藏:0      [点我收藏+]

  

技术分享图片

#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;
}

  

算法 | 0-1背包

原文:https://www.cnblogs.com/jj81/p/9926480.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!