Frequent values RMQ

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 10
2 3
1 10
5 10
0
Sample Output
1
4
3


這題的意思是:給出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;
}

人一我百!人十我萬!永不放棄~~~懷着自信的心,去追逐夢想。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章