C++ Program to find out the sum of shortest cost paths for all given triplets


Suppose, there are n cities and m roads between the cities. The m roads are given to us in an array of roads where the roads are in the format {aource, destination, weight}. Now, we define a triplet (s, t, k) where s, t, and k are cities. Now we have to calculate the minimum time needed to get from city s to city t. To visit t from s, only cities within 1 to k can be visited. If city t is unreachable from s, then we return 0. We have to calculate the minimum time for all triplets (s, t, k), and print the sum of them.

So, if the input is like n = 4, m = 2, edges = {{1, 2, 5}, {2, 3, 4}, {3, 4, 3}}, then the output will be 63.

Steps

To solve this, we will follow these steps −

Define one 2D array dvec initialized with value infinity
for initialize i := 0, when i < n, update (increase i by 1), do:
   dvec[i, i] := 0
for initialize i := 0, when i < m, update (increase i by 1), do:
   a := first value of (edges[i])
   b := second value of (edges[i])
   c := third value of (edges[i])
   decrease a and b by 1
   dvec[a, b] := c
res := 0
for initialize k := 0, when k < n, update (increase k by 1), do:
   for initialize i := 0, when i < n, update (increase i by 1), do:
       for initialize j := 0, when j < n, update (increase j by 1), do:
       dvec[i, j] := minimum of (dvec[i, j] and dvec[i, k] + dvec[k, j])
       if dvec[i, j] is not equal to infinity, then:
          res := res + dvec[i, j]
print(res)

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;

void solve(int n, int m, vector<tuple<int, int, int>> edges){
   vector<vector<int>> dvec(n, vector<int>(n, INF));
   for(int i = 0; i < n; i++)
      dvec[i][i] = 0;
   for(int i = 0; i < m; i++) {
      int a = get<0> (edges[i]);
      int b = get<1> (edges[i]);
      int c = get<2> (edges[i]);
      a--; b--;
      dvec[a][b] = c;
   }
   int res = 0;
   for(int k = 0; k < n; k++) {
      for(int i = 0; i < n; i++) {
         for(int j = 0; j < n; j++) {
            dvec[i][j] = min(dvec[i][j], dvec[i][k]+dvec[k][j]);
            if(dvec[i][j] != INF)
               res += dvec[i][j];
         }
      }
   }
   cout << res << endl;
}
int main() {
   int n = 4, m = 2;
   vector<tuple<int, int, int>> edges = {{1, 2, 5}, {2, 3, 4}, {3, 4, 3}};
   solve(n, m, edges);
   return 0;
}

Input

4, 2, {{1, 2, 5}, {2, 3, 4}, {3, 4, 3}}

Output

63

Updated on: 02-Mar-2022

219 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements