Codeforces Round 914 (Div. 2)(D1/D2)–ST表
D1. Set To Max (Easy Version)
题意:
给出长度为n的数组a和b,可以对a进行任意次数操作,操作方式为选择任意区间将区间内值全部变成该区间的最大值,
是否有可能使得数组a等于数组b。
思路:
D1允许On^2的时间复杂度,所以可以直接暴力:
- 遍历ab数组,若出现ai>bi,直接NO,不可能修改数更小;
- 否则的话就向该元素两边分别遍历,直到找到符合条件的a元素;
- 注意,当出现遍历a元素大于所需b元素或遍历b元素小于所需b元素时结束查找,因为会造成ai>bi的情况;
AC code:
void solve() {
cin >> n;
for (int i = 1; i <= n; i ++) cin >> a[i];
for (int i = 1; i <= n; i ++) cin >> b[i];
for (int i = 1; i <= n; i ++) {
if (a[i] == b[i]) continue;
if (a[i] > b[i]) {
cout << "NO" << endl;
return;
}
int l = i, r = i;
for (int j = i - 1; j >= 1; j --) {
if (a[j] > b[i] || b[j] < b[i]) {
break;
}
if (a[j] == b[i]) {
l = j;
break;
}
}
for (int j = i + 1; j <= n; j ++) {
if (a[j] > b[i] || b[j] < b[i]) {
break;
}
if (a[j] == b[i]) {
r = j;
break;
}
}
if (a[l] != b[i] && a[r] != b[i]) {
cout << "NO" << endl;
return;
}
} cout << "YES" << endl;
}
D2. Set To Max (Hard Version)
题意:同上
思路:
D2需要O1的查询,则需要用到ST表:
思路与D1相似,在查找过程中,不需要去遍历查询符合条件的元素,通过ST表来进行快速查询区间符合条件的元素;
AC code:
int find(int l, int r) {
int k = g[r - l + 1] / g[2];
return max(st[l][k], st[r - (1 << k) + 1][k]);
}
void solve() {
cin >> n;
for (int i = 1; i <= n; i ++) cin >> a[i];
for (int i = 1; i <= n; i ++) cin >> b[i];
if (n == 1) {
if (a[0] == b[0]) cout << "YES" << endl;
else cout << "NO" << endl;
return;
}
g[1] = 0;
for (int i = 2; i <= n; i ++) g[i] = g[i / 2] + 1;
for (int j = 0; j < 18; j ++)
for (int i = 1; i <= n; i ++)
if (j == 0) st[i][j] = a[i];
else st[i][j] = max(st[i][j - 1], st[i + (1 << j - 1)][j - 1]);
int pos = 1;
for (int i = 1; i <= n; i ++) {
if (a[i] > b[i]) {
cout << "NO" << endl;
return;
}
while (pos <= n && (a[pos] < b[i] || (pos < i && find(pos, i) > b[i]))) pos ++;
if (pos > n || (pos >= i && find(i, pos) > b[i])) {
cout << "NO" << endl;
return;
}
}
cout << "YES" << endl;
}
RMQ算法/ST表–快速查询区间最值
本质上为动态规划,先预处理倍增关系,再进行快速查询
时间复杂度上,预处理为Onlogn,查询为O1
缺点:不能修改
预处理:
st(i, j) :从i开始,长度为 2 j 2^j 2j的区间中的最大值
st(i, j) = max(st(i, j - 1), st(i + 2^(j - 1), j - 1))
查询:
找到最大的小于等于(r - l + 1)的
2
k
2^k
2k的k值,取两段综合最大即为区间最大
即:max(st(l, k), st(r -
2
k
2^k
2k + 1, k));
以下为求取任意区间最大值st表
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
const int N = 2e5+10, M = 18;
int n, m;
int a[N], st[N][M], g[N];
void init() { //预处理
for (int j = 0; j < M; j ++)
for (int i = 1; i + (1 << j) - 1 <= n; i ++)
if (j == 0) st[i][j] = a[i];
else st[i][j] = max(st[i][j - 1], st[i + (1 << j - 1)][j - 1]);
}
int find(int l, int r) { //查询
int len = r - l + 1;
int k = log(len) / log(2);
return max(st[l][k], st[r - (1 << k) + 1][k]);
}
void llg() { //预处理log
g[1] = 0;
for (int i = 2; i <= n; i ++) g[i] = g[i / 2] + 1;
}
int main() {
cin >> n;
for (int i = 1; i <= n; i ++)
cin >> a[i];
init();
cin >> m;
while (m --) {
int l, r; cin >> l >> r;
cout << find(l, r) << endl;
}
return 0;
}