洛谷 P4779 【模板】单源最短路径(标准版)
Description
给定一个 N 个点,M 条有向边的带非负权图,请你计算从 S 出发,到每个点的距离。
数据保证你能从 S 出发到任意点。
1≤N≤100000;
1≤M≤200000;
S=1
1≤ui,vi≤N
0≤wi≤10的9次方
0≤∑wi≤10的9次方
Input
- 第一行为三个正整数 N,M,S。
第二行起 M 行,每行三个非负整数 ui,vi,wi,表示从 ui 到 vi 有一条权值为 wi 的边。
Output
- 输出一行 N 个空格分隔的非负整数,表示 S 到每个点的距离。
Sample Input
4 6 1
1 2 2
2 3 2
2 4 1
1 3 5
3 4 3
1 4 4
Sample Output
0 2 4 3
题解:
- 一道dijskra的板子题。我居然拖了一年才学… …
- 挺简单的。朴素dijskra的过程如下:
- 初始化dis[start]=0,其余节点的dis值为无穷大.
- 找一个dis值最小的蓝点x,把节点x变成白点.
- 遍历x的所有出边(x,y,z)若dis[y]>dis[x]+z, 则令dis[y]=dis[x]+z
- 重复2,3两步,直到所有点都成为白点...
- 时间是O(n方)的,主要问题出在第2步上。所以这时用一个堆维护最小值就行了
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#define N 100005
#define M 200005
using namespace std;
struct Node
{
int val, pos;
friend bool operator<(Node x, Node y) {
return x.val > y.val;
}
};
struct E {int next, to, dis;} e[M];
int n, m, s, num;
int h[N], dis[N];
bool vis[N];
int read()
{
int x = 0; char c = getchar();
while(c < '0' || c > '9') c = getchar();
while(c >= '0' && c <= '9') {x = x * 10 + c - '0'; c = getchar();}
return x;
}
void add(int u, int v, int w)
{
e[++num].next = h[u];
e[num].to = v;
e[num].dis = w;
h[u] = num;
}
void dijskra()
{
priority_queue<Node> que;
memset(dis, 0x3f, sizeof(dis));
dis[s] = 0, que.push((Node){0, s});
while(!que.empty())
{
int x = que.top().pos;
que.pop();
if(vis[x]) continue;
vis[x] = 1;
for(int i = h[x]; i != 0; i = e[i].next)
if(dis[x] + e[i].dis < dis[e[i].to])
{
dis[e[i].to] = dis[x] + e[i].dis;
if(!vis[e[i].to]) que.push((Node){dis[e[i].to], e[i].to});
}
}
}
int main()
{
cin >> n >> m >> s;
for(int i = 1; i <= m; i++)
{
int u = read(), v = read(), w = read();
add(u, v, w);
}
dijskra();
for(int i = 1; i <= n; i++) printf("%d ", dis[i]);
return 0;
}