Frequent values POJ - 3368
Posted 啦啦啦
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Frequent values POJ - 3368相关的知识,希望对你有一定的参考价值。
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
------------------------详解请看http://blog.sina.com.cn/s/blog_6635898a0100kzpx.html
1 #include<cmath> 2 #include<cstdio> 3 #include<cstring> 4 #include<iostream> 5 #include<algorithm> 6 #define INF 1e8 7 #define lson l , m , rt << 1 8 #define rson m+1,r, rt << 1 | 1 9 using namespace std; 10 11 const int maxn=100050; 12 13 struct mnode{ int l,r,max; }node[4*maxn]; 14 struct mnseg{ int sta,end; }seg[maxn]; 15 16 int n,q; 17 int num[maxn],hash[maxn]; 18 19 void Inite(){ //将序列处理成点的集合 20 for(int i=1;i<=n;i++) scanf("%d",&num[i]); 21 int k=0,pre=999999; 22 for(int i=1;i<=n;i++){ 23 if(num[i]!=pre){ 24 pre=num[i]; 25 k++; 26 seg[k].sta=i; 27 seg[k].end=i; 28 } 29 else seg[k].end=i; 30 hash[i]=k; 31 } 32 } 33 34 void Build(int l,int r,int rt){ 35 node[rt].l=l; 36 node[rt].r=r; 37 if(l==r){ node[rt].max=seg[l].end-seg[l].sta+1; return; } 38 int m=(l+r)>>1; 39 Build(lson); 40 Build(rson); 41 node[rt].max=max(node[rt<<1].max,node[(rt<<1)|1].max); 42 } 43 44 int Query(int l,int r,int rt){ //key point!!!! 45 if(node[rt].l==l&&node[rt].r==r) return node[rt].max; 46 if(r<=node[rt<<1].r) return Query(l,r,rt<<1); 47 if(l>=node[(rt<<1)|1].l) return Query(l,r,(rt<<1)|1); 48 int a=Query(l,node[rt<<1].r,rt<<1); 49 int b=Query(node[(rt<<1)|1].l,r,(rt<<1)|1); 50 return max(a,b); 51 } 52 53 int main() 54 { while(~scanf("%d",&n)){ 55 if(n==0) break; 56 scanf("%d",&q); 57 58 Inite(); 59 Build(1,n,1); 60 while(q--){ 61 int a,b,pos1,pos2; 62 scanf("%d%d",&a,&b); 63 pos1=hash[a],pos2=hash[b]; 64 if(pos1==pos2) cout<<b-a+1<<endl; 65 else{ 66 int n1,n2,n3; 67 n1=seg[pos1].end-a+1; 68 n2=0; 69 n3=b-seg[pos2].sta+1; 70 if(pos2-pos1>1) n2=Query(pos1+1,pos2-1,1); 71 cout<<max(n1,max(n2,n3))<<endl; 72 } 73 } 74 } 75 return 0; 76 }
以上是关于Frequent values POJ - 3368的主要内容,如果未能解决你的问题,请参考以下文章
POJ 3368 Frequent values (ST表)
POJ3368Frequent values[RMQ 游程编码]