Educational Codeforces Round 7 E. Ants in Leaves 贪心

本文探讨了如何使用贪心策略解决树形结构中蚂蚁从叶子节点移动到根节点的最短时间问题。通过深度优先搜索记录各叶子节点的深度,并利用桶排序优化算法来确定最小时间,确保所有蚂蚁最终到达根节点。

E. Ants in Leaves

题目连接:

http://www.codeforces.com/contest/622/problem/E

Description

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.

Sample Input

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

Sample Output

6

Hint

题意

每个叶子都有一个蚂蚁,然后蚂蚁会爬到根去,每秒可以爬一个节点

然后每个节点的蚂蚁最多同时只有一个(除了根

然后问你最少多久,可以使得所有蚂蚁都在根的位置

题解:

贪心就好了

对于叶子,我们都记录下他们的深度,然后我们发现,如果存在两个叶子的深度相同,那么他们一定会相遇在某个点,所以我们只要使得某个点的深度+1就好了

然后这样不断贪心下去就行了

这个可以用桶排解决,反正最多1e6嘛

代码

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6+7;
vector<int> E[maxn];
int dep[maxn];
int cnt[maxn];
vector<int> tmp;
void dfs(int x,int fa)
{
    if(E[x].size()==1)tmp.push_back(dep[x]);
    for(int i=0;i<E[x].size();i++)
    {
        int v = E[x][i];
        if(v==fa)continue;
        dep[v]=dep[x]+1;
        dfs(v,x);
    }
}
int main()
{
    int n;
    scanf("%d",&n);
    for(int i=1;i<n;i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        E[x].push_back(y);
        E[y].push_back(x);
    }
    //cout<<endl;
    int ans = 0;
    for(int i=0;i<E[1].size();i++)
    {
        for(int j=0;j<=E[E[1][i]].size()+5;j++)
            cnt[j]=0;
        dep[E[1][i]]=1;
        tmp.clear();
        dfs(E[1][i],1);
        sort(tmp.begin(),tmp.end());
        int now = 0;
        for(int j=0;j<tmp.size();j++)
        {
            if(now>=tmp[j])now++;
            else now=tmp[j];
        }
        ans=max(ans,now);
    }
    cout<<ans<<endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值