Leetcode 2858. Minimum Edge Reversals So Every Node Is Reachable
Woodyiiiiiii opened this issue · comments
2858. Minimum Edge Reversals So Every Node Is Reachable
2858. Minimum Edge Reversals So Every Node Is Reachable
讲解:
【模板】换根 DP(Python/Java/C++/Go/JS)
类似题目:
834. Sum of Distances in Tree
2581. Count Number of Possible Root Nodes
re-rooting/换根DP
一般这种题目是求如果以每个节点为根节点的情况下,达到要求的情况个数。一般思路是,先从以0为根节点出发,计算答案,然后从0深度遍历,在转换关系中以0计算出的答案为基础,计算出当前根节点的情况个数。所以,重点是如何在转换中寻找关系。多练习。
class Solution {
public int[] minEdgeReversals(int n, int[][] edges) {
Map<Integer, Set<int[]>> g = new HashMap<>();
for (int[] edge : edges) {
int u = edge[0], v = edge[1];
g.putIfAbsent(u, new HashSet<>());
g.putIfAbsent(v, new HashSet<>());
g.get(u).add(new int[]{v, 1});
g.get(v).add(new int[]{u, -1});
}
int[] ans = new int[n];
dfs(0, -1, g, ans);
reRoot(0, -1, g, ans);
return ans;
}
private void dfs(int cur, int fa, Map<Integer, Set<int[]>> g, int[] ans) {
for (int[] next : g.get(cur)) {
if (next[0] == fa) {
continue;
}
ans[0] += next[1] == -1 ? 1 : 0;
dfs(next[0], cur, g, ans);
}
}
private void reRoot(int cur, int fa, Map<Integer, Set<int[]>> g, int[] ans) {
for (int[] next : g.get(cur)) {
if (next[0] == fa) {
continue;
}
ans[next[0]] = ans[cur] + next[1];
reRoot(next[0], cur, g, ans);
}
}
}