Frequent values
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 Specification
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 Specification
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
解决方案:由于它是按不降序输入,所以,可将其进行游程编码,这样可分成几段,相同的分做一段。Right[i]数组表示该位置所在段的右端点,Left[i]数组表示该位置所在段的左端点,cnt[cur]表示每段的元素个数,num[i]表示该位置所在段的编号,把cnt[i]处理区间查询数组d[i][j]中。这样处理好之后,对于L、R,先是Right[L]-L+1,R-Left[R]+1,这两端的个数,再是RMQ(num[L]+1,num[R]-1);在三者中选最大值即可。
code:#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> #include<cmath> #include <climits> #define MMAX 100010 using namespace std; int d[MMAX][25]; int cnt[MMAX]; int Left[MMAX]; int Right[MMAX]; int num[MMAX]; int Size,N,Q; int value[MMAX]; void init_(){ int pre=INT_MAX,l,cur=-1; for(int i=0;i<N;i++){ if(value[i]==pre){ cnt[cur]++;///该段的相同元素的个数 num[i]=cur;///该位置所在段的编号 Left[i]=l;///该位置所在段的左端点 } else { if(cur>=0){ for(int j=l;j<=i-1;j++){ Right[j]=i-1; }///该位置所在段的右端点 } cur++;///另起一个新段 cnt[cur]=1;///该新段开始只有一个元素 num[i]=cur;///该位置所在段的编号 l=i;///把左端点记下 Left[i]=l;///该位置所在段的左端点 pre=value[i];///记下该段的元素的值 } } for(int i=l;i<N;i++){ Right[i]=N-1;///最后一段的右端点 } Size=cur+1; } void RMQ_init(){ for(int i=0;i<Size;i++) d[i][0]=cnt[i]; for(int j=1;(1<<j)<=Size;j++) for(int i=0;i+(1<<j)-1<Size;i++) d[i][j]=max(d[i][j-1],d[i+(1<<(j-1))][j-1]); }///初识化RMQ; int RMQ(int L,int R){ if(L>R) return 0; int k=0; while((1<<(k+1)<=R-L+1)) k++; return max(d[L][k],d[R-(1<<k)+1][k]); }///RMQ查询; int main(){ while(~scanf("%d",&N)){ if(N==0) break; scanf("%d",&Q); for(int i=0;i<N;i++){ scanf("%d",&value[i]); } memset(cnt,0,sizeof(cnt)); init_(); RMQ_init(); for(int i=0;i<Q;i++){ int L,R; scanf("%d%d",&L,&R); L--,R--; if(num[L]==num[R]) {printf("%d\n",R-L+1);continue;} int c1=Right[L]-L+1; int c2=R-Left[R]+1; int c3=RMQ(num[L]+1,num[R]-1); printf("%d\n",max(c1,max(c2,c3))); } } return 0;}