Long time no brush 51nod, and also I heard topcoder a lot of good questions. So come on 51nod brush it. (The client made a bit annoying (not read))
When the chart is not connected, the answer is infinite.
When FIG communication, the maximum difference between two points is multiplied by the length of the shortest $ D $, floyd run to look at the maximum value of the shortest.
1 #include <bits/stdc++.h> 2 3 const int N = 55; 4 const int INF = 0x3f3f3f3f; 5 6 char s[N]; 7 int mp[N][N], fa[N], n; 8 9 int getfa(int x) { 10 return x == fa[x] ? x : fa[x] = getfa(fa[x]); 11 } 12 13 void unit(int x, int y) { 14 x = getfa(x), y = getfa(y); 15 fa[x] = y; 16 } 17 18 void floyd() { 19 for (int k = 1; k <= n; k++) 20 for (int i = 1; i <= n; i++) 21 for (int j = 1; j <= n; j++) 22 mp[i][j] = std::min(mp[i][j], mp[i][k] + mp[k][j]); 23 } 24 25 int main() { 26 int T; 27 scanf("%d", &T); 28 while (T--) { 29 int d; 30 scanf("%d%d", &n, &d); 31 for (int i = 1; i <= n; i++) fa[i] = i; 32 for (int i = 1; i <= n; i++) { 33 scanf("%s", s + 1); 34 for (int j = 1; j <= n; j++) { 35 if (s[j] == 'Y' && i != j) 36 mp[i][j] = d, unit(i, j); 37 else if (i != j) 38 mp[i][j] = INF; 39 else 40 mp[i][j] = 0; 41 } 42 } 43 int cnt = 0; 44 for (int i = 1; i <= n; i++) 45 if (getfa(i) == i) cnt++; 46 if (cnt > 1) { 47 puts("-1"); 48 continue; 49 } 50 floyd(); 51 int ans = 0; 52 for (int i = 1; i <= n; i++) 53 for (int j = 1; j <= n; j++) 54 if (mp[i][j] < INF) 55 ans = std::max(ans, mp[i][j]); 56 printf("%d\n", ans); 57 } 58 return 0; 59 }