【BZOJ1042】硬幣購物(動態規劃,容斥原理)
題面
BZOJ
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
題解
真題真好啊。
先不考慮任何有關于硬幣個數的限制
設\(f[i]\)表示沒有任何限制的情況下,價格為\(n\)的方案數
直接做一個背包就行了。
現在加上限制來看,我們用總方案減去不合法。
總方案是\(f[n]\),不合法呢?
某一個硬幣如果不合法,那么它就要用\(d+1\)個
剩下的隨便選,也就是\(f[n-c*(d+1)]\)
這樣直接容斥計算即可。
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<set>
#include<map>
#include<vector>
#include<queue>
using namespace std;
#define ll long long
#define RG register
inline int read()
{RG int x=0,t=1;RG char ch=getchar();while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();if(ch=='-')t=-1,ch=getchar();while(ch<='9'&&ch>='0')x=x*10+ch-48,ch=getchar();return x*t;
}
int c[4],d[4],S;
ll f[111111];
int main()
{for(int i=0;i<4;++i)c[i]=read();f[0]=1;for(int k=0;k<4;++k)for(int j=c[k];j<=100000;++j)f[j]+=f[j-c[k]];int Q=read();while(Q--){for(int i=0;i<4;++i)d[i]=read();S=read();ll ss,ans=0;for(int i=0,tt;i<16;++i){ss=tt=0;for(int j=0;j<4;++j)if(i&(1<<j))++tt,ss+=(d[j]+1)*c[j];if(ss>S)continue;(tt&1)?ans-=f[S-ss]:ans+=f[S-ss];}printf("%lld\n",ans);}return 0;
}