Frequent values
You are given a sequence of n integers a1, a2, ..., an in non-decreasing order. In addition to the, you
is 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 the 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 this for each i∈{1, ..., n−1}: Ai≤ai+1. The
Following q lines contain one query each, consisting of the integers I and J (1≤i≤j≤n), which
Indicate the boundary indices for the query.
The last test case was followed by a line containing a single ' 0 '.
Output
For each query, print one line with one integer:the number of occurrences of the frequent value
Within the given range.
Note:a naive algorithm may not run in time!
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
Test instructions
Give you the number of n, q times ask
Each query is the number of repetitions between l,r
Exercises
Since this n number is ascending, we will subdivide it by asking the same number in each position to the left and right to the leftmost position and the right position.
Handled this, using the RMQ solution, judged the largest
Max (RMQ (righti+1,reftj−1), Max (righti−i+1,j−leftj+1))
#include <iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<cmath>#include<map>using namespacestd; typedefLong Longll;Const intN =100000+Ten;inta[n],x,q,n,dp[n][ -],y,l[n],r[n],h[n];;voidRMQ () { for(inti =1; I <= N; i++) dp[i][0] = R[h[i] [L[h[i]] +1; for(inti =1; (1<<i) <= N; i++) { for(intj =1; (J + (1<<i)-1) <= N; J + +) {Dp[j][i]= Max (dp[j][i-1],dp[j + (1<< (I-1))][i-1]); } }}intQueryintLintr) {if(L = = r)return 1; Else if(L > R)return 0; intK = (int) ((Log (Double) (R-l +1))/log (2.0)); returnMax (Dp[l][k], Dp[r-(1<<K) +1][k]);} Map<int,int>MP;intMain () { while(SCANF ("%d%d", &n, &q) = =2&&N) {mp.clear ();intCNT =0; memset (H,0,sizeof(h)); Memset (DP,0,sizeof(DP)); for(inti =1; I <= N; i++) {scanf ("%d",&x); if(Mp[x]) h[i] = cnt, r[cnt] = i, mp[x]++; ElseH[i] = + + cnt, l[cnt] = i, r[cnt] = i,mp[x] =1; } RMQ (); for(inti =1; I <= Q; i++) {scanf ("%d%d",&x,&X); if(H[x] = = H[y]) printf ("%d\n", Y-x +1); Elseprintf ("%d\n", max (query (r[h[x]) +1, L[h[y]]-1), Max (R[h[x])-X +1, Y-l[h[y]] +1))); } } return 0;}
UVA 11235 Frequent values RMQ