#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int INF = 1e9;
void floydWarshall(vector<vector<int>>& graf) {
int V = graf.size();
for (int k = 0; k < V; k++) {
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (graf[i][k] != INF && graf[k][j] != INF)
graf[i][j] = min(graf[i][j], graf[i][k] + graf[k][j]);
}
}
}
}
int fd(const vector<vector<int>>& dist) {
int srednica = 0;
int n = dist.size();
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (i != j)
srednica = max(srednica, dist[i][j]);
return srednica;
}
int fot(const vector<vector<int>>& dist, int n) {
int best = fd(dist);
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (dist[i][j] > 1) {
int nowa_srednica = 0;
for (int a = 0; a < n; a++) {
for (int b = 0; b < n; b++) {
int new_dist = min(dist[a][b], min(dist[a][i] + 1 + dist[j][b], dist[a][j] + 1 + dist[i][b]));
nowa_srednica = max(nowa_srednica, new_dist);
}
}
best = min(best, nowa_srednica);
}
}
}
return best;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int Q, n;
cin >> Q;
while (Q--) {
cin >> n;
vector<vector<int>> dist(n, vector<int>(n, INF));
for (int i = 0; i < n; i++) {
string ciag;
cin >> ciag;
for (int j = 0; j < n; j++) {
if (ciag[j] == '1')
dist[i][j] = 1;
if (i == j)
dist[i][j] = 0;
}
}
floydWarshall(dist);
cout << fot(dist, n) << endl;
}
}
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 | #include <iostream> #include <vector> #include <algorithm> using namespace std; const int INF = 1e9; void floydWarshall(vector<vector<int>>& graf) { int V = graf.size(); for (int k = 0; k < V; k++) { for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (graf[i][k] != INF && graf[k][j] != INF) graf[i][j] = min(graf[i][j], graf[i][k] + graf[k][j]); } } } } int fd(const vector<vector<int>>& dist) { int srednica = 0; int n = dist.size(); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (i != j) srednica = max(srednica, dist[i][j]); return srednica; } int fot(const vector<vector<int>>& dist, int n) { int best = fd(dist); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (dist[i][j] > 1) { int nowa_srednica = 0; for (int a = 0; a < n; a++) { for (int b = 0; b < n; b++) { int new_dist = min(dist[a][b], min(dist[a][i] + 1 + dist[j][b], dist[a][j] + 1 + dist[i][b])); nowa_srednica = max(nowa_srednica, new_dist); } } best = min(best, nowa_srednica); } } } return best; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int Q, n; cin >> Q; while (Q--) { cin >> n; vector<vector<int>> dist(n, vector<int>(n, INF)); for (int i = 0; i < n; i++) { string ciag; cin >> ciag; for (int j = 0; j < n; j++) { if (ciag[j] == '1') dist[i][j] = 1; if (i == j) dist[i][j] = 0; } } floydWarshall(dist); cout << fot(dist, n) << endl; } } |
English