Just a Hook(线段树)

题目链接: Just a Hook

大致题意

给定一个n, 对于区间[1, n]有如下操作: 选定l, r, 把[l, r]区间全部修改为数值c

最后输出[1, n]的区间和

解题思路

考察线段树的区间修改 + 根结点查询.

最后输出语句记得要复制样例的输出!!! 复制全!!! 我少复制了个’.’, debug了半天 TwT

AC代码

#include <bits/stdc++.h>
#define rep(i, n) for (int i = 1; i <= (n); ++i)
using namespace std;
typedef long long ll;
const int N = 1E5 + 10;
struct node {
    int l, r;
    int val; //区间和
    int lazy;
}t[N << 2];
void pushdown(node& op, int lazy) { 
	op.val = lazy * (op.r - op.l + 1);
	op.lazy = lazy; 
}
void pushdown(int x) {
    if (!t[x].lazy) return;
    pushdown(t[x << 1], t[x].lazy);
    pushdown(t[x << 1 | 1], t[x].lazy);
    t[x].lazy = 0;
}

void pushup(int x) { t[x].val = t[x << 1].val + t[x << 1 | 1].val; }

void build(int l, int r, int x = 1) {
    t[x] = { l, r, 1, 0 };
    if (l == r) return;
    int mid = l + r >> 1;
    build(l, mid, x << 1), build(mid + 1, r, x << 1 | 1);
    pushup(x);
}

void modify(int l, int r, int c, int x = 1) {
    if (l <= t[x].l && r >= t[x].r) { pushdown(t[x], c); return; }
    pushdown(x);
    int mid = t[x].l + t[x].r >> 1;
    if (l <= mid) modify(l, r, c, x << 1);
    if (r > mid) modify(l, r, c, x << 1 | 1);
    pushup(x);
}

int main()
{
    int tt; cin >> tt;
    rep(T, tt) {
        int n, m; cin >> n >> m;
        build(1, n);
        while (m--) {
            int l, r, c; scanf("%d %d %d", &l, &r, &c);
            modify(l, r, c);
        }
        
        printf("Case %d: The total value of the hook is %d.\n", T, t[1].val);
    }
    return 0;
}

梦回初中23333

kuangbin线段树专题点这里!!!

END

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

逍遥Fau

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值