Just a Hook(区间修改)

题目链接: Just a Hook


大致题意:

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

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


解题思路:

区间修改 + 根结点查询


AC代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e5 + 10;
int n, m;
struct node {
	int l, r;
	int sum;
	int lazy;
}t[N * 4];
void pushdown(node& x, int lazy) {
	x.sum = lazy * (x.r - x.l + 1); x.lazy = lazy;
}
void pushdown(int index) {
	if (!t[index].lazy)return;
	pushdown(t[index << 1], t[index].lazy);
	pushdown(t[index << 1 | 1], t[index].lazy);
	t[index].lazy = 0;
}
void pushup(int index) {
	t[index].sum = t[index << 1].sum + t[index << 1 | 1].sum;
}
void build(int l, int r, int index = 1) {
	t[index] = { l,r,1,0 };
	if (l == r)return;
	int mid = l + r >> 1;
	build(l, mid, index << 1); build(mid + 1, r, index << 1 | 1);
	pushup(index);
}
void modify(int l, int r, int v, int index = 1) {
	if (t[index].l >= l && t[index].r <= r) {
		pushdown(t[index], v);
		return;
	}
	pushdown(index);
	int mid = t[index << 1].l + t[index << 1 | 1].r >> 1;
	if (l <= mid)modify(l, r, v, index << 1);
	if (r > mid)modify(l, r, v, index << 1 | 1);
	pushup(index);
}
int main() {
	std::ios::sync_with_stdio(false);
	cin.tie(NULL);
	int k; cin >> k;
	for (int i = 1; i <= k; ++i) {
		cin >> n >> m;
		build(1, n);
		while (m--) {
			int l, r, v; cin >> l >> r >> v;
			modify(l, r, v);
		}
		printf("Case %d: The total value of the hook is %d.\n", i, t[1].sum);
	}
	return 0;
}

END

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值