【洛谷】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;
}
相关推荐
罗湖老棍子24 分钟前
【例4-6】香甜的黄油(信息学奥赛一本通- P1345)
算法·图论·dijkstra·floyd·最短路算法·bellman ford
jghhh0140 分钟前
基于C#实现与三菱FX系列PLC串口通信
开发语言·算法·c#·信息与通信
ada7_43 分钟前
LeetCode(python)22.括号生成
开发语言·数据结构·python·算法·leetcode·职场和发展
曹轲恒43 分钟前
JVM之垃圾回收算法(GC)
jvm·算法
YuTaoShao1 小时前
【LeetCode 每日一题】1161. 最大层内元素和——BFS
算法·leetcode·宽度优先
黛色正浓1 小时前
leetCode-热题100-子串合集(JavaScript)
javascript·算法·leetcode
Z1Jxxx1 小时前
字符串翻转
开发语言·c++·算法
闻缺陷则喜何志丹1 小时前
【前缀和 期望】P7875 「SWTR-7」IOI 2077|普及+
c++·算法·前缀和·洛谷·期望
CoovallyAIHub2 小时前
超越Sora的开源思路:如何用预训练组件高效训练你的视频扩散模型?(附训练代码)
深度学习·算法·计算机视觉
源来猿往2 小时前
yolov8n结构化剪枝
算法·yolo·剪枝