📌  相关文章
📜  计算树中所有可能的路径,使得节点 X 不会出现在节点 Y 之前

📅  最后修改于: 2021-09-06 06:21:45             🧑  作者: Mango

给定一个由N 个节点组成的树,这些节点的值在[0, N – 1](N – 1) 条边的范围内,以及两个节点XY ,任务是找到树中可能路径的数量,使得节点X不会出现在路径中的节点Y之前。

例子:

方法:
这个想法是找到节点对的组合,在连接它们的路径中,节点 X 总是出现在节点 Y 之前。然后,从可能的节点对的总数中减去这些对的数量= N C 2 。将节点Y视为根节点。现在,首先遇到X然后遇到Y 的任何路径都从节点X的子树中的节点开始,并在节点Y的子树中的一个节点处结束,但不在节点W的子树中,其中W是节点Y位于这些路径中的XY之间。

因此,最终答案可以通过以下方式计算:

如果将Y作为树的根。然后, size_of_subtree(Y) = N

请按照以下步骤解决问题:

  1. 初始化数组subtree_size []visited []check_subtree []每个大小为N + 1 。将visited [] 的元素初始化为0
  2. Y为根节点执行DFS遍历,为每个节点填充check_subtree[]subtree_size[]check_subtree[]检查当前节点的子树是否包含节点X。
  3. 找到Y的子节点(比如节点 v) ,它位于从XY的路径中。初始化一个整数变量说差异
  4. 将(节点总数 – subtree_size[v] )分配给差异
  5. 返回(N * (N – 1) ) – (subtree_size[A] * (difference))作为答案。

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
#include 
#define int long long int
using namespace std;
  
// Maximum number of nodes
const int NN = 3e5;
  
// Vector to store the tree
vector G[NN + 1];
  
// Function to perform DFS Traversal
int dfs(int node, int A, int* subtree_size,
        int* visited, int* check_subtree)
{
    // Mark the node as visited
    visited[node] = true;
  
    // Initialize the subtree size
    // of each node as 1
    subtree_size[node] = 1;
  
    // If the node is same as A
    if (node == A) {
  
        // Mark check_subtree[node] as true
        check_subtree[node] = true;
    }
  
    // Otherwise
    else
        check_subtree[node] = false;
  
    // Iterate over the adjacent nodes
    for (int v : G[node]) {
  
        // If the adjacent node
        // is not visited
        if (!visited[v]) {
  
            // Update the size of the
            // subtree of current node
            subtree_size[node]
                += dfs(v, A, subtree_size,
                       visited, check_subtree);
  
            // Check if the subtree of
            // current node contains node A
            check_subtree[node] = check_subtree[node]
                                  | check_subtree[v];
        }
    }
  
    // Return size of subtree of node
    return subtree_size[node];
}
  
// Function to add edges to the tree
void addedge(int node1, int node2)
{
  
    G[node1].push_back(node2);
    G[node2].push_back(node1);
}
  
// Function to calculate the number of
// possible paths
int numberOfPairs(int N, int B, int A)
{
    // Stores the size of subtree
    // of each node
    int subtree_size[N + 1];
  
    // Stores which nodes are
    // visited
    int visited[N + 1];
  
    // Initialise all nodes as unvisited
    memset(visited, 0, sizeof(visited));
  
    // Stores if the subtree of
    // a node contains node A
    int check_subtree[N + 1];
  
    // DFS Call
    dfs(B, A, subtree_size,
        visited, check_subtree);
  
    // Stores the difference between
    // total number of nodes and
    // subtree size of an immediate
    // child of Y lies between the
    // path from A to B
    int difference;
  
    // Iterate over the adjacent nodes B
    for (int v : G[B]) {
  
        // If the node is in the path
        // from A to B
        if (check_subtree[v]) {
  
            // Calcualte the difference
            difference = N - subtree_size[v];
  
            break;
        }
    }
  
    // Return the final answer
    return (N * (N - 1))
           - difference * (subtree_size[A]);
}
  
// Driver Code
int32_t main()
{
    int N = 9;
  
    int X = 5, Y = 3;
  
    // Insert Edges
    addedge(0, 2);
    addedge(1, 2);
    addedge(2, 3);
    addedge(3, 4);
    addedge(4, 6);
    addedge(4, 5);
    addedge(5, 7);
    addedge(5, 8);
  
    cout << numberOfPairs(N, Y, X);
  
    return 0;
}


Java
// Java Program to implement
// the above approach
import java.util.*;
class GFG{
  
// Maximum number of nodes
static int NN = (int) 3e5;
  
// Vector to store the tree
static Vector []G = new Vector[NN + 1];
  
// Function to perform DFS Traversal
static int dfs(int node, int A, int[] subtree_size,
               int[] visited, int[] check_subtree)
{
    // Mark the node as visited
    visited[node] = 1;
  
    // Initialize the subtree size
    // of each node as 1
    subtree_size[node] = 1;
  
    // If the node is same as A
    if (node == A) 
    {
  
        // Mark check_subtree[node] as true
        check_subtree[node] = 1;
    }
  
    // Otherwise
    else
        check_subtree[node] = 0;
  
    // Iterate over the adjacent nodes
    for (int v : G[node])
    {
  
        // If the adjacent node
        // is not visited
        if (visited[v] == 0) 
        {
  
            // Update the size of the
            // subtree of current node
            subtree_size[node] += dfs(v, A, subtree_size,
                                      visited, check_subtree);
  
            // Check if the subtree of
            // current node contains node A
            check_subtree[node] = check_subtree[node] | 
                                    check_subtree[v];
        }
    }
  
    // Return size of subtree of node
    return subtree_size[node];
}
  
// Function to add edges to the tree
static void addedge(int node1, int node2)
{
    G[node1].add(node2);
    G[node2].add(node1);
}
  
// Function to calculate the number of
// possible paths
static int numberOfPairs(int N, int B, int A)
{
    // Stores the size of subtree
    // of each node
    int []subtree_size = new int[N + 1];
  
    // Stores which nodes are
    // visited
    int []visited = new int[N + 1];
  
  
    // Stores if the subtree of
    // a node contains node A
    int []check_subtree = new int[N + 1];
  
    // DFS Call
    dfs(B, A, subtree_size,
        visited, check_subtree);
  
    // Stores the difference between
    // total number of nodes and
    // subtree size of an immediate
    // child of Y lies between the
    // path from A to B
    int difference = 0;
  
    // Iterate over the adjacent nodes B
    for (int v : G[B]) 
    {
  
        // If the node is in the path
        // from A to B
        if (check_subtree[v] > 0)
        {
  
            // Calcualte the difference
            difference = N - subtree_size[v];
  
            break;
        }
    }
  
    // Return the final answer
    return (N * (N - 1)) - 
              difference * (subtree_size[A]);
}
  
// Driver Code
public static void main(String[] args)
{
    int N = 9;
  
    int X = 5, Y = 3;
      
    for (int i = 0; i < G.length; i++)
        G[i] = new Vector();
    
    // Insert Edges
    addedge(0, 2);
    addedge(1, 2);
    addedge(2, 3);
    addedge(3, 4);
    addedge(4, 6);
    addedge(4, 5);
    addedge(5, 7);
    addedge(5, 8);
  
    System.out.print(numberOfPairs(N, Y, X));
}
}
  
// This code is contributed by sapnasingh4991


Python3
# Python3 program to implement
# the above approach
  
# Maximum number of nodes
NN = int(3e5)
  
# Vector to store the tree
G = []
for i in range(NN + 1):
    G.append([])
  
# Function to perform DFS Traversal
def dfs(node, A, subtree_size, 
        visited, check_subtree):
  
    # Mark the node as visited
    visited[node] = True
  
    # Initialize the subtree size
    # of each node as 1
    subtree_size[node] = 1
  
    # If the node is same as A
    if (node == A):
  
        # Mark check_subtree[node] as true
        check_subtree[node] = True
  
    # Otherwise
    else:
        check_subtree[node] = False
  
    # Iterate over the adjacent nodes
    for v in G[node]:
  
        # If the adjacent node
        # is not visited
        if (not visited[v]):
  
            # Update the size of the
            # subtree of current node
            subtree_size[node] += dfs(v, A,
                                      subtree_size,
                                      visited, 
                                      check_subtree)
  
            # Check if the subtree of
            # current node contains node A
            check_subtree[node] = (check_subtree[node] | 
                                   check_subtree[v])
  
    # Return size of subtree of node
    return subtree_size[node]
  
# Function to add edges to the tree
def addedge(node1, node2):
  
    G[node1] += [node2]
    G[node2] += [node1]
  
