CF622E Ants in Leaves
第一道紫,纪念一下~。
首先每只蚂蚁肯定是能往上走就往上走的(假设这只蚂蚁能往上走但是它选择礼让,让另一只蚂蚁先往上走,那就相当于另一只蚂蚁能往上就往上,这只蚂蚁被挡住了所以没往上)。 一只蚂蚁不考虑交通堵塞走到根节点的步数就是它的深度,这是一个约束条件,另一个约束条件是和它在同一个根节点儿子的子树中的蚂蚁到这个根节点儿子的时间,即为它到根节点的时间 ,那这只蚂蚁就要停下来等另一只蚂蚁到根节点,再往上走到根节点儿子和根节点,时间为另一只到根节点的时间 再 ,那么我们就可以考虑每个根节点的子树,将子树中蚂蚁们按深度排序,然后用两个约束条件算出每只蚂蚁到达的时间,最后将答案和最后一只蚂蚁到的时间取 max 就行。
时间复杂度 。
Code:
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
typedef long long ll;
typedef pair<int, int> pii;
int n, dep[N], c[N], tot, ans;
vector<int>edges[N];
inline void dfs(int pos, int fa) {
bool flag = false;
dep[pos] = dep[fa] + 1;
for (auto x : edges[pos]) {
if (x == fa) continue;
flag = true;
dfs(x, pos);
}
if (!flag) c[++tot] = dep[pos];
}
int main() {
scanf("%d", &n);
for (int i = 1; i < n; i++) {
int x, y; scanf("%d%d", &x, &y);
edges[x].push_back(y);
edges[y].push_back(x);
}
for (auto x : edges[1]) {
tot = 0;
dfs(x, 1);
sort(c + 1, c + tot + 1);
for (int i = 2; i <= tot; i++) c[i] = max(c[i], c[i - 1] + 1); //更新后的 c[i] 表示 i 到根节点的时间
// i 到根节点的时间被深度, i - 1 到的时间约束, i - 1 到达根节点儿子的时间为 c[i - 1] - 1, 这时 i 不能走到根节点儿子处,
// 只能等 i - 1 到根节点, 即时间为 c[i - 1] 是才能往上走, 时间为 c[i - 1] 时到达根节点儿子, c[i - 1] + 1 时到达根节点
ans = max(ans, c[tot]);
}
printf("%d\n", ans);
return 0;
}