【HDU4085】Peach Blossom Spring【斯坦纳树】【状态压缩】

http://acm.hdu.edu.cn/showproblem.php?pid=4085

裸的斯坦纳树。

参考了凯爷blog:http://blog.csdn.net/lethelody/article/details/44808507


/* Footprints In The Blood Soaked Snow */
#include <cstdio>
#include <algorithm>
#include <queue>
#include <utility>

using namespace std;

typedef pair<int, int> pii;

const int maxn = 55, maxm = 1005, maxs = 1 << 12, inf = 0x3f3f3f3f;

int n, m, k, head[maxn], cnt, dp[maxs], f[maxn][maxs], s[maxn], S;
bool vis[maxn][maxs];

queue<pii> q;

struct _edge {
	int v, w, next;
} g[maxm << 1];

inline int iread() {
	int f = 1, x = 0; char ch = getchar();
	for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
	for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
	return f * x;
}

inline void add(int u, int v, int w) {
	g[cnt] = (_edge){v, w, head[u]};
	head[u] = cnt++;
}

inline void spfa() {
	while(!q.empty()) {
		pii c = q.front(); q.pop();
		int u = c.first, x = c.second;
		for(int i = head[u]; ~i; i = g[i].next) {
			int v = g[i].v;
			if(f[v][x | s[v]] > f[u][x] + g[i].w) {
				f[v][x | s[v]] = f[u][x] + g[i].w;
				if(!(x & s[v]) && !vis[v][x]) q.push(pii(v, x)), vis[v][x] = 1;
			}
		}
		vis[u][x] = 0;
	}
}

inline bool check(int x) {
	int ans = 0;
	for(int i = 0; x; x >>= 1, i++) if(x & 1) ans += i < k ? 1 : -1;
	return ans == 0;
}

int main() {
	for(int T = iread(); T; T--) {
		for(int i = 0; i < maxn; i++) head[i] = -1, s[i] = 0; cnt = 0;
		for(int i = 0; i < maxs; i++) dp[i] = inf, s[i] = 0;
		for(int i = 0; i < maxn; i++) for(int j = 0; j < maxs; j++) f[i][j] = inf, vis[i][j] = 0;

		n = iread(); m = iread(); k = iread(); S = 1 << (k << 1);
		for(int i = 1; i <= m; i++) {
			int u = iread(), v = iread(), w = iread();
			add(u, v, w); add(v, u, w);
		}
		for(int i = 1; i <= k; i++) {
			s[i] = 1 << (i - 1); f[i][s[i]] = 0;
			s[n - i + 1] = 1 << (k + i - 1); f[n - i + 1][s[n - i + 1]] = 0;
		}

		for(int x = 0; x < S; x++) for(int i = 1; i <= n; i++) {
			for(int j = (x - 1) & x; j; j = (j - 1) & x)
				f[i][x] = min(f[i][x], f[i][j | s[i]] + f[i][(x ^ j) | s[i]]);
			if(f[i][x] != inf) q.push(pii(i, x)), vis[i][x] = 1;
			spfa();
		}

		for(int x = 0; x < S; x++) for(int i = 1; i <= n; i++) dp[x] = min(dp[x], f[i][x]);

		for(int x = 0; x < S; x++) if(check(x)) for(int j = (x - 1) & x; j; j = (j - 1) & x) if(check(j))
			dp[x] = min(dp[x], dp[j] + dp[x ^ j]);

		if(dp[S - 1] != inf) printf("%d\n", dp[S - 1]);
		else printf("No solution\n");
	}
	return 0;
}


你可能感兴趣的:(【HDU4085】Peach Blossom Spring【斯坦纳树】【状态压缩】)