poj3368 Frequent values

Frequent values
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 15424   Accepted: 5612

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

Source

Ulm Local 2007



#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define F(i,j,n) for(int i=j;i<=n;i++)
#define D(i,j,n) for(int i=j;i>=n;i--)
#define LL long long
#define pa pair<int,int>
#define MAXN 100005
using namespace std;
int n,q,l,r,t,a[MAXN],f[MAXN][20];
int read()
{
	int ret=0,flag=1;
	char ch=getchar();
	while (ch<'0'||ch>'9')
	{
		if (ch=='-') flag=-1;
		ch=getchar();
	}
	while (ch>='0'&&ch<='9')
	{
		ret=ret*10+ch-'0';
		ch=getchar();
	}
	return ret*flag;
}
int rmq(int l,int r)
{
	if (l>r) return 0;
	int t=int(log2(r-l+1));
	return max(f[l][t],f[r-(1<<t)+1][t]);
}
int find(int l,int r,int x)
{
	int mid;
	while (l<=r)
	{
		mid=(l+r)>>1;
		if (a[mid]==x) l=mid+1;
		else r=mid-1;
	}
	return l;
}
int main()
{
	n=read();
	while (n)
	{
		q=read();
		F(i,1,n) a[i]=read();
		f[0][0]=0;
		F(i,1,n) f[i][0]=a[i]==a[i-1]?(f[i-1][0]+1):1;
		for(int i=1;(1<<i)<=n;i++) F(j,1,n-(1<<i)+1)
			f[j][i]=max(f[j][i-1],f[j+(1<<(i-1))][i-1]);
		F(i,1,q)
		{
			l=read();r=read();
			int t=find(l,r,a[l]);
			printf("%d\n",max(t-l,rmq(t,r)));
		}
		n=read();
	}
}


你可能感兴趣的:(poj)