前言
考试前几天才发现一直写的Dijkstra是错的,有点惭愧,现在打了个板子放在这里,以示后人
题目链接 : https://www.luogu.org/problem/P4779
Code
1 #include <iostream>
2 #include <cstdio>
3 #include <queue>
4 #include <cstring>
5 using namespace std;
6 typedef long long ll;
7 const int N=100002;
8 const int M=200002;
9 const int inf=2147483647;
10 inline int read()
11 {
12 char ch=getchar();
13 int x=0;bool f=false;
14 while (!isdigit(ch)) f^=!(ch^45),ch=getchar();
15 while (isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
16 if (f) x=-x;return x;
17 }
18 int n,m,s;
19 int head[N],to[M],nex[M],cnt=0;
20 ll val[M];
21 ll dis[N];
22 bool vis[N];
23 struct data
24 {
25 int id;
26 ll v;
27 bool operator <(const data&A)const
28 {
29 return A.v<v;
30 }
31 };
32 inline void add(int s,int ed,ll w)
33 {
34 to[++cnt]=ed;
35 val[cnt]=w;
36 nex[cnt]=head[s];
37 head[s]=cnt;
38 }
39 inline void Dijkstra(int st)
40 {
41 priority_queue<data>q;
42 for (int i=1;i<=n;++i)
43 dis[i]=inf;
44 dis[st]=0;
45 q.push((data){st,dis[st]});
46 while (!q.empty())
47 {
48 int now=q.top().id;
49 q.pop();
50 if (vis[now]) continue;
51 vis[now]=true;
52 for (int i=head[now];i;i=nex[i])
53 {
54 int v=to[i];
55 if (!vis[v]&&dis[v]>dis[now]+val[i])
56 {
57 dis[v]=dis[now]+val[i];
58 q.push((data){v,dis[v]});
59 }
60 }
61 }
62 }
63 int main()
64 {
65 n=read(),m=read(),s=read();
66 int x,y,z;
67 for (int i=1;i<=m;++i)
68 {
69 x=read(),y=read(),z=read();
70 add(x,y,z);
71 }
72 Dijkstra(s);
73 for (int i=1;i<=n;++i)
74 printf("%lld ",dis[i]);
75 return 0;
76 }