萌新刚学线段树,求助

P3372 【模板】线段树 1

wo_hen_la @ 2023-07-16 10:41:43

跟着题解学的,全WA

#include<bits/stdc++.h>
using namespace std;
int a[100005];
struct node
{
    int l,r,w,f;
}tree[400005];
int c,x,y,z,n,m;
void build(int k,int ll,int rr)
{
    int mid;
    if(ll>rr)  return;
    if(ll==rr){
        tree[k].l=ll;
        tree[k].r=rr;
        tree[k].w=a[ll];
        return;
    }
    mid=(ll+rr)/2;
    build(k*2,ll,mid);
    build(k*2+1,mid+1,rr);
    tree[k].l=ll;
    tree[k].r=rr;
    tree[k].w=tree[k*2].w+tree[k*2+1].w;
    return;
}
void down(int k)
{
    tree[k*2].w+=tree[k].f;
    tree[k*2+1].w+=tree[k].f;
    tree[k*2].w+=tree[k].f*(tree[k*2].r-tree[k*2].l+1);
    tree[k*2+1].w+=tree[k].f*(tree[k*2+1].r-tree[k*2+1].l+1); 
    tree[k].f=0;
    return;
}
void add(int k,int t,int w)
{
    int mid,num=0;
    if(t>w) return;
    if(x<=t && w<=y){
        tree[k].w+=(w-t+1)*z;
        tree[k].f+=z;
        return;
    }
    mid=(t+w)/2;
    if(tree[k].f) down(k);
    if(x<=mid) add(k*2,t,mid);
    if(y>mid) add(k*2+1,mid+1,w);
    tree[k].w=tree[k*2].w+tree[k*2+1].w;
    return;
}
int ask(int k,int t,int w)
{   
    int mid;
    if (t>w) return 0;
    if (x<=t&&w<=y){
        return tree[k].w;
    }
    mid=(t+w)/2;
    if(tree[k].f) down(k); 
    int sum=0;
    if(x<=mid)sum+=ask(k*2,t,mid);
    if(y>mid)sum+=ask(k*2+1,mid+1,w);
    tree[k].w=tree[k*2].w+tree[k*2+1].w;
    return sum;
}
int main()
{
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        cin>>a[i];
    }
    build(1,1,n);
    while(m--){
        cin>>c>>x>>y;
        if(c==1){
            cin>>z;
            add(1,1,n);
        }
        else printf("%d\n",ask(1,1,n));
    }
    return 0;
}

by wo_hen_la @ 2023-07-16 10:42:44

样例过了


by WsW_ @ 2023-07-16 10:42:53

@wo_hen_la me come see see


by WsW_ @ 2023-07-16 10:44:17

@wo_hen_la build 里面第一个if去掉


by WsW_ @ 2023-07-16 10:45:15

@wo_hen_la
2.down写错啦!


by WsW_ @ 2023-07-16 10:46:46

@wo_hen_la
3.变量名请不要全取单个字母,我怎么知道那什么意思?add里面似乎也有错


by WsW_ @ 2023-07-16 10:48:04

@wo_hen_la
4.你估计是跟许多题解学的吧?好乱!


by wo_hen_la @ 2023-07-16 10:54:44

@WsW_ 就一篇https://www.luogu.com.cn/blog/2005-00-88-wyk/qian-tan-xian-duan-shu


by wo_hen_la @ 2023-07-16 10:55:01

@WsW_ 我再改一下


by wo_hen_la @ 2023-07-16 14:21:04

过了


|