【一个蒟蒻的挣扎】单源最短路(Dijkstra)
赛前没啥时间好好解释了,还有三天2019CSP,大家加油啊!!!
ヾ(◍°∇°◍)ノ゙
背掉它就好啦!!!
我觉得我这一版打得还行就放上来了
#include<cstdio> #include<cstring> #include<iostream> #include<queue> #include<cmath> #include<vector> using namespace std; int n,m,s; int dis[10001],first[10001]; inline void read(int &x) { char c=getchar(); int flag=1; x=0; while (c<'0'||c>'9') { if (c=='-') flag=-1; c=getchar(); } while (c>='0'&&c<='9') { x=x*10+c-'0'; c=getchar(); } x*=flag; } struct edge { int next,to,v; edge() { } edge(int a,int b,int c) { next=a; to=b; v=c; } }E[10004]; struct heap { int to,v; heap() { } heap(int a,int b) { to=a; v=b; } }; priority_queue<heap> h; inline bool operator < (const heap &a,const heap &b) { return a.v>b.v; } int tot; void add_to_edge(int a,int b,int c) { E[++tot]=edge(first[a],b,c); first[a]=tot; } void add_to_heap(int p) { for (int i=first[p]; i; i=E[i].next) { if (dis[E[i].to]==-1) h.push(heap(E[i].to,dis[p]+E[i].v)); } } void dijkstra(int s) { while (!h.empty()) { h.pop(); } memset(dis,-1,sizeof(dis)); dis[s]=0; add_to_heap(s); while (!h.empty()) { if (dis[h.top().to]!=-1) { h.pop(); continue; } int p=h.top().to; dis[p]=h.top().v; h.pop(); add_to_heap(p); } } int main() { read(n); read(m); read(s); for (int i=1; i<=m; i++) { int x,y,z; read(x); read(y); read(z); add_to_edge(x,y,z); } dijkstra(s); for (int i=1; i<=n; i++) cout<<dis[i]<<" "; return 0; }