The Wayback Machine - https://web.archive.org/web/20240725071029/https://www.geeksforgeeks.org/path-with-smallest-product-of-edges-with-weight-1/
Open In App

Path with smallest product of edges with weight >= 1

Last Updated : 10 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Given a directed graph with N nodes and E edges where the weight of each of the edge is > 1, also given a source S and a destination D. The task is to find the path with the minimum product of edges from S to D. If there is no path from S to D then print -1.

Examples:  

Input: N = 3, E = 3, Edges = {{{1, 2}, 5}, {{1, 3}, 9}, {{2, 3}, 1}}, S = 1, and D = 3 
Output: 5 
The path with smallest product of edges will be 1->2->3 
with product as 5*1 = 5.

Input: N = 3, E = 3, Edges = {{{3, 2}, 5}, {{3, 3}, 9}, {{3, 3}, 1}}, S = 1, and D = 3 
Output: -1 

Approach: The idea is to use Dijkstra’s shortest path algorithm with a slight variation. 
The following steps can be followed to compute the result:  

  • If the source is equal to the destination then return 0.
  • Initialise a priority-queue pq with S and its weight as 1 and a visited array v[].
  • While pq is not empty: 
    1. Pop the top-most element from pq. Let’s call it as curr and its product of distance as dist.
    2. If curr is already visited then continue.
    3. If curr is equal to D then return dist.
    4. Iterate all the nodes adjacent to curr and push into pq (next and dist + gr[nxt].weight)
  • return -1.

Below is the implementation of the above approach:  

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the smallest
// product of edges
double dijkstra(int s, int d,
                vector<vector<pair<int, double> > > gr)
{
    // If the source is equal
    // to the destination
    if (s == d)
        return 0;
 
    // Initialise the priority queue
    set<pair<int, int> > pq;
    pq.insert({ 1, s });
 
    // Visited array
    bool v[gr.size()] = { 0 };
 
    // While the priority-queue
    // is not empty
    while (pq.size()) {
 
        // Current node
        int curr = pq.begin()->second;
 
        // Current product of distance
        int dist = pq.begin()->first;
 
        // Popping the top-most element
        pq.erase(pq.begin());
 
        // If already visited continue
        if (v[curr])
            continue;
 
        // Marking the node as visited
        v[curr] = 1;
 
        // If it is a destination node
        if (curr == d)
            return dist;
 
        // Traversing the current node
        for (auto it : gr[curr])
            pq.insert({ dist * it.second, it.first });
    }
 
    // If no path exists
    return -1;
}
 
// Driver code
int main()
{
    int n = 3;
 
    // Graph as adjacency matrix
    vector<vector<pair<int, double> > > gr(n + 1);
 
    // Input edges
    gr[1].push_back({ 3, 9 });
    gr[2].push_back({ 3, 1 });
    gr[1].push_back({ 2, 5 });
 
    // Source and destination
    int s = 1, d = 3;
 
    // Dijkstra
    cout << dijkstra(s, d, gr);
 
    return 0;
}


Java




// Java implementation of the approach
import java.util.ArrayList;
import java.util.PriorityQueue;
 
class Pair implements Comparable<Pair>
{
    int first, second;
 
    public Pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
 
    public int compareTo(Pair o)
    {
        if (this.first == o.first)
        {
            return this.second - o.second;
        }
        return this.first - o.first;
    }
}
 
class GFG{
 
// Function to return the smallest
// xor sum of edges
static int dijkstra(int s, int d,
                    ArrayList<ArrayList<Pair>> gr)
{
     
    // If the source is equal
    // to the destination
    if (s == d)
        return 0;
 
    // Initialise the priority queue
    PriorityQueue<Pair> pq = new PriorityQueue<>();
    pq.add(new Pair(1, s));
 
    // Visited array
    boolean[] v = new boolean[gr.size()];
 
    // While the priority-queue
    // is not empty
    while (!pq.isEmpty())
    {
         
        // Current node
        Pair p = pq.poll();
        int curr = p.second;
 
        // Current xor sum of distance
        int dist = p.first;
 
        // If already visited continue
        if (v[curr])
            continue;
 
        // Marking the node as visited
        v[curr] = true;
 
        // If it is a destination node
        if (curr == d)
            return dist;
 
        // Traversing the current node
        for(Pair it : gr.get(curr))
            pq.add(new Pair(dist ^ it.second, it.first));
    }
 
    // If no path exists
    return -1;
}
 
// Driver code
public static void main(String[] args)
{
    int n = 3;
 
    // Graph as adjacency matrix
    ArrayList<ArrayList<Pair>> gr = new ArrayList<>();
    for(int i = 0; i < n + 1; i++)
    {
        gr.add(new ArrayList<Pair>());
    }
 
    // Input edges
    gr.get(1).add(new Pair(3, 9));
    gr.get(2).add(new Pair(3, 1));
    gr.get(1).add(new Pair(2, 5));
 
    // Source and destination
    int s = 1, d = 3;
 
    System.out.println(dijkstra(s, d, gr));
}
}
 
