POJ3321 Apple Tree

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;
const int maxn = 100002;
//3321	Accepted	4468K	438MS	C++	1790B	2013-08-12 23:20:18
struct node1 {
    int next, tail;
}edge[maxn];

struct node2 {
    int r, l;
}apple[maxn];
int s[maxn], cnt, c[maxn], a[maxn];

void dfs(int u) {
    int i;
    apple[u].l = cnt;
    for(i = s[u]; i != -1; i = edge[i].next) {
        dfs(edge[i].tail);
    }
    apple[u].r = ++cnt;
}

inline int lowbit(int x) {
    return x&(-x);
}

void change(int x) {
    int i;
    if(a[x]) {
        for(i = x; i <= cnt; i += lowbit(i)) {
             c[i]++;
        }
    }
    else {
        for(i = x; i <= cnt; i += lowbit(i)) {
            c[i]--;
        }
    }
}

int sum(int x) {
    int i, res = 0;
    for(i = x; i > 0; i -= lowbit(i))
        res += c[i];
    return res;
}

int main() {
    int i, n, m, t1, t2, t;
    char str[3];
    scanf("%d", &n);
    memset(s, -1, sizeof(s[0])*(n+1));
    memset(c, 0, sizeof(c[0])*(n+1));
    memset(apple, 0, sizeof(apple[0])*(n+1));
    for(i = 0; i < n-1; i++) {
        scanf("%d%d", &t1, &t2);
        edge[i].tail = t2;
        edge[i].next = s[t1];
        s[t1] = i;
    }
    cnt = 1;
    dfs(1);
    scanf("%d", &m);
    //a[1] = 1; change(a[1]); c[1] = 0;
    for(i = 2; i <= n+1; i++) {
        a[i] = 1;
        change(i);
    }
    while(m--) {
        scanf("%s", str);
        scanf("%d", &t);
        getchar();
        if(str[0]=='Q') {
            int res = sum(apple[t].r) - sum(apple[t].l);
            printf("%d\n", res);
        }
        else {
            a[apple[t].r] = (a[apple[t].r] + 1)%2;
            change(apple[t].r);
        }
    }
    return 0;
}

/**
7
1 2
1 4
2 3
2 7
4 5
4 6
4
Q 1
Q 3
C 3
Q 1
**/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值