HDU 3001 Travelling 三进制状压DP

题意:一个图,每个点都要遍历到,且每个点最多经过两次。

思路:用三进制表示状态,第i位上的数(0,1,2)代表第i+1个点经过的次数。

设dp[S][v]为状态S下,到达S状态中的点v的最小花费。

S0 为 状态S中第v-1位的值-1后的结果 ,其他位上的值不变。

那么状态转移方程:dp[S][v] = min(dp[S0][u] + maps[u][v],dp[S][v]).(u在状态S0中)


我的代码:

#include<cstdio>
#include<cstring>
#include<iostream>

#define min(a,b) (a < b ? a : b)
using namespace std;
typedef int LL;
const LL inf = 0x3f3f3f3f;
const LL maxn = 11;

LL n,m;
LL maps[maxn][maxn];
LL dp[177147][11];

LL mod_pow(LL n){
    LL res =  1,a = 3;
    while(n){
        if(n & 1) res *= a;
        a *= a;
        n >>= 1;
    }
    return res;
}

void init(){
    for(int i=0;i<=n;i++){
        for(int j=0;j<=n;j++){
            if(i == 0 || j == 0 || i == j) maps[i][j] = 0;
            else maps[i][j] = inf;
        }
    }
}

bool check(LL S){
    LL tmp;
    for(LL i = 0;i < n; i++){
        tmp = mod_pow(i);
        if((S / tmp) % 3 == 0) return false;
    }
    return true;
}

void solve(){
    LL S,S0,v,u,tmp;
    LL Ed = mod_pow(n);
    for(S = 0;S < Ed; S++){
        for(v = 1; v <= n; v++){
            dp[S][v] = inf;
            tmp = mod_pow(v - 1);
            if((S / tmp) % 3 == 0) continue;
            S0 = S - tmp;
            if(S0 == 0) dp[S][v] = 0;
            else{
                for(u = 1;u <= n; u++){
                    tmp = mod_pow(u - 1);
                    if(v == u || (S0 / tmp) % 3 == 0) continue;
                    dp[S][v] = min(dp[S][v],dp[S0][u] + maps[u][v]);
                }
            }
        }
    }
    LL res = inf;
    for(S = 0;S < Ed; S++){
        if(check(S)){
            for(v = 1; v <= n ; v++)
                res = min(res,dp[S][v]);
        }
    }
    if(res == inf) printf("-1\n");
    else  printf("%d\n",res);
}

int main(){
    while(~scanf("%d%d",&n,&m)){
        init();
        LL a,b,c;
        while(m--){
            scanf("%d%d%d",&a,&b,&c);
            maps[a][b] = maps[b][a] = min(maps[a][b],c);
        }
        solve();
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值