POJ 3321 Apple Tree

    树状数组。

 

代码:

#include <iostream>

#include <cstdio>

#include <cstring>

#include <cmath>

#include <algorithm>

#include <vector>

using namespace std;

#define N 100010



int vis[N],have[N];

int low[N],high[N];

int c[N];

vector< vector<int> > edge(N);

int n,now;



int lowbit(int x)

{

    return x&(-x);

}



void init()

{

    int i;

    for(i=1;i<N;i++)

    {

        have[i] = 1;

        c[i] = lowbit(i);

    }

    memset(vis,0,sizeof(vis));

    now = 1;

    return;

}



void modify(int x)

{

    int val;

    if(have[x])

    {

        have[x] = 0;

        val = -1;

    }

    else

    {

        have[x] = 1;

        val = 1;

    }

    while(x<=n)

    {

        c[x] += val;

        x += lowbit(x);

    }

}



void dfs(int v)

{

    vis[v] = 1;

    low[v] = now;

    for(int i=0;i<edge[v].size();i++)

    {

        if(!vis[edge[v][i]])

        {

            dfs(edge[v][i]);

        }

    }

    high[v] = now;

    now++;

}



int sum(int x)

{

    int res = 0;

    while(x>0)

    {

        res += c[x];

        x -= lowbit(x);

    }

    return res;

}



int main()

{

    int i,a,b,q,v;

    char ss[5];

    init();

    scanf("%d",&n);

    for(i=1;i<=n-1;i++)

    {

        scanf("%d%d",&a,&b);

        edge[a].push_back(b);

        edge[b].push_back(a);

    }

    dfs(1);

    scanf("%d",&q);

    while(q--)

    {

        scanf("%s",ss);

        if(ss[0] == 'Q')

        {

            scanf("%d",&v);

            printf("%d\n",sum(high[v])-sum(low[v]-1));

        }

        else

        {

            scanf("%d",&v);

            modify(high[v]);

        }

    }

    return 0;

}
View Code

 

你可能感兴趣的:(apple)