用Disjoint Union方法计算非循环图中两个顶点之间的节点数
给定一个连通无环图、一个源顶点和一个目标顶点,您的任务是通过不相交联合方法计算给定源顶点和目标顶点之间的顶点数。
例子:
Input : 1 4
4 5
4 2
2 6
6 3
1 3
Output : 3
In the input 6 is the total number of vertices
labeled from 1 to 6 and the next 5 lines are the connection
between vertices. Please see the figure for more
explanation. And in last line 1 is the source vertex
and 3 is the destination vertex. From the figure
it is clear that there are 3 nodes(4, 2, 6) present
between 1 and 3.
要使用不相交联合方法,我们必须首先检查给定图的每个节点的父节点。我们可以使用 BFS 遍历图,计算图的每个顶点的父顶点。例如,如果我们从顶点 1 遍历图(即开始我们的 BFS),那么 1 是 4 的父节点,然后 4 是 5 和 2 的父节点,同样 2 是 6 的父节点,而 6 是 3 的父节点。
现在要计算源节点和目标节点之间的节点数,我们必须创建一个从目标节点的父节点开始的循环,并且在每次迭代之后,我们将使用当前节点的父节点更新该节点,保持数量的计数的迭代。当我们到达源顶点时,循环的执行将终止,并且 count 变量给出了源节点和目标节点的连接路径中的节点数。
在上述方法中,不相交集是所有具有单个顶点的集合,我们使用联合运算来合并两个集合,其中一个包含父节点,另一个包含子节点。
以下是上述方法的实现。
C++
// C++ program to calculate number
// of nodes between two nodes
#include
using namespace std;
// function to calculate no of nodes
// between two nodes
int totalNodes(vector adjac[], int n,
int x, int y)
{
// x is the source node and
// y is destination node
// visited array take account of
// the nodes visited through the bfs
bool visited[n+1] = {0};
// parent array to store each nodes
// parent value
int p[n] ;
queue q;
q.push(x);
// take our first node(x) as first element
// of queue and marked it as
// visited through visited[] array
visited[x] = true;
int m;
// normal bfs method starts
while (!q.empty())
{
m = q.front() ;
q.pop();
for (int i=0; i adjac[7];
// creating graph, keeping length of
// adjacency list as (1 + no of nodes)
// as index ranges from (0 to n-1)
adjac[1].push_back(4);
adjac[4].push_back(1);
adjac[5].push_back(4);
adjac[4].push_back(5);
adjac[4].push_back(2);
adjac[2].push_back(4);
adjac[2].push_back(6);
adjac[6].push_back(2);
adjac[6].push_back(3);
adjac[3].push_back(6);
cout << totalNodes(adjac, 7, 1, 3);
return 0;
}
Java
// Java program to calculate number
// of nodes between two nodes
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Vector;
public class GFG
{
// function to calculate no of nodes
// between two nodes
static int totalNodes(Vector adjac[],
int n, int x, int y)
{
// x is the source node and
// y is destination node
// visited array take account of
// the nodes visited through the bfs
Boolean visited[] = new Boolean[n + 1];
//filling boolean value with false
Arrays.fill(visited, false);
// parent array to store each nodes
// parent value
int p[] = new int[n];
Queue q = new LinkedList<>();
q.add(x);
// take our first node(x) as first element
// of queue and marked it as
// visited through visited[] array
visited[x] = true;
int m;
// normal bfs method starts
while(!q.isEmpty())
{
m = q.peek();
q.poll();
for(int i=0; i < adjac[m].size() ; ++i)
{
int h = adjac[m].get(i);
if(visited[h] != true )
{
visited[h] = true;
// when new node is encountered
// we assign it's parent value
// in parent array p
p[h] = m;
q.add(h);
}
}
}
// count variable stores the result
int count = 0;
// loop start with parent of y
// till we encountered x
int i = p[y];
while(i != x)
{
// count increases for counting
// the nodes
count++;
i = p[i];
}
return count;
}
// Driver program to test above function
public static void main(String[] args)
{
// adjacency list for graph
Vector adjac[] = new Vector[7];
//Initializing Vector for each nodes
for (int i = 0; i < 7; i++)
adjac[i] = new Vector<>();
// creating graph, keeping length of
// adjacency list as (1 + no of nodes)
// as index ranges from (0 to n-1)
adjac[1].add(4);
adjac[4].add(1);
adjac[5].add(4);
adjac[4].add(5);
adjac[4].add(2);
adjac[2].add(4);
adjac[2].add(6);
adjac[6].add(2);
adjac[6].add(3);
adjac[3].add(6);
System.out.println(totalNodes(adjac, 7, 1, 3));
}
}
// This code is contributed by Sumit Ghosh
Python3
# Python3 program to calculate number
# of nodes between two nodes
import queue
# function to calculate no of nodes
# between two nodes
def totalNodes(adjac, n, x, y):
# x is the source node and
# y is destination node
# visited array take account of
# the nodes visited through the bfs
visited = [0] * (n + 1)
# parent array to store each nodes
# parent value
p = [None] * n
q = queue.Queue()
q.put(x)
# take our first node(x) as first
# element of queue and marked it as
# visited through visited[] array
visited[x] = True
m = None
# normal bfs method starts
while (not q.empty()):
m = q.get()
for i in range(len(adjac[m])):
h = adjac[m][i]
if (not visited[h]):
visited[h] = True
# when new node is encountered
# we assign it's parent value
# in parent array p
p[h] = m
q.put(h)
# count variable stores the result
count = 0
# loop start with parent of y
# till we encountered x
i = p[y]
while (i != x):
# count increases for counting
# the nodes
count += 1
i = p[i]
return count
# Driver Code
if __name__ == '__main__':
# adjacency list for graph
adjac = [[] for i in range(7)]
# creating graph, keeping length of
# adjacency list as (1 + no of nodes)
# as index ranges from (0 to n-1)
adjac[1].append(4)
adjac[4].append(1)
adjac[5].append(4)
adjac[4].append(5)
adjac[4].append(2)
adjac[2].append(4)
adjac[2].append(6)
adjac[6].append(2)
adjac[6].append(3)
adjac[3].append(6)
print(totalNodes(adjac, 7, 1, 3))
# This code is contributed by PranchalK
C#
// C# program to calculate number
// of nodes between two nodes
using System;
using System.Collections.Generic;
class GFG
{
// function to calculate no of nodes
// between two nodes
static int totalNodes(List []adjac,
int n, int x, int y)
{
// x is the source node and
// y is destination node
// visited array take account of
// the nodes visited through the bfs
Boolean []visited = new Boolean[n + 1];
// parent array to store each nodes
// parent value
int []p = new int[n];
Queue q = new Queue();
q.Enqueue(x);
// take our first node(x) as first element
// of queue and marked it as
// visited through visited[] array
visited[x] = true;
int m, i;
// normal bfs method starts
while(q.Count != 0)
{
m = q.Peek();
q.Dequeue();
for(i = 0; i < adjac[m].Count ; ++i)
{
int h = adjac[m][i];
if(visited[h] != true )
{
visited[h] = true;
// when new node is encountered
// we assign it's parent value
// in parent array p
p[h] = m;
q.Enqueue(h);
}
}
}
// count variable stores the result
int count = 0;
// loop start with parent of y
// till we encountered x
i = p[y];
while(i != x)
{
// count increases for counting
// the nodes
count++;
i = p[i];
}
return count;
}
// Driver Code
public static void Main(String[] args)
{
// adjacency list for graph
List []adjac = new List[7];
//Initializing Vector for each nodes
for (int i = 0; i < 7; i++)
adjac[i] = new List();
// creating graph, keeping length of
// adjacency list as (1 + no of nodes)
// as index ranges from (0 to n-1)
adjac[1].Add(4);
adjac[4].Add(1);
adjac[5].Add(4);
adjac[4].Add(5);
adjac[4].Add(2);
adjac[2].Add(4);
adjac[2].Add(6);
adjac[6].Add(2);
adjac[6].Add(3);
adjac[3].Add(6);
Console.WriteLine(totalNodes(adjac, 7, 1, 3));
}
}
// This code is contributed by 29AjayKumar
Javascript
输出:
3