Acwing 850-Dijkstra求最短路 II

1.题目:

给定一个 n 个点 m 条边的有向图,图中可能存在重边和自环,所有边权均为非负值。

请你求出 1 号点到 n 号点的最短距离,如果无法从 1 号点走到 n 号点,则输出 −1。

输入格式

第一行包含整数 n 和 m。

接下来 mm 行每行包含三个整数 x,y,z表示存在一条从点 x 到点 y 的有向边,边长为 z。

输出格式

输出一个整数,表示 1 号点到 n 号点的最短距离。

如果路径不存在,则输出 −1。

数据范围

1≤n,m≤1.5×1e5
图中涉及边长均不小于 0,且不超过 10000。

输入样例:

3 3
1 2 2
2 3 1
1 3 4

输出样例:

3

代码:

#pragma GCC optimize(2)
#include<bits/stdc++.h>

using namespace std;

const int N=1.5e5+10;
#define PII pair<int,int>

vector<PII> G[N];
int n,m;
int dist[N];
bool st[N];

int dijkstra()
{
    memset(dist,0x3f,sizeof dist);
    dist[1]=0;

    priority_queue<PII,vector<PII>,greater<> > heap;
    heap.push({0,1});

    while(!heap.empty())
    {
        auto t=heap.top();
        heap.pop();

        int ver=t.second,distance=t.first;
        if(st[ver]) continue;
        
        st[ver]=true;

        for(auto x: G[ver])
        {
            if(dist[x.first]>distance+x.second)
            {
                dist[x.first]=distance+x.second;
                heap.push({dist[x.first],x.first});
            }
        }
    }
    if(dist[n]==0x3f3f3f3f) return -1;
    return dist[n];
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie();cout.tie();
    cin>>n>>m;
    int x,y,z;

    while(m--)
    {
        cin>>x>>y>>z;
        G[x].emplace_back(y,z);
    }

    int t=dijkstra();
    cout<<t<<endl;
    return 0;
}
#include<bits/stdc++.h>

using namespace std;

const int N=1.5e5+10;
#define PII pair<int,int>

vector<PII> G[N];
int n,m;
int dist[N];
bool st[N];

struct hmd{
    int first,second;
};

bool operator <(const hmd &a,const hmd &b)
{
    return a.second>b.second;
}

int dijkstra()
{
    memset(dist,0x3f,sizeof dist);
    dist[1]=0;

    priority_queue<hmd> heap;
    heap.push({1,0});

    while(!heap.empty())
    {
        auto t=heap.top();
        heap.pop();

        int ver=t.first,distance=t.second;
        if(st[ver]) continue;

        st[ver]=true;

        for(auto x: G[ver])
        {
            if(dist[x.first]>distance+x.second)
            {
                dist[x.first]=distance+x.second;
                heap.push({x.first,dist[x.first]});
            }
        }
    }
    if(dist[n]==0x3f3f3f3f) return -1;
    return dist[n];
}

int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>m;
    int x,y,z;

    while(m--)
    {
        cin>>x>>y>>z;
        G[x].emplace_back(y,z);
    }

    int t=dijkstra();
    cout<<t<<endl;
    return 0;
}

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值