1 10 1 2 3 4 5 6 7 8 9 10 Query 1 3 Add 3 6 Query 2 7 Sub 10 2 Add 6 3 Query 3 10 End
Case 1: 6 33 59
树状数组模版一枚~,不过好长时间没做,wa了~; 注意的是存数的时候要从1开始。我感觉应该是个坑 但是我没有跳~ 但是仍被坑~!因为大量数据输入输出,c++输入输出流
不TLE才怪!
#include<iostream>
#include<stdio.h>
#include<string>
#include<string.h>
using namespace std;
const int INF=50003;
int cc[INF];
int c[INF];
int lowbit(int x)
{
    return x&(-x);
}
int sum(int i)
{
    int s=0;
    while(i>0)
    {
        s+=c[i];
        i-=lowbit(i);
    }
    return s;
}
void add(int i,int val)
{
    while(i<INF)
    {
        c[i]+=val;
        i+=lowbit(i);
    }
}
int main()
{
    int t;
    scanf ("%d",&t);
    int cas=1;
    while(t--)
    {
        int n;
        scanf("%d",&n);
        c[0]=0;
        memset(c,0,sizeof(c));
        for(int i=1; i<=n; i++)
        {
            scanf("%d",&cc[i]);
            add(i,cc[i]);
        }
        printf("Case %d:\n",cas++);
        char str[100];
        while(scanf("%s",str)!=EOF)
        {
            if(str[0]=='E')
            {
                break;
            }
            else if(str[0]=='A')
            {
                int a,b;
                scanf("%d%d",&a,&b);
                add(a,b);
            }
            else if(str[0]=='Q')
            {
                int a,b;
                scanf("%d%d",&a,&b);
                printf("%d\n",sum(b)-sum(a-1));
            }
            else if(str[0]=='S')
            {
                int a,b;
                scanf("%d%d",&a,&b);
                add(a,-b);
            }
        }
    }
    return 0;
}
原文:http://blog.csdn.net/lsgqjh/article/details/46664391