Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 16959 | Accepted: 6125 |
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 integersa1 , ... , 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 qlines 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經常用來查詢區間最值問題,對於任意區間,RMQ算法可以方便的在O(1)時間查詢出最值。
以最大值爲例,考慮遞推方程:f[i][j]=max(f[i][j-1],f[i+(1<<(j-1))][j-1]);
f[i][j]:表示區間[i,i+2^j-1],j=0,1,2,在區間內即可。
上面式子即表示:大區間[i,i+2^j-1]區間=小區間[i,i+2^(j-1)-1]U[i+2^(j-1),i+2^(j-1)+2^(j-1)-1],
等式兩邊明顯相等(相同),故成立。
對於該題,查詢區間[l,r],對於區間左端點處和區間外面相等的數字單獨處理即可。
RMQ解法:
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<math.h>
#include<string.h>
using namespace std;
#define LL long long int
#define rep(i,a,n) for(int i=a;i<n;++i)
#define per(i,a,n) for(int i=n-1;i>=a;--i
#define N 100005
const int inf=1e9+10;
int a[N],num[N],rt[N];
int dp[N][20];
void rmq(int n)
{
int i,j;
rep(i,1,n+1) dp[i][0]=num[i];
for(j=1;j<20;++j){
for(i=1;i+(1<<(j-1))<=n;++i){
dp[i][j]=max(dp[i][j-1],dp[i+(1<<(j-1))][j-1]);
}
}
}
int myquery(int l,int r)
{
if(l>r)
return 0;
int k,t1,t2;
k=log(r-l+1.0)/log(2.0);
t1=dp[l][k];
t2=dp[r-(1<<k)+1][k];
return max(t1,t2);
}
int main()
{
//freopen("in.txt","r",stdin);
int n,q;
while(scanf("%d",&n),n){
scanf("%d",&q);
a[0]=inf;
rep(i,1,n+1){
scanf("%d",&a[i]);
if(i==1){
num[i]=1;
}
else if(a[i]==a[i-1]){
num[i]=num[i-1]+1;
}
else{
num[i]=1;
}
}
per(i,1,n+1){
if(a[i]==a[i+1]){
rt[i]=rt[i+1];
}
else{
rt[i]=i;
}
}
rmq(n);
int l,r,t,tmp,ans;
while(q--){
scanf("%d%d",&l,&r);
if(rt[l-1]==rt[l]) t=min(r,rt[l])+1;
else t=l;
tmp=myquery(t,r);
ans=max(t-l,tmp);
cout<<ans<<endl;
}
}
return 0;
}