BZOJ1042(HAOI2008)[硬币购物]--背包+容斥

【链接】
bzoj1042

【解题报告】

初看此题像是背包,但是价值好大啊。。。

所以就看题解,发现好像是容斥。

模型如下:

硬币数不受限制的方案 − 第一枚硬币超过限制其他硬币不受限制的方案 − 第二枚硬币超过限制其他硬币不受限制的方案 ⋯ + 第一枚第二枚硬币超过限制其他硬币不受限制的方案 ⋯

首先用背包求出 f[i] 表示价值为 i 硬币不受限制的方案数。

对于每种硬币,因为该硬币至多为di个,那么超出限制的硬币的方案数为 f[s(di+1)si]

知道如何求解方案数就可以秒了此题了。

#include<cstdio>
#include<cstring>
#define LL long long
using namespace std;
const int maxn=100005;
int n,c[4],d[4];
LL ans,f[maxn];
inline char nc()
{
    static char buf[100000],*l,*r;
    if (l==r) r=(l=buf)+fread(buf,1,100000,stdin);
    if (l==r) return EOF; return *l++;
}
inline int Read()
{
    int res=0,f=1; char ch=nc(),cc=ch;
    while (ch<'0'||ch>'9') cc=ch,ch=nc();
    if (cc=='-') f=-1;
    while (ch>='0'&&ch<='9') res=res*10+ch-48,ch=nc();
    return res*f;
}
void Dfs(int x,int k,int sum)
{
    if (sum<0) return;
    if (x>3)
    {
        if (k&1) ans-=f[sum]; else ans+=f[sum];
        return;
    }
    Dfs(x+1,k,sum);
    Dfs(x+1,k+1,sum-(d[x]+1)*c[x]);
}
int main()
{
    freopen("1042.in","r",stdin);
    freopen("1042.out","w",stdout);
    for (int i=0; i<4; i++) c[i]=Read(); n=Read();
    memset(f,0,sizeof(f)); f[0]=1;
    for (int i=0; i<4; i++)
     for (int j=c[i]; j<=100000; j++)
      f[j]+=f[j-c[i]];
    for (int i=1; i<=n; i++)
     {
        for (int j=0; j<4; j++) d[j]=Read();
        int x=Read(); ans=0; Dfs(0,0,x);
        printf("%lld\n",ans);
     }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值