1235 - Coin Change (IV)
2016-06-10 23:37
351 查看
1235 - Coin Change (IV)
Given n coins, values of them are A1, A2 ... An respectively, you have to find whether you can pay K using the coins. You can use any coin at most two times.
Each case starts with a line containing two integers n (1 ≤ n ≤ 18) and K (1 ≤ K ≤ 109). The next line contains n distinct integers denoting the values of the coins. These values will lie in the range [1, 107].
PROBLEM SETTER: JANE ALAM JAN
思路:折半枚举;
dfs+二分;
PDF (English) | Statistics | Forum |
Time Limit: 1 second(s) | Memory Limit: 32 MB |
Input
Input starts with an integer T (≤ 100), denoting the number of test cases.Each case starts with a line containing two integers n (1 ≤ n ≤ 18) and K (1 ≤ K ≤ 109). The next line contains n distinct integers denoting the values of the coins. These values will lie in the range [1, 107].
Output
For each case, print the case number and 'Yes' if you can pay K using the coins, or 'No' if it's not possible.Sample Input | Output for Sample Input |
3 2 5 1 2 2 10 1 2 3 10 1 3 5 | Case 1: Yes Case 2: No Case 3: Yes |
思路:折半枚举;
dfs+二分;
#include<stdio.h> #include<algorithm> #include<iostream> #include<string.h> #include<queue> #include<stdlib.h> #include<math.h> #include<stack> using namespace std; typedef long long LL; int ans[100]; int ak[100000]; int ac[100000]; int N,M; int id1[100]; int id2[100]; void dfs(int n,int m,int sum) { if(n==m) { ak =sum; N++; return ; } int i; for(i=0; i<=2; i++) { dfs(n+1,m,sum+id1 *i); } } void dfs1(int n,int m,int sum) { if(n==m) { ac[M]=sum; M++; return ; } int i; for(i=0; i<=2; i++) { dfs1(n+1,m,sum+id2 *i); } } int er(int n,int m,int ask) { int mid=(n+m)/2; if(n>m) return 0; if(ac[mid]==ask) { return 1; } else if(ac[mid]>ask) { return er(n,mid-1,ask); } else return er(mid+1,m,ask); } int main(void) { int i,j,k; scanf("%d",&k); int s; int n,m; for(s=1; s<=k; s++) { scanf("%d %d",&n,&m); for(i=0; i<n; i++) { scanf("%d",&ans[i]); } int cnt1=n/2; int cnt2=n-cnt1; for(i=0; i<cnt1; i++) { id1[i]=ans[i]; } for(i=cnt1; i<n; i++) { id2[i-cnt1]=ans[i]; } N=0; M=0; dfs(0,cnt1,0); dfs1(0,cnt2,0); sort(ac,ac+M); int flag=0; for(i=0; i<N; i++) { int ask=m-ak[i]; flag=er(0,M-1,ask); if(flag)break; } printf("Case %d: ",s); if(flag) printf("Yes\n"); else printf("No\n"); } return 0; }
相关文章推荐
- java 8 之Streams 解说
- POJ1947 Rebuilding Roads
- ubuntu下配置和使用ssh
- 滑动切换图片效果的实现
- Android 轻松实现仿淘宝地区选择
- CentOS7 修改网卡名称为eth0 & 在VMWare中添加多网卡配置
- 关于C#窗体中的三类坐标系
- poj 1970(搜索)
- 一个判断网络是否连接的工具类
- 爬虫之路——DAY1
- N的阶乘HDOJ1042
- vim去除或替换^M字符
- ASM ClassReader failed to parse class file - probably due to a new Java class file version that isn't supported yet
- Lex/Yacc 初识Lex
- hdu 1316 How Many Fibs?
- VMware虚拟机Mac OS X无法调整扩展硬盘大小的解决方案
- elementary os 软件及一些问题
- ButterKnife懒人库的使用 摆脱findviewbyid苦力
- TCP需要三次握手才能建立,而断开连接则需要四次握手
- elasticsearch搜索引擎技术