2 qq 32742637 qq_32742637 于 2016.05.06 10:30 提问

多重背包问题,输入正常数据,出现逻辑错误,求解答

输入数据 4 10
1 2 3
2 3 2
3 7 2
2 5 1
会出错,但是输入一些其他的数据又不会报错

 #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int Max(int a, int b);
void Zero_One_package(int *Max_value, int weight, int value, int volume);
void Complete_package(int *Max_value, int weight, int value, int volume);
int Multi_package();
void main()
{
    int Max_V = Multi_package();
    printf("%d", Max_V);
    system("pause");
}
int Max(int a, int b)
{
    return a >= b ? a : b;
}
void Zero_One_package(int *Max_value, int weight, int value, int volume)
{
    for (int i = volume; i >= weight; i--)
    {
        Max_value[i] = Max(Max_value[i], Max_value[i - weight] + value);
    }
}
void Complete_package(int *Max_value, int weight, int value, int volume)
{
    for (int i = weight; i <= volume; i++)
    {
        Max_value[i] = Max(Max_value[i], Max_value[i - weight] + value);
    }
}
int Multi_package()
{
    int num, volume;
    scanf("%d%d", &num, &volume);
    int *weight = (int *)malloc(sizeof(int)*num);
    int *value = (int *)malloc(sizeof(int)*num);
    int *number = (int *)malloc(sizeof(int)*num);
    int *Max_value = (int*)malloc(sizeof(int)*(num + 1));
    for (int i = 0; i < num; i++)
    {
        scanf("%d%d%d", &weight[i], &value[i], &number[i]);
    }
    for (int i = 0; i <= volume; i++)
    {
        Max_value[i] = 0;
    }
    for (int i = 0; i < num; i++)
    {
        if (number[i] * weight[i] >= volume)
        {
            Complete_package(Max_value, weight[i], value[i], volume);
        }
        else
        {
            int ncount = number[i];
            int k = 1;
            while (ncount > k)
            {
                Zero_One_package(Max_value, k*weight[i], k*value[i], volume);
                ncount -= k;
                k *= 2;
            }
            Zero_One_package(Max_value, ncount*weight[i], ncount*value[i], volume);
        }
    }
    return Max_value[volume];
}

1个回答

mazegong
mazegong   2016.05.06 15:50

没有研究过多重背包问题

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!