【模板】单源最短路径(标准版)
题目背景
2018 年 7 月 19 日,某位同学在 NOI Day 1 T1 归程 一题里非常熟练地使用了一个广为人知的算法求最短路。
然后呢?
100→60;
Ag→Cu;
最终,他因此没能与理想的大学达成契约。
小 F 衷心祝愿大家不再重蹈覆辙。
题目描述
给定一个 n 个点,m 条有向边的带非负权图,请你计算从 s 出发,到每个点的距离。
数据保证你能从 s 出发到任意点。
输入格式
第一行为三个正整数 n,m,s。 第二行起 mm 行,每行三个非负整数 ui,vi,wi,表示从 ui 到 vi 有一条权值为 wi 的有向边。
输出格式
输出一行 n 个空格分隔的非负整数,表示 s 到每个点的距离。
#include<bits/stdc++.h>
#define int long long
#define PII pair<int,int>
#define fi first
#define se second
#define pb push_back
#define IOS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std;
const int N = 1e5+10;
int n,m,T;
int A,B;
int dist[N],vis[N];
vector<PII > e[N];
void distra()
{
priority_queue<PII,vector<PII>,greater<PII>> q;
for(int i=1;i<=n;i++) dist[i] = 1e18;
q.push({0,A});
dist[A] = 0;
while(q.size())
{
auto t = q.top();q.pop();
int now = t.se,dis = t.fi;
if(vis[now]==1) continue;
vis[now] = 1;
for(auto tt:e[now])
{
int spot = tt.se,w = tt.fi;
if(dist[spot]>dist[now]+w)
{
dist[spot] = dist[now]+w;
q.push({dist[spot],spot});
}
}
}
}
signed main()
{
IOS;
cin>>n>>m>>A;
while(m--)
{
int a,b,c;
cin>>a>>b>>c;
e[a].pb({c,b});
}
distra();
for(int i=1;i<=n;i++) cout<<dist[i]<<" ";
return 0;
}
道路重建
题目描述
从前,在一个王国中,在 n 个城市间有 m 条道路连接,而且任意两个城市之间至多有一条道路直接相连。在经过一次严重的战争之后,有 d 条道路被破坏了。国王想要修复国家的道路系统,现在有两个重要城市 A 和 B 之间的交通中断,国王希望尽快的恢复两个城市之间的连接。你的任务就是修复一些道路使 A 与 B 之间的连接恢复,并要求修复的道路长度最小。
输入格式
输入文件第一行为一个整数 n (2<n≤100),表示城市的个数。这些城市编号从 1 到 n。