One-Way Street
Practice
1 (1 votes)
Algorithms
Open
Approved
Hard
Algorithms
Problem
54% Success 88 Attempts 50 Points 2s Time Limit 100000MB Memory 1024 KB Max Code

Hackerland is a big country with n cities and some roads. The cities are numbered from 1 to n. The city numbered 1 is the capital city. The people of Hackerland are very smart. They figured out that they need to build only n-1 roads to make travelling between each pair of cities possible. They built the roads in such a way that there exists a unique way to reach a city from each other city.

The roads have the following properties:

  1. Each road connects two cities, x and y. Keep in mind that out of x and y, one will be closer to the capital city than the other.
  2. Each road is a one-way road. Meaning that travelling is possible only from one of the two cities to the other and not in both directions.
  3. The direction of each road changes after one day. On day 1, all roads allow traffic to go away from the capital city. Then on day 2, all roads allow traffic to go towards the capital city. On day 3, again away from the capital city, and so on.

Given a source and destination city, your job is to find the number of days required to complete the journey. Assume that travelling on one road requires a whole day.

Input:

The first line of input contains t, the number of test cases.

The first line of each test case contains n, the number of cities. n-1 lines follow. Each line has two integers x and y, signifying that city x and city y are connected by a road. The next line contain q, the number of queries. Each of the next q lines contains two integers, a and b.

Output:

For each query output a single integer denoting the number of days required to travel from city a to city b. (a!=b)

Constraints:

1<=t<=5

2<=n<= 10000

1<=q<=100000

WARNING : Large input data. Be careful with certain languages.

C++ users: Use scanf instead of cin

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
22 votes
Tags:
Heavy Light DecompositionAdvanced AlgorithmsAlgorithms
Points:50
24 votes
Tags:
Data StructuresHardOpenBinary search treeHeavy light decompositionAlgorithms
Points:50
12 votes
Tags:
Data StructuresGraph TheoryOpenDivide-and-conquer algorithmHardAlgorithms