bzoj 1042: [HAOI2008]硬幣購物

因爲有了個數的限制,我們可以考慮容斥原理,首先對於整體求完全揹包,dp值代表值爲i的選擇方式。

那麼有一個超過限制的情況就是選擇這個面值的多了一個,那麼貢獻就是c[i]*(d[i]+1),所以應該減去dp[s-(c[i]*(d[i]+1))]。

利用容斥,應該減去奇數個超限制的,加上偶數個超限制的。

#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
int c[5],tot,d[5],s;
ll dp[100005],ans;
int main()
{
	for(int i=1;i<=4;i++)scanf("%d",&c[i]);
	dp[0]=1;scanf("%d",&tot);
	for(int i=1;i<=4;i++)
	{
		for(int j=c[i];j<=100002;j++)
		{
			dp[j]+=dp[j-c[i]];
		}
	}
	for(int i=1;i<=tot;i++)
	{
 		for(int j=1;j<=4;j++)scanf("%d",&d[j]);ans=0;
 		scanf("%d",&s);
 		for(int j=0;j<=15;j++)
 		{
 			int tt=s;int cnt=0;
 			for(int k=1;k<=4;k++)
		 	{
 				if((1<<(k-1))&j)
 				{
				 	tt-=c[k]*(d[k]+1);cnt++;
			 	}
 			}	
 			if(tt<0)continue;
 			if(cnt&1)ans-=dp[tt];
		 	else ans+=dp[tt];
		}
		printf("%lld\n",ans);	 
	}
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章