POJ 3368 Frequent values (基础RMQ)

来源:互联网 发布:谁的java视频教程好 编辑:程序博客网 时间:2024/06/16 06:18


Frequent values
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 14742 Accepted: 5354

Description

You are given a sequence of n integersa1 , a2 , ... , an in non-decreasing order. In addition to that, you are given several queries consisting of indicesi and j (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 single0.

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

Source

Ulm Local 2007

题目链接:http://poj.org/problem?id=3368

题目大意:有一串数字,查询区间中频数最大的数字的频数

题目分析:因为数字是按非递增序排列好的,我们可以先预处理出某连续数字在当前位置时出现的频数,比如样例有
dp[1]=1,val[1] = -1
dp[2]=2,val[2] = -1
dp[3]=1,val[3] = 1
dp[4]=2,val[4] = 1
dp[5]=3,val[5] = 1
dp[6]=4,val[6] = 1
。。。
则对于查询区间(l,r),答案即为区间(l,tmp)和(tmp,r)某一数字出现的频数的较大的那个(l <= tmp <= r)
对于区间(l,tmp)直接可得出答案,对于区间(tmp, r)我们可以用RMQ求解

代码:
#include <cstdio>#include <cstring>#include <algorithm>#include <cmath>using namespace std;int const MAX = 100005;int st[MAX][20], dp[MAX], val[MAX];int n, q;void RMQ_Init(){    for(int i = 1; i <= n; i++)        st[i][0] = dp[i];    int k = log((double)(n + 1)) / log(2.0);    for(int j = 1; j <= k; j++)        for(int i = 1; i + (1 << j) - 1 <= n; i++)            st[i][j] = max(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);}int Query(int l, int r){    if(l > r)        return 0;    int k = log((double)(r - l + 1)) / log(2.0);    return max(st[l][k], st[r - (1 << k) + 1][k]);}int main(){    while(scanf("%d", &n) != EOF && n)    {           scanf("%d", &q);        dp[1] = 1;        for(int i = 1; i <= n; i++)        {            scanf("%d", &val[i]);            if(i > 1)                dp[i] = (val[i] == val[i - 1] ? dp[i - 1] + 1 : 1);        }        RMQ_Init();        while(q--)        {            int l, r;            scanf("%d %d", &l, &r);            int tmp = l;            while(tmp <= r && val[tmp] == val[tmp - 1])                tmp ++;            printf("%d\n", max(Query(tmp, r), tmp - l));        }    }}


0 0