运用Floyd建立联系,其实挺水的,一开始没有考虑全面导致wa了两次,做题太心急,其实两个人认识是有很多种不同的方式的,关键就在于如何找出最少的那一条,另外如何保存两个人需要经过多少个人介绍才能认识也是关键,这里我用一个二维数组num[][]保存介绍人数,剩下的问题迎刃而解
代码:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cmath>
using namespace std;
bool mapp[205][205];
int num[205][205];//保存介绍人数
int main()
{
int mm, n;
while(scanf("%d%d",&n,&mm) != EOF){
map<string, int> m;
memset(num, 0, sizeof(num));
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= n; j ++)
if(i == j) mapp[i][j] = 1;
else mapp[i][j] = 0;
int cnt = 0;
string aa, bb;
for(int i = 1; i <= mm; i ++)
{
cin>>aa>>bb;
if(! m[aa]) m[aa] = ++ cnt;
if(! m[bb]) m[bb] = ++ cnt;
mapp[m[aa]][m[bb]] = mapp[m[bb]][m[aa]] = 1;
}
for(int k = 1; k <= n; k ++)
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= n; j ++)
{
if(mapp[i][k] && mapp[k][j] && ! mapp[i][j])//特判第一次
{
mapp[i][j] = mapp[j][i] = 1;
num[i][j] = num[j][i] = (num[i][k] + num[k][j] + 1);
continue;
}
if(mapp[i][k] && mapp[k][j])//之后寻求每一条可能路径的最小值
{
num[i][j] = min((num[i][k] + num[k][j] + 1), num[i][j]);
num[j][i] = num[i][j];
}
}
int maxy = 0;
int flag = 0;
for(int i = 1; i <= n; i ++)
{
for(int j = 1; j <= n; j ++)
{
if(mapp[i][j] == 0)
{
flag = 1;
break;
}
maxy = max(maxy, num[i][j]);
}
}
if(flag == 1) printf("No\n");
else
printf("%d\n",maxy);
}
return 0;
}