标签:
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 9821 | Accepted: 3283 |
Description
Input
Output
Sample Input
2 6 5 ##### #A#A## # # A# #S ## ##### 7 7 ##### #AAA### # A# # S ### # # #AAA### #####
Sample Output
8 11
1 #include<stdio.h> 2 #include<string.h> 3 #include<queue> 4 #include<algorithm> 5 #include <iostream> 6 using namespace std; 7 int map[102][102]; 8 int vis[102][102]; 9 int parent[102]; 10 int row, col; 11 int edge_num = 0; 12 int point_num=0; 13 struct edge { 14 int u, v, w; 15 } e[102 * 102]; 16 struct points { 17 int u, v, d; 18 } point; 19 bool cmp(const edge e1,const edge e2){ 20 return e1.w<e2.w; 21 } 22 int Kruskal(){ 23 int mindis=0; 24 for(int i=1;i<=point_num;i++){ 25 parent[i]=i; 26 } 27 sort(e,e+edge_num,cmp); 28 int pnum=0; 29 for(int i=0;i<edge_num&&pnum<point_num;i++){ 30 int k,g; 31 int u=e[i].u; 32 int v=e[i].v; 33 for(k=parent[u];parent[k]!=k;k=parent[parent[k]]); 34 for(g=parent[v];parent[g]!=g;g=parent[parent[g]]); 35 36 if(k!=g){ 37 parent[g]=k; 38 mindis+=e[i].w; 39 pnum++; 40 } 41 } 42 return mindis; 43 } 44 void BFS(int x, int y) { 45 queue<points> p; 46 points s; 47 s.u = x; 48 s.v = y; 49 s.d = 0; 50 p.push(s); 51 memset(vis, 0, 102 * 102 * sizeof(int)); 52 vis[x][y] = 1; 53 54 while (!p.empty()) { 55 points tmp = p.front(); 56 p.pop(); 57 for (int i = -1; i < 2; i += 2) { 58 points next; 59 next.u = tmp.u + i; 60 next.v = tmp.v; 61 next.d = tmp.d + 1; 62 if (next.u >= 0 && next.u < row) { 63 if (!vis[next.u][next.v]) { 64 int pos = map[next.u][next.v]; 65 vis[next.u][next.v] = 1; 66 if (pos >= 0) 67 p.push(next); 68 if (pos >= 1) { 69 e[edge_num].u = map[x][y]; 70 e[edge_num].v = pos; 71 e[edge_num].w = next.d; 72 edge_num++; 73 } 74 } 75 } 76 } 77 for (int i = -1; i < 2; i += 2) { 78 points next; 79 next.u = tmp.u; 80 next.v = tmp.v + i; 81 next.d = tmp.d + 1; 82 if (next.v >= 0 && next.v < col) { 83 if (!vis[next.u][next.v]) { 84 int pos = map[next.u][next.v]; 85 vis[next.u][next.v] = 1; 86 if (pos >= 0) 87 p.push(next); 88 if (pos >= 1) { 89 e[edge_num].u = map[x][y]; 90 e[edge_num].v = pos; 91 e[edge_num].w = next.d; 92 edge_num++; 93 } 94 } 95 } 96 } 97 98 } 99 } 100 int main() { 101 int n; 102 scanf("%d", &n); 103 char tmp[102]; 104 for (int i = 0; i < n; i++) { 105 point_num=0; 106 edge_num=0; 107 scanf("%d %d", &col, &row); 108 gets(tmp); //坑【一串空格】 109 for (int j = 0; j < row; j++) { 110 for (int k = 0; k < col; k++) { 111 char c; 112 scanf("%c", &c); 113 if (c == ‘ ‘) 114 map[j][k] = 0; 115 else if (c == ‘#‘) 116 map[j][k] = -1; 117 else if (c == ‘\n‘) 118 k--; 119 else 120 map[j][k] = ++point_num; 121 } 122 123 } 124 for (int j = 0; j < row; j++) { 125 for (int k = 0; k < col; k++) { 126 if (map[j][k] > 0) { 127 BFS(j, k); 128 } 129 } 130 } 131 int mid=Kruskal(); 132 printf("%d\n",mid); 133 } 134 return 0; 135 }
Borg Maze - poj 3026(BFS + Kruskal 算法)
标签:
原文地址:http://www.cnblogs.com/sdxk/p/4660848.html