Taking Photos
Time limit8sMemory limit1024 MB
Pick a closed walk through a tree from room 1 that crosses each corridor twice, so each friend's interval covers both of their rooms; minimize the total interval length.
- Level
Hard8 of 10
- Topics
- Tree, Dynamic programming, Bit manipulation, DFS
- Solved
- No attempts yet
Problem
Seoul Science High School can be represented as a tree of rooms and corridors, each connecting two different rooms. Every corridor can be walked in both directions, and any room can be reached from any other room through the corridors. Passing through one corridor takes time .
Bru is about to graduate, and he wants to take photos with friends with whom he built memories at Seoul Science High School.
Bru will take two couple photos with each of the friends. For the -th friend, the photos are taken in room and room . It is guaranteed that to travel from room to room , one must pass through room .
The photos require moving around the school, but if all friends walk together, it gets crowded. So Bru and his friends decide to move as follows.
First, Bru plans a tour of the school. The tour must satisfy the following conditions.
- The tour starts at room at time and ends by arriving at room at time .
- Every corridor is passed exactly twice, once in each direction.
- Time counts only corridor passage. Time for taking photos is ignored.
For convenience, write the tour as a sequence , where is the number of the room Bru has just arrived at at time .
Next, the friends choose when to join the tour. The -th friend chooses a join time and a leave time . Friend takes photos in rooms and with Bru, so Bru must visit both rooms during that interval. That is, there must exist integers and with , , and .
The travel time of friend is defined as . Bru wants to minimize the sum of all friends' travel times. Find the minimum possible sum of travel times.
Input
The first line contains the number of rooms and the number of friends .
From the second line to the -th line, line contains the two room numbers and connected by corridor , separated by a space.
From line to line , line contains the room numbers and where friend takes photos, separated by a space.
Output
Print the minimum possible sum of all friends' travel times.
Constraints
- ()
- ()
- ()
- The given structure of Seoul Science High School is guaranteed to be a tree.
- ()
- ()
- To travel from room to room , one must pass through room . ()
- All input values are integers.