跳到正文

个人记录

Dijkstra算法代码

willAK约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟

版本

  1. v2当前
  2. v1

P4779 【模板】单源最短路径(标准版) code:code:

C++
#include<bits/stdc++.h>
using namespace std;
int from[100010],to[200010],net[200010],v[200010],cnt,d[100010];
bool b[100010];
void add(int x,int y,int w)
{
    to[++cnt]=y;
    v[cnt]=w;
    net[cnt]=from[x];
    from[x]=cnt;
}
priority_queue <pair<int,int> > q;
int main()
{
    int n,m,s;
    cin>>n>>m>>s;
    for(int i=1;i<=m;i++)
	{
		int x,y,z;
        cin>>x>>y>>z;
        add(x,y,z);
    }
    for(int i=1;i<=n;i++)
    {
    	d[i]=1e9;
	}
    d[s]=0;
    q.push({0,s});
    while(!q.empty())
	{
        int x=q.top().second;
        q.pop();
        if(b[x]) continue;
        b[x]=1;
        for(int i=from[x];i;i=net[i])
		{
            int y=to[i],l=v[i];
            if(d[y]>d[x]+l)
			{
                d[y]=d[x]+l;
                q.push({-d[y],y});
            }
        }
    }
    for(int i=1;i<=n;i++)
	{
		cout<<d[i]<<" ";
	}
    return 0;
}
原文