📌  相关文章
📜  计算从根开始的路径中所有边的按位异或的节点等于 K

📅  最后修改于: 2021-10-25 04:43:12             🧑  作者: Mango

给定一个由N 个节点和两个整数RK组成的二叉树。树的每条边都有一个与之关联的正整数,以{u, v, w}的形式给出,其中边(u, v) 的权重为w 。任务是计算从根RS的路径中所有边的按位异或的节点数S等于K

例子:

方法:该问题可以使用深度优先搜索方法解决。请按照以下步骤解决问题:

  1. 0初始化变量ansxor以存储对的数量和边的当前 xor。
  2. 使用深度优先搜索从给定的根顶点R开始遍历给定的树。
  3. 对于每个节点u ,访问其相邻节点。
  4. 对于每条边{u, v} ,如果xor等于K ,则将ans增加1 。否则,当前边缘{U,V,W},更新XOR异或=(XOR ^ W)其中,^是逐位异或。
  5. 遍历后,将存储在计数器ans 中的值打印为对数。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Initialize the adjacency list
// to represent the tree
vector > adj[100005];
 
// Marks visited / unvisited vertices
int visited[100005] = { 0 };
 
// Stores the required count of nodes
int ans = 0;
 
// DFS to visit each vertex
void dfs(int node, int xorr, int k)
{
    // Mark the current node
    // as visited
    visited[node] = 1;
 
    // Update the counter xor is K
    if (node != 1 && xorr == k)
        ans++;
 
    // Visit adjacent nodes
    for (auto x : adj[node]) {
 
        if (!visited[x.first]) {
 
            // Calculate Bitwise XOR of
            // edges in the path
            int xorr1 = xorr ^ x.second;
 
            // Recursive call to dfs function
            dfs(x.first, xorr1, k);
        }
    }
}
 
// Function to construct the tree and
// print required count of nodes
void countNodes(int N, int K, int R,
                vector > edges)
{
 
    // Add edges
    for (int i = 0; i < N - 1; i++) {
        int u = edges[i][0], v = edges[i][1],
            w = edges[i][2];
        adj[u].push_back({ v, w });
        adj[v].push_back({ u, w });
    }
 
    dfs(R, 0, K);
 
    // Print answer
    cout << ans << "\n";
}
 
// Driver Code
int main()
{
    // Given K and R
    int K = 0, R = 1;
 
    // Given edges
    vector > edges
        = { { 1, 2, 3 }, { 1, 3, 1 },
            { 2, 4, 3 }, { 2, 5, 4 },
            { 3, 6, 1 }, { 3, 7, 2 } };
 
    // Number of vertices
    int N = edges.size();
 
    // Function call
    countNodes(N, K, R, edges);
 
    return 0;
}


Java
// Java program for the
// above approach
import java.util.*;
class GFG{
 
static class pair
{
  int first, second;
  public pair(int first,
              int second) 
  {
    this.first = first;
    this.second = second;
  }   
}
   
// Initialize the adjacency list
// to represent the tree
static Vector []adj =
       new Vector[100005];
 
// Marks visited / unvisited
// vertices
static int visited[] =
       new int[100005];
 
// Stores the required
// count of nodes
static int ans = 0;
 
// DFS to visit each
// vertex
static void dfs(int node,
                int xorr,
                int k)
{
  // Mark the current node
  // as visited
  visited[node] = 1;
 
  // Update the counter
  // xor is K
  if (node != 1 &&
      xorr == k)
    ans++;
 
  // Visit adjacent nodes
  for (pair x : adj[node])
  {
    if (visited[x.first] != 1)
    {
      // Calculate Bitwise XOR of
      // edges in the path
      int xorr1 = xorr ^ x.second;
 
      // Recursive call to dfs
      // function
      dfs(x.first, xorr1, k);
    }
  }
}
 
// Function to conthe tree and
// print required count of nodes
static void countNodes(int N, int K,
                       int R, int[][] edges)
{
  // Add edges
  for (int i = 0; i < N - 1; i++)
  {
    int u = edges[i][0],
        v = edges[i][1],
    w = edges[i][2];
    adj[u].add(new pair(v, w ));
    adj[v].add(new pair(u, w ));
  }
 
  dfs(R, 0, K);
 
  // Print answer
  System.out.print(ans + "\n");
}
 
// Driver Code
public static void main(String[] args)
{
  // Given K and R
  int K = 0, R = 1;
   
  for (int i = 0; i < adj.length; i++)
    adj[i] = new Vector();
  // Given edges
  int[][] edges = {{1, 2, 3},
                   {1, 3, 1}, 
                   {2, 4, 3},
                   {2, 5, 4},
                   {3, 6, 1},
                   {3, 7, 2}};
 
  // Number of vertices
  int N = edges.length;
 
  // Function call
  countNodes(N, K, R, edges);
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program for the above approach
 
# Initialize the adjacency list
# to represent the tree
adj = [[] for i in range(100005)]
 
# Marks visited / unvisited vertices
visited = [0] * 100005
 
# Stores the required count of nodes
ans = 0
 
# DFS to visit each vertex
def dfs(node, xorr, k):
     
    global ans
     
    # Mark the current node
    # as visited
    visited[node] = 1
 
    # Update the counter xor is K
    if (node != 1 and xorr == k):
        ans += 1
 
    # Visit adjacent nodes
    for x in adj[node]:
        if (not visited[x[0]]):
 
            # Calculate Bitwise XOR of
            # edges in the path
            xorr1 = xorr ^ x[1]
 
            # Recursive call to dfs function
            dfs(x[0], xorr1, k)
 
# Function to construct the tree and
# prrequired count of nodes
def countNodes(N, K, R, edges):
 
    # Add edges
    for i in range(N - 1):
        u = edges[i][0]
        v = edges[i][1]
        w = edges[i][2]
         
        adj[u].append([v, w])
        adj[v].append([u, w])
 
    dfs(R, 0, K)
 
    # Print answer
    print(ans)
 
# Driver Code
if __name__ == '__main__':
     
    # Given K and R
    K = 0
    R = 1
 
    # Given edges
    edges = [ [ 1, 2, 3 ],[ 1, 3, 1 ],
              [ 2, 4, 3 ],[ 2, 5, 4 ],
              [ 3, 6, 1 ],[ 3, 7, 2 ] ]
 
    # Number of vertices
    N = len(edges)
 
    # Function call
    countNodes(N, K, R, edges)
 
# This code is contributed by mohit kumar 29


C#
// C# program for the
// above approach
using System;
using System.Collections.Generic;
class GFG{
 
public class pair
{
  public int first,
             second;
  public pair(int first,
              int second) 
  {
    this.first = first;
    this.second = second;
  }   
}
   
// Initialize the adjacency list
// to represent the tree
static List []adj =
       new List[100005];
 
// Marks visited / unvisited
// vertices
static int []visited =
       new int[100005];
 
// Stores the required
// count of nodes
static int ans = 0;
 
// DFS to visit each
// vertex
static void dfs(int node,
                int xorr,
                int k)
{
  // Mark the current node
  // as visited
  visited[node] = 1;
 
  // Update the counter
  // xor is K
  if (node != 1 &&
      xorr == k)
    ans++;
 
  // Visit adjacent nodes
  foreach (pair x in adj[node])
  {
    if (visited[x.first] != 1)
    {
      // Calculate Bitwise XOR of
      // edges in the path
      int xorr1 = xorr ^ x.second;
 
      // Recursive call to dfs
      // function
      dfs(x.first, xorr1, k);
    }
  }
}
 
// Function to conthe tree and
// print required count of nodes
static void countNodes(int N, int K,
                       int R, int[,] edges)
{
  // Add edges
  for (int i = 0; i < N - 1; i++)
  {
    int u = edges[i,0];
     int   v = edges[i,1],
    w = edges[i,2];
    adj[u].Add(new pair(v, w ));
    adj[v].Add(new pair(u, w ));
  }
 
  dfs(R, 0, K);
 
  // Print answer
  Console.Write(ans + "\n");
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given K and R
  int K = 0, R = 1;
   
  for (int i = 0; i < adj.Length; i++)
    adj[i] = new List();
   
  // Given edges
  int[,] edges = {{1, 2, 3},
                   {1, 3, 1}, 
                   {2, 4, 3},
                   {2, 5, 4},
                   {3, 6, 1},
                   {3, 7, 2}};
 
  // Number of vertices
  int N = edges.GetLength(0);
 
  // Function call
  countNodes(N, K, R, edges);
}
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:
2

时间复杂度: O(N),其中N是节点数。
辅助空间: O(N)

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