最短路模板

Dijkstra

#include <bits/stdc++.h>
#define pii pair<int,int>
using namespace std;
const int N=1e5+5;
vector<vector<pair<int,int>>> G;
int n,m,s;
priority_queue<pii,vector<pii>,greater<pii>> q;
int dis[N],vis[N];
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cin>>n>>m>>s;
    memset(dis,0x3f,sizeof(dis));
    G.resize(n+1);
    for(int i=1;i<=m;i++)
    {
        int u,v,w;
        cin>>u>>v>>w;
        G[u].push_back({v,w});
    }
    dis[s]=0;
    q.push({dis[s],s});
    while(!q.empty())
    {
        int u=q.top().second;
        q.pop();
        if(vis[u])  //记住vis用来看是否走过
            continue;
        vis[u]=1;
        for(auto pai:G[u])
        {
            int v=pai.first,w=pai.second;
            if(dis[v]>dis[u]+w)
            {
                dis[v]=dis[u]+w;
                q.push({dis[v],v});
            }
        }
    }
    for(int i=1;i<=n;i++)
        cout<<dis[i]<<' ';
}

SPFA

#include <bits/stdc++.h>
using namespace std;
const int N=1e5+5;
int n,m,s;
vector<vector<pair<int,int>>> G;
queue<int> q;
int dis[N],inq[N];
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cin>>n>>m>>s;
    memset(dis,0x3f,sizeof(dis));
    dis[s]=0;
    q.push(s);
    G.resize(n+1);
    for(int i=1;i<=m;i++)
    {
        int u,v,w;
        cin>>u>>v>>w;
        G[u].push_back({v,w});
    }
    while(!q.empty())
    {
        int u=q.front();
        q.pop();
        inq[u]=0;
        for(auto pai:G[u])
        {
            int v=pai.first,w=pai.second;
            if(dis[v]>dis[u]+w)
            {
                dis[v]=dis[u]+w;
                inq[v]=1;
                q.push(v);
            }
        }
    }
    for(int i=1;i<=n;i++)
        cout<<dis[i]<<' ';
}
posted @ 2025-11-01 10:53  wtnbl  阅读(4)  评论(0)    收藏  举报