Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int n;
- const int LOG = 20;
- int timer = 0;
- vector<vector<int>> g;
- vector<vector<int>> up;
- vector<int> depth;
- vector<int> tin, tout;
- void resize_all(int n) {
- g.resize(n);
- up.resize(n, vector<int> (LOG));
- depth.resize(n);
- tin.resize(n);
- tout.resize(n);
- }
- void clear_all() {
- g.clear();
- up.clear();
- depth.clear();
- tin.clear();
- tout.clear();
- }
- void dfs(int v, int p = 0) {
- 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) {
- depth[u] = depth[v] + 1;
- dfs(u, v);
- }
- }
- tout[v] = timer++;
- }
- bool isAncestor(int v, int u) {
- return tin[v] <= tin[u] && tout[u] <= tout[v];
- }
- int Max(int v, int u) {
- return (depth[v] > depth[u] ? v : u);
- }
- 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];
- }
- void solve() {
- clear_all();
- resize_all(n);
- int v, u;
- timer = 0;
- int root = 0;
- for (int i = 0; i < n - 1; ++i) {
- cin >> v >> u;
- --v; --u;
- g[v].push_back(u);
- g[u].push_back(v);
- }
- dfs(root);
- int q;
- cin >> q;
- char type;
- while (q--) {
- cin >> type;
- if (type == '?') {
- cin >> v >> u;
- --v; --u;
- int lca1 = lca(v, u);
- int lca2 = lca(v, root);
- int lca3 = lca(u, root);
- cout << Max(Max(lca1, lca2), lca3) + 1 << "\n";
- } else {
- cin >> root;
- --root;
- }
- }
- int useless;
- cin >> useless;
- }
- int main() {
- fast
- // file_in
- // file_in_out
- while (cin >> n) {
- solve();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement