#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 50050;
int n;
struct Link_cut_tree {
    int bef[maxn],pre[maxn],next[maxn][2];
    void init() {
        memset(pre,0,sizeof(pre));
        memset(next,0,sizeof(next));
    }
    inline void rotate(int x,int kind) {
        int y,z;
        y = pre[x];
        z = pre[y];
        next[y][!kind] = next[x][kind];
        pre[next[x][kind]] = y;
        next[z][next[z][1]==y] = x;
        pre[x] = z;
        next[x][kind] = y;
        pre[y] = x;
    }
    void splay(int x) {
        int rt;
        for(rt=x;pre[rt];rt=pre[rt]);
        if(x != rt) {
            bef[x] = bef[rt];
            bef[rt] = 0;
            while(pre[x]) {
                if(next[pre[x]][0] == x)
                    rotate(x,1);
                else
                    rotate(x,0);
            }
        }
    }
    void access(int x) {
        int father;
        for(father=0;x;x=bef[x]) {
            splay(x);
            pre[next[x][1]] = 0;
            bef[next[x][1]] = x;
            next[x][1] = father;
            pre[father] = x;
            bef[father] = 0;
            father = x;
        }
    }
    int query(int x) {
        access(x);
        splay(x);
        while(next[x][0]) x = next[x][0];
        return x;
    }
    void cut(int x) {
        access(x);
        splay(x);
        bef[next[x][0]] = bef[x];
        bef[x] = 0;
        pre[next[x][0]] = 0;
        next[x][0] = 0;
    }
    void join(int x,int y) {
        if(y == 0) cut(x);
        else {
            int tmp;
            access(y);
            splay(y);
            for(tmp=x;pre[tmp];tmp=pre[tmp]);
            if(tmp != y) {
                cut(x);
                bef[x] = y;
            }
        }
    }
} lct;
void scanf_(int &num){
    char in;
    while((in=getchar())>'9'||in<'0');
    num=in-'0';
    while(in=getchar(),in>='0'&&in<='9')
        num*=10,num+=in-'0';
}
void scanf__(char &in){
    while((in=getchar())>'Z'||in<'A');
}
char ch;
int x , y;
int main() {
    bool flag = false;
    while(~scanf("%d",&n)) {
        if(!flag) flag = true;
        else puts("");
        lct.init();
        for(int i=1;i<=n;i++) scanf_(lct.bef[i]);
        int m; scanf_(m);
        while(m--) {
            scanf__(ch);
            if(ch == 'Q') {
                scanf_(x);
                printf("%d\n",lct.query(x));
            }
            else {
                scanf_(x);scanf_(y);
                lct.join(x,y);
            }
        }
    }
    return 0;
}

 

 posted on 2013-10-31 00:01  tobec  阅读(215)  评论(0编辑  收藏  举报