hdu3001(状态压缩dp)

题目链接: 点击打开链接
题目:
   After coding so many days,Mr Acmer wants to have a good rest.So travelling is the best choice!He has decided to visit n cities(he insists on seeing all the cities!And he does not mind which city being his start station because superman can bring him to any city at first but only once.), and of course there are m roads here,following a fee as usual.But Mr Acmer gets bored so easily that he doesn't want to visit a city more than twice!And he is so mean that he wants to minimize the total fee!He is lazy you see.So he turns to you for help.
分析:
   每天路径最多访问两次,可以使用三进制状态压缩,d[S][j] 表示在状态s下最后一个访问j时的最小花费;
   状态转移方程:d[S][k] = min(d[S][k], d[S-state[k]][j] + G[j][k]);    不过这里通过状态d[S][j] 转移到 ---> d[S+state[k]][k] = min(d[S+state[k]][k], d[S][j]+G[j][k]);

代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>

using namespace std;

const int maxn = 11;
int n, m;
int G[60000][maxn], state[11], vis[60000][maxn];
const int INF = 0x3f3f3f3f;
int d[60000][maxn];

void init(){
    state[0] = 1;
    for(int i = 1; i <= 10; ++i){
        state[i] = 3*state[i-1];
    }
    for(int i = 0; i < state[10]; ++i){
        int tmp = i;
        for(int j = 0; j < 10; ++j){
            vis[i][j] = tmp%3;
            tmp /= 3;
        }
    }
}
int deal(){
    memset(d, 0x3f, sizeof(d));
    for(int i = 0; i < n; ++i) d[state[i]][i] = 0;
    for(int i = 1; i < state[n]; ++i){
        for(int j = 0; j < n; ++j){
            if(d[i][j] == INF) continue;
            for(int k = 0; k < n; ++k){
                if(k==j) continue;
                if(vis[i][k] < 2 && G[j][k]!=INF){
                    d[i+state[k]][k] = min(d[i+state[k]][k], d[i][j]+G[j][k]);
                }
            }
        }
    }
    int ans = INF;
    for(int i = 1; i < state[n]; ++i){
        int ok = 1;
        for(int j = 0; j < n; ++j){
            if(vis[i][j] == 0){
                ok = 0; break;
            }
        }
        if(ok){
            for(int j = 0; j < n; ++j){
                ans = min(ans, d[i][j]);
            }
        }
    }
    return ans;
}

int main()
{
    init();
    while(~scanf("%d%d", &n, &m)){
        int u, v, w;
        memset(G, 0x3f, sizeof(G));
        for(int i = 0; i < m; ++i){
            scanf("%d%d%d", &u, &v, &w);
            u--, v--;
            if(w < G[u][v]){
                G[u][v] = G[v][u] = w;
            }
        }
        int ans = deal();
        if(ans == INF) ans = -1;
        printf("%d\n", ans);
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值