class FenwickTree: """ Implements fenwick tree """ def __init__(self, N: int): """ Initializes fenwick tree with size N, indexed from 0 to N-1. """ self.__N = N self.__data = [0] * N def add(self, pos: int, val: int): """ Applies A[pos] += val """ assert 0 <= pos < self.__N pos += 1 while pos <= self.__N: self.__data[pos - 1] += val pos += pos & -pos def sum(self, s: int, e: int): """ Calculates sum(A[s:e]), where 0 <= s <= e <= N. """ assert 0 <= s <= e <= self.__N return self.__sum(e) - self.__sum(s) def __sum(self, pos: int): ans = 0 while pos > 0: ans += self.__data[pos - 1] pos -= pos & -pos return ans def main(): T = int(input()) for i in range(T): N = int(input()) *A, = map(int, input().split()) D = {} for i in range(N): if A[i] not in D: D[A[i]] = [] D[A[i]].append(i) ans = 0 F = FenwickTree(N) for k in sorted(D.keys()): for i in D[k]: ans += F.sum(0, i) * F.sum(i+1, N) for i in D[k]: F.add(i, 1) F = FenwickTree(N) for k in sorted(D.keys(), reverse=True): for i in D[k]: ans += F.sum(0, i) * F.sum(i+1, N) for i in D[k]: F.add(i, 1) for k in D.keys(): v = D[k] for i in range(len(v)): ans += (len(v)-1-2*i) * v[i] ans += i * (len(v)-i) print(ans) if __name__ == '__main__': main()