链接:戳这里
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;
}