Educational Codeforces Round 7 E. Ants in Leaves 贪心

题目链接:http://codeforces.com/contest/622/problem/E

题意:

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

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

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

解法:

贪心就好了

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

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

复杂度: O((n+m)*log(n)),换成桶排序可以O(n*m)

//CF 622E

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6+7;
vector <int> E[maxn];
int dep[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 n;
int main(){
    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);
    }
    int ans = 0;
    for(int i = 0; i < E[1].size(); i++){
        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);
    }
    printf("%d
", ans);
    return 0;
}
原文地址:https://www.cnblogs.com/spfa/p/6594935.html