码迷,mamicode.com
首页 > 其他好文 > 详细

uva 11235 - Frequent values(RMQ)

时间:2014-08-24 23:53:23      阅读:317      评论:0      收藏:0      [点我收藏+]

标签:style   http   color   os   io   for   ar   amp   line   

题目链接:uva 11235 - Frequent values

题目大意:给定一个非降序的整数数组,要求计算对于一些询问(i,j),回答ai,ai+1,,aj中出现最多的数出现的次数。

解题思路:因为序列为非降序的,所以相同的数字肯定是靠在一起的,所以用o(n)的方法处理处每段相同数字的区间。然后对于每次询问:

  • num[i]=num[j]:j?i+1
  • numinumj:max(RMQ(righti+1,reftj?1),max(righti?i+1,j?leftj+1))
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;
const int maxn = 1e5+5;

int N, Q, num[maxn], rmq[maxn][20];
int left[maxn], right[maxn];

void RMQ_init () {
    memset(rmq, 0, sizeof(rmq));
    for (int i = 1; i <= N; i++)
        rmq[i][0] = right[i] - left[i] + 1;

    for (int j = 1; (1<<j) <= N; j++) {
        for (int i = 1; i + (1<<j) - 1 <= N; i++)
            rmq[i][j] = max(rmq[i][j-1], rmq[i+(1<<(j-1))][j-1]);
    }
}

void init () {
    for (int i = 1; i <= N; i++)
        scanf("%d", &num[i]);

    left[1] = 1;
    for (int i = 2; i <= N; i++) {
        if (num[i] == num[i-1])
            left[i] = left[i-1];
        else
            left[i] = i;
    }

    right[N] = N;
    for (int i = N-1; i >= 1; i--) {
        if (num[i] == num[i+1])
            right[i] = right[i+1];
        else
            right[i] = i;
    }
    RMQ_init();
}

int RMQ (int L, int R) {
    if (L > R)
        return 0;
    int k = 0;
    while (1<<(k+1) <= R-L+1)
        k++;
    return max(rmq[L][k], rmq[R-(1<<k)+1][k]);
}

int main () {
    while (scanf("%d%d", &N, &Q) == 2 && N) {
        init();
        int x, y;
        for (int i = 0; i < Q; i++) {
            scanf("%d%d", &x, &y);
            if (num[x] == num[y])
                printf("%d\n", y - x + 1);
            else
                printf("%d\n", max(RMQ(right[x]+1, left[y]-1), max(right[x] - x + 1, y - left[y] + 1)));
        }
    }
    return 0;
}

uva 11235 - Frequent values(RMQ)

标签:style   http   color   os   io   for   ar   amp   line   

原文地址:http://blog.csdn.net/keshuai19940722/article/details/38804381

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!