标签:else pac 线段 mod algorithm std include sum 分析
题意:给定一个数组a[1],a[2],...,a[n],他可以进行如下的m个操作,一个操作可以是如下三个的其中一个:1.打印[l, r]的和,即求\(\sum_{i = l}^{r}a[i]\)。2.对[l, r]之间的每个数取模x,\(a[i] = a[i]\quad mod\quad x\)。\(3.让a[k] = x\)。
分析:这道题目的lazy标记无法维护,因为pushdown的时候,上面的lazy标记无法叠加到下面的lazy标记上面。因此,我们需要对区间修改进行常数优化,我们可以发现当一个区间的最大值 <= x的时候,是不需要修改的,否则需要递归对每个数进行修改。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
using LL = long long;
const int N = 100005;
int a[N];
struct Node
{
int l, r;
LL val;
LL mx;
int lazy;
}tr[N * 4];
void pushup(int u)
{
tr[u].val = tr[u << 1].val + tr[u << 1 | 1].val;
//区间最大值
tr[u].mx = max(tr[u << 1].mx, tr[u << 1 | 1].mx);
}
void pushdown(int u)
{
}
void build(int u, int l, int r)
{
tr[u] = { l, r };
if (l == r)
{
tr[u].val = a[l];
tr[u].mx = tr[u].val;
return;
}
int mid = l + r >> 1;
build(u << 1, l, mid), build(u << 1 | 1, mid + 1, r);
pushup(u);
}
//区间修改
void modify(int u, int l, int r, int x)
{
if (tr[u].mx < x) return;
if (tr[u].l == tr[u].r)
{
tr[u].val %= x;
tr[u].mx = tr[u].val;
return;
}
//pushdown(u);
int mid = tr[u].l + tr[u].r >> 1;
if (l <= mid) modify(u << 1, l, r, x);
if (r > mid) modify(u << 1 | 1, l, r, x);
pushup(u);
}
void modify2(int u, int pos, int x)
{
if (tr[u].l == tr[u].r)
{
tr[u].val = x;
tr[u].mx = tr[u].val;
return;
}
int mid = tr[u].l + tr[u].r >> 1;
//pushdown(u);
if (pos <= mid) modify2(u << 1, pos, x);
else modify2(u << 1 | 1, pos, x);
pushup(u);
}
LL query(int u, int l, int r)
{
if (l <= tr[u].l && r >= tr[u].r)
{
return tr[u].val;
}
//pushdown(u);
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;
}
int main()
{
int n, m;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; ++i) scanf("%d", &a[i]);
build(1, 1, n);
int type, l, r;
while (m--)
{
scanf("%d%d%d", &type, &l, &r);
if (type == 1)
{
LL res = query(1, l, r);
printf("%lld\n", res);
}
else if (type == 2)
{
int x;
scanf("%d", &x);
modify(1, l, r, x);
}
else
{
modify2(1, l, r);
}
}
return 0;
}
CodeForces 438D. The Child and Sequence(线段树区间更新)
标签:else pac 线段 mod algorithm std include sum 分析
原文地址:https://www.cnblogs.com/pixel-Teee/p/13227024.html