Connecting Two Barns
Time limit2sMemory limit1024 MB
Given N fields with M existing paths, find the minimum cost of adding at most two paths of cost (i-j)^2 so that fields 1 and N become connected.
- Level
Medium7 of 10
- Topics
- Graph, Union-find, Binary search, Greedy
- Solved
- No attempts yet
Problem
Farmer John's farm consists of a set of fields , conveniently numbered . Between these fields are bi-directed paths , each connecting a pair of fields.
The farm contains two barns, one in field 1 and the other in field . Farmer John would like to ensure that there is a way to walk between the two barns along some series of paths. He is willing to build up to two new paths to accomplish this goal. Due to the way the fields are situated, the cost of building a new path between fields and is .
Please help Farmer John determine the minimum cost needed such that barns and become reachable from each other.
Input
Each input test case contains sub-cases , all of which must be solved correctly to solve the input case.
The first line of input contains , after which sub-test cases follow.
Each sub-test case starts with two integers, and . Next, lines follow, each one containing two integers and , indicating a path between two different fields and . It is guaranteed that there is at most one path between any two fields, and that the sum of over all sub-test cases is at most .
Output
Output lines. The th line should contain a single integer giving the minimum cost for the th sub-test case.