Frequently values UVA11235




#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <queue>
#include <algorithm>
#include <vector>
#include <cstring>
#include <stack>
#include <cctype>
#include <utility>   
#include <map>
#include <string>  
#include <climits> 
#include <set>
#include <string>    
#include <sstream>
#include <utility>   
#include <ctime>

using std::priority_queue;
using std::vector;
using std::swap;
using std::stack;
using std::sort;
using std::max;
using std::min;
using std::pair;
using std::map;
using std::string;
using std::cin;
using std::cout;
using std::set;
using std::queue;
using std::string;
using std::istringstream;
using std::make_pair;
using std::getline;
using std::greater;
using std::endl;

const int MAXN(100010);
const int MAXH(20);

int count[MAXN], left[MAXN], right[MAXN], num[MAXN], arr[MAXN];

struct RMQ
{
	int ind[MAXN][MAXH];
	int N;
	int mmx(int op1, int op2)
	{
		return count[op1] >= count[op2]? op1: op2;
	}
	void init()
	{
		for(int i = 1; i <= N; ++i)
			ind[i][0] = i;
		for(int i = 1; (1 << i) <= N; ++i)
		{
			int temp = 1 << i;
			for(int j = 1; (j+temp-1) <= N; ++j)
				ind[j][i] = mmx(ind[j][i-1], ind[j+(1 << (i-1))][i-1]);
		}
	}
	int query(int l, int r)
	{
		int len = r-l+1;
		int temp = 0;
		while((1 << temp) <= len)
			++temp;
		--temp;
		return mmx(ind[l][temp], ind[r-(1 << temp)+1][temp]);
	}
};

RMQ rmq;

int main()
{
	int n, q;
	while(scanf("%d", &n), n)
	{
		scanf("%d", &q);
		for(int i = 1; i <= n; ++i)
			scanf("%d", arr+i);
		int cnt = 1, ts = 1;
		num[1] = 1;
		for(int i = 2; i <= n; ++i)
			if(arr[i] != arr[ts])
			{
				count[cnt] = i-ts;
				left[cnt] = ts;
				right[cnt] = i-1;
				++cnt;
				ts = i;
				num[i] = cnt;
			}
			else
				num[i] = cnt;
		count[cnt] = n-ts+1;
		left[cnt] = ts;
		right[cnt] = n;
		int ql, qr;
		rmq.N = cnt;
		rmq.init();
		for(int i = 0; i < q; ++i)
		{
			scanf("%d%d", &ql, &qr);
			int ans;
			if(num[ql] == num[qr])
				ans = qr-ql+1;
			else
				if(num[ql]+1 == num[qr])
					ans = max(right[num[ql]]-ql+1, qr-left[num[qr]]+1);
				else
					ans = max(count[rmq.query(num[ql]+1, num[qr]-1)], max(right[num[ql]]-ql+1, qr-left[num[qr]]+1));
			printf("%d\n", ans);
		}
	}
	return 0;
}


你可能感兴趣的:(Frequently values UVA11235)