POJ-3237(树链剖分+线段树)

题解:更改把路径上的边值都变为负值一看就是树链剖分,接着我们用点连着深度比较深的边的值设为边的值那么我们查询的时候当到达最近公共祖先的时候最近公共祖先的点的编号注意加一,接着就是线段树的更新用1和0表示区间变为负数或者不变为负数即可,最后要记录一下边队应的编号即可

#include
#include
#include
#include
using namespace std;
#define ls 2*rt
#define rs 2*rt+1
#define mid (L+R)/2
#define lson ls,L,mid
#define rson rs,mid+1,R
#define root 1,1,n
typedef long long int ll;
const int mx = 1e4+5;
struct node{
    int v;
    int pos;
    int next;
}e[mx<<2];
int head[mx];
int top[mx];
int val[mx];
int siz[mx];
int son[mx];
int pos[mx];
int w[mx];
int fa[mx];
int id[mx];
int dep[mx];
int lazy[mx<<2];
int Max[mx<<2];
int Min[mx<<2];
int n,m;
int tot;
int dfn;
void init(){
    tot = 0;
    dfn = 0;
    memset(head,0,sizeof(head));
}
void push_down(int rt){
    if(lazy[rt]){
        lazy[ls] = !lazy[ls];
        lazy[rs] = !lazy[rs];
        Max[ls] *= -1;
        Max[rs] *= -1;
        Min[ls] *= -1;
        Min[rs] *= -1;
        swap(Max[ls],Min[ls]);
        swap(Max[rs],Min[rs]);
        lazy[rt] = 0;
    }
}
void push_up(int rt){
    Max[rt] = max(Max[rs],Max[ls]);
    Min[rt] = min(Min[rs],Min[ls]);
}
void built(int rt,int L,int R){
    lazy[rt] = 0;
    if(L==R){
        Max[rt] = Min[rt] = w[L];
        return;
    }
    built(lson);
    built(rson);
    push_up(rt);
}
void update(int rt,int L,int R,int p,int v){
    if(L==R){
        Max[rt] = Min[rt] = v;
        return;
    }
    push_down(rt);
    if(p>mid)   update(rson,p,v);
    else update(lson,p,v);
    push_up(rt);
}

void add(int u,int v,int pos){
    tot++;
    e[tot].pos = pos;
    e[tot].v = v;
    e[tot].next = head[u];
    head[u] = tot;
}
ll query(int rt,int L,int R,int l,int r){
    if(L>=l&&R<=r)
        return Max[rt];
    push_down(rt);
    if(l>mid)   return query(rson,l,r);
    else if(r<=mid) return query(lson,l,r);
    else
        return max(query(lson,l,mid),query(rson,mid+1,r));
}
ll solve(int a,int b){
    ll sum = -0x3f3f3f3f;
    while(top[a]!=top[b]){
        if(dep[top[a]]id[b])swap(a,b);
    if(id[a]!=id[b])
    sum = max(sum,query(1,1,n,id[a]+1,id[b]));
    return sum;
}
void Nag(int rt,int L,int R,int l,int r){
    if(L>=l&&R<=r){
        Max[rt] *= -1;
        Min[rt] *= -1;
        swap(Max[rt],Min[rt]);
        lazy[rt] = !lazy[rt];
        return;
    }
    push_down(rt);
    if(l>mid)   Nag(rson,l,r);
    else if(r<=mid) Nag(lson,l,r);
    else Nag(lson,l,mid),Nag(rson,mid+1,r);
    push_up(rt);
}
void nag(int a,int b){
    while(top[a]!=top[b]){
        if(dep[top[a]]id[b])swap(a,b);
    if(id[a]!=id[b])
    Nag(root,id[a]+1,id[b]);
}
void dfs(int u,int pre,int d){
    son[u] = 0;
    siz[u] = 1;
    fa[u] = pre;
    dep[u] = d;
    for(int i = head[u]; i; i = e[i].next){
        int v = e[i].v;
        if(v!=pre){
            pos[e[i].pos] = v;
            w[v] = val[e[i].pos];
            dfs(v,u,d+1);
            siz[u] += siz[v];
            if(siz[son[u]]



你可能感兴趣的:(树链剖分,线段树)