poj 3468 A Simple Problem with Integers

A Simple Problem with Integers

Time Limit: 5000MS   Memory Limit: 131072K
Total Submissions: 32903   Accepted: 9360
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

线段树模版题
#include <stdio.h>
#include <stdlib.h>
#define maxn 100040
#define ll long long
struct node
{
 int l,r;
 ll cover,sum;
}t[maxn*9];
ll a[maxn];
ll ans;
void lazy( int n) // 更新节点,把大区间的增值传给小区间,给小区间的值加上增量
{
  if(t[n].cover)
  {
    t[2*n].cover+=t[n].cover; // 更新子树时会用到
    t[2*n+1].cover+=t[n].cover;
    t[2*n].sum+=(t[2*n].r-t[2*n].l+1)*t[n].cover; // 这时候的值就是区间和
    t[2*n+1].sum+=(t[2*n+1].r-t[2*n+1].l+1)*t[n].cover;
    t[n].cover=0;
  }
}
void built( int s,int e,int n)
{
 t[n].l=s,t[n].r=e,t[n].cover=0;
 if(s==e){t[n].sum=a[s];return;}
 int mid=(s+e)>>1;
 built(s,mid,n*2);built(mid+1,e,n*2+1);
 t[n].sum=t[n*2].sum+t[n*2+1].sum;
}
void modify( int s,int e,ll w,int n)
{
  if(t[n].l>e||t[n].r<s) return ;
  if(s<=t[n].l&&t[n].r<=e)
  {
 t[n].cover+=w;t[n].sum+=(t[n].r-t[n].l+1)*w;
 return ;
  }
   if(t[n].l==t[n].r) return ;
   lazy(n);
 
   int mid=(t[n].l+t[n].r)>>1;
   if(e<=mid) modify(s,e,w,n*2);
   else if(s>mid) modify(s,e,w,n*2+1);
   else {modify(s,mid,w,2*n);modify(mid+1,e,w,2*n+1);}
   t[n].sum=t[n*2].sum+t[n*2+1].sum;
}
void solve( int s,int e,int n)
{
 if(t[n].l>e||t[n].r<s) return ;
  if(s<=t[n].l&&t[n].r<=e)
  {
 ans+=t[n].sum;
 return ;
  }
  if(t[n].l==t[n].r) return ;
  lazy(n);
 
  int mid=(t[n].l+t[n].r)>>1;
  if(e<=mid) solve(s,e,2*n);
  else if(s>mid) solve(s,e,2*n+1);
  else {solve(s,mid,2*n);solve(mid+1,e,2*n+1);}
 
}
int main( )
{
  int n,q,x,y;
  ll v;
  int i;
  char s[4];
  scanf("%d%d",&n,&q);
  for( i=1;i<=n;i++)
  {
 scanf("%lld",&a[i]);
  }
  built(1,n,1);
  while(q--)
  {
 scanf("%s",s);
 if(s[0]=='C'){scanf("%d%d%lld",&x,&y,&v);modify(x,y,v,1);}
 if(s[0]=='Q'){scanf("%d%d",&x,&y);ans=0;solve(x,y,1);printf("%lld\n",ans);}
  }
// system("pause");
  return 0;
}

链接:http://poj.org/problem?id=3468

你可能感兴趣的:(Integer)