【poj3368 】Frequent values

来源:互联网 发布:湖北襄阳农村淘宝招募 编辑:程序博客网 时间:2024/05/11 21:08

Frequent values
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 20472 Accepted: 7245
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 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 n integers 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
Source

Ulm Local 2007

题目大意:给定一个数组,其中的元素满足非递减顺序,要求对于一对起点
和终点,回答出其中某个元素重复出现的最多次数。
 比如对于-1 -1 1 1 1 1 3 10 10 10,若起点为1,终点为5,则
重复出现最多的数是1,其次数为3

解题报告
原数组是非递减的,因此相同的数字必然是连续出现的。可以对原数
组进行压缩,把相同数字构成的区间抽象为一个数,这个数就是这个
区间的大小。
1、在同一个区间,ans就是两个数间的距离
2、在相邻的两区间,两个点分别到区间端点的距离中的较大值
3、在不相邻的两个区间,2的值与x+1–y-1求个rmq就好
code:

#include<cstdio>#include<cstring>#include<algorithm>#include<cmath>using namespace std;const int MAXN=100001;const int MAX_INT=0X7fffffff;int n,q,last,x,tot,a[MAXN],p[MAXN],s[MAXN],t[MAXN],f[MAXN][21];//p[]记录每个点属于哪个区间void ST(){    int k=log(tot)/log(2);    for (int i=1; i<=tot; i++) f[i][0]=a[i];    for (int j=1; j<=k; j++)        for (int i=1; i+(1<<j)-1<=n; i++)            f[i][j]=max(f[i][j-1],f[i+(1<<(j-1))][j-1]);}int rmq(int L,int R){    int k=log(R-L+1)/log(2);    return max(f[L][k],f[R-(1<<k)+1][k]);}int main(){    scanf("%d%d",&n,&q);    last=MAX_INT;    for (int i=1; i<=n; i++)    {        scanf("%d",&x);        if (x!=last)        {            if (tot) t[tot]=i-1; s[++tot]=i;        }        a[tot]++; p[i]=tot;        last=x;    }    t[tot]=n;/*  for (int i=1; i<=tot; i++) printf("%d %d %d\n",a[i],s[i],t[i]); printf("\n");    for (int i=1; i<=n; i++) printf("%d ",p[i]);*/    ST();    int x,y;    for (int i=1; i<=q; i++)    {        scanf("%d%d",&x,&y);        if (p[x]==p[y]) printf("%d\n",y-x+1);        if (p[y]-p[x]==1) printf("%d\n",max(t[p[x]]-x+1,y-s[p[y]]+1));        if (p[y]-p[x]>1)        {            int ans=max(t[p[x]]-x+1,y-s[p[y]]+1);            ans=max(ans,rmq(p[x]+1,p[y]-1));//传进去的应该是p[]             printf("%d\n",ans);        }    }    return 0;}/*10 3-1 -1 1 1 1 1 3 10 10 102 31 105 10Sample Output143*/ 
原创粉丝点击