现在的位置: 首页 > 综合 > 正文

BZOJ 2595 WC 2008 游览计划 斯坦纳树

2017年10月16日 ⁄ 综合 ⁄ 共 2206字 ⁄ 字号 评论关闭

题目大意:给出一张图,上面有一些景点,剩下的为通路。通路上需要志愿者驻守以维护秩序,每一个通路需要一定的志愿者。问将所有景点都通过通路链接至少需要多少志愿者。

思路:斯坦纳树,大概意思就是将k个点连接起来的最小生成树。由于是NP完全问题,只能通过状压什么的解决。

设f[i][j][s]为根为(i,j)时景点的联通情况为s的最小生成树权值和。

转移十分巧妙,分两种情况转移。第一种是枚举当前状态S的一个子状态s,用f[i][j][s] + f[i][j][S - s] - src[i][j] 来更新f[i][j][S]。表示的是两个在点(i,j)的根的两种子状态转移。注意之前算的时候算了两次根节点,所以更新的时候要减去。

每一次S转移完成之后,要在f[xx][xx][S]这一层中更新一次,这样可以保证在不改变连通性的情况下更新正常的道路,当然是要所有在上一种情况中更新过的节点才有可能在这次更新别的节点。当然是从每个点向周围的四个点更新。至于更新的顺序问题,SPFA就行了,因为只有被更新过的节点才有可能继续更新其他节点,正好符合SPFA队列的性质。

总之真的是好麻烦啊。。

CODE:

#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define MAX 15
#define MAX_S (1 << MAX)
#define INF 0x3f3f3f3f
using namespace std;
const int dx[] = {0,1,-1,0,0};
const int dy[] = {0,0,0,1,-1};

int m,n,cnt;
int src[MAX][MAX];
int f[MAX][MAX][MAX_S];

struct Complex{
	int x,y,status;
	
	Complex(int _,int __,int ___):x(_),y(__),status(___) {}
	Complex() {}
}from[MAX][MAX][MAX_S];

queue<Complex> q;
bool v[MAX][MAX];

void SPFA(int s)
{
	while(!q.empty()) {
		Complex temp = q.front(); q.pop();
		int x = temp.x,y = temp.y;
		v[x][y] = false;
		for(int k = 1; k <= 4; ++k) {
			int fx = x + dx[k],fy = y + dy[k];
			if(!fx || !fy || x > m || y > n)	continue;
			if(f[fx][fy][s] > f[x][y][s] + src[fx][fy]) {
				f[fx][fy][s] = f[x][y][s] + src[fx][fy];
				if(!v[fx][fy]) {
					v[fx][fy] = true;
					q.push(Complex(fx,fy,s));
				}
				from[fx][fy][s] = Complex(x,y,s);
			}
		}
	}
}

bool ans[MAX][MAX];

void DFS(int x,int y,int s)
{
	if(x == INF || !from[x][y][s].status)	return ;
	ans[x][y] = true;
	DFS(from[x][y][s].x,from[x][y][s].y,from[x][y][s].status);
	if(from[x][y][s].x == x && from[x][y][s].y == y)
		DFS(x,y,s ^ from[x][y][s].status);
}

int main()
{
	cin >> m >> n;
	memset(f,0x3f,sizeof(f));
	for(int i = 1; i <= m; ++i)
		for(int j = 1; j <= n; ++j) {
			scanf("%d",&src[i][j]);
			if(!src[i][j])
				f[i][j][1 << (cnt++)] = 0;
		}
	for(int range = 1; range < (1 << cnt); SPFA(range++))
		for(int i = 1; i <= m; ++i)
			for(int j = 1; j <= n; ++j) {
				for(int s = range&(range - 1); s; s = range&(s - 1)) {
					if(f[i][j][range] > f[i][j][s] + f[i][j][range - s] - src[i][j]) {
						f[i][j][range] = f[i][j][s] + f[i][j][range - s] - src[i][j];
						from[i][j][range] = Complex(i,j,s);
					}
				}
				if(f[i][j][range] != INF) {
					q.push(Complex(i,j,range));
					v[i][j] = true;
				}
			}
	int x,y;
	for(int i = 1; i <= m; ++i)
		for(int j = 1; j <= n; ++j)
			if(!src[i][j]) {
				x = i,y = j;
				break;
			}
	cout << f[x][y][(1 << cnt) - 1] << endl;
	DFS(x,y,(1 << cnt) - 1);
	for(int i = 1; i <= m; ++i) {
		for(int j = 1; j <= n; ++j) {
			if(!src[i][j])	putchar('x');
			else if(ans[i][j])	putchar('o');
			else	putchar('_');
		}
		puts("");
	}
	return 0;
}

抱歉!评论已关闭.