【洛谷】P2880 [USACO07JAN] Balanced Lineup G 的题解

【洛谷】P2880 [USACO07JAN] Balanced Lineup G 的题解

题目传送门

题解

写完模板来水一道 RMQ

题目很简单了,就是求一个区间内的最大值减掉最小值了。所以 RMQ 走起。

设 a [ i ] a[i] a[i] 是要求区间最值的数列, F [ i ] [ j ] F[i][j] F[i][j] 表示从第 i i i 个数起连续 2 j 2^j 2j 个数中的最大值。

F [ 1 ] [ 0 ] F[1][0] F[1][0] 表示第 1 1 1 个数起,长度为 2 0 = 1 2^0=1 20=1 的最大值,其实就是 3 3 3 这个数。

我们可以容易的看出 F [ i ] [ 0 ] F[i][0] F[i][0] 就等于 a [ i ] a[i] a[i]。

接下来就是正常的递推倍增,我们把 F [ i ] [ j ] F[i][j] F[i][j] 平均分成两段, 从 i i i 到 i + 2 ( j − 1 ) − 1 i + 2 ^ (j - 1) - 1 i+2(j−1)−1 为一段, i + 2 ( j − 1 ) i + 2 ^ (j - 1) i+2(j−1) 到 i + 2 j − 1 i + 2 ^ j - 1 i+2j−1 为一段。

于是我们得到了状态转移方程 F [ i , j ] = max ⁡ ( F [ i ] [ j − 1 ] , F [ i + 2 j − 1 ] [ j − 1 ] ) F[i,j]=\max(F[i][j-1],F[i+2^{j-1}][j-1]) F[i,j]=max(F[i][j−1],F[i+2j−1][j−1])。

代码

复制代码
#include <bits/stdc++.h>
#define lowbit(x) x & (-x)
#define endl "\n"
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
namespace fastIO {
	inline int read() {
		register int x = 0, f = 1;
		register char c = getchar();
		while (c < '0' || c > '9') {
			if(c == '-') f = -1;
			c = getchar();
		}
		while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
		return x * f;
	}
	inline void write(int x) {
		if(x < 0) putchar('-'), x = -x;
		if(x > 9) write(x / 10);
		putchar(x % 10 + '0');
		return;
	}
}
using namespace fastIO;
int n, q;
int a[50005], v[50005][25], h[50005][25];
int main() {
	//freopen(".in","r",stdin);
	//freopen(".out","w",stdout);
	n = read(), q = read();
	a[0] = -1;
	for(int i = 1; i <= n; i ++) {
		h[i][0] = read();
		v[i][0] = h[i][0];
		a[i] = a[i >> 1] + 1;
	}
	for(int j = 1; (1 << j) <= n; j ++) {
		for(int i = 1; i + (1 << j) - 1 <= n; i ++) {
			v[i][j] = min(v[i][j - 1], v[i + (1 << j - 1)][j - 1]);
			h[i][j] = max(h[i][j - 1], h[i + (1 << j - 1)][j - 1]);
		}
	}
	while(q --) {
		int l, r;
		l = read(), r = read();
		int x = a[r - l + 1];
		write(max(h[l][x], h[r - (1 << x) + 1][x]) - min(v[l][x], v[r - (1 << x) + 1][x])), putchar('\n');
	}
	return 0;
}
相关推荐
今禾23 分钟前
一行代码引发的血案:new Array(5) 到底发生了什么?
前端·javascript·算法
橙几33 分钟前
击败了90%的解法?Two Sum 从 O(n²) 到 O(n) 的优化之路
算法
叶子爱分享1 小时前
经典排序算法之归并排序(Merge Sort)
算法·排序算法
珹洺1 小时前
C++算法竞赛篇:DevC++ 如何进行debug调试
java·c++·算法
呆呆的小鳄鱼2 小时前
leetcode:冗余连接 II[并查集检查环][节点入度]
算法·leetcode·职场和发展
墨染点香2 小时前
LeetCode Hot100【6. Z 字形变换】
java·算法·leetcode
沧澜sincerely2 小时前
排序【各种题型+对应LeetCode习题练习】
算法·leetcode·排序算法
CQ_07122 小时前
自学力扣:最长连续序列
数据结构·算法·leetcode
弥彦_2 小时前
cf1925B&C
数据结构·算法
YuTaoShao2 小时前
【LeetCode 热题 100】994. 腐烂的橘子——BFS
java·linux·算法·leetcode·宽度优先