dij 52分求调

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

Digital_Sunrise @ 2024-07-11 10:45:34

#include <bits/stdc++.h>
//#define int long long
using namespace std;
const int _ = 1e5 + 5;

inline int read()
{
    int w = 1,f = 0;
    char c = getchar();
    while(c < '0' or c > '9'){if(c == '-') w = -1;c = getchar();}
    while(c >= '0' and c <= '9'){f = f * 10 + c - '0';c = getchar();}
    return w * f;
}

int n,m,s;

struct node
{
    int x,dis;
    node(int x1,int dis1):dis(dis1),x(x1){}
    bool operator < (const node &tmp)const
    {
        return dis > tmp.dis;
    }
};

priority_queue <node> q;
bool vis[_];
int dis[_];
vector <int> G[_];
vector <int> W[_];

void dij()
{
    q.push(node(s,0));
    dis[s] = 0;
    while(!q.empty())
    {
        int u = q.top().x;
        q.pop();
        if(vis[u])
            continue;
        vis[u] = 1;
        for(int i = 0;i < G[u].size();i++)
        {
            int v = G[u][i];
            int w = W[u][i];
            dis[v] = min(dis[v],dis[u] + w);
            if(!vis[v])
                q.push(node(v,dis[v]));
        }
    }
}

signed main()
{
    n = read();
    m = read();
    s = read();
    memset(dis,0x3f,sizeof dis);
    for(int i = 1;i <= m;i++)
    {
        int u = read(),v = read(),w = read();
        G[u].push_back(v);
        G[v].push_back(u);
        W[u].push_back(w);
        W[v].push_back(w);
    }
    dij();
    for(int i = 1;i <= n;i++)
        printf("%d ",dis[i]);
    return 0;
}

by WRuperD @ 2024-07-11 10:51:26

@Digital_Sunrise 有向边


by Digital_Sunrise @ 2024-07-11 10:55:58

@WRuperD 草大师我悟了


by eb0ycn @ 2024-07-11 13:08:11

@Digital_Sunrise 快写 spfa


by stils @ 2024-07-19 16:47:04

草我也是


|