传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=4006
【题解】
即求斯坦纳森林……
然后我们发现可以先把所有点全当做重要点做一遍steiner tree。
然后我们可以求出联通状态为S的时候的最小花费
然后子集更新即可。(再一遍dp)
注意只需要做一遍就够了!!!
而且斯坦纳树板子要用对(大概快4倍左右)
# include <queue> # include <stdio.h> # include <string.h> # include <algorithm> // # include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef unsigned long long ull; const int M = 5e5 + 10, STATUS = 1027, N = 1000 + 10; const int mod = 1e9+7; # define RG register # define ST static int n, m, p; int head[M], nxt[M], to[M], tot, w[M]; inline void add(int u, int v, int _w) { ++tot; nxt[tot] = head[u]; head[u] = tot; to[tot] = v; w[tot] = _w; } inline void adde(int u, int v, int _w) { add(u, v, _w); add(v, u, _w); } int f[N][STATUS], st[STATUS]; bool vis[N]; queue <int> q; int cp[N], cx[N]; int s[STATUS], dp[STATUS]; int cnt[23], all[23]; inline bool ok(int status) { memset(cnt, 0, sizeof cnt); for (int i=1; i<=p; ++i) if(status & (1<<(i-1))) cnt[cp[i]] ++; for (int i=1; i<=p; ++i) if(cnt[i] && cnt[i] != all[i]) return 0; return 1; } inline void spfa(int status) { for (int i=1; i<=n; ++i) vis[i] = 1, q.push(i); while(!q.empty()) { int top = q.front(); q.pop(); vis[top] = 0; for (int i=head[top]; i; i=nxt[i]) { if(f[to[i]][status] > f[top][status] + w[i]) { f[to[i]][status] = f[top][status] + w[i]; if(!vis[to[i]]) { vis[to[i]] = 1; q.push(to[i]); } } } } } int main() { scanf("%d%d%d", &n, &m, &p); for (int i=1, u, v, _w; i<=m; ++i) { scanf("%d%d%d", &u, &v, &_w); adde(u, v, _w); } for (int i=1; i<=p; ++i) scanf("%d%d", &cp[i], &cx[i]), all[cp[i]] ++; int status_size = (1<<p)-1; for (int i=1; i<=n; ++i) for (int j=1; j<=status_size; ++j) f[i][j] = 1e9; for (int i=1; i<=p; ++i) f[cx[i]][1<<(i-1)] = 0, st[cx[i]] = (1<<(i-1)); for (int status = 0; status <= status_size; ++status) { for (int i=1; i<=n; ++i) for (int sub = status-1 & status; sub; sub = sub-1 & status) f[i][status] = min(f[i][status], f[i][sub] + f[i][status^sub]); spfa(status); } for (int status = 0; status <= status_size; ++status) { s[status] = 1e9; for (int i=1; i<=n; ++i) s[status] = min(s[status], f[i][status]); // printf("%d ", s[status]); } for (int status = 0; status <= status_size; ++status) { dp[status] = s[status]; if(ok(status)) for (int sub = status-1 & status; sub; sub = sub-1 & status) if(ok(sub)) dp[status] = min(dp[status], dp[sub] + dp[status^sub]); } printf("%d ", dp[status_size]); return 0; }