1. 程式人生 > >BZOJ 1042: [HAOI2008]硬幣購物

BZOJ 1042: [HAOI2008]硬幣購物

limit sub rst com class long ring tput mat

1042: [HAOI2008]硬幣購物

Time Limit: 10 Sec Memory Limit: 162 MB

Submit: 2824 Solved: 1735

[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

題解

用容斥原理,方案數=1,2,3,4號硬幣非法的方案數-1,2,3號硬幣非法的方案數-1,2,4號硬幣非法的方案數…+1,2號硬幣非法的方案數+1,3號硬幣非法的方案數+…-1號硬幣非法的方案數-2號硬幣非法的方案數-…。

(1,2,3號硬幣非法的方案中4是否非法不管)

先用背包跑出0-S的方案數,然後0-(1<<4)枚舉所有非法情況,對於二進制上為1的硬幣,減去他(d[i]+1)*c[i]的價值,強制使它非法,然後剩余的價值隨便,直接加上f[s-(d[k]+1)*c[k]]。

代碼

.

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
#define LL long long
using namespace std;
const int S=100005;
int tot,s;
int c[10],d[10];
LL ans;
LL f[S];
int main(){
	scanf("%d%d%d%d%d",&c[1],&c[2],&c[3],&c[4],&tot);
	f[0]=1;
	for(int i=1;i<=4;i++){
		for(int j=c[i];j<=100000;j++){
			f[j]+=f[j-c[i]];
		}
	}
	int temp,cnt; 
	while(tot--){
		ans=0;
		scanf("%d%d%d%d%d",&d[1],&d[2],&d[3],&d[4],&s);
		for(int i=0;i<(1<<4);i++){
			cnt=0,temp=s;
			for(int j=1;j<=4;j++){
				if(i&(1<<(j-1))){
					temp-=(d[j]+1)*c[j];
					cnt++;
				}
			} 
			if(temp>=0){
				if(cnt&1)ans-=f[temp];
				else ans+=f[temp];
			}
		}
		printf("%lld\n",ans);
	}
	return 0;
}

BZOJ 1042: [HAOI2008]硬幣購物