#include <cstdio> #include <cstdlib> #include <cassert> #include <algorithm> int mat[512][512]; int single_case() { int n; char line[512]; scanf("%d\n", &n); for (int i = 0; i < n; i++) { scanf("%s\n", line); for (int j = 0; j < n; j++) { mat[i][j] = (line[j] == '1') ? 1 : (n + 1); } mat[i][i] = 0; } // Floyd-Warshall (O(N^3)) for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { mat[i][j] = std::min(mat[i][j], mat[i][k] + mat[k][j]); } } } // for (int i = 0; i < n; i++) { // for (int j = 0; j < n; j++) { // printf("%d ", mat[i][j]); // } // puts(""); // } // For each pair of cities, try to put a teleport there and find the worst case (O(N^4)) int bestest = n + 1; for (int x = 0; x < n - 1; x++) { for (int y = x + 1; y < n; y++) { int worst = 0; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { // printf(" (%d %d): (%d, %d + %d | %d + %d)\n", i, j, mat[i][j], mat[i][x], mat[y][j], mat[i][y], mat[x][j]); worst = std::max(worst, std::min(mat[i][j], std::min(mat[i][x] + mat[y][j], mat[i][y] + mat[x][j]))); } } // printf("Score for (%d, %d): %d\n", x, y, worst); bestest = std::min(bestest, worst); } } return bestest; } int main() { int t; scanf("%d\n", &t); while (t --> 0) { const int answer = single_case(); printf("%d\n", answer); } 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 | #include <cstdio> #include <cstdlib> #include <cassert> #include <algorithm> int mat[512][512]; int single_case() { int n; char line[512]; scanf("%d\n", &n); for (int i = 0; i < n; i++) { scanf("%s\n", line); for (int j = 0; j < n; j++) { mat[i][j] = (line[j] == '1') ? 1 : (n + 1); } mat[i][i] = 0; } // Floyd-Warshall (O(N^3)) for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { mat[i][j] = std::min(mat[i][j], mat[i][k] + mat[k][j]); } } } // for (int i = 0; i < n; i++) { // for (int j = 0; j < n; j++) { // printf("%d ", mat[i][j]); // } // puts(""); // } // For each pair of cities, try to put a teleport there and find the worst case (O(N^4)) int bestest = n + 1; for (int x = 0; x < n - 1; x++) { for (int y = x + 1; y < n; y++) { int worst = 0; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { // printf(" (%d %d): (%d, %d + %d | %d + %d)\n", i, j, mat[i][j], mat[i][x], mat[y][j], mat[i][y], mat[x][j]); worst = std::max(worst, std::min(mat[i][j], std::min(mat[i][x] + mat[y][j], mat[i][y] + mat[x][j]))); } } // printf("Score for (%d, %d): %d\n", x, y, worst); bestest = std::min(bestest, worst); } } return bestest; } int main() { int t; scanf("%d\n", &t); while (t --> 0) { const int answer = single_case(); printf("%d\n", answer); } return 0; } |