#include <iostream> #include <cstring> using namespace std; const int MAX_N = 400; int graph[MAX_N + 1][MAX_N + 1]; int dist[MAX_N + 1][MAX_N + 1]; int main() { int t; cin >> t; for (int test = 0; test < t; test++) { int n; cin >> n; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { char c; cin >> c; graph[i][j] = (c == '1' ? 1 : (i == j ? 0 : 1000)); } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { dist[i][j] = graph[i][j]; } } for (int k = 1; k <= n; k++) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (dist[i][k] + dist[k][j] < dist[i][j]) { dist[i][j] = dist[i][k] + dist[k][j]; } } } } int max_dist = 0; for (int i = 1; i <= n; i++) { for (int j = i + 1; j <= n; j++) { if (dist[i][j] != 1000) { max_dist = max(max_dist, dist[i][j]); } } } int min_bak = max_dist; for (int t1 = 1; t1 <= n; t1++) { for (int t2 = t1 + 1; t2 <= n; t2++) { int local_max = 0; for (int i = 1; i <= n; i++) { for (int j = i + 1; j <= n; j++) { int shortest_path = dist[i][j]; shortest_path = min(shortest_path, dist[i][t1] + dist[t2][j]); shortest_path = min(shortest_path, dist[i][t2] + dist[t1][j]); local_max = max(local_max, shortest_path); } } min_bak = min(min_bak, local_max); } } cout << min_bak << endl; } return 0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | #include <iostream> #include <cstring> using namespace std; const int MAX_N = 400; int graph[MAX_N + 1][MAX_N + 1]; int dist[MAX_N + 1][MAX_N + 1]; int main() { int t; cin >> t; for (int test = 0; test < t; test++) { int n; cin >> n; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { char c; cin >> c; graph[i][j] = (c == '1' ? 1 : (i == j ? 0 : 1000)); } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { dist[i][j] = graph[i][j]; } } for (int k = 1; k <= n; k++) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (dist[i][k] + dist[k][j] < dist[i][j]) { dist[i][j] = dist[i][k] + dist[k][j]; } } } } int max_dist = 0; for (int i = 1; i <= n; i++) { for (int j = i + 1; j <= n; j++) { if (dist[i][j] != 1000) { max_dist = max(max_dist, dist[i][j]); } } } int min_bak = max_dist; for (int t1 = 1; t1 <= n; t1++) { for (int t2 = t1 + 1; t2 <= n; t2++) { int local_max = 0; for (int i = 1; i <= n; i++) { for (int j = i + 1; j <= n; j++) { int shortest_path = dist[i][j]; shortest_path = min(shortest_path, dist[i][t1] + dist[t2][j]); shortest_path = min(shortest_path, dist[i][t2] + dist[t1][j]); local_max = max(local_max, shortest_path); } } min_bak = min(min_bak, local_max); } } cout << min_bak << endl; } return 0; } |