Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 6971 | Accepted: 2345 |
Description
Input
Output
Sample Input
2 6 5 ##### #A#A## # # A# #S ## ##### 7 7 ##### #AAA### # A# # S ### # # #AAA### #####
Sample Output
8 11
1 #include<stdio.h> 2 #include<string.h> 3 #include<queue> 4 using namespace std; 5 6 const int INF = 0x3f3f3f3f; 7 int dis[2510][2510],vis[60][60]; 8 int m,n,cnt; 9 char map[60][60]; 10 struct node 11 { 12 int x,y; 13 int id; 14 }cor[2510]; 15 struct sear 16 { 17 int x,y; 18 int step; 19 }; 20 queue <sear> que; 21 22 int bfs(int x, int y,int ex, int ey) 23 { 24 memset(vis,0,sizeof(vis)); 25 while(!que.empty()) 26 que.pop(); 27 que.push((struct sear){x,y,0}); 28 vis[x][y] = 1; 29 30 while(!que.empty()) 31 { 32 struct sear u = que.front(); 33 que.pop(); 34 if(u.x == ex && u.y == ey) 35 return u.step; 36 if(map[u.x-1][u.y] != '#' && !vis[u.x-1][u.y]) 37 { 38 vis[u.x-1][u.y] = 1; 39 que.push((struct sear){u.x-1,u.y,u.step+1}); 40 } 41 if(map[u.x+1][u.y] != '#' && !vis[u.x+1][u.y]) 42 { 43 vis[u.x+1][u.y] = 1; 44 que.push((struct sear){u.x+1,u.y,u.step+1}); 45 } 46 if(map[u.x][u.y-1] != '#' && !vis[u.x][u.y-1]) 47 { 48 vis[u.x][u.y-1] = 1; 49 que.push((struct sear){u.x,u.y-1,u.step+1}); 50 } 51 if(map[u.x][u.y+1] != '#' && !vis[u.x][u.y+1]) 52 { 53 vis[u.x][u.y+1] = 1; 54 que.push((struct sear){u.x,u.y+1,u.step+1}); 55 } 56 } 57 } 58 int prim_dis[2510]; 59 int prim_vis[2510]; 60 int prim(int id) 61 { 62 int i,j; 63 int ans = 0; 64 memset(prim_vis,0,sizeof(prim_vis)); 65 prim_vis[id] = 1; 66 for(i = 0; i < cnt; i++) 67 prim_dis[i] = dis[id][i]; 68 for(i = 1; i < cnt; i++) 69 { 70 int min = INF,pos; 71 for(j = 0; j < cnt; j++) 72 { 73 if(prim_dis[j] < min && !prim_vis[j]) 74 { 75 min = prim_dis[j]; 76 pos = j; 77 } 78 } 79 prim_vis[pos] = 1; 80 ans += min; 81 for(j = 0; j < cnt; j++) 82 { 83 if(!prim_vis[j] && prim_dis[j] > dis[pos][j]) 84 prim_dis[j] = dis[pos][j]; 85 } 86 } 87 return ans; 88 } 89 90 int main() 91 { 92 int t,i,j; 93 scanf("%d",&t); 94 while(t--) 95 { 96 cnt = 0; 97 scanf("%d %d",&m,&n); 98 char space[1010]; 99 gets(space); 100 for(i = 0; i < n; i++) 101 { 102 gets(map[i]); 103 for(j = 0; j < m; j++) 104 { 105 if(map[i][j] == 'A' || map[i][j] == 'S') 106 cor[cnt++] = ((struct node){i,j,cnt}); 107 } 108 } 109 for(i = 0; i < cnt; i++) 110 { 111 for(j = 0; j < cnt; j++) 112 { 113 if(i == j) dis[i][j] = 0; 114 else dis[i][j] = INF; 115 } 116 } 117 for(i = 0; i < cnt; i++) 118 { 119 for(j = i+1; j < cnt; j++) 120 { 121 dis[i][j] = dis[j][i] = bfs(cor[i].x,cor[i].y,cor[j].x,cor[j].y); 122 } 123 } 124 printf("%d\n",prim(0)); 125 } 126 return 0; 127 }