UVA 11688

Thinking:

Find the shift of status. And observe the nature of rotation.  

Use father's status to solve both sons' status.

AC code:

#include<iostream>
#include<cstring>
using namespace std;


int root;
int L[100005];// L[i] -> i's left son
int R[100005];
int dp[100005];
int h[100005];// how deep can this node stretch
bool f[100005];// f[i] -> does this node have a parent?
inline int find_height(int r)
{
	if (r == 0)// reach the end
	{
		return 0;
	}
	h[r] =max(find_height(L[r]),find_height(R[r])) + 1;
	return h[r];
}

inline void dfs(int x, int lh,int rh,int lcount,int rcount)
{
	if (x == 0)// reach the end
		return;
	if (!f[x])// if x is root
	{
		dp[x] = 1 + max(h[L[x]], h[R[x]]);
	}
	else{
		dp[x] = max(max(lh, rh), max(h[L[x]] + lcount, h[R[x]] + rcount)) + 1;
	}
	
	dfs(L[x], lh, max(rh, h[R[x]] + rcount + 1), lcount, rcount + 1);
	dfs(R[x], max(lh,h[L[x]]+lcount+1),rh,lcount+1, rcount );
}

int main()
{
	int n;
	while (scanf("%d", &n) && n)
	{
	
		for (int i = 1; i <= n; i++)
		{
			f[i] = 0;
		}
		for (int i = 1; i <= n; i++)
		{
			int left_child, right_child;
			scanf("%d%d", &left_child, &right_child);
			L[i] = left_child;
			R[i] = right_child;
			f[left_child] = 1;
			f[right_child]=1;
		}
		for (int i = 1; i <= n; i++)
			if (f[i]==false)
			{
				root = i;// find the root
				break;
			}
			find_height(root);// search from the root
			dfs(root, 0, 0, 0, 0);

		for (int i = 1; i <= n; i++)
			printf("%d\n", dp[i]);

	}
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值