CSUST 2007 我爱吃烧烤 题解(状压dp)

题目链接

题目大意

在这里插入图片描述
总共 n 家烧烤店,有 m 家特殊烧烤店,从 i 到 j 号烧烤点有 mp [ i ] [ j ] 种方案,消耗一点体力值,问消耗 q 点体力值且至少经过 k 家特殊烧烤店的方案数。

题目思路

看到题目好吓人。。。但是要仔细观察题目所给条件,你就会发现这么小的数据不肯定是状压嘛。然后定义状态dp记录走过的特殊店,现在所在位置,还有体力值。空间复杂度可以接受的,然后在转移的时候 ,枚举下一个要到达的地点,还要注意一个关键点,我找了好久的bug,你仔细看转移方程,你会发现要把体力在最外层循环,每次消耗一个体力都要跑完整个图,所以dp转移方程的内外层循环一定要根据dp转移方程来看

代码

#include<set>
#include<map>
#include<queue>
#include<stack>
#include<cmath>
#include<cstdio>
#include<vector>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<unordered_map>
#define fi first
#define se second
#define debug printf(" I am here\n");
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
const int maxn=50+5,inf=0x3f3f3f3f,mod=20190802;
const double eps=1e-10;
int n,m,k,q,mp[maxn][maxn],vis[maxn];
ll dp[1<<(11)][maxn][maxn];//1,2,3维分别是状压,现在地点,体力
int cal(int x){
    int cnt=0;
    while(x){
        cnt+=((x&1)!=0);
        x=x>>1;
    }
    return cnt;
}
signed main(){
    scanf("%d%d%d%d",&n,&m,&k,&q);
    for(int i=1,x;i<=m;i++){
        scanf("%d",&x);
        vis[x]=i;//特殊标记为i,为了状压
    }
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            scanf("%d",&mp[i][j]);
        }
    }
    dp[0][1][0]=1;//初始化
    for(int str=0;str<q;str++){//strength
        //注意转移方程,体力要在最后一维!!!!
        for(int sta=0;sta<(1<<m);sta++){
            for(int now=1;now<=n;now++){//现在的地点
                if(!dp[sta][now][str]) continue;
                for(int nxt=1;nxt<=n;nxt++){
                    if(!mp[now][nxt]) continue;
                    if(vis[nxt]){
                        dp[sta|(1<<(vis[nxt]-1))][nxt][str+1]=(dp[sta|(1<<(vis[nxt]-1))][nxt][str+1]+dp[sta][now][str]*mp[now][nxt])%mod;
                    }else{
                        dp[sta][nxt][str+1]=(dp[sta][nxt][str+1]+dp[sta][now][str]*mp[now][nxt])%mod;
                    }
                }
            }
        }
    }
    ll ans=0;
    for(int sta=0;sta<(1<<m);sta++){
        if(cal(sta)<k) continue;//不满足
        for(int now=1;now<=n;now++){
            ans=(ans+dp[sta][now][q])%mod;
        }
    }
    printf("%lld\n",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_46209312/article/details/107701918