其實就是一道傻逼最小生成樹,只因爲輸入時,爲了喫的scanf剩下的換行符,用了getchar()結果wa到死
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
struct edge{
int from,to,cost;
bool operator<(const edge & a)const
{
return cost < a.cost;
}
}es[1000010];
char str[55][55];
int s[110][2];
int fa[110],e,dist[55][55],vis[55][55];
void init()
{
for(int i=0;i<110;i++)fa[i]=i;
}
int find_p(int x)
{
if(x!=fa[x])fa[x]=find_p(fa[x]);
return fa[x];
}
void unite(int x,int y)
{
x=find_p(x);
y=find_p(y);
if(x!=y)fa[x]=y;
}
int kruskal()
{
init();
sort(es,es+e);
int res=0;
for(int i=0;i<e;i++){
if(find_p(es[i].from)!=find_p(es[i].to)){
unite(es[i].from,es[i].to);
res+=es[i].cost;
}
}
return res;
}
int bfs(int sx,int sy)
{
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
queue<pair<int,int> > que;
memset(vis,0,sizeof(vis));
memset(dist,0,sizeof(dist));
que.push(make_pair(sx,sy));
vis[sx][sy]=1;
while(!que.empty()){
pair<int,int> p=que.front();que.pop();
for(int i=0;i<4;i++){
int tx=p.first+dx[i],ty=p.second+dy[i];
if(!vis[tx][ty]&&str[tx][ty]!='#'){
vis[tx][ty]=1;
dist[tx][ty]=dist[p.first][p.second]+1;
que.push(make_pair(tx,ty));
}
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--){
int n,m,tot=0;e=0;
scanf("%d%d",&n,&m);getchar();//會wa,只有gets()能a;
for(int i=0;i<m;i++){
gets(str[i]);
for(int j=0;j<n;j++){
if(str[i][j]=='S'||str[i][j]=='A')s[tot][0]=i,s[tot][1]=j,tot++;
}
}
for(int i=0;i<tot;i++){
bfs(s[i][0],s[i][1]);
for(int j=i+1;j<tot;j++){
es[e].from=i,es[e].to=j,es[e].cost=dist[s[j][0]][s[j][1]];e++;
es[e].from=j,es[e].to=i,es[e].cost=dist[s[j][0]][s[j][1]];e++;
}
}
printf("%d\n",kruskal());
}
return 0;
}