Advertisement
erek1e

IOI '20 - Stations

Mar 5th, 2023
626
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. #include "stations.h"
  2. #include <bits/stdc++.h>
  3.  
  4. using namespace std;
  5.  
  6. vector<vector<int>> g;
  7. vector<int> tin, tout, depth;
  8. int t;
  9. void dfs(int node, int parent = -1) {
  10.     if (parent == -1) depth[node] = 0;
  11.     else depth[node] = depth[parent] + 1;
  12.  
  13.     tin[node] = ++t;
  14.     for (int child : g[node]) {
  15.         if (child != parent) dfs(child, node);
  16.     }
  17.     tout[node] = ++t;
  18. }
  19.  
  20. void compress(vector<int> &v) {
  21.     vector<int> u = v;
  22.     sort(u.begin(), u.end());
  23.     // all values already unique
  24.     for (int &x : v) {
  25.         x = lower_bound(u.begin(), u.end(), x) - u.begin();
  26.     }
  27. }
  28.  
  29. vector<int> label(int n, int k, vector<int> u, vector<int> v) {
  30.     g.clear(), tin.clear(), tout.clear(), depth.clear();
  31.     g.resize(n);
  32.     for (int i = 0; i < u.size(); ++i) {
  33.         g[u[i]].push_back(v[i]);
  34.         g[v[i]].push_back(u[i]);
  35.     }
  36.     t = -1;
  37.     tin.resize(n), tout.resize(n);
  38.     depth.resize(n);
  39.     dfs(0);
  40.  
  41.     vector<int> labels(n);
  42.     for (int i = 0; i < n; i++) {
  43.         if (depth[i] & 1) labels[i] = tout[i];
  44.         else labels[i] = tin[i];
  45.     }
  46.     compress(labels);
  47.     return labels;
  48. }
  49.  
  50. int find_next_station(int s, int t, vector<int> c) {
  51.     int m = c.size();
  52.     if (m == 1) return c[0];
  53.     sort(c.begin(), c.end());
  54.     if (s < c.front()) { // s has tin, rest have tout
  55.         // c.back() is parent of s
  56.         if (s <= t && t <= c[m-2]) {
  57.             // t is in subtree of s
  58.             // which child
  59.             for (int x : c) {
  60.                 if (t <= x) return x;
  61.             }
  62.         } else {
  63.             // t is not in subtree of s
  64.             return c.back();
  65.         }
  66.     } else { // s has tout, rest have tin
  67.         // c.front() is parent of s
  68.         if (c[1] <= t && t <= s) {
  69.             // t is in subtree of s
  70.             // which child
  71.             for (int i = m-1; i >= 0; --i) {
  72.                 if (t >= c[i]) return c[i];
  73.             }
  74.         } else {
  75.             // t is not in subtree of s
  76.             return c.front();
  77.         }
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement