Farmer John has a farm that consists of $n$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.

Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $d$, where $d_i$ is the smallest amount of time it took the cows to reach the $i$-th pasture from pasture $1$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.


-----Input-----

The first line contains one integer $t$ ($1 \leq t \leq 10^4$) — the number of test cases. Then $t$ cases follow.

The first line of each test case contains a single integer $n$ ($1 \leq n \leq 10^5$) — the number of pastures.

The second line of each test case contains $n$ space separated integers $d_1, d_2, \ldots, d_n$ ($0 \leq d_i \leq 10^9$) — the array $d$. It is guaranteed that $d_1 = 0$.

It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$.


-----Output-----

For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.


-----Examples-----

Input
3
3
0 2 3
2
0 1000000000
1
0
Output
-3
0
0


-----Note-----

In the first test case, you can add roads

from pasture $1$ to pasture $2$ with a time of $2$,

from pasture $2$ to pasture $3$ with a time of $1$,

from pasture $3$ to pasture $1$ with a time of $-3$,

from pasture $3$ to pasture $2$ with a time of $-1$,

from pasture $2$ to pasture $1$ with a time of $-2$.

The total cost is $2 + 1 + -3 + -1 + -2 = -3$.

In the second test case, you can add a road from pasture $1$ to pasture $2$ with cost $1000000000$ and a road from pasture $2$ to pasture $1$ with cost $-1000000000$. The total cost is $1000000000 + -1000000000 = 0$.

In the third test case, you can't add any roads. The total cost is $0$.

Difficulty: MEDIUM
Tags: Graph algorithms

Shortest paths

Constructive algorithms

Sorting

Greedy algorithms
Skill types: Sorting

Greedy algorithms

Starter code:

Solutions:
for _ in range(int(input())):
	n = int(input())
	d = [int(i) for i in input().split()]
	d.sort()
	total_cost = d[-1]
	for ind in range(n - 1):
		total_cost -= (ind + 1) * (n - (ind + 1)) * (d[ind + 1] - d[ind])
	print(total_cost)


from collections import defaultdict
for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	ans = 0
	presum = 0
	for j in range(1, n):
		presum += a[j - 1]
		x = a[j] - a[j - 1]
		y = a[j] * j - presum
		ans += x - y
	print(ans)


for iters in range(int(input())):
	n = int(input())
	num = [int(i) for i in input().split(' ')]
	num.sort()
	negative = 0
	for i in range(0, n):
		negative += (n - 2 * i - 1) * num[i]
	negative += num[n - 1]
	print(negative)


import os
import sys
from io import BytesIO, IOBase
import bisect
import math
from collections import Counter, defaultdict

def main():
	t = int(input())
	while t:
		n = int(input())
		l = [int(i) for i in input().split()]
		l.sort()
		s = l[-1]
		neg = [0] * n
		for i in range(1, n):
			neg[i] = neg[i - 1] + i * (l[i] - l[i - 1])
			s -= neg[i]
		print(s)
		t -= 1
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


T = int(input())
for _ in range(T):
	n = int(input())
	A = list(map(int, input().split()))
	A.sort()
	ans = 0
	val = n - 1
	sub = n - 3
	for i in range(1, n):
		ans = ans + (val - 1) * (A[i] - A[i - 1])
		val = val + sub
		sub = sub - 2
	print(-1 * ans)


import math

def main(args):
	t = int(input())
	for test in range(1, t + 1):
		n = int(input())
		arr = input().split(' ')
		for i in range(len(arr)):
			arr[i] = int(arr[i])
		if n <= 2:
			print(0)
			continue
		arr.sort()
		totals = []
		v = 0
		for i in arr:
			v += i
			totals += [v]
		ans = 0
		for i in range(len(arr)):
			if i - 2 >= 0:
				ans += (i - 1) * arr[i] - totals[i - 2]
		print(-ans)
	return 0
import sys
sys.exit(main(sys.argv))


def solve():
	n = int(input())
	a = sorted((int(v) for v in input().split()))
	if n < 3:
		return 0
	s = a.copy()
	for i in range(n - 1):
		s[i + 1] += s[i]
	ans = 0
	for i in range(n - 2):
		ans += s[-1] - s[i + 1] - a[i] * (n - 2 - i)
	return -ans
t = int(input())
while t:
	t -= 1
	print(solve())


for _ in range(int(input())):
	n = int(input())
	d = list(map(int, input().split()))
	d.sort()
	ans = d[-1] - d[0]
	for i in range(n):
		ans += (n - i - i - 1) * d[i]
	print(ans)


T = int(input())
for q in range(T):
	TT = 0
	tt = 2
	n = int(input())
	arr = input().split()
	arr = list(map(int, arr))
	fin = 0
	arr.sort()
	for i in range(tt, n):
		fin = -((i - 1) * arr[i]) + fin
		TT = arr[i - 2] + TT
		fin = TT + fin
	print(fin)


def solve():
	D.sort()
	ans = 0
	for i in range(1, N):
		left = i
		right = N - i
		weight = D[i - 1] - D[i]
		ans += left * right * weight - weight
	return ans
test_cases = int(input())
for test_case in range(test_cases):
	N = int(input())
	D = list(map(int, input().split()))
	print(solve())


def solve(arr, n):
	if n <= 2:
		return 0
	arr.sort(reverse=True)
	ans = 0
	total = sum(arr)
	for i in range(n - 1):
		total -= arr[i]
		ans += total
		ans = ans - (n - i - 1) * arr[i]
	ans += max(arr)
	return ans
t = int(input())
for _ in range(t):
	n = int(input())
	d = list(map(int, input().split()))
	print(solve(d, n))


for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	cost = 0
	for i in range(1, n):
		cost += i * (n - i) * (a[i] - a[i - 1])
	cost *= -1
	cost += a[n - 1]
	print(cost)


def func1(n, d):
	d_max = max(d)
	result = d_max
	sor = sorted(d)
	for i in range(1, n):
		result += (-1 * i + (n - i - 1)) * sor[i]
	print(result)

def main():
	t = int(input())
	for i in range(t):
		n = int(input())
		d = list(map(int, input().split()))
		if n == 1 or n == 2:
			print(0)
		else:
			func1(n, d)
main()


def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = [int(word) for word in input().split()]
		a.sort()
		ans = 0
		cur = 0
		for i in range(1, n):
			cur += (a[i] - a[i - 1]) * i
			ans -= cur
		print(ans + a[-1])
main()


from math import ceil
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	(res, s) = (0, 0)
	for i in range(2, n):
		s += arr[i - 2]
		res -= arr[i] * (i - 1)
		res += s
	print(res)


def solve(n, a):
	c = 0
	r = 0
	for i in range(n):
		if i > 0:
			c += i * a[i] - r
		r += a[i]
	c -= a[-1]
	return -c
t = int(input())
for i in range(t):
	n = int(input())
	a = sorted(map(int, input().split()))
	print(solve(n, a))


import os
import sys
from io import BytesIO, IOBase
_str = str
str = lambda x=b'': x if type(x) is bytes else _str(x).encode()
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	ans = 0
	for i in range(n - 1):
		ans += (1 - (i + 1) * (n - i - 1)) * (a[i + 1] - a[i])
	print(ans)


def f(a):
	ans = 0
	n = len(a)
	a = sorted(a)
	for i in range(1, len(a)):
		ans += (i - 1) * a[i]
		ans -= max(n - i - 1 - 1, 0) * a[i]
	return -1 * ans
for _ in range(int(input())):
	l = input()
	lst = list(map(int, input().strip().split()))
	print(f(lst))


import sys
input = sys.stdin.readline

def stup(a):
	r = 0
	for i in range(len(a)):
		for j in range(i + 2, len(a)):
			r -= a[j] - a[i]
	return r

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	s = sum(a)
	r = 0
	for i in range(len(a) - 2):
		s -= a[i + 1]
		r -= s - a[i] * (n - i - 2)
	print(r)
for i in range(int(input())):
	solve()


for _ in range(int(input())):
	n = int(input())
	arr = list(sorted(map(int, input().split())))
	if n == 1:
		print(0)
		continue
	narr = [arr[1]]
	for (i, x) in enumerate(arr):
		if i < 2:
			continue
		d = x - arr[i - 1]
		narr.append(narr[-1] + i * d)
	print(-(sum(narr) - arr[-1]))


def solve(lt):
	lt.sort()
	c = 0
	for i in range(len(lt)):
		c += -1 * (lt[i] * i) + (len(lt) - 1 - i) * lt[i]
	c += lt[-1] - lt[0]
	return c
t = int(input())
for i in range(t):
	input()
	lt = list(map(int, input().split()))
	print(solve(lt))


for g in range(int(input())):
	n = int(input())
	l = sorted(list(map(int, input().split())))
	f = 0
	k = 0
	for i in range(2, n):
		k += l[i - 2]
		f -= l[i] * (i - 1)
		f += k
	print(f)


def main():
	for i in range(int(input())):
		(nPastures, times) = (int(input()), sorted(map(int, input().split())))
		if nPastures < 3:
			print(0)
		else:
			print(minimumCost(nPastures - 1, times))

