题目链接
http://poj.org/problem?id=3321
题意
一颗苹果树,以1为根,含有n个结点,每个节点上都会张出苹果。现在给出m个询问
Q v代表修改v结点的状态,即有苹果就摘掉,没有苹果就让其长出苹果。
C v代表查询以v为根的子树中,包含的苹果个数。
思路
用dfs序的连续区间可以代表一个子树,线段树叶子节点存储对应dfs序的结点苹果的有无。然后用线段树更新查询.
用vector存图居然超时了。。
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<string>
#include<queue>
#include<stack>
#include<set>
#include<map>
#define ll long long
using namespace std;
const int INF = ( 2e9 ) + 2;
const ll maxn = 4e5+100;
vector<int> g[maxn];
int col[maxn];
int p1[maxn],p2[maxn],con[maxn];
int index;
struct node
{
int l,r,f;
}t[maxn*4];
struct edge
{
int v,next;
}e[maxn*2];
int head[maxn];
int tot;
void add(int u,int v)
{
e[tot].v=v;
e[tot].next=head[u];
head[u]=tot++;
}
void build(int root,int l,int r)
{
t[root].l=l;
t[root].r=r;
t[root].f=0;
if(l==r)
{
t[root].f=1;
return;
}
int mid=(l+r)>>1;
build(root*2,l,mid);
build(root*2+1,mid+1,r);
t[root].f=t[root*2].f + t[root*2+1].f;
}
void update(int root,int p)
{
int l=t[root].l,r=t[root].r;
if(l==r)
{
t[root].f = !t[root].f;
return;
}
int mid = (l+r)>>1;
if(p<=mid)
update(root*2,p);
else if(p>mid)
update(root*2+1,p);
t[root].f = t[root*2].f + t[root*2+1].f;
}
int query(int root,int ql,int qr)
{
int l=t[root].l,r=t[root].r;
if(ql>r||qr<l)return 0;
if(ql<=l&&qr>=r)
{
return t[root].f;
}
int mid = (l+r)>>1;
if(qr<=mid)
return query(root*2,ql,qr);
else if(ql>mid)
return query(root*2+1,ql,qr);
else
{
return query(root*2,ql,qr) + query(root*2+1,ql,qr);
}
}
void dfs(int u,int fa)
{
p1[u]=++index;
con[u]=index;
for(int i=head[u];i!=-1;i=e[i].next)
{
int v=e[i].v;
if(v==fa)continue;
dfs(v,u);
}
p2[u]=index;
}
int main()
{
int n,u,v;
while(~scanf("%d",&n))
{
memset(head,-1,sizeof(head));
tot=0;
for(int i=1;i<=n-1;i++)
{
scanf("%d%d",&u,&v);
add(u,v);
add(v,u);
}
dfs(1,-1);
build(1,1,n);
char op[5];
int m;
scanf("%d",&m);
for(int i=1;i<=m;i++)
{
scanf("%s%d",op,&u);
if(op[0]=='Q')
{
printf("%d\n",query(1,p1[u],p2[u]));
}
else
{
update(1,con[u]);
}
}
}
}