The time limit is 2 sec, it means the program should have near about ~10^6 iterations. See the limits of V = 10000
and e = 100000
. This means an algorithm of O(V) or O(E) or O(V + E) or even O(E + VlogV)
will easily compute your requirement well in given time.
Note E + Vlogv ~ (100000 + ~132877) which is less than 10^6
// This 10^6 limit is quit good for processors with 10^9 Hz frequency. So, even if your algo has 1000 instructions for each iteration, you will be in safe zone.
So, here is the proposed algorithm:
You will build the graph in O(E)
. Use Adjacency list data structure to represent the graph.
-> While building this data structure, store indegree of each vertex and also store count of vertices.
countV := V;
foreach edge_i
inDegree[to] := inDegree[to] + 1;
Check if there is cycle in the graph in O(V + E)
.
if no vertex with indegree = 0 and countV = 0
graph has no cycle
else if no vertex with indegree = 0 and countV != 0
graph has cycle
else select any vertex having 0 indegree
countV := countV - 1;
decrease all its directed neighbours' inDegree by 1.
So if you get a cycle, your answer is directly infinite.
Make a BFS or DFS to get whether the ending vertex
is reachable from beginning vertex
or not. This can be done in O(V + E)
or even O(E)
. Let us take O(V + E)
. If not reacable your answer is directly 0.
Now, apply dijkstra but in relax condition, just check the opposite. i.e in the pseudocode given here, instead of doing
if alt < dist[v]:
dist[v] := alt;
do
if alt > dist[v]:
dist[v] := alt;
This can be done in O(E + VlogV)
. Hence overall complexity of the solution will be O(E + VlogV)
which is well in constraints.