[Wc2008]游览计划 斯坦纳树

Description
给一张网格图,有一些点必须选,必选的的店无价值,其余有价值,问把必须点全部连起来的最小代价。


Sample Input
4 4
0 1 1 0
2 5 5 1
1 5 5 1
0 1 1 0


Sample Output
6
xoox
___o
___o
xoox


斯坦纳树板子题,存一下代码,耶!


#include <queue>
#include <cstdio>
#include <cstring>

using namespace std;
typedef long long LL;
const int dx[4] = {0, 1, 0, -1};
const int dy[4] = {1, 0, -1, 0};
int _max(int x, int y) {return x > y ? x : y;}
int read() {
	int s = 0, f = 1; char ch = getchar();
	while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();}
	while(ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
	return s * f;
}

struct edge {
	int x, y, c, next;
} e[810]; int len, last[110];
int n, m, f[110][1024], from[110][1024];
int cnt, c[110];
queue<int> q;
bool v[110];

int id(int x, int y) {return (x - 1) * m + y;}

void ins(int x, int y) {
	e[++len].x = x, e[len].y = y;
	e[len].next = last[x], last[x] = len;
}

void spfa(int S) {
	while(!q.empty()) {
		int x = q.front(); q.pop();
		for(int k = last[x]; k; k = e[k].next) {
			int y = e[k].y;
			if(f[y][S] > f[x][S] + c[y]) {
				f[y][S] = f[x][S] + c[y];
				from[y][S] = -x;
				if(!v[y]) v[y] = 1, q.push(y);
			}
		} v[x] = 0;
	}
}

void solve() {
	for(int S = 1; S < (1 << cnt); S++) {
		memset(v, 0, sizeof(v));
		for(int i = 1; i <= n * m; i++) {
			for(int s = (S - 1) & S; s; s = (s - 1) & S) {
				if(f[i][S] > f[i][s] + f[i][S ^ s] - c[i]) f[i][S] = f[i][s] + f[i][S ^ s] - c[i], from[i][S] = s;
			} if(f[i][S] < f[0][0]) q.push(i), v[i] = 1;
		} spfa(S);
	}
}

void dfs(int x, int S) {
	v[x] = 1;
	if(from[x][S] < 0) dfs(-from[x][S], S);
	else if(f[x][S] > 0) dfs(x, from[x][S]), dfs(x, S ^ from[x][S]);
}

int main() {
	n = read(), m = read();
	memset(f, 63, sizeof(f));
	for(int i = 1; i <= n; i++) {
		for(int j = 1; j <= m; j++) {
			int C = read();int n1 = id(i, j); c[n1] = C;
			if(!C) ++cnt, f[n1][1 << cnt - 1] = 0;
			for(int k1 = 0; k1 < 4; k1++) {
				int nx = i + dx[k1], ny = j + dy[k1];
				if(nx <= 0 || ny <= 0 || nx > n || ny > m) continue;
				int n2 = id(nx, ny);
				ins(n1, n2);
			}
		}
	} solve();
	int x = 0, S = (1 << cnt) - 1;
	for(int i = 1; i <= n * m; i++) {
		if(f[x][S] > f[i][S]) x = i;
	} printf("%d\n", f[x][S]);
	memset(v, 0, sizeof(v));
	dfs(x, S);
	for(int i = 1; i <= n; i++) {
		for(int j = 1; j <= m; j++) {
			int hh = id(i, j);
			if(!c[hh]) putchar('x');
			else {
				if(v[hh]) putchar('o');
				else putchar('_');
			}
		} puts("");
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值