ZKW线段树

题目:敌兵布阵

 

题意:给一个数组,然后有一系列操作:(1)把某一个值加上一个数,(2)把某一个值减去一个数,(3)求一段区间的和。

#include <iostream>
#include <string.h>
#include <stdio.h>

using namespace std;
const int N=100005;

int M;
int T[4*N];

void PushUP(int rt)
{
    T[rt]=T[rt<<1]+T[rt<<1|1];
}

void Build(int n)
{
    for(M=1; M<=n+1; M<<=1);
    for(int i=M+1; i<=M+n; i++)
        scanf("%d",&T[i]);
    for(int i=M-1; i>0; i--)
        PushUP(i);
}

void Add(int n,int v)
{
    for(T[n+=M]+=v,n>>=1; n; n>>=1) 
        PushUP(n);
}

int Query(int s,int t)
{
    int ans=0;
    for(s=s+M-1,t=t+M+1; s^t^1; s>>=1,t>>=1)
    {
        if(~s&1) ans+=T[s^1];
        if(t&1)  ans+=T[t^1];
    }
    return ans;
}

int main()
{
    char str[15];
    int n,t,a,b,k=1;
    scanf("%d",&t);
    while(t--)
    {
        printf("Case %d:\n",k++);
        memset(T,0,sizeof(T));
        scanf("%d",&n);
        Build(n);
        while(1)
        {
            scanf("%s",str);
            if(str[0]=='E') break;
            scanf("%d%d",&a,&b);
            if(str[0]=='A')      Add(a,b);
            else if(str[0]=='S') Add(a,-b);
            else                 printf("%d\n",Query(a,b));
        }
    }
    return 0;
}


题目:I Hate It

 

RMQ问题

 

#include <iostream>
#include <string.h>
#include <stdio.h>

using namespace std;
const int N=200005;

int M;
int T[4*N];

void PushUP(int rt)
{
    T[rt]=max(T[rt<<1],T[rt<<1|1]);
}

void Build(int n)
{
    for(M=1; M<=n+1; M<<=1);
    for(int i=M+1; i<=M+n; i++)
        scanf("%d",&T[i]);
    for(int i=M-1; i>0; i--)
        PushUP(i);
}

void Update(int n,int v)
{
    for(T[n+=M]=v,n>>=1; n; n>>=1)
        PushUP(n);
}

int Query(int s,int t)
{
    int ans=-1;
    for(s=s+M-1,t=t+M+1; s^t^1; s>>=1,t>>=1)
    {
        if(~s&1) ans=max(ans,T[s^1]);
        if(t&1)  ans=max(ans,T[t^1]);
    }
    return ans;
}

int main()
{
    char str[15];
    int n,m,a,b;
    while(~scanf("%d%d",&n,&m))
    {
        memset(T,0,sizeof(T));
        Build(n);
        while(m--)
        {
            scanf("%s%d%d",str,&a,&b);
            if(str[0]=='U') Update(a,b);
            else            printf("%d\n",Query(a,b));
        }
    }
    return 0;
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值