【模板】SSSP

时间复杂度\(O(m*log(n))\)

代码如下:

#include <bits/stdc++.h>
using namespace std;
const int maxv=1e5+10;
const int maxe=2e5+10;
const int inf=0x3f3f3f3f;

inline int read(){
    int x=0,f=1;char ch;
    do{ch=getchar();if(ch=='-')f=-1;}while(!isdigit(ch));
    do{x=x*10+ch-'0';ch=getchar();}while(isdigit(ch));
    return f*x;
}

struct edge{
    int nxt,to,w;
}e[maxe];
int tot=1,head[maxv];
inline void add_edge(int from,int to,int w){
    e[++tot]=edge{head[from],to,w},head[from]=tot;
}

int n,m,st,d[maxv];
bool vis[maxv];

void read_and_parse(){
    n=read(),m=read(),st=read();
    for(int i=1,a,b,c;i<=m;i++){
        a=read(),b=read(),c=read();
        add_edge(a,b,c);
    }
}
typedef pair<int,int> P;
priority_queue<P>q;

void solve(){
    memset(d,0x3f,sizeof(d));
    d[st]=0;q.push(make_pair(0,st));
    while(q.size()){
        int u=q.top().second;q.pop();
        if(vis[u])continue;
        vis[u]=1;
        for(int i=head[u];i;i=e[i].nxt){
            int v=e[i].to,w=e[i].w;
            if(d[v]>d[u]+w){
                d[v]=d[u]+w;
                q.push(make_pair(-d[v],v));
            }
        }
    }
    for(int i=1;i<=n;i++)printf("%d%c",d[i],i==n?'\n':' ');
}

int main(){
    read_and_parse();
    solve();
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/wzj-xhjbk/p/9810611.html