#include "stations.h"
#include <bits/stdc++.h>
using namespace std;
int timer = -1;
void dfs(int node, int prev, vector<vector<int>> &adj, vector<int> &tin, vector<int> &tout) {
tin[node] = ++timer;
for (auto &neighbour : adj[node]) {
if (neighbour == prev) continue;
dfs(neighbour, node, adj, tin, tout);
}
tout[node] = timer;
}
int enc(int in, int out) {
return (in + out * (1 << 9));
}
pair<int, int> dec(int x) {
int tin = 0, tout = 0;
for (int i = 0; i < 9; i++) {
tin += x & (1 << i);
}
for (int i = 9; i < 18; i++) {
bool h = x & (1 << i);
if (h) tout += (1 << (i - 9));
}
return {tin, tout};
}
vector<int> label(int n, int k, vector<int> u, vector<int> v) {
vector<vector<int>> adj(n); vector<int> tin(n), tout(n);
vector<int> ans(n);
for (int i = 0; i < n - 1; i++) {
adj[u[i]].push_back(v[i]);
adj[v[i]].push_back(u[i]);
}
timer = -1; dfs(0, -1, adj, tin, tout);
for (int i = 0; i < n; i++) {
int l = tin[i] + tout[i] * (1 << 9);
ans[i] = l;
}
for (int i = 0; i < n; i++) {
if (dec(enc(tin[i], tout[i])) != make_pair(tin[i], tout[i])) {
cout << i << " broke\n";
cout << tin[i] << " " << tout[i] << '\n';
cout << enc(tin[i], tout[i]) << " encd\n";
cout << dec(enc(tin[i], tout[i])).first << " " << dec(enc(tin[i], tout[i])).second << " decd\n";
return ans;
}
}
return ans;
}
bool cont(pair<int, int> &a, pair<int, int> &b) {
if (a.first <= b.first && b.second <= a.second) return true;
else return false;
}
int find_next_station(int s, int t, std::vector<int> c) {
pair<int, int> start = dec(s), end = dec(t);
if (cont(start, end)) {
// move into a child
// cout << "need to move into child\n";
for (auto &x : c) {
pair<int, int> ng = dec(x);
if (cont(start, ng)) {
// this is a child
if (cont(ng, end)) {
return x;
}
}
}
} else {
// move into par
// cout << "move into par\n";
for (auto &x : c) {
pair<int, int> d = dec(x);
if (!cont(start, d)) return x;
}
}
assert(false);
return c[0];
}