#P7991. [USACO21DEC] Connecting Two Barns S

[USACO21DEC] Connecting Two Barns S

Problem Description

Farmer John’s farm consists of NN fields (1N1051 \leq N \leq 10^5), numbered 1N1 \ldots N. There are MM bidirectional roads (0M1050 \leq M \leq 10^5) between the fields, and each road connects two fields.

There are two barns on the farm: one in field 11 and the other in field NN. 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 ii and jj is (ij)2(i-j)^2.

Please help Farmer John find the minimum cost needed to make barns 11 and NN reachable from each other.

Input Format

The input of each test file contains TT subtasks (1T201 \le T \le 20). You must answer all subtasks correctly to pass the entire test file.

The first line contains TT, followed by TT subtasks.

For each subtask, the first line contains two integers NN and MM. The next MM lines each contain two integers ii and jj, indicating a road connecting two different fields ii and jj. The input guarantees that there is at most one road between any pair of fields, and the sum of N+MN+M over all subtasks does not exceed 51055 \cdot 10^5.

Output Format

Output TT lines. The ii-th line contains one integer, the minimum cost for the ii-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 22 and 33, and one road connecting fields 33 and 44.
  • In the second subtask, the best way is to build one road connecting fields 33 and 44. A second road is not needed.

[Constraints]

  • Test point 2 satisfies N20N \le 20.
  • Test points 3-5 satisfy N103N \le 10^3.
  • Test points 6-10 have no additional constraints.

Translated by ChatGPT 5