Sol-Dp-硬币购物

Solution of HAOI2008-硬币购物

容斥原理+Dp好题,值得一做(DaLao饶了我吧我马上就去做难题了这种题DaLao一眼秒QAQ)

首先跑O(NM)的完全背包 , N很小珂以忽略

然后容斥原理 , 珂以打表也珂以用搜索实现

demo:

#include<bits/stdc++.h>
using namespace std;
int c[5],d[5];
long long dp[100010];
long long ans; 
int T,n,s ;
void dfs(int now,int sum,int flag){
    if(sum<0) return;
    if(now>4) {ans+=dp[sum]*flag;return;}
    dfs(now+1,sum,flag);
    dfs(now+1,sum-(d[now]+1)*c[now],-flag);
}
int main(){
    scanf("%d%d%d%d%d",&c[1],&c[2],&c[3],&c[4],&T);
    dp[0]=1;
    for(int i=1;i<=4;++i)
        for(int j=c[i];j<=100001;j++)
            dp[j]+=dp[j-c[i]];
    while(T--){
        ans=0;
        scanf("%d%d%d%d%d",&d[1],&d[2],&d[3],&d[4],&s);
        dfs(1,s,1);
        printf("%lld\n",ans);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42000775/article/details/83514327