【线段树专题】poj2104

这个题已经被花式A了

因为要练习线段树,所以就用函数式线段树写了这个题,

函数式运用了一种可持久化的思想,在修改的同时记录修改以前的样子,

函数式线段树的话就是在每次进行插入操作的时候在上一次线段树的基础上新建一条路径,其余节点都用原来线段树的节点

感觉现在写起来比以前要轻松很多了。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<algorithm>
using namespace std;
int root[200100],a[200100],b[200100],tot,n,q,tail;

struct rec
{
    int l,r,lch,rch,sum;
}tree[4001000];

void maketree(int l,int r)
{
    int now=++tot;
    tree[now].l=l;
    tree[now].r=r;
    if (l==r) return;
    int mid=(l+r)>>1;
    tree[now].lch=tot+1;maketree(l,mid);
    tree[now].rch=tot+1;maketree(mid+1,r);
}

void insert(int x1,int x2,int w)
{
    int now=++tot;
    tree[tot].sum=tree[x1].sum;
    tree[tot].l=tree[x1].l;
    tree[tot].r=tree[x1].r;
    tree[tot].lch=tree[x1].lch;
    tree[tot].rch=tree[x1].rch;
    if (tree[tot].l==tree[tot].r)
    {
        tree[tot].sum++;
        return;
    }
    int mid=(tree[x1].l+tree[x1].r)>>1;
    if (w<=mid) 
    {
        tree[tot].lch=tot+1;
        insert(tree[x1].lch,tot+1,w);
    }
    else
    {
        tree[tot].rch=tot+1;
        insert(tree[x1].rch,tot+1,w);
    }
    tree[now].sum++;
}

int find_ans(int x1,int x2,int k)
{
    if (tree[x1].l==tree[x1].r)
        return a[tree[x1].l];
    if (tree[tree[x2].lch].sum-tree[tree[x1].lch].sum>=k)
        return find_ans(tree[x1].lch,tree[x2].lch,k);
    else
        return find_ans(tree[x1].rch,tree[x2].rch,k-(tree[tree[x2].lch].sum-tree[tree[x1].lch].sum));
}

int main()
{
    freopen("poj2104.in","r",stdin);
    tot=0;
    scanf("%d%d",&n,&q);
    for (int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
        b[i]=a[i];
    }
    sort(a+1,a+n+1);
    tail=unique(a+1,a+n+1)-a-1;
    maketree(1,tail);
    root[0]=1;
    int w;
    for (int i=1;i<=n;i++)
    {
        root[i]=tot+1;
        w=lower_bound(a+1,a+tail+1,b[i])-a;
        insert(root[i-1],root[i],w);
    }
    int l,r,k,ans;
    for (int i=1;i<=q;i++)
    {
        scanf("%d%d%d",&l,&r,&k);
        ans=find_ans(root[l-1],root[r],k);
        printf("%d\n",ans);
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值