bzoj1803: Spoj1487 Query on a tree III

本文介绍了一种使用主席树解决特定图论问题的方法。通过建立图的数据结构,并利用主席树进行插入和查找操作,有效地解决了给定节点的第k小邻居的问题。文章提供了完整的代码实现,包括初始化图结构、构建主席树、DFS遍历以及主要的解决函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链接

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

题解

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

代码

//主席树
#include <cstdio>
#include <algorithm>
#define maxn 200010
int 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值