4120:硬币(动态规划)

 

总时间限制: 
1000ms
 
内存限制: 
262144kB
描述

宇航员Bob有一天来到火星上,他有收集硬币的习惯。于是他将火星上所有面值的硬币都收集起来了,一共有n种,每种只有一个:面值分别为a1,a2… an。 Bob在机场看到了一个特别喜欢的礼物,想买来送给朋友Alice,这个礼物的价格是X元。Bob很想知道为了买这个礼物他的哪些硬币是必须被使用的,即Bob必须放弃收集好的哪些硬币种类。飞机场不提供找零,只接受恰好X元。

输入
第一行包含两个正整数n和x。(1 <= n <= 200, 1 <= x <= 10000)
第二行从小到大为n个正整数a1, a2, a3 … an (1 <= ai <= x)
输出
第一行是一个整数,即有多少种硬币是必须被使用的。
第二行是这些必须使用的硬币的面值(从小到大排列)。
样例输入
5 18
1 2 3 5 10
样例输出
2
5 10
提示
输入数据将保证给定面值的硬币中至少有一种组合能恰好能够支付X元。
如果不存在必须被使用的硬币,则第一行输出0,第二行输出空行。

解题思路:我们考虑a[i]是否满足其实必须元素,容易想到,f[x]-f[x-a[i]]是否为零,但是f[x-a[i]]的方案数中可能也会用到a[i],所以f[x-a[i]]-f[x-a[i]*2],整理一下就是f[x]-f[x-a[i]]+f[x-a[i] *2],也很容易发现容斥规律,由此可以递归求解,递归边界为x-a[i] *k<0或者f[x-a[i] *k]==0;
算法时间复杂度
————————————————
原文链接:https://blog.csdn.net/qq_18455665/article/details/50285203

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<iostream>
 4 using namespace std;
 5 #define N 205
 6 #define M 10005
 7 int n,x,l;
 8 int a[N],ans[N];
 9 int f[M];
10 int calc(int x,int v) {
11     if(x<0) return 0;
12     else return f[x]-calc(x-v,v);
13 }
14 int main() {
15     scanf("%d%d",&n,&x);
16     for(int i=1; i<=n; i++) scanf("%d",&a[i]);
17     f[0]=1;
18     for(int i=1; i<=n; i++)
19         for(int j=x; j>=a[i]; j--)
20             f[j]+=f[j-a[i]];
21     for(int i=1; i<=n; i++) {
22         if(!(f[x]-calc(x-a[i],a[i]))) {
23             ans[++l]=a[i];
24         }
25     }
26     printf("%d\n",l);
27     for(int i=1; i<=l; i++) printf("%d ",ans[i]);
28     return 0;
29 }

猜你喜欢

转载自www.cnblogs.com/aiqinger/p/12607757.html