Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 13365 | Accepted: 4918 |
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
题意:在一个区间里找相同的数的最大个数。
思路:首先离散化把相同的数合并,并且可以得到对于一个数他的左边界和右边界l[i]和r[i],每次查询特殊处理边界,然后中间的部分用MAX[k][v]表示v及其前2^k的最大值。
AC代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int val[100010],l[100010],r[100010],num[100010],point[200030],parent[30][100010],MAX[30][100010];
int solve(int a,int b)
{ if(b<a || b<0 || a<0)
return 0;
if(a==b)
return num[a];
int len=b-a,k=0;
while((1<<k)<=len)
k++;
k--;
return max(MAX[k][b],solve(a,parent[k][b]));
}
int main()
{ int n,m,i,j,k,u,v,pos,sum,a,b,c,ans;
while(~scanf("%d",&n) && n)
{ scanf("%d",&m);
for(i=1;i<=n;i++)
{ scanf("%d",&val[i]);
val[i]+=100010;
}
val[0]=val[n+1]=0;
for(i=1;i<=n;i++)
if(val[i]==val[i-1])
l[i]=l[i-1];
else
l[i]=i;
for(i=n;i>=1;i--)
if(val[i]==val[i+1])
r[i]=r[i+1];
else
r[i]=i;
pos=1;sum=0;
while(pos<=n)
{ sum++;
point[val[pos]]=sum;
num[sum]=r[pos]-l[pos]+1;
pos=r[pos]+1;
}
point[0]=-1;
for(i=1;i<=sum;i++)
{ parent[0][i]=i-1;
MAX[0][i]=max(num[i-1],num[i]);
}
parent[0][1]=-1;
for(k=0;k<29;k++)
for(v=1;v<=sum;v++)
if(parent[k][v]<0)
{ parent[k+1][v]=-1;
MAX[k+1][v]=MAX[k][v];
}
else
{ parent[k+1][v]=parent[k][parent[k][v]];
MAX[k+1][v]=max(MAX[k][v],MAX[k][parent[k][v]]);
}
while(m--)
{ scanf("%d%d",&a,&b);
ans=0;
ans=max(ans,min(r[a],b)-a+1);
ans=max(ans,b-max(a,l[b])+1);
ans=max(ans,solve(point[val[r[a]+1]],point[val[l[b]-1]]));
printf("%d\n",ans);
}
}
}