Educational Codeforces Round 7 E. Ants in Leaves(贪心)
2016-02-11 20:06
423 查看
题意:
给定N≤5×105以1为根的一棵树,所有叶子节点都有1只蚂蚁
所有蚂蚁都可以同时向父亲移动,但是1个节点任意时刻至多只能有1只蚂蚁(根节点除外)
求所有蚂蚁移动到根节点的最短时间
分析:
首先可以发现,对于根节点的所有儿子的子树之间都是独立的
也就是说ans=max{Tsons}
对于某一颗子树来说,可以证明深度小的蚂蚁应该先往根移动,因为深度小的不移动的话,下面深度大的就被堵住了
zi:=i蚂蚁到根节点的时间,显然我们有zi≥zi−1+1,并且zi≥depthi
可以得到zi=max(depthi,zi−1+1)
只要从1递推到sz,Tcur_son=zsz
时间复杂度为O(nlogn)
代码:
给定N≤5×105以1为根的一棵树,所有叶子节点都有1只蚂蚁
所有蚂蚁都可以同时向父亲移动,但是1个节点任意时刻至多只能有1只蚂蚁(根节点除外)
求所有蚂蚁移动到根节点的最短时间
分析:
首先可以发现,对于根节点的所有儿子的子树之间都是独立的
也就是说ans=max{Tsons}
对于某一颗子树来说,可以证明深度小的蚂蚁应该先往根移动,因为深度小的不移动的话,下面深度大的就被堵住了
zi:=i蚂蚁到根节点的时间,显然我们有zi≥zi−1+1,并且zi≥depthi
可以得到zi=max(depthi,zi−1+1)
只要从1递推到sz,Tcur_son=zsz
时间复杂度为O(nlogn)
代码:
// // Created by TaoSama on 2016-02-11 // Copyright (c) 2016 TaoSama. All rights reserved. // #pragma comment(linker, "/STACK:1024000000,1024000000") #include <algorithm> #include <cctype> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <string> #include <set> #include <vector> using namespace std; #define pr(x) cout << #x << " = " << x << " " #define prln(x) cout << #x << " = " << x << endl const int N = 5e5 + 10, INF = 0x3f3f3f3f, MOD = 1e9 + 7; int n; vector<int> G ; void dfs(int u, int fa, int dep, vector<int>& d) { if(G[u].size() == 1) { d.push_back(dep); return; } for(int v : G[u]) if(v != fa) dfs(v, u, dep + 1, d); } int main() { #ifdef LOCAL freopen("C:\\Users\\TaoSama\\Desktop\\in.txt", "r", stdin); // freopen("C:\\Users\\TaoSama\\Desktop\\out.txt","w",stdout); #endif ios_base::sync_with_stdio(0); while(scanf("%d", &n) == 1) { for(int i = 1; i <= n; ++i) G[i].clear(); for(int i = 1; i < n; ++i) { int u, v; scanf("%d%d", &u, &v); G[u].push_back(v); G[v].push_back(u); } int ans = 0; for(int v : G[1]) { vector<int> d; dfs(v, 1, 1, d); sort(d.begin(), d.end()); for(int i = 1; i < d.size(); ++i) d[i] = max(d[i], d[i - 1] + 1); ans = max(ans, d.back()); } printf("%d\n", ans); } return 0; }
相关文章推荐
- 1.一些 贪心算法 的简单思维题:
- 贪心算法——字典序最小问题
- 贪心算法——区间调度问题
- Jump Game I,II 贪心
- Wildcard Matching
- 贪心法实现无向图的划分 代码
- 贪心题目循环和控制台折行
- HDOJ 1009
- 【解题报告】【USACO】酸奶工厂
- 【解题报告】【】交谊舞
- POJ 1328
- Best Cow Line
- HDU 1009 Fatmouse's Trade
- POJ2377 Bad Cowtractors
- 贪心 hdu 1003
- 最大容器
- 满足和为定值的两个数或多个数
- Codeforces Round #300
- HUD1052 __ P2 1002 __ Tian Ji -- The Horse Racing
- 2015年国家集训队测试 BZOJ3816矩阵变幻