#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> PII;
const int N = 405;
int G[N][N];
int dist[N][N];
vector<PII> distp[N];
struct Edge{
int a, b, val;
};
void solve() {
int n;
cin>>n;
for(int i=0;i<n;i++) for(int j=0;j<n;j++) if(i != j) dist[i][j] = 1e9;
for(int i=0;i<=n;i++) distp[i].clear();
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
char x;
cin>>x;
if(x == '1') G[i][j] = 1, dist[i][j] = 1;
else G[i][j] = 0;
}
}
for(int k=0;k<n;k++) {
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
}
}
}
vector<Edge> okp;
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++) {
okp.push_back({i, j, 0});
distp[dist[i][j]].push_back({i, j});
}
}
mt19937 gen(2137);
for(int i=1;i<=n;i++) shuffle(distp[i].begin(), distp[i].end(), gen);
vector<Edge> tmp;
int res = 0;
for(int d=n;d>0;d--) {
for(Edge e: okp) if(e.val < d) tmp.push_back(e);
swap(okp, tmp);
tmp.clear();
if(okp.empty()) {
cout<<d<<endl;
return;
}
for(auto [a, b]: distp[d]) {
for(Edge e: okp) {
int new_val = min(dist[e.a][a] + dist[e.b][b], dist[e.a][b] + dist[e.b][a]);
if(new_val < d) {
e.val = max(e.val, new_val);
tmp.push_back(e);
}
}
swap(okp, tmp);
tmp.clear();
if(okp.empty()) {
cout<<d<<endl;
return;
}
}
}
}
int main() {
ios_base::sync_with_stdio(0);
int Z;
cin>>Z;
while(Z--) 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 79 80 81 82 83 | #include <bits/stdc++.h> using namespace std; typedef pair<int,int> PII; const int N = 405; int G[N][N]; int dist[N][N]; vector<PII> distp[N]; struct Edge{ int a, b, val; }; void solve() { int n; cin>>n; for(int i=0;i<n;i++) for(int j=0;j<n;j++) if(i != j) dist[i][j] = 1e9; for(int i=0;i<=n;i++) distp[i].clear(); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { char x; cin>>x; if(x == '1') G[i][j] = 1, dist[i][j] = 1; else G[i][j] = 0; } } for(int k=0;k<n;k++) { for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]); } } } vector<Edge> okp; for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { okp.push_back({i, j, 0}); distp[dist[i][j]].push_back({i, j}); } } mt19937 gen(2137); for(int i=1;i<=n;i++) shuffle(distp[i].begin(), distp[i].end(), gen); vector<Edge> tmp; int res = 0; for(int d=n;d>0;d--) { for(Edge e: okp) if(e.val < d) tmp.push_back(e); swap(okp, tmp); tmp.clear(); if(okp.empty()) { cout<<d<<endl; return; } for(auto [a, b]: distp[d]) { for(Edge e: okp) { int new_val = min(dist[e.a][a] + dist[e.b][b], dist[e.a][b] + dist[e.b][a]); if(new_val < d) { e.val = max(e.val, new_val); tmp.push_back(e); } } swap(okp, tmp); tmp.clear(); if(okp.empty()) { cout<<d<<endl; return; } } } } int main() { ios_base::sync_with_stdio(0); int Z; cin>>Z; while(Z--) solve(); } |
English