样例输出11 10 22求调

P3372 【模板】线段树 1

Lucien @ 2022-10-27 16:49:39

看了看题解自己瞎写的...调炸了求助SOS

#include <bits/stdc++.h>
using namespace std;
const int maxn = 100005;
int n, m;
struct node
{
    int l, r;
    int w, tag;
} tree[4 * maxn];
int nums[maxn];
void update(int p)
{
    tree[p].w = tree[p * 2].w + tree[p * 2 + 1].w;
}
void build(int l, int r, int p)
{
    tree[p].l = l;
    tree[p].r = r;
    tree[p].tag = 0;
    if (l == r)
    {
        tree[p].w = nums[l];
        return;
    }
    int m = l + r >> 1;
    build(l, m, p * 2);
    build(m + 1, r, p * 2 + 1);
    update(p);
}
void spread(int p)
{
    if (tree[p].tag)
    {
        tree[p * 2].w += tree[p].tag * (tree[p * 2].r - tree[p * 2].l + 1);
        tree[p * 2 + 1].w += tree[p].tag * (tree[p * 2 + 1].r - tree[p * 2 + 1].l + 1);
        tree[p * 2].tag += tree[p].tag;
        tree[p * 2 + 1].tag += tree[p].tag;
        tree[p].tag = 0;
    }
}

long long getAns(int l, int r, int p)
{
    if (l <= tree[p].l && tree[p].r <= r)
    {
        return tree[p].w + tree[p].tag;
    }
    else
    {
        spread(p);
        int mid = (tree[p].l + tree[p].r) / 2;
        int ans = 0;
        if (mid >= l)
        {
            ans += getAns(l, r, p * 2);
        }
        if (mid < r)
        {
            ans += getAns(l, r, p * 2 + 1);
        }
        return ans;
    }
}
void add(int l, int r, int val, int p)
{
    if (l <= tree[p].l && tree[p].r <= r)
    {
        tree[p].w += (long long)val * (tree[p].r - tree[p].l+1);
        tree[p].tag += val;
        return;
    }
    spread(p);
    int mid = (tree[p].l + tree[p].r) / 2;
    if (mid >= l)
    {
        add(l, r, val, p * 2);
    }
    if (mid + 1 <= r)
    {
        add(l, r, val, p * 2 + 1);
    }
    update(p);
}
int main()
{
    cin >> n >> m;
    for (int a = 1; a <= n; a++)
    {
        scanf("%d", &nums[a]);
    }
    build(1, n, 1);
    while (m--)
    {
        int opt;
        scanf("%d", &opt);
        if (opt == 1)
        {
            int x, y, k;
            scanf("%d %d %d", &x, &y, &k);
            add(x, y, k, 1);
        }
        else
        {
            int x, y;
            scanf("%d %d", &x, &y);
            cout << getAns(x, y, 1) << "\n";
        }
    }
    return 0;
}

by yizhiming @ 2022-10-27 16:59:33

getans里改一下,只需要

    if (l <= tree[p].l && tree[p].r <= r)
    {
        return tree[p].w;
    }

即可


by yizhiming @ 2022-10-27 16:59:45

@Lucien


by yizhiming @ 2022-10-27 17:00:20

emm等会还有点锅,我研究一下


by yizhiming @ 2022-10-27 17:01:55

还有就是少开了点long long,开完再改下上面那个就好了


by Lucien @ 2022-10-27 17:14:51

@yizhiming 感谢!!


|