Frequent values (ST表)

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

Hint
A naive algorithm may not run in time!

因为是非下降的序列,所以相同的数字一定是连续的,如题目中的例子,-1出现2次,1出现4次,3出现1次,10出现3次, 用a[i]数组存在位置i的时候,num[i]出现了几次,所以
a[1]=1,a[2]=-1
a[3]=1, a[4]=2, a[5]=3, a[6]=4
a[7]=1
a[8]=1, a[9]=2, a[10]=3
如果询问1-10之间的答案,就是a[6]=4; 如果询问7-10之间的答案就是3
但是如果询问2-3之间出现频率最高的次数,不是a[2]=2,因为-1没有出现两次,所以判断一些num[L]等不等于num[L-1]如果不等于,说明计数从L开始,不妨碍,不然就算一下有多少个num[L],然后取最大的次数

#include<iostream>
#include<string.h>
#include<stdio.h>
#include<algorithm>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<vector>
#include<cmath>
#define LL long long 
#define mem(a, b) memset(a, b, sizeof(a))
#define N 100005 
#define MOD
using namespace std;
const int inf=0x3f3f3f3f;
int n, m, a[N], f[N][64], num[N];

void ST_prework() {
	for(int i=1; i<=n; i++) f[i][0]=a[i];
	int t=log(n)/log(2)+1;
	for(int j=1; j<t; j++) {
		for(int i=1; i<=n-(1<<j)+1; i++){
			f[i][j]=max(f[i][j-1], f[i+(1<<(j-1))][j-1]);
		}	
	}
}

int ST_query(int l, int r) {
	if(l>r) return 0;
	int k=log(r-l+1)/log(2);
	return max(f[l][k], f[r-(1<<k)+1][k]);
}

int main() {
	while(scanf("%d",&n)!=EOF && n){
		scanf("%d",&m);
		mem(f, 0);
		for(int i=1; i<=n; i++){
			scanf("%d",&num[i]);
			if(i==1){
				a[i]=1;
				continue;
			}
			if(num[i]==num[i-1])
				a[i]=a[i-1]+1;
			else a[i]=1;
		}	
		ST_prework();
		for(int i=1; i<=m; i++) {
			int x, y;
			scanf("%d%d",&x, &y);
			int t=x;
			while(t<=y && num[t]==num[t-1])
				t++;
			cout<<max(ST_query(t, y), t-x)<<endl;
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值