树 || 线段树(敌兵布阵)

Input
第一行一个整数T,表示有T组数据。 
每组数据第一行一个正整数N(N<=50000),表示敌人有N个工兵营地,接下来有N个正整数,第i个正整数ai代表第i个工兵营地里开始时有ai个人(1<=ai<=50)。 
接下来每行有一条命令,命令有4种形式: 
(1) Add i j,i和j为正整数,表示第i个营地增加j个人(j不超过30) 
(2)Sub i j ,i和j为正整数,表示第i个营地减少j个人(j不超过30); 
(3)Query i j ,i和j为正整数,i<=j,表示询问第i到第j个营地的总人数; 
(4)End 表示结束,这条命令在每组数据最后出现; 
每组数据最多有40000条命令 
Output
对第i组数据,首先输出“Case i:”和回车, 
对于每个Query询问,输出一个整数并回车,表示询问的段中的总人数,这个数保持在int以内。 
Sample Input
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 
Sample Output
Case 1:
6
33

59


#include<stdio.h>
#include<memory.h>
#include<iostream>
#include<algorithm>
#include<vector>
#include<algorithm>
#include<math.h>
#include<set>
#include<queue>
using namespace std;
typedef long long ll;
int T;
int n;
int a[50005];
int tree[50005<<2];
void build(int l,int r,int root){
	if(l==r){
		tree[root]=a[l];
		return;
	}
	int m=(l+r)/2;
	build(l,m,root*2);
	build(m+1,r,root*2+1);
	tree[root]=tree[root*2]+tree[root*2+1];
}
int query(int x,int y,int l,int r,int root){
	if(x<=l&&y>=r){
		return tree[root];
	}
	int m=(l+r)/2;
	int ans=0;
	if(x<=m){
		ans+=query(x,y,l,m,root*2);
		
	}
	if(y>=m+1){
		ans+=query(x,y,m+1,r,root*2+1);
	}
	return ans;
}
void update(int x,int c,int l,int r,int root){
	if(l==r){
		tree[root]+=c;
		return ;
	}
	int m=(l+r)/2;
	if(x<=m){
		update(x,c,l,m,root*2);
	}
	else if(x>=m+1){
		update(x,c,m+1,r,root*2+1);
	}
	tree[root]+=c;
}
int main(){
	scanf("%d",&T);
	int t=1;
	while(t<=T){
		scanf("%d",&n);
		for(int i=1;i<=n;i++){
			scanf("%d",&a[i]);
		}
		build(1,n,1);
		printf("Case %d:\n",t);
		char c[10];
		int ad,bd;
		while(scanf("%s",&c)){
			if(c[0]=='E')break;
			else if(c[0]=='Q'){
				scanf("%d%d",&ad,&bd);
				printf("%d\n",query(ad,bd,1,n,1));
			}
			else if(c[0]=='A'){
				scanf("%d%d",&ad,&bd);
				update(ad,bd,1,n,1);
			}
			else if(c[0]=='S'){
				scanf("%d%d",&ad,&bd);
				update(ad,-bd,1,n,1);
			}
		}
		t++;
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bekote

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值