def minimumCost(firstFactor, times):
	costMin = times[-1]
	prevFactor = 0
	if firstFactor % 2:
		finalFactor = -(-firstFactor // 2)
		for (i, j) in enumerate(range(firstFactor, finalFactor, -1)):
			prevFactor += 2 * j - firstFactor
			costMin -= prevFactor * (times[i + 1] - times[i] + times[j] - times[j - 1])
		return costMin - (prevFactor + 2 * finalFactor - firstFactor) * (times[finalFactor] - times[finalFactor - 1])
	for (i, j) in enumerate(range(firstFactor, firstFactor // 2, -1)):
		prevFactor += 2 * j - firstFactor
		costMin -= prevFactor * (times[i + 1] - times[i] + times[j] - times[j - 1])
	return costMin
main()


from math import *

def putin():
	return map(int, input().split())

def sol():
	n = int(input())
	A = list(putin())
	A.sort()
	answer = 0
	for i in range(n):
		answer += A[i] * max(n - i - 2, 0)
		answer -= A[i] * max(i - 1, 0)
	print(answer)
for itr in range(int(input())):
	sol()


from collections import deque, Counter
from collections import defaultdict as dfd
from bisect import bisect, bisect_left
from math import sqrt, gcd, ceil, factorial
from heapq import heapify, heappush, heappop
MOD = 10 ** 9 + 7
inf = float('inf')
ans_ = []

def nin():
	return int(input())

def ninf():
	return int(file.readline())

def st():
	return input().strip()

def stf():
	return file.readline().strip()

def read():
	return list(map(int, input().strip().split()))

def readf():
	return list(map(int, file.readline().strip().split()))

def readfl():
	return list(map(float, input().strip().split()))

def readffl():
	return list(map(float, file.readline().strip().split()))

def solve():
	for _ in range(nin()):
		n = nin()
		arr = read()
		arr.sort()
		ans = arr[-1]
		x = 0
		last = 0
		for i in range(1, n):
			last -= i * (arr[i] - arr[i - 1])
			ans += last
		ans_.append(ans)
solve()
for i in ans_:
	print(i)


t = int(input())
for i in range(t):
	n = int(input())
	nd = list(map(int, input().split()))
	nd.sort()
	total = 0
	data = 0
	for j in range(2, n):
		total += nd[j - 2]
		data -= nd[j] * (j - 1)
		data += total
	print(data)


T = int(input())
for t in range(T):
	n = int(input())
	d = [int(x) for x in input().split()]
	d.sort()
	if len(d) == 2 or len(d) == 1:
		print(0)
	else:
		s = 0
		for i in range(1, n):
			s = s + -1 * (n - (2 * i + 1)) * d[i]
		print(d[n - 1] - s)


def readline():
	return map(int, input().split())

def solve():
	n = int(input())
	(prev, *d) = sorted(readline())
	s = 0
	for (i, curr) in enumerate(d, start=1):
		(prev, x) = (curr, curr - prev)
		s -= x * (i * (n - i) - 1)
	print(s)

def main():
	t = int(input())
	for __ in range(t):
		solve()
main()


import math

def I():
	return input()

def II():
	return int(I())

def M():
	return map(int, I().split())

def L():
	return list(M())

def P(a):
	print(a)
for _ in range(II()):
	n = II()
	d = L()
	d.sort()
	if n > 2:
		k = 1
		s = 0
		for i in range(2, n):
			s += k * d[i] - d[i - 2] * (n - i)
			k += 1
		print(-1 * s)
	else:
		print(0)


def main():
	t = int(input())
	while t > 0:
		t -= 1
		n = int(input())
		val = list(map(int, input().split()))
		val.sort()
		suma = 0
		aux = 0
		for i in range(n - 1):
			aux = val[i + 1] - val[i]
			suma -= (i + 1) * (n - i - 1) * aux
			suma += aux
		print(suma)
main()


for _ in range(int(input())):
	n = int(input())
	mas = sorted(list(map(int, input().split())))
	sm = 0
	otv = 0
	for i in range(1, n):
		to = mas[i] - mas[i - 1]
		otv += to
		sm += to * i
		otv -= sm
	print(otv)


def great_graphs(D):
	D.sort()
	sum_ = D[len(D) - 1]
	neg = [0]
	for i in range(1, len(D)):
		neg.append(neg[i - 1] + i * (D[i] - D[i - 1]))
		sum_ -= neg[i]
	print(sum_)
t = int(input())
D = []
for i in range(t):
	n = int(input())
	D = [int(i) for i in input().split()][:n]
	great_graphs(D)


for s in [*open(0)][2::2]:
	n = len((a := sorted(map(int, s.split()))))
	r = i = 0
	for (x, y) in zip(a, a[1:]):
		i += 1
		r -= (y - x) * (i * (n - i) - 1)
	print(r)


def main():
	T = int(input())
	for i in range(T):
		n = int(input())
		arr = sorted(list(map(int, input().split())))
		(sm, rs) = (0, 0)
		for i in range(2, n):
			sm += arr[i - 2]
			rs -= arr[i] * (i - 1)
			rs += sm
		print(rs)
main()


def main():
	for i in range(int(input())):
		(nPastures, times) = (int(input()), list(map(int, input().split())))
		times.sort()
		if nPastures < 3:
			print(0)
		else:
			print(minimumCost(nPastures - 1, times))

def minimumCost(firstFactor, times):
	costMin = times[-1] - firstFactor * (times[1] - times.pop(0) + times.pop(-1) - times[-1])
	prevFactor = firstFactor
	if firstFactor % 2:
		finalFactor = -(-firstFactor // 2)
		for i in range(firstFactor - 1, finalFactor, -1):
			prevFactor = prevFactor + 2 * i - firstFactor
			costMin -= prevFactor * (times[1] - times.pop(0) + times.pop(-1) - times[-1])
		return costMin - (prevFactor + 2 * finalFactor - firstFactor) * (times[1] - times[0])
	for i in range(firstFactor - 1, firstFactor // 2, -1):
		prevFactor = prevFactor + 2 * i - firstFactor
		costMin -= prevFactor * (times[1] - times.pop(0) + times.pop(-1) - times[-1])
	return costMin
main()


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	val = 0
	summ = 0
	for i in range(2, n):
		summ += arr[i - 2]
		val -= arr[i] * (i - 1)
		val += summ
	print(val)


for _ in range(int(input())):
	n = int(input())
	list1 = list(map(int, input().split()))
	list1.sort()
	ans = 0
	sums = 0
	p = 2
	while p < n:
		sums = sums + list1[p - 2]
		ans = ans - list1[p] * (p - 1)
		ans = ans + sums
		p = p + 1
	print(ans)


def greatGraphs(n, d):
	if n == 1:
		return d[0]
	d = sorted(d)
	k = []
	for i in range(n - 1):
		k.append(d[i + 1] - d[i])
	cost = sum(k)
	for i in range(n - 2, -1, -1):
		cost -= k[i] * (n - 1 - i) * (i + 1)
	return cost
for _ in range(int(input())):
	n = int(input())
	d = list(map(int, input().split()))
	print(greatGraphs(n, d))


import os
import sys
import math
from io import BytesIO, IOBase
import io
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
from collections import Counter
import threading
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree1:

	def __init__(self, data, default=10 ** 6, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)
MOD = 10 ** 9 + 7

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod = 10 ** 9 + 7
omod = 998244353
prime = [True for i in range(10001)]
prime[0] = prime[1] = False

def SieveOfEratosthenes(n=10000):
	p = 2
	c = 0
	while p <= n:
		if prime[p] == True:
			c += 1
			for i in range(p, n + 1, p):
				prime[i] = False
		p += 1

class DSU:

	def __init__(self, R, C):
		self.par = range(R * C + 1)
		self.rnk = [0] * (R * C + 1)
		self.sz = [1] * (R * C + 1)

	def find(self, x):
		if self.par[x] != x:
			self.par[x] = self.find(self.par[x])
		return self.par[x]

	def union(self, x, y):
		(xr, yr) = (self.find(x), self.find(y))
		if xr == yr:
			return
		if self.rnk[xr] < self.rnk[yr]:
			(xr, yr) = (yr, xr)
		if self.rnk[xr] == self.rnk[yr]:
			self.rnk[xr] += 1
		self.par[yr] = xr
		self.sz[xr] += self.sz[yr]

	def size(self, x):
		return self.sz[self.find(x)]

	def top(self):
		return self.size(len(self.sz) - 1) - 1

class LazySegTree:

	def __init__(self, _op, _e, _mapping, _composition, _id, v):

		def set(p, x):
			assert 0 <= p < _n
			p += _size
			for i in range(_log, 0, -1):
				_push(p >> i)
			_d[p] = x
			for i in range(1, _log + 1):
				_update(p >> i)

		def get(p):
			assert 0 <= p < _n
			p += _size
			for i in range(_log, 0, -1):
				_push(p >> i)
			return _d[p]

		def prod(l, r):
			assert 0 <= l <= r <= _n
			if l == r:
				return _e
			l += _size
			r += _size
			for i in range(_log, 0, -1):
				if l >> i << i != l:
					_push(l >> i)
				if r >> i << i != r:
					_push(r >> i)
			sml = _e
			smr = _e
			while l < r:
				if l & 1:
					sml = _op(sml, _d[l])
					l += 1
				if r & 1:
					r -= 1
					smr = _op(_d[r], smr)
				l >>= 1
				r >>= 1
			return _op(sml, smr)

		def apply(l, r, f):
			assert 0 <= l <= r <= _n
			if l == r:
				return
			l += _size
			r += _size
			for i in range(_log, 0, -1):
				if l >> i << i != l:
					_push(l >> i)
				if r >> i << i != r:
					_push(r - 1 >> i)
			l2 = l
			r2 = r
			while l < r:
				if l & 1:
					_all_apply(l, f)
					l += 1
				if r & 1:
					r -= 1
					_all_apply(r, f)
				l >>= 1
				r >>= 1
			l = l2
			r = r2
			for i in range(1, _log + 1):
				if l >> i << i != l:
					_update(l >> i)
				if r >> i << i != r:
					_update(r - 1 >> i)

		def _update(k):
			_d[k] = _op(_d[2 * k], _d[2 * k + 1])

		def _all_apply(k, f):
			_d[k] = _mapping(f, _d[k])
			if k < _size:
				_lz[k] = _composition(f, _lz[k])

		def _push(k):
			_all_apply(2 * k, _lz[k])
			_all_apply(2 * k + 1, _lz[k])
			_lz[k] = _id
		_n = len(v)
		_log = _n.bit_length()
		_size = 1 << _log
		_d = [_e] * (2 * _size)
		_lz = [_id] * _size
		for i in range(_n):
			_d[_size + i] = v[i]
		for i in range(_size - 1, 0, -1):
			_update(i)
		self.set = set
		self.get = get
		self.prod = prod
		self.apply = apply
MIL = 1 << 20

def makeNode(total, count):
	return total * MIL + count

def getTotal(node):
	return math.floor(node / MIL)

def getCount(node):
	return node - getTotal(node) * MIL
nodeIdentity = makeNode(0.0, 0.0)

def nodeOp(node1, node2):
	return node1 + node2
	return makeNode(getTotal(node1) + getTotal(node2), getCount(node1) + getCount(node2))
identityMapping = -1

def mapping(tag, node):
	if tag == identityMapping:
		return node
	count = getCount(node)
	return makeNode(tag * count, count)

def composition(mapping1, mapping2):
	return mapping1 if mapping1 != identityMapping else mapping2

def memodict(f):

	class memodict(dict):

		def __missing__(self, key):
			ret = self[key] = f(key)
			return ret
	return memodict().__getitem__

def pollard_rho(n):
	if n & 1 == 0:
		return 2
	if n % 3 == 0:
		return 3
	s = (n - 1 & 1 - n).bit_length() - 1
	d = n >> s
	for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
		p = pow(a, d, n)
		if p == 1 or p == n - 1 or a % n == 0:
			continue
		for _ in range(s):
			prev = p
			p = p * p % n
			if p == 1:
				return math.gcd(prev - 1, n)
			if p == n - 1:
				break
		else:
			for i in range(2, n):
				(x, y) = (i, (i * i + 1) % n)
				f = math.gcd(abs(x - y), n)
				while f == 1:
					(x, y) = ((x * x + 1) % n, (y * y + 1) % n)
					y = (y * y + 1) % n
					f = math.gcd(abs(x - y), n)
				if f != n:
					return f
	return n

@memodict
def prime_factors(n):
	if n <= 1:
		return Counter()
	f = pollard_rho(n)
	return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f)

def distinct_factors(n):
	factors = [1]
	for (p, exp) in prime_factors(n).items():
		factors += [p ** i * factor for factor in factors for i in range(1, exp + 1)]
	return factors

def all_factors(n):
	(small, large) = ([], [])
	for i in range(1, int(n ** 0.5) + 1, 2 if n & 1 else 1):
		if not n % i:
			small.append(i)
			large.append(n // i)
	if small[-1] == large[-1]:
		large.pop()
	large.reverse()
	small.extend(large)
	return small

def binarySearch(arr, n, key):
	left = 0
	right = n - 1
	mid = 0
	res = arr[n - 1]
	while left <= right:
		mid = (right + left) // 2
		if arr[mid] >= key:
			res = arr[mid]
			right = mid - 1
		else:
			left = mid + 1
	return res

def binarySearch1(arr, n, key):
	left = 0
	right = n - 1
	mid = 0
	res = arr[0]
	while left <= right:
		mid = (right + left) // 2
		if arr[mid] > key:
			right = mid - 1
		else:
			res = arr[mid]
			left = mid + 1
	return res
t = 1
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	s = 0
	res = 0
	for i in range(2, n):
		res -= (i - 1) * a[i] - s
		s += a[i - 1]
	print(res)


import os
import sys
from io import BytesIO, IOBase
import math
from decimal import Decimal
from decimal import *
from collections import defaultdict, deque
import heapq
from decimal import Decimal
getcontext().prec = 25
abcd = 'abcdefghijklmnopqrstuvwxyz'
ABCD = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
months = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}
MOD = 1000000007
BUFSIZE = 8192
from bisect import bisect_left, bisect_right

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split(' ')))
	l.sort()
	ans = 0
	f = []
	for i in range(n - 1):
		ans += l[i + 1] - l[i]
		f.append(l[i] - l[i + 1])
	for i in range(n - 1):
		ans += (n - 1 - i) * (i + 1) * f[i]
	print(ans)


def sq(a):
	return a * a
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	count = 0
	val = 0
	for i in range(2, n):
		val += a[i - 2]
		count -= a[i] * (i - 1)
		count += val
	print(count)


from itertools import accumulate

def solve(ar):
	cnt = [i * x for (i, x) in enumerate(ar, 1)]
	return sum(accumulate(cnt))
for _ in range(int(input())):
	n = int(input())
	ar = list(map(int, input().split()))
	ar.sort()
	dif = []
	for i in range(n - 1):
		dif.append(ar[i + 1] - ar[i])
	dif = dif[::-1]
	print(sum(dif) - solve(dif))


def solve_pastures(n, arr):
	arr = sorted(arr)
	result = 0
	prev = n - 2
	for x in range(n - 1):
		result += (arr[x] - arr[x + 1]) * prev
		prev += n - (x + 2) - (x + 1)
	print(result)
for _ in range(int(input())):
	n = int(input())
	solve_pastures(n, list(map(int, input().split())))


import sys
t = int(sys.stdin.readline())
for _ in range(t):
	n = int(sys.stdin.readline())
	bn = list(map(int, sys.stdin.readline().split()))
	bn.sort()
	if len(bn) > 2:
		answer = -(bn[2] - bn[0])
		dp = answer
		for i in range(3, n):
			dp = dp - (bn[i] - bn[i - 1]) * (i - 2) - (bn[i] - bn[i - 2])
			answer += dp
	else:
		answer = 0
	print(answer)


t = int(input())
for i in range(t):
	n = int(input())
	lis = list(map(int, input().split()))
	lis.sort()
	s = 0
	for i in range(n - 1):
		x = lis[i + 1] - lis[i]
		s -= (i + 1) * (n - i - 1) * x
		s += x
	print(s)


for _ in range(int(input())):
	n = int(input())
	d = sorted(list(map(int, input().split())))
	result = d[n - 1]
	for i in range(1, n):
		result -= d[i] * i - d[i - 1]
		d[i] += d[i - 1]
	print(result)


for t in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l = sorted(l)
	min_sum = 0
	for i in range(1, n):
		va = l[i] - l[i - 1]
		min_sum = min_sum + va * (i * (n - i))
	min_sum = -(min_sum - l[n - 1])
	print(min_sum)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	f = 0
	count = 0
	for i in range(2, n):
		count += l[i - 2]
		f -= l[i] * (i - 1)
		f += count
	print(f)


import os, sys
from io import BytesIO, IOBase
from math import log2, ceil, sqrt, gcd
from _collections import deque
import heapq as hp
from bisect import bisect_left, bisect_right
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for i in range(int(input())):
	n = int(input())
	a = sorted(list(map(int, input().split())))
	ans = 0
	tot = 0
	for i in range(1, n):
		ans += -i * a[i] + (a[i] - a[i - 1]) + tot
		tot += a[i]
	print(ans)


import sys
from math import sqrt

def sort_abs_diff(n):
	return abs(n - 50)

def main():
	pass

def binary(n):
	return bin(n).replace('0b', '')

def decimal(s):
	return int(s, 2)

def isPrime(n):
	if n == 1:
		return False
	else:
		root = int(n ** 0.5)
		root += 1
		for i in range(2, root):
			if n % i == 0:
				return False
		return True

def lts(l):
	s = ''.join(map(str, l))
	return s
mod = int(1000000000.0) + 7

def sinp():
	return sys.stdin.readline().strip()

def zinp():
	return int(input())

def zzinp():
	return map(int, sys.stdin.readline().strip().split())

def llinp():
	return list(map(int, sys.stdin.readline().strip().split()))

def p(xyz):
	print(xyz)

def p2(a, b):
	print(a, b)
for _ in range(zinp()):
	n = zinp()
	l1 = llinp()
	l1.sort()
	curr = 0
	ans = 0
	for i in range(2, n):
		ans += l1[i - 2]
		curr -= l1[i] * (i - 1)
		curr += ans
	print(curr)


def main():
	for _ in range(int(input())):
		n = int(input())
		d = sorted(list(map(int, input().split())))
		if n == 1:
			print(0)
			continue
		s = sum(d)
		m = d[1]
		f = n - 4
		k = f + 1
		r = 0
		for i in range(2, n):
			r += k * (d[i] - d[i - 1])
			k += f
			f -= 2
		print(-(s - m) - r)
main()


t = int(input())
for _ in range(t):
	(n, d) = (int(input()), [int(x) for x in input().split()][1:])
	d.sort()
	if n == 1:
		print(0)
	else:
		(s, ps) = (min(d[0], 0), d[0])
		for i in range(1, n - 1):
			s += -abs(d[i]) + (ps - d[i - 1]) - (i - 1) * d[i]
			ps += d[i]
		print(s)


t = int(input())
while t > 0:
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	ans = 0
	temp = 0
	for i in range(n - 2):
		temp += arr[i]
		ans = ans + temp
		ans = ans - arr[i + 2] * (i + 1)
	print(ans)
	t = t - 1


t = int(input())
for i in range(t):
	n = int(input())
	d = list(map(int, input().split()))
	d.sort()
	md = max(d)
	for j in range(n):
		d[j] = d[j] * (2 * j - n + 1)
	print(md - sum(d))


def solve(n, arr):
	n -= 1
	if n == 0:
		return 0
	arr.sort()
	return arr[-1] - sum(((-n + 2 + 2 * i) * arr[i] for i in range(n)))
import sys
input = lambda : sys.stdin.readline().rstrip()
t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))[1:]
	print(solve(n, arr))


