Educational Codeforces Round 7-E. Ants in Leaves

原题链接

E. Ants in Leaves
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Tree is a connected graph without cycles. A leaf of a tree is any vertex connected with exactly one other vertex.

You are given a tree with n vertices and a root in the vertex 1. There is an ant in each leaf of the tree. In one second some ants can simultaneously go to the parent vertex from the vertex they were in. No two ants can be in the same vertex simultaneously except for the root of the tree.

Find the minimal time required for all ants to be in the root of the tree. Note that at start the ants are only in the leaves of the tree.

Input

The first line contains integer n (2 ≤ n ≤ 5·105) — the number of vertices in the tree.

Each of the next n - 1 lines contains two integers xi, yi (1 ≤ xi, yi ≤ n) — the ends of the i-th edge. It is guaranteed that you are given the correct undirected tree.

Output

Print the only integer t — the minimal time required for all ants to be in the root of the tree.

Examples
input
12
1 2
1 3
1 4
2 5
2 6
3 7
3 8
3 9
8 10
8 11
8 12
output
6
input
2
2 1
output
1


只要求出根节点的每棵子树上所有蚂蚁走到根节点所用时间,这些时间的最大值就是答案。那么要求子树上所有蚂蚁到达根节点时间,先求出子树上所有叶子的深度,存在数组p中,在对p从小到大排序,i > 1, p[i] = max(p[i], p[i-1] + 1).若p的长度为len, 那么p[len-1]就是这个子树上的时间

#include <bits/stdc++.h>
#define maxn 500005
#define MOD 1000000007
using namespace std;
typedef long long ll;

vector<int> v[maxn], p;
int n;
void dfs(int j, int f, int h){
	if(v[j].size() == 1){
		p.push_back(h);
		return ;
	}
	for(int i = 0; i < v[j].size(); i++){
		int b = v[j][i];
		if(b != f){
			dfs(b, j, h+1);
		}
	}
}
int main(){
	
//	freopen("in.txt", "r", stdin);
	int a, b;
	scanf("%d", &n);
	for(int i = 0; i < n-1; i++){
	    scanf("%d%d", &a, &b);
	    v[a].push_back(b);
	    v[b].push_back(a);
	}
	int ans = 0;
	for(int i = 0; i < v[1].size(); i++){
		p.clear();
		dfs(v[1][i], 1, 1);
		sort(p.begin(), p.end());
		for(int j = 1; j < p.size(); j++){
			if(p[j] <= p[j-1])
			 p[j] = p[j-1] + 1;
		}
		ans = max(ans, p[p.size()-1]);
	}
	printf("%d\n", ans);
	return 0;
} 



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值