Frequent values
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 21407 Accepted: 7521
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
/*
http://poj.org/problem?id=3368
本题思路就是将问题转化一下
我们利用 num[i] 和 num[i-1] 的关系 来确定 以num[i] 最长连续的长度
然后 问题就转化为了RMQ 问题
然后在查找的时候 在去掉 左端点重复的部分 讲左端点重复的部分 与 第一个不重复 到 r 进行查询 然后查询的结果进行比较去一个最大值
*/
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string>
#include<string.h>
#define MAXN 100007
using namespace std;
int dp[MAXN][20];//RMQ dp 数组 一般第二维就开到2的20次方就差不多了
int A[MAXN];
int F[MAXN];//问题转化
void ST(int n)
{
//进行初始化
for(int i =1;i<=n;i++)
dp[i][0] = F[i];
for(int j =1;(1<<j) <=n;j++)
{
//i + (1<<j) -1 这里就是从i 开始 到 i + (1<<j) -1 结束
for(int i =1;i + (1<<j) -1 <=n;i++)
{
//求区间最大值
dp[i][j] = max(dp[i][j-1],dp[i + (1 << (j-1))][j-1]);
}
}
}
int query(int l,int r)
{
if(l > r) return 0;
int k =0;
//这里是为了求出 最小的2的k次幂 能够覆盖掉整个区间
while((1<<(k+1)) <= r - l + 1) k++;
return max(dp[l][k],dp[r - (1<<k) + 1][k]);
}
int main()
{
int n,m;
while(cin>>n)
{
if(!n) break;
cin>>m;
for(int i = 1;i<=n;i++)
{
cin>>A[i];
if(i == 1)
{
F[i] = 1;
continue;
}
if(A[i] == A[i-1])
F[i] = F[i-1] + 1;
else
F[i] = 1;
}
ST(n);
while(m--)
{
int l,r;
cin>>l>>r;
int t = l;
//这里是为了去掉 l ~ r 中 左边重复的区域
//让 从 第t 个位置开始 到第r 个位置结束的 最大值
//和 重复的个数相比 求一个最大值
while(t <= r && A[t] == A[t-1])
{
t++;
}
int cnt = query(t,r);
int ans = max(t - l ,cnt);
cout<<cnt<<endl;
}
}
return 0;
}