题意:问给定的一张图中,相距最远的两个点的距离为多少。
解法:跟求树的直径差不多,从1 开始bfs,得到一个最远的点,然后再从该点bfs一遍,得到的最长距离即为答案。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <map>
using namespace std;
#define N 100007 map<string,int> mp;
vector<int> G[];
int vis[],n,m,Maxdis,Maxtag;
struct node{
int dis,u;
}; void dfs(int u)
{
vis[u] = ;
for(int i=;i<G[u].size();i++)
{
int v = G[u][i];
if(!vis[v]) dfs(v);
}
} void bfs(int u)
{
queue<node> que;
memset(vis,,sizeof(vis));
node now;
now.dis = ;
now.u = u;
que.push(now);
vis[u] = ;
while(!que.empty())
{
int SZ = que.size();
while(SZ--)
{
node tmp = que.front();
que.pop();
int dis = tmp.dis;
int u = tmp.u;
if(dis > Maxdis)
{
Maxdis = dis;
Maxtag = u;
}
for(int i=;i<G[u].size();i++)
{
int v = G[u][i];
if(!vis[v])
{
now.u = v;
now.dis = dis+;
vis[v] = ;
que.push(now);
}
}
}
}
} int main()
{
int i,j;
string S;
while(scanf("%d",&n)!=EOF && n)
{
mp.clear();
for(i=;i<=n;i++)
{
cin>>S;
mp[S] = i;
G[i].clear();
}
scanf("%d",&m);
string A,B;
for(i=;i<=m;i++)
{
cin>>A>>B;
int a = mp[A], b = mp[B];
G[a].push_back(b);
G[b].push_back(a);
}
memset(vis,,sizeof(vis));
dfs();
int Link = ;
for(i=;i<=n;i++)
if(!vis[i]) Link = ;
if(!Link)
{
puts("-1");
continue;
}
Maxdis = , Maxtag = -;
bfs();
int S = Maxtag;
Maxdis = , Maxtag = -;
bfs(S);
printf("%d\n",Maxdis);
}
return ;
}