Educational Codeforces Round 7

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

题意是给你一棵树,1为根,每个叶子节点有一个蚂蚁,移动到一个邻接节点时间耗费为1,一个节点上不能同时有1个以上的蚂蚁数目(除了根节点外),让你求最后一个蚂蚁到达根节点的最少的时间。

可以先dfs预处理每个叶子节点的深度dep[i],然后把1节点邻接的节点当作一个子根,求这个子根所在的子树上蚂蚁到这个子根的最大的时间,除了子树上蚂蚁最早到达的时间为ans[0] ,其余子树上的蚂蚁为max(ans[i - 1] , dep[i] + 1),最后的答案就是遍历1所相邻的子根所得到的答案取一个最大值。

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int MAXN = 5e5 + 5;
 4 bool ok[MAXN];
 5 vector <int> G[MAXN] , ans;
 6 
 7 void dfs(int u , int par , int dep) {
 8     if(G[u].size() == 1) {
 9         ans.push_back(dep + 1);
10         return ;
11     }
12     for(int i = 0 ; i < G[u].size() ; i++) {
13         if(G[u][i] != par) {
14             dfs(G[u][i] , u , dep + 1);
15         }
16     }
17 }
18 
19 int main()
20 {
21     int n , v , u;
22     scanf("%d" , &n);
23     for(int i = 1 ; i < n ; i++) {
24         scanf("%d %d" , &u , &v);
25         G[u].push_back(v);
26         G[v].push_back(u);
27     }
28     int len = G[1].size() , res = 0 , temp;
29     for(int i = 0 ; i < len ; i++) {
30         dfs(G[1][i] , 1 , 0);
31         sort(ans.begin() , ans.end());
32         temp = ans[0];
33         for(int j = 1 ; j < ans.size() ; j++) {
34             temp = max(temp + 1 , ans[j]);
35         }
36         res = max(res , temp);
37         ans.clear();
38     }
39     printf("%d
" , res);
40 }
原文地址:https://www.cnblogs.com/Recoder/p/5256265.html