Пожалуйста, прочтите новое правило об ограничении использования AI-инструментов. ×

Блог пользователя peoplePleaser

Автор peoplePleaser, история, 4 года назад, По-английски

Does there exist a way an efficient method to find the longest path in a DAG among all possible paths? I know how to solve this in $$$O(V*(V+E))$$$ by considering each vertex as the source, and then using topo sort, and iterating over the vertices in that order and update the distances accordingly. Any suggestions/help would be appreciated or maybe we can prove there doesn't exist a faster method. Thanks!

  • Проголосовать: нравится
  • +4
  • Проголосовать: не нравится

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Auto comment: topic has been updated by peoplePleaser (previous revision, new revision, compare).

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Auto comment: topic has been updated by peoplePleaser (previous revision, new revision, compare).

»
4 года назад, # |
  Проголосовать: нравится +3 Проголосовать: не нравится

The algorithm you described should be $$$O(V+E)$$$, because you can just relax each edge once in your topo-sort order.

  • »
    »
    4 года назад, # ^ |
      Проголосовать: нравится +3 Проголосовать: не нравится

    It's $$$O(V+E)$$$ if we fix the source vertex, right? but we need to find the longest path over all possible paths.

    • »
      »
      »
      4 года назад, # ^ |
        Проголосовать: нравится +6 Проголосовать: не нравится

      Just initialize all vertices to have value 0 instead of -INF; alternatively, make a super-source that connects to all vertices.

      • »
        »
        »
        »
        4 года назад, # ^ |
          Проголосовать: нравится +3 Проголосовать: не нравится

        Thanks, I thought of this solution. But how to handle the case when all weights are negative? We will always end up with a value of zero, right?

        • »
          »
          »
          »
          »
          4 года назад, # ^ |
          Rev. 2   Проголосовать: нравится +3 Проголосовать: не нравится

          You can store longest non-empty path, in which case you relax $$$val[v] = \max(val[v], \max(val[u], 0) + e)$$$

          • »
            »
            »
            »
            »
            »
            4 года назад, # ^ |
              Проголосовать: нравится +3 Проголосовать: не нравится

            Thanks got it!

            My bad! I am such a fool, if all weights are negative, the answer is the largest (least negative) weight edge.