标签:
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 9220 | Accepted: 3087 |
Description
Input
Output
Sample Input
2 6 5 ##### #A#A## # # A# #S ## ##### 7 7 ##### #AAA### # A# # S ### # # #AAA### #####
Sample Output
8 11
Source
1 #include<stdio.h> 2 #include<string.h> 3 #include<queue> 4 using namespace std; 5 int col , row , cnt; 6 char maze[200][200] ; 7 int l[200][200] ; 8 int vis[200][200] ; 9 int map[200][200] ; 10 const int inf = 0x3f3f3f3f ; 11 int move[][2] = {1 , 0 , 0 , 1 , -1 , 0 , 0 , -1} ; 12 13 void bfs (int sx , int sy) 14 { 15 queue <pair <int , int> > q ; 16 while (!q.empty ()) 17 q.pop () ; 18 memset (vis , -1 , sizeof(vis)) ; 19 vis[sx][sy] = 0 ; 20 q.push (make_pair(sx , sy)) ; 21 while (!q.empty ()) { 22 pair <int , int> k = q.front () ; 23 q.pop () ; 24 if (l[k.first][k.second] != -1) 25 map [l[sx][sy]] [l[k.first][k.second]] = vis [k.first][k.second] ; 26 for (int i = 0 ; i < 4 ; i++) { 27 int tx = k.first + move[i][0] ; 28 int ty = k.second + move[i][1] ; 29 if (maze[tx][ty] == ‘#‘ || vis[tx][ty] != -1) 30 continue ; 31 vis[tx][ty] = vis[k.first][k.second] + 1 ; 32 q.push (make_pair(tx , ty)) ; 33 } 34 } 35 } 36 37 void prim () 38 { 39 int p[200] , d[200] ; 40 for (int i = 1 ; i < cnt ; i++) { 41 d[i] = map[1][i] ; 42 p[i] = 1 ; 43 } 44 d[1] = 0 ; 45 int ans = 0 ; 46 for (int i = 1 ; i < cnt - 1 ; i++) { 47 int minc = inf , k ; 48 for (int j = 1 ; j < cnt ; j++) { 49 if (d[j] && d[j] < minc) { 50 minc = d[j] ; 51 k = j ; 52 } 53 } 54 d[k] = 0 ; 55 for (int j = 1 ; j < cnt ; j++) { 56 if (d[j] && d[j] > map[k][j]) { 57 d[j] = map[k][j] ; 58 p[j] = k ; 59 } 60 } 61 ans += minc ; 62 } 63 printf ("%d\n" , ans) ; 64 } 65 66 int main () 67 { 68 // freopen ("a.txt" , "r" , stdin) ; 69 int T ; 70 scanf ("%d" , &T) ; 71 while (T--) { 72 scanf ("%d%d" , &col , &row) ; 73 gets(maze[0]) ; 74 int tol = 1 ; 75 memset (l , -1 , sizeof(l)) ; 76 for (int i = 0 ; i < row ; i++) { 77 gets (maze[i]) ; 78 for (int j = 0 ; j < col ; j++) { 79 if (maze[i][j] == ‘A‘ || maze[i][j] == ‘S‘) { 80 l[i][j] = tol++ ; 81 } 82 } 83 } 84 for (int i = 0 ; i < row ; i++) { 85 for (int j = 0 ; j < col ; j++) { 86 if (l[i][j] != -1) { 87 bfs (i , j); 88 } 89 } 90 } 91 cnt = tol ; 92 prim () ; 93 } 94 return 0 ; 95 }
这道题有巨坑,收空格一定要用gets , 我用getchar RE了一个下午
标签:
原文地址:http://www.cnblogs.com/get-an-AC-everyday/p/4314061.html