poj 3468 A Simple Problem with Integers

该题是一道区间求和的问题,同时对区间值进行改变,这里我们用到lazy,以便我们不要更新到每个节点,直到我们要用到时我们才往下传递,这样就可以节省时间;

#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
class Node
{
public:
int l,r,mid;
long long lazy,sum;
};
Node tree[400024];
long long num[100024];
class Tree
{
public:
void Maketree( int l,int r,int cnt );
void Change( int l,int r,int cnt,int m );
long long Qestion( int l,int r,int cnt );
// void Pushdown( int cnt );
void Updata( int cnt );
};
void Tree::Maketree( int l,int r,int cnt )
{
if( l == r )
{
tree[cnt].l = tree[cnt].r =tree[cnt].mid = l;
tree[cnt].sum = num[l];
tree[cnt].lazy = 0;
return ;
}
else
{
tree[cnt].l = l;
tree[cnt].r = r;
tree[cnt].mid = ( l + r )>>1;
Maketree( l , tree[cnt].mid , cnt*2 );
Maketree( tree[cnt].mid + 1 , r , cnt*2 +1 );
tree[cnt].sum = tree[cnt*2].sum + tree[cnt*2+1].sum;
tree[cnt].lazy = 0;
}
}
void Tree::Change( int l, int r, int cnt,int m )
{
if( l == tree[cnt].l && r == tree[cnt].r )
{
tree[cnt].lazy+=m;
// Updata( cnt );
tree[cnt].sum += ( tree[cnt].r - tree[cnt].l +1 )*m;
// Pushdown( cnt );
return;
}
if( tree[cnt].lazy )
Updata( cnt );
if( r <= tree[cnt].mid )
{
Change( l ,r ,cnt*2 , m );
}
else
{
if( l > tree[cnt].mid )
Change( l , r , cnt*2 +1 ,m );
else
{
Change( l , tree[cnt].mid , cnt*2 , m );
Change( tree[cnt].mid+1 , r ,cnt *2+1 ,m );
}
}
tree[cnt].sum = tree[cnt*2].sum + tree[cnt*2+1].sum;
}
void Tree::Updata( int cnt )
{
tree[cnt*2].lazy += tree[cnt].lazy;
tree[cnt*2+1].lazy += tree[cnt].lazy;
// tree[cnt].sum=(tree[cnt*2].sum + tree[cnt*2+1].sum);
// tree[cnt].sum+=(tree[cnt].r - tree[cnt].l)*tree[cnt].lazy;
tree[cnt*2].sum+=( tree[cnt*2].r - tree[cnt*2].l +1 )*tree[cnt].lazy;
tree[cnt*2+1].sum+=( tree[cnt*2+1].r - tree[cnt*2+1].l +1 )*tree[cnt].lazy;
tree[cnt].lazy=0;
}
//void Tree::Pushdown( int cnt )
//{

// tree[cnt].lazy = 0;
//}
long long Tree::Qestion(int l,int r, int cnt )
{

if( l == tree[cnt].l && r == tree[cnt].r )
{
return tree[cnt].sum;
}
else
{
Updata( cnt );
if( l>tree[cnt].mid )
return Qestion( l , r ,cnt *2 +1 );
else
if( r <= tree[cnt].mid )
return Qestion( l , r, cnt *2 );
else return Qestion( l , tree[cnt].mid , cnt*2 )+Qestion( tree[cnt].mid+1 , r ,cnt*2+1 );
}
}
int main( )
{
int m,n,l,r;
long long number;
char c[5];
while( scanf( "%d%d",&n,&m )==2 )
{
Tree e;
memset( tree,0,sizeof( tree ) );
for( int i=1; i<= n ; i++ )
{
scanf( "%lld",&num[i] );
}
e.Maketree(1 , n , 1);
while( m-- )
{
scanf( "%s",c );
if( c[0]=='Q' )
{
scanf( "%d%d",&l,&r );
printf( "%lld\n",e.Qestion( l , r, 1 ) );
}
else
{
scanf( "%d%d%lld",&l,&r,&number );
e.Change( l ,r ,1, number );
}
}
}
return 0;
}

 

你可能感兴趣的:(Integer)