把最小的城堡的值记录下来,然后每一个城堡都当作一个01背包(背包最大容纳值为前面求得最小值),每个城堡只能放进自己的积木,求出都能达到的最大高度, 177ms
#include <stdio.h>
#include <string.h>
struct node
{
int L[105], len;
}a[105];
int dp[105][10005];
int max(int a, int b)
{
return a>b?a:b;
}
int main()
{
int n, i, j, k, l, x, min, tmp, flag, ans;
scanf("%d", &n);
min = 999999999;
for(i = 0;i < n;i++)
{
a[i].len = tmp = 0;
while(scanf("%d", &x)&&x != -1)
{
a[i].L[a[i].len++] = x;
tmp += x;
}
if(tmp < min) min = tmp;
//printf("ppppp\n");
}
for(i = 0;i < n;i++)
{
for(j = 0;j < a[i].len;j++)
for(k = tmp;k >= a[i].L[j];k--)
dp[i][k] = max(dp[i][k], dp[i][k - a[i].L[j]] + a[i].L[j]);
}
ans = 0;
for(i = tmp;i >= 0;i--)
{
flag = 1;
for(j = 0;j < n;j++)
if(dp[j][i] != i)
flag = 0;
if(flag){
ans = i;
break;
}
}
printf("%d\n", ans);
}