hdu-1806 Frequent values(RMQ,求区间最大频率)

Frequent values

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1475    Accepted Submission(s): 540


Problem Description
You are given a sequence of n integers a 1 , a 2 , ... , a n 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 a i , ... , a j .

 

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 n integers a 1 , ... , a n(-100000 ≤ a i ≤ 100000, for each i ∈ {1, ..., n}) separated by spaces. You can assume that for each i ∈ {1, ..., n-1}: a i ≤ a i+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的序列,求s~t之间出现最多的数字出现的次数

思路:用a数组存题目给的序列,b数组存后面序列有多少个数字和本身一样,再加上1(本身)

最后求的时候比一下求最大值就好。用RMQ求区间(b数组上)最大值。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
#define N 100010
int a[N]; int b[N]; int dp[N][20]; void makermq(int n) { for(int i=0; i<n; i++)
        dp[i][0]=b[i]; for(int j=1; (1<<j)<=n; j++) { for(int i=0; i+(1<<j)-1<n; i++) {
            dp[i][j]=max(dp[i][j-1],dp[i+(1<<(j-1))][j-1]); } } } int getmax(int s,int t) { int k=(int)(log(t-s+1.0)/log(2.0)); return max(dp[s][k],dp[t-(1<<k)+1][k]); } int finds(int s,int t) { int i=s; while(1) { if(i>=t||a[i]!=a[i+1]) break;
       i++; } return i; } int main() { int n,q; int k,l; while(scanf("%d",&n)&&n) {
        scanf("%d",&q); for(int i=0; i<n; i++)
            scanf("%d",&a[i]); int t=1;
        b[0]=1; for(int i=1; i<n; i++) { if(a[i]==a[i-1])
                t++; else
                t=1;
            b[i]=t; }
        makermq(n); while(q--) {
            scanf("%d %d",&k,&l);
            k--;
            l--; int tm=finds(k,l); int num=tm-k+1; if(tm+1>=l)
                printf("%d\n",num); else
            printf("%d\n",max(num,getmax(tm+1,l))); } } return 0; }

你可能感兴趣的:(hdu-1806 Frequent values(RMQ,求区间最大频率))