Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- const int N = 1e5;
- int n, m;
- vector<pair<int, int>> g[N];
- pair<vector<int>, vector<int>> dijkstra(int s) {
- vector<int> dis(n + 1, INT_MAX), par(n + 1, -1);
- priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
- dis[s] = 0;
- pq.push({0, s});
- while (!pq.empty()) {
- auto [d, u] = pq.top();
- pq.pop();
- if (dis[u] < d) continue;
- for (auto [v, w] : g[u]) {
- if (d + w < dis[v]) {
- dis[v] = d + w;
- pq.push({dis[v], v});
- par[v] = u;
- }
- }
- }
- return {dis, par};
- }
- void solve()
- {
- cin >> n >> m;
- for (int i = 1; i <= m; i++) {
- int u, v, w;
- cin >> u >> v >> w;
- g[u].push_back({v, w});
- g[v].push_back({u, w});
- }
- auto [dis, par] = dijkstra(1);
- int q;
- cin >> q;
- while (q--) {
- int d;
- cin >> d;
- cout << dis[d] << '\t';
- vector<int> path;
- while (d != -1) {
- path.push_back(d);
- d = par[d];
- }
- reverse(path.begin(), path.end());
- for (int i = 0; i < path.size() - 1; i++) {
- cout << path[i] << " -> ";
- }
- cout << path.back() << '\n';
- }
- }
- int main()
- {
- int t = 1;
- // cin >> t;
- for (int i = 1; i <= t; i++)
- {
- solve();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment