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

3372. Maximize the Number of Target Nodes After Connecting Trees I

There exist two undirected trees with n and m nodes, with distinct labels in ranges [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. You are also given an integer k.

Node u is target to node v if the number of edges on the path from u to v is less than or equal to k. 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 target to node i of the first tree if you have 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
class Solution {
void dfs(vector<vector<int>>& adj, int u, int par, int k, int& cnt) {
cnt++;
if(!k) return;
for(auto& v : adj[u]) {
if(v != par) dfs(adj,v,u,k-1,cnt);
}
}
vector<int> helper(vector<vector<int>>& E, int k) {
if(k == -1) return vector<int>(E.size() + 1);
vector<int> res(E.size() + 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);
}
for(int i = 0; i < res.size(); i++) {
dfs(adj,i,-1,k,res[i]);
}
return res;
}
public:
vector<int> maxTargetNodes(vector<vector<int>>& edges1, vector<vector<int>>& edges2, int k) {
vector<int> cost1 = helper(edges1, k), cost2 = helper(edges2, k - 1);
int ma = *max_element(begin(cost2), end(cost2));
for(auto& c : cost1) c += ma;
return cost1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/12/01/PS/LeetCode/maximize-the-number-of-target-nodes-after-connecting-trees-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.