标签:des style c class blog code
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 7844 | Accepted: 2623 |
Description
Input
Output
Sample Input
2 6 5 ##### #A#A## # # A# #S ## ##### 7 7 ##### #AAA### # A# # S ### # # #AAA### #####
Sample Output
8 11
#include<queue> #include<cstdio> #define INF 1<<30 #include<cstring> #include<algorithm> using namespace std; int n,m,ans,cnt; struct Node { int x,y,step; }; Node node[110]; int row,line; int dist[60]; char Map[60][60]; bool vis[60][60],vist[60]; //邻接矩阵存储 int mark[60][60],dis[110][110]; //给每个字母一个编号 int dir[4][2]={-1,0, 0,1, 1,0, 0,-1}; void bfs(int index) { queue<Node> que; memset(vis, false, sizeof(vis)); Node now, next; node[index].step = 0; que.push(node[index]); vis[node[index].x][node[index].y] = true; while(!que.empty()) { now = que.front(); que.pop(); int x = now.x, y = now.y; for(int i = 0; i < 4; ++i) { int tx = x + dir[i][0], ty = y +dir[i][1]; if(vis[tx][ty] == false && Map[tx][ty] != ‘#‘) //如果这一步可以走 { next.x = tx; next.y = ty; vis[tx][ty] = true; next.step = now.step + 1; que.push(next); if(Map[next.x][next.y] == ‘A‘ || Map[next.x][next.y] == ‘S‘) dis[ mark[ node[index].x ][ node[index].y ] ][ mark[next.x][next.y] ] = next.step; } } } } int prim() { for(int i = 0; i < cnt; ++i) { dist[i] = INF; vist[i] = false; } dist[0] = 0; while(1) { int min = INF, now = -1; for(int i = 0; i < cnt; ++i) { if(min > dist[i] && vist[i] == false) { min = dist[i]; now = i; } } if(now == -1) return ans; ans += min; vist[now] = true; for(int i = 0; i < cnt; ++i) if(vist[i] == false && dist[i] > dis[now][i]) dist[i] = dis[now][i]; } return ans; } int main() { int n_case; scanf("%d", &n_case); while(n_case--) { cnt = ans = 0; memset(mark, 0, sizeof(mark)); scanf("%d%d", &row, &line); char ch; while(ch = getchar(), ch != ‘\n‘); for(int i = 0; i < line; ++i) { for(int j = 0; j < row; ++j) { Map[i][j] = getchar(); if(Map[i][j] == ‘A‘ || Map[i][j] == ‘S‘) { mark[i][j] = cnt; node[cnt].x = i; node[cnt++].y = j; } } while(ch = getchar(), ch != ‘\n‘); } for(int i = 0; i < cnt; ++i) bfs(i); prim(); printf("%d\n", ans); } return 0; }
图论 --- BFS + MST,布布扣,bubuko.com
标签:des style c class blog code
原文地址:http://www.cnblogs.com/acmer-jsb/p/3751838.html