XOR paths
Practice
3.7 (12 votes)
Advanced data structures
Data structures
Depth first search
Lca
Segment trees
Tries
Problem
60% Success 860 Attempts 50 Points 4s Time Limit 512MB Memory 1024 KB Max Code

You are given a weighted tree (an acyclic undirected connected graph) with \(N\) nodes. The tree nodes are numbered from 1 to \(N\). There are \(N-1\) edges with each having a weight assigned to it.

You have to process \(Q\) queries on it. In each query, you are given three integers \(u,\ v,\ x\). You are required to determine the maximum XOR that you can obtain when you the bitwise XOR operation on any edge weight in the path from node \(u\) to node \(v\) with \(x\).

For example

You are given the following tree:

You get a query \((9,\ 7,\ 1)\). Therefore, in this case, your task is to determine the maximum XOR that you can obtain when you XOR \(x\) with any edges in the path from node 9 to node 7.

The path from node 9 to node 7 is marked red for better understanding.

There are 5 edges in the path from node 9 to node 7 and there weight are as follows: \(\{4,\ 3,\ 2,\ 10,\ 12\}\). If you XOR 12 with \(x\), that is, 12^1 = 13 and this the maximum XOR that you can obtain. Therefore, the answer to this query is 13.

Input format

  • The first line contains two space-separated integers \(N\) and \(Q\).
  • The next \(N-1\) lines contain three space-separated integers \(u,\ v,\ w\) denoting node \(u\) and \(v\) are connected with an edge of weight \(w\).
  • The next \(Q\) lines contain \(u,\ v,\ x\).

Output Format

For each query, print a single integer in a new line.

Constraints

\(\leq\)  N, Q  \(\leq\) 105

\(\leq\) u, v  \(\leq\) N  and (u!=v)

\(\leq\) w, x  \(\leq\) 106

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:50
3 votes
Tags:
TrieAdvanced Data StructuresData Structures
Points:50
4 votes
Tags:
Advanced Data StructuresData StructuresHardSegment TreesTries
Points:50
Tags:
Depth First SearchTrieData StructuresDynamic ProgrammingAdvanced Data Structures