// This code is contributed by sanjeev2552


Python3




# Python3 implementation of the approach
 
# Function to return the smallest
# product of edges
def dijkstra(s, d, gr) :
 
    # If the source is equal
    # to the destination
    if (s == d) :
        return 0;
 
    # Initialise the priority queue
    pq = [];
    pq.append(( 1, s ));
     
    # Visited array
    v = [0]*(len(gr) + 1);
 
    # While the priority-queue
    # is not empty
    while (len(pq) != 0) :
 
        # Current node
        curr = pq[0][1];
 
        # Current product of distance
        dist = pq[0][0];
 
        # Popping the top-most element
        pq.pop();
 
        # If already visited continue
        if (v[curr]) :
            continue;
 
        # Marking the node as visited
        v[curr] = 1;
 
        # If it is a destination node
        if (curr == d) :
            return dist;
 
        # Traversing the current node
        for it in gr[curr] :
            if it not in pq :
                pq.insert(0,( dist * it[1], it[0] ));
 
    # If no path exists
    return -1;
 
# Driver code
if __name__ == "__main__" :
 
    n = 3;
 
    # Graph as adjacency matrix
    gr = {};
     
    # Input edges
    gr[1] = [( 3, 9) ];
    gr[2] = [ (3, 1) ];
    gr[1].append(( 2, 5 ));
    gr[3] = [];
 
    #print(gr);
    # Source and destination
    s = 1; d = 3;
     
    # Dijkstra
    print(dijkstra(s, d, gr));
 
# This code is contributed by AnkitRai01


C#




//C# code for the above approach
using System;
using System.Collections.Generic;
 
class Pair : IComparable<Pair>
{
    public int first, second;
 
    public Pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
 
    public int CompareTo(Pair o)
    {
        if (this.first == o.first)
        {
            return this.second - o.second;
        }
        return this.first - o.first;
    }
}
 
class GFG
{
    // Function to return the smallest
    // xor sum of edges
    static int Dijkstra(int s, int d,
                        List<List<Pair>> gr)
    {
         
        // If the source is equal
        // to the destination
        if (s == d)
            return 0;
 
        // Initialise the priority queue
        SortedSet<Pair> pq = new SortedSet<Pair>();
        pq.Add(new Pair(1, s));
 
        // Visited array
        bool[] v = new bool[gr.Count];
 
        // While the priority-queue
        // is not empty
        while (pq.Count != 0)
        {
             
            // Current node
            Pair p = pq.Min;
            pq.Remove(p);
            int curr = p.second;
 
            // Current xor sum of distance
            int dist = p.first;
 
            // If already visited continue
            if (v[curr])
                continue;
 
            // Marking the node as visited
            v[curr] = true;
 
            // If it is a destination node
            if (curr == d)
                return dist;
 
            // Traversing the current node
            foreach (Pair it in gr[curr])
                pq.Add(new Pair(dist ^ it.second, it.first));
        }
 
        // If no path exists
        return -1;
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        int n = 3;
 
        // Graph as adjacency matrix
        List<List<Pair>> gr = new List<List<Pair>>();
        for (int i = 0; i < n + 1; i++)
        {
            gr.Add(new List<Pair>());
        }
 
        // Input edges
        gr[1].Add(new Pair(3, 9));
        gr[2].Add(new Pair(3, 1));
        gr[1].Add(new Pair(2, 5));
 
        // Source and destination
        int s = 1, d = 3;
 
        Console.WriteLine(Dijkstra(s, d, gr));
    }
}


Javascript




<script>
 
// Javascript implementation of the approach
 
// Function to return the smallest
// product of edges
function dijkstra(s, d, gr)
{
    // If the source is equal
    // to the destination
    if (s == d)
        return 0;
 
    // Initialise the priority queue
    var pq = [];
    pq.push([1, s]);
 
    // Visited array
    var v = Array(gr.length).fill(0);
 
    // While the priority-queue
    // is not empty
    while (pq.length!=0) {
 
        // Current node
        var curr = pq[0][1];
 
        // Current product of distance
        var dist = pq[0][0];
 
        // Popping the top-most element
        pq.shift();
 
        // If already visited continue
        if (v[curr])
            continue;
 
        // Marking the node as visited
        v[curr] = 1;
 
        // If it is a destination node
        if (curr == d)
            return dist;
 
        // Traversing the current node
        for (var it of gr[curr])
            pq.push([dist * it[1], it[0] ]);
        pq.sort();
    }
 
    // If no path exists
    return -1;
}
 
