【线段树 + 简单题】杭电 hdu 1166 敌兵布阵


/* THE PROGRAM IS MADE BY PYY */
/*----------------------------------------------------------------------------//
              Copyright (c) 2011 panyanyany All rights reserved.

    URL   : http://acm.hdu.edu.cn/showproblem.php?pid=1166
    Name  : 1166 敌兵布阵
    Date  : Sunday, September 18, 2011
    Time Stage : half an hour

    Result: 
4622708	2011-09-18 15:43:38	Accepted	1166
46MS	1764K	2586 B
C++	pyy小号

4622706	2011-09-18 15:43:14	Runtime Error
(ACCESS_VIOLATION)	1166
15MS	1164K	2586 B
C++	pyy小号


    Test Data :

Review :
线段树的感觉,比较麻烦一点,同时空间和时间消耗都比树状数组要大
//----------------------------------------------------------------------------*/

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <string.h>

#define MAXSIZE 50001

typedef struct {
	int left, right ;
	int sum ;
} NODE ;

int		tcase, n ;
NODE	tree[MAXSIZE * 4] ;

void build (int node, int left, int right)
{
	tree[node].left		= left ;
	tree[node].right	= right ;
	tree[node].sum		= 0 ;

	if (left == right) 
		return ;

	int mid = (left + right) / 2 ;
	build (node * 2, left, mid) ;
	build (node * 2 + 1, mid + 1, right) ;
}

void update (int node, int pos, int val)
{
	// 当前区间的总人数增加
	tree[node].sum += val ;

	// 刚好走到第pos 个营地所在的叶子
	if (tree[node].left == pos && 
		tree[node].right == pos)
	{
		return ;
	}

	int mid = (tree[node].left + tree[node].right) / 2 ;
	// 若营地在当前区间的左半边
	if (pos <= mid)
		update (node * 2, pos, val) ;
	// 若营地在当前区间的右半边
	else 
		update (node * 2 + 1, pos, val) ;

	return ;
}

int query (int node, int left, int right)
{
	// 若区间刚好匹配
	if (tree[node].left == left &&
		tree[node].right == right)
		return tree[node].sum ;

	// 若区间无交集
	if (tree[node].left > right ||
		tree[node].right < left)
		return 0 ;

	// 若区间有交集
	int mid = (tree[node].left + tree[node].right) / 2 ;

	// 若查询区间在左半边
	if (right <= mid)
		return query (node * 2, left, right) ;
	// 若查查询区间在右半边
	else if (mid < left)
		return query (node * 2 + 1, left, right) ;
	// 若查询区间横跨当前区间的中点
	else
		return query (node * 2, left, mid) + query (node * 2 + 1, mid + 1, right) ;
}


int main ()
{
	char	str[20] ;
	int		i, j ;
	int		x, y ;

	while (scanf ("%d", &tcase) != EOF)
	{
		for (j = 1 ; j <= tcase ; ++j)
		{
			scanf ("%d", &n) ;
			build (1, 1, n) ;
			for (i = 1 ; i <= n ; ++i)
			{
				scanf ("%d", &x) ;
				// 从根部开始查找,第i 个营地的值增加x
				update (1, i, x) ;
			}
			printf ("Case %d:\n", j) ;
			while (scanf ("%s", str), *str != 'E')
			{
				scanf ("%d%d", &x, &y) ;
				if (*str == 'Q')
					printf ("%d\n", query (1, x, y)) ;
				else if (*str == 'A')
					update (1, x, y) ;
				else if (*str == 'S')
					update (1, x, -y) ;
			}
		}
	}
	return 0 ;
}


你可能感兴趣的:(【线段树 + 简单题】杭电 hdu 1166 敌兵布阵)