void-man

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

比较简单的应用,中文题,三种操作

需要注意一点,这次update更新函数需要增加一个参数,应为人数有增删两种操作

#include <stdio.h>
#include <string.h>
#define MAX 100010
int c[MAX],a[MAX];
int lowbit(int x)
{
    return x&(-x);
}
void update(int x,int val)
{
    while(x<MAX)
    {
        c[x]+=val;
        x+=lowbit(x);
    }
}
int get(int x)
{
    int sum=0;
    while(x>0)
    {
        sum+=c[x];
        x-=lowbit(x);
    }
    return sum;
}
int main()
{
    int n,q,l,r,k,t,ca=1;
    char s[10];
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        memset(c,0,sizeof(c));
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
            update(i,a[i]);
        }
        printf("Case %d:\n",ca++);
        for(;1;)
        {
            scanf("%s",s);
            if(s[0]=='E')break;
            scanf("%d%d",&l,&r);
            if(s[0]=='Q')
            printf("%d\n",get(r)-get(l-1));
            else if(s[0]=='A')
            update(l,r);
            else
            update(l,-r);
        }
    }
}

/*线段树做法*/
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <climits>
#define L(x) ( x << 1 )
#define R(x) ( x << 1 | 1 )
#define MID(x,y) ( (x+y)>>1 )
using namespace std;

const int MAX = 50010;
struct Tnode{int sum,l,r;};
Tnode node[MAX*4];
int num[MAX];
void init()
{
	memset(node,0,sizeof(node));
}
void Build(int t,int l,int r)
{
	node[t].l = l; node[t].r = r;
	if( l == r - 1 )
	{
		node[t].sum = num[l-1];
		return ;
	}
	int mid = MID(l,r);
	Build(L(t),l,mid);
	Build(R(t),mid,r);
	node[t].sum = node[R(t)].sum + node[L(t)].sum;
}

void Updata(int t,int l,int r,int sum)//此题只更新一个点,利用线段树可以更新一个区间
{
	if( node[t].l == l && node[t].r == r )
	{
		node[t].sum += sum;
		return ;
	}
	int mid = MID(node[t].l,node[t].r);
	if( l < mid )//,更新区间的话就不能这样写,如果r<mid,更新右区间是r不是mid
		Updata(L(t),l,r,sum);
	if(r>mid)
        Updata(R(t),l,r,sum);
	node[t].sum += sum;
}

int Query(int t,int l,int r)
{
	if( node[t].l == l && node[t].r == r )
		return node[t].sum;
	int mid = MID(node[t].l,node[t].r);
	if( l >= mid )
		return Query(R(t),l,r);
	else
		if( r <= mid )
			return Query(L(t),l,r);
		else
			return Query(L(t),l,mid) + Query(R(t),mid,r);
}

int main()
{
	int ind = 1,ncases,n,x,y;
	char s[10];
	scanf("%d",&ncases);

	while( ncases-- )
	{
		scanf("%d",&n);
		for(int i=0; i<n; i++)
			scanf("%d",&num[i]);
		init();
		Build(1,1,n+1);
		printf("Case %d:\n",ind++);
		while( scanf("%s",s) && strcmp(s,"End") )
		{
			scanf("%d%d",&x,&y);
			if( s[0] == 'A' )
				Updata(1,x,x+1,y);
			else
				if( s[0] == 'S' )
					Updata(1,x,x+1,-y);
				else
					printf("%d\n",Query(1,x,y+1));
		}
	}
return 0;
}

posted on 2011-08-03 00:33  void-man  阅读(180)  评论(0)    收藏  举报