hdu1166(线段树版本)

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 50010;
int tree[maxn*4];
int t = 0, n = 0;

int tree_add(int v, int s, int t, int a, int b, int c, int d) {
    //printf("add(%d, %d, %d)\n", v,s, t);
    if (a<=s && t<=b) {
        tree[v] += d*c;//d表示加减,c插入的值
        //printf("1:tree[%d] = %d\n", v, tree[v]);
        return 0;
    }
    if (s == t) {
        return 0;
    }
    int mid = (s+t)/2;
    if (a <= mid) {
        tree_add(v<<1, s, mid, a, b, c, d);//左孩子
    }
    if (b > mid) {
        tree_add((v<<1)+1, mid+1, t, a, b, c, d);//右孩子
    }
    tree[v] = tree[v<<1] + tree[(v<<1)+1];
    //printf("2:tree[%d] = %d\n", v, tree[v]);
    return 0;
}

int tree_query(int v, int s, int t, int a, int b) {
    int ans = 0;//在区间a到b中查询s到t
    if (a<=s && t<=b) {
        ans += tree[v];
        return ans;
    }
    if (s == t) {
        return 0;
    }
    int mid = (s+t)/2;
    if (a <= mid) {
        ans += tree_query(v<<1, s, mid, a, b);
    }
    if (b > mid) {
        ans += tree_query((v<<1)+1, mid+1, t, a, b);
    }
    return ans;
}

int init() {
    scanf("%d", &n);
    for (int i = 1; i <= n*4; i++) {  //初始化一下
        tree[i] = 0;
    }
    int da[maxn];
    for (int i = 1; i <= n; i++) { //输入n个数
        scanf("%d", &da[i]);
    }
    for (int i = 1; i <= n; i++) {
        tree_add(1, 1, n, i, i, da[i], 1);
    }
    return 0;
}

int work() {
    char cmd[10];
    int a = 0, b = 0, v = 0;
    while (1==scanf("%s", cmd) && cmd[0]!='E') {
        if (cmd[0] == 'A') {//加入元素
            scanf("%d%d", &a, &v);
            tree_add(1, 1, n, a, a, v, 1);
        }
        else if (cmd[0] == 'S') {//减掉
            scanf("%d%d", &a, &v);
            tree_add(1, 1, n, a, a, v, -1);
        }
        else if (cmd[0] == 'Q') {
            scanf("%d%d", &a, &b);//找1到n中查询a到b
            int ans = tree_query(1, 1, n, a, b);
            printf("%d\n", ans);
        }
    }
    return 0;
}

int main()
{
    scanf("%d", &t);//测试实例
    for(int i = 1; i <= t; i++) {
        init();
        printf("Case %d:\n", i);
        work();
    }
    return 0;
}
//赋有调试信息,代码冗余但是便于理解

你可能感兴趣的:(c,tree,cmd,测试,query,include)