ADVANCED DATA STRUCTURES PROGRAM • LEVEL 20 — ADVANCED GRAPH ALGORITHMS
Reweight Edges for Johnson's Algorithm
Learn how to reweight edges for johnson's algorithm using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
0-1:0 0-2:4 1-2:1 1-3:1 2-3:0
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int edges[][3]={{0,1,-2},{0,2,4},{1,2,3},{1,3,2},{2,3,-1}},potential[]={0,-2,0,-1};
for(int i=0;i<5;i++){int from=edges[i][0],to=edges[i][1],weight=edges[i][2]+potential[from]-potential[to];printf("%d-%d:%d%c",from,to,weight,i==4?'\n':' ');}return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
0-1:0 0-2:4 1-2:1 1-3:1 2-3:0
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Use Bellman–Ford potentials to make every reweighted edge non-negative before repeated Dijkstra searches.
- Display the computed result.
Use Bellman–Ford potentials to make every reweighted edge non-negative before repeated Dijkstra searches.
EFFICIENCY
Time and space complexity
Time complexity
O(VE + V(E log V)) for complete Johnson
Auxiliary space
O(V + E)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
