跳到正文

个人记录

djstl(最短路)模板

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

文章信息

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

版本

  1. v1当前
C++
#include<bits/stdc++.h>
using namespace std;
const int N=100010,M=200010;
int n,m,s,cnt,hd[N],d[N];
bool vis[N];
struct edge{
	int v,w,nxt;
}e[M];
struct node{
    int u;
    int dis;
    bool operator <(const node &x) const
    {
        return x.dis<dis;
    }
};
priority_queue <node> q;
void addedge(int u,int v,int w)
{
	e[++cnt]=edge{v,w,hd[u]};
	hd[u]=cnt;
}
void djstl(int s)
{
	memset(d,-1,sizeof(d));
	q.push(node{s,0});
	d[s]=0;
    while(!q.empty())
    {
    	int u=q.top().u;
    	q.pop();
        if(vis[u]) continue;
    	vis[u]=1;
        for(int i=hd[u];i;i=e[i].nxt)
        {
            int v=e[i].v,w=e[i].w;
            if(d[v]==-1||d[v]>d[u]+w)
            {
                d[v]=d[u]+w;
                q.push(node{v,d[v]});
            }
        }
    }
}
int main()
{
	cin>>n>>m>>s;
	for(int i=1,u,v,w;i<=m;i++)
	{
		scanf("%d%d%d",&u,&v,&w);
		addedge(u,v,w);
	}
	djstl(s);
	for(int i=1;i<=n;i++)
		printf("%d ",d[i]);
	return 0;
}
原文