题目
Frequent values
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 15658 Accepted: 5702
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 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
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
题意
给出一个递增序列,问某个区间里最多的数出现了几次。
题解
先需处理一下,第i个数第一次出现b[i] = 1,第二次出现b[i] = 2……以此内推。线段树维护区间最大值。当我们查询[L,R]时。先看最右端L先左延续了多远。假设延续到x,则[L,R]分为[L,x-1]和[x,R].[L,x-1]又是只有一个元素。所以最值就是x-L。[x,R]用线段树找到最大值就可以了。因为序列预处理是从左往右的。所以线段树里[x,R]的最大值的那个区间是全部在[x,R]里的。PS数组要尽量开大。poj测试数据有超过题目数据范围的。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <stack>
#include <string>
#include <set>
#include <cmath>
#include <map>
#include <queue>
#include <sstream>
#include <vector>
#define m0(a) memset(a,0,sizeof(a))
#define mm(a) memset(a,0x3f,sizeof(a))
#define m_1(a) memset(a,-1,sizeof(a))
#define f(i,a,b) for(i = a;i<=b;i++)
#define fi(i,a,b) for(i = a;i>=b;i--)
#define lowbit(a) ((a)&(-a))
#define FFR freopen("data.in","r",stdin)
#define FFW freopen("data.out","w",stdout)
#define SIGN_MAX 0x3f3f3f3f
using namespace std;
#define SIZE 1000000
int a[SIZE];
int b[SIZE];
int E;
int T[SIZE*8+100];
void init(int n){
E = 1;
int i;
while(E<=(n+1))E<<=1;
f(i,1,E*2+10){
T[i] = -SIGN_MAX;
}
}
void Push_up(int t){
T[t] = max(T[t<<1],T[t<<1|1]);
}
void aP(int t,int k){
for(T[t+=E]= k,t>>=1;t;t>>=1)
Push_up(t);
}
int query(int L,int R){
L+=E-1;
R+=E+1;
int tem = -SIGN_MAX;
for(;L^R^1;L>>=1,R>>=1){
if(~L&1){
if(T[L^1]>tem)
tem = T[L^1];
}
if(R&1){
if(T[R^1]>tem)
tem = T[R^1];
}
}
return tem;
}
int main()
{
// ios_base::sync_with_stdio(false); cin.tie(0);
int n,m;
while(scanf("%d",&n)&&n){
scanf("%d",&m);
int i,j;
init(n);
a[0] = SIGN_MAX;
f(i,1,n) scanf("%d",&a[i]);
b[1] = 1;
f(i,2,n){
if(a[i]==a[i-1])
b[i] = b[i-1] + 1;
else
b[i] = 1;
}
f(i,1,n) aP(i,b[i]);
int k1,k2;
f(i,1,m){
int L,R;
scanf("%d%d",&L,&R);
k1 = L;
while(k1<=R&&a[k1]==a[L])k1++;
k2 = R;
int tem = -SIGN_MAX;
if(k1<=k2)
tem = query(k1,k2);
else
printf("%d\n",R-L+1);
if(k1<=k2){
tem = max(tem,k1-L);
printf("%d\n",tem);
}
}
}
return 0;
}