标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 64187 Accepted Submission(s): 27057
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <time.h>
#include <string>
#include <map>
#include <stack>
#include <vector>
#include <set>
#include <queue>
#define M 10000
#define maxn (500000 + 2)
#define pi acos(-1.0)
using namespace std;
struct node
{
int l;
int r;
int sum = 0;
};
node tree[maxn];
void build_tree(int p,int l,int r) //p代表节点下标,从1开始,l和r分别是节点左边界和右边界
{
tree[p].l = l;
tree[p].r = r;
if(l == r) //如果l == r,到达叶子节点,为tree[p].sum赋值
{
scanf("%d",&tree[p].sum);
return ;
}
build_tree(p << 1,l,(l + r) / 2); //如果l != r递归,建左子树
build_tree((p << 1) + 1,(l + r) / 2 + 1,r); //和右子树
tree[p].sum = tree[p << 1].sum + tree[(p << 1) + 1].sum;//下标为p的节点的sum值为(p << 1)和(p << 1 + 1)节点sum值的和;
}
void Add(int i,int add,int n) //减少人数等于添加人数的负值,只用一个函数实现两个功能
{
if(tree[n].l == tree[n].r) //如果节点的l == r,说明l == r == 需要增加(或减少的节点),则,加;
{
tree[n].sum = tree[n].sum + add;
while(1) //往上找该节点的父亲,同加
{
n = n >> 1;
tree[n].sum = tree[n].sum + add;
if(n == 1) return;
}
}
if(i >= tree[n].l && i <= (tree[n].l + tree[n].r) / 2)//如果节点i在下标为n的节点的mid左边,搜索下标为(n << 1)的节点
{
Add(i,add,n << 1);
return;
}
else
{
Add(i,add,(n << 1) + 1); //否则,搜索节点为(n << 1 + 1) 的节点
return;
}
}
int Query(int l,int r,int n)
{
int mid = (tree[n].l + tree[n].r) >> 1;
if(tree[n].l == l && tree[n].r == r) return tree[n].sum;
if(r <= mid) return Query(l,r,n << 1);
if(l >= mid + 1) return Query(l,r,(n << 1) + 1);
else return Query(l,mid,n << 1) + Query(mid + 1,r,(n << 1) + 1);
}
int main()
{
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
int t;
scanf("%d",&t);
for(int Case = 1;Case <= t;Case ++)
{
printf("Case %d:\n",Case);
int n;
scanf("%d", &n);
build_tree(1,1,n);//建树
string Oper;
while(cin >> Oper && Oper != "End")
{
int a,b;
scanf("%d%d",&a,&b);
if(Oper == "Query") printf("%d\n",Query(a,b,1));
else if(Oper == "Add") Add(a,b,1);
else if(Oper == "Sub") Add(a,-b,1);
}
}
return 0;
}
标签:
原文地址:http://www.cnblogs.com/zouqihan/p/5041219.html