BZOJ1042&&洛谷P1450 [HAOI2008]硬币购物

容斥原理+背包dp

每次做背包肯定会tle

那么我们可以重复利用以前的条件,先做完全背包,预处理,然后减去不合法状态

代码

//By AcerMo
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define lli long long int
using namespace std;
const int M=100009;
lli f[M]={1},ans;
int c[4],d[4],tot;
inline int read()
{
	int x=0;char ch=getchar();
	while (ch>'9'||ch<'0') ch=getchar();
	while (ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
	return x;
} 
signed main()
{
    for (int i=0;i<4;i++) c[i]=read();
    tot=read();
    for (int i=0;i<4;i++)
    for (int k=c[i];k<M;k++)
    f[k]+=f[k-c[i]];
    for (int i=1;i<=tot;i++)
	{
        for (int k=0;k<4;k++) d[k]=read();
        s=read();ans=f[s];
        for (int k=1;k<=15;k++)
		{
            int j=0,e=0,now=s;
            for (int tmp=k;tmp;tmp>>=1,j++)
                if(tmp&1) e^=1,now-=(d[j]+1)*c[j];
            if (now>=0) e?ans-=f[now]:ans+=f[now];
        }
        cout<<ans<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/ACerAndAKer/article/details/81304893