POJ3321 Apple Tree (Fenwick tree)

The most critical is the dfs order this title, before there was a demand with which the number of nodes like a parent node, we dfs tree this record nodes and end nodes he began, so long as doing between two points dfs on the line

First, it does not undermine the tree structure, and secondly, he also said that the relative relationship between each node, which is a very common technique of Fenwick tree

Benpian with c ++ code needs to pay, if you want to use g ++, need to change the vector format a bit, I do not know the specific principles, anyway, every time the question of pay, the best c ++ cross, especially poj the evaluation machine.

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<vector>
#include<string>
#include<cstring>
#include<map>
#include<set>
using namespace std;
typedef long long ll;
const int N=1e5+10;
const int inf=0x3f3f3f3f;
int st[N];
int ed[N];
int tr[N];
int vis[N];
vector<int> ma[N];
int n;
int idx;
void dfs(int u){
    idx++;
    st[u]=idx;
    for(int i=0;i<ma[u].size();i++){
        dfs(ma[u][i]);
    }
    ed[u]=idx;
}
int lowbit(int x){
    return x&-x;
}
void add(int x,int c){
    int i;
    for(i=x;i<=n;i+=lowbit(i)){
        tr[i]+=c;
    }
}
int sum(int x){
    int i;
    int res=0;
    for(i=x;i;i-=lowbit(i)){
        res+=tr[i];
    }
    return res;
}
int main(){
    int i;
    cin>>n;
    for(i=1;i<n;i++){
        int u,v;
        scanf("%d%d",&u,&v);
        ma[u].push_back(v);
    }
    dfs(1);
    for(i=1;i<=n;i++){
        add(st[i],1);
        vis[i]=1;
    }
    int m;
    cin>>m;
    while(m--){
        char s[N];
        scanf("%s",s);
        if(*s=='C'){
            int x;
            scanf("%d",&x);
            if(vis[x]){
                add(st[x],-1);
                vis[x]=0;
            }
            else{
                add(st[x],1);
                vis[x]=1;
            }
        }
        else{
            int x;
            scanf("%d",&x);
            printf("%d\n",sum(ed[x])-sum(st[x]-1));
        }
    }
}
View Code

 

Guess you like

Origin www.cnblogs.com/ctyakwf/p/12324130.html