Description
There is an apple tree outside of kaka’s house. Every autumn, a lot of apples will grow in the tree. Kaka likes apple very much, so he has been carefully nurturing the big apple tree.
The tree has
N
forks which are connected by branches. Kaka numbers the forks by
The trouble is that a new apple may grow on an empty fork some time and kaka may pick an apple from the tree for his dessert. Can you help kaka?
Input
The first line contains an integer
N(N≤100000)
, which is the number of the forks in the tree.
The following
N−1
lines each contain two integers
u
and
The next line contains an integer
M(M≤100000)
.
The following
M
lines each contain a message which is either
“
or
“
Note the tree is full of apples at the beginning
Output
For every inquiry, output the correspond answer per line.
Sample Input
3
1 2
1 3
3
Q 1
C 2
Q 1
Sample Output
3
2
Source
POJ Monthly–2007.08.05, Huang, Jinsong
题目大意:
给以一颗根为1,一开始点权全部为1的树,支持两种操作
Cx :如果 x 节点权值为1,就变成0,否则变为1
Qx :查询以 x <script type="math/tex" id="MathJax-Element-411">x</script> 为根的子树的点权和
solution
- 很裸的dfs序+很裸的线段树…感觉没什么好说的啊…
code
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
template<typename T>
void input(T &x) {
x=0; T a=1;
register char c=getchar();
for(;c<'0'||c>'9';c=getchar())
if(c=='-') a=-1;
for(;c>='0'&&c<='9';c=getchar())
x=x*10+c-'0';
x*=a;
return;
}
#define MAXN 100010
struct Edge {
int u,v,next;
Edge(int u=0,int v=0,int next=0):
u(u),v(v),next(next) {}
};
Edge edge[MAXN];
int head[MAXN],cnt;
void addedge(int u,int v) {
edge[++cnt]=Edge(u,v,head[u]);
head[u]=cnt;
return;
}
int dfn[MAXN],last[MAXN],timee;
void dfs(int now) {
dfn[now]=++timee;
for(int i=head[now];i;i=edge[i].next)
if(!dfn[edge[i].v]) dfs(edge[i].v);
last[now]=timee;
return;
}
struct Segment_Tree {
int l,r,sum;
};
Segment_Tree t[MAXN<<2];
void updata(int now) {
t[now].sum=t[now<<1].sum+t[now<<1|1].sum;
return;
}
void build(int now,int l,int r) {
t[now].l=l,t[now].r=r;
if(l==r) {
t[now].sum=1;
return;
}
int mid=l+r>>1;
build(now<<1,l,mid);
build(now<<1|1,mid+1,r);
updata(now);
return;
}
void Modify(int now,int pos) {
int l=t[now].l,r=t[now].r;
if(l==r) {
t[now].sum^=1;
return;
}
int mid=l+r>>1;
if(pos<=mid) Modify(now<<1,pos);
else Modify(now<<1|1,pos);
updata(now);
return;
}
int query(int now,int L,int R) {
int l=t[now].l,r=t[now].r;
if(l==L&&R==r) return t[now].sum;
int mid=l+r>>1;
if(R<=mid) return query(now<<1,L,R);
else if(L>mid) return query(now<<1|1,L,R);
else {
int a=query(now<<1,L,mid),
b=query(now<<1|1,mid+1,R);
return a+b;
}
}
int main() {
int n,m;
input(n);
for(int i=1;i<n;i++) {
int u,v;
input(u),input(v);
addedge(u,v);
}
dfs(1);
build(1,dfn[1],last[1]);
input(m);
char op[5];
int x;
while(m--) {
scanf("%s",op);
input(x);
if(op[0]=='C') Modify(1,dfn[x]);
else printf("%d\n",query(1,dfn[x],last[x]));
}
return 0;
}