2021.01.25

2021.01.25

线段树

#include<cstdio>
#include<stdlib.h>
#include<string.h>
#include<string>
#include<map>
#include<cmath>
#include<iostream>
#include <queue>
#include <stack>
#include<algorithm>
#include<set>
using namespace std;
const int M = 50010;
int tree[4 * M], a[M];
void add(int node, int start, int end, int x, int y)
{
	if (start == end)
	{
		a[x] = y;
		tree[node] += y;
		return;
	}
	int mid = (start + end) / 2;
	int left = 2 * node;
	int right = 2 * node + 1;
	if (x >= start && x <= mid)
		add(left, start, mid, x, y);
	else
		add(right, mid + 1, end, x, y);
	tree[node] = tree[left] + tree[right];
}
int query(int node, int start, int end, int l, int r)
{
	if (r<start || l>end)
		return 0;
	else if (start == end)
		return tree[node];
	else if (r <= start && l >= end)
		return tree[node];
	int mid = (start + end) / 2;
	int left = 2 * node;
	int right = 2 * node + 1;
	int sum_l = query(left, start, mid, l, r);
	int sum_r = query(right, mid + 1, end, l, r);
	return sum_l + sum_r;
}
void build_tree(int node,int start,int end)
{
	if (start == end)
	{
		tree[node] = a[end];
		return;
	}
	int mid = (start + end) / 2;
	int left = 2 * node;
	int right = 2 * node+1;
	build_tree(left,start,mid);
	build_tree(right, mid + 1, end);
	tree[node] = tree[left]+ tree[right];
}
int main() {
	int t, n, ca = 1;
	char ch[10];
	int x, y;
	cin >> t;
	while (t--)
	{
		cin >> n;
		for (int i = 1; i <= n; i++)
			cin >> a[i];
		build_tree(1, 1, n);
		printf("Case %d:\n", ca++);
		while (cin >> ch)
		{
			if (strcmp(ch, "End") == 0)
				break;
			cin >> x >> y;
			if (strcmp(ch, "Add") == 0)
				add(1, 1, n, x, y);
			else if (strcmp(ch, "Sub") == 0)
				sub(1, 1, n, x, y);
			else if (strcmp(ch, "Query") == 0)
				cout << query(1, 1, n, x, y) << endl;
		}
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值