Gym 100712G Heavy Coins(DFS)

来源:互联网 发布:什么是协同过滤算法? 编辑:程序博客网 时间:2024/04/30 12:44
/*********
Gym 100712G


Heavy Coins




Bahosain has a lot of coins in his pocket. These coins are really heavy, so he always tries to get rid of some of
the coins by using them when paying for the taxi.
Whenever Bahosain has to pay S pennies for the taxi driver, he tries to choose the maximum number of coin
pieces to pay. The driver will accept receiving more than S pennies only if he can’t remove one or more of the
given coins and still has S or more pennies.
For example, if Bahosain uses the coins of the following values: 2,7and5 to pay 11 pennies, the taxi driver
will not accept this because the coin of value 2 can be removed. On the other hand, when Bahosain uses coins
of 7 and 5to pay 11 pennies, the driver will accept it.
Note that the driver won’t give Bahosain any change back if he receives more than S pennies, and Bahosain
doesn’t care!




Input
The first line of input contains T (1 ≤ T ≤ 1001),the number of test cases.
The first line of each test case contains two integers: N (1 ≤ N ≤ 10)and S (1 ≤ S ≤ 1000),where N is the
number of coins in Bahosain’s pocket and S is the amount (in pennies) Bahosain has to pay for the taxi driver.
The next line contains N space-separated integers between 1 and 100 that represent the values (in pennies)
of the coins in Bahosain’s pocket.




Output
For each test case, print a single line with the maximum number of coins Bahosain can use to pay for the
driver.




Sample Input
2
5 9
4 1 3 5 4
7 37
7 5 8 8 5 10 4




Sample Output
3
6




Note
In the first test case, Bahosain can pay in any of the following ways: (1, 3, 5), (3, 4, 4) or (1, 4, 4).




题目大意是给你N个硬币,从这N个硬币中拿出若干个硬币使总和大于S,同时从你所选的这堆硬币拿走任何一个都会使总和小于S,也就是说取出若干个硬币且取出的这些硬币没有一个是多余的,求最多能拿出多少个硬币。
题目的N只有10,所以基本上怎么做都行,可以枚举所有的情况,最多也只有1000+种情况,也可以dfs搜索最大个数。但要注意dfs要从大到小,以防止出现拿走一个硬币时总和仍旧大于S的情况。


*********/
#include<cmath>#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;const int MAXN=12;int n,s,ans,coin[MAXN];void dfs(int loc,int sum,int num){    if(sum>=s)    {        ans=max(ans,num);        return ;    }    if(loc<0)        return ;    dfs(loc-1,sum,num);    dfs(loc-1,sum+coin[loc],num+1);}int main(){#ifndef ONLINE_JUDGE    freopen("in.txt","r",stdin);#endif // ONLINE_JUDGE    int tcase;    scanf("%d",&tcase);    while(tcase--)    {        ans=-1;        scanf("%d%d",&n,&s);        for(int i=0;i<n;i++)        {            scanf("%d",&coin[i]);        }        sort(coin,coin+n);        dfs(n-1,0,0);        printf("%d\n",ans);    }    return 0;}

1 0
原创粉丝点击