题解 P1450 【[HAOI2008]硬币购物】

· · 题解

HH_Halo

思路分析

上去就跑了个暴力,结果直接 T 到飞起,貌似全是大数据

所以如果要跑背包的话,那么时间限制是只允许我们跑一遍的,这时候的答案就需要换一个巧妙的方法来得到

然而不同的情况会有交集,这时候就要用到容斥原理:

Code

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define N 100010
#define R register
#define int long long
using namespace std;
inline int read(){
    int x = 0,f = 1;
    char ch = getchar();
    while(ch>'9'||ch<'0'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
    return x*f;
}
int n,s,c[10],d[10],f[N];
void pre(){
    f[0] = 1;
    for(R int i = 1;i <= 4;i++){
        for(R int j = c[i];j <= N;j++){
            f[j] += f[j-c[i]];
        }
    }
}
void solve(){
    int ans=f[s];
    for(R int i=1;i<=15;i++){//状压枚举集合内元素
    int tot=0,cnt=0;
    for(R int j=0;j<4;j++){
        if(i&(1<<j)){//在集合内则强制让其超过个数限制
            cnt++;//记录集合数
        tot+=c[j+1]*(d[j+1]+1);
        }
    }
    int flag = (cnt%2) ? -1 : 1;
    if(tot<=s) ans+=flag*f[s-tot];
    }
    printf("%lld\n",ans);
}
signed main(){
    c[1] = read(),c[2] = read(),c[3] = read(),c[4] = read();
    n = read();
    pre();
    for(R int i = 1;i <= n;i++){
            for(R int i=1;i<=4;i++) d[i]=read();
            s=read();
        solve();
    }
    return 0;
}