首页 > 代码库 > uva 12086 - Potentiometers (树状数组)

uva 12086 - Potentiometers (树状数组)

就是树状数组的模板就可以,但是

特别注意一点,树状数组中的C数组不清零,就会导致出错。

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
using namespace std;
const int maxn = 200010;

int c[maxn];
int a[maxn];
int n;

int lowbit(int x)
{
    return x&(-x);
}

int sum(int x)
{
    int cnt=0;
    while(x>0)
    {
        cnt+=c[x];
        x-=lowbit(x);
    }
    return cnt;
}

void add(int x,int d)
{
    while(x<=n)
    {
        c[x]+=d;
        x+=lowbit(x);
    }
}

int main()
{
    int kase = 0;
    while(scanf("%d",&n)!=EOF)
    {
        if(n==0) break;
        memset(c,0,sizeof(c));///C数组不清零就wrong answer;
        for(int i=1;i<=n;i++){
            scanf("%d",&a[i]);
            add(i,a[i]);
        }
        if(kase) printf("\n");
        printf("Case %d:\n",++kase);
        char s[10];
        while(scanf("%s",s)!=EOF){
            if(s[0]=='E') break;
            if(s[0]=='M'){
                int x,y;
                scanf("%d%d",&x,&y);
                printf("%d\n",sum(y)-sum(x-1));
            }
            else{
                int x,y;
                scanf("%d%d",&x,&y);
                add(x,y-a[x]);
                a[x]=y;
            }
        }
    }
    return 0;
}


uva 12086 - Potentiometers (树状数组)