线段树 Raw code


#include <iostream>
#include <cstdio>

using namespace std;

struct seg_tree
{
	int l, r;
	long long v, lazy;
} tree[400001];

void build(int k, int l, int r)
{
	tree[k].l = l, tree[k].r = r;
	if (l == r)
	{
		scanf("%lld", &tree[k].v);
	}
	else
	{
		int m = (l + r) >> 1;
		build(k << 1, l, m);
		build(k << 1 | 1, m + 1, r);
		tree[k].v = tree[k << 1].v + tree[k << 1 | 1].v;
	}
}

void busify(int k)
{
	int l = tree[k << 1].l, r = tree[k << 1].r;
	tree[k << 1].lazy += tree[k].lazy;
	tree[k << 1].v += (r - l + 1) * tree[k].lazy;

	l = tree[k << 1 | 1].l, r = tree[k << 1 | 1].r;
	tree[k << 1 | 1].lazy += tree[k].lazy;
	tree[k << 1 | 1].v += (r - l + 1) * tree[k].lazy;
	tree[k].lazy = 0;
}

void update(int k, int l, int r, long long v)
{
	if (l > tree[k].r || r < tree[k].l) return;
	if (tree[k].l >= l && tree[k].r <= r)
	{
		tree[k].lazy += v;
		tree[k].v += (tree[k].r - tree[k].l + 1) * v;
	}
	else
	{
		if(tree[k].lazy) busify(k);
		int m = (tree[k].l + tree[k].r) >> 1;
		if (l <= m) update(k << 1, l, r, v);
		if (r > m) update(k << 1 | 1, l, r, v);
		tree[k].v = tree[k << 1].v + tree[k << 1 | 1].v;
	}
}

long long sum(int k, int l, int r)
{
	if (l > tree[k].r || r < tree[k].l) return 0;
	if (tree[k].l >= l && tree[k].r <= r)
	{
		return tree[k].v;
	}
	else
	{
		if(tree[k].lazy) busify(k);
		int m = (tree[k].l + tree[k].r) >> 1; long long s = 0;
		if (l <= m) s += sum(k << 1, l, r);
		if (r > m) s += sum(k << 1 | 1, l, r);
		return s;
	}
}

int main()
{
	int n, m;
	scanf("%d%d", &n, &m);
	build(1, 1, n);
	while (m--)
	{
		int op, a, b; long long c;
		scanf("%d", &op);
		if (op == 1)
		{
			scanf("%d%d%lld", &a, &b, &c);
			update(1, a, b, c);
		}
		else if (op == 2)
		{
			scanf("%d%d", &a, &b);
			printf("%lld\n", sum(1, a, b));
		}
	}
}

posted @ 2017-10-13 22:40  Js2xxx  阅读(389)  评论(0编辑  收藏  举报