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; }