hdu 4039 The Social Network bfs
照着题目的意思打代码就行了,这里我是用邻接表建的图。
先把A的所有朋友找到(统称为B),并且标记,再去找B的朋友,如果B的朋友不是A的朋友,按字典序输出出现次数最多的。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <iostream> #include <string> #include <map> #include <queue> using namespace std; map<string,int> m1; map<int,string> m2; struct node{ int to,pre; }Map[100000]; struct Node{ int from,step; }aa; int n,m,k,num,Max,ar[2000],head[2000]; void init() { int i=0,from,to; string a,b; cin>>n>>m; memset(head,-1,sizeof(head)); k=0; while (n--) { cin>>a>>b; if(m1.find(a)==m1.end()) { m1[a]=from=++k; m2[k]=a; } else from=m1[a]; if(m1.find(b)==m1.end()) { m1[b]=to=++k; m2[k]=b; } else to=m1[b]; Map[i].pre=head[from]; Map[i].to=to; head[from]=i++; Map[i].pre=head[to]; Map[i].to=from; head[to]=i++; } } void bfs() { int i,vis[2000]; queue<Node> q; q.push(aa); memset(vis,0,sizeof(vis)); memset(ar,0,sizeof(ar)); vis[aa.from]=1; Max=-1; while (!q.empty()) { aa=q.front();q.pop(); for (i=head[aa.from];i!=-1;i=Map[i].pre) { int to=Map[i].to; if(aa.step==0) { vis[to]=1; Node bb=aa; bb.step++; bb.from=to; q.push(bb); } else if(aa.step==1&&!vis[to]) { ++ar[to]; if(Max<ar[to])Max=ar[to]; } } } } void print() { int i,cnt=0; string s[1005]; if(Max==-1) { cout<<"-"<<endl; return; } for (i=1;i<=k;i++) if(Max==ar[i]) s[cnt++]=m2[i]; sort(s,s+cnt); cout<<s[0]; for (i=1;i<cnt;i++) cout<<" "<<s[i]; cout<<endl; } int main() { int i,T,t=0; string name; cin>>T; while (T--) { init(); cout<<"Case "<<++t<<":"<<endl; for (i=0;i<m;i++) { cin>>name; aa.from=m1[name]; aa.step=0; bfs(); print(); } m1.clear(); m2.clear(); } return 0; }