Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

RMQ

Posted by 9974 at 2013-04-17 22:22:20 on Problem 3368
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
#define maxn 100005
int a[maxn], v[maxn], c[maxn], p[maxn], l[maxn], r[maxn];
int num, n; // num表示有几段。
int LOG[maxn], f[33][maxn];// LOG[n] = log2(n)向下取整,f数组记录RMQ
void rmq_init() {
	int i, j;
	LOG[0] = -1;
	for (i = 1; i < maxn; i++) 
		LOG[i] = LOG[i >> 1] + 1;
	for (i = 1; i <= num; i++)
		f[0][i] = c[i];
	for (j = 1; j <= LOG[num]; j++) {
		int x = num - (1 << j) + 1;
		for (i = 1; i <= x; i++) {
			int y = i + (1 << j >> 1);
			f[j][i] = max(f[j - 1][i], f[j - 1][y]);
		}
	}
}
int rmq(int l, int r) {
	if (l > r) return 0; // 注意这种情况
	int k = LOG[(r - l + 1)], y = r - (1 << k) + 1;
	return max(f[k][l], f[k][y]);
}
void debug() {
	int i, j;
	for (i = 1; i <= num; i++)
		printf("v[%d] = %d c[%d] = %d\n", i, v[i], i, c[i]);
	for (i = 1; i <= n; i++) {
		printf("p[%d] = %d l = %d r = %d\n", i, p[i], l[i], r[i]);
	}
	for (i = 1; i <= num; i++)
		for (j = i; j <= num; j++)
			printf("[%d, %d] = %d\n", i, j, rmq(i, j));
}
int main() {
	int i, j, k, q;
	while ( ~scanf("%d", &n) && n) {
		scanf("%d", &q);
		for (i = 1; i <= n; i++)
			scanf("%d", &a[i]);
		num = 0;
		for (i = 1; i <= n; i++) {
			for (j = i; j < n && a[j] == a[j + 1]; j++);
			v[++num] = a[i];
			c[num] = j - i + 1;
			for (k = i; k <= j; k++)
				p[k] = num, l[k] = i, r[k] = j;
			i = j;
		}
		rmq_init();
    	//debug();
		int x, y;
		while (q--) {
			scanf("%d%d", &x, &y);
			if(p[x] == p[y]) { printf("%d\n", y-x+1); continue; }
			int t = max(r[x] - x + 1, y - l[y] + 1);
			//cout << "t = " << t << endl;
			printf("%d\n", max(t, rmq(p[x] + 1, p[y] - 1)));
		}
	}
	return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator