线段树样例没过

P3372 【模板】线段树 1

jinzihan0127 @ 2023-12-17 08:23:46

乱学自学了一个线段树,样例都没过,求调:

#include <bits/stdc++.h>
using namespace std;
#define int long long
#define ULL unsigned long long
#define INT __int128
#define tbl ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int n,m,a[100010],tree[400010],mark[400010];
void new_tree(int left,int right,int x){
    if(left==right){
        tree[x]=a[left];
        return ;
    }
    int mid=(left+right)>>1;
    new_tree(left,mid,x*2);
    new_tree(mid+1,right,x*2+1);
    tree[x]=tree[x*2]+tree[x*2+1];
}
void insert_interval(int left_now,int right_now,int left_target,int right_target,int x,int s){
    if(left_now>right_target||right_now<left_target)return ;
    if(left_now>=left_target&&right_now<=right_target){
        tree[x]=(right_now-left_now+1)*s;
        if(left_now<right_now)mark[x]+=s;
    }
    else{
        int mid=(left_now+right_now)>>1;
        mark[x*2]+=mark[x];
        mark[x*2+1]+=mark[x];
        tree[x*2]+=mark[x]*(mid-left_now+1);
        tree[x*2+1]+=mark[x]*(right_now-mid);
        mark[x]=0;
        insert_interval(left_now,mid,left_target,right_target,x*2,s);
        insert_interval(mid+1,right_now,left_target,right_target,x*2+1,s);
        tree[x]=tree[x*2]+tree[x*2+1];
    }
    return ;
}
int query_interval(int left_now,int right_now,int left_target,int right_target,int x){
    if(left_now>right_target||right_now<left_target)return 0;
    if(left_now>=left_target&&right_now<=right_target)return tree[x];
    else{
//  cout<<tree[x]<<endl;
        int mid=(left_now+right_now)>>1;
        mark[x*2]+=mark[x];
        mark[x*2+1]+=mark[x];
        tree[x*2]+=mark[x]*(mid-left_now+1);
        tree[x*2+1]+=mark[x]*(right_now-mid);
        mark[x]=0;
        return query_interval(left_now,mid,left_target,right_target,x*2)+query_interval(mid+1,right_now,left_target,right_target,x*2+1);
    }
}
signed main()
{
//  tbl;
  cin>>n>>m;
  for(int i=1;i<=n;i++)cin>>a[i];
  new_tree(1,n,1);
  for(int i=1;i<=m;i++){
    int q;
    cin>>q;
    if(q==1){
        int x,y,k;
        cin>>x>>y>>k;
        insert_interval(1,n,x,y,1,k);
        }
        else{
            int x,y;
            cin>>x>>y;
            cout<<query_interval(1,n,x,y,1)<<endl;
        }
    }
  return 0;
}

by forgotmyhandle @ 2023-12-17 08:46:21

insert_interval 第二个 if 里有一个 += 写成 = 了


by jinzihan0127 @ 2023-12-27 16:31:28

@forgotmyhandle 谢谢你!!!!我爱你


|