HDUOJ 5418 Victor and World -(状压DP)

博客提供了一个ACM题目的链接,链接为http://acm.hdu.edu.cn/showproblem.php?pid=5418 ,可通过该链接访问相关题目。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5418

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <map>
#include <algorithm>
#include <stack>
#include <cstring>
#include <vector>
using namespace std;

inline int read_int() { int a; scanf("%d", &a); return a; }

const int INF = 0x3fffffff;
#define N 16
int cost[N][N];
int dp[N][1 << N]; // dp[i][S] denotes: cur_pos is i, visited set is S

int main() {
    //std::ios::sync_with_stdio(false);
    //std::cin.tie(NULL);
    int T = read_int();
    while (T--)
    {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++)
                cost[i][j] = INF;
            for (int j = 0; j < (1 << N); j++)
                dp[i][j] = INF;
        }
        dp[0][1] = 0; // start

        const int n = read_int(), m = read_int();
        for (int i = 0; i < m; i++) {
            int u = read_int(), v = read_int(), w = read_int();
            cost[u - 1][v - 1] = min(w, cost[u - 1][v - 1]);
            cost[v - 1][u - 1] = min(w, cost[v - 1][u - 1]);
        }
        // floyd
        for (int k = 0; k < n; k++)
            for (int i = 0; i < n; i++)
                for (int j = 0; j < n; j++)
                    cost[i][j] = min(cost[i][j], cost[i][k] + cost[k][j]);

        // dp[j][S U {j}] = min_i(dp[i][S] + cost[i][j]);
        int S = 1;
        for (; S < (1 << n); S++) {
            for (int j = 0; j < n; j++) {
                // enumerate i in S, with path to j
                for (int i = 0; i < n; i++)
                    if (i != j && S&(1 << i) && cost[i][j] != INF)
                        dp[j][S | (1 << j)] = min(dp[j][S | (1 << j)],
                            dp[i][S] + cost[i][j]);
            }
        }
        printf("%d\n", dp[0][(1 << n) - 1]);
    }

    //system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值