poj Coins (bitset做法)

题目传送门

Description

People in Silverland use coins.They have coins of value A1,A2,A3...An Silverland dollar.One day Tony opened his money-box and found there were some coins.He decided to buy a very nice watch in a nearby shop. He wanted to pay the exact price(without change) and he known the price would not more than m.But he didn't know the exact price of the watch.
You are to write a program which reads n,m,A1,A2,A3...An and C1,C2,C3...Cn corresponding to the number of Tony's coins of value A1,A2,A3...An then calculate how many prices(form 1 to m) Tony can pay use these coins.


Input

The input contains several test cases. The first line of each test case contains two integers n(1<=n<=100),m(m<=100000).The second line contains 2n integers, denoting A1,A2,A3...An,C1,C2,C3...Cn (1<=Ai<=100000,1<=Ci<=1000). The last test case is followed by two zeros.

Output

For each test case output the answer on a single line.

Sample Input
3 10
1 2 4 2 1 1
2 5
1 4 2 1
0 0


Sample Output
8
4

题目大意:有n个不同面值的硬币,告诉你每种硬币的面值,然后告诉你每种硬币的数量,问你,在1~m的面值范围内,你能凑出多少种面值种类。

第一行输入,n,m分别表示n种硬币,m表示总钱数。
第二行输入n个硬币的价值,和n个硬币的数量。

做法:可以用背包求解,这里就不多说,这里只介绍bitset做法。

#include<stdio.h>
#include<bitset>
#include<algorithm>
using namespace std;
int main()
{
    int n,m,c,i,a[101];
    while(scanf("%d%d",&n,&m),n||m)
    {
        for(i=1;i<=n;i++) scanf("%d",&a[i]);
        bitset<100002> ans(0);//初始化时全为0
        ans.set(0);//将第0位设为1
        for(i=1;i<=n;i++)
        {
            scanf("%d",&c);
            int k=1;
            while(k<=c)
            {
                ans|=ans<<(k*a[i]);//将原来ans里面所有的1往左移k*a[i]位然后或上原来的,状态更新完毕
                c-=k;
                k<<=1;
            }
            if(c>0) ans|=ans<<(c*a[i]);//如果还有剩下的,那么也要考虑进去,不然会错
        }
        int sum=0;
        for(i=1;i<=m;i++)
            sum+=ans[i];//sum储存ans里面为1的个数
        printf("%d\n",sum);
    }
    return 0;
}


你可能感兴趣的:(bitset用法)