#include<bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 5;
const int INF = 0x3f3f3f3f;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int , int>>> pq;
vector<pair<long long, int>> to[maxn];
long long dist[maxn];
bool vis[maxn];
void dij() {
memset(dist, 0x3f, sizeof(dist));
dist[1] = 0;
pq.push({0, 1});
while (!pq.empty()) {
int x = pq.top().second;
pq.pop();
if (vis[x]) continue;
vis[x] = true;
for (auto [y, w] : to[x]) {
if (dist[y] > dist[x] + w) {
dist[y] = dist[x] + w;
pq.push({dist[y], y});
}
}
}
}
int main() {
int n, m; cin >> n >> m;
for (int i = 1; i <= m; ++i) {
int x, y, z; cin >> x >> y >> z;
to[x].push_back({y, z});
to[y].push_back({x, z});
}
dij();
int q; cin >> q;
while (q--) {
long long s, t; cin >> s >> t;
cout << dist[s] + dist[t] << "\n";
}
return 0;
}
迪杰斯特拉堆优化
最新推荐文章于 2024-08-25 18:17:58 发布