萌新刚学线段树,求助大佬
【题目链接】https://www.(题目来自于洛谷)
【我的代码】
程序代码:
#include<bits/stdc++.h> #define int unsigned long long using namespace std; inline void build_tree(int arr[],int tree[],int node,int start,int end){ if(start==end) tree[node]=arr[end]; else{ int ln=2*node+1,rn=2*node+2,mid=(start+end)/2; build_tree(arr,tree,ln,start,mid); build_tree(arr,tree,rn,mid+1,end); tree[node]=tree[ln]+tree[rn]; } } inline void update_tree1(int arr[],int tree[],int node,int start,int end,int idx,int val,int p){ if(start==end) arr[idx]*=val,tree[node]*=val; else{ int ln=2*node+1,rn=2*node+2,mid=(start+end)/2; if(idx>=start&&idx<=mid) update_tree1(arr,tree,ln,start,mid,idx,val,p); else update_tree1(arr,tree,rn,mid+1,end,idx,val,p); tree[node]=tree[ln]+tree[rn]; } } inline void update_tree2(int arr[],int tree[],int node,int start,int end,int idx,int val,int p){ if(start==end) arr[idx]+=val,tree[node]+=val; else{ int ln=2*node+1,rn=2*node+2,mid=(start+end)/2; if(idx>=start&&idx<=mid) update_tree2(arr,tree,ln,start,mid,idx,val,p); else update_tree2(arr,tree,rn,mid+1,end,idx,val,p); tree[node]=tree[ln]+tree[rn]; } } inline int query_tree(int arr[],int tree[],int node,int start,int end,int L,int R,int p){ if(R<start||L>end) return 0; else if(L<=start&&R>=end) return tree[node]; else if(start==end) return tree[node]; int mid=(start+end)/2,ln=2*node+1,rn=2*node+2; int sl=query_tree(arr,tree,ln,start,mid,L,R,p); int sr=query_tree(arr,tree,rn,mid+1,end,L,R,p); return (sl%p+sr%p)%p; } int n,m,p,arr[100010],tree[1000010]={0}; signed main(){ freopen("P3373_2.in","r",stdin); freopen("qwq.out","w",stdout); cin>>n>>m>>p; for(int i=0;i<n;i++) cin>>arr[i]; build_tree(arr,tree,0,0,n-1); while(m--){ //for(int i=0;i<=14;i++) cout<<tree[i]<<" "; //puts(""); int type,x,y,k; scanf("%lld %lld %lld",&type,&x,&y); x--;y--; if(type==1){ cin>>k; for(int i=x;i<=y;i++) update_tree1(arr,tree,0,0,n-1,i,k,p); } if(type==2){ cin>>k; for(int i=x;i<=y;i++) update_tree2(arr,tree,0,0,n-1,i,k,p); } if(type==3){ cout<<query_tree(arr,tree,0,0,n-1,x,y,p)%p<<endl; } //puts(""); } return 0; }
【得分】 30
谢谢大佬!