首页 > 其他 > 详细

[P3834]【模板】可持久化线段树 2(主席树)

时间:2020-09-13 09:35:54      阅读:80      评论:0      收藏:0      [点我收藏+]

复习一下主席树板子

#include <bits/stdc++.h>
using namespace std;

#define int long long
const int N = 10000005;
const int V = 1e9;
int n,m,src[N],a[N],ch[N][2],root[N],ind;

void copynode(int dest,int src)
{
    ch[dest][0]=ch[src][0];
    ch[dest][1]=ch[src][1];
    a[dest]=a[src];
}

void modify(int p,int l,int r,int pos,int key)
{
    a[p]+=key;
    if(l<r)
    {
        if(pos<=((l+r)>>1))
        {
            copynode(++ind,ch[p][0]);
            ch[p][0]=ind;
            modify(ch[p][0],l,(l+r)>>1,pos,key);
        }
        else
        {
            copynode(++ind,ch[p][1]);
            ch[p][1]=ind;
            modify(ch[p][1],((l+r)>>1)+1,r,pos,key);
        }
    }
}

void modify(int ver,int pos,int key)
{
    copynode(++ind,root[ver-1]);
    root[ver]=ind;
    modify(root[ver],-V,V,pos,key);
}

int query(int p,int q,int l,int r,int k)
{
    if(l==r)
    {
        return l;
    }
    else
    {
        if(k>a[ch[p][0]]-a[ch[q][0]])
        {
            return query(ch[p][1],ch[q][1],((l+r)>>1)+1,r,k-a[ch[p][0]]+a[ch[q][0]]);
        }
        else
        {
            return query(ch[p][0],ch[q][0],l,(l+r)>>1,k);
        }
    }
}

int query(int verl,int verr,int k)
{
    return query(root[verr],root[verl],-V,V,k);
}

signed main()
{
    ios::sync_with_stdio(false);

    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        cin>>src[i];
        modify(i,src[i],1);
    }
    a[0]=0;ch[0][0]=ch[0][1]=0;
    for(int i=1;i<=m;i++)
    {
        int l,r,k;
        cin>>l>>r>>k;
        cout<<query(l-1,r,k)<<endl;
    }
}

[P3834]【模板】可持久化线段树 2(主席树)

原文:https://www.cnblogs.com/mollnn/p/13660066.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!