On a circle lie $2n$ distinct points, with the following property: however you choose $3$ chords that connect $3$ disjoint pairs of points, no point strictly inside the circle belongs to all $3$ chords. The points are numbered $1, \, 2, \, \dots, \, 2n$ in clockwise order.

Initially, $k$ chords connect $k$ pairs of points, in such a way that all the $2k$ endpoints of these chords are distinct.

You want to draw $n - k$ additional chords that connect the remaining $2(n - k)$ points (each point must be an endpoint of exactly one chord).

In the end, let $x$ be the total number of intersections among all $n$ chords. Compute the maximum value that $x$ can attain if you choose the $n - k$ chords optimally.

Note that the exact position of the $2n$ points is not relevant, as long as the property stated in the first paragraph holds.


-----Input-----

The first line contains a single integer $t$ ($1 \le t \le 100$) — the number of test cases. Then $t$ test cases follow.

The first line of each test case contains two integers $n$ and $k$ ($1 \le n \le 100$, $0 \le k \le n$) — half the number of points and the number of chords initially drawn.

Then $k$ lines follow. The $i$-th of them contains two integers $x_i$ and $y_i$ ($1 \le x_i, \, y_i \le 2n$, $x_i \ne y_i$) — the endpoints of the $i$-th chord. It is guaranteed that the $2k$ numbers $x_1, \, y_1, \, x_2, \, y_2, \, \dots, \, x_k, \, y_k$ are all distinct.


-----Output-----

For each test case, output the maximum number of intersections that can be obtained by drawing $n - k$ additional chords.


-----Examples-----

Input
4
4 2
8 2
1 5
1 1
2 1
2 0
10 6
14 6
2 20
9 10
13 18
15 12
11 7
Output
4
0
1
14


-----Note-----

In the first test case, there are three ways to draw the $2$ additional chords, shown below (black chords are the ones initially drawn, while red chords are the new ones):

We see that the third way gives the maximum number of intersections, namely $4$.

In the second test case, there are no more chords to draw. Of course, with only one chord present there are no intersections.

In the third test case, we can make at most one intersection by drawing chords $1-3$ and $2-4$, as shown below:

Source: codeforces | Difficulty: MEDIUM_HARD
Tags: Constructive algorithms

Geometry

Sorting

Combinatorics

Greedy algorithms


Solutions:
from copy import deepcopy
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def main(t):
	(n, k) = map(int, input().split())
	group = [-1 for i in range(2 * n)]
	groups = [[] for i in range(n)]
	for i in range(k):
		(u, v) = map(int, input().split())
		group[u - 1] = i
		group[v - 1] = i
	ans = 0
	effect = 0
	for start in range(2 * n):
		if group[start] >= 0:
			continue
		if effect > 0:
			continue
		effect += 1
		copygroup = group[:]
		copygroups = deepcopy(groups)
		groupnum = k
		index = start
		while groupnum < n:
			if copygroup[index % (2 * n)] >= 0:
				index += 1
				continue
			copygroup[index % (2 * n)] = groupnum
			groupnum += 1
			index += 1
		groupnum = k
		while groupnum < n:
			if copygroup[index % (2 * n)] >= 0:
				index += 1
				continue
			copygroup[index % (2 * n)] = groupnum
			groupnum += 1
			index += 1
		temp = 0
		nums = []
		for i in range(2 * n):
			flag = True
			for j in range(len(nums)):
				if nums[j] == copygroup[i]:
					temp += len(nums) - j - 1
					nums.pop(j)
					flag = False
					break
			if flag:
				nums.append(copygroup[i])
		ans = max(ans, temp)
	if n == k:
		nums = []
		for i in range(2 * n):
			flag = True
			for j in range(len(nums)):
				if nums[j] == group[i]:
					ans += len(nums) - j - 1
					nums.pop(j)
					flag = False
					break
			if flag:
				nums.append(group[i])
	print(ans)
T = int(input())
t = 1
while t <= T:
	main(t)
	t += 1


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

def split(word):
	return [char for char in word]

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def main():
	for i in range(int(input())):
		(n, k) = map(int, input().split())
		h = [0] * 2 * n
		a = []
		b = []
		for j in range(k):
			(x, y) = map(int, input().split())
			a.append(x - 1)
			b.append(y - 1)
			if a[j] > b[j]:
				t = a[j]
				a[j] = b[j]
				b[j] = t
			h[x - 1] = 1
			h[y - 1] = 1
		h1 = 0
		for j in range(k):
			c = 0
			for l in range(j + 1, k):
				if a[j] < b[l] and a[j] > a[l]:
					if b[j] > b[l] or b[j] < a[l]:
						c = c + 1
				elif a[j] > b[l] or a[j] < a[l]:
					if b[j] < b[l] and b[j] > a[l]:
						c = c + 1
			h1 = h1 + c
			fi = 0
			se = 0
			for l in range(a[j] + 1, b[j]):
				if h[l] == 0:
					fi = fi + 1
			for l in range(a[j]):
				if h[l] == 0:
					se = se + 1
			for l in range(b[j] + 1, 2 * n):
				if h[l] == 0:
					se = se + 1
			if fi > se:
				h1 = h1 + se
			else:
				h1 = h1 + fi
		print(h1 + (n - k) * (n - k - 1) // 2)
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()


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	r = []
	l = []
	points = {i for i in range(1, 2 * n + 1)}
	for i in range(m):
		r.append(sorted(list(map(int, input().split()))))
		points.remove(r[-1][0])
		points.remove(r[-1][1])
	ans = 0

	def inter(i, j, k):
		return k[0] < i < k[1] and (not k[0] < j < k[1]) or (k[0] < j < k[1] and (not k[0] < i < k[1]))
	for i in range(m):
		for j in range(i + 1, m):
			if inter(r[i][0], r[i][1], r[j]):
				ans += 1
	for _ in range(n - m):
		maxi = 0
		p = []
		l = sorted(points)
		p = [l[0], l[len(l) // 2]]
		for i in r:
			if inter(l[0], l[len(l) // 2], i):
				maxi += 1
		r.append(sorted(p))
		points.remove(p[0])
		points.remove(p[1])
		ans += maxi
	print(ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	used = [False] * (2 * n)
	ps = []
	for _ in range(k):
		(x, y) = map(int, input().split())
		(x, y) = (x - 1, y - 1)
		ps.append(sorted([x, y]))
		used[x] = used[y] = True
	unused = [i for (i, v) in enumerate(used) if not v]
	for (x, y) in zip(unused, unused[len(unused) // 2:]):
		ps.append(sorted([x, y]))
	print(sum(((x1 < x2 < y1) != (x1 < y2 < y1) for (x1, y1) in ps for (x2, y2) in ps)) // 2)


T = int(input())
for _ in range(T):
	s = set()
	(N, K) = [int(s) for s in input().split()]
	arr = [i for i in range(1, 2 * N + 1)]
	res = 0
	for _ in range(K):
		(a, b) = [int(s) for s in input().split()]
		if a > b:
			(a, b) = (b, a)
		for i in s:
			if (not a > i[0] or not b < i[1]) and (not a < i[0] or not b > i[1]):
				if a < i[1] and b > i[0]:
					res += 1
		s.add((a, b))
		arr.remove(a)
		arr.remove(b)
	while arr:
		mid = len(arr) // 2
		a = arr[0]
		b = arr[mid]
		arr.remove(a)
		arr.remove(b)
		for i in s:
			if (not a > i[0] or not b < i[1]) and (not a < i[0] or not b > i[1]):
				if a < i[1] and b > i[0]:
					res += 1
		s.add((a, b))
	print(res)


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 math import ceil

def prod(a, mod=10 ** 9 + 7):
	ans = 1
	for each in a:
		ans = ans * each % mod
	return ans

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def lcm(a, b):
	return a * b // gcd(a, b)

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
for _ in range(int(input()) if True else 1):
	(n, k) = map(int, input().split())
	di = {}
	for i in range(k):
		(x, y) = map(int, input().split())
		di[x] = y
		di[y] = x
	left = [i for i in range(1, 2 * n + 1) if i not in di]
	for i in range(len(left) // 2):
		(x, y) = (left[i], left[i + len(left) // 2])
		di[x] = y
		di[y] = x
	ans = 0
	for i in range(1, 2 * n + 1):
		(x, y) = (min(i, di[i]), max(i, di[i]))
		for j in range(1, 2 * n + 1):
			(p, q) = (j, di[j])
			if x < p < y and (not x < q < y):
				ans += 1
	print(ans // 4)


from _ast import Or
import sys
input = sys.stdin.readline

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

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

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

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

def inRange(a, b, c):
	return a <= c <= b

def intersects(i, j, chords):
	return inRange(chords[i][0], chords[i][1], chords[j][0]) and (not inRange(chords[i][0], chords[i][1], chords[j][1])) or (inRange(chords[i][0], chords[i][1], chords[j][1]) and (not inRange(chords[i][0], chords[i][1], chords[j][0])))

def main():
	numTestCases = inp()
	for _testCase in range(numTestCases):
		(n, k) = invr()
		seen = set()
		chords = []
		for _i in range(k):
			(x, y) = invr()
			seen.add(x)
			seen.add(y)
			if y < x:
				(x, y) = (y, x)
			chords.append((x, y))
		missing = []
		for i in range(1, 2 * n + 1):
			if i not in seen:
				missing.append(i)
		chordsToAdd = len(missing) // 2
		for i in range(chordsToAdd):
			chords.append((missing[i], missing[i + chordsToAdd]))
		cntIntersections = 0
		for i in range(n):
			for j in range(i + 1, n):
				if intersects(i, j, chords):
					cntIntersections += 1
		print(cntIntersections)
main()


def ch(x, y):
	if y[0] < x[0] < y[1] and (not y[0] < x[1] < y[1]) or (y[0] < x[1] < y[1] and (not y[0] < x[0] < y[1])):
		return 1
	return 0
t = int(input())
for i in range(t):
	(n, k) = [int(i) for i in input().split()]
	m = []
	use = [0] * (2 * n + 1)
	for j in range(k):
		(l, r) = [int(i) for i in input().split()]
		if l > r:
			(l, r) = (r, l)
		use[l] = 1
		use[r] = 1
		m.append([l, r])
	dontuse = []
	for j in range(1, 2 * n + 1):
		if not use[j]:
			dontuse.append(j)
	ll = len(dontuse)
	for j in range(ll // 2):
		m.append([dontuse[j], dontuse[j + ll // 2]])
	m.sort()
	ans = 0
	for j in range(n):
		for k in range(j + 1, n):
			if ch(m[j], m[k]):
				ans += 1
	print(ans)


def solve():
	(n, k) = map(int, input().split())
	n *= 2
	pos = [0] * (n + 1)
	used = [0] * (n + 1)
	for i in range(k):
		(x, y) = map(int, input().split())
		pos[x] = y
		pos[y] = x
		used[x] = used[y] = 1
	j = 1
	no = []
	for i in range(1, n + 1):
		if used[i] == 0:
			no.append(i)
	m = n // 2 - k
	for i in range(m):
		(x, y) = (no[i], no[m + i])
		pos[x] = y
		pos[y] = x
	used = [0] * (n + 1)
	ans = 0
	for i in range(1, n + 1):
		if used[i] == 0:
			j = pos[i]
			ans += sum(used[i:j])
			used[i] = used[j] = 1
	return ans
import sys
input = lambda : sys.stdin.readline().rstrip()
t = int(input())
for i in range(t):
	print(solve())


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
from bisect import bisect_left as lower_bound, bisect_right as upper_bound

def so():
	return int(input())

def st():
	return input()

def mj():
	return map(int, input().strip().split(' '))

def msj():
	return map(str, input().strip().split(' '))

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

def lebe():
	return list(map(int, input()))

def dmain():
	sys.setrecursionlimit(1000000)
	threading.stack_size(1024000)
	thread = threading.Thread(target=main)
	thread.start()

def joro(L):
	return ''.join(map(str, L))

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

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

def read():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def tr(n):
	return n * (n + 1) // 2

def iu():
	(n, q) = mj()
	L = []
	Y = []
	Z = []
	M = [0] * (2 * n)
	d = 0
	for i in range(q):
		(a, b) = mj()
		a -= 1
		b -= 1
		if b < a:
			c = a
			a = b
			b = c
		Y.append(a)
		Z.append(b)
		M[b] = 1
		M[a] = 1
	for i in range(2 * n):
		if M[i] == 0:
			L.append(i)
	for i in range(n - q):
		Y.append(L[i])
		Z.append(L[i - q + n])
	for i in range(n):
		for j in range(n):
			if Y[i] < Y[j]:
				if Z[i] < Z[j]:
					if Z[i] > Y[j]:
						d += 1
	print(d)

def main():
	for i in range(so()):
		iu()
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')

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()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


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

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

def imi():
	return map(int, input().split())
t = ii()
for _ in range(t):
	(n, k) = imi()
	fp = [1] * (2 * n + 1)
	li = []
	for i in range(k):
		(x, y) = imi()
		if x > y:
			(x, y) = (y, x)
		li.append((x, y))
		fp[x] = 0
		fp[y] = 0
	for i in range(2, 2 * n + 1):
		fp[i] = fp[i] + fp[i - 1]
	s = 0
	for i in range(k):
		(x, y) = li[i]
		ins = fp[y] - fp[x]
		outs = fp[x] + fp[2 * n] - fp[y]
		s += min(ins, outs)
		for j in range(i + 1, k):
			(a, b) = li[j]
			if a < x and x < b < y:
				s += 1
			elif x < a < y and y < b:
				s += 1
	s += (n - k) * (n - k - 1) // 2
	print(s)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	res = 0
	usd = [0 for _ in range(2 * n)]
	s = []
	for i in range(k):
		s.append([int(x) - 1 for x in input().split()])
		usd[s[i][0]] = 1
		usd[s[i][1]] = 1
	for i in range(k):
		for j in range(i + 1, k):
			if s[i][0] < max(s[j]) and s[i][0] > min(s[j]):
				if s[i][1] < min(s[j]) or s[i][1] > max(s[j]):
					res += 1
			elif s[i][1] < max(s[j]) and s[i][1] > min(s[j]):
				if s[i][0] < min(s[j]) or s[i][0] > max(s[j]):
					res += 1
	ost = []
	for i in range(2 * n):
		if usd[i] == 0:
			ost.append(i)
	for i in range(len(ost) // 2):
		s.append([ost[i], ost[i + len(ost) // 2]])
	k = len(s)
	res = 0
	for i in range(k):
		for j in range(i + 1, k):
			if s[i][0] < max(s[j]) and s[i][0] > min(s[j]):
				if s[i][1] < min(s[j]) or s[i][1] > max(s[j]):
					res += 1
			elif s[i][1] < max(s[j]) and s[i][1] > min(s[j]):
				if s[i][0] < min(s[j]) or s[i][0] > max(s[j]):
					res += 1
	print(res)


import collections
import math
import itertools
import sys

def fast_input():
	return sys.stdin.readline().strip()
input = fast_input

def ints_input():
	return list((int(x) for x in input().split()))

def solve():
	(n, k) = ints_input()
	chords = [sorted(ints_input()) for _ in range(k)]
	remaining_points = set(range(1, 2 * n + 1))
	for (a, b) in chords:
		remaining_points.remove(a)
		remaining_points.remove(b)
	remaining_points = sorted(list(remaining_points))
	pairs = len(remaining_points) // 2
	for (p_1, p_2) in zip(remaining_points[:pairs], remaining_points[pairs:]):
		chords.append((p_1, p_2))
	intersections = 0
	for (c_1, c_2) in itertools.product(chords, chords):
		if c_1[0] <= c_2[0]:
			continue
		first_between = c_1[0] < c_2[0] < c_1[1]
		second_between = c_1[0] < c_2[1] < c_1[1]
		if first_between != second_between:
			intersections += 1
	print(intersections)
for _ in range(int(input())):
	solve()


import itertools

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

def intersect(first, second):
	return sum((x < y for x in first for y in second)) & 1

def test_intersect():
	assert intersect((2, 5), (3, 1))
	assert intersect((2, 5), (4, 7))
	assert not intersect((2, 5), (1, 7))
	assert not intersect((2, 5), (4, 3))

def solve():
	(n, k) = readline()
	chords = [tuple(readline()) for __ in range(k)]
	is_free = [True] * (2 * n)
	for point in itertools.chain.from_iterable(chords):
		is_free[point - 1] = False
	free = [i for (i, f) in enumerate(is_free, start=1) if f]
	chords.extend(zip(free, free[n - k:]))
	print(sum((intersect(a, b) for (a, b) in itertools.combinations(chords, 2))))
t = int(input())
for __ in range(t):
	solve()


import sys

def I():
	return int(sys.stdin.readline().rstrip())

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

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

def LI2():
	return list(map(int, sys.stdin.readline().rstrip()))

def S():
	return sys.stdin.readline().rstrip()

def LS():
	return list(sys.stdin.readline().rstrip().split())

def LS2():
	return list(sys.stdin.readline().rstrip())
t = I()
for _ in range(t):
	(n, k) = MI()
	flag = [0] * (2 * n + 1)
	cord = []
	for _ in range(k):
		(x, y) = MI()
		if x > y:
			(x, y) = (y, x)
		cord.append((x, y))
		flag[x] = flag[y] = 1
	left = []
	for i in range(1, 2 * n + 1):
		if not flag[i]:
			left.append(i)
	for i in range(n - k):
		cord.append((left[i], left[i + n - k]))
	ans = 0
	for i in range(n):
		(x0, y0) = cord[i]
		for j in range(i + 1, n):
			(x1, y1) = cord[j]
			if x0 < x1 < y0:
				if y0 < y1 or y1 < x0:
					ans += 1
			elif y0 < x1:
				if x0 < y1 < y0:
					ans += 1
			elif x0 < y1 < y0:
				ans += 1
	print(ans)


from sys import stdin, stdout, setrecursionlimit as srl
from threading import stack_size
from collections import deque, defaultdict as dd
from math import gcd, ceil
from bisect import bisect_left as lb
from bisect import bisect_right as rb
input = stdin.readline
flush = stdout.flush
tc = 1
tc = int(input())
for _ in range(tc):
	(n, k) = map(int, input().split())
	d = {}
	for i in range(k):
		(u, v) = map(int, input().split())
		d[u] = v
		d[v] = u
	for i in range(1, 2 * n + 1):
		if i in d:
			continue
		s = set()
		cnt1 = 0
		cnt2 = 0
		cnt3 = 2 * n - 2 * k - 2
		tn = -1
		tv = -1
		for kk in range(i, 2 * n + i + 1):
			j = kk % (2 * n) + (kk == 2 * n) * kk
			if i == j:
				continue
			if j in d:
				if j not in s:
					cnt1 += 1
					s.add(d[j])
				else:
					cnt1 -= 1
					s.remove(j)
				continue
			if min(cnt2, cnt3) > tv:
				tv = min(cnt2, cnt3)
				tn = j
			cnt2 += 1
			cnt3 = max(0, cnt3 - 1)
		d[i] = tn
		d[tn] = i
		k += 1
	ans = 0
	s = set()
	c = []
	for i in d:
		if i not in s:
			s.add(d[i])
			c.append([i, d[i]])
		else:
			s.remove(i)
	for i in range(len(c)):
		for j in range(len(c)):
			if i == j:
				continue
			cnt = 0
			if c[j][0] < max(c[i]) and c[j][0] > min(c[i]):
				cnt += 1
			if c[j][1] < max(c[i]) and c[j][1] > min(c[i]):
				cnt += 1
			if cnt == 1:
				ans += 1
	print(ans // 2)


import sys

def read(lst=False):
	line = sys.stdin.readline().strip()
	if lst:
		return map(int, line.split())
	return line

def solver(N, K):
	for i in range(N - K):
		pairs.append((unusedPoints[N - K + i], unusedPoints[i]))
	ans = 0
	for i in range(N):
		(x1, y1) = pairs[i]
		for j in range(i + 1, N):
			(x2, y2) = pairs[j]
			if x1 > x2 > y1 and y1 > y2 or (x1 > y2 > y1 and x1 < x2):
				ans += 1
	return ans
(T,) = read(True)
for t in range(T):
	(N, K) = read(True)
	unused = [1] * (2 * N + 1)
	pairs = []
	for i in range(K):
		(X, Y) = read(True)
		unused[X] = unused[Y] = 0
		pairs.append((max(X, Y), min(X, Y)))
	unusedPoints = list(filter(lambda x: unused[x], range(1, 2 * N + 1)))
	ans = solver(N, K)
	print(ans)
sys.exit()


def intersect(c1, c2):
	(a, b) = sorted(list(c1))
	(c, d) = sorted(list(c2))
	return a < c < b and (not a < d < b) or (a < d < b and (not a < c < b))
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	used = set()
	unused = []
	chords = []
	for _ in range(k):
		(x, y) = map(int, input().split())
		used.add(x)
		used.add(y)
		chords.append((x, y))
	for i in range(1, 2 * n + 1):
		if i not in used:
			unused.append(i)
	for i in range(n - k):
		chords.append((unused[i], unused[i + n - k]))
	ans = 0
	for i in range(len(chords)):
		for j in range(i + 1, len(chords)):
			if intersect(chords[i], chords[j]):
				ans += 1
	print(ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = set({})
	a = [[] for _ in range(n)]
	ans = 0
	for i in range(1, 2 * n + 1):
		s.add(i)
	for i in range(k):
		(x, y) = map(int, input().split())
		s.remove(x)
		s.remove(y)
		l = [x, y]
		l.sort()
		a[i] = l
	l = list(s)
	l.sort()
	for i in range(len(l)):
		a[i % (n - k) + k].append(l[i])
	for i in range(n):
		for j in range(i + 1, n):
			x = a[i]
			y = a[j]
			z = x + y
			z.sort()
			if z[:2] == x or z[:2] == y or z[1:3] == x or (z[1:3] == y):
				ans += 0
			else:
				ans += 1
	print(ans)


cases = int(input())

def intersect(pair_1, pair_2):
	(x_1, y_1) = pair_1
	(x_2, y_2) = pair_2
	if x_1 > x_2:
		(x_1, x_2) = (x_2, x_1)
		(y_1, y_2) = (y_2, y_1)
	return y_1 > x_2 and y_1 < y_2
for i in range(cases):
	(halfpoints, chords) = [int(x) for x in input().split()]
	chordpairs = []
	drawn_points = [False for x in range(halfpoints * 2)]
	pairs = []
	for k in range(chords):
		(x, y) = [int(x) for x in input().split()]
		drawn_points[x - 1] = True
		drawn_points[y - 1] = True
		if x > y:
			(x, y) = (y, x)
		pairs.append((x - 1, y - 1))
	not_drawn_points = []
	for j in range(halfpoints * 2):
		if not drawn_points[j]:
			not_drawn_points.append(j)
	for j in range(halfpoints - chords):
		pairs.append((not_drawn_points[j], not_drawn_points[j + halfpoints - chords]))
	counter = 0
	for j in range(halfpoints):
		for k in range(halfpoints):
			if intersect(pairs[j], pairs[k]):
				counter += 1
	print(int(counter / 2))


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	arr = [0] * (2 * n + 5)
	for i in range(k):
		(a, b) = map(int, input().split())
		if a > b:
			(a, b) = (b, a)
		arr[a] = b
		arr[b] = a
	lst = []
	for i in range(1, 2 * n + 1):
		if arr[i] == 0:
			lst.append(i)
	ln = len(lst) // 2
	f = lst[:ln]
	s = lst[ln:]
	j = 0
	for idx in f:
		arr[idx] = s[j]
		arr[s[j]] = idx
		j = (j + 1) % ln
	res = 0
	for i in range(1, 2 * n + 1):
		for j in range(1, 2 * n + 1):
			(a1, a2) = (i, arr[i])
			if a1 > a2:
				(a1, a2) = (a2, a1)
			(b1, b2) = (j, arr[j])
			if b1 > b2:
				(b1, b2) = (b2, b1)
			if a1 < b1 < a2:
				if b2 > a2 or b2 < a1:
					res += 1
	print(res // 4)


import sys
input = sys.stdin.readline

def solve():
	(n, k) = map(int, input().split())
	z = [None] * (2 * n)
	a = [tuple(map(int, input().split())) for i in range(k)]
	i = 0
	for (x, y) in a:
		z[x - 1] = i
		z[y - 1] = i
		i += 1
	w = i
	for j in range(2 * n):
		if z[j] is None:
			if len(a) != n:
				z[j] = i
				a.append([j + 1, None])
				i += 1
			elif len(a) == n:
				if i == n:
					i = w
				z[j] = i
				a[i][1] = j + 1
				i += 1
	r = 0
	for i in range(n):
		(x, y) = a[i]
		if x > y:
			(x, y) = (y, x)
		c = [0] * n
		for j in range(x - 1, y):
			c[z[j]] ^= 1
		r += sum(c)
	print(r // 2)
for i in range(int(input())):
	solve()


import itertools

def intersect(a, b):
	(a0, a1) = a
	(b0, b1) = b
	if b0 > a0 and b0 < a1 or (b0 < a0 and b0 > a1):
		if b1 > a0 and b1 > a1 or (b1 < a0 and b1 < a1):
			return True
	if b1 > a0 and b1 < a1 or (b1 < a0 and b1 > a1):
		if b0 > a0 and b0 > a1 or (b0 < a0 and b0 < a1):
			return True
	return False

def solve(n, k, chords):
	flag = [True] * (2 * n)
	for (a, b) in chords:
		flag[a - 1] = False
		flag[b - 1] = False
	points = []
	for i in range(2 * n):
		if flag[i]:
			points.append(i + 1)
	for i in range(n - k):
		chords.append((points[i], points[i + n - k]))
	cnt = 0
	for (a, b) in itertools.combinations(chords, 2):
		if intersect(a, b):
			cnt += 1
	return cnt

def main():
	t = int(input())
	ans = []
	for i in range(t):
		(n, k) = list(map(int, input().split(' ')))
		chords = [list(map(int, input().split(' '))) for _ in range(k)]
		ans.append(solve(n, k, chords))
	for a in ans:
		print(a)
main()


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	ans = (n - k) * (n - k - 1)
	x = [0] * k
	y = [0] * k
	a = [0] * k
	b = [0] * k
	for i in range(k):
		(x[i], y[i]) = map(int, input().split())
		if x[i] > y[i]:
			(x[i], y[i]) = (y[i], x[i])
		a[i] = y[i] - x[i] - 1
		b[i] = 2 * n - a[i] - 2
	for i in range(k):
		for j in range(k):
			if i != j:
				p = 0
				if x[i] < x[j] < y[i]:
					p = 1
					a[i] -= 1
				else:
					b[i] -= 1
				q = 0
				if x[i] < y[j] < y[i]:
					q = 1
					a[i] -= 1
				else:
					b[i] -= 1
				if p != q:
					ans += 1
	ans //= 2
	for i in range(k):
		ans += min(a[i], b[i])
	print(ans)


import sys
input = iter(sys.stdin.read().splitlines()).__next__

def intersects(x1, y1, x2, y2):
	return x2 < y1 < y2

def solve():
	(n, k) = map(int, input().split())
	pairing = [None] * (n << 1)
	for _ in range(k):
		(x, y) = map(lambda i: int(i) - 1, input().split())
		pairing[x] = y
		pairing[y] = x
	unpaired = [i for (i, partner) in enumerate(pairing) if partner is None]
	for i in range(n - k):
		(x, y) = (unpaired[i], unpaired[n - k + i])
		pairing[x] = y
		pairing[y] = x
	num_intersections = 0
	for i in range(2 * n):
		for j in range(i + 1, 2 * n):
			if pairing[i] < i or pairing[j] < j:
				continue
			if intersects(i, pairing[i], j, pairing[j]):
				num_intersections += 1
	return num_intersections
t = int(input())
output = []
for _ in range(t):
	output.append(solve())
print(*output, sep='\n')


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = [0] * (2 * n + 1)
	b = []
	for i in range(k):
		t = list(map(int, input().split()))
		b.append(t)
		a[t[0]] = 1
		a[t[1]] = 1
	i = 1
	j = 2
	lg = 0
	while i <= n * 2 and j <= 2 * n:
		if a[i] > 0:
			i += 1
			continue
		if a[j] > 0:
			j += 1
			continue
		if j <= i:
			lg = 0
			j += 1
			continue
		lg += 1
		if lg == n - k:
			b.append([i, j])
			a[i] = 1
			a[j] = 1
			lg -= 1
			i += 1
			j += 1
		else:
			j += 1
	ans = 0
	for i in range(n):
		for j in range(i + 1, n):
			t1 = b[i][0]
			t2 = b[i][1]
			t3 = b[j][0]
			t4 = b[j][1]
			t = [(t1, 0), (t2, 0), (t3, 1), (t4, 1)]
			t.sort()
			if t[0][1] == t[1][1] or t[1][1] == t[2][1] or t[2][1] == t[3][1] or (t[3][1] == t[0][1]):
				continue
			else:
				ans += 1
	print(ans)


import os, sys
from io import BytesIO, IOBase

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, 8192))
			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, 8192))
			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')

class dict(dict):

	def __missing__(self, key):
		return 0
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
inp = lambda dtype: [dtype(x) for x in input().split()]
inp_2d = lambda dtype, n: [dtype(input()) for _ in range(n)]
inp_2ds = lambda dtype, n: [inp(dtype) for _ in range(n)]
inp_enu = lambda dtype: [(i, x) for (i, x) in enumerate(inp(dtype))]
inp_enus = lambda dtype, n: [[i] + [inp(dtype)] for i in range(n)]
ceil1 = lambda a, b: (a + b - 1) // b
for _ in range(int(input())):
	(n, k) = inp(int)
	n <<= 1
	adj = [0 for _ in range(n + 1)]
	for i in range(k):
		(u, v) = inp(int)
		(adj[u], adj[v]) = (v, u)
	rem = sorted([x for x in range(1, n + 1) if not adj[x]])
	(md, ans) = (len(rem) >> 1, 0)
	for i in range(md):
		(adj[rem[i]], adj[rem[md + i]]) = (rem[md + i], rem[i])
	for i in range(1, n + 1):
		(be, en, all) = (i % n + 1, adj[i], set())
		while be != en:
			all.add(be)
			be = be % n + 1
		for ele in all:
			ans += adj[ele] not in all
	print(ans >> 2)


import sys
import math
mod = 10 ** 9 + 7
LI = lambda : [int(k) for k in input().split()]
input = lambda : sys.stdin.readline().rstrip()
IN = lambda : int(input())
S = lambda : input()
r = range
for t in r(IN()):
	(n, k) = LI()
	ans = 0
	pair = []
	done = dict()
	for i in range(k):
		(x, y) = LI()
		if x > y:
			(x, y) = (y, x)
		pair += [[x, y]]
		done[x] = 1
		done[y] = 1
	avail = []
	for i in range(1, 2 * n + 1):
		if i not in done:
			avail += [i]
	for i in range(n - k):
		pair += [[min(avail[i], avail[i + n - k]), max(avail[i], avail[i + n - k])]]
	pair.sort()
	for i in range(n):
		for j in range(i + 1, n):
			if pair[i][0] < pair[j][0]:
				if pair[j][0] < pair[i][1]:
					if pair[i][1] < pair[j][1]:
						ans += 1
	print(ans)


import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(2 * 10 ** 5 + 10)
write = lambda x: sys.stdout.write(x + '\n')
debug = lambda x: sys.stderr.write(x + '\n')
writef = lambda x: print('{:.12f}'.format(x))
from itertools import chain
t = int(input())
ans = []
for _ in range(t):
	(n, k) = list(map(int, input().split()))
	done = [0] * (2 * n)
	uv = []
	for i in range(k):
		(u, v) = list(map(int, input().split()))
		u -= 1
		v -= 1
		if u > v:
			(u, v) = (v, u)
		uv.append((u, v))
		done[u] = done[v] = 1
	val = 2 * n - sum(done)
	res0 = val // 2 * (val // 2 - 1) // 2
	res1 = res2 = 0
	for (i, (u, v)) in enumerate(uv):
		v0 = v1 = 0
		for j in range(u + 1, v):
			if not done[j]:
				v0 += 1
		for j in chain(range(v + 1, 2 * n), range(u)):
			if not done[j]:
				v1 += 1
		res1 += min(v0, v1)
		for j in range(i + 1, k):
			if i == j:
				continue
			(uu, vv) = uv[j]
			if u < uu and vv < v or (uu < u and v < vv) or v < uu or (vv < u):
				pass
			else:
				res2 += 1
	ans.append(res0 + res1 + res2)
write('\n'.join(map(str, ans)))


import sys
import bisect
from bisect import bisect_left as lb
from bisect import bisect_right as rb
input_ = lambda : sys.stdin.readline().strip('\r\n')
from math import log
from math import gcd
from math import atan2, acos
from random import randint
sa = lambda : input_()
sb = lambda : int(input_())
sc = lambda : input_().split()
sd = lambda : list(map(int, input_().split()))
sflo = lambda : list(map(float, input_().split()))
se = lambda : float(input_())
sf = lambda : list(input_())
flsh = lambda : sys.stdout.flush()
mod = 10 ** 9 + 7
mod1 = 998244353
gp = []
cost = []
dp = []
mx = []
ans1 = []
ans2 = []
special = []
specnode = []
a = 0
kthpar = []

def dfs2(root, par):
	if par != -1:
		dp[root] = dp[par] + 1
	for i in range(1, 20):
		if kthpar[root][i - 1] != -1:
			kthpar[root][i] = kthpar[kthpar[root][i - 1]][i - 1]
	for child in gp[root]:
		if child == par:
			continue
		kthpar[child][0] = root
		dfs(child, root)
ans = 0
b = []
vis = []
tot = 0
time = []
time1 = []
adj = []
mx = -1

def dfs(a, b, p, c):
	if a == b:
		return c
	for (i, j) in adj[a]:
		if i == p:
			continue
		temp = dfs(i, b, a, c + j)
		if dfs(i, b, a):
			mx = max(i, mx)
			return 1

def hnbhai(tc):
	(n, k) = sd()
	d = [0] * (2 * n)
	a = []
	tot = 2 * n
	for i in range(k):
		(x, y) = sd()
		x -= 1
		y -= 1
		l = [x, y]
		l.sort()
		a.append(l)
		tot -= 2
		d[x] = 1
		d[y] = 1
	for i in range(2 * n):
		if d[i] == 0:
			temp = i
			tt = 0
			while tt != tot // 2:
				temp += 1
				temp %= 2 * n
				if d[temp] == 0:
					tt += 1
			tot -= 2
			a.append(list(sorted([i, temp])))
			d[i] = 1
			d[temp] = 1
	ans = 0
	a.sort()
	for i in range(len(a)):
		for j in range(i + 1, len(a)):
			(x1, y1, x2, y2) = (a[i][0], a[i][1], a[j][0], a[j][1])
			if min(x1, y1) <= min(x2, y2) <= max(x1, y1) and max(x2, y2) >= max(x1, y1):
				ans += 1
	print(ans)

def dfs(root):
	global tot, vis, gp
	for child in gp[root]:
		if vis[child] == 0:
			tot += 1
			vis[child] = 1
			dfs(child)
for _ in range(sb()):
	hnbhai(_ + 1)


import sys, os, io
from sys import stdin
import math
from collections import defaultdict
from heapq import heappush, heappop, heapify
from bisect import bisect_left, bisect_right
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')
alphabets = list('abcdefghijklmnopqrstuvwxyz')
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

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

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def sieveForSmallestPrimeFactor():
	MAXN = 100001
	spf = [0 for i in range(MAXN)]
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, math.ceil(math.sqrt(MAXN))):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i
	return spf

def getPrimeFactorizationLOGN(x):
	spf = sieveForSmallestPrimeFactor()
	ret = list()
	while x != 1:
		ret.append(spf[x])
		x = x // spf[x]
	return ret

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

def si():
	return input()

def divideCeil(n, x):
	if n % x == 0:
		return n // x
	return n // x + 1

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

def li():
	return list(map(int, input().split()))
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	input = lambda : sys.stdin.readline().rstrip('\r\n')

def intersect(a, b, c, d):
	if a > b:
		(a, b) = (b, a)
	if c > d:
		(c, d) = (d, c)
	if a < c < b < d or c < a < d < b:
		return True
	return False

def cntint(l, a, b):
	n = len(l)
	ans = 0
	for j in range(n):
		if j != a and j != b and (l[j] != -1):
			c = j
			d = l[j]
			if intersect(a, b, c, d):
				ans += 1
	return ans

def solve():
	(n, k) = li()
	l = [-1] * (2 * n)
	for i in range(k):
		(le, r) = li()
		le -= 1
		r -= 1
		l[le] = r
		l[r] = le
	ans = 0
	temp = []
	for i in range(2 * n):
		if l[i] == -1:
			temp.append(i)
	temp.sort()
	m = len(temp) // 2
	for i in range(len(temp) // 2):
		l[temp[i]] = temp[m]
		l[temp[m]] = temp[i]
		m += 1
	dd = defaultdict(lambda : 0)
	for i in range(2 * n):
		if l[i] != -1:
			a = i
			b = l[i]
			for j in range(2 * n):
				if j != i and l[j] != -1:
					c = j
					d = l[j]
					xx = [a, b, c, d]
					xx.sort()
					xx = tuple(xx)
					if intersect(a, b, c, d) and dd[xx] == 0:
						dd[xx] = 1
						ans += 1
	print(ans)
	return
	for i in range(n):
		if l[i] != -1:
			continue
		a = i
		which = -1
		mx = -1
		for b in range(1, 2 * n):
			if l[b] != -1 or b == a:
				continue
			cnt = cntint(l, a, b)
			if cnt > mx:
				mx = cnt
				which = b
		if which != -1:
			l[a] = which
			l[which] = a
	print(l)
	if -1 in l:
		ind = l.index(-1)
		for i in range(2 * n):
			if ind != i and l[i] == -1:
				l[ind] = i
				l[i] = ind
				break
	ans = 0
	dd = defaultdict(lambda : 0)
	for i in range(2 * n):
		if l[i] != -1:
			a = i
			b = l[i]
			for j in range(2 * n):
				if j != i:
					c = j
					d = l[j]
					xx = [a, b, c, d]
					xx.sort()
					xx = tuple(xx)
					if intersect(a, b, c, d) and dd[xx] == 0:
						dd[xx] = 1
						ans += 1
	print(l)
	print('ans', ans)
t = 1
t = ii()
for _ in range(t):
	solve()


for __ in range(int(input())):
	(n, k) = map(int, input().split())
	(clis, taken) = ([], [])
	for i in range(k):
		(x, y) = map(int, input().split())
		taken += [x, y]
		if x > y:
			clis.append([y, x])
		else:
			clis.append([x, y])
	n_taken = []
	for i in range(1, 2 * n + 1):
		if i in taken:
			continue
		n_taken.append(i)
	n_taken.sort()

	def intersect(a, b):
		if a[1] > b[1] > a[0] > b[0] or b[1] > a[1] > b[0] > a[0]:
			return True
		return False
	intersections = 0
	for i in range(k):
		for j in range(i + 1, k):
			if intersect(clis[i], clis[j]):
				intersections += 1
	while True:
		if len(n_taken) <= 0:
			break
		a = n_taken.pop(0)
		b = n_taken.pop(len(n_taken) // 2)
		for i in clis:
			if intersect([a, b], i):
				intersections += 1
		clis.append([a, b])
	print(intersections)


def solve(r, n):
	counts = 0
	missing_count = 0
	missing = []
	for i in range(n):
		if r[i] == -1:
			missing_count += 1
			missing.append(i)
	missing_count = int(missing_count / 2)
	for i in range(missing_count):
		r[missing[i]] = missing[i + missing_count]
		r[missing[i + missing_count]] = missing[i]
	for i in range(n):
		if r[i] > i:
			for j in range(i + 1, r[i]):
				if r[j] < i or r[j] > r[i]:
					counts += 1
	return int(counts / 2)
v = []
t = int(input())
for i in range(t):
	(n, k) = [int(x) for x in input().split(' ')]
	n *= 2
	r = [-1] * n
	for j in range(k):
		(x1, x2) = [int(x) - 1 for x in input().split(' ')]
		(r[x1], r[x2]) = (x2, x1)
	print(solve(r, n))


from math import *

class st:

	def __init__(self, noe):
		self.noe = noe
		self.bp = 2 ** ceil(log2(noe))
		self.h = [[] for i in range(2 * self.bp)]
		self.id = 0

	def ri(self, l, r):
		l += self.bp
		r += self.bp
		while l <= r:
			if l & 1:
				self.h[l].append(self.id)
				l += 1
			if not r & 1:
				self.h[r].append(self.id)
				r -= 1
			l //= 2
			r //= 2
		self.id += 1

	def q(self, idx):
		idx += self.bp
		ans = list()
		while idx > 0:
			for el in self.h[idx]:
				ans.append(el)
			idx //= 2
		return ans
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	y = set()
	for i in range(1, 2 * n + 1):
		y.add(i)
	pairs = list()
	for i in range(k):
		tmp = list(map(int, input().split()))
		tmp.sort()
		y.remove(tmp[0])
		y.remove(tmp[1])
		pairs.append(tmp)
	ll = list(y)
	ll.sort()
	sp = len(ll) // 2
	for i in range(sp):
		p = [ll[i], ll[i + sp]]
		pairs.append(p)
	t = st(240)
	ans = 0
	for el in pairs:
		Q = t.q(el[0])
		Q += t.q(el[1])
		tmp = set()
		x = 0
		for ell in Q:
			if ell in tmp:
				x -= 1
			else:
				tmp.add(ell)
				x += 1
		ans += x
		t.ri(el[0], el[1])
	print(ans)


import sys, os
from io import BytesIO, IOBase
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
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')
(stdin, stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
mod = pow(10, 9) + 7
mod2 = 998244353

def inp():
	return stdin.readline().strip()

def iinp():
	return int(inp())

def out(var, end='\n'):
	stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	stdout.write(' '.join(map(str, var)) + end)

def lmp():
	return list(mp())

def mp():
	return map(int, inp().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(m, val) for j in range(n)]

def ceil(a, b):
	return (a + b - 1) // b
S1 = 'abcdefghijklmnopqrstuvwxyz'
S2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def isprime(x):
	if x <= 1:
		return False
	if x in (2, 3):
		return True
	if x % 2 == 0:
		return False
	for i in range(3, int(sqrt(x)) + 1, 2):
		if x % i == 0:
			return False
	return True
for _ in range(iinp()):
	(n, k) = mp()
	lines = []
	taken = l1d(2 * n)
	for i in range(k):
		(a, b) = sorted(mp())
		lines.append((a, b))
		taken[a - 1] = 1
		taken[b - 1] = 1
	new = taken.count(0) // 2
	ans = new * (new - 1) // 2
	acm = 0
	for (a, b) in lines:
		x = taken[a:b].count(0)
		y = 2 * new - x
		ans += min(x, y)
	for i in range(len(lines)):
		(a, b) = lines[i]
		for j in range(i + 1, len(lines)):
			(c, d) = lines[j]
			if a < c < b < d or c < a < d < b or c < a < d < b or (a < c < b < d):
				acm += 1
	print(ans + acm)


def getSide(pair, p):
	return p > min(pair[0], pair[1]) and p < max(pair[0], pair[1])

def findMaxIntersection(n, k, pairs):
	checked = [True for i in range(n * 2)]
	for p in pairs:
		checked[p[0]] = checked[p[1]] = False
	available = [i for i in range(n * 2) if checked[i]]
	for i in range(n - k):
		pairs.append((available[i], available[i + n - k]))
	result = 0
	for pId in range(n):
		for pId1 in range(pId + 1, n):
			if getSide(pairs[pId], pairs[pId1][0]) != getSide(pairs[pId], pairs[pId1][1]):
				result += 1
	return result
t = int(input())
for test in range(t):
	(n, k) = [int(i) for i in input().split()]
	pairs = []
	for i in range(k):
		(x, y) = [int(i) - 1 for i in input().split()]
		pairs.append((x, y))
	print(findMaxIntersection(n, k, pairs))


import itertools

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

def intersect(a, b):
	return sum((x < y for x in a for y in b)) & 1
t = int(input())
for __ in range(t):
	(n, k) = readline()
	chords = [(*readline(),) for __ in range(k)]
	free = set(range(1, 2 * n + 1)) - set(itertools.chain.from_iterable(chords))
	seq = sorted(free)
	chords.extend(zip(seq, seq[n - k:]))
	print(sum((intersect(a, b) for (a, b) in itertools.combinations(chords, 2))))


for __ in range(int(input())):
	(n, k) = map(int, input().split())
	s = [i + 1 for i in range(2 * n)]
	c1 = []
	c2 = []
	ans = 0
	for i in range(k):
		(s1, s2) = map(int, input().split())
		c1.append(max(s1, s2))
		c2.append(min(s1, s2))
		s.remove(s1)
		s.remove(s2)
	for i in range(n - k):
		c1.append(s[i + n - k])
		c2.append(s[i])
	for i in range(n):
		for j in range(n):
			if (c1[i] > c1[j] and c1[j] > c2[i]) != (c1[i] > c2[j] and c2[j] > c2[i]):
				ans += 1
	print(ans // 2)


import sys
from bisect import bisect_left as lb
from collections import deque
from queue import PriorityQueue as pq
from math import *
input_ = lambda : sys.stdin.readline().strip('\r\n')
ii = lambda : int(input_())
il = lambda : list(map(int, input_().split()))
ilf = lambda : list(map(float, input_().split()))
ip = lambda : input_()
fi = lambda : float(input_())
ap = lambda ab, bc, cd: ab[bc].append(cd)
li = lambda : list(input_())
pr = lambda x: print(x)
prinT = lambda x: print(x)
f = lambda : sys.stdout.flush()
inv = lambda x: pow(x, mod - 2, mod)
mod = 10 ** 9 + 7

def inter(x, y):
	if x[0] > y[0]:
		(x, y) = (y, x)
	if x[1] > y[0] and x[1] < y[1]:
		return 1
	return 0
for _ in range(ii()):
	(n, k) = il()
	d = [0 for i in range(2 * n)]
	a = []
	t = 2 * n
	for i in range(k):
		(x, y) = il()
		t -= 2
		x -= 1
		y -= 1
		l = [x, y]
		l.sort()
		a.append(l)
		d[x] = 1
		d[y] = 1
	b = []
	for i in range(2 * n):
		if d[i] == 0:
			b.append(i)
	for i in range(n - k):
		a.append([b[i], b[i + n - k]])
	ans = 0
	for i in range(n):
		for j in range(i + 1, n):
			ans += inter(a[i], a[j])
	print(ans)


T = int(input())
for t in range(T):
	(n, k) = map(int, input().split())
	used = [False] * (2 * n + 1)
	chc = []
	(a, b) = (0, 0)
	for i in range(k):
		(a, b) = map(int, input().split())
		if a > b:
			(a, b) = (b, a)
		chc.append([a, b])
		used[a] = used[b] = True
	unused = []
	for i in range(1, 2 * n + 1):
		if not used[i]:
			unused.append(i)
	for i in range(n - k):
		chc.append([unused[i], unused[i + n - k]])
	ans = 0
	for i in range(n):
		for j in range(i + 1, n):
			(a, b) = (chc[i], chc[j])
			if a[0] > b[0]:
				(a, b) = (b, a)
			p = a[1] > b[0] and a[1] < b[1]
			ans += p
	print(ans)


import sys
from os import path
if path.exists('Input.txt'):
	sys.stdin = open('Input.txt', 'r')
	sys.stdout = open('Output.txt', 'w')
input = lambda : sys.stdin.readline().rstrip()

def solve_tc():
	(n, k) = map(int, input().split())
	a = n - k
	ans = (a - 1) * a // 2
	ll = [0 for _ in range(n * 2)]
	p = []
	for _ in range(k):
		(a, b) = map(int, input().split())
		if a > b:
			p.append([b, a])
		else:
			p.append([a, b])
		ll[a - 1] = b
		ll[b - 1] = a
	for _ in range(len(p)):
		a = p[_][0] - 1
		b = p[_][1] - 1
		ans1 = ans2 = 0
		for j in range(a + 1, b):
			if ll[j]:
				if ll[j] - 1 < a or ll[j] - 1 > b:
					ans += 0.5
			else:
				ans1 += 1
		for j in range(0, a):
			if not ll[j]:
				ans2 += 1
		for j in range(b + 1, n * 2):
			if not ll[j]:
				ans2 += 1
		ans += min(ans2, ans1)
	return str(int(ans))
t = int(input())
for _ in range(t):
	sys.stdout.write(solve_tc() + '\n')


def do_intersect(chord1, chord2):
	(x1, y1) = chord1
	(x2, y2) = chord2
	if x1 > y1:
		(x1, y1) = (y1, x1)
	if x2 > y2:
		(x2, y2) = (y2, x2)
	if x1 < x2 < y1 and (not x1 < y2 < y1):
		return True
	if x2 < x1 < y2 and (not x2 < y1 < y2):
		return True
	return False

def solve():
	(n, k) = (int(x) for x in input().split())
	chordes = [[int(x) for x in input().split()] for _ in range(k)]
	used_indexes = set([x[0] for x in chordes] + [x[1] for x in chordes])
	unused_indexes = [x for x in range(1, 2 * n + 1) if x not in used_indexes]
	n2 = len(unused_indexes) // 2
	new_chordes = []
	for (i, x) in enumerate(unused_indexes[:n2]):
		new_chordes.append([x, unused_indexes[i + n2]])
	intersections = len(new_chordes) * (len(new_chordes) - 1) // 2
	for (i, c1) in enumerate(chordes):
		for c2 in chordes[i + 1:]:
			if do_intersect(c1, c2):
				intersections += 1
		for c2 in new_chordes:
			if do_intersect(c1, c2):
				intersections += 1
	print(intersections)
for _ in range(int(input())):
	solve()


from os import path
from io import BytesIO, IOBase
import sys
from heapq import heappush, heappop
from functools import cmp_to_key as ctk
from collections import deque, Counter, defaultdict as dd
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from itertools import permutations
from datetime import datetime
from math import ceil, sqrt, log, gcd

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

def si():
	return input().rstrip()

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

def li():
	return list(mi())
abc = 'abcdefghijklmnopqrstuvwxyz'
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def bo(i):
	return ord(i) - ord('0')
file = 1

def ceil(a, b):
	return (a + b - 1) // b

def solve():
	for _ in range(1, ii() + 1):
		(n, k) = mi()
		x = []
		p = [0] * (2 * n + 1)
		for i in range(k):
			x.append(li())
			if x[-1][1] < x[-1][0]:
				(x[-1][0], x[-1][1]) = (x[-1][1], x[-1][0])
			p[x[-1][0]] = 1
			p[x[-1][1]] = 1
		y = []
		for i in range(1, 2 * n + 1):
			if p[i] == 0:
				y.append(i)
		cnt = 0
		for i in range(k):
			for j in range(i + 1, k):
				if x[j][0] < x[i][0] < x[j][1] and x[i][0] < x[j][1] < x[i][1]:
					cnt += 1
				elif x[i][0] < x[j][0] < x[j][1] and x[j][0] < x[i][1] < x[j][1]:
					cnt += 1
		rem_cord = n - k
		y += y
		for i in range(rem_cord):
			x1 = y[i]
			y1 = y[i + rem_cord]
			for j in x:
				if j[0] < x1 < j[1] and x1 < j[1] < y1:
					cnt += 1
				elif x1 < j[0] < y1 and j[0] < y1 < j[1]:
					cnt += 1
			x.append([x1, y1])
		print(cnt)
if file:
	if path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	else:
		input = sys.stdin.readline
solve()


for _ in range(int(input())):
	(N, K) = map(int, input().split())
	chords = []
	used = [False] * (2 * N)
	for i in range(K):
		(x, y) = map(int, input().split())
		x -= 1
		y -= 1
		chords.append([x, y])
		used[x] = True
		used[y] = True
	ans = 0
	rem = []
	for i in range(2 * N):
		if not used[i]:
			rem.append(i)
	L = len(rem) // 2
	for i in range(L):
		chords.append([rem[i], rem[L + i]])
	chords.sort()
	for i in range(N):
		for j in range(i + 1, N):
			if chords[i][0] < chords[i][1] < chords[j][0] and (chords[j][0] < chords[j][1] or chords[j][1] < chords[i][0]):
				continue
			elif chords[i][0] < chords[j][1] < chords[j][0] and (chords[j][0] < chords[i][1] or chords[i][1] < chords[i][0]):
				continue
			elif chords[i][0] < chords[i][1] < chords[j][1] < chords[j][0]:
				continue
			elif chords[i][0] < chords[j][0] < chords[j][1] < chords[i][1]:
				continue
			elif chords[i][1] < chords[i][0] < chords[j][0] < chords[j][1]:
				continue
			elif chords[j][1] < chords[i][1] < chords[i][0] < chords[j][0]:
				continue
			else:
				ans += 1
	print(ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	array = []
	visited = [0] * (2 * n + 1)
	for i in range(k):
		tmp = [int(i) for i in input().split()]
		visited[tmp[0]] = 1
		visited[tmp[1]] = 1
		array.append(tmp)
	un = []
	for i in range(1, 2 * n + 1):
		if not visited[i]:
			un.append(i)
	x = len(un)
	for i in range(x // 2):
		array.append([un[i], un[x // 2 + i]])
	ans = 0
	for i in range(n):
		for j in range(i + 1, n):
			if min(array[i]) < min(array[j]) and max(array[i]) > min(array[j]) and (max(array[j]) > max(array[i])):
				ans += 1
			elif min(array[j]) < min(array[i]) and max(array[j]) > min(array[i]) and (max(array[i]) > max(array[j])):
				ans += 1
	print(ans)


T = int(input())

def get_score(n, seq, chord_dict):
	score = 0
	for i in range(n):
		freq = dict()
		chord = chord_dict[i]
		for j in range(chord[0] + 1, chord[1]):
			if seq[j] not in freq:
				freq[seq[j]] = 1
			else:
				freq[seq[j]] += 1
		for ele in freq:
			if freq[ele] == 1:
				score += 1
	return score // 2
for t in range(T):
	(n, k) = map(int, input().split())
	chords = []
	for i in range(k):
		chords.append(sorted([int(x) for x in input().split()]))
	all_points = set()
	for i in range(1, 2 * n + 1):
		all_points.add(i)
	for chord in chords:
		all_points.remove(chord[0])
		all_points.remove(chord[1])
	all_points_list = sorted(list(all_points))
	for i in range(len(all_points) // 2):
		chords.append([all_points_list[i], all_points_list[len(all_points) // 2 + i]])
	chords.sort()
	seq = [0] * (2 * n)
	chord_dict = dict()
	for i in range(len(chords)):
		chord = chords[i]
		seq[chord[0] - 1] = i
		seq[chord[1] - 1] = i
		chord_dict[i] = sorted([chord[0] - 1, chord[1] - 1])
	print(get_score(n, seq, chord_dict))


from __future__ import print_function
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, k) = invr()
	l = []
	ind = []
	h = set()
	for i in range(k):
		l.append(sorted(inlt()))
		h.add(l[-1][0])
		h.add(l[-1][1])
	x = []
	for i in range(1, 2 * n + 1):
		if i not in h:
			x.append(i)
	x.sort()
	m = [None] * (2 * n)
	s = 0
	for i in range(len(l)):
		m[l[i][0] - 1] = [i, 0]
		m[l[i][1] - 1] = [i, 1]
	id = len(l)
	y = x[:len(x) // 2]
	x = x[len(x) // 2:]
	for i in range(len(x)):
		l.append([min(x[i], y[i]), max(x[i], y[i])])
	c = 0
	for i in range(len(l)):
		for j in range(i + 1, len(l)):
			z = [l[i], l[j]]
			z.sort()
			if z[0][1] > z[1][0] and z[0][1] < z[1][1]:
				c += 1
	print(c)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	visited = [False for _ in range(2 * n + 1)]
	arr = []
	for i in range(k):
		(x, y) = map(int, input().split())
		visited[x] = True
		visited[y] = True
		if x > y:
			(x, y) = (y, x)
		arr.append((x, y))
	z = []
	for i in range(1, 2 * n + 1):
		if visited[i] == False:
			z.append(i)
	l = 0
	r = n - k
	while r < 2 * (n - k):
		arr.append((z[l], z[r]))
		l += 1
		r += 1
	count = 0
	arr.sort()
	for i in range(len(arr) - 1):
		for j in range(i + 1, len(arr)):
			if arr[i][0] < arr[j][0] and arr[i][1] < arr[j][1] and (arr[i][1] > arr[j][0]):
				count += 1
			if arr[i][0] > arr[j][0] and arr[i][1] > arr[j][1] and (arr[i][1] < arr[j][0]):
				count += 1
	print(count)


import sys, os
from math import *
from bisect import *
from heapq import *
from collections import *
from itertools import combinations
if os.path.exists('in.txt'):
	sys.stdin = open('in.txt', 'r')
from io import BytesIO, IOBase

def main():
	for _ in range(int(input())):
		(n, k) = MI()
		pair = dict()
		left = set([i + 1 for i in range(2 * n)])
		for __ in range(k):
			(u, v) = MI()
			if v < u:
				(u, v) = (v, u)
			left.remove(u)
			left.remove(v)
			pair[u] = v
		left = list(left)
		left.sort()
		for i in range(n - k):
			pair[left[i]] = left[n - k + i]
		out = 0
		for x in pair:
			for p in pair:
				if p == x:
					continue
				if p < x < pair[p] < pair[x] or x < p < pair[x] < pair[p]:
					out += 1
		print(out // 2)
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 MI():
	return map(int, input().split())

def outP(var):
	sys.stdout.write(str(var) + '\n')
MOD = 10 ** 9 + 7
mod = 998244353
main()


import sys
input = lambda : sys.stdin.readline().rstrip()

class BIT:

	def __init__(self, init):
		if type(init) == int:
			self.n = init + 1
			self.X = [0] * self.n
		else:
			self.n = len(init) + 1
			self.X = [0] + init
			for i in range(1, self.n):
				if i + (i & -i) < self.n:
					self.X[i + (i & -i)] += self.X[i]

	def add(self, i, x=1):
		i += 1
		while i < self.n:
			self.X[i] += x
			i += i & -i

	def getsum(self, i):
		ret = 0
		while i != 0:
			ret += self.X[i]
			i -= i & -i
		return ret

	def getrange(self, l, r):
		return self.getsum(r) - self.getsum(l)
T = int(input())
for _ in range(T):
	(N, K) = map(int, input().split())
	X = [0] * (N * 2)
	Y = []
	for _ in range(K):
		(a, b) = map(int, input().split())
		if a > b:
			(a, b) = (b, a)
		a -= 1
		b -= 1
		Y.append((a, b))
		X[a] = 1
		X[b] = 1
	Z = []
	for (i, x) in enumerate(X):
		if x == 0:
			Z.append(i)
	for i in range(N - K):
		Y.append((Z[i], Z[i + N - K]))
	Y.sort(key=lambda x: x[1])
	bit = BIT(2 * N)
	ans = 0
	for (a, b) in Y:
		ans += bit.getrange(a, b)
		bit.add(a, -1)
		bit.add(b, 1)
	print(ans)


for tests in range(int(input())):
	(n, k) = map(int, input().split())
	ls = [sorted(list(map(int, input().split()))) for i in range(k)]
	ans = 0
	arr = [-1 for i in range(2 * n)]
	for i in range(k):
		arr[ls[i][1] - 1] = ls[i][0] - 1
		arr[ls[i][0] - 1] = ls[i][0] - 1
	ar = []
	for i in range(2 * n):
		if arr[i] == -1:
			ar.append(i + 1)
	for i in range(n - k):
		ls.append([ar[i], ar[i + n - k]])
	ls.sort()
	for i in range(n):
		for j in range(i + 1, n):
			if ls[i][0] < ls[j][0] < ls[i][1] < ls[j][1]:
				ans += 1
	print(ans)


def intersect(a, b):
	if a[0] > b[0]:
		(a, b) = (b, a)
	return a[1] > b[0] and a[1] < b[1]

def f(q, n, k):
	vis = [0] * (2 * n + 1)
	for (l, r) in q:
		vis[l] = 1
		vis[r] = 1
	unvis = []
	for i in range(1, 2 * n + 1):
		if vis[i] == 0:
			unvis.append(i)
	for i in range(n - k):
		q.append((unvis[i], unvis[i + n - k]))
	ans = 0
	for i in range(len(q)):
		for j in range(i):
			ans += intersect(q[i], q[j])
	return ans
for _ in range(int(input())):
	(n, k) = map(int, input().strip().split())
	q = []
	for i in range(k):
		(x, y) = map(int, input().strip().split())
		q.append(sorted([x, y]))
	print(f(q, n, k))


from sys import stdin
t = int(stdin.readline())
for _ in range(t):
	(n, k) = map(int, stdin.readline().split())
	dic = dict(((i, -1) for i in range(2 * n)))
	chords = []
	for idx in range(k):
		(u, v) = map(lambda x: int(x) - 1, stdin.readline().split())
		dic[u] = idx
		dic[v] = idx
		chords.append((u, v))
	free = []
	for i in range(2 * n):
		if dic[i] == -1:
			free.append(i)
	for idx in range(k, n):
		chords.append((free[idx - k], free[idx + n - 2 * k]))
	ans = 0
	for i in range(n):
		for j in range(n):
			(a1, a2) = (min(chords[i]), max(chords[i]))
			(b1, b2) = (min(chords[j]), max(chords[j]))
			if a1 < b1 < a2 < b2:
				ans += 1
	print(ans)


t = int(input())

def intersects(first, second):
	s = ''.join([x[1] for x in sorted([(first[0], 'A'), (first[1], 'B'), (second[0], 'C'), (second[1], 'D')], key=lambda t: t[0])])
	return not (s.find('A') + s.find('B')) % 2
for c in range(t):
	(n, k) = list(map(int, input().split()))
	endpts = [list(map(int, input().split())) for i in range(k)]
	oldpts = set(sum(endpts, []))
	old_count = 0
	for (r, p) in enumerate(endpts):
		for q in endpts[:r]:
			old_count += intersects(p, q)
	old_new = 0
	for (i, j) in endpts:
		dir1 = abs(i - j) - 1 - len(set(range(min(i, j) + 1, max(i, j))).intersection(oldpts))
		dir2 = 2 * n - len(oldpts) - dir1
		old_new += min(dir1, dir2)
	new_count = (n - k) * (n - k - 1) // 2
	print(old_count + old_new + new_count)


import sys
input = sys.stdin.readline

def main():
	(n, k) = map(int, input().split())
	used = set(range(1, 2 * n + 1))
	edges = []
	for _ in range(k):
		(x, y) = map(int, input().split())
		edges.append((x, y))
		used.remove(x)
		used.remove(y)
	lst = list(sorted(used))
	l = len(lst)
	for i in range(l // 2):
		edges.append((lst[i], lst[l // 2 + i]))
	ans = 0
	for i in range(n):
		(r1, l1) = edges[i]
		for j in range(i + 1, n):
			(r2, l2) = edges[j]
			so = sorted([(r1, 1), (l1, 1), (r2, 2), (l2, 2)])
			if so[0][1] == so[2][1]:
				ans += 1
	print(ans)
for _ in range(int(input())):
	main()


t = int(input())
for i in range(t):
	a = []
	(n, k) = map(int, input().split())
	r = list(range(1, 2 * n + 1))
	for j in range(k):
		l = list(map(int, input().split()))
		r.remove(l[0])
		r.remove(l[1])
		a.append(l)
	lr = len(r)
	for j in range(lr // 2):
		a.append([r[j], r[j + lr // 2]])
	for j in range(n):
		a[j].sort()
	it = 0
	for j in range(n):
		for k in range(n):
			if j < k:
				if (a[j][0] < a[k][0] < a[j][1]) + (a[j][0] < a[k][1] < a[j][1]) == 1:
					it += 1
	print(it)


def x_choose_2(x):
	return (x - 1) * x // 2

def does_intersect(chord_1, chord_2):
	between = 0
	(x, y) = sorted([chord_1[0], chord_1[1]])
	if x <= chord_2[0] and y >= chord_2[0]:
		between += 1
	if x <= chord_2[1] and y >= chord_2[1]:
		between += 1
	return between == 1

def solve(n, k, endpoints, on_board):
	to_add = n - k
	total = x_choose_2(to_add)
	unused = []
	for i in range(2 * n):
		if not on_board[i]:
			unused.append(i)
	for i in range(to_add):
		endpoints.append([unused[i], unused[i + to_add], 0])
	for i in range(k):
		for j in range(i + 1, n):
			if does_intersect(endpoints[i], endpoints[j]):
				total += 1
	return total

def main():
	t = int(input())
	for _ in range(t):
		(n, k) = map(int, input().split())
		endpoints = []
		on_board = [0] * 2 * n
		for __ in range(k):
			(x, y) = map(int, input().split())
			x -= 1
			y -= 1
			on_board[x] += 1
			on_board[y] += 1
			endpoints.append([x, y, 1])
		print(solve(n, k, endpoints, on_board))
main()


a = int(input())
for i in range(a):
	(p1, p2) = map(int, input().split())
	par = []
	num = set((i for i in range(1, p1 * 2 + 1)))
	for j in range(p2):
		(k1, k2) = map(int, input().split())
		num.remove(k1)
		num.remove(k2)
		par.append([min(k1, k2), max(k1, k2)])
	num = sorted(list(num))
	maks = 0
	for j in range(len(par)):
		for m in range(j + 1, len(par)):
			if par[j][0] < par[m][0] and par[j][1] > par[m][0] and (par[j][1] < par[m][1]) or (par[j][0] > par[m][0] and par[j][0] < par[m][1] and (par[j][1] > par[m][1])):
				maks += 1
	for j in range(len(num) // 2):
		for ki in par:
			if num[j] < ki[0] and num[j + len(num) // 2] > ki[0] and (num[j + len(num) // 2] < ki[1]) or (num[j] > ki[0] and num[j] < ki[1] and (num[j + len(num) // 2] > ki[1])):
				maks += 1
		par.append([num[j], num[j + len(num) // 2]])
	print(maks)


def intersecting(a, b, n):
	xi = 0
	yi = (a[1] - a[0] + 2 * n) % (2 * n)
	xj = (b[0] - a[0] + 2 * n) % (2 * n)
	yj = (b[1] - a[0] + 2 * n) % (2 * n)
	if xj > yi > yj or xj < yi < yj:
		return True
	else:
		return False

def solve():
	(n, k) = map(int, input().split())
	chords = []
	rem = set()
	for i in range(1, 2 * n + 1):
		rem.add(i)
	for i in range(k):
		(x, y) = map(int, input().split())
		chords.append((x, y))
		rem.remove(x)
		rem.remove(y)
	rem = list(rem)
	lrem = len(rem)
	for i in range(lrem // 2):
		chords.append((rem[i], rem[i + lrem // 2]))
	cnt = 0
	for i in range(n):
		for j in range(i + 1, n):
			if intersecting(chords[i], chords[j], n):
				cnt += 1
	print(cnt)
t = int(input())
for i in range(t):
	solve()


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10 ** 8)
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
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 TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 * 10 ** 9, 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)

class SegmentTree:

	def __init__(self, data, default=-1, 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 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

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

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

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

class TrieNode:

	def __init__(self):
		self.children = [None] * 26
		self.isEndOfWord = False

class Trie:

	def __init__(self):
		self.root = self.getNode()

	def getNode(self):
		return TrieNode()

	def _charToIndex(self, ch):
		return ord(ch) - ord('a')

	def insert(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				pCrawl.children[index] = self.getNode()
			pCrawl = pCrawl.children[index]
		pCrawl.isEndOfWord = True

	def search(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				return False
			pCrawl = pCrawl.children[index]
		return pCrawl != None and pCrawl.isEndOfWord

class Node:

	def __init__(self, data):
		self.data = data
		self.count = 0
		self.left = None
		self.right = None

class BinaryTrie:

	def __init__(self):
		self.root = Node(0)

	def insert(self, pre_xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = pre_xor & 1 << i
			if val:
				if not self.temp.right:
					self.temp.right = Node(0)
				self.temp = self.temp.right
				self.temp.count += 1
			if not val:
				if not self.temp.left:
					self.temp.left = Node(0)
				self.temp = self.temp.left
				self.temp.count += 1
		self.temp.data = pre_xor

	def query(self, xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = xor & 1 << i
			if not val:
				if self.temp.left and self.temp.left.count > 0:
					self.temp = self.temp.left
				elif self.temp.right:
					self.temp = self.temp.right
			elif self.temp.right and self.temp.right.count > 0:
				self.temp = self.temp.right
			elif self.temp.left:
				self.temp = self.temp.left
			self.temp.count -= 1
		return xor ^ self.temp.data
for ik in range(int(input())):
	(n, k) = map(int, input().split())
	s = set([i for i in range(1, 2 * n + 1)])
	q = []
	for i in range(k):
		(a, b) = map(int, input().split())
		s.remove(a)
		s.remove(b)
		q.append((a, b))
	s = sorted(s)

	def find():
		for i in range(n - k):
			q.append((s[i], s[n - k + i]))
		ans = 0
		for i in range(len(q)):
			q[i] = (min(q[i]), max(q[i]))
		q.sort()
		for i in range(len(q)):
			for j in range(i + 1, len(q)):
				if q[i][1] > q[j][0] and q[i][1] < q[j][1]:
					ans += 1
		return ans
	print(find())


def naiveSolve():
	return

def main():
	t = int(input())
	allans = []
	for _ in range(t):
		(n, k) = readIntArr()
		lines = []
		remaining = set(range(1, 2 * n + 1))
		for __ in range(k):
			(x, y) = readIntArr()
			(x, y) = (min(x, y), max(x, y))
			lines.append((x, y))
			remaining.remove(x)
			remaining.remove(y)
		m = len(remaining)
		remaining = sorted(remaining)
		for i in range(m // 2):
			lines.append((remaining[i], remaining[i + m // 2]))

		def crosses(x1, y1, x2, y2):
			return x1 < x2 < y1 < y2 or x2 < x1 < y2 < y1
		ans = 0
		for i in range(n):
			for j in range(i + 1, n):
				(x1, y1) = lines[i]
				(x2, y2) = lines[j]
				if crosses(x1, y1, x2, y2):
					ans += 1
		allans.append(ans)
	multiLineArrayPrint(allans)
	return
import sys
input = sys.stdin.buffer.readline

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]

def makeArr(defaultValFactory, dimensionArr):
	dv = defaultValFactory
	da = dimensionArr
	if len(da) == 1:
		return [dv() for _ in range(da[0])]
	else:
		return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(l, r):
	print('? {} {}'.format(l, r))
	sys.stdout.flush()
	return int(input())

def answerInteractive(x):
	print('! {}'.format(x))
	sys.stdout.flush()
inf = float('inf')
MOD = 10 ** 9 + 7
from math import gcd, floor, ceil
for _abc in range(1):
	main()


def check(a, b):
	if a[0] > b[0]:
		(a, b) = (b, a)
	return a[1] < b[1] and a[1] > b[0]
t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	s = {i for i in range(1, 2 * n + 1)}
	pairs = []
	for i in range(k):
		(a, b) = sorted(map(int, input().split()))
		s.remove(a)
		s.remove(b)
		pairs.append((a, b))
	s = sorted(s)
	m = len(s) >> 1
	(a, b) = (s[:m], s[m:])
	for (x, y) in zip(a, b):
		pairs.append((x, y))
	ans = 0
	for i in range(len(pairs)):
		for j in range(i + 1, len(pairs)):
			ans += check(pairs[i], pairs[j])
	print(ans)


T = int(input())
for t in range(T):
	(n, k) = list(map(int, input().split()))
	chords = []
	for i in range(k):
		chords.append(list(map(int, input().split())))
		chords[i].sort()
	used = [False] * (2 * n + 1)
	for i in range(k):
		used[chords[i][0]] = True
		used[chords[i][1]] = True
	unused = []
	for i in range(1, 2 * n + 1):
		if not used[i]:
			unused.append(i)
	for i in range(n - k):
		chords.append([unused[i], unused[n - k + i]])
	ans = 0
	for i in range(n - 1):
		for j in range(i + 1, n):
			if chords[i][0] < chords[j][0]:
				if chords[j][0] < chords[i][1] < chords[j][1]:
					ans += 1
			elif chords[i][0] < chords[j][1] < chords[i][1]:
				ans += 1
	print(ans)


def side(chord, i, n):
	(a, b) = chord
	(a, b) = (min(a, b), max(a, b))
	if b - a == n and (i < a or i > b):
		return 'Small'
	elif b - a == n and i < a < b:
		return 'Large'
	elif b - a < n and a < i < b:
		return 'Small'
	elif b - a > n and (i > b or i < a):
		return 'Small'
	else:
		return 'Large'

def process(n, chords):
	k = len(chords)
	answer = (n - k) * (n - k - 1) // 2
	answer2 = 0
	for i in range(k):
		(a, b) = chords[i]
		(a, b) = (min(a, b), max(a, b))
		for i2 in range(i):
			(a1, b1) = chords[i2]
			if a1 != a:
				S1 = side([a, b], a1, n)
				S2 = side([a, b], b1, n)
				if abs(b1 - a1) == n and abs(b - a) == n:
					answer2 += 1
				elif S1 != S2:
					answer2 += 1
	S = set([])
	for (a, b) in chords:
		S.add(a)
		S.add(b)
	answer3 = 0
	d = {}
	for i in range(1, 2 * n + 1):
		if i not in S:
			for c in chords:
				if c[0] not in d:
					d[c[0]] = [0, 0]
				if side(c, i, n) == 'Small':
					d[c[0]][0] += 1
				else:
					d[c[0]][1] += 1
	for c in d:
		answer3 += min(d[c][0], d[c][1])
	return answer + answer2 + answer3
t = int(input())
for i in range(t):
	(n, k) = [int(x) for x in input().split()]
	chords = []
	for j in range(k):
		(a, b) = [int(x) for x in input().split()]
		chords.append([a, b])
	print(process(n, chords))


mod = 10 ** 9 + 7

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

def lcm(a, b):
	return a * b // gcd(a, b)

def calc(arr, x, y):
	ret = 0
	for i in range(len(arr)):
		if x < arr[i][0] < y < arr[i][1] or arr[i][0] < x < arr[i][1] < y:
			ret += 1
	return ret

def solve(t_id):
	(n, k) = map(int, input().split())
	used = [False for i in range(2 * n + 1)]
	arr = []
	ans = 0
	cnt = n - k
	brr = []
	for i in range(k):
		(x, y) = map(int, input().split())
		if x > y:
			(x, y) = (y, x)
		arr.append([x, y])
		used[x] = True
		used[y] = True
	for i in range(1, 2 * n + 1):
		if not used[i]:
			brr.append(i)
	for i in range(cnt):
		arr.append([brr[i], brr[i + cnt]])
	for v in arr:
		ans += calc(arr, min(v), max(v))
	print(ans // 2)
t = 1
t = int(input())
for i in range(t):
	solve(i + 1)


import itertools

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

def intersect(pair_of_chords):
	(a, b) = pair_of_chords
	return sum((x < y for x in a for y in b)) & 1

def solve():
	(n, k) = readline()
	chords = [(*readline(),) for __ in range(k)]
	is_free = [True] * (2 * n)
	for point in itertools.chain.from_iterable(chords):
		is_free[point - 1] = False
	free = [i for (i, f) in enumerate(is_free, start=1) if f]
	chords.extend(zip(free, free[n - k:]))
	print(sum(map(intersect, itertools.combinations(chords, 2))))
t = int(input())
for __ in range(t):
	solve()


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	a = []
	for i in range(k):
		a.append([i for i in map(int, input().split())])
	taken_point = []
	remain_point = []
	for i in a:
		taken_point.append(i[0])
		taken_point.append(i[1])
		i.sort()
	for i in range(1, 2 * n + 1):
		if i not in taken_point:
			remain_point.append(i)
	remain_point.sort()
	(i, j) = (0, len(remain_point) // 2)
	for val in range(len(remain_point) // 2):
		a.append([i for i in [remain_point[i], remain_point[j]]])
		i += 1
		j += 1
	count = 0
	for i in range(len(a) - 1):
		for j in range(i + 1, len(a)):
			if a[i][0] in range(a[j][0], a[j][1]) and a[i][1] not in range(a[j][0], a[j][1]):
				count += 1
			elif a[i][1] in range(a[j][0], a[j][1]) and a[i][0] not in range(a[j][0], a[j][1]):
				count += 1
	print(count)


def is_between(min, max, a):
	return min < a < max

def is_cross(pair1, pair2):
	min1 = min(pair1[0], pair1[1])
	max1 = max(pair1[0], pair1[1])
	if is_between(min1, max1, pair2[0]) and (not is_between(min1, max1, pair2[1])):
		return True
	if not is_between(min1, max1, pair2[0]) and is_between(min1, max1, pair2[1]):
		return True
	return False

def solve():
	(n, k) = map(int, input().split())
	hords = []
	used = []
	for _ in range(k):
		(a, b) = map(int, input().split())
		hords.append((a, b))
		used.append(a)
		used.append(b)
	non_used = 2 * (n - k)
	most_far = int(non_used / 2)
	non_used_list = []
	for i in range(1, 2 * n + 1):
		if i in used:
			continue
		non_used_list.append(i)
	for i in range(int(non_used / 2)):
		pair_index = i + most_far
		if pair_index > len(non_used_list) - 1:
			pair_index = pair_index - len(non_used_list)
		new_pair = (non_used_list[i], non_used_list[pair_index])
		hords.append(new_pair)
		used.append(non_used_list[i])
		used.append(non_used_list[pair_index])
	cross = 0
	for i in range(len(hords)):
		for j in range(i + 1, len(hords)):
			if is_cross(hords[i], hords[j]):
				cross += 1
	return cross
for _ in range(int(input())):
	print(solve())


import sys
input = sys.stdin.readline

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

def st():
	return input().rstrip('\n')

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

def ma():
	return map(int, input().split())
t = inp()
while t:
	t -= 1
	(n, k) = ma()
	chords = {}
	intersect = 0
	for i in range(k):
		(u, v) = ma()
		chords[u] = v
		chords[v] = u
		if k:
			left = 0
			right = 0
			(x1, y1) = (min(u, v), max(u, v))
			cur = (x1 - 1) % (2 * n)
			if cur == 0:
				cur = 2 * n
			while cur != y1:
				if cur in chords and chords[cur] > x1 and (chords[cur] < y1):
					intersect += 1
				cur -= 1
				cur = cur % (2 * n)
				if cur == 0:
					cur = 2 * n
	if k == 0:
		chords[n] = 2 * n
		chords[2 * n] = n
	have = []
	for i in range(1, 2 * n + 1):
		if i not in chords:
			have.append(i)
	for i in range(len(have) // 2):
		if 1:
			for j in range(1):
				if 1:
					sof = 0
					ff = have[i + len(have) // 2]
					(x1, y1) = (min(have[i], ff), max(have[i], ff))
					cur = x1
					cur = (cur - 1) % (2 * n)
					if cur == 0:
						cur = 2 * n
					while cur != y1:
						if cur in chords and chords[cur] < y1 and (chords[cur] > x1):
							sof += 1
						cur -= 1
						cur = cur % (2 * n)
						if cur == 0:
							cur = 2 * n
					pos = ff
			chords[pos] = have[i]
			chords[have[i]] = pos
			intersect += sof
	print(intersect)


import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	chords = []
	avai_pts = set(range(2 * n))
	for a in range(k):
		(u, v) = map(int, input().split())
		u -= 1
		v -= 1
		avai_pts.remove(u)
		avai_pts.remove(v)
		chords.append(sorted([u, v]))
	rem_grps = n - k
	avai_pts = sorted(avai_pts)
	p1 = 0
	p2 = rem_grps
	for a in range(rem_grps):
		chords.append(sorted([avai_pts[p1], avai_pts[p2]]))
		p1 += 1
		p2 += 1
	ans = 0
	for ch1 in range(n):
		for ch2 in range(n):
			if ch1 == ch2:
				continue
			if chords[ch1][0] < chords[ch2][0] < chords[ch1][1] < chords[ch2][1]:
				ans += 1
			if chords[ch2][0] < chords[ch1][0] < chords[ch2][1] < chords[ch1][1]:
				ans += 1
	print(ans // 2)


import bisect
import heapq
import math
import collections
import sys
import copy
from functools import reduce
import decimal
from io import BytesIO, IOBase
import os
import itertools
import functools
from types import GeneratorType
sys.setrecursionlimit(10 ** 9)
decimal.getcontext().rounding = decimal.ROUND_HALF_UP
graphDict = collections.defaultdict
queue = collections.deque

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		to = f(*args, **kwargs)
		if stack:
			return to
		else:
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						return to
					to = stack[-1].send(to)
	return wrappedfunc

class Graphs:

	def __init__(self):
		self.graph = graphDict(set)

	def add_edge(self, u, v):
		self.graph[u].add(v)
		self.graph[v].add(u)

	def dfs_utility(self, nodes, visited_nodes, psf):
		global ans
		if len(visited_nodes.keys()) == n:
			ans = psf
			return
		visited_nodes[nodes] = None
		for neighbour in self.graph[nodes]:
			if neighbour not in visited_nodes:
				self.dfs_utility(neighbour, visited_nodes, psf + [neighbour])
		visited_nodes.pop(nodes)
		return

	def dfs(self, node):
		global ans
		Visited = collections.OrderedDict()
		self.dfs_utility(node, Visited, [node])

	def bfs(self, node):
		visited = set()
		if node not in visited:
			queue.append(node)
			visited.add(node)
		while queue:
			parent = queue.popleft()
			print(parent)
			for item in self.graph[parent]:
				if item not in visited:
					queue.append(item)
					visited.add(item)

class Tree:

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

def inorder(node, lis):
	if node:
		inorder(node.left, lis)
		lis.append(node.data)
		inorder(node.right, lis)
	return lis

def leaf_node_sum(root):
	if root is None:
		return 0
	if root.left is None and root.right is None:
		return root.data
	return leaf_node_sum(root.left) + leaf_node_sum(root.right)

def hight(root):
	if root is None:
		return -1
	if root.left is None and root.right is None:
		return 0
	return max(hight(root.left), hight(root.right)) + 1

def rounding(n):
	return int(decimal.Decimal(f'{n}').to_integral_value())

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0), []))

def p_sum(array):
	return list(itertools.accumulate(array))
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, **kwargs):
		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))

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

def map_inp(v_type):
	return map(v_type, inp().split())

def list_inp(v_type):
	return list(map_inp(v_type))
for _ in range(int(inp())):
	(n, k) = map_inp(int)
	paired = []
	all_points = set([item for item in range(1, 2 * n + 1)])
	for i in range(k):
		(a, b) = map_inp(int)
		paired.append([min(a, b), max(a, b)])
		all_points.remove(a)
		all_points.remove(b)
	rem_points = list(sorted(all_points))
	best_rem_pairing = []
	for i in range(len(rem_points) // 2):
		best_rem_pairing.append([rem_points[i], rem_points[len(rem_points) // 2 + i]])
	ans = 0
	temp = best_rem_pairing + paired
	for i in range(len(temp)):
		for j in range(i + 1, len(temp)):
			if temp[i][0] < temp[j][0] < temp[i][1] < temp[j][1] or temp[j][0] < temp[i][0] < temp[j][1] < temp[i][1]:
				ans += 1
	print(ans)


def check(x, y):
	return (y[0] < x[0] < y[1]) != (y[0] < x[1] < y[1])
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	f = [False] * (n * 2 + 1)
	c = []
	for i in range(k):
		(x, y) = map(int, input().split())
		if x > y:
			(x, y) = (y, x)
		c.append((x, y))
		f[x] = True
		f[y] = True
	a = []
	for i in range(1, 2 * n + 1):
		if not f[i]:
			a.append(i)
	k = len(a) // 2
	for i in range(k):
		c.append((a[i], a[i + k]))
	res = 0
	for i in range(n):
		for j in range(i + 1, n):
			if check(c[i], c[j]):
				res += 1
	print(res)


import os
import sys
import time
import math as mt
import itertools as it
import operator as op
import bisect as bs
import heapq as hp
import functools as fn
from collections import deque, defaultdict, OrderedDict, Counter, ChainMap, _chain
(maxx, localsys, mod) = (1 << 60, 0, int(1000000000.0 + 7))

def nCr(n, r):
	return reduce(mul, range(n - r + 1, n + 1), 1) // factorial(r)

def ceil(n, x):
	return (n + x - 1) // x

def lcm(x, y):
	return x * y // mt.gcd(x, y)
(osi, oso) = ('/home/priyanshu/Documents/cp/input.txt', '/home/priyanshu/Documents/cp/output.txt')
if os.path.exists(osi):
	sys.stdin = open(osi, 'r')
	sys.stdout = open(oso, 'w')
input = sys.stdin.readline

def maps():
	return map(int, input().split())
for _ in range(*maps()):
	(n, k) = maps()
	d = {}
	L = []
	for __ in range(k):
		(u, v) = maps()
		if u > v:
			(u, v) = (v, u)
		d[u] = v
		d[v] = u
		L.append((u, v))
	free = []
	for i in range(1, 2 * n + 1):
		if i not in d:
			free.append(i)
	ans = 0
	for i in range(n - k):
		if free[i] < free[i + n - k]:
			L.append((free[i], free[i + n - k]))
	L.sort()
	for i in range(n):
		for j in range(n):
			if L[i][0] < L[j][0] < L[i][1] < L[j][1]:
				ans += 1
	print(ans)


def f(a, b, c, d):
	return min(a, b) < min(c, d) < max(a, b) and max(a, b) < max(c, d) or (max(c, d) > min(a, b) > min(c, d) and max(a, b) > max(c, d))
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	A = []
	B = []
	for i in range(2 * n):
		B.append(False)
	for i in range(m):
		(a, b) = map(int, input().split())
		A.append((a, b))
		B[a - 1] = True
		B[b - 1] = True
	C = []
	for i in range(2 * n):
		if not B[i]:
			C.append(i + 1)
	for i in range(len(C) // 2):
		A.append((C[i], C[i + len(C) // 2]))
	ans = 0
	for i in range(len(A)):
		for j in range(i):
			if f(A[i][0], A[i][1], A[j][0], A[j][1]):
				ans += 1
	print(ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	fill = [True] * 2 * n
	s = []
	for i in range(k):
		(a, b) = map(int, input().split())
		s.append([a - 1, b - 1])
		fill[a - 1] = False
		fill[b - 1] = False
	t = n - k
	ans = t * (t - 1) / 2
	for i in s:
		left = 0
		right = 0
		for j in range(2 * n):
			if fill[j]:
				if j > min(i[0], i[1]) and j < max(i[0], i[1]):
					left += 1
				else:
					right += 1
		ans += min(left, right)
	x = 0
	for i in s:
		for j in s:
			if (i[0] > min(j) and i[0] < max(j)) and (not (i[1] > min(j) and i[1] < max(j))):
				x += 1
			elif (i[1] > min(j) and i[1] < max(j)) and (not (i[0] > min(j) and i[0] < max(j))):
				x += 1
	print(int(ans + x // 2))


from math import *
from decimal import *
from decimal import Decimal as D
from string import ascii_lowercase as lc
from string import ascii_uppercase as uc
from itertools import *
from itertools import permutations as perm
from itertools import product as prod
from sys import *
ip = input
ra = lambda : list(map(int, input().split()))
ri = lambda : int(input())
rd = lambda : map(int, input().split())
MOD = 10 ** 9 + 7
MOD2 = 998244353
maxn = 10 ** 6 + 10
N = 10 ** 5 + 10
N2 = 2 * 10 ** 5
getcontext().prec = 20

def debug(*a):
	stderr.write(' '.join(map(str, a)) + '\n')

def fp(x, p, m):
	r = 1
	while p:
		if p % 2:
			r = r * x % m
			p -= 1
		else:
			x = x * x % m
			p //= 2
	return r

def fact(x, m):
	r = 1
	for i in range(2, x + 1):
		r = r * i % m
	return r

def C(n, k, m):
	return fact(n, m) * fp(fact(n - k, m), m - 2, m) % m * fp(fact(k, m), m - 2, m) % m

class SegmentTree:

	def f(self, a, b):
		return a + b

	def __init__(self, n, a):
		self.tree = [0] * (2 * n)
		self.n = n
		for i in range(n):
			self.tree[n + i] = a[i]
		for i in range(n - 1, 0, -1):
			self.tree[i] = self.f(self.tree[2 * i], self.tree[2 * i + 1])

	def q(self, l, r):
		l += self.n
		r += self.n
		res = 0
		while r > 1:
			if l % 2:
				res = self.f(res, self.tree[l])
				l += 1
			if r % 2:
				r -= 1
				res = self.f(res, self.tree[r])
			r //= 2
			l //= 2
		return res

	def u(self, index, value):
		index += self.n
		self.tree[index] = value
		index //= 2
		while index > 0:
			self.tree[index] = self.f(self.tree[2 * index], self.tree[2 * index + 1])
			index //= 2

def z_function(s):
	(l, r, n) = (0, 0, len(s))
	z = [0] * n
	z[0] = 0
	for i in range(1, n):
		if r >= i:
			z[i] = min(z[i - l], r - i + 1)
		while z[i] + i < n and s[z[i]] == s[z[i] + i]:
			z[i] += 1
		if i + z[i] - 1 > r:
			l = i
			r = l + z[i] - 1
	return z

def pc_pre(a):
	n = len(a)
	r = [0] * (n + 1)
	for i in range(n):
		r[i + 1] = r[i] + a[i]
	return r

def pc_suf(a):
	n = len(a)
	r = [0] * (n + 1)
	for i in range(n - 1, -1, -1):
		r[i] = r[i + 1] + a[i]
	return r

def bsloe(a, v):
	(l, h) = (-1, len(a))
	while h - l > 1:
		m = (h + l) // 2
		if a[m] > v:
			h = m
		else:
			l = m
	return l

def bsh(a, v):
	(l, h) = (-1, len(a))
	while h - l > 1:
		m = (h + l) // 2
		if a[m] > v:
			h = m
		else:
			l = m
	return h

def precalc_fact(n):
	global F
	F = [1] * (n + 1)
	for i in range(2, n + 1):
		F[i] = F[i - 1] * i

def precalc_fact_mod(n, m):
	global F
	F = [1] * (n + 1)
	for i in range(2, n + 1):
		F[i] = F[i - 1] * i % m

def test():
	a = [1, 2, 3]
	s = 'abcabcab'
	assert C(3, 2, 5) == 3
	assert pc_pre(a) == [0, 1, 3, 6]
	assert pc_suf(a) == [6, 5, 3, 0]
	assert z_function(s) == [0, 0, 0, 5, 0, 0, 2, 0]
	assert fp(2, 3, 5) == 3
	assert fact(3, 5) == 1
	t = SegmentTree(3, a)
	assert t.q(1, 3) == t.f(a[1], a[2])
	t.u(0, 5)
	assert t.q(0, 2) == t.f(5, a[1])
	assert bsh(a, 3) == 3
	assert bsloe(a, 3) == 2
	debug('tests passed')
test()

def solve(n, k, f):
	v = [-1] * (2 * n)
	for (a, b) in f:
		v[a] = b
		v[b] = a
	r0 = 0
	for i in range(2 * n):
		if v[i] > i:
			(x, y) = (i, v[i])
			for j in range(x + 1, y):
				if not x < v[j] < y and v[j] != -1:
					r0 += 1
	r0 //= 2
	q = n - k
	r1 = q * (q - 1) // 2
	r2 = 0
	f = [0] * (2 * q)
	j = 0
	for i in range(2 * n):
		if v[i] == -1:
			f[j] = i
			j += 1
	np = []
	for i in range(q):
		(x, y) = (f[i], f[i + q])
		for j in range(x + 1, y):
			if not x < v[j] < y and v[j] != -1:
				r2 += 1
	print(sum([r0, r1, r2]))
(t,) = rd()
for _ in range(t):
	(n, k) = rd()
	f = []
	for i in range(k):
		(a, b) = rd()
		a -= 1
		b -= 1
		f += [[a, b]]
	solve(n, k, f)


t = int(input())
for tt in range(t):
	(n, k) = map(int, input().split())
	chords = []
	vis = [0] * (2 * n)
	for i in range(k):
		chord = list(map(int, input().split()))
		if chord[0] > chord[1]:
			(chord[0], chord[1]) = (chord[1], chord[0])
		chords.append(chord)
		vis[chord[0] - 1] = 1
		vis[chord[1] - 1] = 1
	freepoints = []
	for i in range(2 * n):
		if vis[i] == 0:
			freepoints.append(i + 1)
	for i in range(n - k):
		chord = []
		chord.append(freepoints[i])
		chord.append(freepoints[i + n - k])
		chords.append(chord)
	ans = 0
	for i in range(n):
		for j in range(n):
			if i == j:
				continue
			if chords[i][0] < chords[j][0] and chords[j][0] < chords[i][1] and (chords[i][1] < chords[j][1]):
				ans += 1
	print(ans)


from math import floor, gcd, sqrt, ceil
from collections import Counter, defaultdict
from itertools import combinations
from heapq import heapify, heappop, heappush

def main():
	for _ in range(int(input())):
		(n, k) = map(int, input().split())
		coord = [list(map(int, input().split())) for i in range(k)]
		visited = [False] * (2 * n + 1)
		for (i, j) in coord:
			visited[i] = True
			visited[j] = True
		m = []
		for i in range(1, 2 * n + 1):
			if not visited[i]:
				visited[i] = True
				m.append(i)
		w = len(m) // 2
		for i in range(w):
			coord.append([m[i], m[w + i]])
		ans = 0
		for i in range(len(coord)):
			coord[i].sort()
		a = coord
		for i in range(len(coord)):
			for k in range(len(coord)):
				if i != k:
					if a[i][0] < a[k][0] < a[i][1] and (not a[i][0] < a[k][1] < a[i][1]):
						ans += 1
		print(ans)
main()


for nt in range(int(input())):
	(n, k) = map(int, input().split())
	b = {}
	for i in range(k):
		(x, y) = map(int, input().split())
		b[x] = y
		b[y] = x
	for i in range(1, 2 * n + 1):
		if i in b:
			continue
		o = []
		for j in range(1, 2 * n + 1):
			if i != j and j not in b:
				o.append(j)
		b[i] = o[len(o) // 2]
		b[o[len(o) // 2]] = i
	ans = 0
	for i in range(1, 2 * n + 1):
		for j in range(1, 2 * n + 1):
			if i != j:
				if b[i] > i:
					if j < b[i] and j > i and (b[j] > b[i]):
						ans += 1
				elif j < i and j > b[i] and (b[j] > i):
					ans += 1
	print(ans // 2)


def cross(point, other):
	if point[0] > other[0]:
		(point, other) = (other, point)
	if point[1] < other[0] or point[0] < other[0] < other[1] < point[1]:
		return False
	return True

def main(N, points):
	drawn = set((x for point in points for x in point))
	left = [x for x in range(1, N * 2 + 1) if x not in drawn]
	for i in range(len(left) // 2):
		points += [[left[i], left[i + len(left) // 2]]]
	ret = 0
	for (i, point) in enumerate(points):
		for (j, other) in enumerate(points):
			if i != j and cross(point, other):
				ret += 1
	return ret // 2
for _ in range(int(input())):
	(N, M) = map(int, input().split())
	li = [list(sorted(map(int, input().split()))) for _ in range(M)]
	print(main(N, li))


for _ in range(int(input())):
	(n, k) = map(int, input().split(' '))
	rads = []
	nd = [x for x in range(1, 2 * n + 1)]
	for x in range(k):
		(a, b) = map(int, input().split(' '))
		nd.remove(a)
		nd.remove(b)
		rads.append(sorted([a, b]))
	b = len(nd) // 2
	for x in range(b):
		rads.append([nd[x], nd[x + b]])
	rads.sort(key=lambda x: x[0])
	ct = 0
	for x in range(n):
		for y in range(x + 1, n):
			if rads[y][0] < rads[x][1] and rads[y][1] > rads[x][1]:
				ct += 1
	print(ct)


from itertools import product
from sys import stdin, gettrace
if gettrace():

	def inputi():
		return input()
else:

	def input():
		return next(stdin)[:-1]

	def inputi():
		return stdin.buffer.readline()

def solve():
	(n, k) = map(int, input().split())
	chords = [list(sorted((int(a) for a in input().split()))) for _ in range(k)]
	intersections = (n - k) * (n - k - 1) // 2
	for ((u, v), (w, x)) in product(chords, repeat=2):
		if u < w < v < x:
			intersections += 1
	ep = []
	for (u, v) in chords:
		ep += [u, v]
	for (u, v) in chords:
		intersections += min(v - u - 1 - sum((1 for e in ep if u < e < v)), 2 * n - v + u - 1 - sum((1 for e in ep if not u <= e <= v)))
	print(intersections)

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


import sys
import math
import collections
dy = [1, 0, -1, 0]
dx = [0, 1, 0, -1]
r = sys.stdin.readline
for _ in range(int(r())):
	(N, K) = map(int, r().split())
	L = []
	dic = {}
	for i in range(K):
		(a, b) = map(int, r().split())
		if a > b:
			(a, b) = (b, a)
		L.append([a, b])
		dic[a] = b
		dic[b] = a
	ans = 0
	a = []
	for i in range(1, 2 * N + 1):
		if i not in dic:
			a.append(i)
	for i in range(N - K):
		L.append([a[i], a[i + N - K]])
	L.sort()
	for i in range(N):
		for j in range(N):
			if i == j:
				continue
			if L[i][0] < L[j][0] < L[i][1] < L[j][1]:
				ans += 1
	print(ans)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	xy = []
	for _ in range(k):
		(x, y) = map(int, input().split())
		if x > y:
			(x, y) = (y, x)
		xy.append([x, y])
	s = [0] * (2 * n)
	u = []
	for (x, y) in xy:
		(s[x - 1], s[y - 1]) = (1, 1)
	for i in range(2 * n):
		if not s[i]:
			u.append(i + 1)
	for i in range(n - k):
		xy.append([u[i], u[i + n - k]])
	ans = 0
	for i in range(n):
		(xi, yi) = xy[i]
		for j in range(i + 1, n):
			(xj, yj) = xy[j]
			if xi < xj < yi < yj or xj < xi < yj < yi:
				ans += 1
	print(ans)


PI = 3.141592653589793
INF = float('inf')
MOD = 1000000007

def bin32(num):
	return '{0:032b}'.format(num)

def add(x, y):
	return (x + y) % MOD

def sub(x, y):
	return (x - y + MOD) % MOD

def mul(x, y):
	return x * y % MOD

def gcd(x, y):
	if y == 0:
		return x
	return gcd(y, x % y)

def lcm(x, y):
	return x * y // gcd(x, y)

def power(x, y):
	res = 1
	x %= MOD
	while y != 0:
		if y & 1:
			res = mul(res, x)
		y >>= 1
		x = mul(x, x)
	return res

def mod_inv(n):
	return power(n, MOD - 2)

def prob(p, q):
	return mul(p, power(q, MOD - 2))

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

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

def ls():
	return [i for i in input().split()]
for t in range(ii()):
	t += 1
	(n, k) = li()
	store = [0 for i in range(k)]
	vis = [0 for i in range(2 * n + 2)]
	for i in range(k):
		store[i] = li()
		if store[i][0] > store[i][1]:
			(store[i][0], store[i][1]) = (store[i][1], store[i][0])
		vis[store[i][0]] = 1
		vis[store[i][1]] = 1
	lol = []
	for i in range(1, 2 * n + 1):
		if vis[i] == 0:
			lol.append(i)
	for i in range(n - k):
		store.append([lol[i], lol[i + n - k]])
	store.sort()
	ans = 0
	N = n
	for i in range(N):
		for j in range(i + 1, N):
			if store[i][1] > store[j][0] and store[j][1] > store[i][1]:
				ans += 1
	print(ans)


import random
import math
from collections import defaultdict
import itertools
from sys import stdin, stdout
import sys
import operator
from decimal import Decimal
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 main():
	for _ in range(ii()):
		(n, k) = li()
		ans = (n - k) * (n - k - 1) // 2
		taken = [0] * (2 * n)
		lines = []
		d = defaultdict()
		for i in range(k):
			l = li()
			taken[l[0] - 1] = 1
			taken[l[1] - 1] = 1
			d[l[0]] = l[1]
			d[l[1]] = l[0]
			lines.append(l)
		tmpans = 0
		for line in lines:
			maxi = max(line)
			mini = min(line)
			cntl = 0
			cntu = 0
			takenl = 0
			takenu = 0
			for j in range(mini + 1, maxi):
				if taken[j - 1] == 1:
					if d[j] > maxi or d[j] < mini:
						takenl += 1
				else:
					cntl += 1
			for j in range(maxi + 1, 2 * n):
				if taken[j - 1] == 0:
					cntu += 1
			for j in range(0, mini):
				if taken[j - 1] == 0:
					cntu += 1
			ans += min(cntl, cntu)
			tmpans += takenl
		print(ans + tmpans // 2)
main()


import heapq
import bisect
import math
from collections import defaultdict, Counter
from itertools import permutations

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

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

def get_str():
	return input()

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

def solve_a():
	n = get_int()
	s = list(get_str())
	s_sorted = sorted(s)
	cnt = 0
	for i in range(n):
		if s[i] != s_sorted[i]:
			cnt += 1
	return cnt

def solve_b():
	n = get_int()
	r = [get_ints() for _ in range(n)]

	def beats(i, j):
		cnt = 0
		for x in range(5):
			if r[i][x] < r[j][x]:
				cnt += 1
		return cnt > 2.5
	if n == 1:
		return 1
	else:
		i = 0
		j = 1
		while j < n:
			if beats(i, j):
				j += 1
			else:
				i = j
				j += 1
		for k in range(i):
			if beats(k, i):
				return -1
		return i + 1

def solve_c():
	(n, k) = get_ints()
	avails = set([i for i in range(1, 2 * n + 1)])
	cons = []
	for _ in range(k):
		(x, y) = get_ints()
		avails.remove(x)
		avails.remove(y)
		cons.append((x, y))
	avails = sorted(list(avails))

	def cross(a, b):
		return (min(a) < b[0] < max(a)) ^ (min(a) < b[1] < max(a))
	for i in range(n - k):
		cons.append((avails[i], avails[n - k + i]))
	cnt = 0
	for a in cons:
		for b in cons:
			if a != b and cross(a, b):
				cnt += 1
	return cnt // 2

def solve_d():
	n = get_int()
	a = get_ints()
	a = [abs(x) for x in a]
	C = Counter(a)
	if len(C) <= n - 1:
		return 'YES'
t = get_int()
for _ in range(t):
	print(solve_c())


import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for _ in range(int(input())):
	(n, k) = [int(i) for i in input().split()]
	a = []
	done = []
	cnt = 0
	for j in range(k):
		(u, v) = [int(i) for i in input().split()]
		(u, v) = (min(u, v), max(u, v))
		done.append(u)
		done.append(v)
		for i in a:
			if i[0] > u and i[1] > v and (i[0] < v):
				cnt += 1
			elif i[0] < u and i[1] < v and (u < i[1]):
				cnt += 1
		a.append([u, v])
	vis = [0] * (2 * n + 1)
	for i in done:
		vis[i] = 1
	rem = []
	for i in range(1, 2 * n + 1):
		if not vis[i]:
			rem.append(i)
	rem.sort()
	mid = len(rem) // 2
	pairs = []
	for i in range(mid):
		pairs.append([rem[i], rem[mid + i]])
	for j in pairs:
		(u, v) = j[:]
		for i in a:
			if i[0] > u and i[1] > v and (i[0] < v):
				cnt += 1
			elif i[0] < u and i[1] < v and (u < i[1]):
				cnt += 1
		a.append([u, v])
	print(cnt)


def intersect(a, b):
	a.sort()
	if (b[0] < a[1] and b[0] > a[0]) and (not (b[1] < a[1] and b[1] > a[0])) or ((b[1] < a[1] and b[1] > a[0]) and (not (b[0] < a[1] and b[0] > a[0]))):
		return True
	else:
		return False
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	intersections = []
	S = set()
	for i in range(k):
		l = [int(x) for x in input().split()]
		S.add(l[1])
		S.add(l[0])
		intersections.append(l)
	count = 0
	ch = False
	zoz = 0
	poc = 0
	while len(S) < 2 * n:
		if count + 1 not in S:
			if not ch:
				ch = True
				zoz = count + 1
			else:
				poc += 1
				if poc == (2 * n - len(S)) // 2:
					ch = False
					poc = 0
					S.add(zoz)
					S.add(count + 1)
					intersections.append([zoz, count + 1])
		count += 1
		count %= 2 * n
	res = 0
	for i in range(n):
		for j in range(i + 1, n):
			if intersect(intersections[i], intersections[j]):
				res += 1
	print(res)


import sys
input = sys.stdin.readline
t = int(input())
for tests in range(t):
	(n, k) = map(int, input().split())
	XY = [tuple(map(int, input().split())) for i in range(k)]
	USE = [0] * (2 * n + 1)
	for (x, y) in XY:
		USE[x] = 1
		USE[y] = 1
	XX = []
	for i in range(1, 2 * n + 1):
		if USE[i] == 0:
			XX.append(i)
	LEN = len(XX)
	for i in range(LEN // 2):
		XY.append((XX[i], XX[i + LEN // 2]))
	ANS = 0
	for i in range(len(XY)):
		(k, l) = XY[i]
		if k > l:
			(k, l) = (l, k)
		for j in range(i + 1, len(XY)):
			(u, v) = XY[j]
			if k < u < l and k < v < l:
				True
			elif k < u < l or k < v < l:
				ANS += 1
	print(ANS)


import sys
import math
from math import *
import builtins
import collections
import bisect
import os
from io import BytesIO, IOBase

def print(x, end='\n'):
	sys.stdout.write(str(x) + end)

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

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

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

def get_tuple_ints():
	return tuple(map(int, input().split()))

def print_iterable(p):
	print(' '.join(map(str, p)))

def CountFrequency(arr):
	return collections.Counter(arr)

def reverse(s):
	l = len(s)
	for i in range(l // 2):
		(s[i], s[l - i - 1]) = (s[l - i - 1], s[i])
	return s

def binary_search(arr, x):
	low = 0
	high = len(arr) - 1
	mid = 0
	while low <= high:
		mid = (high + low) // 2
		if arr[mid] < x:
			low = mid + 1
		elif arr[mid] > x:
			high = mid - 1
		else:
			return mid
	return high

def lower_bound(arr, x):
	return bisect.bisect_left(arr, x, lo=0, hi=len(arr))

def upper_bound(arr, x):
	return bisect.bisect_right(arr, x, lo=0, hi=len(arr))

def pow(a, n):
	if n == 0:
		return 1
	elif n % 2 == 0:
		return pow(a, n // 2) % const * (pow(a, n // 2) % const) % const
	else:
		return pow(a, n // 2) % const * (pow(a, n // 2) % const) * (a % const) % const

def count1(list):
	count = 0
	for i in list:
		if i == 0:
			count += 1
	return count

def apt(a, b, c, d):
	a1 = max(a, b)
	a2 = min(a, b)
	if c > a2 and c < a1 and (d < a2 or d > a1):
		return True
	elif d > a2 and d < a1 and (c < a2 or c > a1):
		return True
	else:
		return False

def main():
	n = get_int()
	for i in range(n):
		[p, k] = get_list_ints()
		val = p - k
		ans = val * (val - 1) // 2
		list = [0 for i in range(2 * p)]
		pointl = []
		for i in range(k):
			[x, y] = get_list_ints()
			list[x - 1] = 1
			list[y - 1] = 1
			pointl.append((x, y))
		for (x, y) in pointl:
			x1 = min(x, y)
			y1 = max(x, y)
			ans += min(count1(list[x1:y1 - 1]), count1(list[:x1 - 1] + list[y1:]))
		l = len(pointl)
		initial = 0
		for i in range(l - 1):
			for j in range(i + 1, l):
				if apt(pointl[i][0], pointl[i][1], pointl[j][0], pointl[j][1]) == True:
					initial += 1
		print(ans + initial)
	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')
main()


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def solve():
	(n, k) = map(int, input().split())
	free = set(range(2 * n))
	edges = []
	for _ in range(k):
		(x, y) = map(int, input().split())
		x -= 1
		y -= 1
		free.remove(x)
		free.remove(y)
		if x > y:
			(x, y) = (y, x)
		edges.append((x, y))
	free = sorted(free)
	for i in range(len(free) // 2):
		edges.append((free[i], free[len(free) // 2 + i]))
	count = 0
	for (x1, y1) in edges:
		for (x2, y2) in edges:
			if x1 >= x2:
				continue
			if x1 < x2 < y1 and (not x1 < y2 < y1):
				count += 1
			elif x2 < x1 < y2 and (not x2 < y1 < y2):
				count += 1
	print(count)
t = int(input())
for _ in range(t):
	solve()


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

def input():
	return sys.stdin.readline()[:-1]
INF = 10 ** 10

def dfs(N, L, T, l):
	score_max = -INF
	r_list = []
	for r in range(l + 1, 2 * N):
		if T[r]:
			continue
		sc = 0
		for (l1, r1) in L:
			if l < l1 < r < r1 or l1 < l < r1 < r:
				sc += 1
		if score_max < sc:
			score_max = sc
			r_list = [r]
		elif score_max == sc:
			r_list.append(r)
	T[l] = True
	score = 0
	for r in r_list:
		T[r] = True
		for l1 in range(l + 1, 2 * N):
			if T[l1]:
				continue
			T[l1] = True
			L.append((l, r))
			sc = dfs(N, L, T, l1)
			T[l1] = False
			L.pop()
			score = max(score, sc)
			break
		T[r] = False
	return score + score_max

def solve(N, K, L):
	T = [False] * (2 * N)
	for (l, r) in L:
		T[l] = True
		T[r] = True
	Pos = [x for x in range(2 * N) if not T[x]]
	for i in range(N - K):
		l = Pos[i]
		r = Pos[N - K + i]
		L.append((l, r))
	score0 = 0
	for i in range(N - 1):
		(l1, r1) = L[i]
		T[l1] = True
		T[r1] = True
		for j in range(i + 1, N):
			(l2, r2) = L[j]
			if l1 < l2 < r1 < r2 or l2 < l1 < r2 < r1:
				score0 += 1
	return score0
T0 = int(input())
for _ in range(T0):
	(N, K) = map(int, input().split())
	L = []
	for _ in range(K):
		(x, y) = map(int, input().split())
		x -= 1
		y -= 1
		if x > y:
			(x, y) = (y, x)
		L.append((x, y))
	print(solve(N, K, L))


import itertools

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

def intersect(first, second):
	return sum((x < y for x in first for y in second)) & 1

def solve():
	(n, k) = readline()
	chords = [tuple(readline()) for __ in range(k)]
	total = 2 * n
	l = n - k
	is_free = [True] * total
	for (a, b) in chords:
		is_free[a - 1] = is_free[b - 1] = False
	free = [i for (i, f) in enumerate(is_free, start=1) if f]
	assert len(free) == 2 * l
	chords.extend(zip(free, free[l:]))
	print(sum((intersect(a, b) for (a, b) in itertools.combinations(chords, 2))))
t = int(input())
for __ in range(t):
	solve()


def intersect(l1, l2):
	l1.sort()
	l2.sort()
	if (l2[0] < l1[0] or l2[0] > l1[1]) and l2[1] < l1[1] and (l2[1] > l1[0]):
		return True
	if (l2[1] < l1[0] or l2[1] > l1[1]) and l2[0] < l1[1] and (l2[0] > l1[0]):
		return True
	return False
t = int(input())
for _ in range(t):
	(n, k) = [int(i) for i in input().split(' ')]
	lis = []
	rec = []
	for i in range(k):
		p = [int(j) for j in input().split()]
		p.sort()
		lis += [p]
		rec += p
	pts = [i + 1 for i in range(2 * n)]
	rem = [i for i in pts if i not in rec]
	l = len(rem) // 2
	rem2 = [[rem[i], rem[(i + l) % (2 * l)]] for i in range(l)]
	lis += rem2
	lis.sort()
	ans = 0
	for w1 in lis:
		for e1 in lis:
			if w1[0] == e1[0]:
				continue
			if intersect(w1, e1):
				ans += 1
	print(ans // 2)


t = int(input())
for tt in range(t):
	(n, k) = map(int, input().split())
	start = []
	end = []
	done = [0] * (2 * n)
	for i in range(k):
		(a, b) = map(int, input().split())
		a -= 1
		b -= 1
		start.append(min(a, b))
		end.append(max(a, b))
		(done[a], done[b]) = (1, 1)
	todo = []
	for i in range(2 * n):
		if not done[i]:
			todo.append(i)
	left = len(todo)
	for i in range(left // 2):
		start.append(todo[i])
		end.append(todo[i + left // 2])
	ans = 0
	for i in range(n):
		for j in range(i + 1, n):
			a1 = start[i]
			a2 = start[j]
			b1 = end[i]
			b2 = end[j]
			if start[i] > start[j]:
				(a1, a2) = (a2, a1)
				(b1, b2) = (b2, b1)
			ans += int(a1 < a2 and a2 < b1 and (b1 < b2))
	print(ans)


import sys
input = sys.stdin.readline

def solve():
	(n, k) = map(int, input().split())
	points = []
	missed = [i + 1 for i in range(n * 2)]
	for _ in range(k):
		(x, y) = map(int, input().split())
		start = min(x, y)
		end = max(x, y)
		points.append([start, end])
		missed.remove(start)
		missed.remove(end)
	m_len = len(missed)
	for i in range(m_len // 2):
		points.append([missed[i], missed[i + m_len // 2]])
	count = 0
	points = sorted(points, key=lambda x: x[0])
	starts = [point[0] for point in points]
	ends = [point[1] for point in points]
	for i in range(n):
		for j in range(n):
			if i == j:
				continue
			if points[i][0] < points[j][0] and points[j][0] < points[i][1] and (points[i][1] < points[j][1]):
				count += 1
	print(count)
for _ in range(int(input())):
	solve()


for _ in range(int(input())):
	(n_chords, n_drawn) = [int(a) for a in input().split(' ')]
	if n_drawn == 0:
		print(n_chords * (n_chords - 1) // 2)
		continue
	if n_chords == 1:
		print(0)
		input()
		continue
	points_remaining = {i + 1 for i in range(n_chords * 2)}
	intersections = 0
	structure = []

	def num_intersects(p0, p1):
		return sum([int((p0 - a0) * (p0 - a1) * (p1 - a0) * (p1 - a1) < 0) for (a0, a1) in structure])
	for i in range(n_drawn):
		(p0, p1) = [int(j) for j in input().split(' ')]
		if p0 > p1:
			(p0, p1) = (p1, p0)
		intersections += num_intersects(p0, p1)
		structure.append([p0, p1])
		points_remaining.remove(p0)
		points_remaining.remove(p1)
	points_remaining = sorted(points_remaining)
	lpr = len(points_remaining) // 2
	for (p0, p1) in zip(points_remaining[:lpr], points_remaining[lpr:]):
		intersections += num_intersects(p0, p1)
		structure.append([p0, p1])
	print(intersections)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	l = [0] * (2 * n)
	v = []
	e = []
	for i in range(k):
		(a, b) = map(int, input().split())
		l[a - 1] = 1
		l[b - 1] = 1
		e.append(sorted([a - 1, b - 1]))
	for i in range(2 * n):
		if l[i] == 0:
			v.append(i)
	x = n - k
	for i in range(x):
		e.append([v[i], v[i + x]])
	ans = 0
	for i in range(n):
		for j in range(n):
			if i == n:
				continue
			c = 0
			if e[i][0] < e[j][0] and e[i][1] > e[j][0]:
				c += 1
			if e[i][0] < e[j][1] and e[i][1] > e[j][1]:
				c += 1
			if c == 1:
				ans += 1
	print(ans // 2)