牛牛的最美味和最不美味的零食(線段樹)

在這裏插入圖片描述

思路:我們再線段樹裏面去維護一個區間有多少個數和他的最大值最小值,區間查詢的時候我們去看有多少個數,如果他的數大於R,那麼我們去他的左子樹,如果他的數小於L我們去他的右子樹,都不是的話我們去看他左子樹此時要查詢的數變成L——左子樹數的個數,和右子樹此時要查的數是,1——R-左子樹維護區間數的個數,記住我們查的是數的個數不是區間

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <set>
#include<iostream>
#include<vector>
//#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define SIS std::ios::sync_with_stdio(false)
#define space putchar(' ')
#define enter putchar('\n')
#define lson root<<1
#define rson root<<1|1
typedef pair<int,int> PII;
const int mod=1e4+7;
const int N=2e6+10;
const int inf=0x7f7f7f7f;


ll gcd(ll a,ll b)
{
    return b==0?a:gcd(b,a%b);
}

ll lcm(ll a,ll b)
{
    return a*(b/gcd(a,b));
}

template <class T>
void read(T &x)
{
    char c;
    bool op = 0;
    while(c = getchar(), c < '0' || c > '9')
        if(c == '-')
            op = 1;
    x = c - '0';
    while(c = getchar(), c >= '0' && c <= '9')
        x = x * 10 + c - '0';
    if(op)
        x = -x;
}
template <class T>
void write(T x)
{
    if(x < 0)
        x = -x, putchar('-');
    if(x >= 10)
        write(x / 10);
    putchar('0' + x % 10);
}
struct node
{
    int l,r,sum,big,small;
}tr[N<<2];
int a[N];
void push_up(int root)
{
    tr[root].sum=tr[lson].sum+tr[rson].sum;
    tr[root].big=max(tr[lson].big,tr[rson].big);
    tr[root].small=min(tr[lson].small,tr[rson].small);
}

void build(int root,int l,int r)
{
    tr[root].l=l,tr[root].r=r;
    if(l==r)
    {
        tr[root].sum=1;
        tr[root].big=tr[root].small=a[l];
        return ;
    }
    int mid=l+r>>1;
    build(lson,l,mid);
    build(rson,mid+1,r);
    push_up(root);
}
void del(int root,int x)
{
    if(tr[root].l==tr[root].r)
    {
        tr[root].sum=0;
        tr[root].big=-inf;
        tr[root].small=inf;
        return ;
    }
    int mid=tr[root].l+tr[root].r>>1;
    if(x<=tr[lson].sum) del(lson,x);
    else del(rson,x-tr[lson].sum);
    push_up(root);
}

node query(int root,int x,int y)
{
    if(x<=1&&y>=tr[root].sum)
    {
        return tr[root];
    }
    int mid=tr[root].l+tr[root].r>>1;
    if(y<=tr[lson].sum) return query(lson,x,y);
    else if(x>tr[lson].sum) return query(rson,x-tr[lson].sum,y-tr[lson].sum);
    else
    {
        node t1=query(lson,x,tr[lson].sum);
        node t2=query(rson,1,y-tr[lson].sum);
        node ans;
        ans.big=max(t1.big,t2.big);
        ans.small=min(t1.small,t2.small);
        //cout<<ans.big<<' '<<ans.small<<endl;
        return ans;
    }

}

int main()
{
    SIS;
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n;i++)
     cin>>a[i];
    build(1,1,n);
    while(m--)
    {
        int op,x,y;
        cin>>op;
        if(op==1)
        {
            cin>>x;
            del(1,x);
        }
        else
        {
            cin>>x>>y;
            node ans=query(1,x,y);
            cout<<ans.small<<' '<<ans.big<<endl;
        }
    }






    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章