HDU6386 Age of Moyu BFS+优先队列

HDU6386 Age of Moyu

 BFS+优先队列

#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
const int MAX=1e5+5;
const int INF=0x3f3f3f3f;
struct E
{
    int to,nxt,c;
}e[MAX*4];
int cnt[MAX],head[MAX],tot,n,m;
inline void init()
{
    memset(head,-1,sizeof(head));
    memset(cnt,INF,sizeof(cnt));
    tot=0;
}
inline void add(int u,int v,int c)
{
    e[tot].to=v;
    e[tot].c=c;
    e[tot].nxt=head[u];
    head[u]=tot++;
    e[tot].to=u;
    e[tot].c=c;
    e[tot].nxt=head[v];
    head[v]=tot++;
}
struct nod
{
    int x,c,v;
    nod(){}
    nod(int a,int b,int d){x=a;c=b;v=d;}
    nod(const nod& a){x=a.x;c=a.c;v=a.v;}
};
struct cmp
{
    bool operator()(const nod &a,const nod &b)const
    {
        return a.v>b.v;
    }
};
priority_queue<nod,vector<nod>,cmp>q;
int bfs()
{
    while(!q.empty()) q.pop();
    q.push(nod(1,0,0));cnt[1]=0;
    nod now;
    while(!q.empty())
    {
        now=q.top();q.pop();
        if(now.x==n) return now.v;
        for(int i=head[now.x];i!=-1;i=e[i].nxt)
        {
            if(now.c!=e[i].c)
            {
                if(cnt[e[i].to]<=now.v+1) continue;
                cnt[e[i].to]=now.v+1;
                q.push(nod(e[i].to,e[i].c,now.v+1));
            }
            else
            {
                if(cnt[e[i].to]<=now.v) continue;
                cnt[e[i].to]=now.v;
                q.push(nod(e[i].to,now.c,now.v));
            }
        }
    }
    return -1;
}
int main()
{
//    freopen("1.in","r",stdin);
//    freopen("out.txt","w",stdout);
    int u,v,c;
    while(~scanf("%d%d",&n,&m))
    {
        init();
        for(int i=0;i<m;i++)
        {
            scanf("%d%d%d",&u,&v,&c);
            add(u,v,c);
        }
        printf("%d\n",m==0?-1:bfs());
    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值