题目链接:http://poj.org/problem?id=3026
感觉英语比题目本身难,其实就是个最小生成树,不过要先bfs算出任意两点的权值。
#include <stdio.h>
#include <string.h>
#include <queue>
#include <algorithm>
using namespace std; char maze[][];
int par[];
struct Point
{
int x, y;
}point[]; struct Edge
{
int u, v, w;
bool operator<(const struct Edge &b)const
{
return w < b.w;
}
}edge[]; struct node
{
int x, y, step;
}; int find_set(int x)
{
return x == par[x] ? x : par[x] = find_set(par[x]);
} queue<struct node>q;
bool vis[][];
int bfs(int x, int y, int ex, int ey)
{
while(!q.empty())q.pop();
memset(vis, , sizeof(vis));
int dir[][] = {{, }, {, -}, {-, }, {, }};
q.push((struct node){x, y, });
vis[x][y] = ;
while(!q.empty())
{
struct node u = q.front();
q.pop();
if(u.x == ex && u.y == ey)
return u.step;
for(int i = ; i < ; i++)
{
if(!vis[u.x+dir[i][]][u.y+dir[i][]] && maze[u.x+dir[i][]][u.y+dir[i][]] != '#')
{
vis[u.x+dir[i][]][u.y+dir[i][]] = ;
q.push((struct node){u.x+dir[i][], u.y+dir[i][], u.step+});
}
}
}
} int main()
{
int t, n, m;
char fuck_space[];
scanf("%d%*c", &t);
while(t--)
{
gets(fuck_space);
sscanf(fuck_space, "%d %d", &m, &n);
int point_rear = ;
for(int i = ; i < n; i++)
{
gets(maze[i]);
for(int j = ; j < m; j++)
if(maze[i][j] == 'S' || maze[i][j] == 'A')
point[point_rear++] = (struct Point){i, j};
}
int edge_rear = ;
for(int i = ; i < point_rear; i++)
{
for(int j = i+; j < point_rear; j++)
{
int w = bfs(point[i].x, point[i].y, point[j].x, point[j].y);
edge[edge_rear++] = (struct Edge){i, j, w};
}
}
int ans = ;
for(int i = ; i < point_rear; i++)
par[i] = i;
sort(edge, edge+edge_rear);
for(int i = ; i < edge_rear; i++)
{
int x = find_set(edge[i].u);
int y = find_set(edge[i].v);
if(x != y)
{
ans += edge[i].w;
par[x] = y;
}
}
printf("%d\n", ans);
}
return ;
}