zoukankan      html  css  js  c++  java
  • 【BZOJ-1042】硬币购物 容斥原理 + 完全背包

    1042: [HAOI2008]硬币购物

    Time Limit: 10 Sec  Memory Limit: 162 MB
    Submit: 1811  Solved: 1057
    [Submit][Status][Discuss]

    Description

      硬币购物一共有4种硬币。面值分别为c1,c2,c3,c4。某人去商店买东西,去了tot次。每次带di枚ci硬币,买s
    i的价值的东西。请问每次有多少种付款方法。

    Input

      第一行 c1,c2,c3,c4,tot 下面tot行 d1,d2,d3,d4,s,其中di,s<=100000,tot<=1000

    Output

      每次的方法数

    Sample Input

    1 2 5 10 2
    3 2 3 1 10
    1000 2 2 2 900

    Sample Output

    4
    27

    HINT

    Source

    Solution

    容斥这东西,说是会了,但还不是很会用..

    最暴力的就是跑完全背包啊,很明显不行,所以考虑容斥

    先用完全背包做出方案数,然后容斥一下,也就是减去不满足的方案  

    最终方案=总方案(无限制的方案)-1种硬币超限方案+2种硬币超限方案-3种硬币超限方案+4种硬币超限方案

    对于一个数,限制条件为$D[i]$那么超限至少为$D[i]+1$,所以这种方案数为$f[S-(D[i]+1)*C[i]]$,其余同理

    Code

    #include<iostream>
    #include<cstdio>
    #include<algorithm>
    #include<cstring>
    #include<cmath>
    using namespace std;
    int read()
    {
        int x=0,f=1; char ch=getchar();
        while (ch<'0' || ch>'9') {if (ch=='-') f=-1; ch=getchar();}
        while (ch>='0' && ch<='9') {x=x*10+ch-'0'; ch=getchar();}
        return x*f;
    }
    #define maxn 100010
    int C[5],tot,D[5],S; long long f[maxn],ans;
    void Work(int s,int dep,int x,int t)
    {
        if (dep==5) {if (t%2) ans-=f[s]; else ans+=f[s]; return;}
        Work(s,dep+1,x+1,t);
        if (C[x]*(D[x]+1)<=s) Work(s-C[x]*(D[x]+1),dep+1,x+1,t+1);
    }
    int main()
    {
        for (int i=1; i<=4; i++) C[i]=read(); tot=read();
        f[0]=1;
        for (int i=1; i<=4; i++)
            for (int j=C[i]; j<=maxn; j++)
                f[j]+=f[j-C[i]];
        for (int i=1; i<=tot; i++)
            {
                for (int j=1; j<=4; j++) D[j]=read(); S=read();
                ans=0; Work(S,1,1,0); printf("%lld
    ",ans);
            }
        return 0;
    }
  • 相关阅读:
    1046 Shortest Distance (20 分)(模拟)
    1004. Counting Leaves (30)PAT甲级真题(bfs,dfs,树的遍历,层序遍历)
    1041 Be Unique (20 分)(hash散列)
    1036 Boys vs Girls (25 分)(查找元素)
    1035 Password (20 分)(字符串处理)
    1044 Shopping in Mars (25 分)(二分查找)
    onenote使用小Tip总结^_^(不断更新中...)
    1048 Find Coins (25 分)(hash)
    三个故事
    领导者的举止
  • 原文地址:https://www.cnblogs.com/DaD3zZ-Beyonder/p/5472822.html
Copyright © 2011-2022 走看看