Given a weighted undirected graph T consisting of nodes valued [0, N – 1] and an array Edges[][3] of type {u, v, w} that denotes an edge between vertices u and v having weight w. The task is to find the sum of all pair shortest paths in the given tree.
Examples:
Input: N = 3, Edges[][] = {{0, 2, 15}, {1, 0, 90}}
Output: 210
Explanation:
Sum of weights of path between nodes 0 and 1 = 90
Sum of weights of path between nodes 0 and 2 = 15
Sum of weights of path between nodes 1 and 2 = 105
Hence, sum = 90 + 15 + 105
Input: N = 4, Edges[][] = {{0, 1, 1}, {1, 2, 2}, {2, 3, 3}}
Output: 20
Explanation:
Sum of weights of path between nodes 0 and 1 = 1
Sum of weights of path between nodes 0 and 2 = 3
Sum of weights of path between nodes 0 and 3 = 6
Sum of weights of path between nodes 1 and 2 = 2
Sum of weights of path between nodes 1 and 3 = 5
Sum of weights of path between nodes 2 and 3 = 3
Hence, sum = 1 + 3 + 6 + 2 + 5 + 3 = 20.
Naive Approach: The simplest approach is to find the shortest path between every pair of vertices using the Floyd Warshall Algorithm. After precomputing the cost of the shortest path between every pair of nodes, print the sum of all the shortest paths.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
#define INF 99999
int floyd_warshall( int * graph, int V)
{
int dist[V][V], i, j, k;
for (i = 0; i < V; i++) {
for (j = 0; j < V; j++) {
dist[i][j] = *((graph + i * V) + j);
}
}
for (k = 0; k < V; k++) {
for (i = 0; i < V; i++) {
for (j = 0; j < V; j++) {
if (dist[i][k]
+ dist[k][j]
< dist[i][j]) {
dist[i][j]
= dist[i][k]
+ dist[k][j];
}
}
}
}
int sum = 0;
for (i = 0; i < V; i++) {
for (j = i + 1; j < V; j++) {
sum += dist[i][j];
}
}
return sum;
}
int sumOfshortestPath( int N, int E,
int edges[][3])
{
int g[N][N];
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < N; j++) {
g[i][j] = INF;
}
}
for ( int i = 0; i < E; i++) {
int u = edges[i][0];
int v = edges[i][1];
int w = edges[i][2];
g[u][v] = w;
g[v][u] = w;
}
return floyd_warshall(( int *)g, N);
}
int main()
{
int N = 4;
int E = 3;
int Edges[][3]
= { { 0, 1, 1 }, { 1, 2, 2 },
{ 2, 3, 3 } };
cout << sumOfshortestPath(N, E, Edges);
return 0;
}
|
Java
class GFG{
static final int INF = 99999 ;
static int floyd_warshall( int [][] graph,
int V)
{
int [][]dist = new int [V][V];
int i, j, k;
for (i = 0 ; i < V; i++)
{
for (j = 0 ; j < V; j++)
{
dist[i][j] = graph[i][j];
}
}
for (k = 0 ; k < V; k++)
{
for (i = 0 ; i < V; i++)
{
for (j = 0 ; j < V; j++)
{
if (dist[i][k] + dist[k][j] <
dist[i][j])
{
dist[i][j] = dist[i][k] +
dist[k][j];
}
}
}
}
int sum = 0 ;
for (i = 0 ; i < V; i++)
{
for (j = i + 1 ; j < V; j++)
{
sum += dist[i][j];
}
}
return sum;
}
static int sumOfshortestPath( int N, int E,
int edges[][])
{
int [][]g = new int [N][N];
for ( int i = 0 ; i < N; i++)
{
for ( int j = 0 ; j < N; j++)
{
g[i][j] = INF;
}
}
for ( int i = 0 ; i < E; i++)
{
int u = edges[i][ 0 ];
int v = edges[i][ 1 ];
int w = edges[i][ 2 ];
g[u][v] = w;
g[v][u] = w;
}
return floyd_warshall(g, N);
}
public static void main(String[] args)
{
int N = 4 ;
int E = 3 ;
int Edges[][] = {{ 0 , 1 , 1 }, { 1 , 2 , 2 },
{ 2 , 3 , 3 }};
System.out.print(
sumOfshortestPath(N, E, Edges));
}
}
|
Python3
INF = 99999
def floyd_warshall(graph, V):
dist = [[ 0 for i in range (V)]
for i in range (V)]
for i in range (V):
for j in range (V):
dist[i][j] = graph[i][j]
for k in range (V):
for i in range (V):
for j in range (V):
if (dist[i][k] + dist[k][j] < dist[i][j]):
dist[i][j] = dist[i][k] + dist[k][j]
sum = 0
for i in range (V):
for j in range (i + 1 , V):
sum + = dist[i][j]
return sum
def sumOfshortestPath(N, E,edges):
g = [[INF for i in range (N)]
for i in range (N)]
for i in range (E):
u = edges[i][ 0 ]
v = edges[i][ 1 ]
w = edges[i][ 2 ]
g[u][v] = w
g[v][u] = w
return floyd_warshall(g, N)
if __name__ = = '__main__' :
N = 4
E = 3
Edges = [ [ 0 , 1 , 1 ],
[ 1 , 2 , 2 ],
[ 2 , 3 , 3 ] ]
print (sumOfshortestPath(N, E, Edges))
|
C#
using System;
class GFG{
static readonly int INF = 99999;
static int floyd_warshall( int [,] graph,
int V)
{
int [,]dist = new int [V, V];
int i, j, k;
for (i = 0; i < V; i++)
{
for (j = 0; j < V; j++)
{
dist[i, j] = graph[i, j];
}
}
for (k = 0; k < V; k++)
{
for (i = 0; i < V; i++)
{
for (j = 0; j < V; j++)
{
if (dist[i, k] + dist[k, j] <
dist[i, j])
{
dist[i, j] = dist[i, k] +
dist[k, j];
}
}
}
}
int sum = 0;
for (i = 0; i < V; i++)
{
for (j = i + 1; j < V; j++)
{
sum += dist[i, j];
}
}
return sum;
}
static int sumOfshortestPath( int N, int E,
int [,]edges)
{
int [,]g = new int [N, N];
for ( int i = 0; i < N; i++)
{
for ( int j = 0; j < N; j++)
{
g[i, j] = INF;
}
}
for ( int i = 0; i < E; i++)
{
int u = edges[i, 0];
int v = edges[i, 1];
int w = edges[i, 2];
g[u, v] = w;
g[v, u] = w;
}
return floyd_warshall(g, N);
}
public static void Main(String[] args)
{
int N = 4;
int E = 3;
int [,]Edges = {{0, 1, 1},
{1, 2, 2},
{2, 3, 3}};
Console.Write(sumOfshortestPath(N,
E, Edges));
}
}
|
Javascript
<script>
let INF = 99999;
function floyd_warshall(graph,V)
{
let dist = new Array(V);
for (let i = 0; i < V; i++)
{
dist[i] = new Array(V);
}
let i, j, k;
for (i = 0; i < V; i++)
{
for (j = 0; j < V; j++)
{
dist[i][j] = graph[i][j];
}
}
for (k = 0; k < V; k++)
{
for (i = 0; i < V; i++)
{
for (j = 0; j < V; j++)
{
if (dist[i][k] + dist[k][j] <
dist[i][j])
{
dist[i][j] = dist[i][k] +
dist[k][j];
}
}
}
}
let sum = 0;
for (i = 0; i < V; i++)
{
for (j = i + 1; j < V; j++)
{
sum += dist[i][j];
}
}
return sum;
}
function sumOfshortestPath(N,E,edges)
{
let g = new Array(N);
for (let i = 0; i < N; i++)
{
g[i] = new Array(N);
for (let j = 0; j < N; j++)
{
g[i][j] = INF;
}
}
for (let i = 0; i < E; i++)
{
let u = edges[i][0];
let v = edges[i][1];
let w = edges[i][2];
g[u][v] = w;
g[v][u] = w;
}
return floyd_warshall(g, N);
}
let N = 4;
let E = 3;
let Edges = [[0, 1, 1], [1, 2, 2],
[2, 3, 3]];
document.write(
sumOfshortestPath(N, E, Edges));
</script>
|
Time Complexity:O(N3), where N is the number of vertices.
Auxiliary Space: O(N)
Efficient Approach: The idea is to use the DFS algorithm, using the DFS, for each vertex, the cost to visit every other vertex from this vertex can be found in linear time. Follow the below steps to solve the problem:
- Traverse the nodes 0 to N – 1.
- For each node i, find the sum of the cost to visit every other vertex using DFS where the source will be node i, and let’s denote this sum by Si.
- Now, calculate S = S0 + S1 + … + SN-1. and divide S by 2 because every path is calculated twice.
- After completing the above steps, print the value of sum S obtained.
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
void dfs( int v, int p,
vector<pair< int , int >> t[],
int h, int ans[])
{
for (pair< int , int > u : t[v])
{
if (u.first == p)
continue ;
dfs(u.first, v, t, h + u.second, ans);
}
ans[v] = h;
}
int solve( int n, int edges[][3])
{
vector<pair< int , int >> t[n];
for ( int i = 0; i < n - 1; i++)
{
t[edges[i][0]].push_back({edges[i][1],
edges[i][2]});
t[edges[i][1]].push_back({edges[i][0],
edges[i][2]});
}
int sum = 0;
for ( int i = 0; i < n; i++)
{
int ans[n];
dfs(i, -1, t, 0, ans);
for ( int j = 0; j < n; j++)
sum += ans[j];
}
return sum / 2;
}
int main()
{
int N = 4;
int edges[][3] = { { 0, 1, 1 },
{ 1, 2, 2 },
{ 2, 3, 3 } };
cout << solve(N, edges) << endl;
return 0;
}
|
Java
import java.io.*;
import java.awt.*;
import java.io.*;
import java.util.*;
@SuppressWarnings ( "unchecked" )
class GFG {
static void dfs( int v, int p,
ArrayList<Point> t[],
int h, int ans[])
{
for (Point u : t[v]) {
if (u.x == p)
continue ;
dfs(u.x, v, t, h + u.y, ans);
}
ans[v] = h;
}
static int solve( int n, int edges[][])
{
ArrayList<Point> t[]
= new ArrayList[n];
for ( int i = 0 ; i < n; i++)
t[i] = new ArrayList<>();
for ( int i = 0 ; i < n - 1 ; i++) {
t[edges[i][ 0 ]].add(
new Point(edges[i][ 1 ],
edges[i][ 2 ]));
t[edges[i][ 1 ]].add(
new Point(edges[i][ 0 ],
edges[i][ 2 ]));
}
int sum = 0 ;
for ( int i = 0 ; i < n; i++) {
int ans[] = new int [n];
dfs(i, - 1 , t, 0 , ans);
for ( int j = 0 ; j < n; j++)
sum += ans[j];
}
return sum / 2 ;
}
public static void main(String[] args)
{
int N = 4 ;
int edges[][]
= new int [][] { { 0 , 1 , 1 },
{ 1 , 2 , 2 },
{ 2 , 3 , 3 } };
System.out.println(solve(N, edges));
}
}
|
Python3
def dfs(v, p, t, h, ans):
for u in t[v]:
if (u[ 0 ] = = p):
continue
dfs(u[ 0 ], v, t, h + u[ 1 ], ans)
ans[v] = h
def solve(n, edges):
t = [[] for i in range (n)]
for i in range (n - 1 ):
t[edges[i][ 0 ]].append([edges[i][ 1 ],
edges[i][ 2 ]])
t[edges[i][ 1 ]].append([edges[i][ 0 ],
edges[i][ 2 ]])
sum = 0
for i in range (n):
ans = [ 0 for i in range (n)]
dfs(i, - 1 , t, 0 , ans)
for j in range (n):
sum + = ans[j]
return sum / / 2
if __name__ = = "__main__" :
N = 4
edges = [ [ 0 , 1 , 1 ],
[ 1 , 2 , 2 ],
[ 2 , 3 , 3 ] ]
print (solve(N, edges))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void dfs( int v, int p,
List<Tuple< int , int >> []t,
int h, int []ans)
{
foreach (Tuple< int , int > u in t[v])
{
if (u.Item1 == p)
continue ;
dfs(u.Item1, v, t,
h + u.Item2, ans);
}
ans[v] = h;
}
static int solve( int n, int [,]edges)
{
List<Tuple< int ,
int >> []t = new List<Tuple< int ,
int >>[n];
for ( int i = 0; i < n; i++)
t[i] = new List<Tuple< int , int >>();
for ( int i = 0; i < n - 1; i++)
{
t[edges[i, 0]].Add(
new Tuple< int , int >(edges[i, 1],
edges[i, 2]));
t[edges[i, 1]].Add(
new Tuple< int , int >(edges[i, 0],
edges[i, 2]));
}
int sum = 0;
for ( int i = 0; i < n; i++)
{
int []ans = new int [n];
dfs(i, -1, t, 0, ans);
for ( int j = 0; j < n; j++)
sum += ans[j];
}
return sum / 2;
}
public static void Main(String[] args)
{
int N = 4;
int [,]edges = new int [,] { { 0, 1, 1 },
{ 1, 2, 2 },
{ 2, 3, 3 } };
Console.WriteLine(solve(N, edges));
}
}
|
Javascript
<script>
function dfs(v, p, t, h, ans)
{
for (let u = 0; u < t[v].length; u++)
{
if (t[v][u][0] == p)
continue ;
dfs(t[v][u][0], v, t,
h + t[v][u][1], ans);
}
ans[v] = h;
}
function solve(n, edges)
{
let t = new Array(n);
for (let i = 0; i < n; i++)
t[i] = [];
for (let i = 0; i < n - 1; i++)
{
t[edges[i][0]].push([edges[i][1],
edges[i][2]]);
t[edges[i][1]].push([edges[i][0],
edges[i][2]]);
}
let sum = 0;
for (let i = 0; i < n; i++)
{
let ans = new Array(n);
dfs(i, -1, t, 0, ans);
for (let j = 0; j < n; j++)
sum += ans[j];
}
return sum / 2;
}
let N = 4;
let edges = [ [ 0, 1, 1 ],
[ 1, 2, 2 ],
[ 2, 3, 3 ] ];
document.write(solve(N, edges));
</script>
|
Time Complexity: O(N2), where N is the number of vertices.
Auxiliary Space: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
13 Oct, 2023
Like Article
Save Article