bzoj 2733: [HNOI2012]永无乡

来源:互联网 发布:淘宝五金批发市场 编辑:程序博客网 时间:2024/06/05 22:54

传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=2733
思路:数据结构的启发式合并,把小的塞到大的里就好啦,,,复杂度Nlog^2N,不科学?很科学,,考虑每个点至多合并logn次,,所以,,,不多说,,用cin读入字符狂RE不止,,,我也是醉了,,,真的知道读入优化的必要了把,,,
代码:

#include<iostream>#include<cstdio>#include<string>#include<cstring>#define N 100000using namespace std;struct node { int data,sz,son[2],fa;};node tr[N+5];int n,m,f[N+5],w[N+5],que[N+5];inline int find(int x){ return f[x] == x ? x : f[x] = find(f[x]);}inline void update(int x){ tr[x].sz = tr[tr[x].son[0]].sz + tr[tr[x].son[1]].sz + 1;}inline int getnum(){    char c; int num;    while (!isdigit(c = getchar()));    num = c - '0';    while (isdigit(c = getchar())) num = 10 * num + c - '0';    return num;}void init(){    n = getnum(); m = getnum();    for (int i = 1;i <= n; ++i) w[i] = getnum();    for (int i = 1;i <= n; ++i) f[i] = i;    for (int i = 1;i <= n; ++i) tr[i].sz = 1, tr[i].data = w[i];}inline void rorate(int x){     int y = tr[x].fa,z = tr[y].fa;     bool p = (x == tr[y].son[1]),q = p^1;     if (z) tr[z].son[(y==tr[z].son[1])] = x;     tr[x].fa = z; tr[y].fa = x; tr[tr[x].son[q]].fa = y;     tr[y].son[p] = tr[x].son[q]; tr[x].son[q] = y;     update(y); update(x);}inline void splay(int x,int p){    while (tr[x].fa != p){        int y = tr[x].fa,z = tr[y].fa;        if (z)           if ((y == tr[z].son[0])^(x == tr[y].son[0])) rorate(x);          else rorate(y);        rorate(x);    }    update(x);}inline void insert(int x,int root){    int t = root,last = 0;    while (t){        last = t;        if (tr[x].data > tr[t].data) t = tr[t].son[1];        else t = tr[t].son[0];       }    tr[x].fa = last; tr[last].son[(tr[x].data > tr[last].data)] = x;    update(x); update(last);    splay(x,0);}inline void merge(int u,int v){    splay(u,0); splay(v,0);    if (tr[u].sz > tr[v].sz) swap(u,v);    f[u] = v;    int head = 0,tail = 1,last = v;    que[1] = u;    while (head < tail){        int x = que[++head];        if (tr[x].son[0]) que[++tail] = tr[x].son[0];        if (tr[x].son[1]) que[++tail] = tr[x].son[1];    }    for (int i = 1;i <= tail; ++i) insert(que[i],last),last = que[i];}inline int query(int t,int k){    if (!t) return -1;    int s = tr[tr[t].son[0]].sz + 1;    if (s == k) return t;    if (s > k) return query(tr[t].son[0],k);    else query(tr[t].son[1],k - s);}void DO_IT(){    int a,b,u1,v1;    for (int i = 1;i <= m; ++i){         a = getnum(),b = getnum();         u1 = find(a),v1 = find(b);        if (u1 != v1) merge(u1,v1);    }    int q = getnum();    char ch;    while (q--){        ch = getchar();        while (ch < 'A'||ch > 'Z') ch = getchar();         a = getnum(),b = getnum();        if (ch == 'B') {            u1 = find(a),v1 = find(b);            if (u1 != v1) merge(u1,v1);        }        else splay(a,0),printf("%d\n",query(a,b));    }}int main(){    init();    DO_IT();    return 0;}
0 0
原创粉丝点击