【洛谷】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;
}
相关推荐
聚客AI10 小时前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
大怪v13 小时前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
惯导马工14 小时前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
骑自行车的码农16 小时前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了16 小时前
AcWing学习——双指针算法
c++·算法
moonlifesudo17 小时前
322:零钱兑换(三种方法)
算法
NAGNIP1 天前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队1 天前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下2 天前
最终的信号类
开发语言·c++·算法