BZOJ_P2733/Codevs_P1477 [HNOI2012]永无乡(Treap+启发式合并+并查集)

来源:互联网 发布:kdl50w700a安装软件 编辑:程序博客网 时间:2024/05/16 11:45

BZOJ传送门
Codevs传送门

Time Limit: 10 Sec Memory Limit: 128 MB
Submit: 2033 Solved: 1065
[Submit][Status][Discuss]
Description
永无乡包含 n 座岛,编号从 1 到 n,每座岛都有自己的独一无二的重要度,按照重要度可 以将这 n 座岛排名,名次用 1 到 n 来表示。某些岛之间由巨大的桥连接,通过桥可以从一个岛 到达另一个岛。如果从岛 a 出发经过若干座(含 0 座)桥可以到达岛 b,则称岛 a 和岛 b 是连 通的。现在有两种操作:B x y 表示在岛 x 与岛 y 之间修建一座新桥。Q x k 表示询问当前与岛 x连通的所有岛中第 k 重要的是哪座岛,即所有与岛 x 连通的岛中重要度排名第 k 小的岛是哪 座,请你输出那个岛的编号。

Input

输入文件第一行是用空格隔开的两个正整数 n 和 m,分别 表示岛的个数以及一开始存在的桥数。接下来的一行是用空格隔开的 n 个数,依次描述从岛 1 到岛 n 的重要度排名。随后的 m 行每行是用空格隔开的两个正整数 ai 和 bi,表示一开始就存 在一座连接岛 ai 和岛 bi 的桥。后面剩下的部分描述操作,该部分的第一行是一个正整数 q, 表示一共有 q 个操作,接下来的 q 行依次描述每个操作,操作的格式如上所述,以大写字母 Q 或B 开始,后面跟两个不超过 n 的正整数,字母与数字以及两个数字之间用空格隔开。 对于 20%的数据 n≤1000,q≤1000
对于 100%的数据 n≤100000,m≤n,q≤300000

Output
对于每个 Q x k 操作都要依次输出一行,其中包含一个整数,表 示所询问岛屿的编号。如果该岛屿不存在,则输出-1。

Sample Input
5 1
4 3 2 5 1
1 2
7
Q 3 2
Q 2 1
B 2 3
B 1 5
Q 2 1
Q 2 4
Q 2 3

Sample Output
-1
2
5
1
2

HINT

Source

Sol:
并查集维护连通性,Treap乱搞

#include<cstdio>#include<cstdlib>#include<iostream>using namespace std;#define N 100005inline int in(int x=0,char ch=getchar()){while(ch>'9'||ch<'0') ch=getchar();    while(ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar();return x;}inline char in2(char ch=getchar()){while(ch>'Z'||ch<'A') ch=getchar();return ch;}struct Splay{    struct Node{        int s,v,r,m;Node* ch[2];        Node(int v,int m,Node *nl):v(v),m(m){ch[0]=ch[1]=nl;s=1,r=rand();}        void push(){s=ch[0]->s+ch[1]->s+1;}    }*root,*null;    Splay(){null=new Node(0,0,0);null->s=null->v=0;null->r=0x7fffffff;        null->ch[0]=null->ch[1]=null;root=null;}    void rot(Node* &o,int d){        Node* k=o->ch[d^1];o->ch[d^1]=k->ch[d],k->ch[d]=o;        o->push(),k->push();o=k;    }    void inst(Node* &o,int v,int m){        if(o==null){o=new Node(v,m,null);return;}        inst(o->ch[v>o->v],v,m);        if(o->ch[v>o->v]->r<o->r) rot(o,v<o->v);        else o->push();    }    int rk(Node* &o,int k){        if(o->s<k) return -1;        if(o->ch[0]->s>=k) return rk(o->ch[0],k);        else if(o->ch[0]->s+1<k) return rk(o->ch[1],k-o->ch[0]->s-1);        else return o->m;    }    void work(Node* &o,Node* nl){        if(o==nl) return;        inst(root,o->v,o->m);work(o->ch[0],nl);work(o->ch[1],nl);    }}d[N];int n,m,t;int f[N];inline int find(int x){return x==f[x]?x:find(f[x]);}inline void Union(int x,int y){    int f1=find(x),f2=find(y);    if(f1==f2) return;    if(d[f1].root->s<d[f2].root->s) swap(f1,f2),swap(x,y);    d[f1].work(d[f2].root,d[f2].null);    f[f2]=f1;}int main(){    n=in(),m=in();int u,v;char op;    for(int i=1;i<=n;i++) u=in(),d[i].inst(d[i].root,u,i),f[i]=i;    for(int i=1;i<=m;i++) u=in(),v=in(),Union(u,v);    t=in();int x;    while(t--){        op=in2(),u=in(),v=in();        if(op=='Q') x=find(u),printf("%d\n",d[x].rk(d[x].root,v));        else Union(u,v);    }    return 0;}
1 0