AcWing
  • 首页
  • 活动
  • 题库
  • 竞赛
  • 更多
    • 题解
    • 分享
    • 问答
    • 应用
  • App
  • 教育优惠
    New
  • 登录/注册

AcWing 850. Dijkstra求最短路 II    原题链接    简单

作者: 作者的头像   岩专郭启童 ,  2023-11-20 22:14:00 ,  所有人可见 ,  阅读 26


0


#include<iostream>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;

typedef pair<int,int> PII;
const int N=1e6+10;
int h[N],e[N],w[N],ne[N],idx;
int dist[N];
bool st[N];
int n,m;


void add(int a,int b,int c)
{
    e[idx]=b;w[idx]=c;ne[idx]=h[a];h[a]=idx++;
}

int dijkstra()
{
    memset(dist,0x3f,sizeof(dist));
    dist[1]=0;
    priority_queue<PII,vector<PII>,greater<PII>> heap;//<距离,点>//小根堆
    heap.push({0,1});

    while(heap.size())
    {
        auto t=heap.top();
        heap.pop();
        int ver=t.second,distance=t.first;
        //ver:节点编号//distance:源点距离ver的距离
        if(!st[ver])
        {
            st[ver]=true;
            for(int i=h[ver];i!=-1;i=ne[i])
            {
                int j=e[i];      //i->j
                if(dist[j]>dist[ver]+w[i])
                {
                    dist[j]=dist[ver] + w[i];
                    heap.push({dist[j],j});
                }
            }
        }
    }
    if(dist[n]==0x3f3f3f3f) return -1;
    return dist[n];
}

int main()
{
    cin>>n>>m;
    memset(h,-1,sizeof(h));
    while(m--){
        int a,b,c;
        cin>>a>>b>>c;
        add(a,b,c);
    }
    cout<<dijkstra();
}

0 评论

你确定删除吗?

© 2018-2023 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息