Reputation: 31
There are N cities and there are M bidirectional roads connected to them , I have to find the shortest path between two fixed cities A and B.
But the problem is there are Q queries given such that path between two cities is blocked , i have to find the shortest path in each Q queries.
My time Complexity in my brute force Algorithm is O(QNlogN) which give me Time Limit Exceeded Error, How can i improve my solution please Help
Pseduo Code:
for u in Q:
cin>>a>>b;
graph[a][b] = graph[b][a] = INFINITY VALUE
dijkstra algorithm();
cout<<Distance[D]<<endl;
MY CODE Which Is giving me Time Limit Exceeded Error
Plese Help How can I improve my algorithm ?
Upvotes: 3
Views: 265
Reputation: 33509
The paper Vickrey Prices and Shortest Paths: What is an edge worth? by John Hershberger and Subhash Suri shows how to solve this problem in time O(NlogN+M) where N is the number of vertices, and M is the number of edges.
This allows you to precalculate the M answers depending on which road is blocked, so you can answer each query in O(1), for a total complexity of O(NlogN+M+Q).
Upvotes: 3