[LeetCode] Count Number of Possible Root Nodes

2581. Count Number of Possible Root Nodes

Alice has an undirected tree with n nodes labeled from 0 to n - 1. The tree is represented as a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.

Alice wants Bob to find the root of the tree. She allows Bob to make several guesses about her tree. In one guess, he does the following:

  • Chooses two distinct integers u and v such that there exists an edge [u, v] in the tree.
  • He tells Alice that u is the parent of v in the tree.

Bob’s guesses are represented by a 2D integer array guesses where guesses[j] = [uj, vj] indicates Bob guessed uj to be the parent of vj.

Alice being lazy, does not reply to each of Bob’s guesses, but just says that at least k of his guesses are true.

Given the 2D integer arrays edges, guesses and the integer k, return the number of possible nodes that can be the root of Alice’s tree. If there is no such tree, return 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
unordered_map<int, unordered_map<int, int>> dp;
unordered_map<int, unordered_set<int>> q;
vector<int> adj[101010];
int dfs(int u, int par) {
if(dp[u].count(par)) return dp[u][par];
int& res = dp[u][par] = 0;
if(q.count(u) and q[u].count(par)) res += 1;
for(auto& v : adj[u]) {
if(v == par) continue;
res += dfs(v,u);
}
return res;
}
public:
int rootCount(vector<vector<int>>& edges, vector<vector<int>>& guesses, int k) {
for(auto g : guesses) {
q[g[1]].insert(g[0]);
}
int n = edges.size() + 1;
for(auto e : edges) {
int u = e[0], v = e[1];
adj[u].push_back(v);
adj[v].push_back(u);
}
int res = 0;
for(int i = 0; i < n; i++) {
int now = dfs(i,-1);
if(now >= k) res += 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/03/05/PS/LeetCode/count-number-of-possible-root-nodes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.