📌  相关文章
📜  有向图中边的最小XOR总和的路径

📅  最后修改于: 2021-05-14 00:39:37             🧑  作者: Mango

给定一个有N个节点和E个边的有向图,一个源S和一个目标D节点。任务是找到从SD的边的XOR总和最小的路径。如果没有从SD的路径,则打印-1

例子:

方法:想法是使用Dijkstra的最短路径算法,并稍有变化。下面是解决问题的分步方法:

  • 基本案例:如果源节点等于目标节点,则返回0
  • 使用源节点及其权重为0和访问数组初始化优先级队列。
  • 当优先级队列不为空时:
    1. 从优先级队列中弹出最上面的元素。我们称它为当前节点。
    2. 在被访问数组的帮助下检查当前节点是否已被访问,如果是,则继续。
    3. 如果当前节点是目标节点,则返回当前节点与源节点的XOR总和距离。
    4. 迭代与当前节点相邻的所有节点,并推入优先级队列,并将它们的距离作为XOR与当前距离和边缘权重之和。
  • 否则,就没有从源到目的地的路径。因此,返回-1

下面是上述方法的实现:

C++
// C++ implementation of the approach
 
#include 
using namespace std;
 
// Function to return the smallest
// xor sum of edges
double minXorSumOfEdges(
    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({ 0, 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 xor sum 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;
 
    cout << minXorSumOfEdges(s, d, gr);
 
    return 0;
}


Java
// Java implementation of the approach
import java.util.PriorityQueue;
import java.util.ArrayList;
 
class Pair implements Comparable
{
    int first, second;
 
    public Pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
 
    @Override
    public int compareTo(Pair p)
    {
        if (this.first == p.first)
        {
            return this.second - p.second;
        }
        return this.first - p.first;
    }
}
 
class GFG{
 
// Function to return the smallest
// xor sum of edges
static int minXorSumOfEdges(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(0, s));
 
    // Visited array
    boolean[] v = new boolean[gr.size()];
 
    // While the priority-queue
    // is not empty
    while (!pq.isEmpty())
    {
         
        // Iterator itr = pq.iterator();
        // 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(minXorSumOfEdges(s, d, gr));
}
}
 
// This code is contributed by sanjeev2552


Python3
# Python3 implementation of the approach
from collections import deque
 
# Function to return the smallest
# xor sum of edges
def minXorSumOfEdges(s, d, gr):
     
    # If the source is equal
    # to the destination
    if (s == d):
        return 0
 
    # Initialise the priority queue
    pq = []
    pq.append((0, s))
 
    # Visited array
    v = [0] * len(gr)
 
    # While the priority-queue
    # is not empty
    while (len(pq) > 0):
        pq = sorted(pq)
 
        # Current node
        curr = pq[0][1]
 
        # Current xor sum of distance
        dist = pq[0][0]
 
        # Popping the top-most element
        del pq[0]
 
        # 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]:
            pq.append((dist ^ it[1],
                              it[0]))
    # If no path exists
    return -1
 
# Driver code
if __name__ == '__main__':
     
    n = 3
     
    # Graph as adjacency matrix
    gr = [[] for i in range(n + 1)]
 
    # Input edges
    gr[1].append([ 3, 9 ])
    gr[2].append([ 3, 1 ])
    gr[1].append([ 2, 5 ])
 
    # Source and destination
    s = 1
    d = 3
 
    print(minXorSumOfEdges(s, d, gr))
     
# This code is contributed by mohit kumar 29


C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
class GFG
{
 
  // Function to return the smallest
  // xor sum of edges
  static int minXorSumOfEdges(int s, int d, List>> gr)
  {
 
    // If the source is equal
    // to the destination
    if (s == d)
      return 0;
 
    // Initialise the priority queue
    List> pq = new List>();
    pq.Add(new Tuple(0, s));
 
    // Visited array
    int[] v = new int[gr.Count];
 
    // While the priority-queue
    // is not empty
    while (pq.Count > 0)
    {
      pq.Sort();
 
      // Current node
      int curr = pq[0].Item2;
 
      // Current xor sum of distance
      int dist = pq[0].Item1;
 
      // Popping the top-most element
      pq.RemoveAt(0);
 
      // If already visited continue
      if(v[curr] != 0)
        continue;
 
      // Marking the node as visited
      v[curr] = 1;
 
      // If it is a destination node
      if (curr == d)
        return dist;
 
      // Traversing the current node
      foreach(Tuple it in gr[curr])
      {
        pq.Add(new Tuple(dist ^ it.Item2, it.Item1));
      }
    }
 
    // If no path exists
    return -1;
  }
 
  // Driver code
  static void Main()
  {
    int n = 3;
 
    // Graph as adjacency matrix
    List>> gr = new List>>();
 
    for(int i = 0; i < n + 1; i++)
    {
      gr.Add(new List>());
    }
 
    // Input edges
    gr[1].Add(new Tuple(3, 9));
    gr[2].Add(new Tuple(3, 1));
    gr[1].Add(new Tuple(2, 5));
 
    // Source and destination
    int s = 1;
    int d = 3;
 
    Console.WriteLine(minXorSumOfEdges(s, d, gr));
  }
}
 
// This codee is contributed by divyesh072019.


输出:
4

时间复杂度: O((E + V)logV)