ALuca_Rd's blog

By ALuca_Rd, history, 2 years ago, In English

Given a graph with N nodes with each node numbered from 1 to N and M edges and a target vertex T. Find the number of different ways to reach target vertex T from vertex numbered 1.

2 <= N <= 2 * 10^5, M = min( 2 * 10^5, N * ( N - 1 ) / 2 )

Time limit — 5sec

Compute the answer modulo 10^9 + 7.

  • Vote: I like it
  • +12
  • Vote: I do not like it

| Write comment?
»
2 years ago, # |
  Vote: I like it 0 Vote: I do not like it

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

»
2 years ago, # |
  Vote: I like it +33 Vote: I do not like it

Infinite.

  • »
    »
    2 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Thanks! I didn't thought about that. But if we take the modulo of answer to lets say 10^9 + 7. Then how can we do it.

  • »
    »
    2 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    He forgot to mention, the graph is directed acyclic.

»
2 years ago, # |
Rev. 2   Vote: I like it -8 Vote: I do not like it

Here you can use topological sorting + dp for directed acyclic graph. Link

»
2 years ago, # |
Rev. 2   Vote: I like it +3 Vote: I do not like it

You can find the number of shortest paths from using this.

First, how can we find the length of the shortest path from Vertex 1 to Vertex N? Since the every edge has weight 1, the question can be answered with a BFS (Breadth-First Search) in a total of O(N+M) time.

The original problem can similarly be solved with BFS in a total of O(N+M) time, in which we compute not only the shortest distance from the starting vertex but also the number of the paths accomplishing the distance.

When finding the shortest distance with BFS, we compute the array of shortest distance dist by:

Explanation
Code
»
2 years ago, # |
  Vote: I like it 0 Vote: I do not like it

You can refer to this Blog it may help you — https://www.baeldung.com/cs/graph-number-of-shortest-paths