1 10 1 2 3 4 5 6 7 8 9 10 Query 1 3 Add 3 6 Query 2 7 Sub 10 2 Add 6 3 Query 3 10 End
Case 1: 6 33 59
这道题也是用的线段树做的
代码:
#include<stdio.h>
#include<string.h>
#define maxn 222222
int sum[maxn << 2] ;
int max(int x,int y)
{
return x > y ? x : y ;
}
#define lson l , m , rt << 1 //rt代表root,这里是rt*2 ;
#define rson m+1 , r , rt << 1|1 //这里是rt*2+1 ;
//把当前节点信息更新到父节点信息
void PushUp( int rt )
{
sum[rt] = sum[ rt << 1 ] + sum[rt << 1|1];
}
//建树
void Built(int l , int r , int rt)
{
if(l == r)
{
scanf("%d" , &sum[rt] ) ;
return ;
}
int m = ( l + r ) / 2 ;
Built(lson) ;
Built(rson) ;
PushUp(rt) ;
}
//增加
void Add(int a , int b , int l , int r , int rt )
{
if(l == r)
{
sum[rt] += b ;
return ;
}
int m = ( l + r ) / 2 ;
if(a <= m)
Add(a , b , lson ) ;
else
Add(a , b , rson ) ;
PushUp( rt ) ;
}
//减少
void Sub(int a , int b , int l , int r , int rt )
{
if(l == r)
{
sum[rt] -= b ;
return ;
}
int m = ( l + r ) / 2 ;
if(a <= m)
Sub(a , b , lson ) ;
else
Sub(a , b , rson ) ;
PushUp( rt ) ;
}
//查询
int query(int a , int b , int l , int r ,int rt )
{
if(a <= l && r <= b)
return sum[ rt ] ;
int m = ( r + l ) / 2 ;
int num = 0 ;
if( a <= m )
num += query(a , b ,lson ) ;
if(b > m)
num += query(a , b , rson ) ;
return num ;
}
int main()
{
int N = 0 , M = 0 ;
int T = 0 ;
int x = 1 ;
scanf("%d",&T);
while(T--)
{
scanf("%d" , &N ) ;
Built(1 , N , 1) ;
char w[10] ;
int a , b ;
printf("Case %d:\n", x++);
while( 1 )
{
scanf("%s" , w );
if(w[0] == ‘E‘)
break ;
scanf("%d%d" , &a , &b) ;
if(w[0] == ‘Q‘ )
printf("%d\n" , query(a , b , 1 , N , 1 )) ;
if(w[0] == ‘A‘)
Add( a , b , 1, N ,1) ;
if(w[0] == ‘S‘)
Sub(a , b , 1 , N , 1) ;
}
}
return 0 ;
}
原文地址:http://blog.csdn.net/bluedream1219/article/details/38022671