POJ2761 Feed the dogs

题目大意:

        给出一个初始数列,有N个整数。然后有Q个询问,每个询问问某个区间内第K小的数。


解题思路:

        裸的划分树(划分树可参见http://www.notonlysuccess.com/index.php/divide-tree/)。

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;

#define lson l, mid, rt<<1
#define rson mid+1,r,rt<<1|1
#define LL(rt) rt<<1
#define RR(rt) rt<<1|1
#define inf 1<<30
const int maxn = 100010 ;

int n,m;
int value[maxn];        //sorted array
int val[22][maxn];      //
int toLeft[22][maxn];   //record the number of interval [1,i] discard in the subLeftTree
struct Seg_Tree
{
	int left,right;
}tree[maxn<<2];

void build(int l,int r,int rt,int d)
{
	tree[rt].left = l;
	tree[rt].right = r;
	if(l == r) return;
	//
	int mid = (l+r)>>1;
	int lsame = mid-l+1;     //the number of subLeftTree
	//the number that had in the left
	for(int i=l;i <= r; ++i)
		if(val[d][i] < value[mid])
			--lsame;
	//
	int lpos = l;
	int rpos = mid+1;
	int same = 0;
	//
	for(int i=l;i <= r; ++i)
	{
		//calculate the toLeft array
		if(i == l)
			toLeft[d][i] = 0;
		else
			toLeft[d][i] = toLeft[d][i-1];
		//discard the number to left or riht Tree
		if(val[d][i] < value[mid])
		{
			++toLeft[d][i];
			val[d+1][lpos++] = val[d][i];
		}
		else if(val[d][i] > value[mid])
			val[d+1][rpos++] = val[d][i];
		else
		{
			if(same < lsame)
			{
				++same;
				++toLeft[d][i];
				val[d+1][lpos++] = val[d][i];
			}
			else
				val[d+1][rpos++] = val[d][i];
		}
	}
	build(lson, d+1);
	build(rson, d+1);
}

int query(int l,int r,int rt,int d,int k)
{
	if(l == r)
		return val[d][l];
	//
	int s;        //record the counts of interval [l,r] in the subLeftTree
	int ss;       //record the counts of interval [tree[rt].left, l-1] int the subLeftTree
	if(l == tree[rt].left)
	{
		s = toLeft[d][r];
		ss = 0;
	}
	else
	{
		s = toLeft[d][r]-toLeft[d][l-1];
		ss = toLeft[d][l-1];
	}
	//
	if(s >= k)
	{
		int newl = tree[rt].left+ss;
		int newr = tree[rt].left+ss+s-1;
		return query(newl,newr,LL(rt),d+1,k);
	}
	else
	{
		int mid = (tree[rt].left+tree[rt].right)>>1;
		int bb = l-tree[rt].left-ss;
		int b = r-l+1-s;
		int newl = mid+bb+1;
		int newr = mid+bb+b;
		return query(newl,newr,RR(rt),d+1,k-s);
	}
}

int main()
{
	while(~scanf("%d%d",&n,&m))
	{
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&value[i]);
			//value[i] = -value[i];//
			val[0][i] = value[i];
		}
		sort(value+1,value+n+1);
		build(1,n,1,0);
		//
		while(m--)
		{
			int x,y,k;
			scanf("%d%d%d",&x,&y,&k);
			printf("%d\n",query(x,y,1,0,k));
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值