题目链接
求任意点对的最短距离的最大值
#include <iostream>
#include <queue>
#include <map>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
int N, M;
map<string, int> rap;
vector<vector<int>> v;
int INF = 0x3f3f3f3f;
int bfs()
{
int ans = -1;
for (int i = 0; i < N; i++)
{
// i点 到所有点的最短距离
// 需要找到这些点中的最远的一个点
queue<int> q;
int dp[1005] = {
0};
dp[i] = 1;
q.push(i);
int dist[1005];
fill(dist, dist + 1004, -INF);
dist[i] = 0;
while (!q.empty())
{
auto x = q.front();
q.pop();
for (auto e : v[x])
{
if (dp[e] == 0)
{
dp[e] = 1;
q.push(e);
dist[e] = dist[x] + 1;
}
}
}
int anst = -INF;
for (int i = 0; i < N; i++)
{
if (dist[i] == -INF)
{
anst = -1;
break;
}
anst = max(dist[i], anst);
}
// 在这些点的最短路径中 找到最长的路 才能确定任意两人的朋友链长度
ans = max(anst, ans);
}
return ans;
}
int main()
{
while (cin >> N && N != 0)
{
string s;
v.clear();
v.resize(N + 10);
for (int i = 0; i < N; i++)
{
char c[15];
scanf("%s", c);
rap[(string)c] = i;
}
cin >> M;
while (M--)
{
char x[15], y[15];
scanf("%s%s", x, y);
int nx = rap[x];
int ny = rap[y];
v[nx].push_back(ny);
v[ny].push_back(nx);
}
// cout << bfs() << endl;
printf("%d\n", bfs());
}
return 0;
}