bzoj 1798 && 5039: [Jsoi2014]序列维护(线段树)

5039: [Jsoi2014]序列维护

Time Limit: 20 Sec   Memory Limit: 256 MB
Submit: 17   Solved: 14
[ Submit][ Status][ Discuss]

Description

JYY 有一个维护数列的任务。 他希望你能够来帮助他完成。
JYY 现在有一个长度为 N 的序列 a1,a2,…,aN,有如下三种操作:
1、 把数列中的一段数全部乘以一个值;
2、 把数列中的一段数全部加上一个值;
3、 询问序列中的一段数的和。
由于答案可能很大,对于每个询问,你只需要告诉 JYY 这个询问的答案对 P
取模的结果即可。

Input

第一行包含两个正整数, N 和 P;
第二行包含 N 个非负整数,从左到右依次为 a1,a2,…,aN。
第三行有一个整数 M,表示操作总数。
接下来 M 行,每行满足如下三种形式之一:
1、“ 1 t g c”(不含引号)。表示把所有满足 t ≤ i ≤ g 的 ai 全部乘以 c;
2、“ 2 t g c”(不含引号)。表示把所有满足 t ≤ i ≤ g 的 ai 全部加上 c;
3、“ 3 t g”(不含引号)。表示询问满足 t ≤ i ≤ g 的 ai 的和对 P 取模的值。
1 ≤ N,M ≤ 10^5, 1 ≤ P, c, ai ≤ 2*10^9, 1 ≤ t ≤ g ≤ N

Output

对于每个以 3 开头的操作,依次输出一行,包含对应的结果。

Sample Input

7 43
1 2 3 4 5 6 7
5
1 2 5 5
3 2 4
2 3 7 9
3 1 3
3 4 7

Sample Output

2
35
8


每个区间维护乘法和加法两个懒惰标记

如果当前是询问,那么先乘再加

如果当前是更新,并且是加法操作,就直接更新加法的懒惰标记

如果当前是更新,并且是乘法操作,乘法和加法的懒惰标记都要更新


#include<stdio.h>
#define LL long long
LL tre[400044], tx[400044], tp[400044];
int mod;
void Create(int l, int r, int x)
{
	int m;
	if(l==r)
	{
		scanf("%lld", &tre[x]);
		return;
	}
	tx[x] = 1;
	m = (l+r)/2;
	Create(l, m, x*2);
	Create(m+1, r, x*2+1);
	tre[x] = (tre[x*2]+tre[x*2+1])%mod;
}
void Lazy(int l, int r, int x)
{
	int m;
	m = (l+r)/2;
	if(tx[x]!=1)
	{
		tre[x*2] = tre[x*2]*tx[x]%mod;
		tre[x*2+1] = tre[x*2+1]*tx[x]%mod;
		if(l!=r)
		{
			tx[x*2] = tx[x*2]*tx[x]%mod;
			tx[x*2+1] = tx[x*2+1]*tx[x]%mod;
			tp[x*2] = tp[x*2]*tx[x]%mod;
			tp[x*2+1] = tp[x*2+1]*tx[x]%mod;
		}
		tx[x] = 1;
	}
	if(tp[x])
	{
		tre[x*2] = (tre[x*2]+tp[x]*(m-l+1))%mod;
		tre[x*2+1] = (tre[x*2+1]+tp[x]*(r-m))%mod;
		if(l!=r)
		{
			tp[x*2] = (tp[x*2]+tp[x])%mod;
			tp[x*2+1] = (tp[x*2+1]+tp[x])%mod;
		}
		tp[x] = 0;
	}
}
void Update(int l, int r, int x, int a, int b, int c, int opt)
{
	int m;
	if(l>=a && r<=b)
	{
		if(opt==1)
		{
			tre[x] = tre[x]*c%mod;
			if(l==r)
				return;
			tx[x] = tx[x]*c%mod;
			tp[x] = tp[x]*c%mod;
		}
		else
		{
			tre[x] = (tre[x]+c*(r-l+1))%mod;
			if(l==r)
				return;
			tp[x] = (tp[x]+c)%mod;
		}
		return;
	}
	m = (l+r)/2;
	Lazy(l, r, x);
	if(a<=m)
		Update(l, m, x*2, a, b, c, opt);
	if(b>=m+1)
		Update(m+1, r, x*2+1, a, b, c, opt);
	tre[x] = (tre[x*2]+tre[x*2+1])%mod;
}
LL Query(int l, int r, int x, int a, int b)
{
	int m;
	LL ans = 0;
	if(l>=a && r<=b)
		return tre[x];
	m = (l+r)/2;
	Lazy(l, r, x);
	if(a<=m)
		ans += Query(l, m, x*2, a, b);
	if(b>=m+1)
		ans += Query(m+1, r, x*2+1, a, b);
	return ans%mod;
}
int main(void)
{
	int n, m, opt, a, b, x;
	scanf("%d%d", &n, &mod);
	Create(1, n, 1);
	scanf("%d", &m);
	while(m--)
	{
		scanf("%d", &opt);
		if(opt<=2)
		{
			scanf("%d%d%d", &a, &b, &x);
			Update(1, n, 1, a, b, x, opt);
		}
		else
		{
			scanf("%d%d", &a, &b);
			printf("%lld\n", Query(1, n, 1, a, b));
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值