跳到正文

个人记录

SPFA优化Dijkstra

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

文章信息

收录
2025年12月12日
更新
2026年4月26日
篇幅
约 2 分钟
获赞
1

版本

  1. v1当前
C++
#include <bits/stdc++.h>
using namespace std;
const int N=2e5+8,K=0x3f3f3f3f;
struct node{
    int x,u,fa;
    bool operator<(const node& other)const{return u>other.u;}
};
priority_queue <node> sta;
struct G{int x,u;};
vector <G> a[N];
int n,m,s,ans[N];
void Dijkstra(){
    ans[s]=0,sta.push({s,0,0});
    while (!sta.empty()){
        node t=sta.top();
        sta.pop();
        for (G v:a[t.x])
            if (ans[v.x]>t.u+v.u&&v.x!=t.fa)
                ans[v.x]=t.u+v.u,sta.push({v.x,ans[v.x],t.x});
    }
}
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    cin >>n>>m>>s;
    memset(ans,K,sizeof(ans));
    for (int i=1,x,y,z;i<=m;i++){
        cin >>x>>y>>z;
        a[x].push_back({y,z});
        a[y].push_back({x,z});
    }Dijkstra();
    for (int i=1;i<=n;i++) cout <<ans[i]<<" ";
    return 0;
}
原文