Meet In The Middle
Time limit1sMemory limit1024 MB
Given a weighted tree and K queries each naming two villages, find the village where the two distances are equal, breaking ties by the smallest total distance, or -1.
- Level
Hard8 of 10
- Topics
- Tree, Graph, Shortest path, Math
- Solved
- No attempts yet
Problem
The kingdom of Sinchon has villages numbered through , connected by roads, each joining two distinct villages. Every village can be reached from every other village by roads, and travel within a village takes no distance.
Sinchon is now in turmoil from a pandemic of "symmetry sickness." A person with symmetry sickness feels uneasy in body and mind unless everything is symmetric, to the point of being unable to carry on daily life. The aftermath is so severe that even meetings between people have become difficult. Consider two people in Sinchon who want to meet. If the meeting place is closer to one person's village than the other's, they become very uncomfortable. So the meeting place must be chosen at a spot whose distance to each person's village is exactly the same. In other words, Meet in the middle. They must meet in the middle!
Given the road information of Sinchon and the villages of the two people who want to meet, find a suitable location for the meeting place.
Input
The first line gives the number of villages and the number of meetings .
The next lines give three integers , , describing a road. This means there is a road of length between village and village . , ,
The next lines give the village numbers , of the two people who want to meet.
Output
For each of the lines, print the number of a village where the two people can meet. If no such village exists, print -1. If there are several possible answers, print the one with the smallest sum of distances to the two people's villages.