Frequent values RMQ

来源:互联网 发布:php数组赋值给js数组 编辑:程序博客网 时间:2024/06/06 00:00

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 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 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 102 31 105 100
Sample Output
143


这题的意思是:给出n个数和Q个询问(l,r),对于每个询问求出(l,r)之间连续出现次数最多的次数。

将原序列转换一下,if(num[i]==num[i-1])   f[i]=f[i-1]+1;

                                else   f[i]++;

对于每个询问(l,r),分为两个部分,前半部分求与l之前相同的数的个数直到t,后半部分从t开始直接用RMQ求解最大值就行了。

最后结果为max(前半部分,后半部分)。


然后用RMQ

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#define MAXN 100000
#define INF 0x3f3f3f
using namespace std;
int dp[MAXN][50];
int n;
int a[MAXN],num[MAXN],rt[MAXN];
void rmqis()
{
    for(int j=1;(1<<j)<=n;j++)
    {
        for(int i=1;i+(1<<j)-1<=n;i++)
        {
            dp[i][j]=max(dp[i][j-1],dp[i+(1<<(j-1))][j-1]);
        }
    }
}
int rmq(int l,int r)
{
    if(l>r) return 0;
    int k=0;
    while((1<<(k+1))<=r-l+1) k++;
    return max(dp[l][k],dp[r-(1<<k)+1][k]);
}
int main()
{
    int q;
    while(scanf("%d",&n)&&n)
    {
        scanf("%d",&q);
        a[0]=INF;
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
            if(i==1)
                num[i]=1;
            else if(a[i]==a[i-1])
                num[i]=num[i-1]+1;
            else
                num[i]=1;
                dp[i][0]=num[i];
        }
        for(int i=n;i>=1;i--)
        {
            if(a[i]==a[i+1]) rt[i]=rt[i+1];
            else rt[i]=i;
        }
        rmqis();
        int l,r,t,ans,tm;
        while(q--)
        {
            scanf("%d%d",&l,&r);
            if(rt[l-1]==rt[l]) t=min(r,rt[l])+1;
            else t=l;
            tm=rmq(t,r);
            ans=max(tm,t-l);
            printf("%d\n",ans);
        }
    }
    return 0;
}

人一我百!人十我万!永不放弃~~~怀着自信的心,去追逐梦想。

原创粉丝点击