#USACOC2213B. Connecting Two Barns

Connecting Two Barns

Description

Farmer John's farm consists of a set of NN fields,conveniently numbered 1N1 \ldots N. Between these fields are MM bi-directedpaths, each connecting a pair of fields.

The farm contains two barns, one in field 1 and the other in field NN. FarmerJohn would like to ensure that there is a way to walk between the two barnsalong some series of paths. He is willing to build up to two new paths toaccomplish this goal. Due to the way the fields are situated, the cost ofbuilding a new path between fields ii and jj is (ij)2(i-j)^2.

Please help Farmer John determine the minimum cost needed such that barns 11and NN become reachable from each-other.

  • 1N1051 \leq N \leq 10^5
  • 0M1050 \leq M \leq 10^5

Input Format

Each input test case contains TT sub-cases, all of which mustbe solved correctly to solve the input case.

The first line of input contains TT, after which TT sub-test cases follow.

Each sub-test case starts with two integers, NN and MM. Next, MM linesfollow, each one containing two integers ii and jj, indicating a path betweentwo different fields ii and jj. It is guaranteed that there is at most onepath between any two fields, and that the sum of N+MN+M over all sub-test casesis at most 51055 \cdot 10^5.

  • 1T201\le T\le 20

Output Format

Output TT lines. The iith line should contain a single integer giving theminimum cost for the iith sub-test case.

2
5 2
1 2
4 5
5 3
1 2
2 3
4 5
2
5 2
1 2
4 5
5 3
1 2
2 3
4 5

Scoring

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

Problem Credit

Problem credits: Nick Wu