Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 13535 | Accepted: 4981 |
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
题意: 给你一个非递减序列,然后询问某区间元素出现的最大次数。
分析: 看上去好像不能用RMQ做,但是经过简单的转化之后其实就是一个RMQ问题。
a[i] 就是原数组
freq[k] 表示第k个(不同)元素出现的次数
id[i]=k 下标为i的数字是第k个元素
对于每次查询[x,y],首先利用 id[] 将x,y映射到 freq[]中的位置。
但是这样存在一个问题:
a[] : 1 1 1 2 3 3 3
freq: 3 1 3
询问 [3,5] 时,映射到freq中则是区间[1,3],很明显结果是不正确的。
所以映射后的区间应该是(id[x],id[y]),然后再计算两端点上元素出现的次数,在他们中取最大值。
刚开始Wrong了,是因为没有考虑id[x]==id[y] 的情况。
其实我这个写的效率不是很高,其实可以开一个数组cnt[i] 表示第i个数字之前有多少数字相同,这样就不用每次都用二分算了。
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#define INF 0x7fffffff
using namespace std;
typedef long long LL;
const int N = 1e5 + 10;
int st_max[N][32],Log2[N];
int n,freq[N],a[N],id[N];
void pre_st()
{
Log2[1]=0;
for(int i=2;i<=n;i++)
{
Log2[i]=Log2[i-1];
if((1<<Log2[i]+1)==i) Log2[i]++;
}
for(int i=n-1;i;i--)
{
st_max[i][0]=freq[i];
for(int j=1;(i+(1<<j)-1) < n;j++)
{
st_max[i][j]=max(st_max[i][j-1],st_max[i+(1<<j-1)][j-1]);
}
}
}
int query_max(int l,int r)
{
if(r<l) return 0;
int len=r-l+1,k=Log2[len];
return max(st_max[l][k],st_max[r-(1<<k) +1][k]);
}
int main()
{
int q;
while(scanf("%d",&n)&&n)
{
scanf("%d",&q);
int k=0;
for(int i=0;i<n;i++) freq[i]=1;
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
if(i==0) continue;
if(a[i]==a[i-1]) freq[k]++;
else k++;
id[i]=k;
}
pre_st();
while(q--)
{
int x,y;
scanf("%d%d",&x,&y);
x--,y--;
int l=id[x],r=id[y];
int ans=query_max(l+1,r-1);
int L=upper_bound(id,id+n,l)-id;
int R=lower_bound(id,id+n,r)-id-1;
int res=max(L-x,y-R);
ans=max(ans,res);
ans=min(ans,y-x+1);
printf("%d\n",ans);
}
}
return 0;
}