我正在学习最短路,并尝试写了这样一个板子:
#include<bits/stdc++.h>
using namespace std;
int n, m, s, u, w, v, cnt;
int lc[200005], head[200005], vis[200005];
struct edge{
int st, to, next, w;
}e[500005];
void add(int x, int y, int z){
e[cnt++].to = y, e[cnt].st = x, e[cnt].w = z;
e[cnt].next = head[x];
head[x] = cnt;
}
struct po{
int a, b;
};
bool operator < (po x, po y){
return x.b > y.b;
}
void dijkstra(){
for (int i = 1; i <= n; i++){lc[i] = 0x3f3f3f3f;}
lc[s] = 0;
priority_queue <po> q;
po st; st.a = s; st.b = 0;
q.push(st);
while (!q.empty()){
po now = q.top(); q.pop();
if (vis[now.a]) continue;
vis[now.a] = 1;
for (int i = head[now.a]; i; i = e[i].next){
if (lc[e[i].to]>lc[now.a]+e[i].w){
lc[e[i].to] = lc[now.a] + e[i].w;
po jia;
jia.a = e[i].to;
jia.b = lc[e[i].to];
q.push(jia);
}
}
}
}
int main(){
scanf("%d%d%d", &n, &m, &s);
for (int i = 1; i <= m; i++){
scanf("%d%d%d", &u, &v, &w);
add(u, v, w);
}
dijkstra();
for (int i = 1; i <= n; i++) printf("%d ", lc[i]);
return 0;
}
对于样例我的输出是:
4 6 1
1 2 2
2 3 2
2 4 1
1 3 5
3 4 3
1 4 4
0 1061109567 2 5
由于题解中代码风格与我不同,我没能从题解中找到答案。希望有大佬可以解决,并告诉我问题出在哪里,不胜感激:)