codeforces632E. Thief in a Shop (dp)

A thief made his way to a shop.

As usual he has his lucky knapsack with him. The knapsack can contain k objects. There are n kinds of products in the shop and an infinite number of products of each kind. The cost of one product of kind i is ai.

The thief is greedy, so he will take exactly k products (it's possible for some kinds to take several products of that kind).

Find all the possible total costs of products the thief can nick into his knapsack.

Input

The first line contains two integers n and k (1 ≤ n, k ≤ 1000) — the number of kinds of products and the number of products the thief will take.

The second line contains n integers ai (1 ≤ ai ≤ 1000) — the costs of products for kinds from 1 to n.

Output

Print the only line with all the possible total costs of stolen products, separated by a space. The numbers should be printed in the ascending order.

Examples
input
3 2
1 2 3
output
2 3 4 5 6
input
5 5
1 1 1 1 1
output
5
input
3 3
3 5 11
output

9 11 13 15 17 19 21 25 27 33

题意:给你n种物品以及每种的价值,每一种物品可以任意取多次,问恰好取k次物品能取到的所有可能价值。

思路:容易想到4维dp,用dp[i][j]表示取i次,价值为j是否存在,但是这样的复杂度为10^12爆了,所以要减少一维,先对n个数排序,然后n个数都减去第一个数(这样做的目的是恰好k次很难dp,n个数都减去最小的数后,第1个数就变为0,在这样的情况下,如果我们凑到价值为i的物品少于k件,如只用k-2件拼凑,那么另外两件可以看做都用第1个物品),然后用dp[i]表示最后取到价值为i的物品,dp就行了。


#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define inf 99999999
#define pi acos(-1.0)
#define maxn 1005
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef long double ldb;
int dp[maxn*maxn],a[maxn];

int main()
{
    int n,m,i,j,k;
    while(scanf("%d%d",&n,&k)!=EOF)
    {
        for(i=1;i<=n;i++){
            scanf("%d",&a[i]);
        }
        sort(a+1,a+1+n);
        int t=a[1];
        for(i=1;i<=n;i++){
            a[i]-=t;
        }
        for(i=0;i<=1000000;i++)dp[i]=inf;
        dp[0]=0;

        for(j=0;j<=1000000;j++){
            for(i=1;i<=n;i++){
                if(j>=a[i]){
                    dp[j]=min(dp[j],dp[j-a[i] ]+1);
                }
            }
        }
        int flag=1;
        for(j=0;j<=1000000;j++){
            if(dp[j]<=k){
                printf("%d ",j+t*k);
            }
        }
        printf("\n");
    }
    return 0;
}


你可能感兴趣的:(dp,dp)