TSP
Time limit4sMemory limit1024 MB
Given K vertices in an implicit binary heap-shaped tree with up to 10^18 nodes, find the shortest walk that visits all of them.
Problem
The tree has vertices. For every integer with , there is an edge between vertex and vertex . You are given vertices in this tree. Find the length of the shortest path that starts at any vertex and visits each of the given vertices at least once.
Input
The first line contains the number of test cases .
The first line of each test case contains the number of vertices .
The second line of each test case contains the vertex numbers , separated by spaces. All are distinct.
All input values are integers.
The sum of over all test cases does not exceed .
Output
For each test case, print one line containing the length of the shortest path that starts at any vertex and visits each of the given vertices at least once.
Hint
A path of length in the tree is a sequence of visited vertices such that for each , and are connected by an edge. You may visit the same vertex or edge more than once.