G. Heavy Coins(二进制枚举)

G. 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
​​
,

7
​​
and

5
​​
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

5
​​
to 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  Sample Output
2
5 9
4 1 3 5 4
7 37
7 5 8 8 5 10 4
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)


题意:Bahosain 有很多硬币,它将硬币用来付车费。他需要付给出租车司机的费用为s,只有当所给的硬币价值大于等于s且里面没有多余的硬币(即减少里面的任意一个硬币,总价值都会小于s)时司机才会收取。求Bahosain最多能给司机的硬币数量。

输入:第一行为测试组数t表示测试的数据有t组

          第二行为硬币数量n(n<10),和费用s

   接下来n个数,表示每个硬币的价值

输出:对于每一组测试数据,输出最大值。

解法:用二进制枚举每种情况,然后判断每种情况满足要求的硬币数量。然后取最大值即可。那么我们怎么判断当前状况下没有多余的硬币呢?我们想一下,如果当我们减去所加的最小的一枚硬币时,总值小于s则这种组合就肯定没有多余的硬币。反之则有。

关于二进制枚举:一串二进制数是由0和1组成,我们即可以用0表示未被选中,1表示为被选中.则我对于n个选择,我们可以用0->1<<n来来表示这n个数所有的状态。

AC:
#include <iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int a[100000],s,n,t;
int main()
{
    scanf("%d",&t);
    while(t--)
    {
        int ans=0;
        scanf("%d%d",&n,&s);
        for(int i=0;i<n;i++)
        {
            scanf("%d",&a[i]);
        }
        int ma=1<<n;
        for(int i=0;i<ma;i++)
        {
            int temp,cnt,f,vis;
            int minx=1000000;
            temp=f=cnt=0;
            for(int j=0;j<n;j++)
            {
                if(i&(1<<j))
                {
                         temp+=a[j];
                         cnt++;
                         minx=min(minx,a[j]);


                }
            }
            if(temp-minx<s&&temp>=s) ans=max(ans,cnt);
        }
        printf("%d\n",ans);
    }
    return 0;
}

​​

你可能感兴趣的:(二进制,ACM,codeforces)