线段树模板题求调
查看原帖
线段树模板题求调
700106
Xdik楼主2023/8/14 19:01

「AHOI2009」维护序列,板子题,但是样例的第三个询问错了,输出的是15,求调

code:

#include <bits/stdc++.h>
#pragma GCC optimeze(2)
#pragma GCC optimeze(3)
#define int long long
using namespace std;
const int N = 1e5 + 5;
int tr[N * 4],n,a[N],q,pp,b1[4*N],b2[4*N];
void pushdown(int p,int s,int t){
	int m=(s+t)>>1;
	tr[p*2]=(tr[p*2]*b1[p]+b2[p]*(m-s+1)%pp)%pp;
	tr[p*2+1]=(tr[p*2+1]*b1[p]+b2[p]*(t-m)%pp)%pp;
	b1[p*2]=(b1[p]*b1[p*2])%pp;
	b1[p*2+1]=(b1[p]*b1[p*2+1])%pp;
	b2[p*2]=(b2[p]+b1[p]*b2[p*2])%pp;
	b2[p*2+1]=(b2[p]+b1[p]*b2[p*2+1])%pp;
	b2[p]=0;b1[p]=1;
}
void build(int p, int l, int r) {
	b1[p]=1;
    if (l == r) {
        tr[p] = a[l]%pp;
        return;
    }
    int m = (l + r) >> 1;
    build(p * 2, l, m);
    build(p * 2 + 1, m + 1, r);
    tr[p] = (tr[p * 2] + tr[p * 2 + 1])%pp;
}
int query(int l, int r, int s, int t, int p) {
    if (s >= l && t <= r) {
        return tr[p];
    }
    pushdown(p,s,t);
    int sum = 0;
    int m = (s + t) >> 1;
    if (m >= l)
        sum += query(l, r, s, m, p * 2),sum%=pp;
    if (m < r)
        sum += query(l, r, m + 1, t, p * 2 + 1),sum%=pp;
    return sum;
}
void change1(int l,int r,int c,int s,int t,int p){
	if(s>=l&&t<=r){
		b1[p]*=c,b1[p]%=pp,tr[p]*=c,tr[p]%=pp;
		b2[p]*=c,b2[p]%=pp;	
		return;
	}
	int m=(s+t)>>1;
	pushdown(p,s,t);
	tr[p]=(tr[p*2]+tr[p*2+1])%pp;
	if(m>=l)change1(l,r,c,s,m,p*2);
	if(m<r)change1(l,r,c,m+1,t,p*2+1);
	tr[p]=(tr[p*2]+tr[p*2+1])%pp;
}
void change2(int l,int r,int c,int s,int t,int p){
	if(s>=l&&t<=r){
		b2[p]+=c,b2[p]%=pp,tr[p]+=(s-t+1)*c,tr[p]%=pp;
		return;
	}
	int m=(s+t)>>1;
	pushdown(p,s,t);
	tr[p]=(tr[p*2]+tr[p*2+1])%pp;
	if(m>=l)change2(l,r,c,s,m,p*2);
	if(m<r)change2(l,r,c,m+1,t,p*2+1);
	tr[p]=(tr[p*2]+tr[p*2+1])%pp;
}
//void test(int p,int s,int t){
//	cout<<"test "<<s<<" "<<t<<" "<<tr[p]<<endl;
//	if(s==t)return;
//	pushdown(p,s,t);
//	int m=(s+t)>>1;
//	test(p*2,s,m);
//	test(p*2+1,m+1,t);
//}
signed main() {
    scanf("%lld%lld", &n,&pp);
    for (int i = 1; i <= n; i++) {
        scanf("%lld", &a[i]);
    }
    build(1, 1, n);
    scanf("%lld", &q);
    while (q--) {
        int opt, l, r,c;
        scanf("%lld%lld%lld", &opt, &l, &r);
        if (opt == 3) {
            printf("%lld\n", query(l, r, 1, n, 1));
            	//test(1,1,n);
        } else if(opt==1){
        	scanf("%lld",&c);
            change1(l, r,c, 1, n, 1);
           // 	test(1,1,n);
        }
        else {
        	scanf("%lld",&c);
            change2(l, r,c, 1, n, 1);
            	//test(1,1,n);
        }
    }
    return 0;
}
2023/8/14 19:01
加载中...