题意: 求出S到到各点走的总步数.
题意分析: 可以理解成构建最小生成树, 使得所有的点都联通起来。用bfs求出各点之间的距离, 再用prim求出最小生成树的总权值.
反思: WA了两个小时, 看了Dicuss才知道。。输入的n,m两个整数后面有一大行的空格,要略去才可以。。。好题。。但是。。出题人也太坑了吧。。。
code:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn = 505;
const int inf =0x3f3f3f3f3f;
int n, m;
char c[maxn][maxn];
int Map[maxn][maxn];
int dis[maxn][maxn];
struct node{
int x, y;
int step;
};
int len, ans;
int pos[5][2]={{0,1}, {-1,0}, {0,-1}, {1,0}};
void bfs(int x, int y){
int vis[maxn][maxn];
memset(vis, 0, sizeof(vis));
queue<node>que;
while(!que.empty()) que.pop();
node p;
p.x = x;
p.y = y;
p.step = 0;
vis[x][y]=1;
//cout << x <<y<<endl;
que.push(p);
while(!que.empty()){
node q = que.front();
que.pop();
if(Map[q.x][q.y]>0) dis[Map[q.x][q.y]][Map[x][y]] = dis[Map[x][y]][Map[q.x][q.y]] = q.step;
for(int i=0; i<4; i++){
p.x = q.x + pos[i][0];
p.y = q.y + pos[i][1];
if(!vis[p.x][p.y] && Map[p.x][p.y]!=-1 && p.x>0 &&p.y>0 &&p.x<=m &&p.y<=n){
p.step = q.step+1;
vis[p.x][p.y] = 1;
que.push(p);
}
}
//cout << endl;
}
return ;
}
void prim(int s){
int vis[maxn], d[maxn], i, j, k;
memset(vis, 0, sizeof(vis));
memset(d, inf, sizeof(d));
int MIN=inf, v=0;
d[s]=0;
while(true){
MIN = inf , v = -1;
for(i=1; i<len; i++){
if(!vis[i] && d[i]<MIN){
v = i;
MIN = d[i];
}
}
if(v==-1) return ;
vis[v] = 1;
ans += MIN;
for(i=1;i<len;i++){
if(!vis[i] && d[i] > dis[v][i]){
d[i] = dis[v][i];
}
}
}
return;
}
int main()
{
//freopen("in.txt", "r", stdin);
int T, i, j;
scanf("%d", &T);
while(T--)
{
ans=0;
memset(dis, 0, sizeof(dis));
scanf("%d %d", &n, &m);
gets(c[0]);//两个整数后面有好多空格, 得舍去.
for(i=1; i<=m; i++){
gets(c[i]);
}
len=1;
int op;
for(i=1; i<=m; i++){
for(j=0; j<n; j++){
if(c[i][j] == 'A' || c[i][j] == 'S'){
if(c[i][j] == 'S') op=len;
Map[i][j+1] = len++;
}
else if(c[i][j]=='#') Map[i][j+1] = -1;
else Map[i][j+1] = 0;
}
}
for(i=1; i<=m; i++){
for(j=1; j<=n; j++){
if(Map[i][j]>0) bfs(i, j);
}
}
prim(op);
printf("%d\n", ans);
}
return 0;
}