程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> poj 3468 A Simple Problem with Integers (線段樹成段更新)

poj 3468 A Simple Problem with Integers (線段樹成段更新)

編輯:關於C++

 

A Simple Problem with Integers Time Limit: 5000MS   Memory Limit: 131072K Total Submissions: 77486   Accepted: 23862 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

題目大意:C情況時a-b區間內每個數字添加c,Q情況時查詢區間內值的和。

解題思路:模板線段樹成段更新問題。

代碼如下:

 

#include 
#include 
#define inf 1e12
#define ll long long 
const ll maxn=1000010;
ll n,m,a,b,c;
ll sum[maxn],nd[maxn];
char s[2];
void build(ll l,ll r,ll root)
{
	ll mid=(l+r)/2;
	if(l==r)
	{
		scanf(%lld,&sum[root]);
		return;
	}
	build(l,mid,root*2);
	build(mid+1,r,root*2+1);
	sum[root]=sum[root*2]+sum[root*2+1];
}
void pushdown(ll l,ll root)
{
	if(nd[root]!=0)
	{
		nd[root*2]+=nd[root];
		nd[root*2+1]+=nd[root];
		sum[root*2]+=((l-l/2)*nd[root]);
		sum[root*2+1]+=((l/2)*nd[root]);
		nd[root]=0;
	}
}
ll query(ll l,ll r,ll root)
{
	if(l>=a&&r<=b)
		return sum[root];
	pushdown(r-l+1,root);
	ll mid=(l+r)/2,ans=0;
	if(a<=mid)
		ans+=query(l,mid,root*2);
	if(b>mid)
		ans+=query(mid+1,r,root*2+1);
	return ans;			
}
void update(ll l,ll r,ll root)
{
	if(l>b||r=a&&r<=b)
	{
		nd[root]+=c;
		sum[root]+=(len*c);
		return ;
	}
	pushdown(len,root);
	int mid=(l+r)/2;
	if(a<=mid)
	update(l,mid,root*2);
	if(b>mid)
	update(mid+1,r,root*2+1);
	sum[root]=sum[root*2]+sum[root*2+1];
}
int main(void)
{
	memset(nd,0,sizeof(nd));
	scanf(%lld%lld,&n,&m);
	build(1,n,1);
	for(ll i=0;i

 

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved