codeforces 877E - Danil and a Part-time Job

dfs序 + 线段树 (区间修改时dfs序 不要打出去的标记,而是记录子树的size)

#include <bits/stdc++.h>
#define lc l,mid,x<<1
#define rc mid+1,r,x<<1|1
#define ls x<<1
#define rs x<<1|1
using namespace std;
const int maxn = 200005;
const int maxm = 200005;
int tree[4*maxn][2],laz[4*maxn];
int ver[maxm],ne[maxm],he[maxn],tot,dfn[maxn],sz[maxn],a[maxn];
void add( int x,int y ){
    ver[++tot] = y;
    ne[tot] = he[x];
    he[x] = tot;
}
int tim,h[maxn];
void dfs( int x ){
    dfn[x] = ++tim;sz[x] = 1;h[tim] = x;
    for( int cure = he[x];cure;cure = ne[cure] ){
        int y= ver[cure];
        dfs(y);
        sz[x] += sz[y];
    }
}
void push_up( int x ){
    tree[x][0] = tree[ls][0] + tree[rs][0];
    tree[x][1] = tree[ls][1] + tree[rs][1];
}
void build( int l,int r,int x ){
    if( l == r ){
        tree[x][ a[ h[l] ] ] = 1;
        return;
    }
    int mid = l+r>>1;
    build(lc);
    build(rc);
    push_up(x);
}
void push_down( int x ){
    if( laz[x] ){
        laz[ls] ^= 1;
        laz[rs] ^= 1;
        swap( tree[ls][0],tree[ls][1] );
        swap( tree[rs][0],tree[rs][1] );
    }
    laz[x] = 0;
}
void update( int left,int right,int l,int r,int x ){
    if( left <= l && right >= r ){
        swap( tree[x][0],tree[x][1] );
        laz[x] ^= 1;
        return;
    }
    push_down(x);
    int mid = l+r>>1;
    if( left <= mid )update(left,right,lc);
    if( right > mid )update(left,right,rc );
    push_up(x);
}
int query( int left,int right,int l,int r,int x ){
    if( left <= l && right >= r ){
        return tree[x][1];
    }
    push_down(x);
    int mid = l+r>>1;
    int res = 0;
    if( left <= mid )res += query(left,right,lc);
    if( right > mid )res += query(left,right,rc);
    push_up(x);
    return res;
}
int main(){
    int n,x;scanf("%d",&n);
    for( int i = 2;i <= n;i++ ){
        scanf("%d",&x);add(x,i);
    }
    for( int i = 1;i <= n;i++ ){
        scanf("%d",&a[i]);
    }
    dfs(1);
    build( 1,n,1 );
    int q;scanf("%d",&q);
    char op[10];
    for( int i = 1;i <= q;i++ ){
        scanf("%s",op);
        if( op[0]=='g' ){
            scanf("%d",&x);
            int l = dfn[x],r = dfn[x] + sz[x]-1;
            int res =query( l,r,1,n,1  );
            printf("%d\n",res);
        }else{
            scanf("%d",&x);
            int l = dfn[x],r = dfn[x] + sz[x]-1;
            update( l,r,1,n,1 );
        }
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值