POJ 3321 Apple Tree

树状数组按dfs序计算。邻接表存树。先深搜一遍整个树,low数组记录开始时间,high记录结束时间。low与high之间为子节点。计算出中间子节点的变化加上原有的数目即可。重点在于dfs来将树形结构映射到树状数组上。

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
#define N 2000005
int n;
int c[N];
int r[N];
int tm, ptr;
struct Node {
    int v;
    Node *next;
}*head[N], tree[N];
int low[N], high[N];
int lowbit(int x) {
    return x& (-x);
}
void init() {
    tm = 1;
    ptr = 1;
    memset(low, 0, sizeof(low));
    memset(high, 0, sizeof(high));
    memset(head, NULL, sizeof(head));
}

void add(int x, int y) {
    tree[ptr].v = y;
    tree[ptr].next = head[x];
    head[x] = &tree[ptr++];
    tree[ptr].v = x;
    tree[ptr].next = head[y];
    head[y] = &tree[ptr++];
}

void dfs(int rt, int par) {
    Node *p = head[rt];
    tm++;
    low[rt] = tm;
    while(p != NULL) {
        if(p->v != par) {
            dfs(p->v, rt);
        }
        p = p->next;
    }
    high[rt] = tm;
}
int Sum(int i) {
    int ans = 0;
    while(i > 0)
    {
        ans += c[i];
        i -= lowbit(i);
    }
    return ans;
}
void inst(int i, int del) {
    while(i <= tm) {
        c[i] += del;
        i += lowbit(i);
    }
}
int main() {
    while(scanf("%d", &n)!=EOF) {
        int x, y;
        init();
        for(int i = 1; i < n; i++) {
            scanf("%d%d" , &x, &y);
            add(x, y);
        }
        dfs(1, 1);
        for(int i = 1; i <= tm; i++)
            r[i] = 1;
        int t;
        scanf("%d", &t);
        char ch[3];
        while(t--) {
            scanf("%s%d", ch, &x);
            if(ch[0] == 'C') {
                if(r[x])inst(low[x], -1);
                else inst(low[x], 1);
                r[x] = 1 - r[x];
            }
            else {
                int ans;
                ans = high[x] - low[x] + 1 + Sum(high[x]) - Sum(low[x]-1);
                printf("%d\n", ans);
            }
        }
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值