There is a city that can be represented as a square grid with corner points in $(0, 0)$ and $(10^6, 10^6)$.

The city has $n$ vertical and $m$ horizontal streets that goes across the whole city, i. e. the $i$-th vertical streets goes from $(x_i, 0)$ to $(x_i, 10^6)$ and the $j$-th horizontal street goes from $(0, y_j)$ to $(10^6, y_j)$.

All streets are bidirectional. Borders of the city are streets as well.

There are $k$ persons staying on the streets: the $p$-th person at point $(x_p, y_p)$ (so either $x_p$ equal to some $x_i$ or $y_p$ equal to some $y_j$, or both).

Let's say that a pair of persons form an inconvenient pair if the shortest path from one person to another going only by streets is strictly greater than the Manhattan distance between them.

Calculate the number of inconvenient pairs of persons (pairs $(x, y)$ and $(y, x)$ are the same pair).

Let's recall that Manhattan distance between points $(x_1, y_1)$ and $(x_2, y_2)$ is $|x_1 - x_2| + |y_1 - y_2|$.


-----Input-----

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

The first line of each test case contains three integers $n$, $m$ and $k$ ($2 \le n, m \le 2 \cdot 10^5$; $2 \le k \le 3 \cdot 10^5$) — the number of vertical and horizontal streets and the number of persons.

The second line of each test case contains $n$ integers $x_1, x_2, \dots, x_n$ ($0 = x_1 < x_2 < \dots < x_{n - 1} < x_n = 10^6$) — the $x$-coordinates of vertical streets.

The third line contains $m$ integers $y_1, y_2, \dots, y_m$ ($0 = y_1 < y_2 < \dots < y_{m - 1} < y_m = 10^6$) — the $y$-coordinates of horizontal streets.

Next $k$ lines contains description of people. The $p$-th line contains two integers $x_p$ and $y_p$ ($0 \le x_p, y_p \le 10^6$; $x_p \in \{x_1, \dots, x_n\}$ or $y_p \in \{y_1, \dots, y_m\}$) — the coordinates of the $p$-th person. All points are distinct.

It guaranteed that sum of $n$ doesn't exceed $2 \cdot 10^5$, sum of $m$ doesn't exceed $2 \cdot 10^5$ and sum of $k$ doesn't exceed $3 \cdot 10^5$.


-----Output-----

For each test case, print the number of inconvenient pairs.


-----Examples-----

Input
2
2 2 4
0 1000000
0 1000000
1 0
1000000 1
999999 1000000
0 999999
5 4 9
0 1 2 6 1000000
0 4 8 1000000
4 4
2 5
2 2
6 3
1000000 1
3 8
5 8
8 8
6 8
Output
2
5


-----Note-----

The second test case is pictured below:

For example, points $3$ and $4$ form an inconvenient pair, since the shortest path between them (shown red and equal to $7$) is greater than its Manhattan distance (equal to $5$).

Points $3$ and $5$ also form an inconvenient pair: the shortest path equal to $1000001$ (shown green) is greater than the Manhattan distance equal to $999999$.

But points $5$ and $9$ don't form an inconvenient pair, since the shortest path (shown purple) is equal to its Manhattan distance.

Difficulty: HARD

Solutions:
from bisect import bisect_left
from sys import stdin

def solve():
	(n, m, k) = map(int, stdin.readline().split())
	verti_line = list(map(int, stdin.readline().split()))
	hori_line = list(map(int, stdin.readline().split()))
	verti = []
	hori = []
	for _ in range(k):
		(x, y) = map(int, stdin.readline().split())
		idx1 = bisect_left(verti_line, x)
		idx2 = bisect_left(hori_line, y)
		if verti_line[idx1] == x and hori_line[idx2] == y:
			continue
		elif verti_line[idx1] == x:
			verti.append((idx2, x))
		else:
			hori.append((idx1, y))
	verti = list(sorted(verti))
	hori = list(sorted(hori))
	ans = 0
	j = 0
	for i in range(1, m + 1):
		if j == len(verti):
			break
		count = 0
		temp = []
		curr_bar = -1
		while j < len(verti) and verti[j][0] == i:
			bar = verti[j][1]
			count += 1
			j += 1
			if bar == curr_bar:
				temp[-1] += 1
			else:
				curr_bar = bar
				temp.append(1)
		ans += count * (count - 1) // 2
		for x in temp:
			ans -= x * (x - 1) // 2
	j = 0
	for i in range(1, n + 1):
		if j == len(hori):
			break
		count = 0
		temp = []
		curr_bar = -1
		while j < len(hori) and hori[j][0] == i:
			bar = hori[j][1]
			count += 1
			j += 1
			if bar == curr_bar:
				temp[-1] += 1
			else:
				curr_bar = bar
				temp.append(1)
		ans += count * (count - 1) // 2
		for x in temp:
			ans -= x * (x - 1) // 2
	print(ans)
t = int(stdin.readline().strip())
for _ in range(t):
	solve()


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

class SortedList:

	def __init__(self, iterable=[], _load=200):
		values = sorted(iterable)
		self._len = _len = len(values)
		self._load = _load
		self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
		self._list_lens = [len(_list) for _list in _lists]
		self._mins = [_list[0] for _list in _lists]
		self._fen_tree = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for i in range(len(_fen_tree)):
			if i | i + 1 < len(_fen_tree):
				_fen_tree[i | i + 1] += _fen_tree[i]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len -= 1
		self._fen_update(pos, -1)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len += 1
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				_lists.insert(pos + 1, _list[_load:])
				_list_lens.insert(pos + 1, len(_list) - _load)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = _load
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))
from bisect import bisect_left, bisect_right

class Result:

	def __init__(self, index, value):
		self.index = index
		self.value = value

class BinarySearch:

	def __init__(self):
		pass

	@staticmethod
	def greater_than(num: int, func, size: int=1):
		if isinstance(func, list):
			index = bisect_right(func, num)
			if index == len(func):
				return Result(None, None)
			else:
				return Result(index, func[index])
		else:
			(alpha, omega) = (0, size - 1)
			if func(omega) <= num:
				return Result(None, None)
			while alpha < omega:
				if func(alpha) > num:
					return Result(alpha, func(alpha))
				if omega == alpha + 1:
					return Result(omega, func(omega))
				mid = (alpha + omega) // 2
				if func(mid) > num:
					omega = mid
				else:
					alpha = mid

	@staticmethod
	def less_than(num: int, func, size: int=1):
		if isinstance(func, list):
			index = bisect_left(func, num) - 1
			if index == -1:
				return Result(None, None)
			else:
				return Result(index, func[index])
		else:
			(alpha, omega) = (0, size - 1)
			if func(alpha) >= num:
				return Result(None, None)
			while alpha < omega:
				if func(omega) < num:
					return Result(omega, func(omega))
				if omega == alpha + 1:
					return Result(alpha, func(alpha))
				mid = (alpha + omega) // 2
				if func(mid) < num:
					alpha = mid
				else:
					omega = mid
