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 iand 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 nintegers 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
题意:按顺序给出n个数,m次询问,每次给出一组x,y,问从x到y,同一数字出现的最多次数为多少。如测试案例中:1-10中,1出现次数最多出现了4次,5-10中10出现次数最多为3次。
思路:首先从整体上将每个数出现的次数算出来存入a[i]中,例如测试案例中得出的a[i]应当为:1,2,1,2,3,4,1,1,2,3。然后计算区间[x,y]中出现最多的次数,这个地方我个人认为很有技巧性,看了题解恍然大悟,比如[3,9],分别为:1,1,1,1,3,10,10 先从左边找连续的相同数字的个数,找到了4个1,然后结束,再从3,10,10中找a[i]最大的值,也就是a[9]=2,最后比较4和2,很明显4大。为什么要这样比较呢?举个例子吧:[5,10]:1,3,10,10,10 a[6]虽然等于4,但是在这个区间里只有一个1,这个位置应当为1,而不是4,所以通过while(t<=y&&in[t]==in[t-1]) t++;这句话来求出左边的值,剩下的都是又顺序的,所以无需再求,按照a[i]的值就行啦。
AC代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<utility>
#include<set>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#define maxn 100010
#define INF 0x3f3f3f3f
#define LL long long
#define ULL unsigned long long
#define E 1e-8
#define mod 1000000007
#define P pair<int,int>
using namespace std;
int a[maxn],in[maxn];
int maxsum[maxn][25];
int MAX[maxn][25];
void ST(int n) //预处理->O(nlogn)
{
for(int i=1;i<=n;++i){
maxsum[i][0] = a[i];
}
for(int j=1; j<20; ++j){
for(int i=1; i+(1<<j)<=n+1; ++i){
maxsum[i][j] = max(maxsum[i][j-1], maxsum[i+(1<<(j-1))][j-1]); //区间最大
}
}
}
int query(int l, int r) //查询->O(1)
{
int k = 0;
if(l>r) return 0; //不能忽略
while((1 << (k +1)) <= r - l + 1)k++;
return max(maxsum[l][k], maxsum[r - (1 << k) + 1][k]);
}
int main()
{
int n,m,x,y;
while(scanf("%d %d",&n,&m)!=EOF&&n){
memset(a,0,sizeof(a));
memset(in,0,sizeof(in));
for(int i=1;i<=n;++i){
scanf("%d",&in[i]);
if(i==1){
a[i] = 1;
continue;
}
if(in[i]==in[i-1]) a[i] = a[i-1]+1;
else a[i] = 1;
}
ST(n);
for(int i=1;i<=m;++i){
scanf("%d %d",&x,&y);
int t = x;
while(t<=y&&in[t]==in[t-1]) t++; //重点所在
int cnt = query(t,y);
int ans = max(t-x,cnt);
printf("%d\n",ans);
}
}
return 0;
}