HDU3887 Counting Offspring【dfs序】

题意:求一个节点的子树中 比它标号小的节点有几个


思路:从小到大,查询每个点区间已经有几个点被放进去,再放这个点进去


#include<stdio.h>
#include<iostream>
#include<string.h>
#include<string>
#include<stdlib.h>
#include<math.h>
#include<vector>
#include<list>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<algorithm>
#include<numeric>
#include<functional>
using namespace std;
#define lson(x) 2*x
#define rson(x) 2*x+1
typedef long long ll;
typedef pair<int,int> pii;
const int maxn = 5e5+5;
int in[maxn],out[maxn];
int vis[maxn];
struct Edge
{
	int to,next;
}edge[maxn];
int head[maxn],tot,t;

void init()
{
	memset(head,-1,sizeof head);
	memset(vis,0,sizeof vis);
	tot = 0;
	t = 0;
}

void add(int x,int y)
{
	edge[tot].to = y;
	edge[tot].next = head[x];
	head[x] = tot++;
}

void dfs(int x)
{
	vis[x] = 1;
	in[x] = ++t;
	for(int i = head[x]; i != -1; i = edge[i].next)
	{
		int y = edge[i].to;
		if(vis[y]) continue;
		dfs(y);
	}
	out[x] = t;	
}

struct data
{
	int l,r,num;
}node[maxn*4];

void pushup(int cnt)
{
	node[cnt].num = node[lson(cnt)].num + node[rson(cnt)].num;
}

void build(int x,int y, int cnt)
{
	node[cnt].l = x;
	node[cnt].r = y;
	if(x == y)
	{
		node[cnt].num = 0;
		return;
	}
	int mid = (x+y) / 2;
	build(x,mid,lson(cnt));
	build(mid+1,y,rson(cnt));
	pushup(cnt);
}

void up(int x,int y,int cnt,int val)
{
	if(x == node[cnt].l && y == node[cnt].r)
	{
		node[cnt].num = val;
		return;
	}
	int mid = (node[cnt].l + node[cnt].r) / 2;
	if(y <= mid)
		up(x,y,lson(cnt),val);
	else if(x >= mid+1)
		up(x,y,rson(cnt),val);
	else
	{
		up(x,mid,lson(cnt),val);
		up(mid+1,y,rson(cnt),val);
	}	
	pushup(cnt);
}

int fid(int x,int y,int cnt)
{
	if(x == node[cnt].l && y == node[cnt].r)
	{
		return node[cnt].num;
	}
	int mid = (node[cnt].l + node[cnt].r) / 2;
	if(y <= mid)
		return fid(x,y,lson(cnt));
	else if(x >= mid+1)
		return fid(x,y,rson(cnt));
	else
		return fid(x,mid,lson(cnt)) + fid(mid+1,y,rson(cnt));
}

int main(void)
{
	int n,p;
	while(scanf("%d%d",&n,&p)!=EOF && n+p)
	{
		init();
		for(int i = 1; i < n; i++)
		{
			int a,b;
			scanf("%d%d",&a,&b);
			add(a,b);
			add(b,a);
		}
		dfs(p);
		build(1,n,1);
		for(int i = 1; i <= n; i++)
		{
			printf("%d%c",fid(in[i],out[i],1),i==n?'\n':' ');
			up(in[i],in[i],1,1);
		}
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值