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.
Example
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的树,树的每个叶子结点都有一只蚂蚁,现在所有蚂蚁要到根节点1去问最少时间多少,
每秒钟蚂蚁移动一个结点,每个结点除根节点外只能有一个蚂蚁。
分析:
看到是一棵树,很容易被误导去想树形dp,其实贪心可解
首先对于根节点的每一棵子树来说,如果想让时间最少,肯定要让深度小的叶子结点上的蚂蚁先移动,
这样就避免了后面蚂蚁的“堵塞”,基于这样一种考虑,我们把一棵子树上的所有叶子深度都取出来,
从小到大排序,对于相同深度的叶子结点,一定是前者已有的步数+1(因为同深度的叶子去同一个根
节点会发生堵塞),而深度不同的叶子,要么深度大于当前已经处理出的答案,那么一定不会与前面相堵塞,
更新为深度,如果小于则一定堵塞,答案+1。那么就有递推公式dp[i]=max(dp[i-1]+1,dp[i]);
注意题中给出的是无向边。
#include
using namespace std;
#define fi first
#define se second
#define ff(i,a,b) for(int i = a; i <= b; i++)
#define f(i,a,b) for(int i = a; i < b; i++)
typedef pair<int,int> P;
#define ll long long
vector<int> e[500010],yezi;
int dep[500010];
void dfs(int x, int fa,int depth)
{
dep[x] = depth;
int flag = 0;
f(i,0,e[x].size())
if(e[x][i] != fa){ dfs(e[x][i],x,depth+1); flag = 1; }
if(!flag)
yezi.push_back(dep[x]);
}
int main()
{
ios::sync_with_stdio(false);
int n;
cin >> n;
ff(i,1,n - 1)
{
int x,y;
cin >> x >> y;
e[x].push_back(y);
e[y].push_back(x);
}
int ans = 0;
f(i,0,e[1].size())
{
yezi.clear();
dfs(e[1][i],1,1);
sort(yezi.begin(),yezi.end());
int maxx = yezi[0];
f(i,1,yezi.size())
maxx = max(yezi[i],maxx + 1);
ans = max(ans,maxx);
}
cout << ans << endl;
return 0;
}