线段树功能:update:成段替换
成段更新去要用到延迟标记,具体调试代码就容易懂些
#include <iostream> #include <string> #include <cstdio> #define lson l, m, rt<<1 #define rson m+1, r, rt<<1|1 using namespace std; const int MAXN = 111111; int sum[MAXN<<2], chg[MAXN<<2];//sum表示区间和,chg数组:非0就需要将它的儿子更新,更新是在下一次查询更新 void push_up(int rt) { sum[rt] = sum[rt<<1] + sum[rt<<1|1]; } void push_down(int rt, int len) { if(chg[rt] == 0) return; chg[rt<<1] = chg[rt<<1|1] = chg[rt]; sum[rt<<1] = (len - (len >> 1)) * chg[rt]; sum[rt<<1|1] = (len >> 1) * chg[rt]; chg[rt] = 0; } void build(int l, int r, int rt) { sum[rt] = 1; //也可以写在return语句前,不影响结果 chg[rt] = 0; if(l == r) return; int m = (l + r) >> 1; build(lson); build(rson); push_up(rt); } void update(int L, int R, int c, int l, int r, int rt) { if(L <= l && r <= R) { sum[rt] = c * (r - l + 1); chg[rt] = c; return; } push_down(rt, r-l+1); int m = (l + r) >> 1; if(L <= m) update(L, R, c, lson); if(R > m) update(L, R, c, rson); push_up(rt); } int main() { int T, Case = 0; scanf("%d", &T); while(T--) { int N, Q; scanf("%d%d", &N, &Q); build(1, N, 1); while(Q--) { int X, Y, Z; scanf("%d%d%d", &X, &Y, &Z); update(X, Y, Z, 1, N, 1); } printf("Case %d: The total value of the hook is %d. ", ++Case, sum[1]); } return 0; }