SGU 415. Necessary Coins ( 背包dp )

题意大概是:给出N个硬币, 面值为a_i, 问要凑成X元哪些硬币是不可或缺的.1 ≤ N ≤ 200, 1 ≤ x ≤ 10^4

直接枚举, 然后就是01背包了. 为了不让复杂度多乘个N, 我们就从左往右, 从右往左分别dp一次.这样判断一个硬币就是O(X).总时间复杂度O(NX)

-----------------------------------------------------------------------------

#include<bits/stdc++.h>
 
using namespace std;
 
const int maxn = 209;
const int maxv = 10009;
 
bool L[maxn][maxv], R[maxn][maxv];
int v[maxn], N, V;
vector<int> ans;
 
int main() {
memset(L, false, sizeof L);
memset(R, false, sizeof R);
cin >> N >> V;
for(int i = 1; i <= N; i++)
   scanf("%d", v + i);
L[0][0] = R[N + 1][0] = true;
for(int i = 1; i <= N; i++) {
for(int j = 0; j <= V; j++)
   L[i][j] = L[i - 1][j];
for(int j = V; j >= v[i]; j--)
   L[i][j] |= L[i - 1][j - v[i]];
}
for(int i = N; i; i--) {
for(int j = 0; j <= V; j++)
   R[i][j] = R[i + 1][j]; 
for(int j = V; j >= v[i]; j--)
   R[i][j] |= R[i + 1][j - v[i]];
}
for(int i = 1; i <= N; i++) {
bool F = false;
for(int j = 0; j <= V; j++)
   if(L[i - 1][j] && R[i + 1][V - j]) {
   F = true;
   break;
}
if(!F) ans.push_back(v[i]);
}
printf("%d\n", ans.size());
for(int i = 0; i < ans.size(); i++)
   printf("%d ", ans[i]);
return 0;
}

----------------------------------------------------------------------------- 

415. Necessary Coins
Time limit per test: 1.25 second(s)
Memory limit: 262144 kilobytes
input: standard
output: standard



Vasya has been on vacation on Mars. He's a big fan of foreign coins, and thus has collected exactly one martian coin of each denomination, for a total of n coins: a1 martian dollars, a2 martian dollars, etc, an martian dollars. Unfortunately, he couldn't stand ordering the Pan Galactic Gargle Blaster at the Starport, and has to pay for it — it costs x martian dollars. Vasya is wondering which of his coins are absolutely necessary to do so (i.e., he is forced to abandon them). They don't offer change at the Starport Mars.

Input
The input file contains two integer numbers n and x (1 ≤ n ≤ 200, 1 ≤ x ≤ 104), followed by n distinct integer numbersai (1 ≤ ai ≤ x).

Output
On the first line of output, print the amount of denominations of coins that appear in any subset that sums to xmartian dollars. On the second line of output, print the denominations themselves, in any order, separated with single spaces. It is guaranteed that there exists at least one way to pay x martian dollars with the given coins.

Example(s)
sample input
sample output
5 18 1 2 3 5 10 
2 5 10 

 

转载于:https://www.cnblogs.com/JSZX11556/p/4719198.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值