• BZOJ 1042 硬币购物(背包DP+容斥原理)


    可以看出这是个多重背包,运用单调队列优化可以使每次询问达到O(s).这样总复杂度为O(s*tot). 会TLE。

    因为改题的特殊性,每个硬币的币值是不变的,变的只是每次询问的硬币个数。

    我们不妨不考虑硬币个数的限制。这样可以用完全背包在O(s)的时间求出dp[]数组,表示没有限制的种数。

    现在加入每个硬币的限制后,由于容斥原理,答案就是没有限制的种数-第一个硬币的限制种数-第二个硬币限制种数......

    如果加入第一个硬币的限制后怎么求呢。就相当于你先把第一个硬币用到刚超过限制,剩下的随便怎么选。此时的种数就是dp[s-(d[1]+1)*c[1]],d[1]表示第一种硬币的限制数,

    c[1]表示第一种硬币的币值。 剩下的同理。

    之后所以的询问都可以在O(1)的时间求出。

    因此总复杂度为O(s+tot).

    # include <cstdio>
    # include <cstring>
    # include <cstdlib>
    # include <iostream>
    # include <vector>
    # include <queue>
    # include <stack>
    # include <map>
    # include <set>
    # include <cmath>
    # include <algorithm>
    using namespace std;
    # define lowbit(x) ((x)&(-x))
    # define pi acos(-1.0)
    # define eps 1e-9
    # define MOD 12345678
    # define INF 1000000000
    # define mem(a,b) memset(a,b,sizeof(a))
    # define FOR(i,a,n) for(int i=a; i<=n; ++i)
    # define FO(i,a,n) for(int i=a; i<n; ++i)
    # define bug puts("H");
    # define lch p<<1,l,mid
    # define rch p<<1|1,mid+1,r
    # define mp make_pair
    # define pb push_back
    typedef pair<int,int> PII;
    typedef vector<int> VI;
    # pragma comment(linker, "/STACK:1024000000,1024000000")
    typedef long long LL;
    int Scan() {
        int res=0, flag=0;
        char ch;
        if((ch=getchar())=='-') flag=1;
        else if(ch>='0'&&ch<='9') res=ch-'0';
        while((ch=getchar())>='0'&&ch<='9')  res=res*10+(ch-'0');
        return flag?-res:res;
    }
    void Out(int a) {
        if(a<0) {putchar('-'); a=-a;}
        if(a>=10) Out(a/10);
        putchar(a%10+'0');
    }
    const int N=100005;
    //Code begin...
    
    LL dp[N];
    int c[5], d[5];
    
    void init()
    {
        dp[0]=1;
        FO(i,0,4) FO(j,c[i],N) dp[j]=dp[j]+dp[j-c[i]];
    }
    int main ()
    {
        scanf("%d%d%d%d%d",c,c+1,c+2,c+3,c+4);
        init();
        while (c[4]--) {
            scanf("%d%d%d%d%d",d,d+1,d+2,d+3,d+4);
            LL ans=dp[d[4]];
            FO(i,1,16) {
                int tot=0, tmp=0;
                FO(j,0,4) if (i&(1<<j)) ++tot, tmp+=(d[j]+1)*c[j];
                if (tmp<=d[4]) ans+=((tot&1)?-dp[d[4]-tmp]:dp[d[4]-tmp]);
            }
            printf("%lld
    ",ans);
        }
        return 0;
    }
    View Code
  • 相关阅读:
    Python ES操作
    SVN总结
    MongoDB问题总结
    MySQL
    PyQt小工具
    Python logging模块
    shell脚本
    cmd命令
    eclipse java 项目打包
    Robot Framework:failed: Data source does not exist.错误
  • 原文地址:https://www.cnblogs.com/lishiyao/p/6506266.html
Copyright © 2020-2023  润新知