E - Frequent values

来源:互联网 发布:网络论坛 编辑:程序博客网 时间:2024/05/01 18:39

Time Limit: 2000MS Memory Limit: 65536KB 64bit IO Format: %I64d & %I64u

[Submit]   [Go Back]   [Status]

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 102 31 105 100

Sample Output

143
#include<iostream>#include<string.h>#include<stdio.h>#include<algorithm>using namespace std;#define MAXN 100100int a[MAXN];struct s {int l;int r;int value;}tt[MAXN];struct node {int l;int r;int ma;}t[MAXN*4];void make(int st,int ed,int num){t[num].l=st;t[num].r=ed;if(st==ed){t[num].ma=tt[st].r-tt[st].l+1;return ;}int mid=(t[num].l+t[num].r)/2;make(st,mid,num*2);make (mid+1,ed,2*num+1);t[num].ma=max(t[num*2+1].ma,t[num*2].ma);}int query(int st,int ed,int num){if(st==t[num].l&&ed==t[num].r)returnt[num].ma;int mid=(t[num].l+t[num].r)/2;if(st>mid)return query(st,ed,num*2+1);else if(ed<=mid)return query(st,ed,num*2);else {returnmax(query(st,mid,num*2),query(mid+1,ed,num*2+1));}}int search(int num,int value){int st=1,ed=num;while(st<ed){int mid=(st+ed)/2;if(tt[mid].value>value)ed=mid-1;else if(tt[mid].value<value)st=mid+1;else return mid;}return st;}int main(){int n,q;int e,i;int st,ed;int x,y;int sum;while(scanf("%d%d",&n,&q)!=EOF&&n){e=0;for(i=1;i<=n;i++){scanf("%d",&a[i]);//用tt【】去存储想通值的起点和终点//变相的离散化了///if(tt[e].value!=a[i]){e++;tt[e].l=i;tt[e].r=i;tt[e].value=a[i];}else tt[e].r++;}//printf("%d\n",e);make(1,e,1);for(i=1;i<=q;i++){scanf("%d%d",&x,&y);st=search(e,a[x]);ed=search(e,a[y]);if(st==ed)sum=y-x+1;else if(st+1==ed)sum=max(tt[st].r-x+1,y-tt[ed].l+1);else sum=max(query(st+1,ed-1,1),max(tt[st].r-x+1,y-tt[ed].l+1));printf("%d\n",sum);}}return 0;}

原创粉丝点击