2018.10.18每天认真做一道数学(数论)题之BZOJ 1042 [HAOI2008] 硬币购物【背包DP】【容斥原理】

对于每个询问,答案显然为:S所有超过数量限制的方案数- c [ 1 ] c[1] 超过限制的方案数-硬币 c [ 2 ] c[2] 超过限制的方案数-硬币 c [ 3 ] c[3] 超过限制的方案数-硬币 c [ 4 ] c[4] 超过限制的方案数+硬币 c [ 1 ] , c [ 2 ] c[1],c[2] 超过限制的方案数+…+硬币 c [ 1 ] , c [ 2 ] , c [ 3 ] , c [ 4 ] c[1],c[2],c[3],c[4] 均超过限制的方案数。

所以我们就先最开始无视个数做完全背包,然后容斥原理去掉不合法的方案即可:

#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define db double
#define sg string
#define ll long long
#define rep(i,x,y) for(ll i=(x);i<=(y);i++)
#define red(i,x,y) for(ll i=(x);i>=(y);i--)
using namespace std;

const ll N=1e5+5;
const ll Inf=1e18;

ll v,ans,tot;
ll c[5],d[5],f[N];

inline ll read() {
    ll x=0;char ch=getchar();bool f=0;
    while(ch>'9'||ch<'0'){if(ch=='-')f=1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
    return f?-x:x;
}

void dfs(ll cur,ll cnt,ll sum) {
	if(sum<0) return ;
	
	if(cur==5) {
		if(cnt&1) ans-=f[sum];
		else ans+=f[sum];return ;
	}
	
	dfs(cur+1,cnt,sum);
	dfs(cur+1,cnt+1,sum-(d[cur]+1)*c[cur]);
}

int main() {
	rep(i,1,4) c[i]=read();
	
	f[0]=1;
	
	rep(i,1,4) rep(j,c[i],N-5) f[j]+=f[j-c[i]];
	
	tot=read();
	
	while(tot--) {
		rep(i,1,4) d[i]=read();
		
		ans=0;v=read();
		
		dfs(1,0,v);
		
		printf("%lld\n",ans);
	}

	return 0;
}

猜你喜欢

转载自blog.csdn.net/yanzhenhuai/article/details/83146830
今日推荐