| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 10428 | Accepted: 3463 |
Description
Input
Output
Sample Input
2 6 5 ##### #A#A## # # A# #S ## ##### 7 7 ##### #AAA### # A# # S ### # # #AAA### #####
Sample Output
8 11
Source
#pragma comment(linker, "/STACK:1024000000,1024000000") #include<cstdio> #include<string> #include<iostream> #include<cstring> #include<cmath> #include<stack> #include<queue> #include<vector> #include<map> #include<stdlib.h> #include<algorithm> #define LL __int64 using namespace std; const int MAXN=100+5; const int INF=0x3f3f3f3f; int kase,n,m,tot; char mat[MAXN][MAXN]; int a[MAXN][MAXN]; int w[MAXN][MAXN]; int wis[MAXN*MAXN]; int vis[MAXN][MAXN]; int d[MAXN]; int dir[4][2]={{0,1},{1,0},{0,-1},{-1,0}}; char opt[10]; struct node { int x,y; int step; }s; void BFS(int sx,int sy) { memset(vis,0,sizeof(vis)); queue<node> Q; while(!Q.empty()) Q.pop(); s.x=sx,s.y=sy,s.step=0; vis[sx][sy]=1; Q.push(s); while(!Q.empty()) { node now,next; now=Q.front();Q.pop(); // printf("%d %d\n",now.x,now.y); if(mat[now.x][now.y]==‘A‘ || mat[now.x][now.y]==‘S‘) w[a[sx][sy]][a[now.x][now.y]]=now.step; for(int i=0;i<4;i++) { next.x=now.x+dir[i][0]; next.y=now.y+dir[i][1]; if(mat[next.x][next.y]!=‘#‘ && !vis[next.x][next.y] && 1<=next.x && next.x<=n && 1<=next.y && next.y<=m) { next.step=now.step+1; vis[next.x][next.y]=1; Q.push(next); } } } } void prim() { memset(wis,0,sizeof(wis)); for(int i=2;i<tot;i++) d[i]=w[1][i]; wis[1]=1; int ans=0; for(int i=1;i<tot-1;i++) { int tmp,minn=INF; for(int j=1;j<tot;j++) { if(!wis[j] && d[j]<minn) { minn=d[j]; tmp=j; } } if(minn==INF) break; wis[tmp]=1; ans+=minn; for(int j=1;j<tot;j++) if(!wis[j] && w[tmp][j]<d[j]) d[j]=w[tmp][j]; } printf("%d\n",ans); } int main() { //freopen("in.txt","r",stdin); scanf("%d",&kase); while(kase--) { memset(w,0,sizeof(w)); scanf("%d %d",&m,&n); gets(mat[0]); tot=1; memset(a,-1,sizeof(a)); for(int i=1;i<=n;i++) { gets(mat[i]+1); printf("%s",mat[i]); for(int j=1;j<=m;j++) if(mat[i][j]==‘A‘ || mat[i][j]==‘S‘) a[i][j]=tot++; } for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) if(a[i][j]!=-1) BFS(i,j); prim(); } return 0; }
原文:http://www.cnblogs.com/clliff/p/4709585.html