#include <bits/stdc++.h>
#define ll long long
#define ve vector
#define fi first
#define se second
#define ld long double
#define all(x) x.begin(), x.end()
using namespace std;
typedef pair<int, int> pii;
const int MAXN = 401;
int g[MAXN][MAXN];
int d[MAXN][MAXN];
void bfs(int s, int n){
queue<int> q;
q.push(s);
d[s][s] = 0;
while(!q.empty()){
int v = q.front();
q.pop();
for(int to = 0; to < n; to++)
if(g[v][to] && d[s][to] == 0 && to != s){
d[s][to] = d[s][v] + 1;
q.push(to);
}
}
}
struct path{
int a, b, d;
};
void solve(){
int n;
cin >> n;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++){
char x;
cin >> x;
g[i][j] = x - '0';
d[i][j] = 0;
}
for(int i = 0; i < n; i++)
bfs(i, n);
ve<path> v;
for(int i = 0; i < n; i++)
for(int j = 0; j < i; j++)
v.push_back({i, j, d[i][j]});
int res = n;
sort(all(v), [](auto a, auto b){
return a.d > b.d;
});
for(auto [a, b, cd] : v){
int cans = 0;
for(auto [a1, b1, d1] : v){
if(d1 <= cans || cans >= res) break;
cans = max(cans, min({d[a1][b] + d[b1][a], d[a1][a] + d[b1][b], d1}));
}
res = min(res, cans);
}
cout << res << "\n";
}
signed main(){
ios_base::sync_with_stdio(0); cin.tie(0);
int T= 1;
cin >> T;
while(T--)
solve();
}
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 75 76 77 78 | #include <bits/stdc++.h> #define ll long long #define ve vector #define fi first #define se second #define ld long double #define all(x) x.begin(), x.end() using namespace std; typedef pair<int, int> pii; const int MAXN = 401; int g[MAXN][MAXN]; int d[MAXN][MAXN]; void bfs(int s, int n){ queue<int> q; q.push(s); d[s][s] = 0; while(!q.empty()){ int v = q.front(); q.pop(); for(int to = 0; to < n; to++) if(g[v][to] && d[s][to] == 0 && to != s){ d[s][to] = d[s][v] + 1; q.push(to); } } } struct path{ int a, b, d; }; void solve(){ int n; cin >> n; for(int i = 0; i < n; i++) for(int j = 0; j < n; j++){ char x; cin >> x; g[i][j] = x - '0'; d[i][j] = 0; } for(int i = 0; i < n; i++) bfs(i, n); ve<path> v; for(int i = 0; i < n; i++) for(int j = 0; j < i; j++) v.push_back({i, j, d[i][j]}); int res = n; sort(all(v), [](auto a, auto b){ return a.d > b.d; }); for(auto [a, b, cd] : v){ int cans = 0; for(auto [a1, b1, d1] : v){ if(d1 <= cans || cans >= res) break; cans = max(cans, min({d[a1][b] + d[b1][a], d[a1][a] + d[b1][b], d1})); } res = min(res, cans); } cout << res << "\n"; } signed main(){ ios_base::sync_with_stdio(0); cin.tie(0); int T= 1; cin >> T; while(T--) solve(); } |
English