bzoj1803: Spoj1487 Query on a tree III

来源:互联网 发布:sql server软件下载 编辑:程序博客网 时间:2024/06/11 09:49

链接

  http://www.lydsy.com/JudgeOnline/problem.php?id=1803

题解

  1A的傻逼题。
  直接暴力主席树。

代码

//主席树#include <cstdio>#include <algorithm>#define maxn 200010int N, M, head[maxn], to[maxn], nex[maxn], out[maxn], tid[maxn], ndtot,    tmp[maxn], tot, val[maxn], table[maxn], num[maxn];inline void adde(int a, int b){to[++tot]=b;nex[tot]=head[a];head[a]=tot;}struct segtree{int l, r, size;segtree *ch[2];}pool[maxn*10], *root[maxn];void dfs(int pos, int pre){    int p;    tid[pos]=++tid[0];    for(p=head[pos];p;p=nex[p])        if(to[p]^pre)dfs(to[p],pos);    out[pos]=tid[0];}void ins(segtree *pre, segtree *now, int pos){    int mid=(pre->l+pre->r)>>1;    *now=*pre;now->size++;    if(pre->l==pre->r)return;    if(pos<=mid)ins(pre->ch[0],now->ch[0]=pool+ ++ndtot,pos);    if(pos>mid)ins(pre->ch[1],now->ch[1]=pool+ ++ndtot,pos);}int find(segtree *pre, segtree *now, int k){    int sz;    if(pre->l==pre->r)return pre->l;    sz=now->ch[0]->size-pre->ch[0]->size;    if(k<=sz)return find(pre->ch[0],now->ch[0],k);    return find(pre->ch[1],now->ch[1],k-sz);}void build(segtree *p, int l, int r){    int mid=(l+r)>>1;    p->l=l, p->r=r;    if(l==r)return;    build(p->ch[0]=pool+ ++ndtot,l,mid);    build(p->ch[1]=pool+ ++ndtot,mid+1,r);}inline int read(int x=0){    char c=getchar();    while(c<48 or c>57)c=getchar();    while(c>=48 and c<=57)x=(x<<1)+(x<<3)+c-48,c=getchar();    return x;}inline bool cmp(int a, int b){return tid[a]<tid[b];}void init(){    int i, a, b;    scanf("%d",&N);    for(i=1;i<=N;i++)val[i]=read();    for(i=1;i<N;i++)a=read(), b=read(), adde(a,b), adde(b,a);    build(root[0]=pool+ ++ndtot,1,N);    for(i=1;i<=N;i++)tmp[i]=val[i];std::sort(tmp+1,tmp+N+1);    for(i=1;i<=N;i++)val[i]=std::lower_bound(tmp+1,tmp+N+1,val[i])-tmp;    for(i=1;i<=N;i++)table[val[i]]=i;    dfs(1,-1);    for(i=1;i<=N;i++)num[i]=i;std::sort(num+1,num+N+1,cmp);    for(i=1;i<=N;i++)ins(root[i-1],root[i]=pool+ ++ndtot,val[num[i]]);}void solve(int x, int k){    printf("%d\n",table[find(root[tid[x]-1],root[out[x]],k)]);}int main(){    int x, k, i, M;    init();    M=read();    for(i=1;i<=M;i++)    {        x=read(), k=read();        solve(x,k);    }    return 0;}
0 0