子段求和(线段树)

题意:给出一个长度为N的数组,进行Q次查询,查询从第i个元素开始长度为l的子段所有元素之和。

链接:
https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1081

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn = 50005;
long long sub[maxn<<2];  //注意线段树要开4#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1

void pushup(int rt)
{
    sub[rt]= sub[rt<<1]+sub[rt<<1|1];
}

void build(int l,int r, int rt)
{
    if(l == r)
    {
        scanf("%I64d",&sub[rt]);return ;
    }
    int m = (l+r)>>1;
    build(lson);
    build(rson);
    pushup(rt);
}

long long query(int L,int R,int l,int r,int rt)
{
    if(L<=l && r<=R)
        return sub[rt];
    int m = (l+r)>>1;
    long long ret = 0;
    if(L<=m)
        ret+=query(L,R,lson);
    if(R>m)
        ret+=query(L,R,rson);
    return ret;
}

int main()
{
    int n;
    while(cin >> n)
    {
        build(1,n,1);
        int q;
        cin >> q;
        int l,r,a,b;
        for(int i=0; i<q; i++)
        {
            scanf("%d%d",&a,&b);
            l = a; r = a+b-1;
            printf("%I64d\n",query(l,r,1,n,1)); //注意输出范围
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值