您的位置:首页 > 产品设计 > UI/UE

CodeForces 678C The Values You Can Make (3维DP)

2016-07-09 10:38 369 查看
C. The Values You Can Make

time limit per test
2 seconds

memory limit per test
256 megabytes

input
standard input

output
standard 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 xusing some subset of coins with the sum k.

Formally, Pari wants to know the values x s
4000
uch 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,k(n为数字的个数,k为一个和),从这n个数选出若干个,使得这若干个数的          和为k,求这若干个数所形成的集合的子集中各个元素的和。输出所有可能的和。

最初用了回溯法把子集枚举了一遍并对每个子集所能形成的和再DFS,时间复杂度已经到指       数级别了,结果毫不意外的超时。

思路:我们首先要知道选哪些数能够成和k,再要知道这些数的子集及其各自的和。所以考虑三维      dp,dp[i][j][k]表示用前i个数组成和j时能否构成和k,边界为dp[0][0][0] = true,这      样状态转移方程为dp(i,j,k) = dp(i-1,j,k) | dp(i-1,j-x,k-x) | dp(i-1,j-x,k-x),因       为状态转移中只会用到当前状态和前一状态,所以考虑用滚动数组来节省空间。

#include<cstdio>
#include<vector>
#include<cstring>
using namespace std;

const int maxn = 500 + 10;
bool dp[2][maxn][maxn];
vector<int> ans;

int main() {
int n,K,x;
scanf("%d%d",&n,&K);
dp[0][0][0] = true;
for (int i = 1; i <= n; i++) {
scanf("%d",&x);
int cur = i % 2;
int last = 1 - cur;
for (int j = 0; j <= K; j++) {
for (int k = 0; k <= K; k++) {
dp[cur][j][k] |= dp[last][j][k];
if (j >= x) dp[cur][j][k] |= dp[last][j-x][k];
if (j >= x && k >= x) dp[cur][j][k] |= dp[last][j-x][k-x];
}
}
}
for (int i = 0; i <= K; i++) {
if (dp[n%2][K][i]) ans.push_back(i);
}
printf("%d\n",ans.size());
for (int i = 0; i < ans.size(); i++) {
printf("%d%c",ans[i],i==ans.size()-1?'\n':' ');
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: