zoukankan      html  css  js  c++  java
  • 线段树 :区间修改,区间查询

    题目描述

    思路

    代码

    #include <cstdio>
    #include <cstring>
    long long n, m;
    struct {
    	long long at[1000005], arr[1000005 << 2], ad[1000005 << 2];
    	void build(int k, int l, int r) {
    		if (l == r) {
    			arr[k] = at[l];
    			return;
    		}
    		int mid = l + r >> 1;
    		this->build(k << 1, l, mid);
    		this->build(k << 1 | 1, mid + 1, r);
    		arr[k] = arr[k << 1] + arr[k << 1 | 1];
    	}
    	void change(int k, int l, int r, int x, int y, int v) {
    		if (x <= l && r <= y) {
    			this->add(k, l, r, v);
    			return;
    		}
    		int mid = l + r >> 1;
    		this->pushdown(k, l, r, mid);
    		if (x <= mid) this->change(k << 1, l, mid, x, y, v);
    		if (y > mid) this->change(k << 1 | 1, mid + 1, r, x, y, v);
    		arr[k] = arr[k << 1] + arr[k << 1 | 1]; 
    	}
    	long long query(int k, int l, int r, int x, int y) {
    		if (x <= l && r <= y) return arr[k];
    		long long res = 0;
    		int mid = l + r >> 1;
    		this->pushdown(k, l, r, mid);
    		if (x <= mid) res += this->query(k << 1, l, mid, x, y);
    		if (y > mid) res += this->query(k << 1 | 1, mid + 1, r, x, y);
    		return res;
    	}
    	void add(int k, int l, int r, int v) {
    		ad[k] += v;
    		arr[k] += (long long)(r - l + 1) * v;
    	}
    	void pushdown(int k, int l, int r, int mid) {
    		if (ad[k] == 0) return;
    		add(k << 1, l, mid, ad[k]);
    		add(k << 1 | 1, mid + 1, r, ad[k]);
    		ad[k] = 0;
    	}
    } t;
    
    inline long long read() {
    	long long s = 0, f = 1;
    	char ch = getchar();
    	while (ch < '0' || ch > '9') {
    		if (ch == '-') f = -1;
    		ch = getchar();
    	}
    	while (ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
    	return s * f;
    }
    int main() {
    	n = read(), m = read();
    	for (register int i = 1; i <= n; ++i) t.at[i] = read();
    	t.build(1, 1, n);
    	for (register int i = 1, a, b, c, d; i <= m; ++i) {
    		a = read();
    		if (a == 1) {
    			b = read(), c = read(), d = read();
    			t.change(1, 1, n, b, c, d);
    		} else {
    			b = read(), c = read();
    			printf("%lld
    ", t.query(1, 1, n, b, c));
    		}
    	}
    	return 0;
    }
    
  • 相关阅读:
    mybatis中crud操作范例
    Guava----Function
    Spring mvc Controller接口
    简单的验证码识别(opecv)
    Mat转换为QImage
    将多张图片无缝拼接方法
    模式识别---图像二值化
    双边过滤算法
    C++对于大型图片的加载缩放尝试
    ijg库解码超大型jpeg图片
  • 原文地址:https://www.cnblogs.com/liuzz-20180701/p/11494578.html
Copyright © 2011-2022 走看看