hdu(3033)(分组背包变形之一)

#include <iostream>
#include <cstdio>
#include <string.h>
WA了好多次,才发现动态转移方程有问题,这大概就是多个选择得到最优值吧
此题类似多重背包,每组至少选一个,代码好乱哇
using namespace std;
int max(int a,int b)
{
	if (a>b)
		return a;
	else
        return b;
}
struct node
{
    int k,cost,value;
}s[1500];
int dp[15][10005];
int main()
{
    int n,k,v,i,j,l;
    while(scanf("%d%d%d",&n,&v,&k)!=EOF)
    {
        memset(dp,0,sizeof(dp));
        int flag=0;
        for (i=1;i<=n;++i)
        scanf("%d%d%d",&s[i].k,&s[i].cost,&s[i].value);
        for (i=1;i<=k;++i)
        {
            for (j=1;j<=n;++j)
            if (s[j].k==i)//判断是否属于该组
            {
                if (v<s[j].cost)//总体积过小
                {
                   printf ("Impossible\n");
                    flag=1;
                    break;
                }
                for (l=v;l>=s[j].cost;--l)
                if (dp[i-1][l-s[j].cost]!=0||i==1)//比如2 50 2 1 50 20 2 50 20这种情况,在第一组时已经把钱都用完了,第二组根本没法选
                dp[i][l]=max(dp[i][l],max(dp[i-1][l-s[j].cost]+s[j].value,dp[i][l-s[j].cost]+s[j].value));
            }
        }
        if (flag)
        continue;
        if (dp[k][v]!=0)
        printf ("%d\n",dp[k][v]);
        else
        printf ("Impossible\n");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/1994two/p/3068884.html