Bzoj3631【JLOI2014】松鼠的新家

Solution

先考虑在序列上的做法。注意到是先处理完所有修改后才做询问,那么每次区间加上一个数时就只须在左右端点分别打上一个+和-的标记,最后询问时将整个序列从左到右扫一遍即可。
树上同理。

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
using namespace std;
const int maxn = 300005;
struct edge{
    int x,y,next;
    edge(){}
    edge(int _x,int _y,int _nt): x(_x) , y(_y) , next(_nt){}
}e [maxn << 1];
int head[maxn] , tot = 0;
inline void addedge(int x,int y){
    e[++tot] = edge( x , y , head[x] ); head[x] = tot;
    e[++tot] = edge( y , x , head[y] ); head[y] = tot;
}
int top[maxn],p[maxn],siz[maxn],son[maxn],fa[maxn],dep[maxn];
int n,m,T;
int tag[maxn][2],a[maxn],c[maxn],s[maxn];
void DFS1(int x){
    siz[x] = 1; son[x] = 0;
    for(int y,i = head[x] ; i ; i = e[i].next ){
        y = e[i].y;
        if( dep[y] ) continue;
        dep[y] = dep[x] + 1;
        fa[y] = x;
        DFS1( y );
        siz[x] += siz[y];
        if( siz[y] > siz[son[x]] ) son[x] = y;
    }
}
void DFS2(int x,int chain){
    p[x] = ++T; top[x] = chain;
    if( son[x] ) DFS2( son[x] , chain );
    for(int y,i = head[x] ; i ; i = e[i].next ){
        y = e[i].y;
        if( p[y] || y == son[x] ) continue;
        DFS2( y , y );
    }
}
int sum = 0;
void DFS3(int x){
    sum += tag[x][0];
    s[x] = sum;
    sum -= tag[x][1];
    if( son[x] ) DFS3(son[x]);
}
int main(){
    scanf("%d",&n);
    for(int i = 1 ; i <= n ; i++)scanf("%d",&a[i]);
    for(int i = 2 ; i <= n ; i++) c[a[i]]++;
    for(int x,y,i = 1 ; i <= n-1 ; i++){
        scanf("%d%d",&x,&y);
        addedge(x,y);
    }
    dep[1]=1;
    DFS1( 1 );
    DFS2( 1 , 1 );
    for(int x,y,i = 1 ; i <= n-1 ;i++){
        x = a[i]; y = a[i+1];

        while( top[x] != top[y] ){
            if( dep[top[x]] < dep[top[y]] )swap( x, y );
                tag[top[x]][0]++;
            tag[x][1]++;
            x = fa[top[x]];
        }
        if( dep[x] > dep[y] ) swap( x , y );
        tag[x][0]++;
        tag[y][1]++;
    }
    for(int i = 1 ; i <= n ; i++)
        if( i == top[i] ) DFS3(i);
    for(int i = 1 ; i <= n ; i++)
        printf("%d\n",s[i]-c[i]);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值