1. 程式人生 > 其它 >【模板】單源最短路徑(標準版)

【模板】單源最短路徑(標準版)

P4779 【模板】單源最短路徑(標準版) - 洛谷 | 電腦科學教育新生態 (luogu.com.cn)

題目背景

2018 年 7 月 19 日,某位同學在 NOI Day 1 T1 歸程 一題裡非常熟練地使用了一個廣為人知的演算法求最短路。

然後呢?

100 \rightarrow 6010060;

\text{Ag} \rightarrow \text{Cu}AgCu;

最終,他因此沒能與理想的大學達成契約。

小 F 衷心祝願大家不再重蹈覆轍。

題目描述

給定一個 nn 個點,mm 條有向邊的帶非負權圖,請你計算從 ss 出發,到每個點的距離。

資料保證你能從 ss 出發到任意點。

輸入格式

第一行為三個正整數 n, m, sn,m,s。 第二行起 mm 行,每行三個非負整數 u_i, v_i, w_iui,vi,wi,表示從 u_iui 到 v_ivi 有一條權值為 w_iwi 的有向邊。

輸出格式

輸出一行 nn 個空格分隔的非負整數,表示 ss 到每個點的距離。

輸入輸出樣例

輸入 #1
4 6 1
1 2 2
2 3 2
2 4 1
1 3 5
3 4 3
1 4 4
輸出 #1
0 2 4 3

說明/提示

樣例解釋請參考 資料隨機的模板題

1 \leq n \leq 10^51n105;

1 \leq m \leq 2\times 10^51m2×105;

s = 1s=1;

1 \leq u_i, v_i\leq n1ui,vin;

0 \leq w_i \leq 10 ^ 90wi109,

0 \leq \sum w_i \leq 10 ^ 90wi109。

本題資料可能會持續更新,但不會重測,望周知。

2018.09.04 資料更新 from @zzq

做做模板題圖一樂哈哈

裸的dijkstra

#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
typedef pair<int,int> PAII;
const int N=1e7+10; int h[N],e[N],ne[N],idx,dist[N],w[N]; bool st[N]; int n,m,s; void add(int a,int b,int c) { e[idx]=b; w[idx]=c; ne[idx]=h[a]; h[a]=idx++; } void dijkstra(int x){ priority_queue<PAII,vector<PAII>,greater<PAII> >heap; memset(dist,0x3f,sizeof(dist)); dist[x]=0; heap.push({0,x}); while(heap.size()) { auto t=heap.top(); heap.pop(); int dis=t.first,ver=t.second; if(st[ver]) continue; else st[ver]=true; for(int i=h[ver];i!=-1;i=ne[i]) { int j=e[i]; if(dist[j]>dist[ver]+w[i]) { dist[j]=dist[ver]+w[i]; if(!st[j]) { heap.push({dist[j],j}); } } } } } int main(){ memset(h,-1,sizeof(h)); cin>>n>>m>>s; while(m--) { int a,b,c; cin>>a>>b>>c; add(a,b,c); } dijkstra(s); for(int i=1;i<=n;i++) cout<<dist[i]<<" "; return 0; }