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

📅  最后修改于: 2021-04-22 07:57:06             🧑  作者: Mango

(N – 1) 给定一个树选自N在范围[1 0,N]具有值的节点的边缘,和两个节点XY中,任务是找到在树,使得可能的路径的数量节点X不在路径中的节点Y之前出现。

例子:

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

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

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

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

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

下面是上述方法的实现:

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)