您的位置:首页 > 其它

1235 - Coin Change (IV)

2016-06-10 23:37 351 查看
1235 - Coin Change (IV)

PDF (English)StatisticsForum
Time Limit: 1 second(s)Memory Limit: 32 MB
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.

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

PROBLEM SETTER: JANE ALAM JAN
思路:折半枚举;
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: