http://acm.hdu.edu.cn/showproblem.php?pid=1698
要求:
1. 区间修改
2. 最后整个区间求和
分析:
因为没有多次查询,而只有最后的一次整个区间的求和查询,所以可以省去query查询函数。
#include <cstdio> #include <iostream> #define lson rt << 1, l, m #define rson rt << 1 | 1, m+1, r using namespace std; const int MAXN = 131072 + 5; int sum[MAXN * 2]; int set[MAXN * 2]; int n; void pushup(int rt) { sum[rt] = sum[rt << 1] + sum[rt << 1 | 1]; } void pushdown(int rt, int m) { if(set[rt]) { set[rt<<1] = set[rt<<1|1] = set[rt]; sum[rt<<1] = (m - (m >> 1)) * set[rt]; sum[rt<<1|1] = (m >> 1) * set[rt]; set[rt] = 0; } } void update(int ql, int qr, int x, int rt, int l, int r) { if(ql <= l && r <= qr) { set[rt] = x; sum[rt] = x * (r - l + 1); } else { pushdown(rt, r-l+1); int m = (l + r) >> 1; if(ql <= m) update(ql, qr, x, lson); if(qr > m) update(ql, qr, x, rson); pushup(rt); } } void build(int rt, int l, int r) // O(n) { set[rt] = 0; // Initialization if(l == r) { sum[rt] = 1; // the original hook is made up of cupreous sticks. } else { int m = (l + r) >> 1; build(lson); build(rson); pushup(rt); } } int main () { int T, q, x, y, z; scanf("%d", &T); for(int kase=1; kase<=T; kase++) { scanf("%d%d", &n, &q); build(1, 1, n); while(q--) { scanf("%d%d%d", &x, &y, &z); update(x, y, z, 1, 1, n); } printf("Case %d: The total value of the hook is %d.\n", kase, sum[1]); } return 0; }