題意:
小瘋子和小傻子是好朋友,今天他們玩一個關於朋友的遊戲:
從一個有 n 個人的花名冊裏面求出一個最小的 k 值,任意兩個人通過小於k個人介紹認識的。(任意兩個人認識的是由最少的人介紹決定的。)
如果 a 和 b 是朋友, b 和 c 是朋友,那麼 a 和 c 成爲朋友是通過 b 介紹認識的。
好難啊,來幫幫小傻子!!!思路:
bfs就出來了。
其中這裏學到了:
(1).map<string, int> mp;
的映射,要不是知道了這個,不知道這道題要多麻煩才能解出來。
(2).ios::sync_with_stdio(0); cin.tie(0);
確實是比scanf(), printf()
快一些,但是唯一的侷限就是,輸入輸出只能使用,cin>>, cout<<
輸出換行也只能使用\n
。複雜度:
時間複雜度:O(n^2 * lg(n))
空間複雜度:O(n^2)代碼
/* ***********************************************
Author :Ilovezilian
Created Time :2015/9/2 22:52:10
File Name :1007_1.cpp
************************************************ */
#include <bits/stdc++.h>
using namespace std;
const int N = 1010, mod = 1e9+7, INF = 1000001;
map<string, int> mp;
int n, dis[N][N];
vector<int> G[N];
bool vis[N];
queue<int> q;
void bfs(int x)
{
memset(vis, 0, sizeof(vis[0]) * n);
while(!q.empty()) q.pop();
vis[x] = 1;
dis[x][x] = 0;
q.push(x);
while(!q.empty())
{
int u = q.front();
q.pop();
int sz = G[u].size();
for(int j = 0; j < sz; j ++) if(!vis[G[u][j]])
{
int v = G[u][j];
q.push(v);
vis[v] = 1;
dis[x][v] = dis[x][u] + 1;
}
}
}
void solve()
{
string s1, s2;
while(cin>>n && n)
{
mp.clear();
for(int i = 0; i < n; i ++) G[i].clear();
for(int i = 0; i < n; i ++)
{
cin>>s1;
mp[s1] = i;
}
int m;
cin>>m;
for(int i = 0; i < m; i ++)
{
cin>>s1>>s2;
int x = mp[s1], y = mp[s2];
G[x].push_back(y);
G[y].push_back(x);
}
for(int i = 0; i < n; i ++) for(int j = 0; j < n; j ++) dis[i][j] = INF;
dis[0][0] = 0;
for(int i = 0; i < n; i ++) bfs(i);
int ans = 0;
for(int i = 0; i < n; i ++) for(int j = i + 1; j < n; j ++) ans = max(ans, dis[i][j]);
if(ans == INF) ans = -1;
cout<<ans<<'\n';
//cout<<flush;開始以爲要加這個
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
//freopen("","r",stdin);
//freopen("","w",stdout);
solve();
return 0;
}