WikiOI 1228 苹果树
题目描述Description
在卡卡的房子外面,有一棵苹果树。每年的春天,树上总会结出很多的苹果。卡卡非常喜欢吃苹果,所以他一直都精心的呵护这棵苹果树。我们知道树是有很多分叉点的,苹果会长在枝条的分叉点上面,且不会有两个苹果结在一起。卡卡很想知道一个分叉点所代表的子树上所结的苹果的数目,以便研究苹果树哪些枝条的结果能力比较强。
卡卡所知道的是,每隔一些时间,某些分叉点上会结出一些苹果,但是卡卡所不知道的是,总会有一些调皮的小孩来树上摘走一些苹果。
于是我们定义两种操作:
C x
表示编号为x的分叉点的状态被改变(原来有苹果的话,就被摘掉,原来没有的话,就结出一个苹果)
G x
查询编号为x的分叉点所代表的子树中有多少个苹果
我们假定一开始的时候,树上全都是苹果,也包括作为根结点的分叉1。
输入描述Input Description
第一行一个数N (n<=100000)
接下来n-1行,每行2个数u,v,表示分叉点u和分叉点v是直接相连的。
再接下来一行一个数M,(M<=100000)表示询问数
接下来M行,表示询问,询问的格式如题目所述Q x或者C x
输出描述Output Description
对于每个Q x的询问,请输出相应的结果,每行输出一个
样例输入Sample Input
3
1 2
1 3
3
Q 1
C 2
Q 1
样例输出Sample Output
3
2
和RQ60那一题相似,几下把代码写完,交,WA0!!
查了好久的错,没找到
后来仔细看看题,发现是单点修改!!!
但是我dfs出来的是区间,又怎么单点修改呢?
以样例为例,
L[1]=1 R[1]=3
L[2]=2 R[2]=2
L[3]=3 R[3]=3
我们发现没有 (1,1) 这个区间,为什么没有呢?他其实就是当前单个点的区间,所以单个点的去见就是当前子树 x 的 ( L[x] , L[x] )
问题解决了,AC
测评情况(WikiOI)
C++ AC Code
/*http://blog.csdn.net/jiangzh7 By Jiangzh*/ #include<cstdio> const int N=100000+10; int n; struct link{int y;link *next;}*head[N]; int L[N],R[N],dfstime,hash[N]; int sum[N*4],val[N*4]; void inlink(int x,int y) { link *node=new link; node->y=y; node->next=head[x]; head[x]=node; } void read() { scanf("%d",&n); for(int i=1;i<n;i++) { int x,y; scanf("%d%d",&x,&y); inlink(x,y); inlink(y,x); } } void dfs(int x) { if(hash[x]) return; hash[x]=true; L[x]=++dfstime; for(link *node=head[x];node;node=node->next) dfs(node->y); R[x]=dfstime; } void downloading(int p,int l,int r,int m) { if(val[p]!=-1) { sum[p<<1]=(m-l+1)*val[p]; sum[(p<<1)+1]=(r-m)*val[p]; val[p<<1]=val[(p<<1)+1]=val[p]; val[p]=-1; } } void uploading(int p) { if(val[p<<1]==val[(p<<1)+1] && val[p<<1]!=-1) val[p]=val[p<<1]; sum[p]=sum[p<<1]+sum[(p<<1)+1]; } void modify(int p,int l,int r,int a,int b) { if(a<=l && b>=r) if(val[p]!=-1) { val[p]=!val[p]; sum[p]=(r-l+1)*val[p]; return; } int m=(l+r)>>1; downloading(p,l,r,m); if(a<=m) modify(p<<1,l,m,a,b); if(b>m) modify((p<<1)+1,m+1,r,a,b); uploading(p); } int query(int p,int l,int r,int a,int b) { if(a<=l && b>=r) return sum[p]; int m=(l+r)>>1,x1=0,x2=0; downloading(p,l,r,m); if(a<=m) x1=query(p<<1,l,m,a,b); if(b>m) x2=query((p<<1)+1,m+1,r,a,b); return x1+x2; } void work() { dfs(1); //for(int i=1;i<=n;i++) printf("%d %d\n",L[i],R[i]); modify(1,L[1],R[1],L[1],R[1]); int q;scanf("%d",&q); while(q--) { char op; int x; scanf("\n%c%d",&op,&x); if(op=='Q') printf("%d\n",query(1,L[1],R[1],L[x],R[x])); else modify(1,L[1],R[1],L[x],L[x]); } } int main() { freopen("1228.in","r",stdin); freopen("1228.out","w",stdout); read(); work(); return 0; }