单源最短路径(优化dij)

请编写程序求给定正权有向图的单源最短路径长度。图中包含n个顶点,编号为0至n-1,以顶点0作为源点。

输入格式:

输入第一行为两个正整数n和e,分别表示图的顶点数和边数,其中n不超过20000,e不超过1000。接下来e行表示每条边的信息,每行为3个非负整数a、b、c,其中a和b表示该边的端点编号,c表示权值。各边并非按端点编号顺序排列。

输出格式:

输出为一行整数,为按顶点编号顺序排列的源点0到各顶点的最短路径长度(不含源点到源点),每个整数后一个空格。如源点到某顶点无最短路径,则不输出该条路径长度。

输入样例:

4 4
0 1 1
0 3 1
1 3 1
2 0 1

输出样例:

1 1 
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<int,int> pII;
const int N=2e4+2;
const int INF=0x3f3f3f3f;
vector<pII> g[N];
priority_queue<pII,vector<pII>,greater<pII> >q;
int n,m;
int dist[N];
bool vis[N];
void dij(int s)
{
    for(int i=0;i<n;i++)
    {
        dist[i]=INF;
    }
    dist[s]=0;
    q.push({0,s});
    while (!q.empty())
    {
        int w=q.top().first;
        int u=q.top().second;
        q.pop();
        if(vis[u]) continue;
        vis[u]=true;
        for(int i=0;i<g[u].size();i++)
        {
            pII temp=g[u][i];
            if(dist[temp.first]>(w+temp.second))
            {
                dist[temp.first]=(w+temp.second);
                q.push({dist[temp.first],temp.first});
            }
        }
    }
    
}
int main()
{
    int u,v,w;
    cin>>n>>m;
    for(int i=0;i<m;i++)
    {
        cin>>u>>v>>w;
        g[u].push_back({v,w});
    }
    dij(0);
    for(int i=1;i<n;i++)
    {
        if(dist[i] !=INF)
        {
            cout<<dist[i]<<" ";
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值