大概题意:给你y行的字符串,求所有A点和S点在内所有点的最小连接距离;
这道题只要有思路就非常好写,思路大概是这样的:先用一个数组记录所有A点和S点
的坐标,用BFS来算出每每两个点的距离,接下里就可以用最小生成树来做了。
题目本身有一个比较坑的地方就是,你输入,x,y的时候。
需要这样写:scanf("%d %d ",&x,&y);
就是要多一个空格,就因为这样WA了一次。
这题也算对以前的的BFS的一个小小的复习。
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;
const int maxn=1000;
const int inf=1<<29;
int xx[4]= {1,-1,0,0},yy[4]= {0,0,-1,1};
int n,m;
struct Node
{
int x,y;
};
Node e,s,t,tp,que[maxn*maxn];
Node a[maxn];
int d[maxn][maxn];
int cnt1=0,cnt2=0;
char str[maxn][maxn];
struct Node2
{
int from;
int to;
int w;
bool operator<(const Node2 &c)const
{
return w<c.w;
}
} E[maxn*maxn];
int bfs()
{
int title=0,head=0;
for(int i=0; i<m; i++)
for(int j=0; j<n; j++)
d[i][j]=inf;
d[s.x][s.y]=0;
que[title++]=s;
while(head<=title)
{
t=que[head++];
if(t.x==e.x&&t.y==e.y)
return d[t.x][t.y];
for (int i = 0; i < 4; i++)
{
tp.x = t.x + xx[i];
tp.y = t.y + yy[i];
if (0 <= tp.x && tp.x < n &&0 <= tp.y && tp.y < m && str[tp.x][tp.y] != '#' && d[tp.x][tp.y] == inf)
{
d[tp.x][tp.y] = d[t.x][t.y] + 1;
que[title++] = tp;
}
}
}
return d[e.x][e.y];
}
int p[maxn];
int cha(int x)
{
if(p[x]==-1)
return x;
return p[x]=cha(p[x]);
}
int lxsb()
{
int ans=0;
for(int i=0;i<cnt2;i++)
{
int x=cha(E[i].from);
int y=cha(E[i].to);
if(x!=y)
{
ans+=E[i].w;
p[x]=y;
}
}
return ans;
}
int main()
{
int tt;
scanf("%d",&tt);
while(tt--)
{
cnt2=0,cnt1=0;
memset(p,-1,sizeof(p));
scanf("%d%d ",&n,&m);
getchar();
for(int i=0; i<m; i++)
gets(str[i]);
for(int i=0; i<m; i++)
for(int j=0; j<m; j++)
{
if(str[i][j]=='A'||str[i][j]=='S')
{
a[cnt1].x=i,a[cnt1].y=j;
cnt1++;
}
}
for(int i=0; i<cnt1; i++)
{
for(int j=i+1; j<cnt1; j++)
{
s.x=a[i].x;
s.y=a[i].y;
e.x=a[j].x;
e.y=a[j].y;
E[cnt2].from=i+1;
E[cnt2].to=j+1;
E[cnt2].w=bfs();
cnt2++;
}
}
sort(E,E+cnt2);
printf("%d\n",lxsb());
}
return 0;
}