def ans(d):
	n = len(d)
	d.sort()
	a = d[n - 1]
	for j in range(1, n + 1):
		a += d[j - 1] * (n - 2 * j + 1)
	return a
t = int(input())
for i in range(t):
	input()
	print(ans(list(map(int, input().split()))))


def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		A = list(map(int, input().split()))
		A.sort()
		D = []
		for i in range(n - 1):
			D.append(A[i + 1] - A[i])
		ans = A[-1]
		for i in range(n - 1):
			temp = D[i] * (i + 1) * (n - 1 - i)
			ans -= temp
		print(ans)
main()


import bisect
from collections import *
from itertools import *
import math
import heapq
import sys
from pprint import pprint
input = sys.stdin.readline

def inp():
	return int(input())

def inlist():
	return list(map(int, input().split()))

def instring():
	s = input()
	return list(s[:len(s) - 1])

def invariable():
	return map(int, input().split())

def main(a):
	n = len(a)
	if n == 1:
		return 0
	a = sorted(a)
	b = []
	for (x1, x2) in zip(a[:-1], a[1:]):
		b.append(x2 - x1)
	res = 0
	m = len(b)
	for i in range(len(b)):
		bi = b[i]
		mul = (m - i) * (i + 1)
		res += bi * mul
	return -res + max(a)
