【题解】P3959 [NOIP 2017 提高组] 宝藏

题意

Link

给定一张无向带权图 \(G=(V,E,w)\),其中 \(|V|=n\),\(|E|=m\),边权 \(w(u,v)>0\)。

选择任意一个节点 \(r \in V\) 作为根,并选择一棵以 \(r\) 为根的有根生成树 \(T\)。对于 \(T\) 中的每个节点 \(v\),定义其深度 \(\text{dep}(v)\) 为从根 \(r\) 到 \(v\) 的路径上的节点数,即 \(\text{dep}(r)=1\),且若 \(u\) 是 \(v\) 的父节点,则 \(\text{dep}(v)=\text{dep}(u)+1\)。

生成树 \(T\) 的总代价定义为

\[\text{cost}(T) = \sum_{(u,v)\in T,\ u\text{是}v\text{的父节点}} w(u,v) \cdot \text{dep}(u). \]

求最小总代价:

\[\min \text{cost}(T). \]

思路

注意到 \(n\) 的范围很小,考虑状压 DP。设 \(dp_{i,S}\) 表示枚举到第 \(i\) 层,已经进入生成树的节点集合为 \(S\) 的最小代价。

设 \(cost_{S,T}\) 为从点集 \(T\) 扩展到点集 \(S\) 的最小代价(不考虑节点深度)。

可以得出状态转移方程:

\[dp_{i+1,S} = \min_{T \subseteq S} dp_{i,T}+i\times cost_{S,T} \]

然后预处理 \(cost\) 数组即可。

代码

#include <bits/stdc++.h>
using namespace std;

const int MAXN = 12;
const int INF = 0x3f3f3f3f;
int n, m, G[MAXN][MAXN];
int cost[1 << MAXN][1 << MAXN], dp[MAXN + 1][1 << MAXN];

signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    cin >> n >> m;
    memset(G, 0x3f, sizeof G);
    memset(dp, 0x3f, sizeof dp);
    for (int i = 1; i <= m; i++) {
        int u, v, w;
        cin >> u >> v >> w;
        G[v - 1][u - 1] = G[u - 1][v - 1] = min(G[u - 1][v - 1], w);
    }
    for (int s = 0; s < (1 << n); s++)
        for (int t = s; t; t = (t - 1) & s)
            for (int i = 0; i < n; i++)
                if (((s ^ t) >> i) & 1) {
                    int mn = INF;
                    for (int j = 0; j < n; j++)
                        if ((t >> j) & 1) mn = min(mn, G[i][j]);
                    if (mn == INF) {
                        cost[s][t] = INF;
                        break;
                    }
                    cost[s][t] += mn;
                }
    for (int i = 0; i < n; i++) dp[1][1 << i] = 0;
    for (int i = 1; i <= n; i++)
        for (int s = 0; s < (1 << n); s++)
            for (int t = s; t; t = (t - 1) & s)
                if (dp[i][t] != INF && cost[s][t] != INF) 
                    dp[i + 1][s] = min(dp[i + 1][s], dp[i][t] + i * cost[s][t]);
    int ans = INF;
    for (int i = 1; i <= n; i++) ans = min(ans, dp[i][(1 << n) - 1]);
    cout << ans << "\n";
    return 0;
}
posted @ 2026-09-25 11:56  C0nfidence  阅读(22)  评论(0)    收藏  举报