📜  具有最小边乘积且权重 >= 1 的路径

📅  最后修改于: 2021-10-28 02:09:43             🧑  作者: Mango

给定一个有N 个节点和E 条边的有向图,其中每条边的权重> 1 ,还给定一个源S和一个目的地D 。任务是找到从SD的边乘积最小的路径。如果没有从SD 的路径,则打印-1

例子:

方法:这个想法是使用 Dijkstra 的最短路径算法,稍有变化。
可以按照以下步骤计算结果:

  • 如果源等于目标,则返回0
  • S和它的权重为1和一个访问过的数组v[]初始化一个优先级队列pq
  • 虽然pq不为空:
    1. pq弹出最顶层的元素。我们将其称为curr ,将其乘积称为dist
    2. 如果curr已被访问,则继续。
    3. 如果curr等于D则返回dist
    4. 迭代所有与curr相邻的节点并推入pq (next and dist + gr[nxt].weight)
  • 返回-1

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the smallest
// product of edges
double dijkstra(int s, int d,
                vector > > gr)
{
    // If the source is equal
    // to the destination
    if (s == d)
        return 0;
 
    // Initialise the priority queue
    set > 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 > > 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
{
    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> gr)
{
     
    // If the source is equal
    // to the destination
    if (s == d)
        return 0;
 
    // Initialise the priority queue
    PriorityQueue 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> gr = new ArrayList<>();
    for(int i = 0; i < n + 1; i++)
    {
        gr.add(new ArrayList());
    }
 
    // 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


输出:
5

时间复杂度: O((E + V) logV)
辅助空间:O(V)。

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程