分块求调
查看原帖
分块求调
572891
Run24楼主2024/11/22 20:38
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
inline ll read(){
    ll x=0,f=1;
    char z=getchar();
    while(z<'0'||z>'9'){
        if(z=='-') f=-1;
        z=getchar();
    }
    while(z>='0'&&z<='9') x=x*10+(z^48),z=getchar();
    return x*f;
}
const int maxn = 505001;
int n, q;
ll mod, a[maxn];
int len, id[maxn];
ll lz[maxn], s[maxn], changer[maxn];
void init() {
	len = sqrt(n);
	for(int i=1; i<=n; i++) {
		id[i] = (i-1)/len+1;
		s[id[i]] += a[i];
	}
}
void add(int l, int r, ll x) {
	int st=id[l], ed=id[r];
	if(st == ed) {
		for(int i=l; i<=r; i++)
			a[i]+=x, s[st]+=x;
		return ;
	}
	for(int i=l; id[i]==st; i++)
		a[i]+=x, a[i]%=mod, s[st]+=x, s[st]%=mod;
	for(int i=st+1; i<ed; i++)
		lz[i]+=x, lz[i]%=mod, s[i]+=len*x, s[i]%=mod, changer[i]=lz[i];
	for(int i=r; id[i]==ed; i--)
		a[i]+=x, a[i]%=mod, s[ed]+=x, s[ed]%=mod;
}
void tms(int l, int r, ll x) {
	int st=id[l], ed=id[r];
	if(st == ed) {
		for(int i=l; i<=r; i++)
			a[i] *= l, s[st] *= x;
		return ;
	}
	for(int i=l; id[i]==st; i++)
		a[i]*=x, a[i]%=mod, s[st]+=a[i]*x, s[st]%=mod;
	for(int i=st+1; i<ed; i++) {
		s[i]*=x, s[i]%=mod;
		if(changer[i])
			lz[i]+=changer[i]*x, changer[i]=0, lz[i]%=mod;
	}
	for(int i=r; id[i]==ed; i--)
		a[i]*=x, a[i]%=mod, s[ed]+=a[i]*x, s[ed]%=mod;
}
inline ll query(int l, int r) {
	ll ans=0;
	int st=id[l], ed=id[r];
	if(st == ed) {
		for(int i=l; i<=r; i++)
			ans += a[i]+lz[st];
		return ans;
	}
	for(int i=l; id[i]==st; i++)
		ans+=a[i]+lz[st], ans%=mod;
	for(int i=st+1; i<ed; i++)
		ans+=s[i], ans%=mod;
	for(int i=r; id[i]==ed; i--)
		ans+=a[i]+lz[ed], ans%=mod;
	return ans;
}
int op, x, y, k;
signed main(){
	n=read(), q=read(), mod=read();
	for(int i=1; i<=n; i++)
		a[i] = read();
	init();
	while(q--) {
		op=read();
		if(op==1) {
			x=read(), y=read(), k=read();
			tms(x, y, k);
		}
		if(op==2) {
			x=read(), y=read(), k=read();
			add(x, y, k);
		}
		if(op==3) {
			x=read(), y=read();
			ll ans=query(x, y);
			ans%=mod;
			printf("%lld\n", ans);
		}
	}
    return 0;
}
2024/11/22 20:38
加载中...