📌  相关文章
📜  查找距离相等的节点对的数量

📅  最后修改于: 2021-10-25 03:08:36             🧑  作者: Mango

给定一个具有N 个节点和N-1 条边的连通无环图,找出彼此距离相等的节点对。
例子:

Input:
3
1 2 
2 3
Output: 1
Explanation:
    1
   /
  2
 /
3
Input:
5
1 2
2 3
1 4
4 5
Output: 4

方法:

  • 假设一个图有 6 个级别(0 到 5),级别 0、2、4 的距离相等,但级别 1、3、5 的距离也是均匀的,因为它们的差异是 2,这是偶数,因此我们必须兼顾两者条件即计算偶数和奇数。
  • 给定的问题可以通过执行 dfs 遍历来解决
  • 选择任意一个源节点作为root,进行dfs遍历并维护访问过的节点
    用于执行 dfs 和 dist 数组以计算与根的距离的数组
  • 现在遍历距离数组并保持偶数级和奇数级的计数
  • 计算总数为 ((even_count * (even_count-1)) + (odd_count * (odd_count-1))/2

下面是上述方法的实现:

C++
// C++ program to find
// the count of nodes
// at even distance
#include 
using namespace std;
 
// Dfs function to find count of nodes at
// even distance
void dfs(vector graph[], int node, int dist[],
                                    bool vis[], int c)
{
    if (vis[node]) {
        return;
    }
    // Set flag as true for current
    // node in visited array
    vis[node] = true;
 
    // Insert the distance in
    // dist array for current
    // visited node u
    dist[node] = c;
 
    for (int i = 0; i < graph[node].size(); i++) {
        // If its neighbours are not vis,
        // run dfs for them
        if (!vis[graph[node][i]]) {
            dfs(graph, graph[node][i], dist, vis, c + 1);
        }
    }
}
 
int countOfNodes(vector graph[], int n)
{
    // bool array to
    // mark visited nodes
    bool vis[n + 1] = { false };
 
    // Integer array to
    // compute distance
    int dist[n + 1] = { 0 };
 
    dfs(graph, 1, dist, vis, 0);
 
    int even = 0, odd = 0;
 
    // Traverse the distance array
    // and count the even and odd levels
    for (int i = 1; i <= n; i++) {
        if (dist[i] % 2 == 0) {
            even++;
        }
        else {
            odd++;
        }
    }
 
    int ans = ((even * (even - 1)) + (odd * (odd - 1))) / 2;
 
    return ans;
}
 
// Driver code
int main()
{
 
    int n = 5;
    vector graph[n + 1] = { {},
                                 { 2 },
                                 { 1, 3 },
                                 { 2 } };
 
    int ans = countOfNodes(graph, n);
    cout << ans << endl;
 
    return 0;
}


Java
// Java program to find the count of
// nodes at even distance
import java.util.*;
 
class GFG
{
 
// Dfs function to find count of nodes at
// even distance
static void dfs(Vector graph[],
                   int node, int dist[],
                   boolean vis[], int c)
{
    if (vis[node])
    {
        return;
    }
     
    // Set flag as true for current
    // node in visited array
    vis[node] = true;
 
    // Insert the distance in
    // dist array for current
    // visited node u
    dist[node] = c;
 
    for (int i = 0; i < graph[node].size(); i++)
    {
        // If its neighbours are not vis,
        // run dfs for them
        if (!vis[graph[node].get(i)])
        {
            dfs(graph, graph[node].get(i),
                        dist, vis, c + 1);
        }
    }
}
 
static int countOfNodes(Vector graph[],
                                         int n)
{
    // bool array to
    // mark visited nodes
    boolean []vis = new boolean[n + 1];
 
    // Integer array to
    // compute distance
    int []dist = new int[n + 1];
 
    dfs(graph, 1, dist, vis, 0);
 
    int even = 0, odd = 0;
 
    // Traverse the distance array
    // and count the even and odd levels
    for (int i = 1; i <= n; i++)
    {
        if (dist[i] % 2 == 0)
        {
            even++;
        }
        else
        {
            odd++;
        }
    }
    int ans = ((even * (even - 1)) +
                (odd * (odd - 1))) / 2;
 
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
    int n = 5;
    Vector []graph = new Vector[n + 1];
    for(int i = 0; i< n + 1; i++)
    {
        graph[i] = new Vector();
    }
     
    graph[0] = new Vector();
    graph[1] = new Vector(Arrays.asList(2));
    graph[2] = new Vector(1, 3);
    graph[3] = new Vector(2);
    int ans = countOfNodes(graph, n);
    System.out.println(ans);
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program to find
# the count of nodes
# at even distance
 
# Dfs function to find count of
# nodes at even distance
def dfs(graph, node, dist, vis, c) :
 
    if (vis[node]) :
        return;
     
    # Set flag as true for current
    # node in visited array
    vis[node] = True;
 
    # Insert the distance in
    # dist array for current
    # visited node u
    dist[node] = c;
 
    for i in range(len(graph[node])) :
        # If its neighbours are not vis,
        # run dfs for them
        if (not vis[graph[node][i]]) :
            dfs(graph, graph[node][i],
                    dist, vis, c + 1);
 
def countOfNodes(graph, n) :
 
    # bool array to
    # mark visited nodes
    vis = [False] * (n + 1);
 
    # Integer array to
    # compute distance
    dist = [0] * (n + 1);
 
    dfs(graph, 1, dist, vis, 0);
 
    even = 0; odd = 0;
 
    # Traverse the distance array
    # and count the even and odd levels
    for i in range(1, n + 1) :
        if (dist[i] % 2 == 0) :
            even += 1;
     
        else :
            odd += 1;
 
    ans = ((even * (even - 1)) +
            (odd * (odd - 1))) // 2;
 
    return ans;
 
# Driver code
if __name__ == "__main__" :
 
    n = 5;
    graph = [[], [ 2 ], [ 1, 3 ], [ 2 ]];
 
    ans = countOfNodes(graph, n);
    print(ans);
 
# This code is contributed by kanugargng


C#
// C# program to find the count of
// nodes at even distance
using System;
using System.Collections.Generic;
     
class GFG
{
 
// Dfs function to find count of
// nodes at even distance
static void dfs(List []graph,
                int node, int []dist,
                bool []vis, int c)
{
    if (vis[node])
    {
        return;
    }
     
    // Set flag as true for current
    // node in visited array
    vis[node] = true;
 
    // Insert the distance in
    // dist array for current
    // visited node u
    dist[node] = c;
 
    for (int i = 0; i < graph[node].Count; i++)
    {
        // If its neighbours are not vis,
        // run dfs for them
        if (!vis[graph[node][i]])
        {
            dfs(graph, graph[node][i],
                    dist, vis, c + 1);
        }
    }
}
 
static int countOfNodes(List []graph,
                                    int n)
{
    // bool array to
    // mark visited nodes
    bool []vis = new bool[n + 1];
 
    // int array to
    // compute distance
    int []dist = new int[n + 1];
 
    dfs(graph, 1, dist, vis, 0);
 
    int even = 0, odd = 0;
 
    // Traverse the distance array
    // and count the even and odd levels
    for (int i = 1; i <= n; i++)
    {
        if (dist[i] % 2 == 0)
        {
            even++;
        }
        else
        {
            odd++;
        }
    }
    int ans = ((even * (even - 1)) +
                (odd * (odd - 1))) / 2;
 
    return ans;
}
 
// Driver code
public static void Main(String[] args)
{
    int n = 5;
    List []graph = new List[n + 1];
    for(int i = 0; i< n + 1; i++)
    {
        graph[i] = new List();
    }
     
    graph[0] = new List{};
    graph[1] = new List{2};
    graph[2] = new List{1, 3};
    graph[3] = new List{2};
    int ans = countOfNodes(graph, n);
    Console.WriteLine(ans);
}
}
 
// This code is contributed by Rajput-Ji


Javascript


输出:

6

时间复杂度: O(V+E)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程