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 indicesi and j (1 ≤ i ≤ j ≤ n). For each query, determine the most frequent value among the integersai , ... , aj.
Input
The input consists of several test cases. Each test case starts with a line containing two integersn and q (1 ≤ n, q ≤ 100000). The next line containsn integers a1 , ... , an (-100000 ≤ ai ≤ 100000, for eachi ∈ {1, ..., n}) separated by spaces. You can assume that for each i ∈ {1, ..., n-1}: ai ≤ ai+1. The followingq 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
题意:按照非递减顺序给出一串数字,求任意区间【l , r 】内同一个数出现最多的次数,输出次数。
分析:直接考虑难以求解,可将其转化并用ST表求解。
①设置辅助数组b[max],初始全为1,从1位置~n位置数字,遇到相同的则累计+1,
如 -1 -1 1 1 1 1 3 10 10 10转变成b数组得到
b 1 2 1 2 3 4 1 1 2 3
②对b数组进行ST表处理,给定任意一个区间【l,r】,先利用ST表求出b数组中【l,r】的最大值m
③实际上区间【l,r】内最大值应该是<=m的,因为区间【l,r】可能将连续相同的数字串截断
如b中的【4,8】为:2 3 4 1 1 计算出的m为4,但实际上最多出现的次数为3
④如何解决上述问题呢?分析可知,区间【l,r】切割的第一个连续的数字串会造成数值的影响,而切割的其他数字串不会影响最终的数值。
故遍历找到第一个连续相同的数字串结尾end,如果end等于r说明最大出现次数为(r-l+1)
for(i=l+1;i<=r;i++)
if(a[i]!=a[i-1])break; //或者改成b[i]<=b[i-1]
<strong><span style="font-size:14px;"></span></strong><pre name="code" class="cpp"> if(i==r+1){ //区间内数字全都相同
result=b[r]-b[l]+1;
}
不等的话,第一个连续相同的数字串最多出现次数为(end-l+1),[end+1,r]之间相同数字最多出现的次数就是【end+1,r】之间的最大值。两者取最大值。
else
{
x=rmq_find(i,r);
y=b[i-1]-b[l]+1;
result=max(x,y);
}
#include <iostream>
#include <cstdio>
#include <cmath>
#define Max 100010
using namespace std;
int a[Max];
int b[Max];
int dp[Max][20];
void rmq_st(int n)
{
for(int i=1;i<=n;i++)
dp[i][0]=b[i];
for(int j=1;(1<<j)<=n;j++)
{
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 rmq_find(int l,int r)
{
int k=(int)(log(1.0*(r-l+1))/log(2.0));
return max(dp[l][k],dp[r-(1<<k)+1][k]);
}
void change(int n)
{
int i;
for(i=1;i<=n;i++)b[i]=1;
i=2;
while(i<=n)
{
if(a[i]==a[i-1]) b[i]=b[i-1]+1;
i++;
}
}
int main()
{
int n,q,i,l,r;
while(scanf("%d",&n)!=EOF)
{
if(n==0) break;
scanf("%d",&q);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
change(n);
rmq_st(n);
while(q--)
{
scanf("%d%d",&l,&r);
int x,y,result;
for(i=l+1;i<=r;i++)
if(a[i]!=a[i-1])break; //或者改成b[i]<=b[i-1]
if(i==r+1)
{
result=b[r]-b[l]+1;
}
else
{
x=rmq_find(i,r);
y=b[i-1]-b[l]+1;
result=max(x,y);
}
printf("%d\n",result);
}
}
return 0;
}