Advertisement
ThegeekKnight16

Toll Upsol

Jun 16th, 2023
839
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.11 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. const int MAXN = 5e4 + 10;
  4. const int INF = 0x3f3f3f3f;
  5. array<array<int, 6>, MAXN> Dist;
  6. array<bool, MAXN> Marc;
  7. array<vector<pair<int, int>>, MAXN> grafo;
  8. int K, N, M, O;
  9.  
  10. void bfs(int nivel, int nivelFim)
  11. {
  12.     Marc.fill(0);
  13.     queue<int> q;
  14.     for (int k = 0, v = nivel*K; k < K; k++, v++)
  15.     {
  16.         Dist[v][k] = 0;
  17.         q.push(v);
  18.         Marc[v] = 1;
  19.     }
  20.  
  21.     while (!q.empty())
  22.     {
  23.         int cur = q.front(); q.pop();
  24.         // if (cur/K > nivelFim) break;
  25.         for (auto [viz, p] : grafo[cur])
  26.         {
  27.             for (int k = 0; k < K; k++)
  28.             {
  29.                 Dist[viz][k] = min(Dist[viz][k], Dist[cur][k] + p);
  30.             }
  31.             if (!Marc[viz]) {q.push(viz); Marc[viz] = 1;}
  32.         }
  33.     }
  34. }
  35.  
  36. bool cmp(tuple<int, int, int> a, tuple<int, int, int> b)
  37. {
  38.     if (((get<0>(a))/K) == ((get<0>(b))/K)) return get<1>(a) > get<1>(b);
  39.     return get<0>(a) < get<0>(b);
  40. }
  41.  
  42. int main()
  43. {
  44.     ios_base::sync_with_stdio(false);
  45.     cin.tie(NULL);
  46.     cin >> K >> N >> M >> O;
  47.     for (int i = 1; i <= M; i++)
  48.     {
  49.         int X, Y, P;
  50.         cin >> X >> Y >> P;
  51.         grafo[X].emplace_back(Y, P);
  52.     }
  53.     Dist.fill({INF, INF, INF, INF, INF, INF});
  54.  
  55.     vector<tuple<int, int, int> > queries;
  56.     for (int i = 0; i < O; i++)
  57.     {
  58.         int X, Y;
  59.         cin >> X >> Y;
  60.         queries.emplace_back(X, Y, i);
  61.     }
  62.     sort(queries.begin(), queries.end(), cmp);
  63.  
  64.     vector<int> resp(O); int lastNivel = -1;
  65.     for (auto [X, Y, id] : queries)
  66.     {
  67.         // cerr << '\r' << X << " " << Y << " " << id;
  68.         if (X/K >= Y/K) {resp[id] = -1; continue;}
  69.         if (lastNivel < (X/K)) {bfs((X/K)+1, N/K); lastNivel = (X/K)+1;}
  70.         if (lastNivel == (X/K)+1)
  71.         {
  72.             resp[id] = INF;
  73.             for (auto [viz, p] : grafo[X]) resp[id] = min(resp[id], Dist[Y][viz%K] + p);
  74.             if (resp[id] >= INF) resp[id] = -1;
  75.         }
  76.         else if (lastNivel == (X/K)) resp[id] = (Dist[Y][X%K] >= INF ? -1 : Dist[Y][X%K]);
  77.     }
  78.  
  79.     for (auto x : resp) cout << x << '\n';
  80. }
  81.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement