hdu 2665 划分树模板题(可作为模板)

Kth number

Time Limit: 15000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6951    Accepted Submission(s): 2214

Problem Description
Give you a sequence and ask you the kth big number of a inteval.
 
Input
The first line is the number of the test cases.
For
each test case, the first line contain two integer n and m (n, m <=
100000), indicates the number of integers in the sequence and the number
of the quaere.
The second line contains n integers, describe the sequence.
Each of following m lines contains three integers s, t, k.
[s, t] indicates the interval and k indicates the kth big number in interval [s, t]
 
Output
For each test case, output m lines. Each line contains the kth big number.
 
Sample Input
1
10 1
1 4 2 3 5 6 7 8 9 0
1 3 2
 
Sample Output
2
 
Source
 
Recommend
zty   |   We have carefully selected several similar problems for you:  2660 2662 2667 2663 2661 
 by
狂斌
求某个小区间的第k大的数
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std; const int MAXN=;
int tree[][MAXN];//表示每层每个位置的值
int sorted[MAXN];//已经排序的数
int toleft[][MAXN];//toleft[p][i]表示第i层从1到i有多少个数分入左边 void build(int l,int r,int dep)
{
if(l==r)return;
int mid=(l+r)>>;
int same=mid-l+;//表示等于中间值而且被分入左边的个数
for(int i=l;i<=r;i++)
if(tree[dep][i]<sorted[mid])
same--;
int lpos=l;
int rpos=mid+;
for(int i=l;i<=r;i++)
{
if(tree[dep][i]<sorted[mid])//比中间的数小,分入左边
tree[dep+][lpos++]=tree[dep][i];
else if(tree[dep][i]==sorted[mid]&&same>)
{
tree[dep+][lpos++]=tree[dep][i];
same--;
}
else //比中间值大分入右边
tree[dep+][rpos++]=tree[dep][i];
toleft[dep][i]=toleft[dep][l-]+lpos-l;//从1到i放左边的个数 }
build(l,mid,dep+);
build(mid+,r,dep+); } //查询区间第k大的数,[L,R]是大区间,[l,r]是要查询的小区间
int query(int L,int R,int l,int r,int dep,int k)
{
if(l==r)return tree[dep][l];
int mid=(L+R)>>;
int cnt=toleft[dep][r]-toleft[dep][l-];//[l,r]中位于左边的个数
if(cnt>=k)
{
//L+要查询的区间前被放在左边的个数
int newl=L+toleft[dep][l-]-toleft[dep][L-];
//左端点加上查询区间会被放在左边的个数
int newr=newl+cnt-;
return query(L,mid,newl,newr,dep+,k);
}
else
{
int newr=r+toleft[dep][R]-toleft[dep][r];
int newl=newr-(r-l-cnt);
return query(mid+,R,newl,newr,dep+,k-cnt);
}
} int main(){
int T;
int n,m;
int s,t,k;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
memset(tree,,sizeof(tree));//这个必须
for(int i=;i<=n;i++)//从1开始
{
scanf("%d",&tree[][i]);
sorted[i]=tree[][i];
}
sort(sorted+,sorted+n+);
build(,n,);
while(m--)
{
scanf("%d%d%d",&s,&t,&k);
printf("%d\n",query(,n,s,t,,k));
}
}
return ;
}
上一篇:(三)backbone - API学习 - v0.9.2 与 v1.1.2区别


下一篇:python写入文本报错TypeError: expected a string or other character buffer object