【POJ3321】Apple Tree

41 篇文章 0 订阅
26 篇文章 0 订阅

题目大意:

思路:

算法分析:对于棵树进行 d f s dfs dfs遍历,并记录每一个点的 d f s dfs dfs序号 s t [ i ] st[i] st[i],在一个节点的所有儿子都被遍历过后,记录当前 e n [ i ] en[i] en[i]为当前最大 d f s dfs dfs序号的节点的 d f s dfs dfs序号。

于是,我们把问题转换为将某一点的权值改变,询问区间 [ s t [ x ] , e n [ x ] ] [st[x], en[x]] [st[x],en[x]]的和
树状数组可以轻松实现这些操作。

代码:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<queue>
#include<stack>
#include<map>
#include<cstring>
using namespace std;

long long n, m, tot, head[100100], d[100100], st[100100], en[100100];
long long c[100100], a[100100];
struct node
{
	long long to, next;
}b[100100];

void VL_ljb(long long x, long long y)
{
	b[++tot].to=y;
	b[tot].next=head[x];
	head[x]=tot;
} 

void VL_dfs(long long x)
{
	tot++;
	st[x]=tot;
	for(long long i=head[x]; i; i=b[i].next)
	{
	    VL_dfs(b[i].to);
	}
	en[x]=tot;
}

long long VL_lowbit(long long x){return x & -x;}
void VL_change(long long x, long long y)
{
	for(; x<=n; x+=VL_lowbit(x))
		c[x]+=y;
}
long long VL_find(long long x)
{
	long long ans=0;
	for(; x; x-=VL_lowbit(x))
		ans+=c[x];
	return ans;
}
int main(){
	scanf("%lld", &n);
	for(long long i=1; i<n; i++)
	{
		long long x, y;
		scanf("%lld%lld", &x, &y);
		VL_ljb(x, y);
	}
	tot=0;
	VL_dfs(1);
	for(long long i=1; i<=n; i++)
	{
		a[i]=1;
		VL_change(st[i], 1);
	}
	scanf("%lld", &m);
	for(long long i=1; i<=m; i++)
	{
		char c;
		long long x;
		cin>>c;
		if(c=='Q')
		{
			cin>>x;	
			printf("%lld\n", VL_find(en[x])-VL_find(st[x]-1));
		}
		else
		{
			cin>>x;
			if(a[x]==0)
			{
				VL_change(st[x],1);
				a[x]=1;
			}
			else
			{
				VL_change(st[x], -1);
				a[x]=0;
			}
		}
	} 
	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值