题目链接: Pot!!
大致题意
给定一个长度为n的序列, 初始所有元素都为1. 有如下两种操作:
① MULTIPLY l r x, 给[l, r]都乘上数x.
② MAX l r, 询问[l, r]区间所有数字中, 单个数字质因子出现的最大次数.
解题思路
线段树 做题之前我先看了看大佬们的博客, 都被吓傻了, 四棵线段树解题QAQ. 为什么不能用一棵树来维护四个值呢?
首先分析一下这个题的突破点, 重点是x的取值范围, 只有2~10, 这是什么概念呢? 10之内的质数实际上只有2, 3, 5, 7. 我们其实只需要维护对于每一个数字而言, 唯一分解后, 表示成2p1 + 3p2 + 5p3 + 7p4, 中p1, p2, p3, p4的个数即可.
由于查询是区间查询, 因此可以采用线段树维护. 每个节点需要维护的值即为: 当前区间单个数字max({ p1, p2, p3, p4 });
考虑到要维护的属性有点多, 我们可以封装一个结构体, 来进行每次的操作.(见代码)
AC代码
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 1; i <= (n); ++i)
using namespace std;
typedef long long ll;
const int N = 1E5 + 10;
struct nums {
int a, b, c, d;
bool empty() const { return !a and !b and !c and !d; }
void clear() { a = b = c = d = 0; }
int getmax() const { return max({ a, b, c, d }); }
friend nums tomax(const nums& x, const nums& y) { return { max(x.a, y.a), max(x.b, y.b), max(x.c, y.c), max(x.d, y.d) }; } //传递max
nums operator+ (const nums& t) const { return { a + t.a, b + t.b, c + t.c, d + t.d }; }
}NUM[15]; //NUM存储每个数字的质因子情况
void init() { //预处理2~10的质因子情况.
rep(i, 10) {
int x = i;
while (x and x % 2 == 0) NUM[i].a++, x /= 2;
while (x and x % 3 == 0) NUM[i].b++, x /= 3;
while (x and x % 5 == 0) NUM[i].c++, x /= 5;
while (x and x % 7 == 0) NUM[i].d++, x /= 7;
}
}
struct node { //线段树
int l, r;
nums num;
nums lazy;
}t[N << 2];
void pushdown(node& op, const nums& lazy) {
op.num = op.num + lazy;
op.lazy = op.lazy + lazy;
}
void pushdown(int x) {
if (t[x].lazy.empty()) return;
pushdown(t[x << 1], t[x].lazy), pushdown(t[x << 1 | 1], t[x].lazy);
t[x].lazy.clear();
}
void pushup(int x) { t[x].num = tomax(t[x << 1].num, t[x << 1 | 1].num); }
void build(int l, int r, int x = 1) {
t[x] = { l, r }; t[x].num.clear(), t[x].lazy.clear();
if (l == r) return;
int mid = l + r >> 1;
build(l, mid, x << 1), build(mid + 1, r, x << 1 | 1);
}
void modify(int l, int r, const nums& c, int x = 1) {
if (l <= t[x].l and r >= t[x].r) {
pushdown(t[x], c);
return;
}
pushdown(x);
int mid = t[x].l + t[x].r >> 1;
if (l <= mid) modify(l, r, c, x << 1);
if (r > mid) modify(l, r, c, x << 1 | 1);
pushup(x);
}
int ask(int l, int r, int x = 1) {
if (l <= t[x].l and r >= t[x].r) {
return t[x].num.getmax();
}
pushdown(x);
int mid = t[x].l + t[x].r >> 1;
int res = 0;
if (l <= mid) res = max(res, ask(l, r, x << 1));
if (r > mid) res = max(res, ask(l, r, x << 1 | 1));
return res;
}
int main()
{
init();
int n, m; cin >> n >> m;
build(1, n);
rep(i, m) {
char s[20]; int l, r; scanf("%s %d %d", s, &l, &r);
if (s[1] == 'U') {
int c; scanf("%d", &c);
modify(l, r, NUM[c]);
}
else printf("ANSWER %d\n", ask(l, r));
}
return 0;
}