Codeforces Round #360 (Div. 2) E dp 類似01揹包

CrossDolphin發表於2016-07-06



連結:戳這裡


E. The Values You Can Make
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
Pari wants to buy an expensive chocolate from Arya. She has n coins, the value of the i-th coin is ci. The price of the chocolate is k, so Pari will take a subset of her coins with sum equal to k and give it to Arya.

Looking at her coins, a question came to her mind: after giving the coins to Arya, what values does Arya can make with them? She is jealous and she doesn't want Arya to make a lot of values. So she wants to know all the values x, such that Arya will be able to make x using some subset of coins with the sum k.

Formally, Pari wants to know the values x such that there exists a subset of coins with the sum k such that some subset of this subset has the sum x, i.e. there is exists some way to pay for the chocolate, such that Arya will be able to make the sum x using these coins.

Input
The first line contains two integers n and k (1  ≤  n, k  ≤  500) — the number of coins and the price of the chocolate, respectively.

Next line will contain n integers c1, c2, ..., cn (1 ≤ ci ≤ 500) — the values of Pari's coins.

It's guaranteed that one can make value k using these coins.

Output
First line of the output must contain a single integer q— the number of suitable values x. Then print q integers in ascending order — the values that Arya can make for some subset of coins of Pari that pays for the chocolate.

Examples
input
6 18
5 6 1 10 12 2
output
16
0 1 2 3 5 6 7 8 10 11 12 13 15 16 17 18 
input
3 50
25 25 50
output
3
0 25 50 


題意:

給出n個零錢的價值,以及一個總額m

任意選零錢一次使得能湊出m,只要是能湊出m的零錢面額都拿出來拼成一個集合S

問S中的零錢能湊出的面額個數,並輸出


思路:

dp[i][j][k]表示當前第i個面額,總和為j,能否湊出k

類似於01揹包只取一次,能湊到的面額都是有效的面額


程式碼:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
#include<vector>
#include <ctime>
#include<queue>
#include<set>
#include<map>
#include<stack>
#include<iomanip>
#include<cmath>
#define mst(ss,b) memset((ss),(b),sizeof(ss))
#define maxn 0x3f3f3f3f
#define MAX 1000100
///#pragma comment(linker, "/STACK:102400000,102400000")
typedef long long ll;
typedef unsigned long long ull;
#define INF (1ll<<60)-1
using namespace std;
int n,K;
int a[1010];
bool dp[550][550];
vector<int> V;
int main(){
    scanf("%d%d",&n,&K);
    for(int i=1;i<=n;i++) scanf("%d",&a[i]);
    sort(a+1,a+n+1);
    dp[0][0]=true;
    for(int i=1;i<=n;i++){
        for(int j=K;j>=a[i];j--){
            for(int l=0;l<=j;l++){
                dp[j][l]|=dp[j-a[i]][l];
                if(l>=a[i]) dp[j][l]|=dp[j-a[i]][l-a[i]];
            }
        }
    }
    for(int i=0;i<=500;i++){
        if(dp[K][i]) V.push_back(i);
    }
    printf("%d\n",V.size());
    for(auto & a : V) printf("%d ",a);
    puts("");
    return 0;
}


相關文章