二叉索引树(树状数组)

来源:互联网 发布:中小型企业网络建设 编辑:程序博客网 时间:2024/05/22 17:18

连续和查询问题。给定一个n个元素的数组 A1,A2,...,An ,你的任务是数据结构,支持一个查询操作 Query(L,R):计算 A(L) + A(L+1) + ... + A(R)

树状数组比较简单

http://img1.imgtn.bdimg.com/it/u=1910791428,787613617&fm=21&gp=0.jpg

主要是求区间和操作 and  改变某个值操作

#include <iostream>#include <string.h>using namespace std;int const MAX = 10005;int n, C[MAX];int lowbit(int x){    return x & (-x);}int sum(int x){    int ret = 0;    while(x > 0){        ret += C[x];   x -= lowbit(x);    }    return ret;}void add(int x, int d){// x 代表要改变的数的位置(下标) d 代表在该位置要增加多少数    while(x <= n){        C[x] += d;  x += lowbit(x);    }}int main(){    C[0] = 0;    while(cin >> n && n){        for(int i = 1; i <= n; i++){            cin >> C[i];            int t = lowbit(i) - 1;            while(t > 0){                C[i] += C[t];                t -= lowbit(t);            }        }        char op[10];        while(cin >> op && op[0] != 'e'){            if(!strcmp(op, "add")){                int x, d;                cout << "位置:";                cin >> x;                cout << "要增加多少:" ;                cin >> d;                add(x, d);            }            if(!strcmp(op, "sum")){                int x, y;                cout << "请输入要查询的区间:";                cin >> x >> y;                cout << sum(y) - sum(x-1) << endl;            }        }    }    return 0;}



0 0
原创粉丝点击