D. The Child and Sequence
[link](Problem - D - Codeforces)
题意:
给定一个序列,要你进行区间求和、区间取模、单点修改三个操作。
题解:
考虑用线段树,区间求和,以及单点修改直接操作即可,特殊的在于区间取模这个操作,对于这个操作来看,是很难打个tag并维护的。考虑暴力的话,发现每个数取模以后至少变成原来的二分之一,所以一个数最多被mod log次,记录一个区间最大值,如果当前这个区间的最大值都小于mod那么整个区间就不需要取模了, 否则就暴力递归修改,再维护父节点,复杂度相当于多乘了个logc。
Code
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <set>
#include <queue>
#include <vector>
#include <map>
#include <unordered_map>
#include <cmath>
#include <stack>
#include <iomanip>
#include <deque>
#include <sstream>
#define x first
#define y second
using namespace std;
typedef long double ld;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
typedef unsigned long long ULL;
const int N = 1e5 + 10, M = 2 * N, INF = 0x3f3f3f3f, mod = 1e9 + 7;
const double eps = 1e-8;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int h[N], e[M], ne[M], w[M], idx;
void add(int a, int b, int v = 0) {
e[idx] = b, w[idx] = v, ne[idx] = h[a], h[a] = idx ++;
}
int n, m, k;
int a[N];
struct Node {
int l, r;
LL mx, sum;
}tr[N << 2];
void pushup(int u) {
tr[u].sum = tr[u << 1].sum + tr[u << 1 | 1].sum;
tr[u].mx = max(tr[u << 1].mx, tr[u << 1 | 1].mx);
}
void build(int u, int l, int r) {
tr[u] = {l, r};
if (l == r) {
tr[u].sum = tr[u].mx = a[r];
return ;
}
int mid = l + r >> 1;
build(u << 1, l, mid), build(u << 1 | 1, mid + 1, r);
pushup(u);
}
LL query(int u, int l, int r) {
if (l <= tr[u].l && tr[u].r <= r) return tr[u].sum;
int mid = tr[u].l + tr[u].r >> 1;
LL res = 0;
if (l <= mid) res += query(u << 1, l, r);
if (r > mid) res += query(u << 1 | 1, l, r);
return res;
}
void modify(int u, int pos, int x) {
if (tr[u].l == tr[u].r) {
tr[u].sum = tr[u].mx = x;
return ;
}
int mid = tr[u].l + tr[u].r >> 1;
if (pos <= mid) modify(u << 1, pos, x);
else modify(u << 1 | 1, pos, x);
pushup(u);
}
void modify_mod(int u, int l, int r, int mod) {
if (l > tr[u].r || r < tr[u].l || tr[u].mx < mod) return ; // 剪枝
if (tr[u].l == tr[u].r) { // 单点修改
tr[u].sum = tr[u].mx = tr[u].sum % mod;
return ;
}
int mid = (tr[u].l + tr[u].r) >> 1;
if (l <= mid) modify_mod(u << 1, l, r, mod);
if (r > mid) modify_mod(u << 1 | 1, l, r, mod);
pushup(u);
}
int main() {
ios::sync_with_stdio(false), cin.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i ++ ) cin >> a[i];
build(1, 1, n);
int op;
while (m --) {
cin >> op;
if (op == 1) {
int l, r;
cin >> l >> r;
cout << query(1, l, r) << endl;
}
else if (op == 2) { // 区间取模
int l, r, x;
cin >> l >> r >> x;
modify_mod(1, l, r, x);
}
else {
int pos, x;
cin >> pos >> x;
modify(1, pos, x);
}
}
return 0;
}