Friend Chains
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 96 Accepted Submission(s): 41
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 .
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.
If the value of k is infinite, then print -1 instead.
3 XXX YYY ZZZ 2 XXX YYY YYY ZZZ 0
2
#include<cstdio>
#include<map>
#include<queue>
#include<string>
#include<iostream>
using namespace std;
const int N=1001;
const int M=20001;
const int INF=0x3f3f3f3f;
map<string,int> hs;
int dis[N],head[M],v[M],nxt[M],n,cnt;
void add(int a,int b)
{
v[cnt]=b;
nxt[cnt]=head[a];
head[a]=cnt++;
}
void spfa(int s)
{
int i,p,q,he=0,ta=1,Q[N];
bool inQ[N];
for(i=0;i<n;i++){dis[i]=INF;inQ[i]=0;}
Q[0]=s;inQ[s]=1;dis[s]=0;
while(he!=ta)
{
p=Q[he++];inQ[p]=0;
for(i=head[p];i!=-1;i=nxt[i])
{
q=v[i];
if(dis[q]>dis[p]+1)
{
dis[q]=dis[p]+1;
if(!inQ[q]){Q[ta++]=q;inQ[q]=1;if(ta==N)ta=0;}
}
}
if(he==N)he=1;
}
}
/*void spfa(int s)
{
int i,p;
queue<int> Q;
bool inQ[N];
for(i=0;i<n;i++){dis[i]=INF;inQ[i]=0;}
Q.push(s);dis[s]=0;inQ[s]=1;
while(!Q.empty())
{
s=Q.front();Q.pop();inQ[s]=0;
for(i=head[s];i!=-1;i=nxt[i])
{
p=v[i];
if(dis[p]>dis[s]+1)
{
dis[p]=dis[s]+1;
if(!inQ[p]){Q.push(p);inQ[p]=1;}
}
}
}
}*/
int main()
{
string s1,s2;
int i,j,m;
while(scanf("%d",&n),n)
{
cnt=0;hs.clear();
memset(head,-1,sizeof(head));
for(i=0;i<n;i++){cin>>s1;hs[s1]=i;}
scanf("%d",&m);
while(m--)
{
cin>>s1>>s2;
int a=hs[s1],b=hs[s2];
add(a,b);
add(b,a);
}
int ans=0;
for(i=0;i<n;i++)
{
spfa(i);
for(j=0;j<n;j++)ans=max(ans,dis[j]);
}
if(ans==INF)puts("-1");
else printf("%d\n",ans);
}
return 0;
}
6586



被折叠的 条评论
为什么被折叠?



