Spoj MKTHNUM - K-th Number

Posted 蒟蒻JHY

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spoj MKTHNUM - K-th Number相关的知识,希望对你有一定的参考价值。

题目描述

English Vietnamese You are working for Macrohard company in data structures department. After failing your previous task about key insertion you were asked to write a new data structure that would be able to return quickly k-th order statistics in the array segment.

That is, given an array a[1 ... n] of different integer numbers, your program must answer a series of questions Q(i, j, k) in the form: "What would be the k-th number in a[i ... j] segment, if this segment was sorted?"

For example, consider the array a = (1, 5, 2, 6, 3, 7, 4). Let the question be Q(2, 5, 3). The segment a[2 ... 5] is (5, 2, 6, 3). If we sort this segment, we get (2, 3, 5, 6), the third number is 5, and therefore the answer to the question is 5.

输入输出格式

输入格式:

 

The first line of the input contains n — the size of the array, and m — the number of questions to answer (1 ≤ n ≤ 100000, 1 ≤ m ≤ 5000).

The second line contains n different integer numbers not exceeding 10^9 by their absolute values — the array for which the answers should be given.

The following m lines contain question descriptions, each description consists of three numbers: i, j, and k (1 ≤ i ≤ j ≤ n, 1 ≤ k ≤ j - i + 1) and represents the question Q(i, j, k).


SAMPLE INPUT
7 3
1 5 2 6 3 7 4
2 5 3
4 4 1
1 7 3

 

输出格式:

 


For each question output the answer to it — the k-th number in sorted 
a[i ... j] segment. 

SAMPLE OUTPUT
5
6
3

Note : naive solution will not work!!!

 

 

打个版,留给以后复制粘贴2333

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<cstring>
#define ll long long
#define maxn 100005
using namespace std;
struct node{
	node *lc,*rc;
	int s;
}nil[maxn*30],*rot[maxn],*cnt;
int a[maxn],num[maxn],n,ky;
int m,le,ri,k;
char ch;

node *update(node *u,int l,int r){
	node *ret=++cnt;
	*ret=*u;
	ret->s++;
	
	if(l==r) return ret;
	
	int mid=l+r>>1;
	if(le<=mid) ret->lc=update(ret->lc,l,mid);
	else ret->rc=update(ret->rc,mid+1,r);
	
	return ret;
}

int query(node *u,node *v,int l,int r){
	if(l==r) return num[l];
	
	int mid=l+r>>1,c=v->lc->s-u->lc->s;
	if(k<=c) return query(u->lc,v->lc,l,mid);
	else{
		k-=c;
		return query(u->rc,v->rc,mid+1,r);
	}
}

inline void prework(){
	cnt=rot[0]=nil->lc=nil->rc=nil;
	nil->s=0;
	
	for(int i=1;i<=n;i++){
		le=a[i];
		rot[i]=update(rot[i-1],1,ky);
	}
}

inline void solve(){
	while(m--){
		scanf("%d%d%d",&le,&ri,&k);
		printf("%d\n",query(rot[le-1],rot[ri],1,ky));
	}
}

int main(){
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++) scanf("%d",a+i),num[i]=a[i];
	sort(num+1,num+n+1);
	ky=unique(num+1,num+n+1)-num-1;
	for(int i=1;i<=n;i++) a[i]=lower_bound(num+1,num+ky+1,a[i])-num;
	
	prework();
	solve();
	
	return 0;
}

  

以上是关于Spoj MKTHNUM - K-th Number的主要内容,如果未能解决你的问题,请参考以下文章

[SP3946]MKTHNUM - K-th Number

K-th Number

K-th Number

K-th Number

K-th Number

poj[2104]K-th Number