首頁 文章 线段树模板

线段树模板

2022-07-11 09:01  瀏覽數:486  來源:Coat    

#include<bits/stdc++.h>
using namespace std;
const long long N = 1e6 + 7;
typedef long long ll;
ll a[N];
ll n, p;
struct node
{
ll l;
ll r;
ll v;
ll lazyadd;
ll lazymul;
}tree[N * 4];
void pushup(ll x)
{
tree[x].v = tree[x * 2].v % p + tree[x * 2 + 1].v % p;
}
void eval(node& t, int add, int mul)
{
t.v = ((ll)t.v * mul + (ll)(t.r - t.l + 1) * add) % p;
t.lazymul = (ll)t.lazymul * mul % p;
t.lazyadd = ((ll)t.lazyadd * mul + add) % p;
}
void pushdown(ll x)
{
eval(tree[x << 1], tree[x].lazyadd, tree[x].lazymul);
eval(tree[x << 1 | 1], tree[x].lazyadd, tree[x].lazymul);
tree[x].lazyadd = 0;
tree[x].lazymul = 1;
}
void built(ll l, ll r, ll x)
{
if (l == r)
{
tree[x] = { l ,r ,a[l],0,1 };
return;
}
tree[x] = { l ,r,0,0,1 };
ll mid = (l + r) / 2;
built(l, mid, x * 2);
built(mid + 1, r, x * 2 + 1);
pushup(x);
}
void modifyadd(ll l, ll r, ll value, ll x)
{
if (tree[x].l >= l && tree[x].r <= r)
{
eval(tree[x], value, 1);
return;
}
pushdown(x);
ll mid = (tree[x].l + tree[x].r) / 2;
if (l <= mid)modifyadd(l, r, value, x * 2);
if (r > mid)modifyadd(l, r, value, x * 2 + 1);
pushup(x);
}
void modifymul(ll l, ll r, ll value, ll x)
{
if (tree[x].l >= l && tree[x].r <= r)
{
eval(tree[x], 0, value);
return;
}
pushdown(x);
ll mid = (tree[x].l + tree[x].r) / 2;
if (l <= mid)modifymul(l, r, value, x * 2);
if (r > mid)modifymul(l, r, value, x * 2 + 1);
pushup(x);
}
ll query(ll l, ll r, ll x)
{
if (tree[x].l >= l && tree[x].r <= r)
{
return tree[x].v % p;
}
pushdown(x);
ll mid = (tree[x].l + tree[x].r) / 2;
ll v = 0;
if (l <= mid)v += query(l, r, x * 2);
if (r > mid)v += query(l, r, x * 2 + 1);
return v % p;
}
int main()
{
ll m;
cin >> n >> m >> p;
for (ll i = 1; i <= n; i++)
{
cin >> a[i];
}
built(1, n, 1);
for (ll i = 1; i <= m; i++)
{
ll x;
cin >> x;
if (x == 1)
{
ll y, z, s;
cin >> y >> z >> s;
modifymul(y, z, s, 1);
}
else if (x == 2)
{
ll y, z, s;
cin >> y >> z >> s;
modifyadd(y, z, s, 1);
}
else
{
ll y, z;
cin >> y >> z;
cout << query(y, z, 1) % p << endl;
}
}
return 0;
}



聲明:以上文章均為用戶自行添加,僅供打字交流使用,不代表本站觀點,本站不承擔任何法律責任,特此聲明!如果有侵犯到您的權利,請及時聯系我們刪除。

字符:    改为:
去打字就可以设置个性皮肤啦!(O ^ ~ ^ O)