很早以前做的了,拿出来记录下。


#include<stdio.h>

#include<string.h>


const int N=100001;
struct Node
{
int v;
struct Node *next;
Node(int n=0,struct Node *P=NULL){v=n;next=P;}
}node[N];


struct Range{
int b,e;
}range[N];






bool visited[N];
int c[N];
int n;


void Dfs(int p,int &id);


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


void Modify(int i,int v);


int Sum(int n);








int main()
{
while(scanf("%d",&n)!=EOF){
int i,j;
int a,b;
int id;
for(i=1;i<=n;i++)
node[i].v=i;
for(i=1;i<n;i++)
{
scanf("%d%d",&a,&b);
node[a].next=new Node(b,node[a].next);
node[b].next=new Node(a,node[b].next);
}
// memset(map,0,sizeof(map));
// memset(c,0,sizeof(c));
memset(visited,false,sizeof(visited));


id=1;
Dfs(1,id);
for(i=1;i<=n;i++)Modify(range[i].b,1);


int Q;
scanf("%d",&Q);
// scanf("%c",&ch);
while(Q--){
//scanf("%c",&ch);
char ch;
scanf("\n%c%d",&ch,&a);
if(ch=='Q'){
printf("%d\n",Sum(range[a].e)-Sum(range[a].b-1));
}
else{
if(visited[range[a].b]){
Modify(range[a].b,-1);
visited[range[a].b]=false;
}
else{
Modify(range[a].b,1);
visited[range[a].b]=true;
}
}
}//while(Q)
}//while(EOF)
return 0;
}




void Dfs(int i,int &id){
visited[i]=true;
range[i].b=id++;
Node *p;
for(p=node[i].next;p!=NULL;p=p->next){
if(visited[p->v]==false)
Dfs(p->v,id);
}
range[i].e=id-1;
}






void Modify(int index,int x){
for(;index<N;c[index]+=x,index+=Lowbit(index));

return ;
}


int Sum(int i){
int s=0;
for(;i>0;s+=c[i],i-=Lowbit(i));
return s;
}
posted on 2012-03-18 23:39  Bester  阅读(126)  评论(0编辑  收藏  举报