t = inp()
outputs = []
for _ in range(t):
	n = inp()
	a = inlist()
	output = main(a)
	outputs.append(output)
for o in outputs:
	if type(o) is list:
		print(' '.join(map(str, o)))
	else:
		print(o)


from collections import defaultdict
import sys
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.buffer.readline())

def MI():
	return map(int, sys.stdin.buffer.readline().split())

def LI():
	return list(map(int, sys.stdin.buffer.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def BI():
	return sys.stdin.buffer.readline().rstrip()

def SI():
	return sys.stdin.buffer.readline().rstrip().decode()

def li():
	return [int(i) for i in input().split()]

def lli(rows):
	return [li() for _ in range(rows)]

def si():
	return input()

def ii():
	return int(input())

def ins():
	return input().split()

def solve():
	n = II()
	d = LI()
	d.sort()
	d_sum = [0]
	for i in range(1, n):
		d_sum.append(d_sum[-1] + d[i])
	return -(sum(d[:n - 1]) + sum([(i - 1) * d[i] - d_sum[i - 1] for i in range(2, n)]))

def main():
	for _ in range(II()):
		sys.stdout.write(str(solve()) + '\n')
main()


it = int(input())
for ite in range(it):
	a = int(input())
	mm = []
	c = input().split()
	b = map(int, c)
	for i in b:
		mm.append(i)
	mm.sort()
	k = int(mm[-1])
	su = 0
	for i in range(a):
		su += int(mm[i]) * (i - a + i + 1)
	print(k - su)


for _ in range(int(input())):
	n = int(input())
	m = list(map(int, input().split()))
	m.sort()
	v = 0
	l = 0
	for i in range(2, n):
		l += m[i - 2]
		v -= m[i] * (i - 1)
		v += l
	print(v)


import sys
import math
import heapq
from collections import defaultdict as dd
from collections import OrderedDict as od
from collections import deque
from itertools import permutations as pp
from itertools import combinations as cc
from sys import stdin
from functools import cmp_to_key
from functools import lru_cache
from bisect import bisect_left as bs_l
from bisect import bisect_right as bs_r
input = sys.stdin.readline
mod = 10 ** 9 + 7
sys.setrecursionlimit(10 ** 5)
T = int(input())
for _ in range(T):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	l = []
	for i in range(1, n):
		l.append(arr[i] - arr[i - 1])
	(ml, prev) = (1, 0)
	ans = 0
	ss = sum(l)
	for i in l:
		k = ml * i
		prev += k
		ml += 1
		ans += prev
	print(ss - ans)


T = int(input())
for k in range(T):
	n = int(input())
	d = list(map(int, input().split()))
	d.sort()
	S = d[:]
	for i in range(1, n):
		S[i] += S[i - 1]
	ans = d[-1]
	for i in range(1, n):
		ans += S[i - 1] - i * d[i]
	print(ans)


t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	req = 0
	s = 0
	j = 2
	while j < n:
		req -= l[j] * (j - 1)
		s += l[j - 2]
		req += s
		j += 1
	print(req)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a = sorted(a)
	b = []
	for i in range(1, n):
		b += [a[i] - a[i - 1]]
	ans = 0
	n = len(b)
	for i in range(n):
		ans -= (n - i) * (i + 1) * b[i]
	print(ans + sum(b))


t = int(input())
for z in range(t):
	x = int(input())
	li = list(map(int, input().split()))
	c1 = 0
	diff = 0
	li.sort()
	for i in range(2, x):
		c1 += li[i - 2]
		diff -= li[i] * (i - 1)
		diff += c1
	print(diff)


import heapq
import sys
from math import *
import threading
from heapq import *
from itertools import count
from pprint import pprint
from collections import defaultdict
from heapq import heapify, heappop, heappush
sys.setrecursionlimit(300000)
mod = 10 ** 9 + 7
inf = 10 ** 15
decision = ['NO', 'YES']
yes = 'YES'
no = 'NO'
import os
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def npr(n, r):
	return factorial(n) % mod // (factorial(n - r) % mod) if n >= r else 0

def ncr(n, r):
	return factorial(n) % mod // (factorial(r) % mod * (factorial(n - r) % mod)) if n >= r else 0

def lower_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer

def upper_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] <= num:
			answer = middle
			start = middle + 1
		else:
			end = middle - 1
	return answer

def abs(x):
	return x if x >= 0 else -x

def binary_search(li, val):
	ans = -1
	lb = 0
	ub = len(li) - 1
	while lb <= ub:
		mid = (lb + ub) // 2
		if li[mid] > val:
			ub = mid - 1
		elif val > li[mid]:
			lb = mid + 1
		else:
			ans = mid
			break
	return ans

def kadane(x):
	sum_so_far = 0
	current_sum = 0
	for i in x:
		current_sum += i
		if current_sum < 0:
			current_sum = 0
		else:
			sum_so_far = max(sum_so_far, current_sum)
	return sum_so_far

def pref(li):
	pref_sum = [0]
	for i in li:
		pref_sum.append(pref_sum[-1] + i)
	return pref_sum

def SieveOfEratosthenes(n):
	prime = [{1, i} for i in range(n + 1)]
	p = 2
	while p <= n:
		for i in range(p * 2, n + 1, p):
			prime[i].add(p)
		p += 1
	return prime

def primefactors(n):
	factors = []
	while n % 2 == 0:
		factors.append(2)
		n //= 2
	for i in range(3, int(sqrt(n)) + 1, 2):
		while n % i == 0:
			factors.append(i)
			n //= i
	if n > 2:
		factors.append(n)
	return factors

def prod(li):
	ans = 1
	for i in li:
		ans *= i
	return ans

def sumk(a, b):
	print('called for', a, b)
	ans = a * (a + 1) // 2
	ans -= b * (b + 1) // 2
	return ans

def sumi(n):
	ans = 0
	if len(n) > 1:
		for x in n:
			ans += int(x)
		return ans
	else:
		return int(n)

def checkwin(x, a):
	if a[0][0] == a[1][1] == a[2][2] == x:
		return 1
	if a[0][2] == a[1][1] == a[2][0] == x:
		return 1
	if len(set(a[0])) == 1 and a[0][0] == x or (len(set(a[1])) == 1 and a[1][0] == x) or (len(set(a[2])) == 1 and a[2][0] == x):
		return 1
	if len(set(a[0][:])) == 1 and a[0][0] == x or (len(set(a[1][:])) == 1 and a[0][1] == x) or (len(set(a[2][:])) == 1 and a[0][0] == x):
		return 1
	return 0
karmanya = int(input())
while karmanya != 0:
	karmanya -= 1
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	ans = a[n - 1]
	s = 0
	for i in range(1, n):
		s += a[i - 1]
		ans += s - i * a[i]
	print(ans)


t = int(input())
while t > 0:
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	ans = 0
	total = 0
	for i in range(2, n):
		total = total + a[i - 2]
		ans = ans - a[i] * (i - 1)
		ans = ans + total
	print(ans)
	t = t - 1


for t in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	tem1 = 0
	tem2 = 0
	for i in range(2, n):
		tem2 += arr[i - 2]
		tem1 -= arr[i] * (i - 1)
		tem1 += tem2
	print(tem1)


from collections import Counter
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	ssum = arr[-1]
	neg = [0] * n
	for i in range(1, n):
		neg[i] = neg[i - 1] + i * (arr[i] - arr[i - 1])
	print(ssum - sum(neg))


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import *
from collections import deque
from operator import itemgetter, attrgetter
from decimal import *
import bisect
import math
import heapq as hq
MOD = 10 ** 9 + 7

def is_prime(n):
	if n == 2 or n == 3:
		return True
	if n < 2 or n % 2 == 0:
		return False
	if n < 9:
		return True
	if n % 3 == 0:
		return False
	r = int(n ** 0.5)
	f = 5
	while f <= r:
		if n % f == 0:
			return False
		if n % (f + 2) == 0:
			return False
		f += 6
	return True

def pow(a, b, m):
	ans = 1
	while b:
		if b & 1:
			ans = ans * a % m
		b //= 2
		a = a * a % m
	return ans

def ispalindrome(s):
	if s[:] == s[::-1]:
		return 1
	return 0
dp = []
limit = []
v = []

def dpdfs(u, t=-1):
	dp[0][u] = 0
	dp[1][u] = 0
	for i in v[u]:
		if i == t:
			continue
		if dp[1][i] == -1:
			dpdfs(i, u)
		dp[0][u] += max(abs(limit[0][u] - limit[1][i]) + dp[1][i], abs(limit[0][u] - limit[0][i]) + dp[0][i])
		dp[1][u] += max(abs(limit[1][u] - limit[1][i]) + dp[1][i], abs(limit[1][u] - limit[0][i]) + dp[0][i])
vis = []
f = 0

def dfs(i):
	vis[i] = 1
	act[i] = 1
	for j in v[i]:
		if act[j]:
			f = 1
			return -1
		if vis[j] == 0:
			if dfs(j) == -1:
				return -1
	act[i] = 0
	ans.append(i)
	return 0
from queue import PriorityQueue

def z_algorithm(s):
	res = [0] * len(s)
	res[0] = len(s)
	(i, j) = (1, 0)
	while i < len(s):
		while i + j < len(s) and s[j] == s[i + j]:
			j += 1
		res[i] = j
		if j == 0:
			i += 1
			continue
		k = 1
		while i + k < len(s) and k + res[k] < j:
			res[i + k] = res[k]
			k += 1
		(i, j) = (i + k, j - k)
	return res

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def lcm(a, b):
	return a / gcd(a, b) * b
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	suffix = [0 for i in range(n)]
	suffix[n - 1] = l[n - 1]
	for i in range(n - 2, -1, -1):
		suffix[i] = suffix[i + 1] + l[i]
	ans = 0
	for i in range(n - 1):
		ans += (n - i - 1) * l[i] - suffix[i + 1]
	print(ans + l[-1])


import sys, io, os
BUFSIZE = 8192

class FastIO(io.IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = io.BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(io.IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
T = int(input())
for _ in range(T):
	N = int(input())
	D = sorted(map(int, input().split()))
	c = 0
	n = 0
	ans = 0
	for i in range(2, N):
		d = D[i]
		c += D[i - 2]
		n += 1
		ans += n * d - c
	print(-ans)


def greatGraphs(n, array):
	cost = 0
	for x in range(1, n):
		cost += array[x] - array[x - 1]
	array.sort()
	ans = 0
	l = array[n - 1]
	res = 0
	for x in range(1, n):
		ans = -1 * (array[x] - array[x - 1]) * x + ans
		res += ans
	return res + l
t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	print(greatGraphs(n, l))


for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	s = 0
	ans = 0
	for i in range(n):
		if i - 2 >= 0:
			s += a[i - 2]
			ans += (i - 1) * a[i] - s
	print(-ans)


import math
from collections import deque
import os
import sys
from io import BytesIO, IOBase

def main():
	pass
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
mod = 10 ** 9 + 7

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s)])

