HDU1166 树状数组入门

旧街凉风 提交于 2019-11-30 06:07:38
/**/
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <stack>
#include <queue>

typedef long long LL;
typedef unsigned long long ULL;
using namespace std;

bool Sqrt(LL n) { return (LL)sqrt(n) * sqrt(n) == n; }
const double PI = acos(-1.0), ESP = 1e-10;
const LL INF = 99999999999999;
const int inf = 999999999, N = 5e4 + 24;
int T, n, w, a[N], C[N];
char s[6];

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

void Add(int i, int w) {
    while(i <= n) {
        C[i] += w;
        i += lowbit(i);
    }
}

int sum(int i) {
    int sum = 0;
    while(i > 0) {
        sum += C[i];
        i -= lowbit(i);
    }
    return sum;
}

int main()
{
    //freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
    scanf("%d", &T);
    for(int kase = 1; kase <= T; kase++) {
        scanf("%d", &n);
        // memset(a, 0, sizeof a); memset(C, 0, sizeof C);
        for(int i = 0; i <= n; i++) a[i] = C[i] = 0;
        for(int i = 1; i <= n; i++) { scanf("%d", &w); Add(i, w); }
        printf("Case %d:\n", kase);
        // if(s[0] == 'E') continue;
        // else if(s[0] == 'A') {
        // }
        // else if(s[0] == 'S') Sub();
        // else if(s[0] == 'Q') Query();
        int u, v;
        // getchar();
        while(scanf("%s", s), strcmp(s, "End") != 0) {
            // printf("\ns = %s\n", s);
            scanf("%d%d", &u, &v);
            if(strcmp(s, "Query") == 0) printf("%d\n", sum(v) - sum(u - 1));
            if(strcmp(s, "Add") == 0) Add(u, v);
            if(strcmp(s, "Sub") == 0) Add(u, -v); 
        }
    }

    return 0;
}
/*
    input:
    output:
    modeling:
    methods:
    complexity:
    summary:
*/

 

Sample Input
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
 
Sample Output
Case 1:
6
33
59
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!