Codeforces 622E (树DP)

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


题意:一棵树根节点是1,每个叶子节点有一只蚂蚁,每单位时间可以爬到当前节点的父亲,除了根节点某个节点不能出现多于两只蚂蚁。求所有蚂蚁到达根节点的最少时间。

对于因为根节点的特殊性可以把根节点分开来考虑,对于根节点的每个子树,只需要知道某个子树蚂蚁爬完的最大值。而对于不能在同一个节点存在两只蚂蚁的子树,可以先求出所有的蚂蚁爬到这个子树根节点的时间,然后相同的时间必须要加一,他们必须错开到达这个子树根节点的时间。

#include <cstdio>
#include <cmath>
#include <iostream>
#include <vector>
#include <cstring>
#include <bits/stdc++.h>
using namespace std;
#define maxn 511111
#define maxm 1111111

struct node {
	int u, v, next;
}edge[maxm];
vector <int> a;
int head[maxn], cnt;
int n;

void add_edge (int u, int v) {
	edge[cnt].u = u; edge[cnt].v = v; edge[cnt].next = head[u]; head[u] = cnt++;
	return ;
}

void dfs (int u, int deep, int father) {
	int son = 0;
	for (int i = head[u]; i != -1; i = edge[i].next) {
		int v = edge[i].v;
		if (v == father)
			continue;
		dfs (v, deep+1, u);
		son++;
	}
	if (!son)
		a.push_back (deep);
}

int main () {
	scanf ("%d", &n);
	memset (head, -1, sizeof head);
	cnt = 0;
	int u, v;
	for (int i = 0; i < n-1; i++) {
		scanf ("%d%d", &u, &v);
		add_edge (u, v);
		add_edge (v, u);
	}
	int ans = 0;
	for (int i = head[1]; i != -1; i = edge[i].next) {
		a.clear ();
		int v = edge[i].v;
		dfs (v, 1, 1);
		sort (a.begin (), a.end ());
		//for (int i = 0; i < a.size (); i++) cout << a[i] << " "; cout << endl;
		int l = a.size ();
		for (int i = 1; i < l; i++) {
			a[i] = max (a[i-1]+1, a[i]);
		}
		ans = max (ans, a[l-1]);
	}
	cout << ans << endl;
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值