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.

AdvancedAdvanced graphsGraph optimization

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

ads-johnson-reweighting.c
Open in compiler
#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;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

0-1:0 0-2:4 1-2:1 1-3:1 2-3:0
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Use Bellman–Ford potentials to make every reweighted edge non-negative before repeated Dijkstra searches.
  3. 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.