题解:P17458 [GESP202609 六级] 分树规划
linshenghuan · · 题解
六级考生前来报到。
:::info[前言]{open}
本人两次不过六级两题
\texttt{Solution}
题目大意
将一棵树(不是二叉树)割掉一条边,使该树变成两个连通块,求出两个连通块最小的节点数差。
分析
STEP 1:存树
题目给出的树不是二叉树,所以我们使用 vector 来存树。
定义 vector 为 vector <int> g[N]。那么输入边 g[u].push_back(v)。
:::warning[注意]{open}
本人考场内亲身经历:
-
这里存储儿子需要在 u 的儿子中加上v ,也需要在v 的儿子中加上u ,并且 DFS 时必须有一个形参fa表示该节点的父亲。
STEP 2:计算子树节点数量
为什么要计算子树节点数量呢?注意到题目要让我们计算节点数,那么我们使用 dfs(rt)(
那么递推式表达计算
注:
\text{child}_u 为节点u 的儿子集合。
::::info[举例证明]
:::info[二叉树] :::
过程:
注意:设
\operatorname{subtree}(u) 为以u 为根的子树。
-
遍历节点
1 :不是叶子节点,儿子节点有\{2,3\} ,先遍历2 :- 遍历节点
2 :不是叶子节点,儿子节点有\{4, 5\} ,先遍历4 :- 遍历节点
4 :是叶子节点,节点数量设为1 ,即\text{trsize}_4 \to 1 。
- 遍历节点
- 回溯到节点
2 :加上子树\operatorname{subtree}(4) 的节点数量,即\text{trsize}_2 \to \text{trsize}_2 + \text{trsize}_4 ,\text{trsize}_2 的值变为1 。继续遍历下一个儿子5 :- 遍历节点
5 :是叶子节点,节点数量设为1 ,即\text{trsize}_5 \to 1 。
- 遍历节点
- 回溯到节点
2 :加上子树\operatorname{subtree}(5) 的节点数量,即\text{trsize}_2 \to \text{trsize}_2 + \text{trsize}_5 ,\text{trsize}_2 的值变为2 。所有儿子遍历完毕,注意,自己也在以自己为根的子树中,所以\text{trsize}_2 还要加上1 ,变成3 。
- 遍历节点
-
回溯到节点
1 :加上子树\operatorname{subtree}(2) 的节点数量,即\text{trsize}_1 \to \text{trsize}_1 + \text{trsize}_2 ,\text{trsize}_1 的值变为3 。继续遍历下一个儿子3 :- 遍历节点
3 :是叶子节点,节点数量设为1 ,即为\text{trsize}_3 \to 1 。
- 遍历节点
-
回溯到节点
1 :加上子树\operatorname{subtree}(3) 的节点数量,即\text{trsize}_1 \to \text{trsize}_1 + \text{trsize}_3 ,\text{trsize}_1 的值变为4 。所有儿子遍历完毕,注意,自己也在以自己为根的子树中,所以\text{trsize}_1 还要加上1 ,变成5 。 -
这样,我们就得到了
\text{trsize} 数组:
::::
STEP 3:分成两个连通块
由于题目要求割掉一条边分成两个连通块,我们应该枚举边吗?
不。我们存储的是一个节点的儿子而不是边,所以我们枚举点
但是要通过
有以下的树:
:::info[二叉树] :::
注:其中红色的数字为子树
\operatorname{subtree}(u) 的节点数量。
我们设我们现在以 类似前缀和?。
:::success[结论]{open}
- 如果要割掉
u 和u 的父亲的连接边,那么两个连通块的大小分别为:
::cute-table{tuack}
| 根节点所在的连通块 | 以 |
|---|---|
:::
考场代码
:::success[code]
#include <bits/stdc++.h>
using namespace std;
const int N = 2e4 + 5;
vector <int> g[N];
int trsize[N], n;
void dfs(int rt, int fa) {
if (!g[rt].size()) {trsize[rt] = 1; return;}
trsize[rt] = 1;
for (int i = 0; i < g[rt].size(); i ++) {
int child = g[rt][i];
if (child == fa) continue;
dfs(child, rt);
trsize[rt] += trsize[child];
}
}
int main() {
cin >> n;
for (int i = 1; i <= n - 1; i ++) {
int u, v;
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
dfs(1, 0);
int ans = INT_MAX;
for (int i = 1; i <= n; i ++) {
int cnt1 = trsize[i]; // 蓝色连通块
int cnt2 = n - cnt1; // 红色连通块
// cout << cnt1 << ' ' << cnt2 << endl;
ans = min(ans, abs(cnt1 - cnt2));
}
cout << ans;
return 0;
}
:::
AD
- T1 的题解