HDU3308 线段树区间合并 (求最长连续子串+单点修改)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/computer_user/article/details/79977773

传送门:HDU3308


分析:线段树区间合并被刷烂的水题。。把自己代码风格的线段树放上来。

//HDU3308 线段树区间合并 (求最长连续子串+单点修改)
#include <cstdio>
using namespace std;

const int maxn = 100000;
struct node{
    int l,r;
    int lv,rv,mv;
};
int n,m;
int A[maxn+10];

inline int Min(int x, int y) { return x<y?x:y; }
inline int Max(int x, int y) { return x>y?x:y; }


struct Tree{
    node tr[maxn*4+10];
    #define lch(u) (u<<1)
    #define rch(u) (u<<1|1)
    #define Mid (tr[u].l+tr[u].r)>>1

    inline void push_up(int u, int a, int b) {
        tr[u].lv = tr[lch(u)].lv;
        tr[u].rv = tr[rch(u)].rv;
        tr[u].mv = Max(tr[lch(u)].mv,tr[rch(u)].mv);

        int mid = (a+b)>>1;
        int len = b-a+1;
        if (A[mid] < A[mid+1]) {
            if (tr[u].lv == len-(len>>1)) tr[u].lv += tr[rch(u)].lv;
            if (tr[u].rv == (len>>1)) tr[u].rv += tr[lch(u)].rv;
            tr[u].mv = Max(tr[u].mv,tr[lch(u)].rv+tr[rch(u)].lv);
        }
    }

    void build(int u, int a, int b) {
        tr[u].l = a; tr[u].r = b;
        if (a == b) {
            tr[u].lv = tr[u].rv = tr[u].mv = 1;
            return ;
        }

        int mid = Mid;
        build(lch(u),a,mid);
        build(rch(u),mid+1,b);
        push_up(u,a,b);
    }

    void update(int u, int a, int b, int pos) {
         if (a == b) return ;
         int mid = (a+b)>>1;
         if (pos<=mid) update(lch(u),a,mid,pos);
         else update(rch(u),mid+1,b,pos);
         push_up(u,a,b);
    }

    int query(int u, int a, int b) {
         if ( a <= tr[u].l && tr[u].r <= b) return tr[u].mv;
         int ans = 0;
         int mid = Mid;
         if (a <= mid) ans = Max(ans, query(lch(u),a,b) );
         if (b > mid) ans = Max(ans, query(rch(u),a,b) );
         if (A[mid] < A[mid+1]) ans = Max(ans,Min(mid-a+1,tr[lch(u)].rv) + Min(b-mid,tr[rch(u)].lv) );
         return ans;
    }
}T;

void init(){
    scanf("%d%d",&n,&m);
    for (int i=1; i<=n; i++) scanf("%d",&A[i]);
    T.build(1,1,n);
}

void solve() {
     char s[5];
     int x,y;
     for (int i=1; i<=m; i++) {
        scanf("%s%d%d",s,&x,&y);
        if (s[0] == 'U') {
            A[++x] = y;
            T.update(1,1,n,x);
        }
        else printf("%d\n",T.query(1,++x,++y));
     }
}

int main(){
    int T;
    scanf("%d",&T);
    while (T--) {
        init();
        solve();
    }
    return 0;
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页