Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 5258 | Accepted: 1756 |
Description
Input
Output
Sample Input
2 6 5 ##### #A#A## # # A# #S ## ##### 7 7 ##### #AAA### # A# # S ### # # #AAA### #####
Sample Output
8 11
Source
S与A都当成图的顶点,用广搜来求出各边的距离,再用prim算法
#include<iostream> using namespace std; const int MAX_NODE = 105; const int MAX_ROW = 55; const int INF = 100000000; int row,col,n; int node[MAX_NODE]; //用来记录S和A结点,以这种形式:r*col+c(col是列数) char map[MAX_ROW][MAX_ROW]; //record the map int graph[MAX_NODE][MAX_NODE]; //the graph to build by bfs void BFS(int start,int d[][MAX_ROW]) //d[i][j]表示从起点到i行,j列的最短距离 { int r,c,i,j,rr,cc; //(r,c)指当前点,(rr,cc)指下一点 int dir[4][2] = {{-1,0},{1,0},{0,-1},{0,1}}; //上,下,左,右 int head = 0,rear = 0,que[MAX_ROW*MAX_ROW]; //BFS用到的队列,当是' ','S','A',入队 bool vis[MAX_ROW][MAX_ROW]; //记录访问的点 for(i=0;i<row;i++) //初始化 for(j=0;j<col;j++) { d[i][j] = INF; vis[i][j] = false; } que[rear++] = start; //起点入队 r = start / col; c = start % col; vis[r][c] = true; d[r][c] = 0; while(head != rear) //判断队是否为空 { int t = que[head++]; r = t / col; c = t % col; for(i=0;i<4;i++) { rr = r + dir[i][0]; cc = c + dir[i][1]; if(!vis[rr][cc] && map[rr][cc] != '#') //判断可扩展结点 { d[rr][cc] = d[r][c] + 1; que[rear++] = rr*col + cc; } vis[rr][cc] = true; } } } void BuildGraph() { int i,j; int d[MAX_ROW][MAX_ROW]; for(i=0;i<n;i++) for(j=0;j<n;j++) graph[i][j] = INF; for(i=0;i<n;i++) { BFS(node[i],d); for(j=0;j<n;j++) { if(i == j) graph[i][j] = INF; else graph[i][j] = d[node[j]/col][node[j]%col]; } } } int Prim() { int i,j,k,res = 0; int dis[MAX_NODE]; bool vis[MAX_NODE]; k = 0; for(i=0;i<n;i++) { vis[i] = false; dis[i] = graph[k][i]; } dis[k]=0; vis[k] = true; res = 0; for(j=1;j<n;j++) { int min = INF; for(i=0;i<n;i++) if(!vis[i] && min > dis[i]) min = dis[k = i]; res += min; vis[k] = true; for(i=0;i<n;i++) if(!vis[i] && dis[i] > graph[k][i]) dis[i] = graph[k][i]; } return res; } int main() { int T; int i,j; cin >> T; while(T--) { cin >> col >> row; n = 0; for(i=0;i<row;i++) { while(getchar() != '\n'); //测试数据的问题,害我WA了好多次,输入行列后面还有很多空格,无语…… for(j=0;j<col;j++) { map[i][j] = getchar(); if(map[i][j] == 'A' || map[i][j] == 'S') node[n++] = i*col + j; } } BuildGraph(); cout << Prim() <<endl; } system("pause"); return 0; }