Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- #define f first
- #define s second
- #define pb push_back
- using namespace std;
- const int MAXN = 1e6 + 10;
- const int INF = 1e9 + 7;
- bool was[MAXN];
- vector <int> g[MAXN];
- int up[MAXN][23];
- int tin[MAXN], tout[MAXN], l;
- bool upper(int a, int b){
- return (tin[a] <= tin[b] && tout[a] >= tout[b]);
- }
- int timer = 0;
- void dfs(int x, int p = 0){
- was[x] = 1;
- tin[x] = ++timer;
- up[x][0] = p;
- for (int i = 1; i <= l; i++){
- up[x][i] = up[up[x][i - 1]][i - 1];
- }
- for (int i = 0; i < g[x].size(); i++){
- int to = g[x][i];
- if (!was[to]){
- dfs(to, x);
- }
- }
- tout[x] = ++timer;
- }
- int lca(int a, int b){
- if (upper(a, b))
- return a;
- if (upper(b, a))
- return b;
- for (int i = l; i >= 0; i--){
- if (!upper(up[a][i], b))
- a = up[a][i];
- }
- return up[a][0];
- }
- void solve(){
- tout[0] = INF;
- int q;
- cin >> q;
- pair <string, pair <int, int> > a[q + 1];
- for (int i = 0; i < q; i++){
- cin >> a[i].f >> a[i].s.f >> a[i].s.s;
- if (a[i].f == "ADD"){
- g[a[i].s.f].push_back(a[i].s.s);
- }
- }
- l = 0;
- while ((1 << l) < MAXN){
- l++;
- }
- dfs(1);
- for (int i = 0; i < q; i++){
- if (a[i].f == "GET"){
- cout << lca(a[i].s.f, a[i].s.s) << '\n';
- }
- }
- }
- int main() {
- ios::sync_with_stdio(0);
- cin.tie(nullptr);
- cout.tie(nullptr);
- int ttt = 1;
- //cin >> ttt;
- while (ttt--){
- solve();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment