﻿ BZOJ 1798 [Ahoi2009]维护序列seq (线段树) - 鸿网互联

1.给一个区间的数乘c
2.给一个区间的数加c
3.查询区间和。

# 代码

``````#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define LL long long
#define Lowbit(x) ((x)&(-x))
#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1|1
#define MP(a, b) make_pair(a, b)
const int INF = 0x3f3f3f3f;
const int maxn = 1e5 + 7;
const double eps = 1e-8;
const double PI = acos(-1.0);

LL p;
LL sum[maxn<<2];

void PushUp(int rt)
{
sum[rt] = (sum[rt<<1] + sum[rt<<1|1]) % p;
}

void PushDown(int rt, int m)
{
mul[rt<<1] = (mul[rt<<1] * mul[rt]) % p;
mul[rt<<1|1] = (mul[rt<<1|1] * mul[rt]) % p;
sum[rt<<1] = (sum[rt<<1] * mul[rt] + add[rt] * (m - (m >> 1))) % p;
sum[rt<<1|1] = (sum[rt<<1|1] * mul[rt] + add[rt] * (m >> 1)) % p;
mul[rt] = 1, add[rt] = 0;
}

void build(int l, int r, int rt)
{
add[rt] = 0, mul[rt] = 1;
if (l == r)
{
scanf("%lld", &sum[rt]);
//printf("%d %d %d\n", l, r, sum[rt]);
return ;
}
int mid = (l + r) >> 1;
build(lson);
build(rson);
PushUp(rt);
}

void update(int L, int R, int type, LL c, int l, int r, int rt)
{
if (L <= l && r <= R)
{
if (type == 1)
{
mul[rt] = (mul[rt] * c) % p;
sum[rt] = (sum[rt] * c) % p;
}
else if (type == 2)
{
sum[rt] = (sum[rt] + (LL)(r - l + 1) * c) % p;
}
return;
}
PushDown(rt, r - l + 1);
int mid = (l + r) >> 1;
if (L <= mid) update(L, R, type, c, lson);
if (R > mid) update(L, R, type, c, rson);
PushUp(rt);
}

LL query(int L, int R, int l, int r, int rt)
{
if (L <= l && r <= R)
{
return sum[rt] % p;
}
PushDown(rt, r - l + 1);
int mid = (l + r) >> 1;
LL res = 0;
if (L <= mid) res = (res + query(L, R, lson)) % p;
if (R > mid) res = (res + query(L, R, rson)) % p;
return res;
}

int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int n, m;
while (scanf("%d%lld", &n, &p) != EOF)
{
build(1, n, 1);
scanf("%d", &m);
for (int i = 1; i <= m; i++)
{
int t, l, r, c = 0;
scanf("%d", &t);
if (t == 1)
{
scanf("%d %d %d", &l, &r, &c);
update(l, r, 1, c, 1, n, 1);
}
if (t == 2)
{
scanf("%d %d %d", &l, &r, &c);
update(l, r, 2, c, 1, n, 1);
}
if (t == 3)
{
scanf("%d %d", &l, &r);
printf("%lld\n", query(l, r, 1, n, 1));
}
}
}
return 0;
}``````

<