#include <bits/stdc++.h> #define rep(i, j, k) for (int i = (j); i <= (k); ++i) #define per(i, j, k) for (int i = (j); i >= (k); --i) #define SZ(v) int((v).size()) #define ALL(v) (v).begin(),(v).end() #define fi first #define se second using ll = long long; using pii = std::pair<int, int>; using pll = std::pair<ll, ll>; template<class T> void chkmn(T &x, T y) { if (y < x) x = y; } template<class T> void chkmx(T &x, T y) { if (y > x) x = y; } using namespace std; const int maxn = 410; int n, a[maxn][maxn]; string str; void work() { cin >> n; rep (i, 1, n) { cin >> str; rep (j, 1, n) a[i][j] = str[j - 1] - '0'; } rep (i, 1, n) rep (j, 1, n) if (i != j && !a[i][j]) a[i][j] = 1e9; rep (k, 1, n) rep (i, 1, n) rep (j, 1, n) chkmn(a[i][j], a[i][k] + a[k][j]); vector<pii> vec; rep (i, 1, n) rep (j, i + 1, n) vec.emplace_back(i, j); sort(ALL(vec), [&](pii x, pii y) { return a[x.fi][x.se] > a[y.fi][y.se]; }); int ans = 1e9; rep (u, 1, n) rep (v, u + 1, n) { int mx = 0, cur; for (auto [x, y] : vec) { if (a[x][y] <= mx) break; if ((cur = min(a[x][u] + a[v][y], a[x][v] + a[u][y])) >= a[x][y]) { chkmx(mx, a[x][y]); break; } chkmx(mx, cur); } chkmn(ans, mx); } cout << ans << '\n'; } int main() { cin.tie(nullptr) -> ios::sync_with_stdio(false); int t; cin >> t; while (t--) work(); }
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 | #include <bits/stdc++.h> #define rep(i, j, k) for (int i = (j); i <= (k); ++i) #define per(i, j, k) for (int i = (j); i >= (k); --i) #define SZ(v) int((v).size()) #define ALL(v) (v).begin(),(v).end() #define fi first #define se second using ll = long long; using pii = std::pair<int, int>; using pll = std::pair<ll, ll>; template<class T> void chkmn(T &x, T y) { if (y < x) x = y; } template<class T> void chkmx(T &x, T y) { if (y > x) x = y; } using namespace std; const int maxn = 410; int n, a[maxn][maxn]; string str; void work() { cin >> n; rep (i, 1, n) { cin >> str; rep (j, 1, n) a[i][j] = str[j - 1] - '0'; } rep (i, 1, n) rep (j, 1, n) if (i != j && !a[i][j]) a[i][j] = 1e9; rep (k, 1, n) rep (i, 1, n) rep (j, 1, n) chkmn(a[i][j], a[i][k] + a[k][j]); vector<pii> vec; rep (i, 1, n) rep (j, i + 1, n) vec.emplace_back(i, j); sort(ALL(vec), [&](pii x, pii y) { return a[x.fi][x.se] > a[y.fi][y.se]; }); int ans = 1e9; rep (u, 1, n) rep (v, u + 1, n) { int mx = 0, cur; for (auto [x, y] : vec) { if (a[x][y] <= mx) break; if ((cur = min(a[x][u] + a[v][y], a[x][v] + a[u][y])) >= a[x][y]) { chkmx(mx, a[x][y]); break; } chkmx(mx, cur); } chkmn(ans, mx); } cout << ans << '\n'; } int main() { cin.tie(nullptr) -> ios::sync_with_stdio(false); int t; cin >> t; while (t--) work(); } |