~~~题目链接~~~
题目大意:现给出一个区间, 刚开始时区间中的每个点对应的值为1, 现在更新q次, 把x-y区间的点的值全跟新为z, 现在求出整个区间点的值的和。
思路:线段树, 跟新每个区间时只更新到覆盖的区间, 下回更新时再通过cv【】数组往下更新。
code:
#include <stdio.h> #include <string.h> #define N 100002 using namespace std; int n = 0, x = 0, y = 0, z = 0, cv[4*N], t[4*N]; void build(int c, int l, int r) { int m = l+(r-l)/2; if(l == r) { t[c] = 1; return ; } build(2*c, l, m); build(2*c+1, m+1, r); t[c] = t[2*c]+t[2*c+1]; } void cover(int c, int l, int r) { int m = l+(r-l)/2; cv[2*c] = cv[2*c+1] = cv[c]; t[2*c] = (m-l+1)*cv[c]; t[2*c+1] = (r-m)*cv[c]; cv[c] = 0; } void update(int c, int l, int r, int lf, int rt, int w) { int m = l+(r-l)/2; if(cv[c] && l != r) cover(c, l, r); if(l == lf && r == rt) { cv[c] = w; t[c] = (r-l+1)*w; return ; } if(lf>m) update(2*c+1, m+1, r, lf, rt, w); else if(rt<=m) update(2*c, l, m, lf, rt, w); else { update(2*c, l, m, lf, m, w); update(2*c+1, m+1, r, m+1, rt, w); } t[c] = t[2*c]+t[2*c+1]; } int main() { // freopen("input.txt", "r", stdin); int i = 0, j = 0, tt = 0, q = 0, cnt = 0; scanf("%d", &tt); while(tt--) { scanf("%d %d", &n, &q); memset(t, 0, sizeof(t)); memset(cv, 0, sizeof(cv)); build(1, 1, n); while(q--) { scanf("%d %d %d", &x, &y, &z); update(1, 1, n, x, y, z); } printf("Case %d: The total value of the hook is %d.\n", ++cnt, t[1]); } return 0; }