Highways
Time limit3sMemory limit128 MB
Given a tree plus extra highway edges, count for each query (x,y) the main tree path plus alternative single-highway paths that touch the main path only at x and y.
- Level
Hard9 of 10
- Topics
- Tree, DFS, Prefix sum, Dynamic programming
- Solved
- No attempts yet
Problem
Byteland is a small country with cities connected by bidirectional roads. Using only roads, there is exactly one way to travel between any two cities, so the road network forms a tree. Because that single path causes heavy traffic, several highways were built, and each highway directly connects some pair of cities.
A route is a sequence of roads and highways along which every visited city is distinct (a simple path). For every pair of cities and there is exactly one route that uses no highway at all; we call it the main route between and (the unique path through the road network).
To travel from city to city , people may take the main route, or take an alternative route that uses exactly one highway. An alternative route is allowed only if it shares no city with the main route other than the endpoints and .
For each queried pair of cities, report the number of routes people can take between them (the main route together with every allowed alternative route).
Input
The first line contains a single integer (), the number of cities. Cities are numbered from to .
Each of the next lines contains two integers and (), meaning cities and are connected by a road.
The next line contains an integer (), the number of highways. Each of the next lines gives the two cities that one highway connects.
The next line contains an integer (), the number of queries. Each of the next lines contains two integers and , a query about travel between cities and . Highways and queries are given in the same two-integer format as the roads.
Output
Print exactly lines. The -th line must contain a single integer, the number of routes for the -th query.