暑期集训4 G题
传送门:http://poj.org/problem?id=3321
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 25847 | Accepted: 7662 |
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 1 to N and the root is always numbered by 1. Apples will grow on the forks and two apple won't grow on the same fork. kaka wants to know how many apples are there in a sub-tree, for his study of the produce ability of the apple tree.
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 ≤ 100,000) , which is the number of the forks in the tree.
The following N - 1 lines each contain two integers u and v, which means fork u and fork v are connected by a branch.
The next line contains an integer M (M ≤ 100,000).
The following M lines each contain a message which is either
"C x" which means the existence of the apple on fork x has been changed. i.e. if there is an apple on the fork, then Kaka pick it; otherwise a new apple has grown on the empty fork.
or
"Q x" which means an inquiry for the number of apples in the sub-tree above the fork x, including the apple (if exists) on the fork x
Note the tree is full of apples at the beginning
Output
Sample Input
3 1 2 1 3 3 Q 1 C 2 Q 1
Sample Output
3 2
题意:给你一颗苹果树,每棵树枝(节点)上都有一个苹果
先给你两个操作
C a表示a点的苹果去掉或者长出来(如果此时没长出来则去掉,如果此时去掉则长出来)
Q a表示询问这棵树上a以及a的所有子节点的苹果个数
题解:求出DFS序然后用树状数组即可
另外用vector可能会超时
...第一次发现DFS序还能这样用啊
下面代码
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
struct node1{
int to,next;
}k[200005];
struct node2{
int q,z;
}l[100005];
int mark[100005];
int head[100005];
int ans[200005];
int tree[200005];
int nn=0,mm=1;
void dadd(int a,int b)
{
k[nn].to=b;
k[nn].next=head[a];
head[a]=nn++;
}
void dfs(int a,int fa)
{
int i;
ans[mm++]=a;
l[a].q=mm-1;
for(i=head[a];1;i=k[i].next)
{
if(i==-1) break;
if(k[i].to==fa) continue;
dfs(k[i].to,a);
}
ans[mm++]=a;
l[a].z=mm-1;
}
void add(int k,int num)
{
while(k<=mm)
{
tree[k]+=num;
k+=k&-k;
}
}
int read(int k)
{
int sum=0;
while(k)
{
sum+=tree[k];
k-=k&-k;
}
return sum;
}
int main()
{
int n,m,i,a,b;
char c;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
mark[i]=-1;
head[i]=-1;
}
for(i=1;i<n;i++)
{
scanf("%d%d",&a,&b);
dadd(a,b);
dadd(b,a);
}
dfs(1,0);
mm--;
for(i=1;i<=mm;i++)
add(i,1);
scanf("%d",&m);
for(i=1;i<=m;i++)
{
scanf("%c",&c);
if(c=='\n') scanf("%c",&c);
if(c=='Q')
{
scanf("%d",&a);
int sum=read(l[a].z)-read(l[a].q-1);
sum=sum/2;
printf("%d\n",sum);
}
if(c=='C')
{
scanf("%d",&a);
add(l[a].q,mark[a]);
add(l[a].z,mark[a]);
mark[a]=-mark[a];
}
}
return 0;
}