Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const int LOG = 20;
- int timer = 1;
- vector<vector<int>> g;
- vector<vector<int>> up;
- vector<int> tin, tout;
- void resize_all(int n) {
- g.resize(n);
- up.resize(n, vector<int>(LOG, 0));
- tin.resize(n);
- tout.resize(n);
- }
- void dfs(int v, int p) {
- tin[v] = timer++;
- up[v][0] = p;
- for (int i = 1; i < LOG; ++i) {
- up[v][i] = up[up[v][i - 1]][i - 1];
- }
- for (auto u : g[v]) {
- if (u != p) {
- dfs(u, v);
- }
- }
- tout[v] = timer++;
- }
- bool isAncestor(int v, int u) {
- return tin[v] <= tin[u] && tout[u] <= tout[v];
- }
- int lca(int v, int u) {
- if (isAncestor(v, u)) return v;
- if (isAncestor(u, v)) return u;
- for (int i = LOG - 1; i >= 0; --i) {
- if (!isAncestor(up[v][i], u)) {
- v = up[v][i];
- }
- }
- return up[v][0];
- }
- int main() {
- int n;
- cin >> n;
- resize_all(n);
- int v, u;
- for (int i = 0; i < n - 1; ++i) {
- cin >> v >> u;
- --v; --u;
- g[v].push_back(u);
- g[u].push_back(v);
- }
- dfs(0, 0);
- timer = 1;
- int q;
- cin >> q;
- char type;
- while (q--) {
- cin >> type;
- if (type == '?') {
- cin >> v >> u;
- --v; --u;
- cout << lca(v, u) + 1 << '\n';
- } else {
- cin >> v;
- --v;
- dfs(v, v);
- timer = 1;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement