Shortest Path in Tree
Coding Problem Keys
Shortest Path in Tree
Problem Statement
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.
Input Format
The first line consists of 2 integers denoting N (No. of Nodes) and E (No. of Edges).
Next, E lines consists of 3 integers denoting u, v, w.
Output Format
The first line contains the sum of all pair shortest paths in the given tree.
Sample Input/Output 1
Input
3 2
0 2 15
1 0 90
Output
210
Explanation
Sum of weight of the path between nodes 0 and 1 = 90
Sum of weight of the path between nodes 0 and 2 = 15
Sum of weight of the path between nodes 1 and 2 = 105
Hence, sum = 90 + 15 + 105
Sample Input/Output 2
Input
4 3
0 1 1
1 2 2
2 3 3
Output
20
Explanation
Sum of weight of the path between nodes 0 and 1 = 1
Sum of weight of the path between nodes 0 and 2 = 3
Sum of weight of the path between nodes 0 and 3 = 6
Sum of weight of the path between nodes 1 and 2 = 2
Sum of weight of the path between nodes 1 and 3 = 5
Sum of weight of the path between nodes 2 and 4 = 3
Hence, sum = 1 + 3 + 6 + 2 + 5 + 3 = 20
Solution
Programming Language: C++ Language
#include <iostream>
using namespace std;
#define INF 99999
int check(int* graph, int v){
int arr[v][v],i,j,k;
for(i=0;i<v;i++){
for(j=0;j<v;j++){
arr[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(arr[i][k]+arr[k][j]<arr[i][j]){
arr[i][j]=arr[i][k]+arr[k][j];
}
}
}
}
int sum=0;
for(i=0;i<v;i++){
for(j=i+1;j<v;j++){
sum+=arr[i][j];
}
}
return sum;
}
int main(){
int n,e;
cin>>n>>e;
int arr[e][3];
for(int i=0;i<e;i++){
for(int j=0;j<3;j++){
cin>>arr[i][j];
}
}
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=arr[i][0];
int v=arr[i][1];
int w=arr[i][2];
g[u][v]=w;
g[v][u]=w;
}
cout<<check((int*)g,n);
return 0;
}
// Published By PKJCODERS
(Note: Incase If the code doesn't Pass the output kindly comment us with your feedback to help us improvise.)
Comments