小白日记.2 HDU - 4460 Friend Chains
题目大意:如果两个人互为朋友则距离为一,距离可累加,求一群人中任意两个人之间的最短距离的最大值。
常见的BFS
利用邻接表剪枝
代码如下:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <iostream>
#include <string>
#include <map>
using namespace std;
map <string,int> m;
vector <int> gx[1007];
int cc[1007];
int k=0,ok=0,N;
struct node{
int p;
int t;
};
void Bfs(int x)
{
memset(cc,0,sizeof(cc));
queue <node> q;
node now,next;
now.p=x;
now.t=0;
q.push(now);
cc[x]=1;
while(!q.empty()){
now=q.front();
q.pop();
for(int i=0;i<gx[now.p].size();i++){//利用邻接表简化代码
int j=gx[now.p][i];
if(cc[j]==0){
next.p=j;
next.t=now.t+1;
q.push(next);
cc[j]=1;//查重 剪枝
k=max(k,next.t);
}
}
}
for(int i=0;i<N;i++){
if(cc[i]==0){
ok=1;
}
}
}
int main()
{
int c;
string str;
while(cin>>N&&N){
ok=0;
k=0;
m.clear();
for(int i=0;i<N;i++){//初始化
gx[i].clear();
}
for(int i=0;i<N;i++){
cin>>str;
m[str]=i;//将字符串映射为数字
}
cin>>c;
while(c--){
int a1,a2;
cin>>str;
a1=m[str];
cin>>str;
a2=m[str];
gx[a1].push_back(a2);
gx[a2].push_back(a1);//建立邻接表
}
for(int i=0;i<N;i++){
Bfs(i);
if(ok==1) break;
}
if(ok==1)
cout<<-1<<endl;
else
cout<<k<<endl;
}
return 0;
}
总结与收获:
1.邻接表的使用
2.map将字符串映射为数字
3.初始化