📌  相关文章
📜  有向无环图 (DAG) 中节点与其祖先之间的最大差异

📅  最后修改于: 2021-10-25 05:15:16             🧑  作者: Mango

给定一个二维数组Edges[][] ,表示有向无环连接图中节点对之间的有向边,该图由N 个节点组成,从[1, N]和一个数组arr[]表示每个节点的权重,任务是找到任何节点与其任何祖先的权重之间的最大绝对差异。

例子:

方法:解决给定问题的思路是对Graph进行DFS遍历,填充从每个节点到其子节点的最大值和最小值,并找到最大绝对差。
请按照以下步骤解决给定的问题:

  • 初始化一个变量,比如ans作为 INT_MIN 来存储所需的最大差异。
  • 通过执行以下操作,对给定图执行 DFS 遍历以找到节点与其任何祖先的权重之间的最大绝对差异:
    • 对于每个源节点,比如src ,更新ans的值以分别存储srccurrentMincurrentMax的权重之间的绝对差值的最大值。
    • currentMin的值更新为currentMin和源节点src值的最小值。
    • 更新为最大currentMax的和源节点SRC的值currentMax的值。
    • 现在,递归遍历src的子节点并将currentMaxcurrentMin 的值更新为DFS(child, Adj, ans, currentMin, currentMax)
  • 完成上述步骤后,打印ans的值作为结果的最大差值。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to perform DFS
// Traversal on the given graph
void DFS(int src, vector Adj[],
         int& ans, int arr[],
         int currentMin, int currentMax)
{
 
    // Update the value of ans
    ans = max(
        ans, max(abs(
                     currentMax - arr[src - 1]),
                 abs(currentMin - arr[src - 1])));
 
    // Update the currentMin and currentMax
    currentMin = min(currentMin,
                     arr[src - 1]);
 
    currentMax = min(currentMax,
                     arr[src - 1]);
 
    // Traverse the adjacency
    // list of the node src
    for (auto& child : Adj[src]) {
 
        // Recursively call
        // for the child node
        DFS(child, Adj, ans, arr,
            currentMin, currentMax);
    }
}
 
// Function to calculate maximum absolute
// difference between a node and its ancestor
void getMaximumDifference(int Edges[][2],
                          int arr[], int N,
                          int M)
{
 
    // Stores the adjacency list of graph
    vector Adj[N + 1];
 
    // Create Adjacency list
    for (int i = 0; i < M; i++) {
        int u = Edges[i][0];
        int v = Edges[i][1];
 
        // Add a directed edge
        Adj[u].push_back(v);
    }
 
    int ans = 0;
 
    // Perform DFS Traversal
    DFS(1, Adj, ans, arr,
        arr[0], arr[0]);
 
    // Print the maximum
    // absolute difference
    cout << ans;
}
 
// Driver Code
int main()
{
    int N = 5, M = 4;
    int Edges[][2]
        = { { 1, 2 }, { 2, 3 },
            { 4, 5 }, { 1, 3 } };
    int arr[] = { 13, 8, 3, 15, 18 };
 
    getMaximumDifference(Edges, arr, N, M);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
     
static int ans;
 
// Function to perform DFS
// Traversal on the given graph
static void DFS(int src,
                ArrayList > Adj,
                int arr[], int currentMin,
                int currentMax)
{
     
    // Update the value of ans
    ans = Math.max(ans,
          Math.max(Math.abs(currentMax - arr[src - 1]),
                   Math.abs(currentMin - arr[src - 1])));
 
    // Update the currentMin and currentMax
    currentMin = Math.min(currentMin, arr[src - 1]);
 
    currentMax = Math.min(currentMax, arr[src - 1]);
 
    // Traverse the adjacency
    // list of the node src
    for(Integer child : Adj.get(src))
    {
         
        // Recursively call
        // for the child node
        DFS(child, Adj, arr, currentMin, currentMax);
    }
}
 
// Function to calculate maximum absolute
// difference between a node and its ancestor
static void getMaximumDifference(int Edges[][],
                                 int arr[], int N,
                                 int M)
{
    ans = 0;
     
    // Stores the adjacency list of graph
    ArrayList> Adj = new ArrayList<>();
 
    for(int i = 0; i < N + 1; i++)
        Adj.add(new ArrayList<>());
 
    // Create Adjacency list
    for(int i = 0; i < M; i++)
    {
        int u = Edges[i][0];
        int v = Edges[i][1];
 
        // Add a directed edge
        Adj.get(u).add(v);
    }
 
    // Perform DFS Traversal
    DFS(1, Adj, arr, arr[0], arr[0]);
 
    // Print the maximum
    // absolute difference
    System.out.println(ans);
}
 
// Driver code
public static void main(String[] args)
{
    int N = 5, M = 4;
    int Edges[][] = { { 1, 2 }, { 2, 3 },
                      { 4, 5 }, { 1, 3 } };
    int arr[] = { 13, 8, 3, 15, 18 };
 
    getMaximumDifference(Edges, arr, N, M);
}
}
 
// This code is contributed by offbeat


Python3
# Python3 program for the above approach
ans = 0
 
# Function to perform DFS
# Traversal on the given graph
def DFS(src, Adj, arr, currentMin, currentMax):
     
    # Update the value of ans
    global ans
    ans = max(ans, max(abs(currentMax - arr[src - 1]),
                       abs(currentMin - arr[src - 1])))
 
    # Update the currentMin and currentMax
    currentMin = min(currentMin, arr[src - 1])
 
    currentMax = min(currentMax, arr[src - 1])
 
    # Traverse the adjacency
    # list of the node src
    for child in Adj[src]:
         
        # Recursively call
        # for the child node
        DFS(child, Adj, arr, currentMin, currentMax)
 
# Function to calculate maximum absolute
# difference between a node and its ancestor
def getMaximumDifference(Edges, arr, N, M):
     
    global ans
     
    # Stores the adjacency list of graph
    Adj = [[] for i in range(N + 1)]
 
    # Create Adjacency list
    for i in range(M):
        u = Edges[i][0]
        v = Edges[i][1]
 
        # Add a directed edge
        Adj[u].append(v)
 
    # Perform DFS Traversal
    DFS(1, Adj, arr, arr[0], arr[0])
 
    # Print the maximum
    # absolute difference
    print(ans)
 
# Driver Code
if __name__ == '__main__':
     
    N = 5
    M = 4
    Edges = [[1, 2], [2, 3], [4, 5], [1, 3]]
    arr =  [13, 8, 3, 15, 18]
     
    getMaximumDifference(Edges, arr, N, M)
 
# This code is contributed by ipg2016107


Javascript


输出:
10

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

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