- Recently I came across a new idea to solve graph-related problems using segment trees, I would like to discuss the same with a problem.
Problem:
Given a graph $$$G$$$ with $$$N$$$ nodes and many edges (around $$$O(N^2)$$$), the goal is to perform Dijkstra algorithm on this dense graph and find out the shortest path from node 1 to all other nodes.
The edges are given in a compressed format. The input follows $$$M$$$ lines. Each of the M lines consists of 4 integers U Lx Rx C
meaning there are edges from node U
to all other nodes in range [Lx , Rx]
with cost C
.
Example:
For N = 6
, the edge-group U = 1 , Lx = 3 , Rx = 5 , C = 2
Looks like:
Constraints:
- $$$1 \le N \le 10^5$$$
- $$$1 \le M \le 10^5$$$
- $$$1 \le U \le N$$$
- $$$1 \le Lx \le Rx \le N$$$
- $$$1 \le C \le 10^9$$$
Initial Thought Process:
- The main problem faced here is that in the worst case, we have plenty of edges $$$O(N^2)$$$, performing Dijkstra in this dense graph would lead to time complexity $$$O(N^2 log(N))$$$ which would lead to TLE. Also, it is not possible to store all edges in adjacency list, which would lead to MLE.
- So we have to seek out some ways to reduce the number of edges so that time complexity can be improved.
- Our solution proceeds like this, we first try to convert this dense graph to a sparse graph with less number of edges and then perform Dijkstra Algorithm to find our answer.
Segment Tree as a structure:
One main observation in this problem is that we add