给定一个由N 个节点组成的N叉树,其值取自[1, N] ,其中节点1是根节点,任务是计算节点对之间的最小距离等于两个节点的距离之差从根本上。
例子:
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
朴素的方法:最简单的方法是找到所有可能对(i, j)之间的距离,并检查每对节点(i, j) ,是否distance(i, j) = distance(1, i) – distance( 1, j)或不使用深度优先搜索遍历。
时间复杂度: O(N 2 )
辅助空间: O(N)
高效的方法:上述方法可以基于以下观察进行优化:
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.
请按照以下步骤解决问题:
- 初始化一个变量,比如ans ,以存储节点对的计数。
- 从根节点执行 DFS 遍历,参数为当前节点、父节点和节点深度,直到当前节点。
- 以当前节点为父节点,深度增加1,对每个节点的子节点递归进行DFS遍历。
- 在每次调用中,将当前节点的深度添加到变量ans 中。
- 完成以上步骤后,打印ans的值作为结果。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Stores the count of pairs
long long ans = 0;
// Store the adjacency list of
// the connecting vertex
vector adj[int(1e5) + 1];
// Function for theto perform DFS
// traversal of the given tree
void dfsUtil(int u, int par, int depth)
{
// Traverse the adjacency list
// of the current node u
for (auto it : adj[u]) {
// If the current node
// is the parent node
if (it != par) {
dfsUtil(it, u, depth + 1);
}
}
// Add number of ancestors, which
// is same as depth of the node
ans += depth;
}
// Function for DFS traversal of
// the given tree
void dfs(int u, int par, int depth)
{
dfsUtil(u, par, depth);
// Print the result
cout << ans << endl;
}
// Function to find the count of pairs
// such that the minimum distance
// between them is equal to the difference
// between distance of the nodes from root node
void countPairs(vector > edges)
{
for (int i = 0; i < edges.size(); i++) {
int u = edges[i][0];
int v = edges[i][1];
// Add edges to adj[]
adj[u].push_back(v);
adj[v].push_back(u);
}
dfs(1, 1, 1);
}
// Driver Code
int main()
{
vector > edges
= { { 1, 2 }, { 1, 3 }, { 2, 4 } };
countPairs(edges);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG
{
// Stores the count of pairs
static int ans = 0;
// Store the adjacency list of
// the connecting vertex
static ArrayList []adj = new ArrayList[(int)(1e5) + 1];
static{
for(int i = 0; i < adj.length; i++)
adj[i] = new ArrayList<>();
}
// Function for theto perform DFS
// traversal of the given tree
static void dfsUtil(int u, int par, int depth)
{
// Traverse the adjacency list
// of the current node u
for (int it : adj[u]) {
// If the current node
// is the parent node
if (it != par) {
dfsUtil(it, u, depth + 1);
}
}
// Add number of ancestors, which
// is same as depth of the node
ans += depth;
}
// Function for DFS traversal of
// the given tree
static void dfs(int u, int par, int depth)
{
dfsUtil(u, par, depth);
// Print the result
System.out.print(ans +"\n");
}
// Function to find the count of pairs
// such that the minimum distance
// between them is equal to the difference
// between distance of the nodes from root node
static void countPairs(int [][]edges)
{
for (int i = 0; i < edges.length; i++) {
int u = edges[i][0];
int v = edges[i][1];
// Add edges to adj[]
adj[u].add(v);
adj[v].add(u);
}
dfs(1, 1, 1);
}
// Driver Code
public static void main(String[] args)
{
int [][]edges
= { { 1, 2 }, { 1, 3 }, { 2, 4 } };
countPairs(edges);
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 program for the above approach
# Stores the count of pairs
ans = 0
# Store the adjacency list of
# the connecting vertex
adj = [[] for i in range(10**5+1)]
# Function for theto perform DFS
# traversal of the given tree
def dfsUtil(u, par, depth):
global adj, ans
# Traverse the adjacency list
# of the current node u
for it in adj[u]:
# If the current node
# is the parent node
if (it != par):
dfsUtil(it, u, depth + 1)
# Add number of ancestors, which
# is same as depth of the node
ans += depth
# Function for DFS traversal of
# the given tree
def dfs(u, par, depth):
global ans
dfsUtil(u, par, depth)
# Prthe result
print (ans)
# Function to find the count of pairs
# such that the minimum distance
# between them is equal to the difference
# between distance of the nodes from root node
def countPairs(edges):
global adj
for i in range(len(edges)):
u = edges[i][0]
v = edges[i][1]
# Add edges to adj[]
adj[u].append(v)
adj[v].append(u)
dfs(1, 1, 1)
# Driver Code
if __name__ == '__main__':
edges = [ [ 1, 2 ], [ 1, 3 ], [ 2, 4 ] ]
countPairs(edges)
# This code is contributed by mohit kumar 29.
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG
{
// Stores the count of pairs
static int ans = 0;
// Store the adjacency list of
// the connecting vertex
static List []adj = new List[(int)(1e5) + 1];
// Function for theto perform DFS
// traversal of the given tree
static void dfsUtil(int u, int par, int depth)
{
// Traverse the adjacency list
// of the current node u
foreach (int it in adj[u]) {
// If the current node
// is the parent node
if (it != par) {
dfsUtil(it, u, depth + 1);
}
}
// Add number of ancestors, which
// is same as depth of the node
ans += depth;
}
// Function for DFS traversal of
// the given tree
static void dfs(int u, int par, int depth)
{
dfsUtil(u, par, depth);
// Print the result
Console.Write(ans +"\n");
}
// Function to find the count of pairs
// such that the minimum distance
// between them is equal to the difference
// between distance of the nodes from root node
static void countPairs(int [,]edges)
{
for (int i = 0; i < edges.GetLength(0); i++)
{
int u = edges[i,0];
int v = edges[i,1];
// Add edges to []adj
adj[u].Add(v);
adj[v].Add(u);
}
dfs(1, 1, 1);
}
// Driver Code
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();
countPairs(edges);
}
}
// This code is contributed by 29AjayKumar
Javascript
8
时间复杂度: O(N)
辅助空间: O(N)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live