• 洛谷P3372 【模板】线段树 1(树状数组)


    题意

    题目链接

    Sol

    Get到了这题树状数组的做法,感觉非常nice

    区间加:直接差分

    区间求和:考虑每一位的贡献

    (sum_{i = 1}^x (x+1 - i) d_i)

    (= sum_{i = 1}^x (x+1)d_i - sum_{i = 1}^x id_i)

    (= (x+1) sum_{i = 1}^x d_i - sum_{i = 1}^x id_i)

    #include<bits/stdc++.h>
    #define lb(x) (x & (-x))
    #define LL long long 
    #define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1<<22, stdin), p1 == p2) ? EOF : *p1++)
    char buf[(1 << 22)], *p1 = buf, *p2 = buf;
    char obuf[1<<24], *O = obuf;
    void print(LL x) {if(x > 9) print(x / 10); *O++ = x % 10 + '0';}
    #define OS  *O++ = '
    ';
    #define fout fwrite(obuf, O-obuf, 1 , stdout);
    using namespace std;
    const int MAXN = 1e5 + 10;
    inline LL read() {
    	char c = getchar(); LL x = 0, f = 1;
    	while(c < '0' || c > '9') {if(c == '-')f =- 1; c = getchar();}
    	while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    	return x * f;
    }
    int N, M;
    LL a[MAXN], T1[MAXN], T2[MAXN];
    void insert(LL *T, int pos, LL val) {
    	while(pos <= N) T[pos] += val, pos += lb(pos);
    }
    LL sum(LL *T, int pos) {
    	LL ans = 0;
    	while(pos) ans += T[pos], pos -= lb(pos);
    	return ans;
    }
    LL Query(int pos) {
    	return 1ll * (pos + 1) * sum(T1, pos) - sum(T2, pos);
    }
    main() {
    	N = read(); M = read();
    	for(int i = 1; i <= N; i++) a[i] = read(), insert(T1, i, a[i] - a[i - 1]), insert(T2, i, 1ll * i * (a[i] - a[i - 1]));
    	while(M--) {
    		int opt = read(), l = read(), r = read();
    		if(opt == 1) {
    			LL val = read();
    			insert(T1, l, val); insert(T1, r + 1, -val);
    			insert(T2, l, 1ll * l * val); insert(T2, r + 1, 1ll * -(r + 1) * val);
    		} else print(Query(r) - Query(l - 1)), OS;
    	}
    	fout;
    }
    /*
    */
    
    
  • 相关阅读:
    【PyTorch深度学习60分钟快速入门 】Part1:PyTorch是什么?
    如何编写一个gulp插件
    进阶之初探nodeJS
    模拟Vue之数据驱动5
    模拟Vue之数据驱动4
    模拟Vue之数据驱动3
    模拟Vue之数据驱动2
    树结构之JavaScript
    模拟Vue之数据驱动1
    CORS详解[译]
  • 原文地址:https://www.cnblogs.com/zwfymqz/p/9735306.html
Copyright © 2020-2023  润新知