The question says that, starting from S, we can split up and forward in S or. After thinking about it, we find that we need to find a minimum spanning tree.
First, bfs pre-processes the distance between each two points. My program uses map to map the coordinates of each point to 1-N, which makes it easier to create a graph.
Then, the prime is enough. Note that when you use gets () to read a map, you must use gets () to catch useless spaces .. (Why not use getchar? 0 0. I only know after reading the Forum,
Because there are many spaces ..................)
# Include <cstdio> # include <algorithm> # include <cstring> # include <map> # include <iostream> using namespace std; # define INF 0x3f3f3fchar map1 [55] [55]; int head, tail; int x, y; map <int, int> M; struct node {int x, y; int dis;} q [100000]; int top; int start; int dx [] = {-,}; int dy [] = }; int dis [150] [150]; bool vis [150] [150]; void bfs (int k, int st) {memset (vis, 0, sizeof (vis )); head = tail = 0; node tmp, tt; tmp. x = st /X; tmp. y = st % x; vis [tmp. x] [tmp. y] = 1; tmp. dis = 0; int tot = 0; q [tail ++] = tmp; int f; while (head <tail) {tmp = q [head]; for (int d = 0; d <4; d ++) {tt = tmp; tt. x + = dx [d]; tt. y + = dy [d]; tt. dis ++; if (map1 [tt. x] [tt. y]! = '#'&&! Vis [tt. x] [tt. y]) {vis [tt. x] [tt. y] = 1; if (f = M [tt. x * x + tt. y]) {tot ++; dis [k] [f] = tt. dis;} q [tail ++] = tt; if (tot = top) return ;}} head ++ ;}} int n, sum; int visit [150], d [150]; void prime (int n) {int I, j, min, v; sum = 0; for (I = 1; I <= n; I ++) {d [I] = dis [1] [I]; visit [I] = 0;} visit [1] = 1; for (I = 1; I <n; I ++) {min = INF; v = 1; for (j = 1; j <= n; j ++) {if (! Visit [j] & min> d [j]) {min = d [j]; v = j ;}} sum + = min; visit [v] = 1; for (j = 1; j <= n; j ++) {if (! Visit [j] & dis [v] [j] <d [j]) d [j] = dis [v] [j] ;}} int main () {char tmp [1000]; int cas; scanf ("% d", & cas); while (cas --) {memset (dis, 0x3f, sizeof (dis )); m. clear (); top = 0; scanf ("% d", & x, & y); gets (tmp); // catch the space for (int I = 0; I <y; I ++) {gets (map1 [I]) ;}for (int I = 1; I <Y-1; I ++) {for (int j = 1; map1 [I] [j]; j ++) {if (map1 [I] [j] = 'A' | map1 [I] [j] = 's') {top ++; if (map1 [I] [j] = 's') start = top; M [I * x + j] = top; dis [top] [top] = 0 ;}}for (int I = 1; I <Y-1; I ++) {for (int j = 1; map1 [I] [j]; j ++) {if (map1 [I] [j] = 'A' | map1 [I] [j] ='s ') {bfs (M [I * x + j], I * x + j) ;}} prime (top); printf ("% d \ n", sum );} return 0 ;}