bs = BinarySearch()
for _ in range(int(input()) if True else 1):
	(n, m, k) = map(int, input().split())
	xco = sorted(list(map(int, input().split())))
	yco = sorted(list(map(int, input().split())))
	(xc, yc) = (set(xco), set(yco))
	persons = []
	ypo = []
	xpo = []
	ypod = {}
	xpod = {}
	for i in range(k):
		(x, y) = map(int, input().split())
		if x in xc and y in yc:
			continue
		persons += [(x, y)]
		if x in xc:
			ypo += [y]
			if x not in ypod:
				ypod[x] = []
			ypod[x] += [y]
		else:
			if y not in xpod:
				xpod[y] = []
			xpod[y] += [x]
			xpo += [x]
	ans = 0
	xpo = sorted(xpo)
	ypo = sorted(ypo)
	for x in xpod:
		xpod[x] = sorted(xpod[x])
	for y in ypod:
		ypod[y] = sorted(ypod[y])
	for (x, y) in persons:
		if x in xc:
			yh = bs.greater_than(y - 1, yco).value
			yl = bs.less_than(y + 1, yco).value
			c1 = bs.greater_than(yl, ypo).index
			c2 = bs.less_than(yh, ypo).index
			if c1 is None or c2 is None:
				continue
			ans += c2 - c1 + 1
			c1 = bs.greater_than(yl, ypod[x]).index
			c2 = bs.less_than(yh, ypod[x]).index
			if c1 is None or c2 is None:
				continue
			ans -= c2 - c1 + 1
		else:
			xh = bs.greater_than(x - 1, xco).value
			xl = bs.less_than(x + 1, xco).value
			c1 = bs.greater_than(xl, xpo).index
			c2 = bs.less_than(xh, xpo).index
			if c1 is None or c2 is None:
				continue
			ans += c2 - c1 + 1
			c1 = bs.greater_than(xl, xpod[y]).index
			c2 = bs.less_than(xh, xpod[y]).index
			if c1 is None or c2 is None:
				continue
			ans -= c2 - c1 + 1
	print(ans // 2)


def naiveSolve():
	return

def solve():
	return

class SegmentTree:

	def __init__(self, arr, combinerFunction, isCommutative=True):
		self.n = len(arr)

		def cmb(a, b):
			if a == None:
				return b
			if b == None:
				return a
			return combinerFunction(a, b)
		self.cmb = cmb
		self.sz = self.n if isCommutative else pow(2, (self.n - 1).bit_length())
		self.t = [None] * (2 * self.sz)
		for i in range(self.n):
			self.t[i + self.sz] = arr[i]
		for i in range(self.sz - 1, 0, -1):
			self.pull(i)

	def pull(self, p):
		self.t[p] = self.cmb(self.t[2 * p], self.t[2 * p + 1])

	def update(self, idx, val):
		idx += self.sz
		self.t[idx] = val
		idx //= 2
		while idx > 0:
			self.pull(idx)
			idx //= 2

	def query(self, l, r):
		l += self.sz
		r += self.sz + 1
		a = b = None
		while l < r:
			if l % 2 == 1:
				a = self.cmb(a, self.t[l])
				l += 1
			if r % 2 == 1:
				r -= 1
				b = self.cmb(self.t[r], b)
			l //= 2
			r //= 2
		return self.cmb(a, b)

def getMaxSegTree(arr):
	return SegmentTree(arr, lambda a, b: max(a, b), False)

def getMinSegTree(arr):
	return SegmentTree(arr, lambda a, b: min(a, b), False)

def getSumSegTree(arr):
	return SegmentTree(arr, lambda a, b: a + b, False)
from collections import defaultdict

def countHorizontal(xes, onX):
	xSet = set(xes)
	for (x, y) in onX:
		xSet.add(x)
	xSorted = sorted(xSet)
	N = len(xSorted)
	xMap = {x: i for (i, x) in enumerate(xSorted)}
	for (i, x) in enumerate(xes):
		xes[i] = xMap[x]
	for (i, [x, y]) in enumerate(onX):
		onX[i][0] = xMap[x]
	yItems = defaultdict(list)
	for (x, y) in onX:
		yItems[y].append(x)
	for v in yItems.values():
		v.sort()
	segArr = [0] * (N + 1)
	for (x, y) in onX:
		segArr[x] += 1
	st = getSumSegTree(segArr)
	cnts = 0
	for (x, y) in onX:
		i = -1
		bb = len(xes)
		while bb > 0:
			while i + bb < len(xes) and xes[i + bb] < x:
				i += bb
			bb //= 2
		left = xes[i] + 1
		right = xes[i + 1] - 1
		include = st.query(left, right)
		arr = yItems[y]
		i = -1
		bb = len(arr)
		while bb > 0:
			while i + bb < len(arr) and arr[i + bb] < left:
				i += bb
			bb //= 2
		left2 = i + 1
		i = -1
		bb = len(arr)
		while bb > 0:
			while i + bb < len(arr) and arr[i + bb] <= right:
				i += bb
			bb //= 2
		right2 = i
		exclude = right2 - left2 + 1
		cnts += include - exclude
	return cnts

def main():
	t = int(input())
	allans = []
	for _ in range(t):
		(n, m, k) = readIntArr()
		xes = [-1] + readIntArr() + [1000001]
		yes = [-1] + readIntArr() + [1000001]
		xSet = set(xes)
		ySet = set(yes)
		onX = []
		onY = []
		onXandY = []
		for __ in range(k):
			(x, y) = readIntArr()
			isOnX = x in xSet
			isOnY = y in ySet
			if isOnX and isOnY:
				onXandY.append((x, y))
			elif isOnX and (not isOnY):
				onX.append([x, y])
			else:
				onY.append([x, y])
		xN = len(onX)
		yN = len(onY)
		xyN = len(onXandY)
		assert xN + yN + xyN == k
		ans = 0
		ans += countHorizontal(xes, onY)
		onX2 = [[y, x] for (x, y) in onX]
		ans += countHorizontal(yes, onX2)
		ans //= 2
		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(x):
	print('{}'.format(x))
	sys.stdout.flush()
	return int(input())

def answerInteractive(ans):
	print('! {}'.format(ans))
	sys.stdout.flush()
inf = float('inf')
from math import gcd, floor, ceil
for _abc in range(1):
	main()


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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import defaultdict
from bisect import bisect_left, bisect_right
for _ in range(int(input())):
	(n, m, k) = map(int, input().split())
	x = [*map(int, input().split())]
	y = [*map(int, input().split())]
	sx = set(x)
	sy = set(y)
	nx = []
	ny = []
	dx = defaultdict(list)
	dy = defaultdict(list)
	for i in range(k):
		(a, b) = map(int, input().split())
		if a in sx and b in sy:
			continue
		elif a in sx:
			nx.append(b)
			dx[a].append(b)
		else:
			ny.append(a)
			dy[b].append(a)
	for key in dx:
		dx[key].sort()
	for key in dy:
		dy[key].sort()
	nx.sort()
	ny.sort()
	x.sort()
	y.sort()
	ans = 0
	for xcor in dx:
		for ycor in dx[xcor]:
			upper_street = 10 ** 7
			upper_street_index = bisect_right(y, ycor)
			if upper_street_index != len(y):
				upper_street = y[upper_street_index]
			lower_street_index = upper_street_index - 1
			lower_street = -1
			if lower_street_index != -1:
				lower_street = y[lower_street_index]
			total_cities_between = bisect_right(nx, upper_street) - bisect_right(nx, lower_street)
			total_cities_between_same_street = bisect_right(dx[xcor], upper_street) - bisect_right(dx[xcor], lower_street)
			ans += total_cities_between - total_cities_between_same_street
	for ycor in dy:
		for xcor in dy[ycor]:
			upper_street = 10 ** 7
			upper_street_index = bisect_right(x, xcor)
			if upper_street_index != len(x):
				upper_street = x[upper_street_index]
			lower_street_index = upper_street_index - 1
			lower_street = -1
			if lower_street_index != -1:
				lower_street = x[lower_street_index]
			total_cities_between = bisect_right(ny, upper_street) - bisect_right(ny, lower_street)
			total_cities_between_same_street = bisect_right(dy[ycor], upper_street) - bisect_right(dy[ycor], lower_street)
			ans += total_cities_between - total_cities_between_same_street
	print(ans // 2)


import sys, collections, bisect
for _ in range(int(sys.stdin.readline())):
	(n, m, k) = [int(i) for i in sys.stdin.readline().split()]
	x = [int(i) for i in sys.stdin.readline().split()]
	y = [int(i) for i in sys.stdin.readline().split()]
	(sx, sy) = (set(x), set(y))
	px = collections.defaultdict(lambda : collections.defaultdict(int))
	py = collections.defaultdict(lambda : collections.defaultdict(int))
	for i in range(k):
		(a, b) = [int(i) for i in sys.stdin.readline().split()]
		if not (a in sx and b in sy):
			if a in sx:
				px[bisect.bisect(y, b)][a] += 1
			else:
				py[bisect.bisect(x, a)][b] += 1
	r = sum((sum(dd.values()) ** 2 - sum((x * x for x in dd.values())) for dd in px.values())) + sum((sum(dd.values()) ** 2 - sum((x * x for x in dd.values())) for dd in py.values()))
	sys.stdout.write(str(r // 2) + '\n')


import os
import sys
import math
import collections
import functools
import itertools
import heapq
import bisect
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
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')
ALPHA = 'abcde'
MOD = 10 ** 9 + 7
EPS = 1e-06
INF = 10 ** 18

def Ceil(a, b):
	return a // b + int(a % b > 0)

def INT():
	return int(input())

def STR():
	return input()

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

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

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

def solve(n, m, k, X, Y, P):
	X_set = set(X)
	Y_set = set(Y)
	X_dp = {}
	Y_dp = {}
	for (x, y) in P:
		if x in X_set and y in Y_set:
			continue
		if x in X_set:
			idx = bisect.bisect(Y, y)
			if idx not in X_dp:
				X_dp[idx] = {}
				X_dp[idx]['t'] = 0
			if x not in X_dp[idx]:
				X_dp[idx][x] = 1
			else:
				X_dp[idx][x] += 1
			X_dp[idx]['t'] += 1
		else:
			idx = bisect.bisect(X, x)
			if idx not in Y_dp:
				Y_dp[idx] = {}
				Y_dp[idx]['t'] = 0
			if y not in Y_dp[idx]:
				Y_dp[idx][y] = 1
			else:
				Y_dp[idx][y] += 1
			Y_dp[idx]['t'] += 1
	res = 0
	for d in X_dp.values():
		total = d['t']
		for (k, v) in d.items():
			if k == 't':
				continue
			res += v * (total - v)
	for d in Y_dp.values():
		total = d['t']
		for (k, v) in d.items():
			if k == 't':
				continue
			res += v * (total - v)
	print(res // 2)
for t in range(INT()):
	(n, m, k) = INTS()
	X = ARRINT()
	Y = ARRINT()
	P = [INTS() for _ in range(k)]
	solve(n, m, k, X, Y, P)


from collections import defaultdict
import bisect
import sys
input = sys.stdin.readline

def f(a):
	return a * (a - 1) // 2
t = int(input())
for _ in range(t):
	(n, m, k) = map(int, input().split())
	nm = max(n, m)
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	dx = dict()
	dy = dict()
	for i in range(n):
		dx[x[i]] = i
	for i in range(m):
		dy[y[i]] = i
	(xx, yy) = (set(x), set(y))
	x0 = [defaultdict(lambda : 0) for _ in range(m + 5)]
	y0 = [defaultdict(lambda : 0) for _ in range(n + 5)]
	for _ in range(k):
		(xp, yp) = map(int, input().split())
		if xp in xx and yp in yy:
			continue
		if xp in xx:
			i = bisect.bisect_left(y, yp) - 1
			x0[i][dx[xp]] += 1
		else:
			i = bisect.bisect_left(x, xp) - 1
			y0[i][dy[yp]] += 1
	ans = 0
	for x1 in x0:
		if x1:
			(u, v) = (0, 0)
			for i in x1.values():
				u += i
				v += f(i)
			ans += f(u) - v
	for y1 in y0:
		if y1:
			(u, v) = (0, 0)
			for i in y1.values():
				u += i
				v += f(i)
			ans += f(u) - v
	print(ans)


import sys

def pair_count(indices, PointX, PointY, X):
	L = len(X)
	ptr = 0
	line_points = {}
	ans = 0
	c = 0
	valid_indices = valid_Xindices(indices, PointX, X)
	for i in valid_indices:
		p = indices[i]
		while ptr + 1 < L and X[ptr + 1] <= PointX[p]:
			ans += c * (c - 1) // 2
			c = 0
			line_points.clear()
			ptr += 1
		if X[ptr] < PointX[p]:
			c += 1
			y = PointY[p]
			if y not in line_points:
				line_points[y] = 0
			ans -= line_points[y]
			line_points[y] += 1
	ans += c * (c - 1) // 2
	return ans

def valid_Xindices(indices, PointX, X):
	set_X = set(X)
	x_indices = []
	for i in range(K):
		p = indices[i]
		if PointX[p] not in set_X:
			x_indices.append(i)
	return x_indices

def solve():
	indices = list(range(K))
	indices.sort(key=lambda i: PointX[i])
	ans1 = pair_count(indices, PointX, PointY, X)
	indices.sort(key=lambda i: PointY[i])
	ans2 = pair_count(indices, PointY, PointX, Y)
	return ans1 + ans2
input = sys.stdin.buffer.readline
test_cases = int(input())
for test_case in range(test_cases):
	(N, M, K) = map(int, input().split())
	X = list(map(int, input().split()))
	Y = list(map(int, input().split()))
	PointX = []
	PointY = []
	for i in range(K):
		(x, y) = map(int, input().split())
		PointX.append(x)
		PointY.append(y)
	print(solve())


from collections import defaultdict
from bisect import bisect
for _ in range(int(input())):
	(n, m, k) = map(int, input().split())
	xs = list(map(int, input().split()))
	ys = list(map(int, input().split()))
	xss = set(xs)
	yss = set(ys)
	zx = defaultdict(lambda : defaultdict(int))
	zy = defaultdict(lambda : defaultdict(int))
	for _ in range(k):
		(x, y) = map(int, input().split())
		if x in xss and y in yss:
			continue
		if x in xss:
			iy = bisect(ys, y)
			zx[iy][x] += 1
		else:
			ix = bisect(xs, x)
			zy[ix][y] += 1
	ans = 0
	for z in (zx, zy):
		for l in [list(v.values()) for v in z.values()]:
			s = sum(l)
			if s < 2:
				continue
			ans += s * (s - 1) // 2 - sum((q * (q - 1) // 2 for q in l))
	print(ans)


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

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')
from bisect import bisect_left, bisect_right
from collections import Counter

def C2(n):
	return n * (n + 1) // 2
t = int(input())
for _ in range(t):
	(n, m, k) = map(int, input().split())
	X = list(map(int, input().split()))
	Y = list(map(int, input().split()))
	P = [list(map(int, input().split())) for i in range(k)]
	partX = [Counter() for j in range(m + 1)]
	partY = [Counter() for j in range(n + 1)]
	for (x, y) in P:
		if Y[bisect_left(Y, y)] != y:
			partX[bisect_right(Y, y)][bisect_left(X, x)] += 1
		if X[bisect_left(X, x)] != x:
			partY[bisect_right(X, x)][bisect_left(Y, y)] += 1
	ans = 0
	for j in range(m + 1):
		sum_p = 0
		for cnt in partX[j].values():
			ans -= C2(cnt)
			sum_p += cnt
		ans += C2(sum_p)
	for i in range(n + 1):
		sum_p = 0
		for cnt in partY[i].values():
			ans -= C2(cnt)
			sum_p += cnt
		ans += C2(sum_p)
	print(ans)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	ps = list((tuple(map(int, input().split())) for _ in range(k)))
	(sx, sy) = (set(x), set(y))
	px = sorted(((i, j) for (i, j) in ps if i not in sx))
	py = sorted(((j, i) for (i, j) in ps if j not in sy))
	s = 0
	l = r = 0
	for i in range(n - 1):
		while r < len(px) and px[r][0] < x[i + 1]:
			r += 1
		while l < r and px[l][0] <= x[i]:
			l += 1
		if l < r - 1:
			s += (l - r + 1) * (l - r) // 2
			c = {}
			for (i, j) in px[l:r]:
				c[j] = c.get(j, 0) + 1
			for i in c.values():
				if i > 1:
					s -= i * (i - 1) // 2
	l = r = 0
	for i in range(m - 1):
		while r < len(py) and py[r][0] < y[i + 1]:
			r += 1
		while l < r and py[l][0] <= y[i]:
			l += 1
		if l < r - 1:
			s += (l - r + 1) * (l - r) // 2
			c = {}
			for (i, j) in py[l:r]:
				c[j] = c.get(j, 0) + 1
			for i in c.values():
				if i > 1:
					s -= i * (i - 1) // 2
	print(s)


import sys
input = sys.stdin.readline

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

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

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

def input_int_gen():
	return map(int, input().split())
from bisect import bisect_left
from collections import defaultdict
from math import comb
tests = inp()
for _ in range(tests):
	(n, m, k) = input_int_gen()
	xs = input_list()
	ys = input_list()
	horis_total = defaultdict(int)
	vertis_total = defaultdict(int)
	horis = defaultdict(lambda : defaultdict(int))
	vertis = defaultdict(lambda : defaultdict(int))
	for _ in range(k):
		(a, b) = input_int_gen()
		ix = bisect_left(xs, a)
		iy = bisect_left(ys, b)
		if xs[ix] != a:
			horis_total[ix] += 1
			horis[ix][iy] += 1
		elif ys[iy] != b:
			vertis_total[iy] += 1
			vertis[iy][ix] += 1
	res = 0
	for d in horis.values():
		for x in d.values():
			res -= comb(x, 2)
	for d in vertis.values():
		for x in d.values():
			res -= comb(x, 2)
	for c in horis_total.values():
		res += comb(c, 2)
	for c in vertis_total.values():
		res += comb(c, 2)
	print(res)


import sys
input = sys.stdin.readline
from collections import Counter
for _ in range(int(input())):
	(N, M, K) = map(int, input().split())
	V = list(map(int, input().split()))
	H = list(map(int, input().split()))
	P = [tuple(map(int, input().split())) for _ in range(K)]
	XS = P
	YS = [(y, x) for (x, y) in P]

	def f(C, bord) -> int:
		C.sort(key=lambda v: v[0])
		N = len(bord)
		bi = 0
		cnt = 0
		res = 0
		D = Counter()

		def fin():
			nonlocal cnt, res
			if cnt:
				for (k, v) in D.items():
					res += v * (cnt - v)
				cnt = 0
				D.clear()
		for (c, o) in C:
			while c > bord[bi + 1]:
				fin()
				bi += 1
				cnt = 0
			if bord[bi] < c < bord[bi + 1]:
				cnt += 1
				D[o] += 1
		fin()
		return res
	print((f(YS, H) + f(XS, V)) // 2)


import sys
import os
import math
from io import BytesIO, IOBase
from collections import defaultdict, Counter, deque
import 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')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
t = int(input())
for i in range(t):
	(n, m, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	x.sort()
	y.sort()
	ans = 0
	dx = defaultdict(dict)
	dy = defaultdict(dict)
	for j in range(k):
		(x1, y1) = map(int, input().split())
		indx = bisect.bisect_right(x, x1)
		indy = bisect.bisect_right(y, y1)
		if x[indx - 1] == x1 and y[indy - 1] == y1:
			continue
		if y[indy - 1] == y1:
			if dx[indx].get(indy) == None:
				dx[indx][indy] = 1
			else:
				dx[indx][indy] += 1
		elif dy[indy].get(indx) == None:
			dy[indy][indx] = 1
		else:
			dy[indy][indx] += 1
	for jj in dx:
		cur = list(dx[jj].values())
		prex = cur[-1]
		for j in range(len(cur) - 2, -1, -1):
			ans += cur[j] * prex
			prex += cur[j]
	for jj in dy:
		cur = list(dy[jj].values())
		prex = cur[-1]
		for j in range(len(cur) - 2, -1, -1):
			ans += cur[j] * prex
			prex += cur[j]
	print(ans)


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
from collections import defaultdict
mod = 10 ** 9 + 7
mod1 = 998244353
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')

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 ** 51, func=lambda a, b: 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=0, func=lambda a, b: 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
for ik in range(int(input())):
	(n, m, k) = map(int, input().split())
	xlist = list(map(int, input().split()))
	ylist = list(map(int, input().split()))
	xse = set(xlist)
	yse = set(ylist)
	points = defaultdict(list)
	tot = []
	point = defaultdict(list)
	tots = []
	for i in range(k):
		(x, y) = map(int, input().split())
		if x in xse:
			points[x].append(y)
			tot.append(y)
		else:
			point[y].append(x)
			tots.append(x)
	for i in points:
		points[i].sort()
	for i in point:
		point[i].sort()
	tot.sort()
	tots.sort()
	ans = 0
	for i in points:
		for j in range(len(points[i])):
			y = points[i][j]
			ind = binarySearchCount(ylist, len(ylist), y) - 1
			prev = ylist[ind]
			if ylist[ind] == y:
				continue
			nex = ylist[ind + 1]
			bet = max(0, binarySearchCount(tot, len(tot), nex - 1) - binarySearchCount(tot, len(tot), prev))
			betsame = max(0, binarySearchCount(points[i], len(points[i]), nex - 1) - binarySearchCount(points[i], len(points[i]), prev))
			ans += bet - betsame
	ans1 = 0
	for i in point:
		for j in range(len(point[i])):
			x = point[i][j]
			ind = binarySearchCount(xlist, len(xlist), x) - 1
			prev = xlist[ind]
			if xlist[ind] == x:
				continue
			nex = xlist[ind + 1]
			bet = max(0, binarySearchCount(tots, len(tots), nex - 1) - binarySearchCount(tots, len(tots), prev))
			betsame = max(0, binarySearchCount(point[i], len(point[i]), nex - 1) - binarySearchCount(point[i], len(point[i]), prev))
			ans1 += bet - betsame
	print(ans // 2 + ans1 // 2)


def solve(points, ver, hor):
	sol = 0
	points.sort()
	i = 0
	for x in sorted(ver):
		(curr, total) = ({}, 0)
		while i < len(points) and points[i][0] <= x:
			if points[i][0] < x:
				total += 1
				curr[points[i][1]] = curr.get(points[i][1], 0) + 1
			i += 1
		for v in curr.values():
			sol += v * (total - v)
	points.sort(key=lambda x: x[1])
	i = 0
	for y in sorted(hor):
		(curr, total) = ({}, 0)
		while i < len(points) and points[i][1] <= y:
			if points[i][1] < y:
				total += 1
				curr[points[i][0]] = curr.get(points[i][0], 0) + 1
			i += 1
		for v in curr.values():
			sol += v * (total - v)
	return sol // 2
t = int(input())
for _ in range(t):
	(n, m, k) = map(int, input().split())
	ver = list(map(int, input().split()))
	hor = list(map(int, input().split()))
	points = [tuple(map(int, input().split())) for _ in range(k)]
	print(solve(points, ver, hor))


from functools import lru_cache
from bisect import bisect

def get_stripe_num2(a, n, points):
	for j in range(n - 1):
		p1 = points[j]
		p2 = points[j + 1]
		if p1 < a < p2:
			return j

def get_stripe_num(a, n, points):
	(L, R) = (0, n - 1)
	while R - L > 1:
		M = (L + R) // 2
		if points[M] > a:
			R = M
		else:
			L = M
	return L
t = int(input())
for _ in range(t):
	ssss = input()
	(n, m, k) = tuple(map(int, ssss.split(' ')))
	ssss = input()
	ssss = ssss.split(' ')
	xs = tuple(map(int, ssss))
	xxs = set(xs)
	ssss = input()
	ys = tuple(map(int, ssss.split(' ')))
	yys = set(ys)
	y_people = dict()
	x_people = dict()
	ny_people = dict()
	nx_people = dict()
	n_pair = 0
	for i in range(k):
		ssss = input()
		(x, y) = tuple(map(int, ssss.split(' ')))
		a = x in xxs
		b = y in yys
		if a and b:
			continue
		if a:
			y_stripe = bisect(ys, y)
			dct = y_people.get(y_stripe, dict())
			nnn = dct.get(x, 0)
			dct[x] = nnn + 1
			y_people[y_stripe] = dct
			stripe_n = ny_people.get(y_stripe, 0)
			ny_people[y_stripe] = stripe_n + 1
			n_pair += stripe_n - nnn
		if b:
			x_stripe = bisect(xs, x)
			dct = x_people.get(x_stripe, dict())
			nnn = dct.get(y, 0)
			dct[y] = nnn + 1
			x_people[x_stripe] = dct
			stripe_n = nx_people.get(x_stripe, 0)
			nx_people[x_stripe] = stripe_n + 1
			n_pair += stripe_n - nnn
	print(n_pair)


from bisect import bisect_left
maxc = 10 ** 6

def solve():
	(n, m, k) = map(int, input().split())
	xc = list(map(int, input().split()))
	yc = list(map(int, input().split()))
	L1 = [{} for i in range(n)]
	L2 = [{} for i in range(m)]
	for ii in range(k):
		(x, y) = map(int, input().split())
		x0 = bisect_left(xc, x)
		y0 = bisect_left(yc, y)
		if xc[x0] == x and yc[y0] == y:
			continue
		if yc[y0] == y:
			if y0 in L1[x0]:
				L1[x0][y0] += 1
			else:
				L1[x0][y0] = 1
		elif x0 in L2[y0]:
			L2[y0][x0] += 1
		else:
			L2[y0][x0] = 1
	ans = 0
	for L in (L1, L2):
		for d in L:
			sm = sum(d.values())
			ans += sm * (sm - 1) // 2
			for x in d.values():
				ans -= x * (x - 1) // 2
	return ans
import sys
input = lambda : sys.stdin.readline().rstrip()
t = int(input())
for i in range(t):
	print(solve())


import sys

class DInconvenientPairs:

	def solve(self, tc=0):
		N = 10 ** 6
		from bisect import bisect_left, bisect_right
		for _ in range(int(input())):
			(n, m, k) = [int(_) for _ in input().split()]
			xl = [int(_) for _ in input().split()]
			x = set(xl)
			yl = [int(_) for _ in input().split()]
			y = set(yl)
			p = [[int(_) for _ in input().split()] for _ in range(k)]
			convenient = 0
			by_x = {xi: [] for xi in x}
			by_y = {yi: [] for yi in y}
			for pt in p:
				if pt[0] in x:
					by_x[pt[0]].append(pt[1])
				if pt[1] in y:
					by_y[pt[1]].append(pt[0])
			for (coord, item) in by_x.items():
				item.sort()
			for (coord, item) in by_y.items():
				item.sort()
			all_x = [pt[0] for pt in p]
			all_x.sort()
			all_y = [pt[1] for pt in p]
			all_y.sort()

			def count_in_range(arr, l, r):
				return bisect_left(arr, r) - bisect_right(arr, l)
			ans = 0
			for (i, pt) in enumerate(p):
				if pt[0] in x and pt[1] in y:
					convenient += k - 1
				elif pt[0] in x:
					index = bisect_left(yl, pt[1])
					y_down = yl[index - 1]
					y_up = yl[index]
					in_segment = count_in_range(by_x[pt[0]], y_down, y_up)
					ans += count_in_range(all_y, y_down, y_up)
					ans -= in_segment
				elif pt[1] in y:
					index = bisect_left(xl, pt[0])
					x_down = xl[index - 1]
					x_up = xl[index]
					in_segment = count_in_range(by_y[pt[1]], x_down, x_up)
					ans += count_in_range(all_x, x_down, x_up)
					ans -= in_segment
			print(ans // 2)
solver = DInconvenientPairs()
input = sys.stdin.readline
solver.solve()


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

def getnum(cor, arr):
	cor.append([2147483647, 1])
	m = len(cor)
	index = 1
	point = 0
	dic = {}
	output = 0
	while point < m:
		if cor[point][0] > arr[index]:
			while index < len(arr) and arr[index] < cor[point][0]:
				index += 1
			totnum = 0
			for key in dic:
				totnum += dic[key]
				output -= dic[key] * dic[key]
			output += totnum * totnum
			dic = {}
		if cor[point][1] not in dic:
			dic[cor[point][1]] = 0
		dic[cor[point][1]] += 1
		point += 1
	return output // 2

def main(t):
	(n, m, k) = map(int, input().split())
	xn = list(map(int, input().split()))
	ym = list(map(int, input().split()))
	(dicx, dicy) = ({}, {})
	for i in range(n):
		dicx[xn[i]] = 1
	for i in range(m):
		dicy[ym[i]] = 1
	corx = []
	cory = []
	for _ in range(k):
		(x, y) = map(int, input().split())
		if x in dicx and y in dicy:
			continue
		if x in dicx:
			cory.append([y, x])
		elif y in dicy:
			corx.append([x, y])
	corx = sorted(corx)
	cory = sorted(cory)
	ans = getnum(corx, xn) + getnum(cory, ym)
	print(ans)
T = int(input())
t = 1
while t <= T:
	main(t)
	t += 1


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

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
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')
ALPHA = 'abcdefghijklmnopqrstuvwxyz'
M = 998244353
EPS = 1e-06

def Ceil(a, b):
	return a // b + int(a % b > 0)

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

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

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
for _ in range(Int()):
	(n, m, k) = value()
	x_lines = array()
	y_lines = array()
	person = []
	x_lines.append(inf)
	y_lines.append(inf)
	for i in range(k):
		person.append(value())
	have = defaultdict(int)
	deleted = [defaultdict(int) for i in range(m + 2)]
	ans = 0
	for (x, y) in person:
		group = bisect_left(y_lines, y)
		if y_lines[group] != y:
			ans += have[group] - deleted[group][x]
			deleted[group][x] += 1
			have[group] += 1
	have.clear()
	deleted = [defaultdict(int) for i in range(n + 2)]
	for (x, y) in person:
		group = bisect_left(x_lines, x)
		if x_lines[group] != x:
			ans += have[group] - deleted[group][y]
			deleted[group][y] += 1
			have[group] += 1
	print(ans)


import math

def binary_search_leftmost(array, find_this_number):
	left = 0
	right = len(array) - 1
	while left < right:
		middle = math.floor((left + right) / 2)
		if check_smaller(array, middle, find_this_number):
			left = middle + 1
		else:
			right = middle
	return left

def check_smaller(array, middle, find_this_number):
	return array[middle] <= find_this_number

def solve(xstreets, ystreets, peoples):
	y_between = get_y_between(peoples, ystreets, False)
	x_between = get_y_between(peoples, xstreets, True)
	total = 0
	for s in y_between:
		interval = y_between[s]
		count = interval['count']
		for xs in interval:
			if xs == 'count':
				continue
			total += interval[xs] * (count - interval[xs])
			count -= interval[xs]
	for s in x_between:
		interval = x_between[s]
		count = interval['count']
		for xs in interval:
			if xs == 'count':
				continue
			total += interval[xs] * (count - interval[xs])
			count -= interval[xs]
	return total

def get_y_between(peoples, ystreets, swap):
	y_between = {}
	for (px, py) in peoples:
		if swap:
			tmp = px
			px = py
			py = tmp
		index = binary_search_leftmost(ystreets, py)
		if ystreets[index] != py and ystreets[max(index - 1, 0)] != py:
			if ystreets[index] not in y_between:
				y_between[ystreets[index]] = {'count': 0}
			tmp = y_between[ystreets[index]]
			tmp['count'] += 1
			if px not in tmp:
				tmp[px] = 0
			tmp[px] += 1
	return y_between
import os
import io
import time
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input().decode().strip())
for t in range(T):
	(n, m, k) = [int(x) for x in input().decode().strip().split(' ')]
	xstreets = [int(x) for x in input().decode().strip().split(' ')]
	assert len(xstreets) == n
	ystreets = [int(x) for x in input().decode().strip().split(' ')]
	assert len(ystreets) == m
	peoples = []
	for _ in range(k):
		(px, py) = [int(x) for x in input().decode().strip().split(' ')]
		peoples.append((px, py))
	res = solve(xstreets, ystreets, peoples)
	print(res)


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 solve(N, M, K, X, Y, Pos):
	Xdic = {X[i]: i for i in range(N)}
	Ydic = {Y[i]: i for i in range(M)}
	Tx = [collections.defaultdict(int) for _ in range(M - 1)]
	Ty = [collections.defaultdict(int) for _ in range(N - 1)]
	for (x, y) in Pos:
		if x in Xdic and y in Ydic:
			continue
		if x in Xdic:
			k = bisect.bisect_left(Y, y)
			Tx[k - 1][Xdic[x]] += 1
		if y in Ydic:
			k = bisect.bisect_left(X, x)
			Ty[k - 1][Ydic[y]] += 1
	ans = 0
	for k in range(M - 1):
		s = 0
		v = 0
		for (i, n) in Tx[k].items():
			s += n
			v += n * (n - 1) // 2
		ans += s * (s - 1) // 2 - v
	for k in range(N - 1):
		s = 0
		v = 0
		for (i, n) in Ty[k].items():
			s += n
			v += n * (n - 1) // 2
		ans += s * (s - 1) // 2 - v
	return ans
T0 = int(input())
for _ in range(T0):
	(N, M, K) = map(int, input().split())
	X = list(map(int, input().split()))
	Y = list(map(int, input().split()))
	Pos = []
	for _ in range(K):
		(x, y) = map(int, input().split())
		Pos.append((x, y))
	print(solve(N, M, K, X, Y, Pos))


import sys
import math
from collections import deque, Counter
from sys import stdin
int1 = lambda x: int(x) - 1
stinput = lambda : stdin.readline()[:-1]
ii = lambda : int(stinput())
mi = lambda : map(int, stdin.readline().split())
li = lambda : list(mi())
mi1 = lambda : map(int1, stdin.readline().split())
li1 = lambda : list(mi1())
mis = lambda : map(str, stdin.readline().split())
pr = print
rg = range
from collections import defaultdict
mod = 10 ** 9 + 7
Mod = 998244353
INF = 10 ** 18
ans = 0
num = 2 ** 30
t = ii()
for _ in range(t):
	(n, m, k) = mi()
	x = li()
	y = li()
	sx = set(x)
	sy = set(y)
	a = []
	b = []
	for i in x:
		b.append(i * num + 2 ** 20)
	for i in y:
		a.append(i * num + 2 ** 20)
	for i in range(k):
		(p, q) = mi()
		if p in sx:
			if q not in sy:
				a.append(num * q + p)
		else:
			b.append(num * p + q)
	a.sort()
	b.sort()
	ans = 0
	d = defaultdict(int)
	tmp = 0
	for i in a:
		(p, q) = (i // num, i % num)
		if q == 2 ** 20:
			d = defaultdict(int)
			ans += tmp * (tmp - 1) // 2
			tmp = 0
		else:
			ans -= d[q]
			d[q] += 1
			tmp += 1
	d = defaultdict(int)
	tmp = 0
	for i in b:
		(p, q) = (i // num, i % num)
		if q == 2 ** 20:
			d = defaultdict(int)
			ans += tmp * (tmp - 1) // 2
			tmp = 0
		else:
			ans -= d[q]
			d[q] += 1
			tmp += 1
	print(ans)


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, m, k) = MI()
	X = LI()
	Y = LI()
	set_X = set(X)
	set_Y = set(Y)
	ans = 0
	A = []
	B = []
	for _ in range(k):
		(x, y) = MI()
		if x in set_X and y in set_Y:
			continue
		if x in set_X:
			A.append((y, x))
		elif y in set_Y:
			B.append((x, y))
	A.sort()
	A += [(10 ** 18, 0)]
	len_A = len(A)
	idx = 0
	for y in Y[1:]:
		count = 0
		Z = []
		for i in range(idx, len_A):
			if A[i][0] < y:
				count += 1
				Z.append(A[i][1])
			else:
				ans += count * (count - 1) // 2
				if count:
					Z.sort()
					Z += [-1]
					cnt = 1
					prev = Z[0]
					for z in Z[1:]:
						if z == prev:
							cnt += 1
						else:
							ans -= cnt * (cnt - 1) // 2
							prev = z
							cnt = 1
				count = 0
				idx = i
				Z = []
				break
	B.sort()
	B += [(10 ** 18, 0)]
	len_B = len(B)
	idx = 0
	for x in X[1:]:
		count = 0
		W = []
		for i in range(idx, len_B):
			if B[i][0] < x:
				count += 1
				W.append(B[i][1])
			else:
				ans += count * (count - 1) // 2
				if count:
					W.sort()
					W += [-1]
					cnt = 1
					prev = W[0]
					for w in W[1:]:
						if w == prev:
							cnt += 1
						else:
							ans -= cnt * (cnt - 1) // 2
							prev = w
							cnt = 1
				count = 0
				idx = i
				W = []
				break
	print(ans)


from collections import Counter, defaultdict
import bisect
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')
print = lambda s: sys.stdout.write(str(s) + '\n')

def solve():
	(n, m, k) = map(int, input().split())
	X = list(map(int, input().split()))
	Y = list(map(int, input().split()))
	xd = defaultdict(int)
	xdd = defaultdict(int)
	yd = defaultdict(int)
	ydd = defaultdict(int)
	sX = set(X)
	sY = set(Y)
	for _ in range(k):
		(x, y) = map(int, input().split())
		if x in sX and y in sY:
			continue
		if x in sX:
			i = bisect.bisect_left(Y, y)
			xd[i] += 1
			xdd[i, x] += 1
		else:
			i = bisect.bisect_left(X, x)
			yd[i] += 1
			ydd[i, y] += 1
	ans = 0
	for v in xd.values():
		ans += v * v
	for v in yd.values():
		ans += v * v
	for v in xdd.values():
		ans -= v * v
	for v in ydd.values():
		ans -= v * v
	print(ans // 2)
for nt in range(int(input())):
	solve()


from collections import defaultdict
from bisect import bisect_left
T = int(input())
for t in range(T):
	(N, M, K) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	arrx = defaultdict(lambda : defaultdict(int))
	arry = defaultdict(lambda : defaultdict(int))
	for i in range(K):
		(xp, yp) = map(int, input().split())
		indx = bisect_left(x, xp)
		if x[indx] != xp:
			arrx[indx][yp] += 1
		else:
			indy = bisect_left(y, yp)
			if y[indy] != yp:
				arry[indy][xp] += 1
	ans = 0
	ans += sum(map(lambda x: sum(x.values()) ** 2 - sum(map(lambda y: y * y, x.values())), arrx.values()))
	ans += sum(map(lambda x: sum(x.values()) ** 2 - sum(map(lambda y: y * y, x.values())), arry.values()))
	print(ans // 2)


import sys
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
import bisect
from collections import Counter
t = int(input())
for _ in range(t):
	(n, m, k) = map(int, input().split())
	X = list(map(int, input().split()))
	Y = list(map(int, input().split()))
	X.sort()
	Y.sort()
	H = [Counter() for i in range(n)]
	V = [Counter() for i in range(m)]
	for _ in range(k):
		(x, y) = map(int, input().split())
		i = bisect.bisect_right(X, x) - 1
		j = bisect.bisect_right(Y, y) - 1
		if X[i] == x and Y[j] == y:
			continue
		elif X[i] == x:
			V[j][i] += 1
		elif Y[j] == y:
			H[i][j] += 1
	ans = 0
	for i in range(n):
		s = 0
		for c in H[i].values():
			ans -= c * (c - 1) // 2
			s += c
		ans += s * (s - 1) // 2
	for j in range(m):
		s = 0
		for c in V[j].values():
			ans -= c * (c - 1) // 2
			s += c
		ans += s * (s - 1) // 2
	print(ans)


import sys
from collections import Counter, deque
input = sys.stdin.buffer.readline

def calc(xl, ppls):
	(n, res) = (len(xl), 0)
	(p, pn) = (0, len(ppls))
	ppls.sort()
	cc = Counter()
	for i in range(1, n):
		(bx, cx) = (xl[i - 1], xl[i])
		while p < pn and ppls[p][0] < cx:
			if ppls[p][0] != bx:
				cc[ppls[p][1]] += 1
			p += 1
		if not cc:
			continue
		m = 0
		for yc in cc.values():
			(res, m) = (res + m * yc, m + yc)
		if cc:
			cc.clear()
	return res
T = int(input())
for _ in range(T):
	(n, m, k) = map(int, input().split())
	xl = list(map(int, input().split()))
	yl = list(map(int, input().split()))
	ppls = []
	for _ in range(k):
		(x, y) = map(int, input().split())
		ppls.append((x, y))
	res = calc(xl, ppls)
	ppls = [(y, x) for (x, y) in ppls]
	res += calc(yl, ppls)
	print(res)


import sys
from sys import stdin
tt = int(stdin.readline())
ANS = []
for loop in range(tt):
	(n, m, k) = map(int, stdin.readline().split())
	x = list(map(int, stdin.readline().split()))
	y = list(map(int, stdin.readline().split()))
	xs = set(x)
	ys = set(y)
	Xxy = []
	Yyx = []
	for i in range(k):
		(tx, ty) = map(int, stdin.readline().split())
		if tx not in xs:
			Xxy.append((tx, ty))
		elif ty not in ys:
			Yyx.append((ty, tx))
	Xxy.sort()
	Xxy.reverse()
	Xans = 0
	dic = {}
	for tx in x:
		num = 0
		while len(Xxy) > 0 and Xxy[-1][0] < tx:
			num += 1
			tup = (tx, Xxy[-1][1])
			if not tup in dic:
				dic[tup] = 0
			dic[tup] += 1
			del Xxy[-1]
		Xans += num * (num - 1) // 2
	for tup in dic:
		Xans -= dic[tup] * (dic[tup] - 1) // 2
	Yyx.sort()
	Yyx.reverse()
	Yans = 0
	dic = {}
	for ty in y:
		num = 0
		while len(Yyx) > 0 and Yyx[-1][0] < ty:
			num += 1
			tup = (ty, Yyx[-1][1])
			if not tup in dic:
				dic[tup] = 0
			dic[tup] += 1
			del Yyx[-1]
		Yans += num * (num - 1) // 2
	for tup in dic:
		Yans -= dic[tup] * (dic[tup] - 1) // 2
	ANS.append(str(Xans + Yans))
print('\n'.join(ANS))


import sys
inputt = sys.stdin.readline
printt = sys.stdout.write
import math
import functools
from collections import deque
import heapq
from queue import PriorityQueue

def get():
	return inputt().strip()

def gets():
	return inputt().split()

def getint():
	return int(inputt())

def getints():
	return map(int, inputt().split())
for _ in range(getint()):
	answer = 0
	(n, m, k) = getints()
	xl = list(getints())
	yl = list(getints())
	xs = set(xl)
	ys = set(yl)
	pver = []
	phor = []
	for i in range(k):
		(xp, yp) = tuple(getints())
		ver = xp in xs
		hor = yp in ys
		if ver and hor:
			continue
		elif ver:
			pver.append((xp, yp))
		elif hor:
			phor.append((xp, yp))
	pver.sort(key=lambda x: x[1])
	phor.sort(key=lambda x: x[0])
	phi = 0
	for yhi in range(1, m):
		dhi = dict()
		keyhi = set()
		while phi < len(pver):
			if pver[phi][1] < yl[yhi]:
				if pver[phi][0] in keyhi:
					dhi[pver[phi][0]] += 1
				else:
					keyhi.add(pver[phi][0])
					dhi[pver[phi][0]] = 1
			else:
				break
			phi += 1
		lhi = list(dhi.values())
		sumhi = sum(lhi)
		answer += sumhi * (sumhi - 1) // 2 - sum(map(lambda x: x * (x - 1) // 2, lhi))
	phi = 0
	for xhi in range(1, n):
		dhi = dict()
		keyhi = set()
		while phi < len(phor):
			if phor[phi][0] < xl[xhi]:
				if phor[phi][1] in keyhi:
					dhi[phor[phi][1]] += 1
				else:
					keyhi.add(phor[phi][1])
					dhi[phor[phi][1]] = 1
			else:
				break
			phi += 1
		lhi = list(dhi.values())
		sumhi = sum(lhi)
		answer += sumhi * (sumhi - 1) // 2 - sum(map(lambda x: x * (x - 1) // 2, lhi))
	print(answer)


import sys
import getpass
from collections import Counter
input = sys.stdin.readline
M9 = 10 ** 9 + 7
(yes, no) = ('YES', 'NO')
MAXINT = sys.maxsize
OFFLINE_TEST = getpass.getuser() == 'hkmac'

def log(*args):
	if OFFLINE_TEST:
		print('\x1b[36m', *args, '\x1b[0m', file=sys.stderr)

def solve(*args):
	if OFFLINE_TEST:
		log('----- solving ------')
		log(*args)
		log('----- ------- ------')
	return solve_(*args)

def read_matrix(rows):
	return [list(map(int, input().split())) for _ in range(rows)]

def read_strings(rows):
	return [input().strip() for _ in range(rows)]

def minus_one(arr):
	return [x - 1 for x in arr]

def minus_one_matrix(mrr):
	return [[x - 1 for x in row] for row in mrr]
import os
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

def solve_():
	(n, m, k) = list(map(int, input().split()))
	xrr = list(map(int, input().split()))
	yrr = list(map(int, input().split()))
	xset = set(xrr)
	yset = set(yrr)
	xset.add(-1)
	xset.add(LARGE)
	yset.add(-1)
	yset.add(LARGE)
	arr = [(y, -1) for y in yrr]
	brr = [(x, -1) for x in xrr]
	del xrr
	del yrr
	mrr = read_matrix(k)
	for (x, y) in mrr:
		if x in xset and y in yset:
			continue
		if x in xset:
			arr.append((y, x))
		if y in yset:
			brr.append((x, y))
	del xset
	del yset
	del mrr
	arr.sort(key=lambda x: x[0])
	brr.sort(key=lambda x: x[0])
	res = 0
	cnt = 0
	cntr = Counter()
	for (y, x) in arr:
		if x == -1:
			cnt = 0
			cntr = Counter()
		else:
			res += cnt
			res -= cntr[x]
			cnt += 1
			cntr[x] += 1
	cnt = 0
	cntr = Counter()
	for (x, y) in brr:
		if y == -1:
			cnt = 0
			cntr = Counter()
		else:
			res += cnt
			res -= cntr[y]
			cnt += 1
			cntr[y] += 1
	return res
for case_num in range(int(input())):
	res = solve()
	print(res)


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
eps = 1e-07

def hnbhai(tc):
	(n, m, k) = sd()
	x = [-1] + sd() + [10000000]
	y = [-1] + sd() + [10000000]
	dx = {}
	dy = {}
	for i in x:
		dx[i] = 1
	for j in y:
		dy[j] = 1
	crd = []
	for i in range(k):
		(a, b) = sd()
		if dx.get(a) is not None and dy.get(b) is not None:
			continue
		crd.append([a, b])
	crd.sort(key=lambda z: z[0])
	d = {}
	j = 0
	ans = 0
	for i in range(len(x) - 1):
		while j < len(crd) and crd[j][0] <= x[i]:
			j += 1
		while j < len(crd) and crd[j][0] < x[i + 1]:
			d[crd[j][1]] = d.get(crd[j][1], 0) + 1
			j += 1
		tt = 0
		for ele in d:
			ans += tt * d[ele]
			tt += d[ele]
		d = {}
	crd.sort(key=lambda z: z[1])
	d = {}
	j = 0
	for i in range(len(y) - 1):
		while j < len(crd) and crd[j][1] <= y[i]:
			j += 1
		while j < len(crd) and crd[j][1] < y[i + 1]:
			d[crd[j][0]] = d.get(crd[j][0], 0) + 1
			j += 1
		tt = 0
		for ele in d:
			ans += tt * d[ele]
			tt += d[ele]
		d = {}
	print(ans)
for _ in range(sb()):
	hnbhai(_ + 1)


from itertools import product
import itertools
import math
import sys
import heapq
from collections import deque
MOD = 1000000000007

def find(parent, i):
	if parent[i] != i:
		parent[i] = find(parent, parent[i])
	return parent[i]

def union(parent, rank, xx, yy):
	x = find(parent, xx)
	y = find(parent, yy)
	if rank[x] > rank[y]:
		parent[y] = x
	elif rank[y] > rank[x]:
		parent[x] = y
	else:
		parent[y] = x
		rank[x] += 1
ans = 0
K = int(sys.stdin.readline().strip())
x = 0
y = 0
for _ in range(K):
	(n, m, k) = list(map(int, sys.stdin.readline().strip().split()))
	v = list(map(int, sys.stdin.readline().strip().split()))
	h = list(map(int, sys.stdin.readline().strip().split()))
	sv = set(v)
	sh = set(h)
	vp = []
	hp = []
	for _ in range(k):
		(x, y) = list(map(int, sys.stdin.readline().strip().split()))
		if x in sv and y in sh:
			continue
		elif x in sv:
			vp.append((y, x))
		else:
			hp.append((x, y))
	vp.sort()
	hp.sort()
	p = -1
	ans = 0
	for i in range(1, len(h)):
		d = {}
		r = 0
		while p + 1 < len(vp) and vp[p + 1][0] < h[i]:
			p += 1
			r += 1
			if vp[p][1] in d:
				d[vp[p][1]] += 1
			else:
				d[vp[p][1]] = 1
		ans += (r - 1) * r // 2
		for kkk in d:
			kk = d[kkk]
			vv = (kk - 1) * kk // 2
			ans -= vv
	p = -1
	for i in range(1, len(v)):
		d = {}
		r = 0
		while p + 1 < len(hp) and hp[p + 1][0] < v[i]:
			p += 1
			r += 1
			if hp[p][1] in d:
				d[hp[p][1]] += 1
			else:
				d[hp[p][1]] = 1
		ans += (r - 1) * r // 2
		for kkk in d:
			kk = d[kkk]
			vv = (kk - 1) * kk // 2
			ans -= vv
	print(ans)


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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

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

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

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

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

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

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

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

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

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

def solve_a():
	n = get_int()
	s = get_str()
	cnt = 0
	for i in range(n):
		for j in range(i + 1, n + 1):
			if s[i:j].count('a') == s[i:j].count('b'):
				return (i + 1, j)
	return (-1, -1)

def solve_b():
	n = get_int()
	s = list(map(int, get_str()))
	grid = [['='] * n for _ in range(n)]
	if 1 <= s.count(2) <= 2:
		print('NO')
		return
	else:
		winners = []
		for (i, x) in enumerate(s):
			if x == 1:
				for j in range(n):
					grid[i][j] = '='
			else:
				winners.append(i)
		m = len(winners)
		for i in range(m):
			grid[winners[i]][winners[i - 1]] = '+'
			grid[winners[i - 1]][winners[i]] = '-'
		for i in range(n):
			grid[i][i] = 'X'
		print('YES')
		for row in grid:
			print(''.join(row))
		return

def inv_mod(a, M):
	return pow(a, M - 2, M)

def choices(n, M):
	ret = [0] * (n + 1)
	ret[0] = 1
	for k in range(1, n + 1):
		ret[k] = ret[k - 1] * (n - k + 1) * inv_mod(k, M) % M
	return ret

def powers(a, n, M):
	ret = [0] * (n + 1)
	ret[0] = 1
	for k in range(1, n + 1):
		ret[k] = ret[k - 1] * a % M
	return ret

def factorials(n, M):
	ret = [0] * (n + 1)
	ret[0] = 1
	for k in range(1, n + 1):
		ret[k] = ret[k - 1] * k % M
	return ret
M = 998244353
F = factorials(2 * 10 ** 5 + 1, M)

def solve_c():
	n = get_int()
	a = get_ints()
	c = choices(n, M)
	C = Counter(a)
	s = list(C.items())
	s.sort()
	if len(s) == 1:
		return F[n]
	else:
		tops = s[-1][1]
		seconds = s[-2][1]
		ans = F[n]
		if tops > 1:
			return ans
		elif s[-1][0] != s[-2][0] + 1:
			return 0
		c = choices(n - tops - seconds, M)
		for i in range(n - 1):
			if i >= tops + seconds - 1:
				ans -= F[i] * F[n - i - 1] * c[i - tops - seconds + 1] * tops
				ans %= M
		ans -= tops * F[n - 1]
		ans %= M
		return ans

class DSU:

	def __init__(self, nodes, recursive=True, choose_join=True):
		self.p = [i for i in range(nodes)]
		self.r = [0 for i in range(nodes)]
		self.s = [1 for i in range(nodes)]
		self.recursive = recursive
		self.choose_join = choose_join

	def _get_recursive(self, u):
		if u != self.p[u]:
			self.p[u] = self.get(self.p[u])
		return self.p[u]

	def _get_nonrecursive(self, u):
		v = self.p[u]
		while v != self.p[v]:
			v = self.p[v]
		while u != v:
			(u, self.p[u]) = (self.p[u], v)
		return v

	def get(self, u):
		if self.recursive:
			return self._get_recursive(u)
		else:
			return self._get_nonrecursive(u)

	def union(self, u, v):
		u = self.get(u)
		v = self.get(v)
		if u != v:
			if self.r[u] > self.r[v] and self.choose_join:
				(u, v) = (v, u)
			self.p[u] = v
			if self.r[u] == self.r[v]:
				self.r[v] += 1
			self.s[v] += self.s[u]

def solve_d():
	(n, m, k) = get_ints()
	x = get_ints()
	y = get_ints()
	x.sort()
	y.sort()
	xd = defaultdict(int)
	yd = defaultdict(int)
	xd2 = defaultdict(int)
	yd2 = defaultdict(int)
	xs = set(x)
	ys = set(y)
	cnt = 0
	for _ in range(k):
		(a, b) = get_ints()
		if a in xs and b in ys:
			continue
		elif a in xs:
			i = bisect.bisect_left(y, b)
			xd[i] += 1
			xd2[i, a] += 1
		elif b in ys:
			j = bisect.bisect_left(x, a)
			yd[j] += 1
			yd2[j, b] += 1
	cnt = 0
	for (k, v) in xd.items():
		cnt += v * (v - 1) // 2
	for (k, v) in yd.items():
		cnt += v * (v - 1) // 2
	for (k, v) in xd2.items():
		cnt -= v * (v - 1) // 2
	for (k, v) in yd2.items():
		cnt -= v * (v - 1) // 2
	return cnt
t = get_int()
for _ in range(t):
	print(solve_d())


import sys
input = sys.stdin.buffer.readline
from bisect import *
for t in range(int(input())):
	(N, M, K) = map(int, input().split())
	X = list(map(int, input().split()))
	Y = list(map(int, input().split()))
	Z = [list(map(int, input().split())) for i in range(K)]
	V = [[0] * 2 for i in range(K)]
	W = [[], []]
	for i in range(K):
		G = 0
		V[i][0] = bisect_left(X, Z[i][0])
		if X[V[i][0]] == Z[i][0]:
			G += 1
		V[i][1] = bisect_left(Y, Z[i][1])
		if Y[V[i][1]] == Z[i][1]:
			G += 2
		if G == 1:
			W[0].append((V[i][1], V[i][0]))
		if G == 2:
			W[1].append((V[i][0], V[i][1]))
	ANS = 0
	for i in range(2):
		c = 0
		d = 0
		W[i].sort()
		for j in range(len(W[i])):
			if j and W[i][j][0] == W[i][j - 1][0]:
				if W[i][j][1] == W[i][j - 1][1]:
					d += 1
				else:
					c += 1 + d
					d = 0
				ANS += c
			else:
				c = 0
				d = 0
	print(ANS)


try:
	import sys
	from functools import lru_cache, cmp_to_key
	from heapq import merge, heapify, heappop, heappush
	from collections import defaultdict as dd, deque, Counter as C
	from itertools import combinations as comb, permutations as perm
	from bisect import bisect_left as bl, bisect_right as br, bisect, insort
	from time import perf_counter
	from fractions import Fraction
	import copy
	from copy import deepcopy
	import time
	starttime = time.time()
	mod = int(pow(10, 9) + 7)
	mod2 = 998244353

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

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

	def L():
		return list(sp())

	def sl():
		return list(ssp())

	def sp():
		return map(int, data().split())

	def ssp():
		return map(str, data().split())

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

	def l2d(n, m, val=0):
		return [l1d(n, val) for j in range(m)]
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
except:
	pass
for _ in range(L()[0]):
	(n, m, k) = L()
	X = sorted(L())
	Y = sorted(L())
	dx = set(X)
	dy = set(Y)
	R = dd(dict)
	C = dd(dict)
	CntRow = CntCol = 0
	cy = dd(int)
	rx = dd(int)
	for i in range(k):
		(xp, yp) = L()
		if xp in dx and yp in dy:
			continue
		if xp in dx:
			y = br(Y, yp)
			C[y][xp] = C[y].get(xp, 0) + 1
			cy[y] += 1
		else:
			x = br(X, xp)
			R[x][yp] = R[x].get(yp, 0) + 1
			rx[x] += 1
	ans = 0
	for x in R:
		for cx in R[x]:
			y = rx[x] - R[x][cx]
			ans += y * R[x][cx]
	for x in C:
		for cx in C[x]:
			y = cy[x] - C[x][cx]
			ans += y * C[x][cx]
	print(ans // 2)


from bisect import bisect
import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m, k) = map(int, input().split())
	xs = list(map(int, input().split()))
	ys = list(map(int, input().split()))
	p = [list(map(int, input().split())) for _ in range(k)]
	(xset, yset) = (set(xs), set(ys))
	count_hor = [{} for _ in range(n)]
	for (x, y) in p:
		if y in yset and x not in xset:
			pos = bisect(xs, x)
			if y not in count_hor[pos]:
				count_hor[pos][y] = 1
			else:
				count_hor[pos][y] += 1
	count_ver = [{} for _ in range(m)]
	for (x, y) in p:
		if x in xset and y not in yset:
			pos = bisect(ys, y)
			if x not in count_ver[pos]:
				count_ver[pos][x] = 1
			else:
				count_ver[pos][x] += 1
	ans = 0
	for d in count_hor:
		if len(d) > 1:
			suma = sum((v for v in d.values()))
			for v in d.values():
				suma -= v
				ans += v * suma
	for d in count_ver:
		if len(d) > 1:
			suma = sum((v for v in d.values()))
			for v in d.values():
				suma -= v
				ans += v * suma
	print(ans)


import bisect
import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, m, k) = map(int, input().split())
	xx = list(map(int, input().split()))
	yy = list(map(int, input().split()))
	xxse = set(xx)
	yyse = set(yy)
	dicx = {}
	dicy = {}
	for i in range(k):
		(x, y) = map(int, input().split())
		if not x in xxse:
			xreq = bisect.bisect_right(xx, x)
			if xreq in dicx:
				if y in dicx[xreq]:
					dicx[xreq][y] += 1
				else:
					dicx[xreq][y] = 1
			else:
				dicx[xreq] = {y: 1}
		elif not y in yyse:
			yreq = bisect.bisect_right(yy, y)
			if yreq in dicy:
				if x in dicy[yreq]:
					dicy[yreq][x] += 1
				else:
					dicy[yreq][x] = 1
			else:
				dicy[yreq] = {x: 1}
	ans = 0
	for i in dicx:
		su = sum(dicx[i].values())
		for j in dicx[i]:
			val = dicx[i][j]
			su -= val
			ans += su * val
	for i in dicy:
		su = sum(dicy[i].values())
		for j in dicy[i]:
			val = dicy[i][j]
			su -= val
			ans += su * val
	print(ans)


import sys
input = sys.stdin.buffer.readline

def process(X, Y, K):
	X_set = set(X)
	Y_set = set(Y)
	n1 = len(X)
	n2 = len(Y)
	h_only = []
	v_only = []
	answer = 0
	for (a, b) in K:
		if a in X_set and b not in Y_set:
			h_only.append((a, b))
		elif a not in X_set and b in Y_set:
			v_only.append((a, b))
	h_only = sorted(h_only, key=lambda a: a[1])
	v_only = sorted(v_only, key=lambda a: a[0])
	index = 0
	m1 = len(h_only)
	for i in range(1, n2):
		d = {}
		total = 0
		y0 = Y[i - 1]
		y1 = Y[i]
		while index < m1 and h_only[index][1] < y1:
			(a, b) = h_only[index]
			if a not in d:
				d[a] = 0
			d[a] += 1
			total += 1
			index += 1
		pairs = total * (total - 1) // 2
		for a in d:
			pairs -= d[a] * (d[a] - 1) // 2
		answer += pairs
	m2 = len(v_only)
	index = 0
	for i in range(1, n1):
		d = {}
		total = 0
		x0 = X[i - 1]
		x1 = X[i]
		while index < m2 and v_only[index][0] < x1:
			(a, b) = v_only[index]
			if b not in d:
				d[b] = 0
			d[b] += 1
			total += 1
			index += 1
		pairs = total * (total - 1) // 2
		for a in d:
			pairs -= d[a] * (d[a] - 1) // 2
		answer += pairs
	return answer
t = int(input())
for i in range(t):
	(n, m, k) = [int(x) for x in input().split()]
	X = [int(x) for x in input().split()]
	Y = [int(x) for x in input().split()]
	K = []
	for j in range(k):
		(a, b) = [int(x) for x in input().split()]
		K.append([a, b])
	print(process(X, Y, K))


import sys
input = sys.stdin.readline
from _collections import defaultdict
T = int(input())
for iii in range(T):
	(n, m, k) = map(int, input().split())
	mitix = set()
	mitiy = set()
	x = list(map(int, input().split()))
	for i in range(n):
		mitix.add(x[i])
	y = list(map(int, input().split()))
	for i in range(m):
		mitiy.add(y[i])
	px = []
	py = []
	ans = 0
	for i in range(k):
		(X, Y) = map(int, input().split())
		if X in mitix:
			if Y in mitiy:
				pass
			else:
				px.append((X, Y))
		else:
			py.append((X, Y))
	px.sort(key=lambda x: x[1], reverse=True)
	for i in range(m - 1):
		dic = defaultdict(int)
		while px and y[i] < px[-1][1] < y[i + 1]:
			(a, b) = px.pop()
			dic[a] += 1
		xs = [dic[key] for key in dic]
		subans = 0
		subans += sum(xs) ** 2 - sum((nod ** 2 for nod in xs))
		subans //= 2
		ans += subans
	py.sort(key=lambda x: x[0], reverse=True)
	for i in range(n - 1):
		dic = defaultdict(int)
		while py and x[i] < py[-1][0] < x[i + 1]:
			(a, b) = py.pop()
			dic[b] += 1
		ys = [dic[key] for key in dic]
		subans = 0
		subans += sum(ys) ** 2 - sum((nod ** 2 for nod in ys))
		subans //= 2
		ans += subans
	print(ans)


from __future__ import division, print_function
import os
import sys
from bisect import bisect_left
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

def main():
	t = int(input())
	for _ in range(t):
		(n, m, k) = map(int, input().split())
		x = [int(xi) for xi in input().split()]
		y = [int(xi) for xi in input().split()]
		p = [[int(i) for i in input().split()] for _ in range(k)]
		sol = 0
		(seen, prev, curr) = ([0] * len(y), [0] * len(y), [0] * len(y))
		for (xp, yp) in sorted(p, key=lambda x: x[0]):
			idx_x = bisect_left(x, xp)
			idx_y = bisect_left(y, yp)
			if y[idx_y] == yp:
				continue
			if prev[idx_y] != idx_x:
				seen[idx_y] += curr[idx_y]
				prev[idx_y] = idx_x
				curr[idx_y] = 0
			curr[idx_y] += 1
			sol += seen[idx_y]
		(seen, prev, curr) = ([0] * len(x), [0] * len(x), [0] * len(x))
		for (xp, yp) in sorted(p, key=lambda x: x[1]):
			idx_x = bisect_left(x, xp)
			idx_y = bisect_left(y, yp)
			if x[idx_x] == xp:
				continue
			if prev[idx_x] != idx_y:
				seen[idx_x] += curr[idx_x]
				prev[idx_x] = idx_y
				curr[idx_x] = 0
			curr[idx_x] += 1
			sol += seen[idx_x]
		print(sol)
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()


import math
import sys
input = sys.stdin.readline

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

def II():
	return int(input().strip())

def LI():
	return [*map(int, input().strip().split())]
from heapq import heappush, heappop, heapify
from bisect import bisect_left, bisect_right
from collections import deque, defaultdict, Counter, OrderedDict
from itertools import permutations, chain, combinations, groupby
from operator import itemgetter
from types import GeneratorType
from typing import Iterable, TypeVar, Union

def get(a, u):
	ans = 0
	a.sort()
	arr = []
	for i in range(len(a)):
		arr.append(bisect_left(u, a[i]))
	c = Counter(arr)
	for i in c.values():
		ans += nc2(i)
	return ans

def nc2(p):
	if p < 2:
		return 0
	return p * (p - 1) // 2
for _ in range(II()):
	(n, m, k) = LI()
	u = LI()
	v = LI()
	x = set(u)
	y = set(v)
	(a, b) = ([], [])
	sx = defaultdict(lambda : [])
	sy = defaultdict(lambda : [])
	for _ in range(k):
		(l, r) = LI()
		if l in x and r in y:
			continue
		if l in x:
			sx[l].append(r)
			a.append(r)
		if r in y:
			sy[r].append(l)
			b.append(l)
	u.sort()
	v.sort()
	ans = get(b, u) + get(a, v)
	for a in sx.values():
		ans -= get(a, v)
	for b in sy.values():
		ans -= get(b, u)
	print(ans)


import sys
input = sys.stdin.readline

def solve():
	(n, m, k) = map(int, input().split())
	X = list(map(int, input().split()))
	Y = list(map(int, input().split()))
	P = [list(map(int, input().split())) for _ in range(k)]
	P.sort(key=lambda x: x[0])
	ans = 0
	j = 0
	for i in range(n):
		cnt = 0
		tmp = {}
		while j < k and P[j][0] <= X[i]:
			if P[j][0] == X[i]:
				j += 1
				continue
			if P[j][1] not in tmp:
				tmp[P[j][1]] = 0
			tmp[P[j][1]] += 1
			cnt += 1
			j += 1
		ans += cnt * (cnt - 1) // 2
		for key in tmp:
			ans -= tmp[key] * (tmp[key] - 1) // 2
	j = 0
	P.sort(key=lambda x: x[1])
	for i in range(m):
		cnt = 0
		tmp = {}
		while j < k and P[j][1] <= Y[i]:
			if P[j][1] == Y[i]:
				j += 1
				continue
			if P[j][0] not in tmp:
				tmp[P[j][0]] = 0
			tmp[P[j][0]] += 1
			cnt += 1
			j += 1
		ans += cnt * (cnt - 1) // 2
		for key in tmp:
			ans -= tmp[key] * (tmp[key] - 1) // 2
	return ans
for _ in range(int(input())):
	print(solve())