HDU - 4460 Friend Chains(邻接表&BFS)

小白日记.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.初始化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值