线段树-某个区间段的第k个数

Description
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 <= 5000).
The second line contains n different integer numbers not exceeding 109 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


Solution
In this problem, we need to find the maximum number in a given segment. Therefore, segment tree should come into mind. The segment tree is constructed not only with the segment but also the sorted element in that segment. The sorted array for each node can be constructed in a similar method to merge sort. It is difficult to find the kth number for a segment [a,b] because it might be consisted of multiple smaller segments. Therefore, binary search is used to identify a proper number to search and the index of that number, say, numbers[mid] is found.
1) k-1 elements smaller than numbers[mid] on the segment [a,b] and numbers[mid] is on the segment [a,b]
2) at least k elements smaller than numbers than numbers[mid] on the segment [a,b] and no matter numers[mid] exists on the segment [a,b], a smaller number should be tested
3)
(1) less than k-1 elements smaller than numbers[mid] in the segment [a,b], a bigger number should be tested
(2) k-1 elements smaller than numbers[mid] on the segment [a,b] but numbers[mid] is not the on the segment. Then the kth element on the segment must be greater than numbers[mid]. Any number on the segment [a,b] and less than numbers[mid] is at most the k-1th number on the segment [a,b]


后来终于明白了,重点在main循环中,找到[a,b]的第k个数。每次用不同的数据查询,这个数在[a,b]段中是第几大,不断缩小范围,不断逼近要求取的[a,b]段的第k个数字。

SegmentTree的query只是用来查询num在这个段中是第几大。


import java.util.Arrays;
import java.util.Scanner;
 
/**
 *
 * @author yeming
 */
public class Main {
     static boolean exist;
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int m = scanner.nextInt();
        int[] numbers = new int[n];
        for(int i = 0; i < n; i++) {
            numbers[i] = scanner.nextInt();
        }
         
        SegmentTree root = new SegmentTree(1, n, numbers);
        numbers = root.getArray();
        while(m-- > 0) {
            int a = scanner.nextInt();
            int b = scanner.nextInt();
            int k = scanner.nextInt();
            int start = 0;
            int end = n-1;
            while(start <= end) {
                int mid = (start+end) >> 1;
                exist = false;
                int index = root.query(a, b, numbers[mid]);
                if(index+1 == k && exist) {
                    //k-1 elements smaller than numbers[mid] on the segment [a,b]
                    //and numbers[mid] is on the segment [a,b]
                    System.out.println(numbers[mid]);
                    break;
                }else if(index+1 > k) {
                    //at least k elements smaller than numbers than numbers[mid] on the segment [a,b]
                    //no matter numers[mid] exists on the segment [a,b], a smaller number should be tested
                    end = mid-1;
                }else {
                    //less than k-1 elements smaller than numbers[mi] in the segment [a,b],
                    //a biger number shoudl be tested
                    //k-1 elements smaller than numbers[mid] on the segment [a,b] but numbers[mid]
                    //is not the on the segment. Then the kth element on the segment must be greater
                    //than numbers[mid]. Any number on the segment [a,b] and less than numbers[mid]
                    //is at most the k-1th number on the segment [a,b]
                    start = mid+1;
                }
            }
        }
    }
}
 
class SegmentTree {
     
    private int start;
    private int end;
    private int[] array;
    private SegmentTree left;
    private SegmentTree right;
     
    public SegmentTree(int start, int end, int[] numbers) {
        this.start = start;
        this.end = end;
        this.array = new int[end-start+1];
        if(start == end) {
            this.array[0] = numbers[start-1];
            this.left = null;
            this.right = null;
        }else {
            //divide step of the merge sort
            int mid = (start + end) >> 1;
            this.left = new SegmentTree(start, mid, numbers);
            this.right = new SegmentTree(mid+1, end, numbers);
            //merge step of the merge sort
            int leftIndex = 0;
            int rightIndex = 0;
            int index = 0;
            while(leftIndex < left.array.length && rightIndex < right.array.length) {
                if(left.array[leftIndex] < right.array[rightIndex]) {
                    array[index++] = left.array[leftIndex++];
                }else {
                    array[index++] = right.array[rightIndex++];
                }
            }
            while(leftIndex < left.array.length) {
                array[index++] = left.array[leftIndex++];
            }
            while(rightIndex < right.array.length) {
                array[index++] = right.array[rightIndex++];
            }
        }
    }
     
    public int query(int a, int b, int num) {
        int index;
        if(a == start && b == end) {
            index = Arrays.binarySearch(array, num);
            if(index < 0) {
                index = -index - 1;
            }else {
                Main.exist = true;
            }
        }else {
            int mid = (start+end) >> 1;
            if(b <= mid) {
                return left.query(a, b, num);
            }else if(a > mid) {
                return right.query(a, b, num);
            }else {
                int leftIndex = left.query(a, mid, num);
                int rightIndex = right.query(mid + 1, b, num);
                index = leftIndex + rightIndex;
            }
        }
        return index;
    }
     
    public boolean isLeave() {
        return start == end;
    }
     
    public int[] getArray() {
        return array;
    }
}

 

参考:http://www.yeminghu.com/?p=239

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值