[BZOJ3631][JLOI2014]松鼠的新家(链剖)

题目描述

传送门

题解

小傻逼手残
随便写链剖。

代码

#include
#include
#include
using namespace std;

const int max_n=3e5+5;
const int max_e=max_n*2;
const int max_tree=max_n*5;

int n,x,y,N;
int a[max_n],ans[max_n];
int tot,point[max_n],next[max_e],v[max_e];
int father[max_n],son[max_n],size[max_n],h[max_n];
int num[max_n],top[max_n];
int sum[max_tree],delta[max_tree];
inline int in(){
    int x=0; char ch=getchar();
    while (ch<'0'||ch>'9') ch=getchar();
    while (ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
    return x;
}

inline void addedge(int x,int y){
    ++tot; next[tot]=point[x]; point[x]=tot; v[tot]=y;
    ++tot; next[tot]=point[y]; point[y]=tot; v[tot]=x;
}
inline void dfs_1(int x,int fa,int dep){
    size[x]=1; h[x]=dep; father[x]=fa;
    int maxson=0;
    for (int i=point[x];i;i=next[i])
      if (v[i]!=fa){
        dfs_1(v[i],x,dep+1);
        size[x]+=size[v[i]];
        if (maxsonint x,int fa){
    if (son[fa]!=x) top[x]=x;
    else top[x]=top[fa];
    num[x]=++N;
    if (son[x]) dfs_2(son[x],x);
    for (int i=point[x];i;i=next[i])
      if (v[i]!=son[x]&&v[i]!=fa)
        dfs_2(v[i],x);
}

inline void update(int now){
    sum[now]=sum[now<<1]+sum[now<<1|1];
}
inline void pushdown(int now,int l,int r,int mid){
    if (delta[now]){
        sum[now<<1]+=delta[now]*(mid-l+1);
        delta[now<<1]+=delta[now];
        sum[now<<1|1]+=delta[now]*(r-mid);
        delta[now<<1|1]+=delta[now];
        delta[now]=0;
    }
} 
inline void interval_change(int now,int l,int r,int lrange,int rrange){
    int mid=(l+r)>>1;
    if (lrange<=l&&r<=rrange){
        sum[now]+=r-l+1;
        ++delta[now];
        return;
    }
    pushdown(now,l,r,mid);
    if (lrange<=mid)
      interval_change(now<<1,l,mid,lrange,rrange);
    if (mid+1<=rrange)
      interval_change(now<<1|1,mid+1,r,lrange,rrange);
    update(now);
}
inline int query(int now,int l,int r,int x){
    int mid=(l+r)>>1;
    if (l==r) return sum[now];
    pushdown(now,l,r,mid);
    if (x<=mid)
      return query(now<<1,l,mid,x);
    else
      return query(now<<1|1,mid+1,r,x);
}

inline void change(int u,int t){
    int f1=top[u],f2=top[t];
    while (f1!=f2){
        if (h[f1]1,1,N,num[f1],num[u]);
        u=father[f1];
        f1=top[u];
    }
    if (num[u]>num[t]) swap(u,t);
    interval_change(1,1,N,num[u],num[t]);
}

int main(){
    n=in();
    for (int i=1;i<=n;++i)
      a[i]=in();
    for (int i=1;iin(); y=in();
        addedge(x,y);
    }
    dfs_1(1,0,1);
    dfs_2(1,0);
    for (int i=1;i1]);
    for (int i=1;i<=n;++i)
      ans[i]=query(1,1,N,num[i]);
    for (int i=2;i<=n;++i)
      --ans[a[i]];
    for (int i=1;i<=n;++i)
      printf("%d\n",ans[i]);
}

你可能感兴趣的:(题解,省选,树链剖分)