Advertisement
lukadupli

Shortest path query

Feb 19th, 2023
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | Source Code | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. #define X first
  4. #define Y second
  5.  
  6. using namespace std;
  7.  
  8. typedef long long ll;
  9. typedef pair<int, int> pii;
  10.  
  11. const int MAXN = 5e4 + 5;
  12.  
  13. int n, m, q;
  14. vector<pii> adj[MAXN], hull[MAXN];
  15.  
  16. bool ccw(pii a, pii b, pii c){
  17.     return (ll)a.X * (b.Y - c.Y) + (ll)b.X * (c.Y - a.Y) + (ll)c.X * (a.Y - b.Y) > 0LL;
  18. }
  19.  
  20. void gethull(int node){
  21.     if(!hull[node].empty()) return;
  22.  
  23.     if(node == 1){
  24.         hull[1].push_back({0, 0});
  25.         return;
  26.     }
  27.  
  28.     vector<pii> temp;
  29.     for(auto &nxt : adj[node]){
  30.         gethull(nxt.X);
  31.  
  32.         for(auto &e : hull[nxt.X]){
  33.             if(nxt.Y == 0) temp.push_back({e.X + 1, e.Y});
  34.             else temp.push_back({e.X, e.Y + 1});
  35.         }
  36.     }
  37.  
  38.     sort(temp.begin(), temp.end());
  39.  
  40.     for(auto &point : temp){
  41.         while(hull[node].size() >= 2 &&
  42.               !ccw(hull[node][hull[node].size() - 2], hull[node][hull[node].size() - 1], point))
  43.                 hull[node].pop_back();
  44.  
  45.         hull[node].push_back(point);
  46.     }
  47. }
  48.  
  49. int dist(int a, int b, pii point){
  50.     return a * point.X + b * point.Y;
  51. }
  52.  
  53. int main()
  54. {
  55.     cin >> n >> m;
  56.     for(int i = 0; i < m; i++){
  57.         int a, b, c;
  58.         cin >> a >> b >> c;
  59.  
  60.         adj[b].push_back({a, c});
  61.     }
  62.  
  63.     cin >> q;
  64.     while(q--){
  65.         int a, b, x;
  66.         cin >> a >> b >> x;
  67.  
  68.         gethull(x);
  69.  
  70.         int l = 0, r = hull[x].size() - 1;
  71.         while(r > l){
  72.             int m = (l + r) / 2;
  73.  
  74.             if(dist(a, b, hull[x][m]) <= dist(a, b, hull[x][m + 1])) r = m;
  75.             else l = m + 1;
  76.         }
  77.  
  78.         cout << dist(a, b, hull[x][l]) << '\n';
  79.     }
  80.  
  81.     return 0;
  82. }
  83.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement