题目链接: 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