[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;
}

### 回答1: Python实现最小斯坦纳树的代码可以使用Prim算法来解决。具体实现如下: ```python import sys # 为了方便表示图的邻接矩阵,使用无穷大代表不可达 inf = sys.maxsize def prim(graph): num_vertices = len(graph) key = [inf] * num_vertices # 记录顶点到最小生成树的最小权值边 parent = [None] * num_vertices # 记录最小生成树中顶点的父节点 visited = [False] * num_vertices # 记录顶点是否已访问 # 将第一个顶点设为起始顶点 key[0] = 0 for _ in range(num_vertices): # 找到未访问的顶点中键值最小的顶点 min_key = inf min_vertex = None for v in range(num_vertices): if not visited[v] and key[v] < min_key: min_key = key[v] min_vertex = v # 将找到的顶点标记为已访问 visited[min_vertex] = True # 更新顶点的最小权值边和父节点 for v in range(num_vertices): if not visited[v] and graph[min_vertex][v] < key[v]: key[v] = graph[min_vertex][v] parent[v] = min_vertex return parent def min_steiner_tree(graph, terminals): num_terminals = len(terminals) # 构建终端间的最短路径图 shortest_paths = [[inf] * num_terminals for _ in range(num_terminals)] for i in range(num_terminals): for j in range(num_terminals): shortest_paths[i][j] = dijkstra(graph, terminals[i], terminals[j]) # 在最短路径图上生成最小斯坦纳树 steiner_tree = [[inf] * num_terminals for _ in range(num_terminals)] for i in range(num_terminals): for j in range(num_terminals): if i == j: steiner_tree[i][j] = 0 else: for k in range(num_terminals): steiner_tree[i][j] = min(steiner_tree[i][j], shortest_paths[i][k] + shortest_paths[k][j]) # 使用Prim算法生成最小生成树 parent = prim(steiner_tree) return parent # 测试代码 graph = [[0, 7, 9, inf, inf, 14], [7, 0, 10, 15, inf, inf], [9, 10, 0, 11, inf, 2], [inf, 15, 11, 0, 6, inf], [inf, inf, inf, 6, 0, 9], [14, inf, 2, inf, 9, 0]] terminals = [0, 2, 4] parent = min_steiner_tree(graph, terminals) print(parent) ``` 此代码是使用Prim算法在最短路径图上生成最小斯坦纳树。输入的图是一个邻接矩阵,其中inf表示顶点之间不可达。terminals是终端节点的列表。输出是一个列表,表示每个顶点在生成的最小斯坦纳树中的父节点。 ### 回答2: Python实现最小斯坦纳树的代码可以使用图的最小生成树算法和动态规划的思想。 首先,我们可以使用Prim算法或Kruskal算法找到图的最小生成树,即连接所有顶点的最小权重的子图。 接下来,对于每一条边,我们通过遍历所有顶点集合的子集来找到最小斯坦纳树。子集的大小从1开始递增,直到包含所有顶点为止。 对于每个子集,我们通过动态规划的方法来找到连接子集中所有顶点的最小权重的边。 具体的实现步骤如下: 1. 使用Prim算法或Kruskal算法找到图的最小生成树,并保存最小生成树的边集合。 2. 对于每条边e in 最小生成树的边集合: 2.1 对于每个顶点集合V'(从1个元素开始递增到总顶点数): 2.1.1 如果V'包含边e的两个顶点,则忽略该顶点集合。 2.1.2 否则,遍历V'的所有子集V'': 2.1.2.1 如果V''中不包含边e的两个顶点,则忽略该子集。 2.1.2.2 否则,计算通过V''中的顶点连接边e的权重和,并更新最小权重值和对应的边。 3. 最后得到的最小权重值和对应的边即为最小斯坦纳树的结果。 以下是一个简单的Python代码示例: ```python import math def minimum_steiner_tree(graph): n = len(graph) inf = float('inf') dp = [[inf] * n for _ in range(1 << n)] for v in range(n): dp[1 << v][v] = 0 for S in range(1 << n): for v in range(n): for u in range(n): dp[S | (1 << u)][u] = min(dp[S | (1 << u)][u], dp[S][v] + graph[v][u]) return min(dp[-1]) # 测试代码 graph = [[0, 2, 3, math.inf], [2, 0, 1, 3], [3, 1, 0, 2], [math.inf, 3, 2, 0]] result = minimum_steiner_tree(graph) print("最小斯坦纳树的权重为:", result) ``` 权重矩阵graph表示的是无向图的邻接矩阵,math.inf表示无穷大,表示两个顶点之间没有边。代码中的结果为最小斯坦纳树的权重。 ### 回答3: Python最小斯坦纳树的代码可以通过使用Dijkstra算法和回溯法来实现。以下是一个可能的实现: ```python import sys def dijkstra(graph, src): n = len(graph) dist = [sys.maxsize] * n dist[src] = 0 visited = [False] * n for _ in range(n): u = min_distance(dist, visited) visited[u] = True for v in range(n): if graph[u][v] > 0 and not visited[v] and dist[v] > dist[u] + graph[u][v]: dist[v] = dist[u] + graph[u][v] return dist def min_distance(dist, visited): min_dist = sys.maxsize min_index = -1 for v in range(len(dist)): if not visited[v] and dist[v] < min_dist: min_dist = dist[v] min_index = v return min_index def tsp_solver(graph, start): n = len(graph) tsp_path = None tsp_cost = sys.maxsize def tsp_recursion(curr_node, visited, current_path, current_cost): nonlocal tsp_path, tsp_cost if len(visited) == n: if graph[curr_node][start] > 0: current_cost += graph[curr_node][start] current_path.append(start) if current_cost < tsp_cost: tsp_cost = current_cost tsp_path = current_path.copy() current_path.pop() current_cost -= graph[curr_node][start] return for next_node in range(n): if next_node not in visited: new_path = current_path.copy() new_path.append(next_node) tsp_recursion(next_node, visited + [next_node], new_path, current_cost + graph[curr_node][next_node]) tsp_recursion(start, [start], [start], 0) return tsp_path, tsp_cost def min_steiner_tree(graph, terminals): n = len(graph) t = len(terminals) dp = [[sys.maxsize] * t for _ in range(1 << t)] # 动态规划表格 path = [[None] * t for _ in range(1 << t)] # 记录路径 for i in range(t): dist = dijkstra(graph, terminals[i]) for j in range(t): dp[1 << i][j] = dist[terminals[j]] for i in range(1 << t): for j in range(t): if dp[i][j] == sys.maxsize: continue for k in range(t): if (i >> k) & 1 == 0 and dp[i][j] + dp[1 << k | i][k] < dp[1 << k | i][k]: dp[1 << k | i][k] = dp[i][j] + dp[1 << k | i][k] path[1 << k | i][k] = j min_cost = sys.maxsize min_path = None for i in range(t): if dp[(1 << t) - 1][i] < min_cost: min_cost = dp[(1 << t) - 1][i] min_path = [i] while len(min_path) < t: last_node = min_path[-1] min_path.append(path[(1 << t) - 1][last_node]) min_path = [terminals[i] for i in min_path] tsp_path, tsp_cost = tsp_solver(graph, terminals[0]) min_cost += tsp_cost min_path += tsp_path[1:] return min_path, min_cost # 测试例子 graph = [ [0, 2, 3, 0, 0], [2, 0, 0, 4, 0], [3, 0, 0, 1, 3], [0, 4, 1, 0, 2], [0, 0, 3, 2, 0] ] terminals = [1, 2, 3] path, cost = min_steiner_tree(graph, terminals) print("最小斯坦纳树路径:", path) print("最小斯坦纳树总成本:", cost) ``` 这段代码通过调用`min_steiner_tree`函数来计算给定图和终端点集合的最小斯坦纳树的路径和成本。`graph`代表图的邻接矩阵,`terminals`代表终端点的列表。最后将得到的最小斯坦纳树路径和成本打印出来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值