线段树查询和

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <set>
#include <queue>
#include <map>
#include <sstream>
#include <cstdio>
#include <cstring>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <deque>
#include <bitset>
//#include <unordered_set>
//#include <unordered_map>
//#include <bits/stdc++.h>
//#include <xfunctional>
#define ll  long long
#define PII  pair<int, int>
using namespace std;
int dir[5][2] = { { 0,1 } ,{ 0,-1 },{ 1,0 },{ -1,0 } ,{ 0,0 } };
const long long INF = 0x7f7f7f7f7f7f7f7f;
const int inf = 0x3f3f3f3f;
const double pi = 3.14159265358979;
const int mod = 1e9 + 7;
const int maxn = 2005;
//if(x<0 || x>=r || y<0 || y>=c)
//1000000000000000000
int a[200005];
struct node {
    int l;
    int r;
    int w;
}tree[maxn];
void change(int x, int a) {//x节点的值修改为tree[x].w+a
    if (x == 0) return;//代表更新完毕
    tree[x].w += a;
    change(x / 2, a);
    return;
}
void build(int x, int left, int right) {//x是当前节点标号
    tree[x].l = left;
    tree[x].r = right;
    if (left == right) {
        change(x, a[left]);//修改x的值为a[left]
        return;
    }
    build(2 * x, left, (left + right) / 2);
    build(2 * x + 1, (left + right) / 2 + 1, right);
    //左右分别递归调用
    return;
}
int add(int x, int left, int right) {//返回区间和
    if ((tree[x].l == left) && (tree[x].r == right))//正好相等,返回w
        return tree[x].w;
    int mid = (tree[x].l + tree[x].r) / 2;
    if (right <= mid) //只可能存在于左儿子
        return add(x * 2, left, right);
    if (left>mid) //只可能存在于右儿子
        return add(x * 2 + 1, left, right);
    return add(x * 2, left, mid) + add(x * 2 + 1, mid + 1, right);//最普遍情况,再次一分为二
}


int main()
{
    int size;
    cin >> size;
    for (int i = 1; i <= size; i++)
        cin >> a[i];
    build(1,1,size);
    int res = 0;
    for (int i = 1; i <= size; i++)
    {
        for (int j = 0; i + j <= size; j++)
        {
            if (add(1, i, i + j))
                res++;
        }
    }
    cout << res << endl;
    return 0;
}