图论 - 最短路 - Dijkstra
图论 - 最短路 - Dijkstra
题目链接: https://www.luogu.org/problem/P4779
代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
const int M = 2e5 + 10;
int n, m, s, dis[N];
bool vis[N];
/*<-----Edge_add----->*/
int tot, head[N], to[M], nxt[M], val[M];
void add(int x, int y, int z) {
to[ ++ tot] = y;
val[tot] = z;
nxt[tot] = head[x];
head[x] = tot;
}
/*<-----Dijkstra----->*/
priority_queue < pair < int, int > > q;
void Dijkstra(int s) {
memset(vis, 0, sizeof vis);
memset(dis, 0x3f, sizeof dis);
dis[s] = 0;
q.push(make_pair(0, s));
while (! q.empty()) {
int now = q.top().second;
if (vis[now]) {
q.pop();
continue ;
}
q.pop();
vis[now] = 1;
for (int i = head[now]; i; i = nxt[i]) {
if (dis[to[i]] > dis[now] + val[i]) {
dis[to[i]] = dis[now] + val[i];
q.push(make_pair(-dis[to[i]], to[i]));
}
}
}
}
int main() {
scanf("%d%d%d", &n, &m, &s);
for (int i = 1; i <= m; i ++ ) {
int x, y, z;
scanf("%d%d%d", &x, &y, &z);
add(x, y, z);
}
Dijkstra(s);
for (int i = 1; i <= n; i ++ ) {
printf("%d ", dis[i]);
}
return 0;
}