XOR
Time limit2sMemory limit512 MB
In a connected weighted graph where a ride's cost is the XOR of its edge lengths and edges may repeat, answer queries for the minimum cost between two vertices.
- Level
Hard8 of 10
- Topics
- Graph, Bit manipulation, Union-find, Math
- Solved
- No attempts yet
Problem
A new city called Xor was recently built in Croatia. The city has intersections and two-way roads. Each road connects a pair of intersections and has a length, a non-negative integer. Mirko moved to Xor and plans to take taxis often. Taxi fares in Xor are computed in an unusual way. The price of a ride is the bitwise XOR of the lengths of the roads the taxi drives along. For example, a ride along roads of lengths 3, 4 and 6 costs 3 XOR 4 XOR 6 = 1. During one ride the taxi may drive along the same road several times, and every pass counts toward the price.
Mirko wants to spend as little as possible on his rides. Each ride is given by a starting intersection and a destination intersection , and you have to find the smallest possible price of that ride. The taxi may drive through intersection and keep going, but the ride has to end at .
Input
The first line contains the number of intersections and the number of roads . ()
Each of the next lines describes one road with three integers , and (, ), meaning that a road of length connects intersections and .
No two roads connect the same pair of intersections.
Every intersection can be reached from every other intersection.
The next line contains the number of Mirko's rides . ()
Each of the next lines describes one ride with the starting intersection and the destination intersection . ()
Output
For each of the rides print the smallest possible price on its own line, in the order the rides are given in the input.
Note that bit of XOR is 1 exactly when bit of and bit of differ. (for example, 0011 XOR 0101 = 0110)
Hint
In the first example the taxi visits intersections 1, 2, 3, 4, 5, 3, 2 in that order, and the price is 3 XOR 9 XOR 2 XOR 6 XOR 7 XOR 9 = 0.