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.
Input
The first line of the input file contains n — the size of the array, and m — the number of questions to answer (1 <= n <= 100 000, 1 <= m <= 5 000).
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).
Output
For each question output the answer to it — the k-th number in sorted a[i…j] segment.
Sample Input
7 3
1 5 2 6 3 7 4
2 5 3
4 4 1
1 7 3
Sample Output
5
6
3
Hint
This problem has huge input,so please use c-style input(scanf,printf),or you may got time limit exceed.
用java写注定还是要超时,提示说的很明白了。
代码:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class Main
{
public static void main(String[]args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
int B=(int)Math.sqrt(n);
ArrayList<Integer> bucket[]=(ArrayList<Integer>[])new ArrayList[n/B+1];
for(int i=0;i<bucket.length;i++)
bucket[i]=new ArrayList<Integer>();
int a[]=new int[n];//需要原始数据的原因是处理桶边界的需要
int num[]=new int[n];//需要一个数列经过排序的副本
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
bucket[i/B].add(a[i]);
num[i]=a[i];
}
for(int i=0;i<n/B;i++)
Collections.sort(bucket[i]);//每个桶排序
Arrays.sort(num);//排序
while((m--)>0)
{
int l=sc.nextInt()-1,r=sc.nextInt(),k=sc.nextInt();
int lb=0,ub=n-1;
while(lb<=ub)//二分查找
{
int md=(lb+ub)/2;
int x=num[md];
//System.out.println(x);
int tl=l,tr=r,c=0;
while(tl<tr&&tl%B!=0)if(a[tl++]<=x)c++;
while(tl<tr&&tr%B!=0)if(a[--tr]<=x)c++;//逐个统计桶边界的元素
//System.out.println("c1:"+c);
while(tl<tr)
{
int b=tl/B;
c+=upperBound(bucket[b],x);
tl+=B;
}//每个桶二分统计小于x的个数
if(c>=k)
ub=md-1;
else
lb=md+1;
System.out.println(num[lb]);
}
}
static int upperBound(ArrayList<Integer>list,int x)//求出小于等于x的个数
{
int l=0,r=list.size()-1;
while(l<=r)
{
int m=(l+r)/2;
if(list.get(m)<=x)
l=m+1;
else
r=m-1;
}
return r+1;
}
}

本文介绍了一种使用桶排序和二分查找的方法来高效地解决数组中特定区间内第k小的数值问题。针对大规模数据输入,该算法通过预处理数组为桶结构并排序,结合二分查找策略,实现快速定位答案。
488

被折叠的 条评论
为什么被折叠?



