题意:
屠夫的钩子区间是1~n,每段可能由铜,银,金组成,价值分别为1,2,3,进行一系列的更新之后,求钩子的总价值。
思路:
线段树的成段更新:要设置一个临时的线段树,每次更新的时候把更新段的值放在临时数组中,等到下次更新线段树的时候再向下更新(延迟更新)
#include <cstdio>
#define lhs l, m, rt << 1
#define rhs m + 1, r, rt << 1 | 1
const int maxn = 100010;
int seg[maxn << 2];
int col[maxn << 2];
void PushUp(int rt)
{
seg[rt] = seg[rt << 1] + seg[rt << 1 | 1];
}
void PushDown(int rt, int len)
{
if (col[rt] > 0)
{
col[rt << 1] = col[rt << 1 | 1] = col[rt];
seg[rt << 1] = (len - (len >> 1)) * col[rt];
seg[rt << 1 | 1] = (len >> 1) * col[rt];
col[rt] = 0;
}
}
void Build(int l, int r, int rt)
{
col[rt] = 0;
if (l == r)
seg[rt] = 1;
else
{
int m = (l + r) >> 1;
Build(lhs);
Build(rhs);
PushUp(rt);
}
}
void Update(int beg, int end, int value, int l, int r, int rt)
{
if (beg <= l && r <= end)
{
col[rt] = value;
seg[rt] = (r - l + 1) * value;
}
else
{
PushDown(rt, r - l + 1);
int m = (l + r) >> 1;
if (beg <= m)
Update(beg, end, value, lhs);
if (end > m)
Update(beg, end, value, rhs);
PushUp(rt);
}
}
int main()
{
int cases, cnt = 0;
scanf("%d", &cases);
while (cases--)
{
int n, q;
scanf("%d %d", &n, &q);
Build(1, n, 1);
for (int i = 0; i < q; ++i)
{
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
Update(a, b, c, 1, n, 1);
}
printf("Case %d: The total value of the hook is %d.\n", ++cnt, seg[1]);
}
return 0;
}