hdu1166 敌兵布阵 --更新查询

原题链接: http://acm.hdu.edu.cn/showproblem.php?pid=1166


一:分析
一道模板题,就是考察更新查询的知识。


二:AC代码
#define _CRT_SECURE_NO_DEPRECATE 

#include<iostream>
#include<algorithm>
using namespace std;

struct Node
{
	int left;
	int mid;//在add或sub时,是加在左子树呢还是右子树呢
	int right;
	int num;//人数
};

Node node[500002];

void init(int a, int b, int n)
{
	node[n].left = a;
	node[n].right = b;
	node[n].mid = (a + b) / 2 + 1;
	node[n].num = 0;

	if (a == b)
		return;

	init(a, (a + b) / 2, 2 * n);
	init((a + b) / 2 + 1, b, 2 * n + 1);
}

void add(int pos, int value, int n)
{
	node[n].num += value;
	if (node[n].left == node[n].right)
		return;

	if (pos < node[n].mid)
		add(pos, value, n * 2);
	else
		add(pos, value, n * 2 + 1);
}

void sub(int pos, int value, int n)
{
	node[n].num -= value;
	if (node[n].left == node[n].right)
		return;

	if (pos < node[n].mid)
		sub(pos, value, n * 2);
	else
		sub(pos, value, n * 2 + 1);
}

int query(int a, int b, int n)
{
	if (node[n].left == a&&node[n].right == b)
		return node[n].num;

	if (a < node[n].mid)
	{
		if (b < node[n].mid)
			return query(a, b, 2 * n);
		else
			return query(a, node[n].mid - 1, n * 2) + query(node[n].mid, b, n * 2 + 1);
	}
	else
		return query(a, b, 2 * n + 1);
}

int main()
{
	int T;
	int N;
	int x;
	char ch[10];
	int a, b;

	scanf("%d", &T);

	for (int i = 1; i <= T; i++)
	{
		scanf("%d", &N);
		init(1, N, 1);

		for (int j = 1; j <= N; j++)
		{
			scanf("%d", &x);
			add(j, x, 1);
		}

		printf("Case %d:\n", i);

		while (1)
		{
			scanf("%s", ch);

			if (strcmp(ch, "End") == 0)
				break;

			scanf("%d%d", &a, &b);

			if (strcmp(ch, "Query") == 0)
				printf("%d\n", query(a, b, 1));
			else if (strcmp(ch, "Add") == 0)
				add(a, b, 1);
			else
				sub(a, b, 1);
		}
	}

	return 0;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值