This page is still under construction.

Parts of this page are still being built. What you see may change.

Connecting Two Barns

Time limit2sMemory limit1024 MB

Summary
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 NN fields (1≤N≤105)(1 \leq N \leq 10^5), conveniently numbered 1…N1 \ldots N. Between these fields are MM bi-directed paths (0≤M≤105)(0 \leq M \leq 10^5), each connecting a pair of fields.

The farm contains two barns, one in field 1 and the other in field NN. 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 ii and jj is (i−j)2(i-j)^2.

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

Input

Each input test case contains TT sub-cases (1≤T≤20)(1\le T\le 20), all of which must be 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 lines follow, each one containing two integers ii and jj, indicating a path between two different fields ii and jj. It is guaranteed that there is at most one path between any two fields, and that the sum of N+MN+M over all sub-test cases is at most 5⋅1055 \cdot 10^5.

Output

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

Examples1

  1. Example 1

    Input
    2
    5 2
    1 2
    4 5
    5 3
    1 2
    2 3
    4 5
    
    Expected output
    2
    1