Frequent values
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 18364 Accepted: 6602
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
10 3
-1 -1 1 1 1 1 3 10 10 10
2 3
1 10
5 10
0
Sample Output
1
4
3
题意:
给出一组数, 若干的区间访问, 输出区间里出现次数最多的那个数的次数
(数列是非严格上升).
解题思路:
因为数列是非严格上升的, 所以可以对数列进行离散化处理.
对于相同的数, 记录下子区间的左右坐标, 那么就可以对其进行ST维护.
st[i][j]记录的是第i个离散化区间开始, (1<
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
const int maxn = 1e5+5;
struct node
{
int left;
int right;
}dised[maxn];
int a[maxn];
int pos[maxn];
int st[maxn][30];
int n;
int dised_num;
void init()
{
for(int i = 1; i <= dised_num; i++)
st[i][0] = dised[i].right - dised[i].left + 1;
for(int j = 1; (1 << j) <= dised_num; j++){
int t = (1 << j);
for(int i = 1; i + t <= dised_num; i++)
st[i][j] = max(st[i][j-1], st[i + (t >> 1)][j-1]);
}
}
int cmp(int left, int right)
{
int t = (int)(log(right - left + 1.0) / log(2.0));
return max(st[left][t], st[right - (1 << t) + 1][t]);
}
int main()
{
ios::sync_with_stdio(0);
int q;
while(cin >> n){
if(!n){
return 0;
}
cin >> q;
for(int i = 1; i <= n; i++){
cin >> a[i];
if(a[i] != a[i-1]){
dised_num++;
pos[i] = dised_num;
dised[dised_num].left = i;
dised[dised_num].right = i;
}
else{
pos[i] = dised_num;
dised[dised_num].right = i;
}
}
init();
while(q--){
int left;
int right;
cin >> left >> right;
if(pos[left] == pos[right])
cout << right - left + 1 << endl;
else if (pos[right] == pos[left] + 1)
cout << max(dised[pos[left]].right - left + 1, right - dised[pos[right]].left + 1) << endl;
else{
int tmp = max(dised[pos[left]].right - left + 1, right - dised[pos[right]].left + 1);
cout << max(tmp, cmp(pos[left]+1, pos[right]-1)) << endl;
}
}
}
return 0;
}