Advertisement
akashtadwai

Dijkstra-Atmost 1 edge

Aug 22nd, 2021
1,007
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define pb push_back
  4. #define int long long
  5. #define INF LLONG_MAX
  6. #define ar array
  7. #define arr ar<int, 2>
  8. #define IOS                         \
  9.   std::ios::sync_with_stdio(false); \
  10.   cin.tie(NULL);
  11.  
  12. int n, m;
  13.  
  14. vector<int> dijkstra(int v, vector<vector<ar<int, 2>>> &g)
  15. {
  16.   auto compare = [](const arr a, const arr b)
  17.   {
  18.     return a[1] > b[1];
  19.   };
  20.   priority_queue<arr, vector<arr>, decltype(compare)> pq(compare);
  21.   vector<int> dis(n, INF);
  22.   dis[v] = 0;
  23.   pq.push({v, 0});
  24.   while (!pq.empty())
  25.   {
  26.     auto tp = pq.top();
  27.     pq.pop();
  28.     int dist = tp[1];
  29.     if (dis[tp[0]] != dist)
  30.       continue;
  31.  
  32.     for (auto v : g[tp[0]])
  33.     {
  34.       int ver = v[0], weight = v[1];
  35.       if (dis[ver] > dis[tp[0]] + weight)
  36.       {
  37.         dis[ver] = dis[tp[0]] + weight;
  38.         pq.push({ver, dis[ver]});
  39.       }
  40.     }
  41.   }
  42.   return dis;
  43. }
  44. void init()
  45. {
  46.   cin >> n >> m;
  47.   vector<vector<ar<int, 2>>> g, grev;
  48.   vector<ar<int, 3>> edges;
  49.   g.resize(n), grev.resize(n);
  50.   for (int i = 0; i < m; i++)
  51.   {
  52.     int u, v, w;
  53.     cin >> u >> v >> w;
  54.     --u, --v;
  55.     g[u].pb({v, w});
  56.     grev[v].pb({u, w});
  57.     edges.pb({u, v, w});
  58.   }
  59.   vector<int> a = dijkstra(0, g);
  60.   vector<int> b = dijkstra(n - 1, grev);
  61.  
  62.   int ans = INF;
  63.  
  64.   for (auto edge : edges)
  65.   {
  66.     int st = edge[0], end = edge[1];
  67.     if (a[st] != INF and b[end] != INF)
  68.     {
  69.       ans = min(ans, b[end] + a[st] + edge[2] / 2);
  70.     }
  71.   }
  72.   cout << ans << endl;
  73. }
  74. int32_t main()
  75. {
  76.   IOS;
  77.   init();
  78.   return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement