# 2019ICPC南昌邀请赛现场赛A题 - Attack(斯坦纳树)

## 分析：

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

const int N  = 50 + 5, M = 1000 + 5;
const int inf = 0x3f3f3f3f;

int n, m, w, tot, cnt, maxsta, head[N], vis[N];
int dp[N][1 << 10], ans[1 << 11];
string a, b;
queue<int> q;
map<string, int> maps;

struct node {
int v, w, next;
} e[M << 1];

void init() {
tot = cnt = 0;
memset(dp, inf, sizeof dp);
memset(vis, 0, sizeof vis);
while (!q.empty()) q.pop();
maps.clear();
}

void addedge(int u, int v, int w) {
e[++cnt].v = v;
e[cnt].w = w;
}

void spfa(int sta) {
while (!q.empty()) {
int u = q.front();
q.pop();
vis[u] = 0;
for (int i = head[u]; i; i = e[i].next) {
int v = e[i].v, val = e[i].w;
if (dp[v][sta] > dp[u][sta] + val) {
dp[v][sta] = dp[u][sta] + val;
if (!vis[v]) q.push(v), vis[v] = 1;
}
}
}
}

bool check(int sta) {
for (int i = 0; i < 8; i += 2) {
if ((sta >> i & 1) ^ (sta >> (i + 1) & 1)) return false;
}
return true;
}

int main() {
while (cin >> n >> m) {
init();
for (int i = 1; i <= n; i++) {
cin >> a;
maps[a] = ++tot;
}
for (int i = 1; i <= m; i++) {
cin >> a >> b >> w;
}
for (int i = 0; i < 8; i++) {
cin >> a;
dp[maps[a]][1 << i] = 0;
}
maxsta = 1 << 8;
for (int sta = 0; sta < maxsta; sta++) {
while(!q.empty()) q.pop();
for (int i = 1; i <= n; i++) {
for (int s = sta; s; s = (s - 1) & sta) {
if(dp[i][sta] > dp[i][s] + dp[i][sta ^ s])
dp[i][sta] = dp[i][s] + dp[i][sta ^ s];
}
if(dp[i][sta] < inf) q.push(i), vis[i] = 1;
}
spfa(sta);
}
memset(ans, inf, sizeof ans);
for (int s = 0; s < maxsta; s++) {
if (!check(s)) continue;
for (int i = 1; i <= n; i++) {
ans[s] = min(ans[s], dp[i][s]);
}
}
for (int s = 0; s < maxsta; s++) {
if (!check(s)) continue;
for (int p = (s - 1) & s; p; p = (p - 1) & s)
ans[s] = min(ans[s], ans[p] + ans[s ^ p]);
}
cout << ans[maxsta - 1] << '\n';
}
return 0;
}
``````

2019ICPC南昌邀请赛现场赛A题 - Attack(斯坦纳树)

(0)
(0)