求最短路(堆優化)
#include <bits/stdc++.h>
using namespace std;
#define LL long long
int main(){
ios::sync_with_stdio(false);cin.tie(0);
int n, m;
cin >> n >> m;
vector < vector <pair<LL, int> > > g(n + 1);
for (int i = 1; i <= m; i ++ ){
int u, v, w;
cin >> u >> v >> w;
g[u].push_back({w, v});
}
auto dijkstra = [&](){
vector <LL> dis(n + 1, 1e9);
vector <bool> vis(n + 1, false);
dis[1] = 0;
priority_queue < pair<int, int>, vector< pair<int, int> >, greater< pair<int, int> > > q;
q.push({0, 1});
while(q.size()){
auto t = q.top();
q.pop();
int u = t.second;
if (vis[u]) continue;
vis[u] = true;
for (auto [w, v] : g[u]){
if (dis[v] > dis[u] + w){
dis[v] = dis[u] + w;
q.push({dis[v], v});
}
}
}
if (dis[n] == 1e9) cout << "-1\n";
else cout << dis[n] << "\n";
};
dijkstra();
return 0;
}
Acwing 模板:https://www.acwing.com/problem/content/852/
計算最短路的數量
題目鏈接
http://acm.zjgsu.edu.cn/contests/117/problems/0
題目大意:
輸入 \(n, m, s, e\),分別表示點的數量、邊的數量、起點和終點。點的編號從 0 開始,第二行輸入每個點的快樂值(權重)。接下來 \(m\) 行每行輸入三個數,\(u, v, w\),表示從 \(u\) 到 \(v\) 有一條長為 \(w\) 的邊。
輸出從起點到終點的最短路的數量以及最短路的最大快樂值。
代碼:
#include <bits/stdc++.h>
using namespace std;
#define LL long long
#define fi first
#define se second
#define PLL pair <LL, LL>
#define pb push_back
const int N = 1e3 + 10;
LL s, e, n, m, dis[N], v[N], w[N], cnt[N], ans[N];
vector <PLL> g[N];
void dijkstra(){
memset(dis, 0x3f, sizeof dis);
dis[s] = 0;
priority_queue< PLL, vector<PLL>, greater<PLL> > q;
q.push( {0, s} );
while ( q.size() ){
PLL t = q.top();
q.pop();
LL x = t.se;
if (v[x]) continue;
v[x] = 1;
for (auto tt : g[x]){
LL d = tt.fi, y = tt.se;
if (dis[y] > dis[x] + d){
dis[y] = dis[x] + d;
cnt[y] = cnt[x];
ans[y] = ans[x] + w[y];
q.push( {dis[y], y} );
}
else if (dis[y] == dis[x] + d){
cnt[y] += cnt[x];
ans[y] = max(ans[y], ans[x] + w[y]);
}
}
}
}
int main(){
cin >> n >> m >> s >> e;
for (int i = 0; i < n; ++ i)
scanf("%lld", &w[i]);
for (int i = 1; i <= m; ++ i){
LL a, b, c;
scanf("%lld%lld%lld", &a, &b, &c);
g[a].pb( {c, b} );
g[b].pb( {c, a} );
}
cnt[s] = 1;
ans[s] = w[s];
dijkstra();
cout << cnt[e] << " " << ans[e] << "\n";
return 0;
}
浙公網安備 33010602011771號