POJ 3368 (RMQ)

                                                                                                                           Frequent values
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 9430 Accepted: 3405

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 indicesi andj (1 ≤ i ≤ j ≤ n). For each query, determine the most frequent value among the integersai , ... , aj.

Input

The input consists of several test cases. Each test case starts with a line containing two integersn andq (1 ≤ n, q ≤ 100000). The next line containsn integersa1 , ... , an (-100000 ≤ ai ≤ 100000, for eachi ∈ {1, ..., n}) separated by spaces. You can assume that for eachi ∈ {1, ..., n-1}: ai ≤ ai+1. The followingq lines contain one query each, consisting of two integersi 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.



把原数列转化一下。。。

     if (num2[i] == num2[i-1]) num[i] = num[i-1]+1;
       else num[i] = 1;

然后对查询区间[l,r]分两部分,前面被切割部分和后面完整部分,前面直接计数,后面完整部分RMQ求最大值


#include<stdio.h>
#include<iostream>
#include<math.h>
#include<string.h>

using namespace std;

#define clear(a,b) memset(a,b,sizeof(a))
#define MAXN 100100
#define mmax(a,b) ((a)>(b)?(a):(b))
#define mmin(a,b) ((a)>(b)?(b):(a))

int num2[MAXN],num[MAXN];
int f1[MAXN][100]; //max


//spatse table

void st(int n)
{
    int i,j,k,m;
    k = (int)(log((double)n)/log(2.0));
    for(i = 1;i <= n;i++)
      f1[i][0] = num[i];
    for(j = 1;j <= k;j++) {
      for(i = 1;i+(1<<j)-1 <= n;i++) {
        m = i + (1<<(j-1));
        f1[i][j] = mmax(f1[i][j-1],f1[m][j-1]);
        }
      }
}

int rmq_max(int i,int j)
{
   if (i > j) return 0;
   int k = (int)(log((double)(j-i+1))/log(2.0));
   return mmax(f1[i][k],f1[j-(1<<k)+1][k]);
}

int work()
{
   int n,q,i,l,r,t;
   scanf("%d",&n);
   if (n == 0) return 0;
   scanf("%d",&q);
   clear(num,0);
   clear(num2,0);
   clear(f1,0);
   num2[0] = MAXN;
   for(i = 1;i <= n;i++) {
     scanf("%d",&num2[i]);
     if (num2[i] == num2[i-1]) num[i] = num[i-1]+1;
       else num[i] = 1;
     }
   st(n);
   for(i = 1;i <= q;i++) {
     scanf("%d%d",&l,&r);
     t = l;
     while (num2[t] == num2[t-1] && t <= r) t++;
     printf("%d\n",mmax(t-l,rmq_max(t,r)));
     }
   return 1;
}

int main()
{
    while(work());
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值