// Driver code
var n = 3;
 
// Graph as adjacency matrix
var gr = Array.from(Array(n + 1), ()=> Array());
 
// Input edges
gr[1].push([3, 9]);
gr[2].push([3, 1]);
gr[1].push([2, 5]);
 
// Source and destination
var s = 1, d = 3;
 
// Dijkstra
document.write(dijkstra(s, d, gr));
 
// This code is contributed by rrrtnx.
</script>


Output: 

5

 

Time complexity: O((E + V) logV)
Auxiliary Space: O(V). 
 



Previous Article
Next Article

Similar Reads

Path with smallest product of edges with weight&gt;0
Given a directed graph with N nodes and E edges where the weight of each edge is &gt; 0, also given a source S and a destination D. The task is to find the path with the minimum product of edges from S to D. If there is no path from S to D, then print -1. Examples: Input: N = 3, E = 3, Edges = {{{1, 2}, 0.5}, {{1, 3}, 1.9}, {{2, 3}, 3}}, S = 1, and
7 min read
Count number of paths whose weight is exactly X and has at-least one edge of weight M
Given an infinite tree and three numbers N, M, and X which has exactly N child from every node. Every edge has a weight of 1, 2, 3, 4..N. The task is to find the count of paths whose weight is exactly X and has a minimum of one edge of weight M in it. The diagram above shows a tree shown till level-3 and N = 3. Examples: Input: N = 3, M = 2, X = 3
8 min read
Maximize cost of segment having weight at most K from given weight and cost of N items
Given two arrays W[] and C[] containing weight and cost of N (1 to N) items respectively, and an integer K, find a segment from 1 to N, such that the total weight of the segment is at most K and the total cost is maximum. Print the cost of this segment. Examples: Input: N = 6, K = 20, W[] = {9, 7, 6, 5, 8, 4}, C[] = {7, 1, 3, 6, 8, 3}Output: 17Expl
12 min read
Choose maximum weight with given weight and value ratio
Given weights and values of n items and a value k. We need to choose a subset of these items in such a way that ratio of the sum of weight and sum of values of chosen items is K and sum of weight is maximum among all possible subset choices. Input : weight[] = [4, 8, 9] values[] = [2, 4, 6] K = 2 Output : 12 We can choose only first and second item
9 min read
Remove all outgoing edges except edge with minimum weight
Given a directed graph having n nodes. For each node, delete all the outgoing edges except the outgoing edge with minimum weight. Apply this deletion operation for every node and then print the final graph remaining where each node of the graph has at most one outgoing edge and that too with minimum weight. Note: Here, the graph is stored as Adjace
9 min read
Ways to Remove Edges from a Complete Graph to make Odd Edges
Given a complete graph with N vertices, the task is to count the number of ways to remove edges such that the resulting graph has odd number of edges. Examples: Input: N = 3 Output: 4 The initial graph has 3 edges as it is a complete graph. We can remove edges (1, 2) and (1, 3) or (1, 2) and (2, 3) or (1, 3) and (2, 3) or we do not remove any of th
4 min read
Pendant Vertices, Non-Pendant Vertices, Pendant Edges and Non-Pendant Edges in Graph
Pre-requisites: Handshaking theorem. Pendant Vertices Let G be a graph, A vertex v of G is called a pendant vertex if and only if v has degree 1. In other words, pendant vertices are the vertices that have degree 1, also called pendant vertex. Note: Degree = number of edges connected to a vertex In the case of trees, a pendant vertex is known as a
7 min read
Path with smallest difference between consecutive cells (Path with minimum effort)
Given a 2D array arr[] of size N x M, where arr[i][j] represents the value of cell (i, j). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (n-1, m-1). You can move up, down, left, or right, and you wish to find a path such that the maximum absolute difference in values between two consecutive cells of
14 min read
Check if alternate path exists from U to V with smaller individual weight in a given Graph
Given a directed weighted graph with N vertices and M edges and an edge (U, V). The task is to find whether there is an alternate path present from U to V with individual weight of edges in alternate path less than the weight of direct path. If present print Yes else print No. Examples For the given directed graph: Input: N = 7, M = 10, U = 3, V =
10 min read
Path from a given source to a given destination having Kth largest weight in a Graph
Given a weighted graph consisting of N nodes and M edges, a source vertex, a destination vertex, and an integer K, the task is to find the path with Kth largest weight from source to destination in the graph. Examples: Input: N = 7, M = 8, source = 0, destination = 6, K = 3, Edges[][] = {{0, 1, 10}, {1, 2, 10}, {2, 3, 10}, {0, 3, 40}, {3, 4, 2}, {4
14 min read
three90RightbarBannerImg