HDU-4460.Friend Chains(spfa算法)
Problem Description
For a group of people, there is an idea that everyone is equals to or less than 6 steps away from any other person in the group, by way of introduction. So that a chain of “a friend of a friend” can be made to connect any 2 persons and it contains no more than 7 persons.
For example, if XXX is YYY’s friend and YYY is ZZZ’s friend, but XXX is not ZZZ’s friend, then there is a friend chain of length 2 between XXX and ZZZ. The length of a friend chain is one less than the number of persons in the chain.
Note that if XXX is YYY’s friend, then YYY is XXX’s friend. Give the group of people and the friend relationship between them. You want to know the minimum value k, which for any two persons in the group, there is a friend chain connecting them and the chain’s length is no more than k .
Input
There are multiple cases.
For each case, there is an integer N (2<= N <= 1000) which represents the number of people in the group.
Each of the next N lines contains a string which represents the name of one people. The string consists of alphabet letters and the length of it is no more than 10.
Then there is a number M (0<= M <= 10000) which represents the number of friend relationships in the group.
Each of the next M lines contains two names which are separated by a space ,and they are friends.
Input ends with N = 0.
Output
For each case, print the minimum value k in one line.
If the value of k is infinite, then print -1 instead.
Sample Input
3
XXX
YYY
ZZZ
2
XXX YYY
YYY ZZZ
0
Sample Output
2
spfa算法
求任意两点间的最短路径,Floyd算法可以,但会超时,所以只能用spfa算法来做。
#include <iostream>
#include <unordered_map>
#include <algorithm>
#include <vector>
#include <string>
#include <queue>
using namespace std;
struct Frends{
int v;
int d;
Frends(int v,int d){
this->v = v;
this->d = d;
}
};
const int maxv = 1005;
const int MAXN = 10005;
const int INF = 0x3f3f3f3f;
int t; // 人数
int n; // 朋友关系数
vector<Frends> f[maxv];
bool book[maxv];
int dist[maxv];
unordered_map<string,int> mp;
int spfa(int s,int n){
for(int i = 0;i <= n;i++){
book[i] = false;
dist[i] = INF;
}
queue<int> que;
book[s] = true;
dist[s] = 0;
que.push(s);
while(!que.empty()){
int u = que.front();
que.pop();
book[u] = false;
for(int i = 0;i < (int)f[u].size();i++){
Frends e = f[u][i];
if(dist[e.v] > dist[u] + e.d){
dist[e.v] = dist[u] + e.d;
if(!book[e.v]){
book[e.v] = true;
que.push(e.v);
}
}
}
}
int ans = 0;
for(int i = 1;i <= n;i++){
ans = max(ans,dist[i]);
}
return ans;
}
int main(){
/* freopen("test.txt","r",stdin); */
while(cin >> t && t){
for(int i = 0;i <= t;i++) f[i].clear();
mp.clear();
string u,v;
int cnt = 1;
for(int i = 0; i < t;i++){
string s;
cin >> s;
if(mp[s] == 0) mp[s] = cnt++;
}
cin >> n;
for(int i = 0;i < n;i++){
cin >> u >> v;
f[mp[u]].push_back(Frends(mp[v],1));
f[mp[v]].push_back(Frends(mp[u],1));
}
int ans = 0;
for(int i = 1;i <= t;i++){
ans = max(ans, spfa(i,t));
}
if(ans == INF) cout << -1 << endl;
else cout << ans << endl;
}
return 0;
}