UVa12086 - Potentiometers

题目大意

给定n个数,你的任务是实现如下两种操作:

“S x y“ 把第x个数修改为y

“M x y”计算第X个数到第Y个数之和

题解

这刚好是树状数组的功能,修改元素的值和求区间和

代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#define MAXN 200005
using namespace std;
int n;
int c[MAXN];
int lowbit(int x)
{
    return x&-x;
}
void add(int x,int d)
{
    while(x<=n)
    {
        c[x]+=d;
        x+=lowbit(x);
    }
}
int sum(int x)
{
    int ret=0;
    while(x>0)
    {
        ret+=c[x];
        x-=lowbit(x);
    }
    return ret;
}
int main(void)
{
    int i,k,x,y,p,t;
    bool first_case=true;
    string s;
    p=0;
    while(scanf("%d",&n)&&n)
    {
        if (!first_case)
            cout << endl;
        first_case = false;
        printf("Case %d:\n",++p);
        memset(c,0,sizeof(c));
        for(i=1; i<=n; i++)
        {
            scanf("%d",&k);
            add(i,k);
        }
        while(cin>>s)
        {
            if(s=="END") break;
            if(s=="M")
            {
                scanf("%d%d",&x,&y);
                printf("%d\n",sum(y)-sum(x-1));
            }
            else
            {
                scanf("%d%d",&x,&y);
                t=sum(x)-sum(x-1);
                add(x,y-t);
            }
        }
    }
    return 0;
}

posted on 2013-04-19 20:08  仗剑奔走天涯  阅读(331)  评论(0编辑  收藏  举报

导航