| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 12028 | Accepted: 3930 |
Description
Input
Output
Sample Input
2 6 5 ##### #A#A## # # A# #S ## ##### 7 7 ##### #AAA### # A# # S ### # # #AAA### #####
Sample Output
8 11
Source
1 50 50 ################################################## #AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# # A# #S A# ################################################## 答案应该输出141
#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn = 505;
int n,m;
int ans,cnt;
char space[1000];
int vis[maxn][maxn];
int fx[4] = {0,0,1,-1};
int fy[4] = {1,-1,0,0};
int set[maxn * maxn];
char a[maxn][maxn];
int b[maxn][maxn];
struct point
{
int x,y;
int dis;
};
point now,temp,end;
struct Edge
{
int a,b;
int dis;
}edge[maxn * maxn];
void bfs(int x,int y,int from)
{
memset(vis,0,sizeof(vis));
queue <point> q;
now.x = x;
now.y = y;
now.dis = 0;
vis[x][y] = 1;
q.push(now);
while(!q.empty())
{
temp = q.front();
q.pop();
for(int p=0;p<4;p++)
{
end.x = temp.x + fx[p];
end.y = temp.y + fy[p];
end.dis = temp.dis + 1;
if(end.x >=0 && end.x < n && end.y >= 0 && end.y < m && vis[end.x][end.y] == 0 && b[end.x][end.y] != -1)
{
vis[end.x][end.y] = 1;
q.push(end);
if(b[end.x][end.y] > 0)
{
edge[ans].a = from;
edge[ans].b = b[end.x][end.y];
edge[ans++].dis = end.dis;
}
}
}
}
}
int cmp(Edge a,Edge b)
{
return a.dis < b.dis;
} //cmp
int find(int x)
{
int k,j,r;
r = x;
while(r != set[r])
r = set[r];
k = x;
while(k != r)
{
j = set[k];
set[k] = r;
k = j;
}
return r;
} //并查集查找 + 路径压缩
void merge(int x,int y)
{
set[y] = x;
} //并查集合并
void init()
{
for(int i=1;i<=cnt;i++)
set[i] = i;
} //并查集初始化;
int Kruskal()
{
init();
int ans1 = 0;
sort(edge,edge + ans,cmp);
for(int i=0;i<ans;i++)
{
int f1 = find(edge[i].a);
int f2 = find(edge[i].b);
if(f1 == f2)
continue;
else
{
ans1 += edge[i].dis;
merge(f1,f2);
}
}
return ans1;
} //Kru算法
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(b,0,sizeof(b));
scanf("%d%d",&m,&n);
gets(space);
for(int i=0;i<n;i++)
{
gets(a[i]);
}
cnt = 1;
ans = 0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(a[i][j] == '#')
b[i][j] = -1;
if(a[i][j] == ' ')
b[i][j] = 0;
if(a[i][j]=='S'||a[i][j]=='A')
{
b[i][j] = cnt;
cnt++;
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(b[i][j] > 0)
bfs(i,j,b[i][j]);
}
}
int flag = Kruskal();
printf("%d\n",flag);
}
return 0;
}
Pku oj 3026 Borg Maze(BFS+MST)
原文:http://blog.csdn.net/sara_yf/article/details/51367439