Count pairs of nodes having minimum distance between them equal to the difference of their distances from root
Given an N-ary Tree consisting of N nodes valued from [1, N], where node 1 is the root, the task is to count the pairs of nodes having minimum distance between them equal to the difference between the distances of both the nodes from the root.
Examples:
Input: N = 3, Edges[][] = {{1, 2}, {1, 3}}, Below is the Tree:
1
/ \
2 3
Output: 5
Explanation: The following pairs satisfy the conditions: {(1, 1), (2, 2), (3, 3), (2, 1), (3, 1)}.
Input: N = 4, Edges[][] = {{1, 2}, {1, 3}, {2, 4}}, Below is the Tree:
1
/ \
2 3
|
4
Output: 8
Naive Approach: The simplest approach is to find the distance between all possible pairs (i, j) and check for each pair of nodes (i, j), whether distance(i, j) = distance(1, i) – distance(1, j) or not by using Depth-First Search Traversal.
Time Complexity: O(N2)
Auxiliary Space: O(N)
Efficient Approach: The above approach can be optimized based on the following observations:
The minimum distance from node X and the ancestor of node X satisfy the above criteria. Therefore, the task is reduced to finding all the ancestors of every node of the tree.
Follow the steps below to solve the problem:
- Initialize a variable, say ans, to store the count of pairs of nodes.
- Perform a DFS Traversal from the root node with arguments current node, parent node, and depth of node up until the current node.
- Recursively perform DFS Traversal on the child node of every node with the current node as parent node and depth increased by 1.
- In every call, add the depth of the current node to the variable ans.
- After completing the above steps, print the value of ans as the result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
long long ans = 0;
vector< int > adj[ int (1e5) + 1];
void dfsUtil( int u, int par, int depth)
{
for ( auto it : adj[u]) {
if (it != par) {
dfsUtil(it, u, depth + 1);
}
}
ans += depth;
}
void dfs( int u, int par, int depth)
{
dfsUtil(u, par, depth);
cout << ans << endl;
}
void countPairs(vector<vector< int > > edges)
{
for ( int i = 0; i < edges.size(); i++) {
int u = edges[i][0];
int v = edges[i][1];
adj[u].push_back(v);
adj[v].push_back(u);
}
dfs(1, 1, 1);
}
int main()
{
vector<vector< int > > edges
= { { 1, 2 }, { 1, 3 }, { 2, 4 } };
countPairs(edges);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int ans = 0 ;
static ArrayList<Integer> []adj = new ArrayList[( int )(1e5) + 1 ];
static {
for ( int i = 0 ; i < adj.length; i++)
adj[i] = new ArrayList<>();
}
static void dfsUtil( int u, int par, int depth)
{
for ( int it : adj[u]) {
if (it != par) {
dfsUtil(it, u, depth + 1 );
}
}
ans += depth;
}
static void dfs( int u, int par, int depth)
{
dfsUtil(u, par, depth);
System.out.print(ans + "\n" );
}
static void countPairs( int [][]edges)
{
for ( int i = 0 ; i < edges.length; i++) {
int u = edges[i][ 0 ];
int v = edges[i][ 1 ];
adj[u].add(v);
adj[v].add(u);
}
dfs( 1 , 1 , 1 );
}
public static void main(String[] args)
{
int [][]edges
= { { 1 , 2 }, { 1 , 3 }, { 2 , 4 } };
countPairs(edges);
}
}
|
Python3
ans = 0
adj = [[] for i in range ( 10 * * 5 + 1 )]
def dfsUtil(u, par, depth):
global adj, ans
for it in adj[u]:
if (it ! = par):
dfsUtil(it, u, depth + 1 )
ans + = depth
def dfs(u, par, depth):
global ans
dfsUtil(u, par, depth)
print (ans)
def countPairs(edges):
global adj
for i in range ( len (edges)):
u = edges[i][ 0 ]
v = edges[i][ 1 ]
adj[u].append(v)
adj[v].append(u)
dfs( 1 , 1 , 1 )
if __name__ = = '__main__' :
edges = [ [ 1 , 2 ], [ 1 , 3 ], [ 2 , 4 ] ]
countPairs(edges)
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
static int ans = 0;
static List< int > []adj = new List< int >[( int )(1e5) + 1];
static void dfsUtil( int u, int par, int depth)
{
foreach ( int it in adj[u]) {
if (it != par) {
dfsUtil(it, u, depth + 1);
}
}
ans += depth;
}
static void dfs( int u, int par, int depth)
{
dfsUtil(u, par, depth);
Console.Write(ans + "\n" );
}
static void countPairs( int [,]edges)
{
for ( int i = 0; i < edges.GetLength(0); i++)
{
int u = edges[i,0];
int v = edges[i,1];
adj[u].Add(v);
adj[v].Add(u);
}
dfs(1, 1, 1);
}
public static void Main(String[] args)
{
int [,]edges
= { { 1, 2 }, { 1, 3 }, { 2, 4 } };
for ( int i = 0; i < adj.GetLength(0); i++)
adj[i] = new List< int >();
countPairs(edges);
}
}
|
Javascript
<script>
var ans = 0;
var adj = Array.from(Array(100001), ()=>Array());
function dfsUtil(u, par, depth)
{
adj[u].forEach(it => {
if (it != par) {
dfsUtil(it, u, depth + 1);
}
});
ans += depth;
}
function dfs(u, par, depth)
{
dfsUtil(u, par, depth);
document.write( ans + "<br>" );
}
function countPairs(edges)
{
for ( var i = 0; i < edges.length; i++) {
var u = edges[i][0];
var v = edges[i][1];
adj[u].push(v);
adj[v].push(u);
}
dfs(1, 1, 1);
}
var edges
= [ [ 1, 2 ], [ 1, 3 ], [ 2, 4 ] ];
countPairs(edges);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Last Updated :
16 Sep, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...