洛谷P4141消失之物

題目描述

ftiasch 有 N 個物品, 體積分別是 W1, W2, …, WN。 因爲她的疏忽, 第 i 個物品丟失了。 「要使用剩下的 N – 1 物品裝滿容積爲 x 的揹包,有幾種方法呢?」 — 這是經典的問題了。她把答案記爲 Count(i, x) ,想要獲得全部1 <= i <= N, 1 <= x <= M的 Count(i, x) 表格。html

輸入輸出格式

輸入格式:ios

 

第1行:兩個整數 N (1 ≤ N ≤ 2 × 10^3)N(1N2×103) 和 M (1 ≤ M ≤ 2 × 10^3)M(1M2×103),物品的數量和最大的容積。git

第2行: N 個整數 W1, W2, …, WN, 物品的體積。spa

 

輸出格式:rest

 

一個 N × M 的矩陣, Count(i, x)的末位數字。code

 

This DP is pretty hard.htm

First we should know that F[i][j] means that how many funcation what we can have when we put i's stuff in the bag which has j's volume.blog

If the i's stuff had to taken, it wil  be f[i-1][j-w[i]], else, it will be f[i-1][j], So we can get the funcation :f[i][j]=f[i-1][j]+f[i-1][j-w[i];get

we can use rounded array change it to f[j]=f[j]+f[j-w[i]].string

So, how can we get the count ?

we had to enumeration whitch stuff we had lost.

if w[i]>j, that means, all of the answer has include the stuff i, because it was bigger than the volume. Therefore, the answer should be f[j] , which means take all of the answer.

if w[i]<=j, that means there are some anwer has be counted. what we should do is minus the rest of stuff(except i) to pull in j-w[i]. which is f[j]-c[i][j-w[i]]

if w[i]==0 , the c[i][j] will be 1.

that's all.

 

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#define in(a) a=read()
#define REP(i,k,n)  for(int i=k;i<=n;i++) 
using namespace std;
inline int read(){
    int x=0,f=1;
    char ch=getchar();
    for(;!isdigit(ch);ch=getchar())
        if(ch=='-')
            f=-1;
    for(;isdigit(ch);ch=getchar())
        x=x*10+ch-'0';
    return x*f;
} 
int n,m;
int f[2010],c[2010][2010],w[2010]; 
int main(){
    in(n),in(m);
    REP(i,1,n)  in(w[i]); 
    f[0]=1;  
    REP(i,1,n)
        for(int j=m;j>=w[i];j--) 
            f[j]=(f[j]+f[j-w[i]])%10;
    REP(i,1,n){
        c[i][0]=1;
        REP(j,1,m){ 
            if(j<w[i])  c[i][j]=f[j];
            else  c[i][j]=(f[j]-c[i][j-w[i]]+10)%10;
            printf("%d",c[i][j]);
        }
        printf("\n");     
    } 
    return 0;
} 
相關文章
相關標籤/搜索