Advertisement
shimulxx

sample sakim

Jul 20th, 2020
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. struct myself { int first, second; };
  4. bool operator<(const myself &a, const myself &b) { return a.second > b.second; }
  5. int main() {
  6.     //freopen("input.txt", "r", stdin);
  7.     ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  8.     int n, e; cin >> n >> e;
  9.     vector<vector<myself>> adV(n + 1);
  10.     unordered_map<int, bool> visited;
  11.     for (int i = 1; i <= e; ++i) {
  12.         int a, b, cost; cin >> a >> b >> cost;
  13.         adV[a].push_back({ b,cost }); adV[b].push_back({ a, cost });
  14.     }
  15.     vector<int> parent(n + 1, 0), distTance(n + 1, INT32_MAX);
  16.     bool flag = false;
  17.     priority_queue<myself> s;
  18.     s.push({ 1, 0 });
  19.     while (!s.empty()) {
  20.         myself p = s.top(); s.pop();
  21.         int curNode = p.first, curCost = p.second;
  22.         visited[curNode] = true;
  23.         if (curNode == n) { flag = true; break; }
  24.         for (auto des : adV[curNode]) {
  25.             if (!visited[des.first]) {
  26.                 int totalCost = curCost + des.second;
  27.                 if (totalCost < distTance[des.first]) {
  28.                     distTance[des.first] = totalCost;
  29.                     s.push({ des.first, totalCost });
  30.                     parent[des.first] = curNode;
  31.                 }
  32.             }
  33.         }
  34.     }
  35.     if (flag) {
  36.         vector<int> ans; ans.push_back(n);
  37.         int i = n;
  38.         while (parent[i]) ans.push_back(parent[i]), i = parent[i];
  39.         for (int i = ans.size() - 1; i >= 0; --i) cout << ans[i] << " ";
  40.     }
  41.     else cout << "-1";
  42.     cout << "\n";
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement