Maximize Shortest Path between given Vertices by Adding a Single Edge


In this problem, we will maximize the shortest path between the vertex 1 to N by adding the edge between two selected vertices.

Here, we will track the distance of each node of the graph from the 0th and N − 1 nodes. After that, we will insert the single edge between any two selected vertices in such a way that we can maximize the shortest path between 1 to N.

Problem statement − We have given an undirected graph. The graph contains the N vertices and M edges. Also, we have given the s_edges[] array containing the K−selected edges. We need to maximize the shorted path between vertex 1 and N by inserting the new edge between any two selected vertices. It is also given that we can insert the edge between selected vertices having an edge between them already.

Sample examples

Input

N = 6, M = 5, K = 2, s_edges[] = {1, 4}
              
                   0
	          / 	  
	         1               5	 
	         \              /
	          2  -  3  -  4 

Output

3

Explanation − Here, we have only two options to select vertices. So, when we add the edge between 1 to 4, we find the distance 3.

Input

N = 6, M = 5, K = 3, s_edges[] = {1, 4, 3}
             
                   0
	          /
	         1               5
	         \              /
 		  2   -  3  -  4 

Output

5

Explanation − Here, we have 3 options to add an edge between two vertices.

  • If we add an edge between 1 and 4, the shortest path is 3.

  • If we add the edge between 1 and 3, the shortest path is 4.

  • If we add an edge between 3 and 4, the shortest path is 5.

Here, we need to maximize the shortest path. So, we added an edge between 3 and 4.

Approach

In this approach, we will first find the distance of each node of the graph from the source node and end node. After that, we will sort the selected vertices based on the difference between their distance from the source node and the end node. As the difference is more, it means the length of the shortest path is more, which will help us to maximize the shortest path.

After that, we will traverse the sorted selected vertices to maximize the shortest path by inserting an edge between any two nodes.

Algorithm

Step 1 − Define the global variables edgesArray[200005] array to store the edges of the graph, and v_dist[2][200000] array to store the distance of each node from the start and end. Here, we will use the dist[0][] to store the distance from the 0th node and dist[1][] to store the distance of a current node from the destination node.

Step 2 − In the main() method, prepare a graph.

Step 3 − Execute the preformBFS() function two times to find the distance of each node from the source and destination node, respectively.

Step 3.1 − In the performBFS() function, define the que[] array and use the fill() method to fill all elements of the array with the maximum value.

Step 3.2 − Define the q_left and q_right variables to use as the queue's left and right pointer in the que[] array. Initialize the que[q_right++] with the start and v_dist[start] with 0, as the distance of the start node from itself is 0.

Step 3.3 − Use the while loop, and make iterations until q_left is less than the q_right.

Step 3.4 − In the loop, take the element from the q_left index of the array and store it into the temp. Also, increment the q_left by 1.

Step 3.5 − Use the nested loop to traverse all edges of the temp vertex. If the current edge is not visited, update its distance with the v_dist[temp] + 1, and insert it into the que[] array at the q_right index. After that, increment the q_right by 1.

Step 4 − After finding the distance of each node from the source and destination node, define the distDiff[] list to store the difference of distance for each vertex.

Step 5 − Traverse through each element of the s_edges[] array. Next, store the pair of differences between its distance from the source and destination node and the current node itself into the ‘distDiff’ list.

Step 6 − Sort the distDiff list according to the difference in distance. Here, we need to maximize the shortest distance after adding the edge between two vertices. So, we need to find two adjacent vertices in the sorted list having the maximum shortest path.

Step 7 − Now, initialize the ‘shortDist’ with 0 and ‘maximumDist’ with the minimum integer value.

Step 8 − Start traversing the ‘distDiff’ list. Take the second element of the current pair, representing the vertex.

Step 9 − Update the ‘shortDist’ value if it is less than the maximumDist + v_dist[1][current] as we need to maximize the shortest distance.

Step 10 − Also, update the ‘maximumDist’ value if it is less than the v_dist[0][current]. Here, the ‘maximumDist’ store the maximum distance of any particular node from the source node. In the next iteration, we add it to the distance from the current node to the end node to maximize the shortest distance.

Step 11 − At the end, print either v_dist[0][N − 1] or shortDist + 1, whichever is minimum.

Example

#include <bits/stdc++.h>
using namespace std;

const int maxi = 1e9 + 7;
int N, M;
// To store the graph as an adjacency list
vector<int> edgesArray[200005];
// To store the shortest path
int v_dist[2][200000];
void performBFS(int *v_dist, int start) {
    int que[200000];
    // Initialize all que[] elements with maxi
    fill(v_dist, v_dist + N, maxi);
    int q_right = 0, q_left = 0;
    que[q_right++] = start;
    v_dist[start] = 0;
    // BFS algorithm
    while (q_left < q_right) {
        int temp = que[q_left++];
        // Iteraet the current edge
        for (int ed : edgesArray[temp]) {
            // For non-visited vertice
            if (v_dist[ed] == maxi) {
                // Change the distance
                v_dist[ed] = v_dist[temp] + 1;
                // Add to the queue
                que[q_right++] = ed;
            }
        }
    }
}
void getShortestPath(int s_edges[], int K) {
    vector<pair<int, int>> distDiff;
    // Updating the shortest distance between 0 to other nodes
    performBFS(v_dist[0], 0);
    // Updating distance between last node and other nodes
    performBFS(v_dist[1], N - 1);
    for (int p = 0; p < K; p++) {
        // Get minimum distance for each s_edges node
        distDiff.emplace_back(v_dist[0][s_edges[p]] - v_dist[1][s_edges[p]], s_edges[p]);
    }
    // Sort distances
    sort(distDiff.begin(), distDiff.end());
    int shortDist = 0;
    int maximumDist = -maxi;
    // Traverse distDiff[]
    for (auto iter : distDiff) {
        int current = iter.second;
        // maximumDist is a distance from 0 to a. We add distance from a to N - 1 node and take the shortest distance.
        shortDist = max(shortDist, maximumDist + v_dist[1][current]);
        // Maximizing the difference
        maximumDist = max(maximumDist, v_dist[0][current]);
    }
    cout << "The minimum path cost after adding an edge between selected nodes is - " << min(v_dist[0][N - 1], shortDist + 1);
}
int main() {
    // Total nodes and edges
    N = 6, M = 5;
    // selected vertices
    int K = 2;
    int s_edges[] = {1, 4};
    // Sort array of selected vertices
    sort(s_edges, s_edges + K);
    // Creating the graph
    edgesArray[0].push_back(1);
    edgesArray[1].push_back(0);
    edgesArray[1].push_back(2);
    edgesArray[2].push_back(1);
    edgesArray[2].push_back(3);
    edgesArray[3].push_back(2);
    edgesArray[3].push_back(4);
    edgesArray[4].push_back(3);
    edgesArray[4].push_back(5);
    edgesArray[5].push_back(4);
    getShortestPath(s_edges, K);
    return 0;
}

Output

The minimum path cost after adding an edge between selected nodes is - 3

Time complexity − O(K*logK + N), where O(KlogK) is to sort the ‘distDiff’ list, and O(N) is to perform the BFS traversal.

Space complexity − O(K + N), where O(K) is to sort the list, and O(N) is for que[] array used in the BFS traversal.

The logical part of the problem is to take the distance of each node from the source and destination node, sort the selected vertices based on their distance difference and add an edge between two adjacent vertices to maximize the shortest path.

Updated on: 02-Aug-2023

89 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements