poj 3368 Frequent values(SparseTable)

Description

You are given a sequence of n integers a1 , a2 , … , an in non-decreasing order. In addition to that, you are given several queries consisting of indices i and j (1 ≤ i ≤ j ≤ n). For each query, determine the most frequent value among the integers ai , … , aj.

Input

The input consists of several test cases. Each test case starts with a line containing two integers n and q (1 ≤ n, q ≤ 100000). The next line contains n integers a1 , … , an (-100000 ≤ ai ≤ 100000, for each i ∈ {1, …, n}) separated by spaces. You can assume that for each i ∈ {1, …, n-1}: ai ≤ ai+1. The following q lines contain one query each, consisting of two integers i and j (1 ≤ i ≤ j ≤ n), which indicate the boundary indices for the
query.

The last test case is followed by a line containing a single 0.

Output

For each query, print one line with one integer: The number of occurrences of the most frequent value within the given range.

Sample Input

Sample Output

给定一个有序的序列,然后询问一个区间内最多次数出现的数字的次数。

可以用ST表的思路,因为序列是有序的,所以说相同数字一定是在一起的。所以我们可以预先扫一遍这个序列,确定出每个数各是这个数字的第几个,用一个dis数组来存这个信息。然后用这个数组来预处理得到st表,那么我们查询区间的时候,只需要查找区间最大值即可。

但是并没有那么简单,上面那种思路有一个误区,比如:1,1,1,1,1,2,2这样一个序列,如果我要查5-7这样一个区间,那么得到的答案是5而不是2。因为上面那种思路只适用于区间左端点l正好是这个数字的第一号元素。所以正是因为这一点,可以再开一个数组R来记录每一个数的右边界,然后我们判断一下R[l]的情况即可。等于说把查询的区间分为:l-R[l]和R[l]+1-r两段。

然后就可以st表查询了。

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注