def invr():
	return map(int, input().split())
for _ in range(inp()):
	n = inp()
	l = inlt()
	l.sort()
	d = []
	for i in range(n - 1):
		d.append(l[i + 1] - l[i])
	n = n - 1
	ans = 0
	d.reverse()
	ps = []
	s = 0
	for i in range(n):
		s += d[i]
		ps.append(s)
	s = 0
	ps2 = []
	for i in range(n):
		s += ps[i]
		ps2.append(s)
	ps2 = [0] + ps2
	ps = [0] + ps
	for i in range(n - 1):
		ans += ps2[-1] - ps[i] * (n - i - 1) - ps2[i + 1]
	print(-1 * ans)


for _ in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	a.sort()
	(v, s) = (0, 0)
	for i in range(2, n):
		s += a[i - 2]
		v -= a[i] * (i - 1)
		v += s
	print(v)


def solve(A, n):
	A.sort()
	sm = 0
	ans = 0
	for (i, it) in enumerate(A):
		ans += sm - i * it
		sm += it
	ans += A[-1]
	return ans
for case in range(int(input())):
	n = int(input())
	A = list(map(int, input().split()))
	ans = solve(A, n)
	print(ans)


for t in range(int(input())):
	n = int(input())
	a = sorted(list(map(int, input().split())))
	(val, total) = (0, 0)
	for i in range(2, n):
		total += a[i - 2]
		val -= a[i] * (i - 1)
		val += total
	print(val)


import sys
import io
import math
import collections
import decimal
import itertools
import bisect
import heapq

def input():
	return sys.stdin.readline()[:-1]

def solve(N, D):
	D.sort()
	B = [D[i + 1] - D[i] for i in range(N - 1)]
	v = 0
	for i in range(N - 1):
		v += (i + 1) * (N - 1 - i) * B[i]
	return sum(B) - v
T0 = int(input())
for _ in range(T0):
	N = int(input())
	D = list(map(int, input().split()))
	ans = solve(N, D)
	print(ans)


import sys
input = lambda : sys.stdin.readline()
int_arr = lambda : list(map(int, input().split()))
str_arr = lambda : list(map(str, input().split()))
get_str = lambda : map(str, input().split())
get_int = lambda : map(int, input().split())
get_flo = lambda : map(float, input().split())
mod = 1000000007

def solve(n, arr):
	(pos_sum, neg_sum) = (0, 0)
	for i in range(2, n):
		pos_sum += arr[i - 2]
		neg_sum -= (i - 1) * arr[i]
		neg_sum += pos_sum
	print(neg_sum)
for _ in range(int(input())):
	n = int(input())
	arr = sorted(int_arr())
	solve(n, arr)


def solve(values):
	if len(values) == 1:
		return 0
	values = sorted(values)
	result = values[-1]
	for i in range(len(values) - 1):
		result -= (values[i + 1] - values[i]) * (i + 1) * (len(values) - i - 1)
	return result
t = int(input())
for _ in range(t):
	input()
	values = list(map(int, input().split()))
	print(solve(values))


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	k = 0
	for i in range(n - 1):
		k += (l[i] - l[i + 1]) * (i + 1) * (n - i - 1)
	print(l[-1] - abs(k))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	p = sorted(a)
	q = 0
	s = 0
	for i in range(2, n):
		s = s + p[i - 2]
		q = q - p[i] * (i - 1)
		q = q + s
	print(q)


import sys
import math
import heapq
import bisect
from collections import Counter
from collections import defaultdict
from io import BytesIO, IOBase
import string

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None
		self.BUFSIZE = 8192

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def get_int():
	return int(input())

def get_ints():
	return list(map(int, input().split(' ')))

def get_int_grid(n):
	return [get_ints() for _ in range(n)]

def get_str():
	return input().strip()

def get_strs():
	return get_str().split(' ')

def flat_list(arr):
	return [item for subarr in arr for item in subarr]

def yes_no(b):
	if b:
		return 'YES'
	else:
		return 'NO'

def binary_search(good, left, right, delta=1, right_true=False):
	limits = [left, right]
	while limits[1] - limits[0] > delta:
		if delta == 1:
			mid = sum(limits) // 2
		else:
			mid = sum(limits) / 2
		if good(mid):
			limits[int(right_true)] = mid
		else:
			limits[int(~right_true)] = mid
	if good(limits[int(right_true)]):
		return limits[int(right_true)]
	else:
		return False

def prefix_sums(a):
	p = [0]
	for x in a:
		p.append(p[-1] + x)
	return p

def solve_a():
	n = get_int()
	d = get_ints()
	d.sort()
	S = 0
	for i in range(n):
		S += (2 * i - (n - 1)) * d[i]
	return d[-1] - S
t = get_int()
for _ in range(t):
	print(solve_a())


import sys
from sys import stdin
tt = int(stdin.readline())
ANS = []
for loop in range(tt):
	n = int(stdin.readline())
	d = list(map(int, stdin.readline().split()))
	d.sort()
	ans = 0
	nsum = 0
	for i in range(n):
		ans -= d[i] * i - nsum
		nsum += d[i]
	ANS.append(ans + max(d))
print('\n'.join(map(str, ANS)))


def func():
	if n == 1:
		print(0)
	else:
		prefix = [0]
		pre_sum = [0]
		for i in range(1, n):
			ele = d[i] - prefix[-1]
			prefix.append(ele)
		total = d[-1]
		for i in range(1, n):
			ele = (d[i] - d[i - 1]) * i + pre_sum[-1]
			pre_sum.append(ele)
			total -= pre_sum[i]
		print(total)
for _ in range(int(input())):
	n = int(input())
	d = list(map(int, input().split()))
	d.sort()
	func()


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = sorted(a)
	pos = b[-1]
	neg = 0
	for i in range(n - 1):
		pos += b[i] * (n - i - 1)
	for i in range(n - 1, -1, -1):
		neg += b[i] * i
	print(pos - neg)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	an = max(a)
	a.sort()
	for i in range(1, n):
		an -= a[i] * i
		an += a[i] * (n - 1 - i)
	print(an)


def fun(n, l):
	l.sort()
	v = 0
	sum = 0
	for i in range(2, n):
		sum = sum + l[i - 2]
		v = v - l[i] * (i - 1) + sum
	print(v)
t = int(input())
for t in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	fun(n, l)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a = sorted(a)
	S = 0
	v = 0
	for i in range(2, n):
		S += a[i - 2]
		v -= a[i] * (i - 1)
		v += S
	print(v)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	d = list(map(int, input().split()))
	d.sort()
	ans = 0
	t = 0
	for i in range(1, n):
		ans -= d[i] * i - t
		t += d[i]
	print(ans + d[-1])


def farm(a):
	ans = 0
	a.sort()
	dec = 0
	for (i, n) in enumerate(a):
		if i == 0:
			continue
		diff = n - a[i - 1]
		dec += i * diff
		ans += diff
		ans -= dec
	return ans
t = int(input())
for i in range(t):
	n = int(input())
	s = input()
	a = [int(a) for a in s.split(' ')]
	print(farm(a))


