最大数(线段树)

最大数

 

题目思路:

  入门题,每加入一个数就在树中单点修改一次,注意加入时要加上上一次查询的答案。

#include<bits/stdc++.h>
#define ll long long
using namespace std;
void push_down(int p,int v);
typedef struct segment
{
    int left,right;
    int lazy;
    int max;
    segment()
    {
        lazy = -1;
    }
}T;
T tree[4*200010];
ll n,m,a[200010],p;
void build(int p,int l,int r)
{
    tree[p].left = l,tree[p].right = r;
    if(l==r)
    {
        tree[p].max = a[l];        
        return ;
    }
    int mid = (l+r)/2;
    build(p*2,l,mid);
    build(p*2+1,mid+1,r);
    tree[p].max = max(tree[2*p].max,tree[2*p+1].max);
}
int query(int p,int l,int r)
{//cout<<p<<" "<<l<<" "<<r<<" "<<tree[p].left<<" "<<tree[p].right<<endl;
    int inf = -100000007;
    if(l<=tree[p].left&&r>=tree[p].right)    
        return tree[p].max;
    push_down(p,tree[p].lazy);
    int mid = (tree[p].left+tree[p].right)/2;
    if(l<=mid)
        inf = max(inf,query(p*2,l,r));
    if(mid<r)
        inf = max(inf,query(p*2+1,l,r));
    return inf;
        
}
void change(int p,int x,int v)//单点修改
{
    if(tree[p].left==tree[p].right)
    {
        tree[p].max = v;
        return ;
    }
    int mid = (tree[p].left+tree[p].right)/2;
    if(x<=mid)
        change(p*2,x,v);
    else
        change(p*2+1,x,v);
    tree[p].max = max(tree[p*2].max,tree[p*2+1].max);
}
void push_down(int p,int v)
{
    if(tree[p].lazy==-1)
        return ;
    tree[p*2].max = v;
    tree[p*2+1].max = v;
    tree[p*2].lazy = v;
    tree[p*2+1].lazy = v;

}
void change2(int p,int l,int r,int v)//区间修改
{
    if(l<=tree[p].left&&r>=tree[p].right)    
    {
        tree[p].max = v;
        if(tree[p].left!=tree[p].right)
            tree[p].lazy = v;
        return ;
    }
    push_down(p,tree[p].lazy);
    int mid = (tree[p].left+tree[p].right)/2;
    if(l<=mid)
        change2(p*2,l,r,v);
    if(mid<r)
        change2(p*2+1,l,r,v);
    tree[p].max = max(tree[p*2].max,tree[p*2+1].max);
}
int main()
{
    char c;
    ll c1,c2,c3,last = 0,sum = 0;
    cin>>m>>p;
    build(1,1,200001);
    for(int i = 0;i<m;i++)
    {
        cin>>c>>c1;
        if(c=='A')
        {
            sum++;
            change(1,sum,(c1+last)%p);
        }
        else
        {
            last = query(1,sum-c1+1,sum);
            cout<<last<<endl;
        }
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/loganacmer/p/11296898.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值