【poj2104】不带修改的区间第k大 主席树

【题目大意】

给定一个长为N的序列,每个序列的权值为Ai.有M个询问,每个询问为(L,R,K),分别代表[L,R]的第K大的数。

期中n=100000,m=5000

【题解】

用主席树解决,那么什么是主席树呢?

首先我们先明确一下权值线段树的概念。

平常我们用的线段树都是区间线段树,而权值线段树和平衡树中树的结点意义是类似的。

权值线段树中(下文所说线段树均值权值线段树),每个结点记录的信息是在[l,r]区间内出现的数的总次数。

如将序列{1,2,1,2,3,3,4}建成一颗权值线段树,那么[1,4]对应的结点权值就是7,[2,3]对应的结点权值就是4。

然后再来看主席树的概念。

主席树,又名可持久化线段树,记录每一个历史版本。

如在上题中,主席树就要保存向线段树中每插入一个数的线段树的版本。

但是直接开点记录空间上吃不消,于是我们考虑这样一种情况,如果在插入一个数后,线段树中某些子树的权值没有发生变化,那么我们就可以从新树向该子树连边,就不用新建结点了。

我们通过这样的方式建出来的一棵树,称之为主席树。

具体看代码吧

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<cmath>
#include<algorithm>
using namespace std;
#define FILE "read"
#define MAXN 3200010
#define up(i,j,n) for(int i=j;i<=n;++i)
#define dn(i,j,n) for(int i=j;i>=n;--i)
namespace INIT{
	char buf[1<<15],*fs,*ft;
	inline char getc(){return (fs==ft&&(ft=(fs=buf)+fread(buf,1,1<<15,stdin),fs==ft))?0:*fs++;}
	inline int read(){
		int x=0,f=1;  char ch=getc();
		while(!isdigit(ch))  {if(ch=='-')  f=-1;  ch=getc();}
		while(isdigit(ch))  {x=x*10+ch-'0';  ch=getc();}
		return x*f;
	}
}using namespace INIT;
int n,m,tot,cnt,a[MAXN],num[MAXN],sum[MAXN],hash[MAXN],root[MAXN],son[MAXN][2];
int find(int x){
	int l=1,r=tot;
	while(l+1<r){
		int mid=(l+r)>>1;
		if(hash[mid]<x)  l=mid;
		else r=mid;
	}
	return hash[l]==x?l:r;
}
int newroot(int last){
	sum[++cnt]=sum[last]+1;
	son[cnt][0]=son[last][0];
	son[cnt][1]=son[last][1];
	return cnt;
}
void insert(int l,int r,int &root,int last,int x){
	root=newroot(last);
	if(l==r)  return;
	int mid=(l+r)>>1;
	if(x<=mid)  insert(l,mid,son[root][0],son[last][0],x);
	else insert(mid+1,r,son[root][1],son[last][1],x);
}
int ask(int l,int r,int root,int last,int x){
	if(l==r)  return l;
	int mid=(l+r)>>1,temp=sum[son[root][0]]-sum[son[last][0]];
	if(x<=temp)  return ask(l,mid,son[root][0],son[last][0],x);
	else return ask(mid+1,r,son[root][1],son[last][1],x-temp);
}
int main(){
	freopen(FILE".in","r",stdin);
	freopen(FILE".out","w",stdout);
	n=read();  m=read();
	up(i,1,n)  a[i]=num[i]=read();
	sort(num+1,num+n+1);  hash[++tot]=num[1];
	up(i,2,n)  if(num[i]!=num[i-1])  hash[++tot]=num[i];
	up(i,1,n)  insert(1,tot,root[i],root[i-1],find(a[i]));
	up(i,1,m){
		int x=read(),y=read(),k=read();
		printf("%d\n",hash[ask(1,tot,root[y],root[x-1],k)]);
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值