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

📅  最后修改于: 2021-04-17 17:18:45             🧑  作者: Mango

给定二维数组Edges [] [] ,它表示有向无环连通图中一对节点之间的有向边,该有向无环连通图中包含从[1,N]取值的N个节点和代表每个节点权重的数组arr []是找到任何节点及其任何祖先权重之间的最大绝对差。

例子:

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

  • 初始化一个变量,将ans表示为INT_MIN,以存储所需的最大差异。
  • 通过执行以下操作,对给定图执行DFS遍历,以找到节点及其任何祖先权重之间的最大绝对差:
    • 对于每个源节点,例如src ,更新ans的值以分别存储src的权重与currentMincurrentMax之间的绝对差的最大值。
    • 更新为最小currentMin的和源节点SRC的值currentMin的值。
    • currentMax的值更新为currentMax和源节点src的最大值。
    • 现在,递归地遍历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


输出:
10

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