[LeetCode] Maximize the Number of Target Nodes After Connecting Trees II

3373. Maximize the Number of Target Nodes After Connecting Trees II

There exist two undirected trees with n and m nodes, labeled from [0, n - 1] and [0, m - 1], respectively.

You are given two 2D integer arrays edges1 and edges2 of lengths n - 1 and m - 1, respectively, where edges1[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the first tree and edges2[i] = [ui, vi] indicates that there is an edge between nodes ui and vi in the second tree.

Node u is target to node v if the number of edges on the path from u to v is even. Note that a node is always target to itself.

Return an array of n integers answer, where answer[i] is the maximum possible number of nodes that are target to node i of the first tree if you had to connect one node from the first tree to another node in the second tree.

Note that queries are independent from each other. That is, for every query you will remove the added edge before proceeding to the next query.

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
34
35
36
37
38
class Solution {
vector<int> bfs(vector<vector<int>>& E) {
vector<int> res(E.size() + 1,-1);
vector<vector<int>> adj(E.size() + 1);
for(auto& e : E) {
int u = e[0], v = e[1];
adj[u].push_back(v);
adj[v].push_back(u);
}
queue<int> q;
q.push(0); res[0] = 0;
while(q.size()) {
int qsz = q.size();
while(qsz--) {
int u = q.front(); q.pop();
for(auto& v : adj[u]) {
if(res[v] != -1) continue;
res[v] = !res[u];
q.push(v);
}
}
}
return res;
}
public:
vector<int> maxTargetNodes(vector<vector<int>>& edges1, vector<vector<int>>& edges2) {
vector<int> A = bfs(edges1), B = bfs(edges2);
unordered_map<int,int> c1,c2;
for(auto& a : A) c1[a]++;
for(auto& b : B) c2[b]++;
int ma = max(c2[0],c2[1]);
vector<int> res;
for(int i = 0; i < A.size(); i++) {
res.push_back(c1[A[i]] + ma);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/12/01/PS/LeetCode/maximize-the-number-of-target-nodes-after-connecting-trees-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.