#P7991. [USACO21DEC] Connecting Two Barns S
[USACO21DEC] Connecting Two Barns S
Problem Description
Farmer John’s farm consists of fields (), numbered . There are bidirectional roads () between the fields, and each road connects two fields.
There are two barns on the farm: one in field and the other in field . Farmer John wants to make sure there is a way to walk between the two barns along some sequence of roads. He is willing to build at most two new roads to achieve this. Because of the fields’ locations, the cost to build a new road between fields and is .
Please help Farmer John find the minimum cost needed to make barns and reachable from each other.
Input Format
The input of each test file contains subtasks (). You must answer all subtasks correctly to pass the entire test file.
The first line contains , followed by subtasks.
For each subtask, the first line contains two integers and . The next lines each contain two integers and , indicating a road connecting two different fields and . The input guarantees that there is at most one road between any pair of fields, and the sum of over all subtasks does not exceed .
Output Format
Output lines. The -th line contains one integer, the minimum cost for the -th subtask.
2
5 2
1 2
4 5
5 3
1 2
2 3
4 5
2
1
Hint
[Sample Explanation]
- In the first subtask, the best way is to build one road connecting fields and , and one road connecting fields and .
- In the second subtask, the best way is to build one road connecting fields and . A second road is not needed.
[Constraints]
- Test point 2 satisfies .
- Test points 3-5 satisfy .
- Test points 6-10 have no additional constraints.
Translated by ChatGPT 5