# Function to calculate the number of
# possible paths
def numberOfPairs(N, B, A):
  
    # Stores the size of subtree
    # of each node
    subtree_size = [0] * (N + 1)
  
    # Stores which nodes are
    # visited
    visited = [0] * (N + 1)
  
    # Stores if the subtree of
    # a node contains node A
    check_subtree = [0] * (N + 1)
  
    # DFS Call
    dfs(B, A, subtree_size,
        visited, check_subtree)
  
    # Stores the difference between
    # total number of nodes and
    # subtree size of an immediate
    # child of Y lies between the
    # path from A to B
    difference = 0
  
    # Iterate over the adjacent nodes B
    for v in G[B]:
  
        # If the node is in the path
        # from A to B
        if (check_subtree[v]):
  
            # Calcualte the difference
            difference = N - subtree_size[v]
            break
  
    # Return the final answer
    return ((N * (N - 1)) - 
               difference * (subtree_size[A]))
  
# Driver Code
N = 9
X = 5
Y = 3
  
# Insert Edges 
addedge(0, 2)
addedge(1, 2)
addedge(2, 3)
addedge(3, 4)
addedge(4, 6)
addedge(4, 5)
addedge(5, 7)
addedge(5, 8)
  
# Function call
print(numberOfPairs(N, Y, X))
  
# This code is contributed by Shivam Singh


C#
// C# Program to implement
// the above approach
using System;
using System.Collections.Generic;
  
class GFG{
  
// Maximum number of nodes
static int NN = (int) 3e5;
  
// List to store the tree
static List []G = new List[NN + 1];
  
// Function to perform DFS Traversal
static int dfs(int node, int A, int[] subtree_size,
               int[] visited, int[] check_subtree)
{
    // Mark the node as visited
    visited[node] = 1;
  
    // Initialize the subtree size
    // of each node as 1
    subtree_size[node] = 1;
  
    // If the node is same as A
    if (node == A) 
    {
  
        // Mark check_subtree[node] as true
        check_subtree[node] = 1;
    }
  
    // Otherwise
    else
        check_subtree[node] = 0;
  
    // Iterate over the adjacent nodes
    foreach (int v in G[node])
    {
  
        // If the adjacent node
        // is not visited
        if (visited[v] == 0) 
        {
  
            // Update the size of the
            // subtree of current node
            subtree_size[node] += dfs(v, A, subtree_size,
                                      visited, check_subtree);
  
            // Check if the subtree of
            // current node contains node A
            check_subtree[node] = check_subtree[node] | 
                                    check_subtree[v];
        }
    }
  
    // Return size of subtree of node
    return subtree_size[node];
}
  
// Function to add edges to the tree
static void addedge(int node1, int node2)
{
    G[node1].Add(node2);
    G[node2].Add(node1);
}
  
// Function to calculate the number of
// possible paths
static int numberOfPairs(int N, int B, int A)
{
    // Stores the size of subtree
    // of each node
    int []subtree_size = new int[N + 1];
  
    // Stores which nodes are
    // visited
    int []visited = new int[N + 1];
  
  
    // Stores if the subtree of
    // a node contains node A
    int []check_subtree = new int[N + 1];
  
    // DFS Call
    dfs(B, A, subtree_size,
        visited, check_subtree);
  
    // Stores the difference between
    // total number of nodes and
    // subtree size of an immediate
    // child of Y lies between the
    // path from A to B
    int difference = 0;
  
    // Iterate over the adjacent nodes B
    foreach (int v in G[B]) 
    {
  
        // If the node is in the path
        // from A to B
        if (check_subtree[v] > 0)
        {
  
            // Calcualte the difference
            difference = N - subtree_size[v];
  
            break;
        }
    }
  
    // Return the readonly answer
    return (N * (N - 1)) - 
              difference * (subtree_size[A]);
}
  
// Driver Code
public static void Main(String[] args)
{
    int N = 9;
  
    int X = 5, Y = 3;
      
    for (int i = 0; i < G.Length; i++)
        G[i] = new List();
    
    // Insert Edges
    addedge(0, 2);
    addedge(1, 2);
    addedge(2, 3);
    addedge(3, 4);
    addedge(4, 6);
    addedge(4, 5);
    addedge(5, 7);
    addedge(5, 8);
  
    Console.Write(numberOfPairs(N, Y, X));
}
}
  
  
// This code is contributed by sapnasingh4991


输出:
60





时间复杂度: O(N)
辅助空间: O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live