团体程序设计天梯赛L3-001 凑零钱
2017-03-02 21:55
387 查看
L3-001. 凑零钱
时间限制200 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越
韩梅梅喜欢满宇宙到处逛街。现在她逛到了一家火星店里,发现这家店有个特别的规矩:你可以用任何星球的硬币付钱,但是绝不找零,当然也不能欠债。韩梅梅手边有104枚来自各个星球的硬币,需要请你帮她盘算一下,是否可能精确凑出要付的款额。
输入格式:
输入第一行给出两个正整数:N(<=104)是硬币的总个数,M(<=102)是韩梅梅要付的款额。第二行给出N枚硬币的正整数面值。数字间以空格分隔。
输出格式:
在一行中输出硬币的面值 V1 <= V2 <= ... <= Vk,满足条件 V1 + V2 + ... + Vk =
M。数字间以1个空格分隔,行首尾不得有多余空格。若解不唯一,则输出最小序列。若无解,则输出“No Solution”。
注:我们说序列{A[1], A[2], ...}比{B[1], B[2], ...}“小”,是指存在 k >= 1 使得 A[i]=B[i] 对所有 i < k 成立,并且 A[k] < B[k]。
输入样例1:
8 9 5 9 8 7 2 3 4 1
输出样例1:
1 3 5
输入样例2:
4 8 7 2 4 3
输出样例2:
No Solution
解题思路:背包或者dfs
背包
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
#include <set>
#include <stack>
#include <map>
#include <climits>
using namespace std;
#define LL long long
const int INF=-0x3f3f3f3f;
stack<int>s;
int dp[10009],p[10009],a[10009];
int main()
{
int n,m;
while(~scanf("%d %d",&n,&m))
{
for(int i=0;i<=10008;i++) dp[i]=INF;
dp[0]=0;
for(int i=0; i<n;i++) scanf("%d",&a[i]);
sort(a,a+n);
for(int i=0; i<n;i++)
{
for(int j=m; j>=a[i];j--)
{
if(dp[j]<=dp[j-a[i]]+1)
{
dp[j]=dp[j-a[i]]+1;
p[j]=j-a[i];
}
}
}
if(dp[m]>0)
{
int k=m;
while(p[k])
{
s.push(k-p[k]);
k=p[k];
}
printf("%d",k);
while(!s.empty())
{
printf(" %d",s.top());
s.pop();
}
printf("\n");
}
else printf("No Solution\n");
}
return 0;
}
dfs
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
#include <set>
#include <stack>
#include <map>
#include <climits>
using namespace std;
#define LL long long
const int INF=0x3f3f3f3f;
int a[10005];
int n,m,ans[10005];
int flag,cnt;
void dfs(int k,int sum1,int sum2)
{
if(sum1==m) {flag=1;ans[cnt++]=k;return;}
if(sum1+sum2<m||k>=n) return;
if(sum1+a[k]<=m)
{
dfs(k+1,sum1+a[k],sum2-a[k]);
if(flag) {ans[cnt++]=k;return ;}
dfs(k+1,sum1,sum2-a[k]);
if(flag) return ;
}
else return ;
}
int main()
{
while(~scanf("%d %d",&n,&m))
{
int sum=0;
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
sum+=a[i];
}
sort(a,a+n);
cnt=flag=0;
dfs(0,0,sum);
if(flag)
{
printf("%d",a[ans[cnt-1]]);
for(int i=cnt-2;i>0;i--)
printf(" %d",a[ans[i]]);
printf("\n");
}
else printf("No Solution\n");
}
return 0;
}
相关文章推荐
- 团体程序设计天梯赛-练习集 L3-001. 凑零钱
- L3-001. 凑零钱-PAT团体程序设计天梯赛GPLT(01背包,动态规划)
- 团体程序设计天梯赛-练习集 L3-001. 凑零钱
- 团体程序设计天梯赛-练习集 L3-001. 凑零钱 强行dfs+剪枝 解题报告
- 团体天梯赛 L3-001. 凑零钱
- 团体程序设计天梯赛L3-004 肿瘤诊断
- 团体程序设计天梯赛 L3-008. 喊山 BFS
- 团体程序设计天梯赛-练习集 L3-002. 堆栈 线段树 单点更新 解题报告
- 团体程序设计天梯赛L3-008 喊山
- 2017团体程序设计天梯赛大区赛 L3-3 球队“食物链”
- 团体程序设计天梯赛 L3-007. 天梯地图(dijkstral+记录所有最短路径)
- 团体程序设计天梯赛 L2-001. 紧急救援(dijkstra)
- 团体程序设计天梯赛 L3-003. 社交集群(并差集)
- 团体程序设计天梯赛L3-013 非常弹的球
- 团体程序设计天梯赛-练习集 L2-001. 紧急救援
- 团体程序设计天梯赛-练习集 L2-001. 紧急救援
- 团体程序设计天梯赛 决赛 L3 是否完全二叉搜索树
- 2016年团体程序设计天梯赛-模拟赛 L3-1. 肿瘤诊断 (三维 BFS)
- 【题解】PAT.团体程序设计天梯赛.L3-004.肿瘤诊断
- 团体程序设计天梯赛-练习集-L3-004. 肿瘤诊断(三维bfs)