线段树全RE,0分求助!

P3372 【模板】线段树 1

yyrwlj @ 2023-06-30 12:46:56

#include <iostream>
using namespace std;
const int N=100005,M=400005;
long long a[N],k;
struct Tree{
    long long val,tag;
    int left,right;
}tree[M];
int l,r;
void init(int u,int left,int right)
{
    if (left==right)
    {
        tree[u].val = a[left];
        tree[u].left = tree[u].right = left;
        return;
    }
    int mid=(left+right)>>1;
    init(u*2,left,mid);
    init(u*2+1,mid+1,right);
    tree[u].val = tree[u*2].val + tree[u*2+1].val;
    tree[u].left = tree[u*2].left;
    tree[u].right = tree[u*2+1].right;
}
long long find(int u)
{
    if (l <= tree[u].left && r >= tree[u].right)
        return tree[u].val;
    if (l <= tree[u].left || r >= tree[u].right)
        return find(u*2) + find(u*2+1);
    return 0;
}
void maketag(int u,int len,long long x)
{
    tree[u].val += len*x;
    tree[u].tag += x;
}
void pushdown(int u)
{
    int mid = (tree[u].left + tree[u].right) / 2;
    maketag(u*2, mid - tree[u].left + 1, tree[u].tag);
    maketag(u*2+1, tree[u].right - mid, tree[u].tag);
    tree[u].tag = 0;
}
void update(int u)
{
    if (l <= tree[u].left && r >= tree[u].right)
        maketag(u,tree[u].right - tree[u].left + 1,k);
    else if (l <= tree[u].left || r >= tree[u].right)
    {
        if (tree[u].tag)
            pushdown(u);
        update(u*2);
        update(u*2+1);
        tree[u].val = tree[u*2].val + tree[u*2+1].val;
    }
}
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    int n,m;
    cin >> n >> m;
    for (int i=1;i<=n;i++)
        cin >> a[i];
    init(1,1,n);

    while (m--)
    {
        int op;
        cin >> op >> l >> r;
        if (op==1)
        {
            cin >> k;
            update(1);
        }
        else
            cout << find(1) << '\n';
    }
    return 0;
}

by yyrwlj @ 2023-06-30 12:49:39

应该不是输入输出的问题,scanf和cin都是全RE


by hjqhs @ 2023-06-30 12:57:05

tree[u].left = tree[u*2].left;
tree[u].right = tree[u*2+1].right;

这段啥意思啊


by zymooll @ 2023-06-30 13:07:07

@hjqhs 这段实际上是没有必要的,这俩跟形参相等的.


by fqfengqi @ 2023-06-30 13:08:48

结构体信息没给


by yyrwlj @ 2023-06-30 13:10:05

@hjqhs 存进结构体里,递归调用函数的时候就可以少传两项参数


by yyrwlj @ 2023-06-30 13:12:56

struct Tree{
    long long val,tag;
    //val:节点的值
    //tag:延迟标记,标记的值
    int left,right;
    //分别是节点的左右端点的位置
};

by hjqhs @ 2023-06-30 13:32:23

@yyrwlj 我知道这什么意思 我是问不该是

tree[u].left=left;
tree[u].right=right;

这样吗
自己结点的左区间为什么要等于左儿子左区间


by fqfengqi @ 2023-06-30 13:37:48

我的评价是有一堆bug慢慢调


by zymooll @ 2023-06-30 13:46:23

@yyrwlj 我的评价时可以但非常没必要,纯浪费空间,这玩意在建树方式确定时可以确定的...


by yyrwlj @ 2023-06-30 21:14:53

此帖终结,已AC,死因是查询时没有pushdown (没有结构体做)


|