[题]Balanced Lineup G #倍增

题目

Balanced Lineup G


不知道为什么,假如我把初始化函数Init()放在输入之前就会无法初始化……迷惑,这种奇奇怪怪的错误能够卡我半小时。


代码

#include
using namespace std;
const int N = 1e5 + 10;

int p[20], Log[N];
int n, q;
int f[N][20], d[N][20];
void init()
{
	p[0] = 1;
	for(int i = 1; i <= 16; i ++) p[i] = p[i - 1] << 1;
	Log[0] = -1;
	for(int i = 1 ; i <= n ; i++) Log[i] = Log[i >> 1] + 1;
}

int main()
{
	scanf("%d%d", &n, &q);
	init();
	for(int i = 1; i <= n; i ++)
	{
		scanf("%d", &f[i][0]);
		d[i][0] = f[i][0];
	}	
	
	for(int len = 1; len <= Log[n]; len ++)
		for(int i = 1; i + p[len] - 1 <= n; i ++)
		{
			f[i][len] = max(f[i][len - 1], f[i + p[len - 1]][len - 1]);
			d[i][len] = min(d[i][len - 1], d[i + p[len - 1]][len - 1]);
		}	
	
	for(int i = 1; i <= q; i ++)
	{
		int l, r;
		scanf("%d%d", &l, &r);
		int l_2 = Log[r - l + 1];
		printf("%d\n", max(f[l][l_2], f[r - p[l_2] + 1][l_2]) - min(d[l][l_2], d[r - p[l_2] + 1][l_2]));
	}
//	for(int i = 1; i <= n; i ++) printf("%d\n", Log[i]);
	return 0;
}

你可能感兴趣的:(算法,c++)