POJ 3368 Frequent values (RMQ)

题目链接:http://poj.org/problem?id=3368

题目大意:

给出一个n个数长度的串, m个询问

求出给定范围内的最大连续字符串的长度

方法:

RMQ模板, 记录每个位置的数连续的次数,用RMQ求出每个区间的最大连续字符的长度值

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>

using namespace std;
const int maxn = 100010;
int A[maxn];
int Max[maxn][20];
int f[maxn];

void RMQ(int n)
{
	int k = (int )(log(n) / log(2));
	for(int j=1; j<=k; j++)
		for(int i=1; i<=n; i++)
			if(i + (1<<j) - 1 <= n){
				Max[i][j] = max(Max[i][j-1], Max[i+(1<<(j-1))][j-1]);
			}
}

int main()
{
	int n, q;
	while(~scanf("%d",&n) && n)
	{
		scanf("%d",&q);
		memset(f, 0, sizeof(f));
		for(int i=1; i<=n ;i++){
			scanf("%d", &A[i]);
			if(A[i] == A[i-1] && i > 1)
				f[i] = f[i-1] + 1;
			else {
				f[i]++;
			}
			Max[i][0] = f[i];
		}
		RMQ(n);
		//for(int i=1; i<=n; i++)
		//	printf("%d ",f[i]);
		while(q--){
			int a, b;
			scanf("%d%d",&a,&b);
			int t = a;
			while(t <= b && A[t] == A[t-1])
				t++;
			int k = (int )(log(b-t+1)/log(2));
			int ans;
			if(t > b)
				ans = 0;
			else 
				ans = max(Max[t][k], Max[b-(1<<k)+1][k]);
			printf("%d\n", max(ans,t-a));
		}
	}
	return 0;
}











你可能感兴趣的:(POJ 3368 Frequent values (RMQ))