POJ - 3468 A Simple Problem with Integers 线段树

A Simple Problem with Integers
Time Limit: 5000MS   Memory Limit: 131072K
Total Submissions: 131119   Accepted: 40685
Case Time Limit: 2000MS

Description

You have N integers, A1, A2, ... , AN. You need to deal with two kinds of operations. One type of operation is to add some given number to each number in a given interval. The other is to ask for the sum of numbers in a given interval.

Input

The first line contains two numbers N and Q. 1 ≤ N,Q ≤ 100000.
The second line contains N numbers, the initial values of A1, A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of Aa, Aa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of Aa, Aa+1, ... , Ab.

Output

You need to answer all Q commands in order. One answer in a line.

Sample Input

10 5
1 2 3 4 5 6 7 8 9 10
Q 4 4
Q 1 10
Q 2 4
C 3 6 3
Q 2 4

Sample Output

4
55
9
15

Hint

The sums may exceed the range of 32-bit integers.

Source

POJ Monthly--2007.11.25, Yang Yi

还是线段树的一道模板题

这题用了cin cout超时了QAQ,不知道是不是我代码的写的太丑

#include
#include
#include
using namespace std;
#define MAXN 200010
typedef long long ll;
ll n, m;
ll a[MAXN];
struct node{
	ll l, r, tag,sum;
}tree[MAXN << 2];
char ch[2];

void build(ll k, ll l, ll r)
{
	tree[k].l = l; tree[k].r = r;
	if (l == r)
	{
		tree[k].sum = a[l];
		return;
	}
	ll mid = (l + r) >> 1;
	build(k << 1, l, mid); build(k << 1 | 1, mid + 1, r);
	tree[k].sum = tree[k << 1].sum+ tree[k << 1 | 1].sum;
}
void prework()
{
	
	for (ll i = 1; i <= n; i++)
		scanf("%lld", &a[i]);
	build(1, 1, n);
}
void change(ll k)
{
	if (tree[k].l == tree[k].r)
	{
		tree[k].sum += tree[k].tag;
	}
	else
	{
		tree[k].sum += (tree[k].r - tree[k].l + 1)*tree[k].tag;
		tree[k << 1].tag += tree[k].tag;
		tree[k << 1 | 1].tag += tree[k].tag;
	}
	tree[k].tag = 0;
}
void add(ll k, ll l, ll r, ll x)
{
	if (tree[k].tag)
		change(k);
	if (tree[k].l == l&&tree[k].r == r)
	{
		tree[k].tag += x;
		return;
	}
	tree[k].sum += (r - l + 1)*x;
	ll mid = (tree[k].l + tree[k].r) >> 1;
	if (r <= mid)
		add(k << 1, l, r, x);
	else if (l >= mid+1)
		add(k << 1 | 1, l, r, x);
	else
	{
		add(k << 1, l, mid, x);
		add(k << 1|1, mid + 1, r, x);
	}
}
ll query(ll k, ll l, ll r)
{
	if (tree[k].tag)
		change(k);
	ll mid = (tree[k].l + tree[k].r) >> 1;
	if (tree[k].r == r&&tree[k].l == l)
		return tree[k].sum;
	if (l >= mid + 1)
		return query(k << 1 | 1, l, r);
	else if (r <= mid)
		return query(k << 1, l, r);
	else
		return query(k << 1, l, mid) + query(k << 1|1, mid+1, r);
}
void mainwork()
{
	ll num,d, x;
	for (ll i = 1; i <= m; i++)
	{
		scanf("%s", ch);
		if (ch[0] == 'Q')
		{
			scanf("%lld%lld", &d, &x);
			printf("%lld\n", query(1, d, x));
		}
		else
		{
			scanf("%lld%lld%lld",&d,&x,&num);
			add(1, d, x, num);
		}

	}
}
int main()
{
	while (~scanf("%lld%lld", &n, &m)){
		prework();
		mainwork();
	}
	return 0;
}

你可能感兴趣的:(POJ - 3468 A Simple Problem with Integers 线段树)