zoukankan      html  css  js  c++  java
  • Coin Change (IV) (dfs)

    Time Limit: 1000MS   Memory Limit: 32768KB   64bit IO Format: %lld & %llu

    []   [Go Back]   [Status]  

    Description

    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

    3

    2 5

    1 2

    2 10

    1 2

    3 10

    1 3 5

    Sample Output

    Case 1: Yes

    Case 2: No

    Case 3: Yes

     1 #include <iostream>
     2 #include <stdio.h>
     3 #include <math.h>
     4 #include <string.h>
     5 #include <algorithm>
     6 using namespace std;
     7 int a[50];
     8 bool dfs(int n,int re,int sh)
     9 {
    10     if(re==0||sh==re)return true;
    11     if(n==0||re<0||re>sh)return false;
    12     if(dfs(n-1,re,sh-2*a[n]))return true;
    13     if(dfs(n-1,re-a[n],sh-2*a[n]))return true;
    14     if(dfs(n-1,re-2*a[n],sh-2*a[n]))return true;
    15     return false;
    16 }
    17 int main()
    18 {
    19     int t,n,k,i,j,sum;
    20     scanf("%d",&t);
    21     for(i=1; i<=t; i++)
    22     {
    23         sum=0;
    24         scanf("%d%d",&n,&k);
    25         for(j=1; j<=n; j++)scanf("%d",&a[j]);
    26         sort(a+1,a+n+1);
    27         for(j=1; j<=n; j++)sum+=a[j]<<1;
    28         cout<<"Case "<<i<<": ";
    29         if(dfs(n,k,sum))
    30             cout<<"Yes"<<endl;
    31         else cout<<"No"<<endl;
    32     }
    33 }
    View Code
  • 相关阅读:
    常量池 栈 堆
    函数的调用
    字符、数组
    整理
    JavaScript深入之——原型与原型链
    虚拟机(VMware)中文破解版,及创建虚拟机
    小程序之mpvue使用
    报错整理及解决办法
    js 关于时间方面的通用函数
    iview Cascader级联选择省市区问题
  • 原文地址:https://www.cnblogs.com/ERKE/p/3582222.html
Copyright © 2011-2022 走看看