POJ 3206 Borg Maze (BFS+Prim)
Borg Maze
Borg Maze
大意:给你一个m*n的迷宫,可以上下左右的走,只能走空格或字母,求出将所有字母连通起来的最小耗费。
思路:先用BFS求出S到所有A的距离,再用Prim求最小生成树,求出最小耗费。这个题坑的不在题,是数据太坑了,在空格处理上没弄好,贡献了好几个WA和CE,看Discuss才知道很坑,最后用G++过了的代码,C++还RE,实在不知道说什么好了 =。=
1 #include <stdio.h> 2 #include <iostream> 3 #include <string.h> 4 #define INF 0xfffffff 5 using namespace std; 6 7 char str[55][55]; 8 int Map[55][55]; 9 int dis[55]; 10 int dist[105][105]; 11 int edge[105][105]; 12 int num, n, m, p ; 13 14 int Move[4][2] = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}}; 15 16 int min(int a, int b) 17 { 18 return a > b ? b : a; 19 } 20 21 void BFS(int i, int j) 22 { 23 int head = 0, tail = 0; 24 int q_x[2550], q_y[2550]; 25 bool vis[55][55]; 26 memset(vis, false, sizeof(vis)); 27 memset(dist, 0, sizeof(dist)); 28 vis[i][j] = true; 29 q_x[tail] = i; 30 q_y[tail++] = j; 31 while(head < tail) 32 { 33 int x = q_x[head]; 34 int y = q_y[head++]; 35 if(Map[x][y]) 36 { 37 edge[Map[i][j]][Map[x][y]] = dist[x][y]; 38 } 39 for(int t = 0; t < 4; t++) 40 { 41 int dx = x+Move[t][0]; 42 int dy = y+Move[t][1]; 43 if(dx >= 1 && dx <= m && dy >= 1 && dy <= n) 44 { 45 if(!vis[dx][dy] && str[dx][dy] != '#') 46 { 47 q_x[tail] = dx; 48 q_y[tail++] = dy; 49 vis[dx][dy] = true; 50 dist[dx][dy] = dist[x][y]+1; 51 } 52 } 53 } 54 } 55 } 56 57 58 int Prim() 59 { 60 int Ans; 61 int Min_ele, Min_node; 62 for(int i = 1; i <= num; i++) 63 { 64 dis[i] = INF; 65 } 66 Ans = 0; 67 int r = 1; 68 for(int i = 1; i <= num-1; i++) 69 { 70 Min_ele = INF; 71 dis[r] = -1; 72 for(int j = 1; j <= num; j++) 73 { 74 if(dis[j] >= 0) 75 { 76 dis[j] = min(dis[j], edge[r][j]); 77 if(dis[j] < Min_ele) 78 { 79 Min_ele = dis[j]; 80 Min_node = j; 81 } 82 } 83 } 84 r = Min_node; 85 Ans += Min_ele; 86 } 87 return Ans; 88 } 89 90 void Solve() 91 { 92 int i, j; 93 cin >> p; 94 while(p--) 95 { 96 memset(Map, 0, sizeof(Map)); 97 num = 0; 98 cin >> n >> m; 99 char s[100]; 100 gets(s);///这里太坑了 101 for(int i = 1; i <= m; i++) 102 { 103 gets(str[i]); 104 for(int j = 0; j < n; j++) 105 { 106 if(str[i][j] == 'A' || str[i][j] == 'S') 107 { 108 Map[i][j] = ++num; 109 } 110 } 111 } 112 for(int i = 1; i <= m; i++) 113 { 114 for(int j = 1; j <= n; j++) 115 { 116 if(Map[i][j]) 117 { 118 BFS(i, j); 119 } 120 } 121 } 122 printf("%d\n", Prim()); 123 } 124 } 125 126 int main() 127 { 128 Solve(); 129 130 return 0; 131 }