// Function to compute subtree sizes rooted at each node
function getSubtreeSizes(node, parent, graph, processed, subtree) {
subtree[node] = 1;
for (let i of graph[node]) {
if (!processed[i] && i !== parent) {
subtree[node] += getSubtreeSizes(i, node, graph, processed, subtree);
}
}
return subtree[node];
}
// Function to find the centroid of the subtree
function getCentroid(desired, node, parent, graph, processed, subtree) {
for (let i of graph[node]) {
if (!processed[i] && i !== parent && subtree[i] >= desired) {
return getCentroid(desired, i, node, graph, processed, subtree);
}
}
return node;
}
// Function to update the counter array with node counts at each depth
function getCount(node, parent, filling, depth, graph, processed, cnt, ans, k) {
if (depth > k) return;
mxDepth = Math.max(mxDepth, depth);
if (filling) cnt[depth]++;
else ans[0] += cnt[k - depth];
for (let i of graph[node]) {
if (!processed[i] && i !== parent) {
getCount(i, node, filling, depth + 1, graph, processed, cnt, ans, k);
}
}
}
// Centroid decomposition function
function centroidDecomp(node, graph, processed, subtree, cnt, ans, k) {
let centroid = getCentroid(getSubtreeSizes(node, 0, graph, processed, subtree) >> 1, node, 0, graph, processed, subtree);
processed[centroid] = true;
mxDepth = 0;
for (let i of graph[centroid]) {
if (!processed[i]) {
getCount(i, centroid, false, 1, graph, processed, cnt, ans, k);
getCount(i, centroid, true, 1, graph, processed, cnt, ans, k);
}
}
cnt.fill(0, 1, mxDepth + 1);
for (let i of graph[centroid]) {
if (!processed[i]) {
centroidDecomp(i, graph, processed, subtree, cnt, ans, k);
}
}
}
// Driver code
function main() {
// Static input
let n = 5; // Number of nodes
let k = 2; // Maximum depth
let ans = [0]; // Final answer
let graph = new Array(n + 1).fill(null).map(() => []);
let processed = new Array(n + 1).fill(false);
let subtree = new Array(n + 1).fill(0);
let cnt = new Array(n + 1).fill(1);
// Static graph edges
graph[1].push(2);
graph[2].push(1);
graph[2].push(3);
graph[3].push(2);
graph[3].push(4);
graph[3].push(5);
graph[4].push(3);
graph[5].push(3);
// Performing centroid decomposition and computing the final answer
centroidDecomp(1, graph, processed, subtree, cnt, ans, k);
// Outputting the final answer
console.log(ans[0]);
}
main();
// This code is contributed by Ayush Mishra