Gomgomi's Part-Time Job
Time limit2sMemory limit1024 MB
Given a tree and delivery triples (A, B, C), count the ordered pairs of distinct cities where two drumsticks can be bought along the walk A to B to C.
- Level
Medium7 of 10
- Topics
- Tree, DFS, Implementation
- Solved
- No attempts yet
Problem

Gomgomi, who is good at running errands, recently got a chance to take a delivery part-time job.
In Gomgomi's country, delivery orders must be handled in pairs, in the order they came in. So once Gomgomi sets out, Gomgomi must visit two cities in order. Each order is written as a tuple of three cities . Gomgomi starts at city , where the restaurant is, travels along the shortest path to city , and then travels along the shortest path from to . The country is a tree: cities are connected by bidirectional roads, forming a connected graph.
Gomgomi likes chicken and tries to buy chicken drumsticks whenever possible. Gomgomi can buy a drumstick in any city passed along the way, but at most one drumstick per city. When the order is finished, there must be exactly two drumsticks.
Each time Gomgomi finishes an order, Gomgomi writes in a notebook the ordered pair of cities where the drumsticks were bought. For example, if a drumstick was bought in city 3 and then in city 1, the pair is written as .
Find the number of ordered pairs that can be made for each order.
Input
The first line contains the number of cities and the number of orders , separated by a space.
From the second line through the th line after that, each line contains integers and , separated by a space. This means there is a bidirectional road connecting city and city .
From the th line through the lines after that, each line contains integers , , and , separated by spaces, which form the delivery order .
Output
For each delivery order, print on a separate line the number of ordered pairs that can be made for that order. There are lines in total.