POJ3321 Apple Tree(樹狀數組+dfs序)

題意:有n個點,每個點都有蘋果,操作1 查詢 點x的子樹上有又多少個蘋果包括自身,操作2 若點x上有蘋果則摘下,沒有則長出一個

思路:用樹狀數組去維護蘋果樹上的蘋果個數,dfs序建樹獲取樹上子樹和根的區間。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <set>
#include<iostream>
#include<vector>
//#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define SIS std::ios::sync_with_stdio(false)
#define space putchar(' ')
#define enter putchar('\n')
#define lson root<<1
#define rson root<<1|1
typedef pair<int,int> PII;
const int mod=1e4+7;
const int N=2e5+10;
const int inf=0x7f7f7f7f;


ll gcd(ll a,ll b)
{
    return b==0?a:gcd(b,a%b);
}

ll lcm(ll a,ll b)
{
    return a*(b/gcd(a,b));
}

template <class T>
void read(T &x)
{
    char c;
    bool op = 0;
    while(c = getchar(), c < '0' || c > '9')
        if(c == '-')
            op = 1;
    x = c - '0';
    while(c = getchar(), c >= '0' && c <= '9')
        x = x * 10 + c - '0';
    if(op)
        x = -x;
}
template <class T>
void write(T x)
{
    if(x < 0)
        x = -x, putchar('-');
    if(x >= 10)
        write(x / 10);
    putchar('0' + x % 10);
}

vector<vector<int> > vt(N);
int head[N],root,p1[N],p2[N],cnt,ljy[N],tr[N];
int n;
void dfs(int a)
{
    p1[a]=cnt;
    for(int i=0; i<vt[a].size(); i++)
    {
        cnt+=1;
        dfs(vt[a][i]);
    }
    p2[a]=cnt;


}

int lowbit(int x)
{
    return x&(-x);
}
void update(int x,int k)
{
    while(x<=n)
    {
        ljy[x]+=k;

        x+=lowbit(x);
    }
}
int query(int x)
{

    int ans=0;
    while(x>0)
    {
        ans+=ljy[x];
        x-=lowbit(x);
    }
    return ans;
}

int main()
{


    scanf("%d",&n);

    for(int i=0; i<n-1; i++)
    {
        int a,b;

        scanf("%d%d",&a,&b);
        vt[a].push_back(b);
    }
// cout<<11112;
    cnt=1;dfs(1);
    for(int i=1; i<=n; i++)
    {
        tr[i]=1;
        update(i,1);
    }
      int m;
   scanf("%d",&m);
    for(int i=0;i<m;i++)
    {
        // cout<<1111;
        char ch[10];
        int x;
        scanf("%s%d",ch,&x);
        if(ch[0]=='Q')
        {
          
           int ans=query(p2[x])-query(p1[x]-1);
           printf("%d\n",ans);

        }
        else
        {
            if(tr[x])
                update(p1[x],-1);
            else
                update(p1[x],1);
                tr[x]^=1;


        }
    }


    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章