2287: 【POJ Challenge】消失之物
Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 650 Solved: 378
[Submit][Status][Discuss]
Description
ftiasch 有 N 个物品, 体积分别是 W1, W2, ..., WN。 由于她的疏忽, 第 i 个物品丢失了。 “要使用剩下的 N - 1 物品装满容积为 x 的背包,有几种方法呢?” -- 这是经典的问题了。她把答案记为 Count(i, x) ,想要得到所有1 <= i <= N, 1 <= x <= M的 Count(i, x) 表格。
Input
第1行:两个整数 N (1 ≤ N ≤ 2 × 103) 和 M (1 ≤ M ≤ 2 × 103),物品的数量和最大的容积。
第2行: N 个整数 W1, W2, ..., WN, 物品的体积。
Output
一个 N × M 的矩阵, Count(i, x)的末位数字。
Sample Input
3 2
1 1 2
1 1 2
Sample Output
11
11
21
11
21
HINT
如果物品3丢失的话,只有一种方法装满容量是2的背包,即选择物品1和物品2。
背包dp
f[i][j]表示前i个物品放满j容量的包的方案数
c[i][j]表示不用i放满j的方案
j<a[i]时 c[i][j]=f[n][j]
j>=a[i]时 c[i][j]=f[n][j]-c[i][j-a[i]]
由2可知c[i][0]=1 能下初始化
#include<cmath>
#include<ctime>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<complex>
#include<iostream>
#include<algorithm>
#include<iomanip>
#include<vector>
#include<string>
#include<queue>
#include<set>
#include<map>
using namespace std;
inline int read()
{
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch<='9'&&ch>='0'){x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
return x*f;
}
const int N=2010;
typedef long long ll;
ll n,m,a[N],c[N][N],f[N][N];
int main()
{
n=read();m=read();
for(int i=1;i<=n;i++)a[i]=read();
f[0][0]=1;
for(int i=1;i<=n;i++)
for(int j=0;j<=m;j++)
{
f[i][j]=(f[i][j]+f[i-1][j])%10;
if(j>=a[i])f[i][j]=(f[i][j]+f[i-1][j-a[i]])%10;
}
for(int i=1;i<=n;i++)
{
for(int j=0;j<=m;j++)
{
if(j<a[i]) c[i][j]=f[n][j];
else c[i][j]=(f[n][j]-c[i][j-a[i]]+10)%10;
if(j>0) printf("%lld",c[i][j]);
}
printf("\n");
}
return 0;
}
/*
3 2
1 1 2
11
11
21
*/