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

Автор KyRillos_BoshRa, история, 8 лет назад, По-английски

I am trying to solve this problem for a while now but I can't come up with solution better than SPFA from every node which (for sure) gives TLE. so can you help finding a faster solution? thanks in advance.

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

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

Bellman-Ford?

»
8 лет назад, скрыть # |
← Rev. 3  
Проголосовать: нравится +6 Проголосовать: не нравится

The answer is not going to be <insert shortest paths algorithm here>, that would be boring.

Maybe this gives TLE but here is what I would do. First, let's check if there is a negative cycle. If so, output -inf. Now, let dp[u] denote the length of the shortest path that ends with the vertex u. To calculate dp[u] we do this:

initially dp[u] = inf for all u
repeat M times
    for all edges u->v:
        dp[v] = min(dp[v], dp[u] + cost(u, v))

Now, output the minimum of dp[u] over all vertices u.