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;
    }
    
  • 相关阅读:
    GitHub上创建项目
    html5的标签中,哪些是行内元素,哪些是块级元素。
    盒子模型及其他的层次结构关系
    二维码生成
    SSH整合笔记
    Spring回顾
    struts2 测试错题解析
    Java Script基础
    Java OOP考试错题分析
    接口的用法及注意点
  • 原文地址:https://www.cnblogs.com/liuzz-20180701/p/11494578.html
Copyright © 2011-2022 走看看