// Arup Guha
// 8/3/2017
// Solution to 2017 UCF Locals Problem: Rotating Cards

import java.util.*;
import java.io.*;

public class cards {

	public static void main(String[] args) throws Exception {

		BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
		int numCases = Integer.parseInt(stdin.readLine());

		// Process each case.
		for (int loop=0; loop<numCases; loop++) {

			// Read in the ordering and store the inverse function.
			StringTokenizer tok = new StringTokenizer(stdin.readLine());
			int n = Integer.parseInt(tok.nextToken());
			int[] list = new int[n];
			for (int i=0; i<n; i++)
				list[i] = Integer.parseInt(tok.nextToken());
			int[] rev = new int[n+1];
			for (int i=0; i<n; i++)
				rev[list[i]] = i+1;

			// Put all values in the bit with gaps so we don't have to worry about off by one errors.
			// Intentionally inefficient so we can give the students a little bit of a buffer run time wise.
			bit mybit = new bit(2*n+1);
			for (int i=1; i<=n; i++)
				mybit.add(2*i,list[i-1]);

			// Initial values...
			int cur = 1;
			long left = ((long)n)*(n+1)/2;
			long res = 0;

			// Now, go through the queries.
			for (int i=1; i<=n; i++) {

				// Get the next item to go to.
				int next = rev[i];

				// Get range for query.
				int low = Math.min(cur, next);
				int high = Math.max(cur, next);

				// Add in best option to cost.
				long sum = mybit.sum(2*low-1, 2*high-1);
				long other = left - sum;
				res += Math.min(sum, other);

				// Bookkeeping - update what's left, BIT and cur index.
				left -= list[next-1];
				mybit.add(2*next, -list[next-1]);
				cur = next;
			}

			// Ta da!
			System.out.println(res);
		}
	}
}

class bit {

	public long[] cumfreq;

	// Do indexes 1 to n.
	public bit(int n) {
		int size = 1;
		while (size < n) size <<= 1;
		n = size;
		cumfreq = new long[n+1];
	}

	// Uses 1 based indexing.
	public void add(int index, long value) {
		while (index < cumfreq.length) {
			cumfreq[index] += value;
			index += (index&(-index));
		}
	}

	// Returns the sum of everything upto index.
	public long sum(int index) {
		long ans = 0;
		while (index > 0) {
			ans += cumfreq[index];
			index -= (index&(-index));
		}
		return ans;
	}

	// Use 1 based indexing.
	public long sum(int low, int high) {
		return sum(high) - sum(low-1);
	}
}