def divisors(M):
	d = []
	i = 1
	while M >= i ** 2:
		if M % i == 0:
			d.append(i)
			if i ** 2 != M:
				d.append(M // i)
		i = i + 1
	return d

def popcount(x):
	x = x - (x >> 1 & 1431655765)
	x = (x & 858993459) + (x >> 2 & 858993459)
	x = x + (x >> 4) & 252645135
	x = x + (x >> 8)
	x = x + (x >> 16)
	return x & 127

def eratosthenes(n):
	res = [0 for i in range(n + 1)]
	prime = set([])
	for i in range(2, n + 1):
		if not res[i]:
			prime.add(i)
			for j in range(1, n // i + 1):
				res[i * j] = 1
	return prime

def factorization(n):
	res = []
	for p in prime:
		if n % p == 0:
			while n % p == 0:
				n //= p
			res.append(p)
	if n != 1:
		res.append(n)
	return res

def euler_phi(n):
	res = n
	for x in range(2, n + 1):
		if x ** 2 > n:
			break
		if n % x == 0:
			res = res // x * (x - 1)
			while n % x == 0:
				n //= x
	if n != 1:
		res = res // n * (n - 1)
	return res

def ind(b, n):
	res = 0
	while n % b == 0:
		res += 1
		n //= b
	return res

def isPrimeMR(n):
	d = n - 1
	d = d // (d & -d)
	L = [2, 3, 5, 7, 11, 13, 17]
	for a in L:
		t = d
		y = pow(a, t, n)
		if y == 1:
			continue
		while y != n - 1:
			y = y * y % n
			if y == 1 or t == n - 1:
				return 0
			t <<= 1
	return 1

def findFactorRho(n):
	from math import gcd
	m = 1 << n.bit_length() // 8
	for c in range(1, 99):
		f = lambda x: (x * x + c) % n
		(y, r, q, g) = (2, 1, 1, 1)
		while g == 1:
			x = y
			for i in range(r):
				y = f(y)
			k = 0
			while k < r and g == 1:
				ys = y
				for i in range(min(m, r - k)):
					y = f(y)
					q = q * abs(x - y) % n
				g = gcd(q, n)
				k += m
			r <<= 1
		if g == n:
			g = 1
			while g == 1:
				ys = f(ys)
				g = gcd(abs(x - ys), n)
		if g < n:
			if isPrimeMR(g):
				return g
			elif isPrimeMR(n // g):
				return n // g
			return findFactorRho(g)

def primeFactor(n):
	i = 2
	ret = {}
	rhoFlg = 0
	while i * i <= n:
		k = 0
		while n % i == 0:
			n //= i
			k += 1
		if k:
			ret[i] = k
		i += 1 + i % 2
		if i == 101 and n >= 2 ** 20:
			while n > 1:
				if isPrimeMR(n):
					(ret[n], n) = (1, 1)
				else:
					rhoFlg = 1
					j = findFactorRho(n)
					k = 0
					while n % j == 0:
						n //= j
						k += 1
					ret[j] = k
	if n > 1:
		ret[n] = 1
	if rhoFlg:
		ret = {x: ret[x] for x in sorted(ret)}
	return ret

def divisors(n):
	res = [1]
	prime = primeFactor(n)
	for p in prime:
		newres = []
		for d in res:
			for j in range(prime[p] + 1):
				newres.append(d * p ** j)
		res = newres
	res.sort()
	return res

def xorfactorial(num):
	if num == 0:
		return 0
	elif num == 1:
		return 1
	elif num == 2:
		return 3
	elif num == 3:
		return 0
	else:
		x = baseorder(num)
		return 2 ** x * ((num - 2 ** x + 1) % 2) + function(num - 2 ** x)

def xorconv(n, X, Y):
	if n == 0:
		res = [X[0] * Y[0] % mod]
		return res
	x = [X[i] + X[i + 2 ** (n - 1)] for i in range(2 ** (n - 1))]
	y = [Y[i] + Y[i + 2 ** (n - 1)] for i in range(2 ** (n - 1))]
	z = [X[i] - X[i + 2 ** (n - 1)] for i in range(2 ** (n - 1))]
	w = [Y[i] - Y[i + 2 ** (n - 1)] for i in range(2 ** (n - 1))]
	res1 = xorconv(n - 1, x, y)
	res2 = xorconv(n - 1, z, w)
	former = [(res1[i] + res2[i]) * inv for i in range(2 ** (n - 1))]
	latter = [(res1[i] - res2[i]) * inv for i in range(2 ** (n - 1))]
	former = list(map(lambda x: x % mod, former))
	latter = list(map(lambda x: x % mod, latter))
	return former + latter

def merge_sort(A, B):
	(pos_A, pos_B) = (0, 0)
	(n, m) = (len(A), len(B))
	res = []
	while pos_A < n and pos_B < m:
		(a, b) = (A[pos_A], B[pos_B])
		if a < b:
			res.append(a)
			pos_A += 1
		else:
			res.append(b)
			pos_B += 1
	res += A[pos_A:]
	res += B[pos_B:]
	return res

class UnionFindVerSize:

	def __init__(self, N):
		self._parent = [n for n in range(0, N)]
		self._size = [1] * N
		self.group = N

	def find_root(self, x):
		if self._parent[x] == x:
			return x
		self._parent[x] = self.find_root(self._parent[x])
		stack = [x]
		while self._parent[stack[-1]] != stack[-1]:
			stack.append(self._parent[stack[-1]])
		for v in stack:
			self._parent[v] = stack[-1]
		return self._parent[x]

	def unite(self, x, y):
		gx = self.find_root(x)
		gy = self.find_root(y)
		if gx == gy:
			return
		self.group -= 1
		if self._size[gx] < self._size[gy]:
			self._parent[gx] = gy
			self._size[gy] += self._size[gx]
		else:
			self._parent[gy] = gx
			self._size[gx] += self._size[gy]

	def get_size(self, x):
		return self._size[self.find_root(x)]

	def is_same_group(self, x, y):
		return self.find_root(x) == self.find_root(y)

class WeightedUnionFind:

	def __init__(self, N):
		self.parent = [i for i in range(N)]
		self.size = [1 for i in range(N)]
		self.val = [0 for i in range(N)]
		self.flag = True
		self.edge = [[] for i in range(N)]

	def dfs(self, v, pv):
		stack = [(v, pv)]
		new_parent = self.parent[pv]
		while stack:
			(v, pv) = stack.pop()
			self.parent[v] = new_parent
			for (nv, w) in self.edge[v]:
				if nv != pv:
					self.val[nv] = self.val[v] + w
					stack.append((nv, v))

	def unite(self, x, y, w):
		if not self.flag:
			return
		if self.parent[x] == self.parent[y]:
			self.flag = self.val[x] - self.val[y] == w
			return
		if self.size[self.parent[x]] > self.size[self.parent[y]]:
			self.edge[x].append((y, -w))
			self.edge[y].append((x, w))
			self.size[x] += self.size[y]
			self.val[y] = self.val[x] - w
			self.dfs(y, x)
		else:
			self.edge[x].append((y, -w))
			self.edge[y].append((x, w))
			self.size[y] += self.size[x]
			self.val[x] = self.val[y] + w
			self.dfs(x, y)

class Dijkstra:

	class Edge:

		def __init__(self, _to, _cost):
			self.to = _to
			self.cost = _cost

	def __init__(self, V):
		self.G = [[] for i in range(V)]
		self._E = 0
		self._V = V

	@property
	def E(self):
		return self._E

	@property
	def V(self):
		return self._V

	def add_edge(self, _from, _to, _cost):
		self.G[_from].append(self.Edge(_to, _cost))
		self._E += 1

	def shortest_path(self, s):
		import heapq
		que = []
		d = [10 ** 15] * self.V
		d[s] = 0
		heapq.heappush(que, (0, s))
		while len(que) != 0:
			(cost, v) = heapq.heappop(que)
			if d[v] < cost:
				continue
			for i in range(len(self.G[v])):
				e = self.G[v][i]
				if d[e.to] > d[v] + e.cost:
					d[e.to] = d[v] + e.cost
					heapq.heappush(que, (d[e.to], e.to))
		return d

def Z_algorithm(s):
	N = len(s)
	Z_alg = [0] * N
	Z_alg[0] = N
	i = 1
	j = 0
	while i < N:
		while i + j < N and s[j] == s[i + j]:
			j += 1
		Z_alg[i] = j
		if j == 0:
			i += 1
			continue
		k = 1
		while i + k < N and k + Z_alg[k] < j:
			Z_alg[i + k] = Z_alg[k]
			k += 1
		i += k
		j -= k
	return Z_alg

class BIT:

	def __init__(self, n, mod=0):
		self.BIT = [0] * (n + 1)
		self.num = n
		self.mod = mod

	def query(self, idx):
		res_sum = 0
		mod = self.mod
		while idx > 0:
			res_sum += self.BIT[idx]
			if mod:
				res_sum %= mod
			idx -= idx & -idx
		return res_sum

	def update(self, idx, x):
		mod = self.mod
		while idx <= self.num:
			self.BIT[idx] += x
			if mod:
				self.BIT[idx] %= mod
			idx += idx & -idx
		return

class dancinglink:

	def __init__(self, n, debug=False):
		self.n = n
		self.debug = debug
		self._left = [i - 1 for i in range(n)]
		self._right = [i + 1 for i in range(n)]
		self.exist = [True for i in range(n)]

	def pop(self, k):
		if self.debug:
			assert self.exist[k]
		L = self._left[k]
		R = self._right[k]
		if L != -1:
			if R != self.n:
				(self._right[L], self._left[R]) = (R, L)
			else:
				self._right[L] = self.n
		elif R != self.n:
			self._left[R] = -1
		self.exist[k] = False

	def left(self, idx, k=1):
		if self.debug:
			assert self.exist[idx]
		res = idx
		while k:
			res = self._left[res]
			if res == -1:
				break
			k -= 1
		return res

	def right(self, idx, k=1):
		if self.debug:
			assert self.exist[idx]
		res = idx
		while k:
			res = self._right[res]
			if res == self.n:
				break
			k -= 1
		return res

class SparseTable:

	def __init__(self, A, merge_func, ide_ele):
		N = len(A)
		n = N.bit_length()
		self.table = [[ide_ele for i in range(n)] for i in range(N)]
		self.merge_func = merge_func
		for i in range(N):
			self.table[i][0] = A[i]
		for j in range(1, n):
			for i in range(0, N - 2 ** j + 1):
				f = self.table[i][j - 1]
				s = self.table[i + 2 ** (j - 1)][j - 1]
				self.table[i][j] = self.merge_func(f, s)

	def query(self, s, t):
		b = t - s + 1
		m = b.bit_length() - 1
		return self.merge_func(self.table[s][m], self.table[t - 2 ** m + 1][m])

class BinaryTrie:

	class node:

		def __init__(self, val):
			self.left = None
			self.right = None
			self.max = val

	def __init__(self):
		self.root = self.node(-10 ** 15)

	def append(self, key, val):
		pos = self.root
		for i in range(29, -1, -1):
			pos.max = max(pos.max, val)
			if key >> i & 1:
				if pos.right is None:
					pos.right = self.node(val)
					pos = pos.right
				else:
					pos = pos.right
			elif pos.left is None:
				pos.left = self.node(val)
				pos = pos.left
			else:
				pos = pos.left
		pos.max = max(pos.max, val)

	def search(self, M, xor):
		res = -10 ** 15
		pos = self.root
		for i in range(29, -1, -1):
			if pos is None:
				break
			if M >> i & 1:
				if xor >> i & 1:
					if pos.right:
						res = max(res, pos.right.max)
					pos = pos.left
				else:
					if pos.left:
						res = max(res, pos.left.max)
					pos = pos.right
			elif xor >> i & 1:
				pos = pos.right
			else:
				pos = pos.left
		if pos:
			res = max(res, pos.max)
		return res

def solveequation(edge, ans, n, m):
	x = [0] * m
	used = [False] * n
	for v in range(n):
		if used[v]:
			continue
		y = dfs(v)
		if y != 0:
			return False
	return x

	def dfs(v):
		used[v] = True
		r = ans[v]
		for (to, dire, id) in edge[v]:
			if used[to]:
				continue
			y = dfs(to)
			if dire == -1:
				x[id] = y
			else:
				x[id] = -y
			r += y
		return r

class SegmentTree:

	def __init__(self, init_val, segfunc, ide_ele):
		n = len(init_val)
		self.segfunc = segfunc
		self.ide_ele = ide_ele
		self.num = 1 << (n - 1).bit_length()
		self.tree = [ide_ele] * 2 * self.num
		self.size = n
		for i in range(n):
			self.tree[self.num + i] = init_val[i]
		for i in range(self.num - 1, 0, -1):
			self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])

	def update(self, k, x):
		k += self.num
		self.tree[k] = x
		while k > 1:
			self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
			k >>= 1

	def query(self, l, r):
		if r == self.size:
			r = self.num
		res = self.ide_ele
		l += self.num
		r += self.num
		while l < r:
			if l & 1:
				res = self.segfunc(res, self.tree[l])
				l += 1
			if r & 1:
				res = self.segfunc(res, self.tree[r - 1])
			l >>= 1
			r >>= 1
		return res

	def bisect_l(self, l, r, x):
		l += self.num
		r += self.num
		Lmin = -1
		Rmin = -1
		while l < r:
			if l & 1:
				if self.tree[l] <= x and Lmin == -1:
					Lmin = l
				l += 1
			if r & 1:
				if self.tree[r - 1] <= x:
					Rmin = r - 1
			l >>= 1
			r >>= 1
		if Lmin != -1:
			pos = Lmin
			while pos < self.num:
				if self.tree[2 * pos] <= x:
					pos = 2 * pos
				else:
					pos = 2 * pos + 1
			return pos - self.num
		elif Rmin != -1:
			pos = Rmin
			while pos < self.num:
				if self.tree[2 * pos] <= x:
					pos = 2 * pos
				else:
					pos = 2 * pos + 1
			return pos - self.num
		else:
			return -1
import sys, random, bisect
from collections import deque, defaultdict
from heapq import heapify, heappop, heappush
from itertools import permutations
from math import gcd, log
input = lambda : sys.stdin.readline().rstrip()
mi = lambda : map(int, input().split())
li = lambda : list(mi())
for _ in range(int(input())):
	n = int(input())
	d = li()
	d.sort()
	res = 0
	S = 0
	for i in range(1, n):
		res += d[i] - d[i - 1]
		res += S - d[i] * i
		S += d[i]
	print(res)


t = int(input())
while t:
	n = int(input())
	d = list(map(int, input().split()))
	d.sort()
	res = 0
	x = 0
	for i in range(2, n):
		x += d[i - 2]
		res -= d[i] * (i - 1)
		res += x
	print(res)
	t -= 1


t = int(input())
for hh in range(0, t):
	n = int(input())
	a = [int(x) for x in input().split()]
	a.sort()
	if n <= 2:
		print(0)
	else:
		pre = 0
		finalans = 0
		for i in range(1, n):
			val1 = i * a[i]
			val1 -= pre
			finalans += -1 * val1
			pre += a[i]
		finalans += a[-1]
		print(finalans)


import sys
import os.path
import math
import heapq
import copy
from sys import stdin, stdout
from collections import *
from math import gcd, ceil, floor
mod = int(1000000000.0 + 7)
if os.path.exists('Updated prg/Input3d.txt'):
	sys.stdout = open('Updated prg/Output3d.txt', 'w')
	sys.stdin = open('Updated prg/Input3d.txt', 'r')

def sinp():
	return input()

def ninp():
	return int(sinp())

def mapinp():
	return map(int, sinp().split())

def smapinp():
	return map(str, sinp().split())

def fastinp():
	return map(int, sys.stdin.readline().split())

def linp():
	return list(mapinp())

def sl():
	return list(sinp())

def prnt(a):
	print(a)

def prntl(a):
	print(a, end=' ')

def prntlist(a):
	print(*a)
for _ in range(ninp()):
	n = ninp()
	d = linp()
	d.sort()
	s1 = d[n - 1]
	updated_distance = [0] * n
	updated_distance[0] = d[0]
	for i in range(1, n):
		s2 = d[i] - d[i - 1]
		updated_distance[i] = updated_distance[i - 1] + i * s2
		s1 = s1 - updated_distance[i]
	prnt(s1)


import math
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	cnt = 0
	result = 0
	for i in range(2, n):
		cnt += l[i - 2]
		result -= l[i] * (i - 1)
		result += cnt
	print(result)


for samples in range(int(input())):
	size = int(input())
	arr = sorted(list(map(int, input().split())), reverse=True)
	ans = 0
	for i in range(1, size):
		ans -= abs(arr[i - 1] - arr[i]) * (i * (size - i))
	lowest = min(arr)
	highest = max(arr)
	ans += highest - lowest
	print(ans)


import sys
input = lambda : sys.stdin.readline().rstrip()
T = int(input())
for _ in range(T):
	N = int(input())
	A = sorted([int(a) for a in input().split()])
	ans = A[-1]
	su = 0
	for (i, a) in enumerate(A):
		ans += su - a * i
		su += a
	print(ans)


t = int(input())
for o in range(t):
	n = int(input())
	d = list(map(int, input().strip().split()))
	d.sort()
	sm = []
	cur = 0
	for i in d:
		cur += i
		sm.append(cur)
	subtract = sum(sm) - cur
	add = 0
	for i in range(n - 1, -1, -1):
		add += i * d[i]
	print(subtract - add + d[-1])


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	d = list(map(int, input().split()))
	d.sort()
	ans = d[-1]
	for i in range(n - 1):
		dd = d[i + 1] - d[i]
		(l, r) = (i + 1, n - i - 1)
		ans -= dd * l * r
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	d = sorted(list(map(int, input().split())))[::-1]
	difs = [d[i] - d[i + 1] for i in range(n - 1)][::-1]
	ls = [d[0] - d[i] for i in range(1, n)]
	ans = 0
	for i in range(n - 1):
		ans += ls[i] * (i + 1)
		ans -= difs[i] * (i * (i + 1) // 2)
	print(-(ans - d[0]))


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	if n < 3:
		print(0)
		continue
	l.sort()
	pre = []
	s = 0
	for i in l:
		pre.append(i + s)
		s += i
	a = 0
	for i in range(2, n):
		a += l[i] * (i - 1) - pre[i - 2]
	print(-a)


for _ in range(int(input())):
	n = int(input().strip())
	arr = list(map(int, input().strip().split()))
	arr.sort()
	prefix = [0] * n
	prefix[0] = arr[0]
	for i in range(1, n):
		prefix[i] = prefix[i - 1] + arr[i]
	ans = 0
	for i in range(1, n):
		ans += prefix[i - 1] - i * arr[i]
	print(ans + arr[n - 1])


from sys import *
input = lambda : stdin.readline()
int_arr = lambda : list(map(int, stdin.readline().strip().split()))
str_arr = lambda : list(map(str, stdin.readline().split()))
get_str = lambda : map(str, stdin.readline().strip().split())
get_int = lambda : map(int, stdin.readline().strip().split())
get_float = lambda : map(float, stdin.readline().strip().split())
mod = 1000000007
setrecursionlimit(1000)
for _ in range(int(input())):
	n = int(input())
	arr = sorted(int_arr())
	(su1, su2) = (0, 0)
	for i in range(2, n):
		su1 += arr[i - 2]
		su2 -= (i - 1) * arr[i]
		su2 += su1
	print(su2)


for _ in range(int(input())):
	n = int(input())
	a = sorted(list(map(int, input().split())))
	if n <= 2:
		print(0)
		continue
	i = 0
	ans = 0
	while i + i < n:
		s = a[n - i - 1] - a[i]
		ans += s * (n - 2 * i - 1)
		i += 1
	print(-ans + a[-1])


import sys, os
if os.environ['USERNAME'] == 'kissz':
	inp = open('in.txt', 'r').readline

	def debug(*args):
		print(*args, file=sys.stderr)
else:
	inp = sys.stdin.readline

	def debug(*args):
		pass
for _ in range(int(inp())):
	n = int(inp())
	D = [*map(int, inp().split())]
	D.sort()
	S = 0
	x = 0
	for i in range(1, n):
		S += D[i] - D[i - 1]
		x += i * (D[i] - D[i - 1])
		S -= x
	print(S)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	(c, f) = (0, 0)
	for i in range(2, n):
		c += a[i - 2]
		f -= a[i] * (i - 1)
		f = f + c
	print(f)


import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
	n = int(input())
	d = list(map(int, input().split()))
	d.sort()
	mn = d[-1]
	tot = 0
	for i in range(n):
		mn += tot - i * d[i]
		tot += d[i]
	print(mn)


def main():
	n = int(input())
	for _ in range(n):
		t = int(input())
		l = list(map(int, input().split()))
		l.sort()
		s = max(l)
		a = 0
		for i in range(1, t):
			s -= i * l[i] - a
			a += l[i]
		print(s)
main()


import sys
for _ in range(int(sys.stdin.readline())):
	n = int(sys.stdin.readline())
	data = [0] + list(map(int, sys.stdin.readline().split()))
	temp = [0] * (n + 1)
	data.sort()
	for i in range(1, n + 1):
		temp[i] = temp[i - 1] + data[i]
	ans = data[-1]
	for i in range(2, n + 1):
		ans -= data[i] * (i - 1) - temp[i - 1]
	print(ans)


def solve():
	n = int(input())
	dist = [int(x) for x in input().split()]
	dist.sort()
	cost = 0
	for i in range(1, n):
		diff = dist[i] - dist[i - 1]
		cost += diff
		cost -= diff * i * (n - i)
	return cost
for _ in range(int(input())):
	print(solve())


from itertools import accumulate

def solve():
	n = int(input())
	(*d,) = map(int, input().split())
	d.sort()
	ans = 0
	(*prefix,) = accumulate(d)
	for i in range(2, n):
		ans -= d[i] * (i - 1) - prefix[i - 2]
	print(ans)
for _ in range(int(input())):
	solve()


import traceback
import math
from collections import defaultdict, Counter
from functools import lru_cache
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def geti():
	return int(input())

def gets():
	return input()

def getil():
	return list(map(int, input().split()))

def getsl():
	return input().split()

def get2d(nrows, ncols, n=0):
	return [[n] * ncols for r in range(nrows)]
from itertools import accumulate

def get_acc(a):
	return list(accumulate(a))
inf = float('inf')
mod = 10 ** 9 + 7

def main():
	N = geti()
	a = getil()
	a.sort()
	acc = get_acc(a)
	ans = a[-1] - a[0]
	for i in range(N):
		ans += acc[i] - (i + 1) * a[i]
	return ans
try:
	Test = geti()
	answers = []
	for _ in range(Test):
		ans = main()
		ans = str(ans)
		answers.append(ans)
	print('\n'.join(answers))
except Exception as e:
	print(e)
	traceback.print_exc()


t = int(input())
for _ in range(t):
	n = int(input())
	d = list(map(int, input().split()))
	d.sort()
	ans = d[-1]
	for i in range(n - 1):
		dd = d[i + 1] - d[i]
		(l, r) = (i + 1, n - i - 1)
		ans -= dd * l * r
	print(ans)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	pos = arr[-1]
	neg = [0] * n
	for i in range(1, n):
		neg[i] = neg[i - 1] + i * (arr[i] - arr[i - 1])
	print(pos - sum(neg))


for _ in range(int(input())):
	n = int(input())
	d = list(map(int, input().split()))
	d.sort()
	(val, sm) = (0, 0)
	for i in range(2, n):
		sm += d[i - 2]
		val -= d[i] * (i - 1)
		val += sm
	print(val)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	cost = 0
	time_diff = 0
	arr.sort()
	for i in range(2, n):
		time_diff += arr[i - 2]
		cost -= arr[i] * (i - 1)
		cost += time_diff
	print(cost)


for _ in range(int(input())):
	x = int(input())
	a = list(map(int, input().split()))
	a.sort()
	s = [0] * x
	for i in range(1, x):
		s[i] = (a[i] - a[i - 1]) * i + s[i - 1]
	print(-sum(s) + a[-1])


t = int(input())

def cost(li: list) -> int:
	z = 0
	min_cost = 0
	for f in range(2, len(li)):
		z += li[f - 2]
		min_cost -= li[f] * (f - 1)
		min_cost += z
	return min_cost
for _ in range(t):
	n_ = int(input())
	li = []
	t = input()
	li = t.split(' ')
	li = list(map(int, li))
	li.sort()
	print(cost(li))


from math import *
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	ans = 0
	ma = 0
	val = 0
	for i in range(1, n):
		if i != 1:
			now = i * (a[i] - a[i - 1]) * (n - i - 1) + (a[i] - a[i - 1]) * (i - 1)
			ans -= now
		else:
			now = i * (n - i - 1) * (a[i] - a[i - 1])
			ans -= now
	print(ans)


def enjoy(n, lst):
	lst.sort()
	ans = 0
	a = 0
	return yes(n, lst, ans, a)

def yes(n, lst, ans, a):
	for i in range(2, n):
		a += lst[i - 2]
		ans -= lst[i] * (i - 1)
		ans += a
	return ans
for t in range(int(input())):
	n = int(input())
	lst = list(map(int, input().split()))
	print(enjoy(n, lst))


import sys
import math
from collections import deque, Counter
sys.setrecursionlimit(10 ** 7)
int1 = lambda x: int(x) - 1
mi = lambda : map(int, input().split())
li = lambda : list(mi())
mi1 = lambda : map(int1, input().split())
li1 = lambda : list(mi1())
mod = 10 ** 9 + 7
Mod = 998244353
INF = 10 ** 18
ans = 0
t = int(input())
for _ in range(t):
	n = int(input())
	ans = 0
	a = li()
	a.sort()
	ans += a[-1]
	cnt = 0
	for i in range(1, n):
		ans -= a[i] * i - cnt
		cnt += a[i]
	print(ans)


t = int(input())
for k in range(t):
	n = int(input())
	sum = 0
	x = 0
	y = 0
	arr = sorted(list(map(int, input().split())))
	for i in range(n):
		x = arr[i] * (n - 2 * i - 1)
		if i != n - 1:
			y = arr[i] - arr[i + 1]
		else:
			y = 0
		sum = sum + x - y
	print(sum)


import sys
input = sys.stdin.readline
t = int(input())
for tests in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	A.sort()
	ANS = 0
	SUM = A[-1]
	for i in range(n - 1):
		ANS += (A[i + 1] - A[i]) * (i + 1) * (n - i - 1)
	print(SUM - ANS)


for _ in range(int(input())):
	n = int(input())
	a = sorted(list(map(int, input().split())))
	(pos_wg, neg_wg) = (0, 0)
	helper = 0
	for i in range(2, n):
		pos_wg += a[i - 2]
		neg_wg -= a[i] * (i - 1)
		helper += pos_wg
	print(helper + neg_wg)


import sys
import math
from bisect import bisect_right as br
from itertools import combinations as cb

def int_arr():
	return list(map(int, sys.stdin.readline().strip().split()))

def str_arr():
	return list(map(str, sys.stdin.readline().strip().split()))

def input():
	return sys.stdin.readline().strip()
for _ in range(int(input())):
	n = int(input())
	arr = int_arr()
	arr.sort()
	ans = 0
	sm = sum(arr)
	prev = 0
	for i in range(n):
		ans += arr[i] - prev
		prev = arr[i]
	arr.reverse()
	for i in range(n):
		sm -= arr[i]
		t = arr[i] * (n - (i + 1))
		ans += sm - t
	print(ans)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	if n == 1:
		print(0)
	elif n == 2:
		print(0)
	elif n == 3:
		print(-arr[-1])
	else:
		sum1 = sum(arr[1:])
		final = sum1
		temp = n - 1
		for i in range(0, n - 1):
			sum1 = sum1 + temp * (arr[i] - arr[i + 1])
			temp = temp - 1
			final = final + sum1
		print(-final + arr[-1])


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l = sorted(l)
	v = 0
	s = 0
	for i in range(2, n):
		s = s + l[i - 2]
		v = v - l[i] * (i - 1)
		v = v + s
	print(v)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	if n == 1:
		print(0)
		continue
	ans = 0
	s = 0
	for i in range(1, n):
		s += (a[i - 1] - a[i]) * i
		ans += s
	print(ans + a[-1])


from math import gcd as GCD
import bisect
import copy
import decimal
import fractions
import heapq
import itertools
import math
import random
import sys
from collections import Counter, deque, defaultdict
from functools import lru_cache, reduce
from heapq import heappush, heappop, heapify, heappushpop, _heappop_max, _heapify_max

def _heappush_max(heap, item):
	heap.append(item)
	heapq._siftdown_max(heap, 0, len(heap) - 1)

def _heappushpop_max(heap, item):
	if heap and item < heap[0]:
		(item, heap[0]) = (heap[0], item)
		heapq._siftup_max(heap, 0)
	return item
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
t = int(readline())
for _ in range(t):
	N = int(readline())
	D = list(map(int, readline().split()))
	D.sort()
	D_ = []
	for i in range(N - 1):
		D_.append(D[i + 1] - D[i])
	ans = D[-1]
	for i in range(N - 1):
		ans -= (i + 1) * (N - i - 1) * D_[i]
	print(ans)