标签:
2 6 5 ##### #A#A## # # A# #S ## ##### 7 7 ##### #AAA### # A# # S ### # # #AAA### #####
8 11
1 #include <iostream> 2 #include <cstdio> 3 #include <queue> 4 #include <cstring> 5 #define INF 0x3f3f3f3f 6 #define pii pair<int,int> 7 using namespace std; 8 const int maxn = 110; 9 const int mx = 1000000; 10 int e[maxn][maxn],d[maxn][maxn],hs[maxn][maxn],ds[mx],n,m,tot; 11 bool done[mx]; 12 char mp[maxn][maxn]; 13 bool isIn(int x,int y) { 14 return x >=0 && x < n && y >= 0 && y < m; 15 } 16 void bfs(int x,int y) { 17 queue< pii >q; 18 q.push(make_pair(x,y)); 19 memset(d,-1,sizeof(d)); 20 d[x][y] = 0; 21 static const int dir[4][2] = {-1,0,1,0,0,-1,0,1}; 22 while(!q.empty()) { 23 pii now = q.front(); 24 q.pop(); 25 for(int i = 0; i < 4; ++i) { 26 int tx = now.first + dir[i][0]; 27 int ty = now.second + dir[i][1]; 28 if(isIn(tx,ty) && mp[tx][ty] != ‘#‘ && d[tx][ty] == -1) { 29 d[tx][ty] = d[now.first][now.second] + 1; 30 q.push(make_pair(tx,ty)); 31 if(mp[tx][ty] == ‘A‘ || mp[tx][ty] == ‘S‘) { 32 e[hs[x][y]][hs[tx][ty]] = d[tx][ty]; 33 } 34 } 35 } 36 } 37 } 38 39 int prim() { 40 int ans = 0,cnt = 0; 41 for(int i = 0; i < tot; ++i) { 42 done[i] = false; 43 ds[i] = INF; 44 } 45 ds[0] = 0; 46 while(true) { 47 int minV = INF,idx = -1; 48 for(int i = 0; i < tot; ++i) 49 if(ds[i] < minV && !done[i]) minV = ds[idx = i]; 50 if(minV == INF || idx == -1) break; 51 ans += minV; 52 done[idx] = true; 53 for(int i = 1; i < tot; ++i) 54 if(!done[i] && e[idx][i] < ds[i]) ds[i] = e[idx][i]; 55 } 56 return ans; 57 } 58 59 int main() { 60 int kase; 61 scanf("%d",&kase); 62 while(kase--) { 63 scanf("%d %d",&m,&n); 64 gets(mp[0]); 65 for(int i = tot = 0; i < n; ++i) { 66 gets(mp[i]); 67 for(int j = 0; j < m; ++j) { 68 if(mp[i][j] == ‘A‘ || mp[i][j] == ‘S‘) 69 hs[i][j] = tot++; 70 } 71 } 72 for(int i = 0; i < n; ++i) { 73 for(int j = 0; j < m; ++j) 74 if(mp[i][j] == ‘A‘ || mp[i][j] == ‘S‘) bfs(i,j); 75 } 76 printf("%d\n",prim()); 77 } 78 return 0; 79 }
标签:
原文地址:http://www.cnblogs.com/crackpotisback/p/4335099.html