📜  门| GATE-CS-2014-(Set-1)|第60章(1)

📅  最后修改于: 2023-12-03 15:28:43.739000             🧑  作者: Mango

GATE-CS-2014 Set-1 : Problem 60

Introduction

This problem deals with finding the longest path in a directed acyclic graph (DAG). The problem requires the implementation of the topological sorting algorithm to find the longest path.

Problem Statement

Given a weighted DAG, the longest path in the graph needs to be found, where the length of the path is defined as the sum of the weights of the edges in the path. The input to the algorithm is the adjacency matrix with the weights of the edges. The output is the longest distance from the start node to each node of the graph.

Approach

To solve this problem, we first need to topologically sort the graph, which can be done using the Depth First Search (DFS) algorithm. After the topologically sorting, we can iterate through the nodes in a topologically sorted order and for each node update its neighbors with the longest distance found so far. We initialize the distances to negative infinity and set the distance of the start node to zero.

In the end, we will have the longest distance from the start node to each node of the graph.

Code
import sys
from collections import deque

def topological_sort(graph):
    visited = set()
    stack = deque()

    def dfs(vertex):
        visited.add(vertex)
        for neighbor in graph[vertex]:
            if neighbor not in visited:
                dfs(neighbor)
        stack.append(vertex)

    for vertex in range(len(graph)):
        if vertex not in visited:
            dfs(vertex)

    return list(stack)[::-1]

def longest_path_DAG(graph, start):
    distances = [-sys.maxsize - 1 for _ in range(len(graph))]
    distances[start] = 0
    topological_order = topological_sort(graph)

    for vertex in topological_order:
        for neighbor in graph[vertex]:
            edge_weight = graph[vertex][neighbor]
            new_distance = distances[vertex] + edge_weight
            if new_distance > distances[neighbor]:
                distances[neighbor] = new_distance

    return distances
Complexity Analysis

The time complexity of the above algorithm is O(V+E), where V is the number of vertices in the graph, and E is the number of edges in the graph. The space complexity of the algorithm is O(V), as we need to keep track of the distance of each node from the start node.

Conclusion

In this problem, we have seen how to find the longest path in a directed acyclic graph using the topological sorting algorithm. The algorithm is efficient and works well on large graphs. The implementation of the algorithm requires understanding of the topological sorting algorithm and DFS.