Just a Hook 【线段树】

题目链接HDU-1698

[kuangbin带你飞]专题七 线段树

题目描述

Now Pudge wants to do some operations on the hook.

Let us number the consecutive metallic sticks of the hook from 1 to N. For each operation, Pudge can change the consecutive metallic sticks, numbered from X to Y, into cupreous sticks, silver sticks or golden sticks.
The total value of the hook is calculated as the sum of values of N metallic sticks. More precisely, the value for each kind of stick is calculated as follows:

For each cupreous stick, the value is 1.
For each silver stick, the value is 2.
For each golden stick, the value is 3.

Pudge wants to know the total value of the hook after performing the operations.
You may consider the original hook is made up of cupreous sticks.

思路

区间修改,询问区间和。 典型的线段树板子题;
易错
1.需要用到lazy标记;

代码

#include <bits/stdc++.h>
using namespace std;

#define long long long
#define MAX 100010

struct Node{
    long l, r, sum, lazy;
    void updata(long val)
    {
        sum = (r - l + 1) * val;
        lazy = val;
    }
}tree[MAX * 4];

void push_up(int k)
{
    tree[k].sum = tree[k<<1].sum + tree[k<<1|1].sum;
}

void push_down(int k)
{
    long lazyval = tree[k].lazy;
    if(lazyval)
    {
        tree[k<<1].updata(lazyval);
        tree[k<<1|1].updata(lazyval);
        tree[k].lazy = 0;
    }
}

void build(int k, int l, int r)
{
    tree[k].l = l, tree[k].r = r;
    tree[k].sum = tree[k].lazy = 0;
    if(l == r)
    {
        tree[k].sum = 1;
    }
    else
    {
        int mid = (l + r) >> 1;
        build(k<<1, l, mid);
        build(k<<1|1, mid+1, r);
        push_up(k);
    }
}

void updata(int k, int l, int r, int val)
{
    int L = tree[k].l, R = tree[k].r;
    if(l <= L && R <= r)
    {
        tree[k].updata(val);
    }
    else
    {
        push_down(k);
        int mid = (L + R) >> 1;
        if(l <= mid)
            updata(k<<1, l, r, val);
        if(mid < r)
            updata(k<<1|1, l, r, val);
        push_up(k);
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int t;
    cin >> t;
    for(int i = 1; i<=t; i++)
    {
        int n, m;
        cin >> n >> m;
        build(1, 1, n);
        for(int j = 1; j<=m; j++)
        {
            int x, y, val;
            cin >> x >> y >> val;
            updata(1, x, y, val);
        }
        cout << "Case " << i << ": The total value of the hook is " << tree[1].sum << "." << endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值