标题:萌新刚学线段树,求助大佬
取消只看楼主
OIer_Zheng
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2020-2-3
结帖率:0
已结贴  问题点数:20 回复次数:0 
萌新刚学线段树,求助大佬
【题目链接】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
谢谢大佬!
搜索更多相关主题的帖子: tree end int start node 
2020-02-03 21:53



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-499090-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.633457 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved