SPOJ 8002 Horrible Queries(线段树)区间更新,区间和

HORRIBLE - Horrible Queries


World is getting more evil and it's getting tougher to get into the Evil League of Evil. Since the legendary Bad Horse has retired, now you have to correctly answer the evil questions of Dr. Horrible, who has a PhD in horribleness (but not in Computer Science). You are given an array of N elements, which are initially all 0. After that you will be given Ccommands. They are -

0 p q v - you have to add v to all numbers in the range of p to q (inclusive), where p and q are two indexes of the array.

1 p q - output a line containing a single integer which is the sum of all the array elements between p and (inclusive)

 

Input

In the first line you'll be given T, number of test cases.

Each test case will start with (N <= 100 000) and C (C <= 100 000). After that you'll be given commands in the format as mentioned above. 1 <= pq <= N and 1 <= v <= 10^7.

Output

Print the answers of the queries.

Example

Input:
1
8 6
0 2 4 26
0 4 8 80
0 4 5 20
1 8 8
0 5 7 14
1 4 8

Output:
80
508
#include<cstdio>
#include<limits.h>
#include<iostream>
using namespace std;
#define ll long long 
ll lazy[450000],tree[450000];
void update_tree(ll node, ll a, ll b, ll i, ll j, ll val)
{
	if(lazy[node]!=0)
	{
		tree[node]+=lazy[node];
		if(a!=b)
		{
			lazy[2*node+1]+=(lazy[node]/(b-a+1))*(((a+b)/2)-a+1);
			lazy[2*node+2]+=(lazy[node]/(b-a+1))*(b-((a+b)/2));
		}
		lazy[node]=0;
	}
	if(a>b || a>j || b<i)
	{
		return;
	}
	if(a>=i && b<=j)
	{
		tree[node]+=val*(b-a+1);
		if(a!=b)
		{
			ll mid=(a+b)/2;
			lazy[node*2+1]+=val*(mid-a+1);
			lazy[node*2+2]+=val*(b-mid);
		}
		return;
	}
	ll mid=(a+b)/2;
	update_tree(node*2+1,a,mid,i,j,val);
	update_tree(node*2+2,mid+1,b,i,j,val);
	tree[node]=tree[node*2+1]+tree[node*2+2];
}
ll query(ll node, ll a, ll b, ll i, ll j)
{
	if(a>b || a>j || b<i)
	{
		return 0;
	}
	if(lazy[node]!=0)
	{
		tree[node]+=lazy[node];
		if(a!=b)
		{
			lazy[2*node+1]+=(lazy[node]/(b-a+1))*(((a+b)/2)-a+1);
			lazy[2*node+2]+=(lazy[node]/(b-a+1))*(b-((a+b)/2));
		}
		lazy[node]=0;
	}
	if(a>=i && b<=j)
	{
		return tree[node];
	}
	ll mid=(a+b)/2;
	ll q1=query(node*2+1,a,mid,i,j);
	ll q2=query(node*2+2,mid+1,b,i,j);
	ll res=q1+q2;
	return res;
}
int main()
{
	ios::sync_with_stdio(false);
	long long t;
	cin >> t;
	ll i;
	

	while(t--)
	{
		ll n,c;
		for(i=0;i<450000;i++)
		{
			lazy[i]=0;
			tree[i]=0;
		}
		int key;
		cin>>n>>c;
		while(c--)
		{
			cin>>key;
			if(key==0)
			{
				ll x,y,v;
				cin>>x>>y>>v;
				update_tree(0,0,n-1,x-1,y-1,v);
			}
			else
			{
				ll x,y;
				cin >> x >>y;
				cout << query(0,0,n-1,x-1,y-1) << "\n";
			}	
		}
	}
	return 0;
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值