A sequence $a = [a_1, a_2, \ldots, a_l]$ of length $l$ has an ascent if there exists a pair of indices $(i, j)$ such that $1 \le i < j \le l$ and $a_i < a_j$. For example, the sequence $[0, 2, 0, 2, 0]$ has an ascent because of the pair $(1, 4)$, but the sequence $[4, 3, 3, 3, 1]$ doesn't have an ascent.

Let's call a concatenation of sequences $p$ and $q$ the sequence that is obtained by writing down sequences $p$ and $q$ one right after another without changing the order. For example, the concatenation of the $[0, 2, 0, 2, 0]$ and $[4, 3, 3, 3, 1]$ is the sequence $[0, 2, 0, 2, 0, 4, 3, 3, 3, 1]$. The concatenation of sequences $p$ and $q$ is denoted as $p+q$.

Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has $n$ sequences $s_1, s_2, \ldots, s_n$ which may have different lengths.

Gyeonggeun will consider all $n^2$ pairs of sequences $s_x$ and $s_y$ ($1 \le x, y \le n$), and will check if its concatenation $s_x + s_y$ has an ascent. Note that he may select the same sequence twice, and the order of selection matters.

Please count the number of pairs ($x, y$) of sequences $s_1, s_2, \ldots, s_n$ whose concatenation $s_x + s_y$ contains an ascent.


-----Input-----

The first line contains the number $n$ ($1 \le n \le 100000$) denoting the number of sequences.

The next $n$ lines contain the number $l_i$ ($1 \le l_i$) denoting the length of $s_i$, followed by $l_i$ integers $s_{i, 1}, s_{i, 2}, \ldots, s_{i, l_i}$ ($0 \le s_{i, j} \le 10^6$) denoting the sequence $s_i$.

It is guaranteed that the sum of all $l_i$ does not exceed $100000$.


-----Output-----

Print a single integer, the number of pairs of sequences whose concatenation has an ascent.


-----Examples-----

Input
5
1 1
1 1
1 2
1 4
1 3
Output
9
Input
3
4 2 0 2 0
6 9 9 8 8 7 7
1 6
Output
7
Input
10
3 62 24 39
1 17
1 99
1 60
1 64
1 30
2 79 29
2 20 73
2 85 37
1 100
Output
72


-----Note-----

For the first example, the following $9$ arrays have an ascent: $[1, 2], [1, 2], [1, 3], [1, 3], [1, 4], [1, 4], [2, 3], [2, 4], [3, 4]$. Arrays with the same contents are counted as their occurences.

Source: codeforces | Difficulty: MEDIUM
Tags: Sorting

Combinatorics

Implementation

Dynamic programming

Data structures


Solutions:
import sys
from math import floor

def binSearch(target):
	low = 0
	up = len(maxs) - 1
	mid = 0
	found = -1
	while low <= up:
		mid = floor((low + up) / 2)
		if maxs[mid] < target:
			low = mid + 1
		elif maxs[mid] > target:
			up = mid - 1
		else:
			found = mid
			low = mid + 1
	return low
numberOfArrays = int(input())
mins = []
maxs = []
for index in range(0, numberOfArrays):
	inp = input().split(' ')
	curMin = sys.maxsize
	curMax = -1
	for i in range(1, int(inp[0]) + 1):
		curMin = min(int(inp[i]), curMin)
		if curMin < int(inp[i]):
			curMin = -1
			curMax = sys.maxsize
			break
		curMax = max(int(inp[i]), curMax)
	mins.append(curMin)
	maxs.append(curMax)
maxs.sort()
count = 0
for i in range(0, numberOfArrays):
	count += len(maxs) - binSearch(mins[i])
print(count)


import sys
n = int(input())
(min_a, max_a) = ([], [])
asc = set()
for (i, a) in enumerate((list(map(int, l.split())) for l in sys.stdin)):
	if any((a[j] < a[j + 1] for j in range(1, a[0]))):
		asc.add(i)
	else:
		min_a.append(min(a[1:]))
		max_a.append(max(a[1:]))
min_a.sort()
max_a.sort()
max_a.append(10 ** 18)
ans = 0
j = 0
m = len(min_a)
for i in range(m):
	while min_a[i] >= max_a[j]:
		j += 1
	ans += m - j + len(asc)
print(ans + n * len(asc))


import sys
from functools import partial
from math import sqrt
import bisect

def insert(l, n):
	bisect.insort(l, n)
	return l

def abs(x):
	if x < 0:
		return -x
	return x

def bin_search(f, f_derivative, x, is_min=True):
	pass

def longest_zipline(w, g, h, x):
	return sqrt(g ** 2 + x ** 2) + sqrt(h ** 2 + (w - x) ** 2)

def lz_derivative(w, g, h, r, x):
	return x / sqrt(g ** 2 + x ** 2) + (x - w) / sqrt(h ** 2 + (w - x) ** 2)

def is_ascend(s):
	low = 10 ** 6
	for i in range(len(s)):
		if s[i] < low:
			low = s[i]
		if s[i] > low:
			return True
	return False
low = []
high = []
count = 0
ascends = 0
for (i, line) in enumerate(sys.stdin):
	if i == 0:
		n = int(line.strip())
	else:
		s = [int(x) for x in line.strip().split()]
		s = s[1:]
		if not is_ascend(s):
			low.append(s[-1])
			high.insert(bisect.bisect(high, s[0]), s[0])
		else:
			ascends += 1
for l in low:
	count += len(low) - bisect.bisect_right(high, l)
print(count + ascends * ascends + 2 * len(low) * ascends)


n = int(input())
a = []
for i in range(n):
	a.append([int(x) for x in input().split()[1:]])

def has_ascent(a):
	for i in range(len(a) - 1):
		if a[i] < a[i + 1]:
			return True
	return False
ans = 0
ascent = 0
info = []
for i in a:
	if has_ascent(i):
		ascent += 1
	else:
		info.append((min(i), max(i)))
ans += 2 * ascent * (n - ascent)
ans += ascent * ascent
men = sorted([i[0] for i in info])
may = sorted([i[1] for i in info])
from bisect import bisect_left
for i in range(len(may)):
	ans += bisect_left(men, may[i])
print(ans)


import bisect
m = n = int(input())
gaba = 0
l = []
a = []
primeiro = []
ultimos = []
for _ in range(n):
	b = input().split()
	l.append(int(b[0]))
	b.pop(0)
	a.append(list(map(int, b)))
for i in range(n - 1, -1, -1):
	men = a[i][0]
	tot = 0
	for j in range(l[i]):
		tot += 1
		if a[i][j] <= men:
			men = a[i][j]
		else:
			gaba += 2 * m - 1
			a.pop(i)
			m -= 1
			tot = 0
			break
	if tot == l[i]:
		primeiro.append(a[i][0])
primeiro.sort()
for i in range(m):
	id = bisect.bisect_right(primeiro, a[i][-1])
	gaba += len(primeiro) - id
print(gaba)


from bisect import bisect_right as bi
n = int(input())
mn_a = []
mx_a = []
ans = n ** 2
for i in range(n):
	inp = list(map(int, input().split()))
	l = inp[0]
	ss = inp[1:]
	not_asc = True
	for j in range(l - 1):
		if ss[j] < ss[j + 1]:
			not_asc = False
			break
	if not_asc or l == 1:
		mn_a.append(ss[-1])
		mx_a.append(ss[0])
mn_a.sort()
mx_a.sort()
for i in range(len(mn_a)):
	ans -= bi(mx_a, mn_a[i])
print(ans)


def main():
	nSequences = int(input())
	nAscents = nNonAscents = 0
	(nonAscentStarts, nonAscentEnds) = ([], [])
	nSequencesToCombine = nSequences - 1
	for i in range(nSequences):
		sequence = list(map(int, input().split()))
		if sorted(sequence[1:], reverse=True) != sequence[1:]:
			nAscents += 1 + nSequencesToCombine + nSequencesToCombine
			nSequencesToCombine -= 1
		else:
			nonAscentStarts.append(sequence[1])
			nonAscentEnds.append(sequence[-1])
			nNonAscents += 1
	nonAscentEnds.sort()
	return nAscents + nConcatenatedAscentsTotal(nNonAscents, nonAscentStarts, nonAscentEnds)

def nConcatenatedAscentsTotal(nNonAscents, nonAscentStarts, nonAscentEnds):
	return sum((nConcatenatedAscents(nNonAscents, nonAscentStarts[i], nonAscentEnds) for i in range(nNonAscents)))

def nConcatenatedAscents(nNonAscents, start, nonAscentEnds):
	(iFirst, iLast) = (0, nNonAscents)
	iCurr = (iFirst + iLast) // 2
	while iCurr != iFirst:
		if start > nonAscentEnds[iCurr]:
			iFirst = iCurr
		else:
			iLast = iCurr
		iCurr = (iFirst + iLast) // 2
	if start <= nonAscentEnds[iCurr]:
		return iCurr
	return iCurr + 1
print(main())


import bisect
n = int(input())
arrays = []
for i in range(n):
	cur = input().split(' ')
	arrays.append([int(x) for x in cur[1:]])
highest = []
lowest = []
result = 0
for array in arrays:
	cur = False
	last = 1000000
	curh = 0
	curl = 1000000
	for a in array:
		if a > last:
			cur = True
		last = a
		curh = max(a, curh)
		curl = min(a, curl)
	if cur:
		result += 2 * n
	else:
		bisect.insort(highest, curh)
		lowest.append(curl)
l = len(lowest)
tot = result + l ** 2
for i in range(l):
	p = l - bisect.bisect_right(highest, lowest[i])
	result += l - bisect.bisect_right(highest, lowest[i])
result -= tot - n ** 2
print(result)


import sys
import math
import heapq
import bisect
import re
from collections import deque
sys.setrecursionlimit(1000000000)

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

def iinput():
	return int(input())

def finput():
	return float(input())

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

def rinput():
	return map(int, tinput())

def rlinput():
	return list(rinput())

def modst(w, s):
	res = 1
	while s:
		if s % 2:
			res *= w
		w *= w
		s //= 2
	return res

def error(n):
	print('YES')
	exit(n)

def main():
	n = iinput()
	res = 0
	q = []
	t = 0
	for i in range(n):
		w = rlinput()
		mi = 1000000.0
		ma = 0
		fl = 1
		for i in range(1, w[0] + 1):
			if mi > w[i]:
				mi = w[i]
			if ma < w[i]:
				ma = w[i]
		for i in range(1, w[0]):
			if w[i + 1] > w[i]:
				res += n + n - 1
				fl = 0
				t += 1
				break
		if fl:
			q.append([mi, ma])
	res -= t * (t - 1)
	q = sorted(q)
	(w, e) = ([], [])
	for i in q:
		w.append(i[0])
		e.append(i[1])
	for i in range(len(w)):
		res += bisect.bisect_left(w, e[i])
	print(res)
for i in range(1):
	main()


n = int(input())
from bisect import *
ar = []
br = []
for i in range(n):
	a = list(map(int, input().split()))
	a.pop(0)
	if sorted(a, reverse=True) == a or len(a) == 1:
		ar.append(min(a))
		br.append(max(a))
br.sort()
ans = 0
for i in ar:
	pos = bisect_left(br, i + 0.1)
	ans += len(br) - pos
print(ans + (n - len(br)) * len(br) * 2 + (n - len(br)) ** 2)


import sys
from bisect import bisect_left, bisect_right

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

def has_ascent(l):
	return any((l[i] < l[i + 1] for i in range(len(l) - 1)))
n = int(input())
lists = []
mins = []
maxs = []
hasasc = []
for i in range(n):
	lists.append(list(map(int, input().split()))[1:])
	if has_ascent(lists[i]):
		mins.append(-sys.maxsize)
		maxs.append(sys.maxsize)
	else:
		mins.append(min(lists[i]))
		maxs.append(max(lists[i]))
maxs.sort()
ans = 0
for i in range(n):
	ans += n - bisect_right(maxs, mins[i])
print(ans)


n = int(input())
mini = []
maxi = []
ans = 0
count = 0
for i in range(n):
	arr = list(map(int, input().split()))
	mi = arr[1]
	hehe = True
	for j in range(1, arr[0] + 1):
		if mi < arr[j]:
			hehe = False
			break
		else:
			mi = arr[j]
	if hehe:
		mini.append(mi)
		maxi.append(arr[1])
	else:
		ans += 2 * (n - count) - 1
		count += 1
mini.sort()
maxi.sort()
k = 0
l = 0
while k < len(mini) and l < len(maxi):
	if maxi[l] > mini[k]:
		k += 1
	else:
		ans += k
		l += 1
while l < len(maxi):
	ans += len(mini)
	l += 1
print(ans)


def main():
	nb_sequences = int(input())
	(mini, maxi) = ([], [])
	asc = nasc = 0
	for _ in range(nb_sequences):
		t = [int(i) for i in input().split()]
		(n, L) = (t[0], t[1:])
		for i in range(n):
			if i > 0 and L[i] > L[i - 1]:
				asc += 1
				break
			elif i == n - 1:
				nasc += 1
				mini.append(min(L))
				maxi.append(max(L))
	total = asc ** 2 + 2 * asc * nasc
	mini.sort()
	maxi.sort()
	i = 0
	for x in maxi:
		while i < nasc and mini[i] < x:
			i += 1
		total += i
	print(total)
main()


from fractions import gcd
from heapq import *
import math
from collections import defaultdict, Counter, deque
from bisect import *
import itertools
import fractions
MOD = 10 ** 9 + 7

def main():
	n = int(input())
	l = [list(map(int, input().split())) for i in range(n)]
	mi = [0] * n
	ma = [0] * n
	asc = 0
	desc = 0
	v = [0] * 1010101
	ans = 0
	c = [True] * n
	for i in range(n):
		a = l[i][1]
		f = True
		for j in range(2, l[i][0] + 1):
			if a < l[i][j] and f:
				f = False
				c[i] = False
				break
			elif a > l[i][j]:
				a = l[i][j]
		if not f:
			continue
		tt = min(l[i][1:])
		mi[i] = tt
		t = max(l[i][1:])
		ma[i] = t
		v[t] += 1
	for i in range(1010100, -1, -1):
		v[i - 1] += v[i]
	k = 0
	for i in range(n):
		if c[i]:
			ans += v[mi[i] + 1]
		else:
			k += 1
			ans += n * 2
	print(ans - k * k)
main()


from bisect import *
n = int(input())
(a, b) = ([], [])
for _ in [0] * n:
	(l, *s) = map(int, input().split())
	if sorted(s) == s[::-1]:
		a += (s[0],)
		b += (s[-1],)
a.sort()
print(n * n - sum((bisect(a, x) for x in b)))


import sys
input = sys.stdin.readline
import bisect

def main():
	N = int(input())
	mi = []
	ma = []
	for _ in range(N):
		l = [int(x) for x in input().split()]
		ll = l.pop(0)
		is_asc = False
		for i in range(ll - 1):
			if l[i + 1] > l[i]:
				is_asc = True
				break
		if is_asc:
			ma.append(float('inf'))
			mi.append(-float('inf'))
		else:
			mi.append(min(l))
			ma.append(max(l))
	mi.sort()
	ma.sort()
	ans = 0
	for v in mi:
		x = bisect.bisect_right(ma, v)
		ans += N - x
	print(ans)
main()


import bisect
n = int(input())
m = []
mm = []
for i in range(n):
	x = list(map(int, input().split()))
	s = x[1:]
	if sorted(s) == s[::-1]:
		m.append(s[0])
		mm.append(s[-1])
m.sort()
mm.sort()
ans = 0
for i in range(len(m)):
	j = bisect.bisect_right(m, mm[i])
	ans = ans + j
print(n * n - ans)


n = int(input())
(minis, maxis, casc, cdes) = ([], [], 0, 0)
for i in range(n):
	s = list(map(int, input().split()))
	s.pop(0)
	for j in range(len(s)):
		if j > 0 and s[j] > s[j - 1]:
			casc += 1
			break
		elif j == len(s) - 1:
			cdes += 1
			minis.append(min(s))
			maxis.append(max(s))
total = casc * casc + 2 * casc * cdes
minis.sort()
maxis.sort()
i = 0
for j in maxis:
	while i < cdes and minis[i] < j:
		i += 1
	total += i
print(total)


n = int(input())
req = 0
reqmin = []
reqmax = []
hav = 0
for _ in range(n):
	l = [int(s) for s in input().split()]
	flag = 0
	for i in range(2, l[0] + 1):
		if l[i] > l[i - 1]:
			flag = 1
			break
	if flag:
		hav += 1
	else:
		req += 1
		w1 = min(l[1:])
		w2 = max(l[1:])
		reqmin += [[w1, w2]]
		reqmax += [[w2, w1]]
ans = 2 * hav * req + hav * hav
reqmin.sort()
reqmax.sort()
i = 0
j = 0
while i < req and j < req:
	if reqmin[i][0] < reqmax[j][0]:
		if reqmin[i][1] > reqmin[i][0]:
			ans += req - j
		else:
			ans += req - j
		i += 1
	else:
		j += 1
print(ans)


num = int(input())
minimo = []
maximo = []
cresc = 0
decr = 0
for a in range(num):
	seq = list(map(int, input().split()))
	seq.reverse()
	seq.pop()
	seq.reverse()
	for b in range(len(seq)):
		if b > 0 and seq[b] > seq[b - 1]:
			cresc += 1
			break
		elif b == len(seq) - 1:
			decr += 1
			minimo.append(min(seq))
			maximo.append(max(seq))
res = cresc * cresc + 2 * (cresc * decr)
minimo.sort()
maximo.sort()
i = 0
for c in maximo:
	while i < decr and minimo[i] < c:
		i += 1
	res += i
print(res)


import bisect
n = int(input())
minis = []
maxis = []
self_test_cnt = 0
for N in range(n):
	l = list(map(int, input().split()))
	sz = l[0]
	curr = l[1:]
	mini = 987654321
	maxi = -1
	self_test = 0
	for i in curr:
		if i > maxi:
			maxi = i
		if i > mini:
			self_test = 1
		if i < mini:
			mini = i
	self_test_cnt += self_test
	if self_test == 0:
		minis.append(mini)
		maxis.append(maxi)
ans = 2 * self_test_cnt * (n - self_test_cnt) + self_test_cnt * self_test_cnt
minis = sorted(minis)
maxis = sorted(maxis)
for i in maxis:
	ans += bisect.bisect_left(minis, i)
print(ans)


def mi():
	return list(map(int, input().split()))
n = int(input())
na = n
(ma, mi) = ([], [])
ol = 0
asc = 0
for ii in range(n):
	a = list(map(int, input().split()))
	n = a[0]
	if n == 1:
		ol += 1
	a = a[1:]
	maa = -1
	mii = 10 ** 6 + 5
	vis = False
	for i in range(n):
		if a[i] < mii:
			mii = a[i]
		if a[i] > maa:
			maa = a[i]
		if (mii != 10 ** 6 + 5 and mii < a[i]) and (not vis):
			vis = True
			asc += 1
	if not vis:
		ma.append(maa)
		mi.append(mii)
from bisect import bisect_left as bl
from bisect import bisect_right as br
ans = 0
n = na
mi.sort()
ma.sort()
lma = len(ma)
for i in mi:
	ans += lma - br(ma, i)
print(ans + asc * (na * 2 - 1) - asc * (asc - 1))


n = int(input())
mi = []
ma = []
i = j = cnt = 0
for _ in range(n):
	a = list(map(int, input().split()))
	flag = False
	for k in range(1, a[0]):
		if a[k] < a[k + 1]:
			flag = True
	if flag:
		cnt += 1
		continue
	a.pop(0)
	mi.append(min(a))
	ma.append(max(a))
mi.sort()
ma.sort()
ans = cnt * ((2 * n - 1 + (2 * n - cnt * 2 + 1)) // 2)
n = len(mi)
while i < n:
	while j < n and ma[j] <= mi[i]:
		j += 1
	ans += n - j
	i += 1
print(ans)


def MaxyMin(k1):
	x = len(k1)
	mini = min(k1[1:x])
	maxi = max(k1[1:x])
	minx = k1[1]
	for i in range(1, x - 1):
		if minx < k1[i + 1]:
			return (True, mini, maxi)
		else:
			minx = k1[i + 1]
	return (False, mini, maxi)

def resuelve(mn, mx, cont, contA, s):
	mn.sort()
	for i in range(len(mn)):
		r = binary(mn, mx[i], cont)
		cont += r
	cont += contA * s + (s - contA) * contA
	return cont

def binary(Lmin, maxi, cont):
	left = 0
	right = len(Lmin) - 1
	while left <= right:
		mid = (left + right) // 2
		if Lmin[mid] < maxi:
			left = mid + 1
		elif Lmin[mid] >= maxi:
			right = mid - 1
	if left != 0:
		return left
	else:
		return mid
s = int(input())
maxis = []
minis = []
cont = 0
contA = 0
for i in range(s):
	k = list(map(int, input().split()))
	(si, m1, m2) = MaxyMin(k)
	if not si:
		minis.append(m1)
		maxis.append(m2)
	else:
		contA += 1
print(resuelve(minis, maxis, cont, contA, s))


def has_ascent(s):
	if len(s) == 1:
		return False
	for i in range(len(s) - 1):
		if s[i + 1] > s[i]:
			return True
	return False
n = int(input())
min_of_s = []
max_of_s = []
ascent = []
count = 0
k = n
for _ in range(n):
	(l, *s) = list(map(int, input().split()))
	if has_ascent(s):
		count += 2 * k - 1
		k -= 1
	else:
		min_of_s.append(min(s))
		max_of_s.append(max(s))
min_of_s.sort()
max_of_s.sort()
i = 0
j = 0
while i < len(min_of_s) and j < len(max_of_s):
	if min_of_s[i] < max_of_s[j]:
		count += k - j
		i += 1
	else:
		j += 1
print(count)


import bisect
n = int(input())
firsts = []
lasts = []
ans = n ** 2
for i in range(n):
	a = list(map(int, input().split()))
	is_ascent = False
	cur_min = a[1]
	for j in range(2, a[0] + 1):
		if a[j] > cur_min:
			is_ascent = True
			break
		elif a[j] < cur_min:
			cur_min = a[j]
	if not is_ascent:
		firsts.append(a[1])
		lasts.append(a[-1])
firsts.sort()
minus = 0
for i in lasts:
	minus += bisect.bisect(firsts, i)
print(ans - minus)


from bisect import *
from sys import stdin, stdout
n = int(stdin.readline())
arr = []
arr1 = []
for i in range(n):
	line = list(map(int, stdin.readline().split()))[1:]
	flag = False
	m = 10 ** 6
	for i1 in line:
		if m < i1:
			flag = not flag
			break
		m = i1
	if not flag:
		arr.append([line[0], line[-1]])
		arr1.append(line[-1])
arr1.sort()
t = 0
for i in arr:
	t += len(arr) - bisect(arr1, i[0] - 1)
stdout.write(str(n ** 2 - t))


import bisect
n = int(input())
(a, b) = ([], [])
for _ in range(n):
	(l, *s) = map(int, input().split())
	if sorted(s) == s[::-1]:
		a.append(s[0])
		b.append(s[-1])
a.sort()
count = 0
for val in b:
	count += bisect.bisect(a, val)
print(n ** 2 - count)


def binarySearchCount(arr, n, key):
	left = 0
	right = n
	mid = 0
	while left < right:
		mid = (right + left) // 2
		if arr[mid] == key:
			while mid + 1 < n and arr[mid + 1] == key:
				mid += 1
			break
		elif arr[mid] > key:
			right = mid
		else:
			left = mid + 1
	while mid > -1 and arr[mid] > key:
		mid -= 1
	return mid + 1
n = int(input())
ls = []
for i in range(n):
	a = input().split()
	a[0] = int(a[0])
	for j in range(1, a[0] + 1):
		a[j] = int(a[j])
	minimum = a[1]
	flag = False
	for j in range(2, a[0] + 1):
		if a[j] > minimum:
			flag = True
			break
		else:
			minimum = a[j]
	if flag == False:
		ls.append([a[1], 1])
		ls.append([a[-1], 2])
ls.sort()
ans = 0
count = 0
for i in range(len(ls)):
	if ls[i][1] == 2:
		ans += count
	else:
		count += 1
print(n ** 2 - ans)


(a, b) = ([], [])
(count, s) = (0, 0)
n = int(input())
for i in range(n):
	l = list(map(int, input().split()))
	l = l[1:]
	if sorted(l, reverse=True) == l or min(l) == max(l):
		a.append(l[0])
		b.append(l[len(l) - 1])
	else:
		s += 1
a.sort()
b.sort()
for end in b:
	(lo, hi, ans) = (0, len(a) - 1, len(a))
	while lo <= hi:
		mid = (lo + hi) // 2
		if a[mid] > end:
			ans = mid
			hi = mid - 1
		else:
			lo = mid + 1
	count += n - ans
print(count + s * n)


import sys
readline = sys.stdin.readline
N = int(readline())
M = 10 ** 6 + 5
table1 = [0] * M
table2 = [0] * M
ans = 0
cnt = 0
for _ in range(N):
	(l, *k) = list(map(int, readline().split()))
	if all((k2 - k1 <= 0 for (k1, k2) in zip(k, k[1:]))):
		table1[k[-1]] += 1
		table2[k[0]] += 1
	else:
		cnt += 1
ans = N ** 2 - (N - cnt) ** 2
for i in range(M - 2, -1, -1):
	table2[i] += table2[i + 1]
for i in range(M):
	if not table1[i]:
		continue
	ans += table1[i] * table2[i + 1]
print(ans)


import bisect
from sys import stdin, stdout
read = lambda : map(int, stdin.readline().split())
I = lambda : stdin.readline()
(mins, maxs) = ([], [])
n = int(I())
for _ in range(n):
	(l, *arr) = read()
	ascent = False
	minn = 10 ** 7
	maxx = -1
	for i in arr:
		if minn < i:
			ascent = True
		else:
			minn = i
		if maxx < i:
			maxx = i
	if not ascent:
		mins.append(minn)
		maxs.append(maxx)
maxs.sort()
print(n * n - sum((bisect.bisect_right(maxs, i) for i in mins)))


def main():
	n = int(input())
	s = []
	l = []
	for i in range(n):
		tmps = list(map(int, input().split()))
		l.append(tmps[0])
		s.append(tmps[1:])
	ans = 0
	calc = n
	min_ls = []
	max_ls = []
	for idx in range(n):
		s_t = s[idx]
		maxi = s_t[0]
		mini = s_t[0]
		flag = False
		for i in range(l[idx]):
			if s_t[i] > mini:
				flag = True
				break
			elif s_t[i] < mini:
				mini = s_t[i]
			else:
				pass
		if flag:
			ans += 2 * calc - 1
			calc -= 1
		else:
			min_ls.append(mini)
			max_ls.append(maxi)
	min_ls.sort()
	max_ls.sort()
	prev = 0
	for i in range(calc):
		cur = max_ls[i]
		for j in range(prev, calc):
			if min_ls[j] < cur:
				prev = j + 1
			else:
				break
		ans += prev
	print(ans)
main()


import sys
from collections import deque
from bisect import bisect_right
input = sys.stdin.readline
n = int(input())
min_s = deque([])
max_s = deque([])
good_s = 0
for _ in range(n):
	s = [int(x) for x in input().strip().split()][1:]
	ss_ = float('inf')
	isgood = False
	for ss in s:
		if ss > ss_:
			good_s += 1
			isgood = True
			break
		elif ss < ss_:
			ss_ = ss
	if isgood:
		continue
	min_s.append(min(s))
	max_s.append(max(s))
max_s = sorted(list(max_s))
ans = good_s * n + (n - good_s) * good_s
len_bad_s = len(max_s)
for (i, s) in enumerate(min_s):
	ind = bisect_right(max_s, s)
	ans += len_bad_s - ind
print(ans)


def check(l):
	mini = 1000000
	for i in l:
		if mini >= i:
			mini = i
		else:
			return 1
	return 0
n = int(input())
cnt = 0
fmin = []
fmax = []
m = n
for test in range(n):
	l = list(map(int, input().split()))
	if check(l[1:]):
		cnt = cnt + (2 * (m - 1) + 1)
		m = m - 1
	else:
		fmin.append(min(l[1:]))
		fmax.append(max(l[1:]))
fmin.sort()
fmax.sort()
r = len(fmin) - 1
for i in range(len(fmin) - 1, -1, -1):
	while r >= 0 and fmin[i] < fmax[r]:
		r -= 1
	cnt += len(fmin) - r - 1
print(cnt)


def main():
	import sys
	import bisect
	input = sys.stdin.readline
	N = int(input())
	smin = []
	smax = []
	ok = 0
	for i in range(N):
		l_si = list(map(int, input().split()))
		l = l_si[0]
		si = l_si[1:]
		flg = 0
		prev = 10 ** 9
		for a in si:
			if a > prev:
				flg = 1
				break
			prev = a
		if flg:
			ok += 1
		else:
			smin.append(min(si))
			smax.append(max(si))
	smax.sort()
	ans = ok * N
	for i in smin:
		ans += N - bisect.bisect_left(smax, i + 1)
	print(ans)
main()


import sys
import bisect
RI = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
n = int(ri())
cnt = 0
mina = []
maxa = []
for _ in range(n):
	temp = RI()
	l = temp[0]
	a = temp[1:]
	minn = -1
	maxx = -1
	flag = False
	for i in range(len(a)):
		if a[i] > minn and i != 0:
			flag = True
		if i == 0:
			minn = a[i]
			maxx = a[i]
		else:
			minn = min(minn, a[i])
			maxx = max(maxx, a[i])
	if flag:
		cnt += 1
	else:
		mina.append(minn)
		maxa.append(maxx)
mina.sort()
maxa.sort()
ans = 0
for i in range(len(mina)):
	pos = bisect.bisect_right(maxa, mina[i])
	ans += len(maxa) - pos
temp = n - cnt
ans += cnt * (2 * temp) + cnt * cnt
print(ans)


n = int(input())
small = []
large = []
for i in range(n):
	line = [int(i) for i in input().split()[1:]]
	if line == sorted(line, key=lambda x: -x):
		small.append(line[0])
		large.append(line[-1])
small.sort()
large.sort()
ans = n * n
ptr = 0
for i in range(len(large)):
	while ptr < len(small) and large[i] >= small[ptr]:
		ptr += 1
	ans -= ptr
print(ans)


n = int(input())
first = []
last = []
suc = []
already = 0
for i in range(n):
	lst = list(map(int, input().split()))
	fl = False
	for j in range(1, len(lst) - 1):
		if lst[j + 1] > lst[j]:
			already += 1
			fl = True
			break
	if fl:
		continue
	if len(lst) == 2:
		first.append(lst[1])
		last.append(lst[1])
	else:
		first.append(lst[1])
		last.append(lst[-1])
first.sort()
last.sort()
ans = max(0, already * (n - already) * 2 + already * already)
ptr = 0
for i in range(len(last)):
	while ptr < len(first) and last[i] >= first[ptr]:
		ptr += 1
	ans += len(first) - ptr
print(ans)


n = int(input())
count = 0
a = []
b = []
for _ in range(n):
	num = map(int, input().split())
	num = list(num)
	num = num[1:]
	m = num[0]
	ok = False
	for x in num[1:]:
		if x > m:
			ok = True
			count += 1
			break
		m = x
	if ok == True:
		continue
	a.append(min(num))
	b.append(max(num))
ans = count * n * 2 - count ** 2
i = 0
n -= count
a.sort()
b.sort()
for x in a:
	while i < len(b) and b[i] <= x:
		i += 1
	if i == len(b):
		break
	ans += n - i
print(ans)


import sys
from sys import stdin, stdout
import bisect
import math
import heapq

def modinv(n, p):
	return pow(n, p - 2, p)

def cin():
	return map(int, sin().split())

def ain():
	return list(map(int, sin().split()))

def sin():
	return input()

def inin():
	return int(input())
import math

def Divisors(n):
	l = []
	for i in range(1, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n // i == i:
				l.append(i)
			else:
				l.append(i)
				l.append(n // i)
	return l

def main():
	n = inin()
	a = []
	b = []
	ans = 0
	d = {}
	for i in range(n):
		l = ain()
		l = l[1:]
		xx = 100000000000
		for x in l:
			xx = min(xx, x)
			if x > xx:
				d[i] = 1
				break
		if i not in d:
			a.append(min(l))
		b.append(max(l))
	aa = a[:]
	aa.sort()
	for i in range(n):
		if i in d:
			ans += n
		else:
			x = bisect.bisect_left(aa, b[i])
			ans += x + len(d)
	print(ans)
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			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')
import sys

class ostream:

	def __lshift__(self, a):
		sys.stdout.write(str(a))
		return self
cout = ostream()
endl = '\n'

def readnumbers(zero=0):
	conv = ord if py2 else lambda x: x
	A = []
	numb = zero
	sign = 1
	i = 0
	s = sys.stdin.buffer.read()
	try:
		while True:
			if s[i] >= b'0'[0]:
				numb = 10 * numb + conv(s[i]) - 48
			elif s[i] == b'-'[0]:
				sign = -1
			elif s[i] != b'\r'[0]:
				A.append(sign * numb)
				numb = zero
				sign = 1
			i += 1
	except:
		pass
	if s and s[-1] >= b'0'[0]:
		A.append(sign * numb)
	return A
main()


n = int(input())
M = []
m = []
good = 0
for i in range(n):
	(l, *s) = map(int, input().split())
	if s == sorted(s)[::-1]:
		M.append(s[0])
		m.append(s[-1])
	else:
		good += 1
ans = good ** 2 + good * (n - good) * 2
M.sort(reverse=True)
m.sort(reverse=True)
c = n - good
p = 0
for k in M:
	while k <= m[p] and c >= 1:
		c -= 1
		p += 1
		if c == 0:
			break
	if c == 0:
		break
	ans += c
print(ans)


import atexit
import io
import sys
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER

@atexit.register
def write():
	sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())

def num():
	return int(input())

def line():
	return map(int, input().split())
from itertools import repeat, tee
from bisect import bisect, insort

def pairwise(it):
	(a, b) = tee(it)
	next(b)
	return zip(a, b)

def has_up(s):
	return any((x < y for (x, y) in pairwise(s)))
n = num()
ss = (list(line())[1:] for _ in repeat(None, n))
with_up = 0
mns = []
mxs = []
for s in ss:
	if has_up(s):
		with_up += 1
	else:
		mns.append(min(s))
		insort(mxs, max(s))
count = 0
h = n - with_up
for mn in mns:
	count += h - bisect(mxs, mn)
count += with_up * h * 2 + with_up * with_up
print(count)


n = int(input())
a = []
c = []
k = n
q = 0
ans = 0
for i in range(n):
	b = [int(x) for x in input().split()]
	b = b[1:]
	if min(b) == max(b):
		a.append(b[0])
		c.append(b[0])
		continue
	if b[::-1] != sorted(b):
		ans += 2 * k - 1
		k -= 1
	else:
		a.append(b[0])
		c.append(b[-1])
a = sorted(a)
c = sorted(c)
j = 0
a.append(1000000000)
for i in c:
	while a[j] <= i:
		j += 1
	ans += k - j
print(ans)


import bisect as b
import sys
input = sys.stdin.readline
n = int(input())
l = [list(map(int, input().split())) for i in range(n)]
cl = [False] * n
ocnt = 0
for i in range(n):
	for j in range(l[i][0] - 1):
		if l[i][j + 1] < l[i][j + 2]:
			cl[i] = True
			ocnt += 1
			break
M = [max(l[i][1:]) if not cl[i] else -1 for i in range(n)]
m = [min(l[i][1:]) for i in range(n)]
M.sort()
ans = 0
for i in range(n):
	if cl[i]:
		ans += n
		continue
	ans += n - b.bisect_right(M, m[i])
print(ans + n * ocnt - ocnt ** 2)


import sys
import collections
from collections import Counter, deque
import itertools
import math
import timeit
import random

def sieve(n):
	if n < 2:
		return list()
	prime = [True for _ in range(n + 1)]
	p = 3
	while p * p <= n:
		if prime[p]:
			for i in range(p * 2, n + 1, p):
				prime[i] = False
		p += 2
	r = [2]
	for p in range(3, n + 1, 2):
		if prime[p]:
			r.append(p)
	return r

def divs(n, start=1):
	divisors = []
	for i in range(start, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				divisors.append(i)
			else:
				divisors.extend([i, n // i])
	return divisors

def divn(n, primes):
	divs_number = 1
	for i in primes:
		if n == 1:
			return divs_number
		t = 1
		while n % i == 0:
			t += 1
			n //= i
		divs_number *= t

def flin(d, x, default=-1):
	left = right = -1
	for i in range(len(d)):
		if d[i] == x:
			if left == -1:
				left = i
			right = i
	if left == -1:
		return (default, default)
	else:
		return (left, right)

def ceil(n, k):
	return n // k + (n % k != 0)

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

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

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

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

def prr(a, sep=' '):
	print(sep.join(map(str, a)))

def dd():
	return collections.defaultdict(int)

def ddl():
	return collections.defaultdict(list)

def upper_bound(a, p, l, r):
	ans = -1
	while l <= r:
		mid = l + (r - l) // 2
		if a[mid] > p:
			ans = mid
			r = mid - 1
		else:
			l = mid + 1
	return ans

def good(d):
	for i in range(1, len(d)):
		if d[i] > d[i - 1]:
			return True
	return False
n = ii()
dmin = []
dmax = []
res = 0
g = 0
for i in range(n):
	t = li()[1:]
	if good(t):
		res += n
		g += 1
		continue
	dmin.append(min(t))
	dmax.append(max(t))
dmax.sort()
for el in dmin:
	p = upper_bound(dmax, el, l=0, r=len(dmax) - 1)
	if p != -1:
		res += len(dmax) - p
	res += g
print(res)


n = int(input())
(mini, maxi, asc, nasc) = ([], [], 0, 0)
while n > 0:
	s = list(map(int, input().split()))[1:]
	for i in range(len(s)):
		if i > 0 and s[i] > s[i - 1]:
			asc += 1
			break
		elif i == len(s) - 1:
			nasc += 1
			mini.append(min(s))
			maxi.append(max(s))
	n -= 1
total = asc * asc + 2 * asc * nasc
mini.sort()
maxi.sort()
i = 0
for x in maxi:
	while i < nasc and mini[i] < x:
		i += 1
	total += i
print(total)


from bisect import bisect_right
n = int(input())
mi = []
ma = []
flg = [False] * n
flg2 = [False] * n
cnt = 0
for i in range(n):
	(k, *a) = map(int, input().split())
	m = 0
	q = float('inf')
	for j in range(k - 1, -1, -1):
		q = min(q, a[j])
		if m <= a[j]:
			m = a[j]
		else:
			flg[i] = True
			break
	else:
		mi.append(q)
		ma.append(m)
		if q == m:
			flg2[i] = True
ma.sort()
ans = 0
cnt = flg.count(True)
for i in range(n):
	if flg[i]:
		ans += n
	else:
		ans += cnt
for (i, x) in enumerate(mi):
	ans += n - bisect_right(ma, x) - cnt
print(ans)


from bisect import *

def main():
	m = int(input())
	(a, c, ans) = ([], [], 0)
	for i in range(m):
		(b, f) = (list(map(int, input().split())), 1)
		for j in range(1, len(b) - 1):
			if b[j + 1] > b[j]:
				f = 0
				break
		if f:
			a.append(b[1])
			c.append(b[-1])
	a.sort()
	for i in c:
		x = bisect_right(a, i)
		ans += x
	print(m * m - ans)
main()


sequencias = int(input())
cont = 0
cresc = 0
ncresc = 0
maxi = []
mini = []
for x in range(sequencias):
	sequencia = str(input()).split()
	s = sequencia[1:]
	sint = [int(p) for p in s]
	for y in range(len(sint)):
		if y > 0 and sint[y] > sint[y - 1]:
			cresc += 1
			break
		elif y == len(sint) - 1:
			maxi.append(max(sint))
			mini.append(min(sint))
			ncresc += 1
cont = cresc * cresc + cresc * ncresc * 2
mini.sort()
maxi.sort()
h = 0
for g in range(len(maxi)):
	while h < ncresc and int(mini[h]) < int(maxi[g]):
		h += 1
	cont += h
print(cont)


N = int(input())
L = []
for i in range(N):
	k = input().split()
	k[0] = int(k[0])
	for j in range(1, k[0] + 1):
		k[j] = int(k[j])
	lo = k[1]
	c = 0
	for j in range(2, k[0] + 1):
		if k[j] > lo:
			c = 1
			break
		else:
			lo = k[j]
	if c == 0:
		L.append([k[1], 1])
		L.append([k[-1], 2])
L.sort()
x = ctr = 0
for i in range(len(L)):
	if L[i][1] == 2:
		x += ctr
	else:
		ctr += 1
print(N ** 2 - x)


def bin_search(array, elem):
	left = -1
	right = len(array)
	while right - left > 1:
		middle = (right + left) // 2
		if array[middle] > elem:
			right = middle
		else:
			left = middle
	return right
n = int(input())
arrays = []
up = [0] * n
lasts = []
for i in range(n):
	array = [int(s) for s in input().split()][1:]
	for j in range(1, len(array)):
		if array[j] > array[j - 1]:
			up[i] = 1
			break
	arrays.append(array)
ans = sum(up) * n
firsts = []
for i in range(len(arrays)):
	if up[i] == 0:
		firsts.append(arrays[i][0])
firsts = sorted(firsts)
for i in range(len(arrays)):
	if up[i] == 0:
		idx = bin_search(firsts, arrays[i][-1])
		ans += n - idx
print(ans)


n = int(input())
l = []
s = []
for _ in range(n):
	(li, *si) = map(int, input().split())
	l.append(li)
	s.append(si)

def hasAscent(s):
	result = False
	min_i = s[0]
	max_i = s[0]
	for i in s:
		if i <= min_i:
			min_i = i
		else:
			result = True
		max_i = max(max_i, i)
	return (result, min_i, max_i)
hasAscentList = []
notHasAscentList = []
min_i_list = []
max_i_list = []
for si in s:
	(result, min_i, max_i) = hasAscent(si)
	if result:
		hasAscentList.append((min_i, max_i))
	else:
		notHasAscentList.append((min_i, max_i))
		min_i_list.append(min_i)
		max_i_list.append(max_i)
max_i_list.sort()
ans = 0
ans += len(hasAscentList) * len(hasAscentList)
ans += len(hasAscentList) * len(notHasAscentList)
ans += len(notHasAscentList) * len(hasAscentList)
import bisect
for (min_i, max_i) in notHasAscentList:
	ans += len(notHasAscentList) - bisect.bisect_right(max_i_list, min_i)
print(ans)


n = int(input())
p = 0
pp = 0
mini = []
a = []
import bisect
for i in range(n):
	l = [int(x) for x in input().split()]
	d = l[1:]
	l = int(l[0])
	if d != sorted(d, reverse=True):
		pp += 1
		continue
	mini.append(min(d))
	a.append(d)
mini.sort()
for j in range(len(a)):
	mi = max(a[j])
	g = bisect.bisect_left(mini, mi)
	p += g
h = 2 * n - 1
for i in range(pp):
	p += h
	h -= 2
print(p)


from bisect import *
n = int(input())
(a, b) = ([], [])
for _ in [0] * n:
	(l, *s) = map(int, input().split())
	if all((x >= y for (x, y) in zip(s, s[1:]))):
		a += (s[0],)
		b += (s[-1],)
a.sort()
print(n * n - sum((bisect(a, x) for x in b)))


num_de_sequencias = int(input())
pequenos = []
grandes = []
aux1 = 0
for i in range(num_de_sequencias):
	sequencia = list(map(int, input().split()))
	tamanho = sequencia[0]
	pequeno = 10000000
	grande = 0
	flag = False
	for j in range(1, tamanho + 1):
		if j > 1 and sequencia[j] > pequeno and (not flag):
			aux1 += 1
			flag = True
		pequeno = min(pequeno, sequencia[j])
		grande = max(grande, sequencia[j])
	if not flag:
		pequenos.append(pequeno)
		grandes.append(grande)
pequenos.append(10000000)
pequenos.sort()
grandes.sort()
cont = 0
aux2 = 0
for i in range(len(grandes)):
	while pequenos[aux2] < grandes[i] and aux2 < len(pequenos):
		aux2 += 1
	cont += aux2
print(aux1 * aux1 + 2 * (num_de_sequencias - aux1) * aux1 + cont)


from bisect import bisect_left as bl, bisect_right as br

def chk(x):
	l = len(x)
	mi = 10 ** 9
	for i in x:
		if i > mi:
			return 1
		mi = min(i, mi)
	return 0
n = int(input())
a = []
b = []
ans = 0
for i in range(n):
	x = list(map(int, input().split()))
	x = x[1:]
	if chk(x):
		ans += 2 * n - 1
		n -= 1
	else:
		a.append(max(x))
		b.append(min(x))
a.sort()
b.sort()
for i in a:
	ans += bl(b, i)
print(ans)


maxa = [0] * (10 ** 6 + 2)
seq_mins = []
a = 0
for _ in range(int(input())):
	s = list(map(int, input().split()))
	notAscent = True
	(minm, maxm) = (s[1], s[1])
	for k in s[2:]:
		minm = min(minm, k)
		maxm = max(maxm, k)
		if notAscent and minm < k:
			notAscent = False
	if notAscent:
		maxa[maxm] += 1
		seq_mins.append(minm)
	else:
		a += 1
for i in range(1, 10 ** 6 + 2):
	maxa[i] += maxa[i - 1]
c = 2 * a * maxa[-1] + a * a
for mi in seq_mins:
	c += maxa[-1] - maxa[mi]
print(c)


from bisect import *
n = int(input())
low = []
high = []
ans = 0
e = 0
c = 0
for _ in range(n):
	t = list(map(int, input().split()))
	s = t[0]
	a = t[1:]
	if a == sorted(a, reverse=True):
		low.append(a[s - 1])
		high.append(a[0])
		e += 1
	else:
		ans += 2 * n - 1 - 2 * c
		c += 1
low.sort()
for i in high:
	ans += bisect_right(low, i - 1)
print(ans)


import sys

class BNewYearAndAscentSequence:

	def solve(self):
		from bisect import bisect_right
		n = int(input())
		seq = []
		mins = []
		maxes = []
		already = [0] * n
		for i in range(n):
			line = [int(_) for _ in input().split()][1:]
			sorted_line = sorted(line, reverse=True)
			if sorted_line != line:
				already[i] = 1
				continue
			seq.append(line)
			mins.append([min(line), i])
			maxes.append([max(line), i])
		mins.sort()
		maxes.sort()
		s = sum(already)
		ans = s * s
		l = len(seq)
		for i in range(l):
			ans += 2 * s
			ind = bisect_right(maxes, [mins[i][0], float('inf')])
			ans += l - 1 - ind + 1
		print(ans)
solver = BNewYearAndAscentSequence()
input = sys.stdin.readline
solver.solve()


from bisect import bisect, insort
from sys import stdin, stdout
n = int(stdin.readline())
(a, b) = ([], [])
for _ in [0] * n:
	(l, *s) = map(int, stdin.readline().split())
	if all((s[i] >= s[i + 1] for i in range(len(s) - 1))):
		insort(a, s[0])
		(b.append(s[-1]),)
stdout.write(str(n * n - sum((bisect(a, x) for x in b))))


def search(arr, num):
	(l, r) = (0, len(arr) - 1)
	while l <= r:
		mid = (l + r) // 2
		if arr[mid] <= num:
			l = mid + 1
		else:
			r = mid - 1
	return l
import sys
t = int(sys.stdin.readline())
(mini, maxi) = ([], [])
count = 0
ans = 0
for _ in range(t):
	l = list(map(int, sys.stdin.readline().split()))[1:]
	z = True
	for i in range(len(l) - 1):
		if l[i + 1] > l[i]:
			ans += 2 * t - 1
			count += 1
			z = False
			break
	if z:
		mini.append(min(l))
		maxi.append(max(l))
maxi.sort()
n = len(maxi)
ans -= count * (count - 1)
for i in range(n):
	a = search(maxi, mini[i])
	if a < n:
		ans += n - a
	elif a == 0:
		ans += n
print(ans)


n = int(input())
ans = 0
mins = []
maxes = []
good = 0
for _ in range(n):
	a = list(map(int, input().split()))[1:]
	for j in range(1, len(a)):
		if a[j] > a[j - 1]:
			ans += 2 * n
			good += 1
			break
	else:
		mins.append(min(a))
		maxes.append(max(a))
ans -= good ** 2
mins.sort()
maxes.sort()
k = len(maxes)
j = 0
for i in range(len(mins)):
	while j < k and maxes[j] <= mins[i]:
		j += 1
	ans += k - j
print(ans)


from bisect import bisect_left as bl
from bisect import bisect_right as br
import heapq
import math
from collections import *
from functools import reduce, cmp_to_key
import sys
input = sys.stdin.readline

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

def li():
	return [int(i) for i in input().rstrip('\n').split(' ')]

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

def val():
	return int(input().rstrip('\n'))

def li2():
	return [i for i in input().rstrip('\n').split(' ')]

def li3():
	return [int(i) for i in input().rstrip('\n')]
n = val()
l = []
for i in range(n):
	l.append(li()[1:])
d = {}
minmax = []
for (ind, i) in enumerate(l):
	(currmin, currmax) = (i[0], i[0])
	d[ind] = 0
	for j in i:
		if j > currmin:
			d[ind] = 1
		currmin = min(currmin, j)
		currmax = max(currmax, j)
	if not d[ind]:
		minmax.append([currmin, currmax])
(maxlen, minlen) = (sorted([i[1] for i in minmax]), sorted([i[0] for i in minmax]))
tot = 0
for i in range(len(minmax)):
	tot += len(minmax) - br(maxlen, minmax[i][0])
curr = 0
for i in range(len(l)):
	if d[i]:
		tot += (len(l) - curr) * 2 - 1
		curr += 1
print(tot)


from collections import Counter, defaultdict, deque
from heapq import heappop, heappush, heapify
import sys, bisect, math, itertools, pprint, fractions
sys.setrecursionlimit(10 ** 8)
mod = 10 ** 9 + 7
mod2 = 998244353
INF = float('inf')

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

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

def inpln(n):
	return list((int(sys.stdin.readline()) for i in range(n)))
n = inp()
mx = []
data = [0] * n
t_cnt = 0
for i in range(n):
	a = inpl()
	for j in range(a[0] - 1):
		if a[j + 2] > a[j + 1]:
			flag = True
			t_cnt += 1
			break
	else:
		flag = False
	if not flag:
		mx.append(max(a[1:]))
	data[i] = [flag, min(a[1:])]
mx.sort()
l = len(mx)
res = 0
for (i, d) in enumerate(data):
	if d[0]:
		res += n
		continue
	res += t_cnt + l - bisect.bisect_left(mx, d[1] + 1)
print(res)


n = int(input())
ls = []
for i in range(n):
	a = input().split()
	a[0] = int(a[0])
	for j in range(1, a[0] + 1):
		a[j] = int(a[j])
	minimum = a[1]
	flag = False
	for j in range(2, a[0] + 1):
		if a[j] > minimum:
			flag = True
			break
		else:
			minimum = a[j]
	if flag == False:
		ls.append([a[1], 1])
		ls.append([a[-1], 2])
ls.sort()
ans = 0
count = 0
for i in range(len(ls)):
	if ls[i][1] == 2:
		ans += count
	else:
		count += 1
print(n ** 2 - ans)


n = int(input())
lis = []
allok = 0
maxlis = []
minlis = []
for i in range(n):
	s = list(map(int, input().split()))
	flag = True
	for j in range(s[0]):
		j += 1
		if j == 1:
			nmin = s[j]
			nmax = s[j]
		elif nmin < s[j]:
			flag = False
			break
		else:
			nmin = min(nmin, s[j])
			nmax = max(nmax, s[j])
	if flag:
		minlis.append(nmin)
		maxlis.append(nmax)
	else:
		allok += 1
ans = 0
ans += allok * allok + 2 * allok * (n - allok)
minlis.sort()
maxlis.sort()
minlis.reverse()
maxlis.reverse()
maxlis.append(float('-inf'))
maxind = 0
for i in minlis:
	while i < maxlis[maxind]:
		maxind += 1
	ans += maxind
print(ans)


n = int(input())
ngoes = []
goes = 0
for i in range(n):
	A = list(map(int, input().split()))
	l = A.pop(0)
	mini = 0
	f = 1
	for j in range(len(A)):
		if A[j] < A[mini]:
			mini = j
		if A[j] > A[mini]:
			goes += 1
			f = 0
			break
	if f:
		ngoes.append((min(A), max(A)))
ans = goes * n
maxs = sorted(ngoes, key=lambda x: x[1])
for el in ngoes:
	L = -1
	R = len(ngoes)
	while R - L > 1:
		m = (R + L) // 2
		if el[0] < maxs[m][1]:
			R = m
		else:
			L = m
	ans += n - R
print(ans)


from bisect import bisect
from sys import stdin

def main():
	input = lambda : stdin.readline()[:-1]
	N = int(input())
	LS = [tuple(map(int, input().split())) for _ in [0] * N]
	n = N
	ans = 0
	(min_, max_) = ([], [])
	for ls in LS:
		for i in range(1, ls[0]):
			if ls[i] < ls[i + 1]:
				ans += n * 2 - 1
				n -= 1
				break
		else:
			min_.append(min(ls[1:]))
			max_.append(max(ls[1:]))
	min_.sort()
	max_.sort()
	for i in min_:
		j = bisect(max_, i)
		ans += n - j
	print(ans)
main()


numberSequences = int(input())
(mini, maxi, numberSequencesWithAscention, numberSequencesWithoutAscention) = ([], [], 0, 0)
for i in range(numberSequences):
	currentSequenceString = input().split()[1:]
	currentSequence = []
	for e in currentSequenceString:
		currentSequence.append(int(e))
	for j in range(len(currentSequence)):
		if j > 0 and currentSequence[j] > currentSequence[j - 1]:
			numberSequencesWithAscention += 1
			break
		elif j == len(currentSequence) - 1:
			numberSequencesWithoutAscention += 1
			mini.append(min(currentSequence))
			maxi.append(max(currentSequence))
answer = numberSequencesWithAscention * numberSequencesWithAscention + 2 * numberSequencesWithAscention * numberSequencesWithoutAscention
mini.sort()
maxi.sort()
j = 0
for i in range(len(maxi)):
	while j < numberSequencesWithoutAscention and mini[j] < maxi[i]:
		j += 1
	answer += j
print(answer)


n = int(input())
(a, head, tail, l, pointer, point, ans) = (0, list(), list(), [0] * 1000001, 0, 0, 0)
for i2 in range(n):
	x = list(map(int, input().split()))
	(check, ans) = (0, 0)
	for i in range(1, x[0] + 1):
		if i > 1 and x[i] > x[i - 1]:
			a += 1
			break
		if i == x[0]:
			head.append(x[1])
			tail.append(x[i])
head.sort()
tail.sort()
for i in range(len(head)):
	while pointer < len(tail) and head[i] > tail[pointer]:
		point += 1
		pointer += 1
	ans += point
ans += a + 2 * a * (n - a) + 2 * (a * (a - 1) / 2)
print(int(ans))


import bisect
n = int(input())
lu = []
mim = []
mam = []
lu = 0
for i in range(n):
	t = list(map(int, input().split()))[1:]
	ma = 0
	mi = 10 ** 6
	l = 0
	for j in t:
		if ma < j:
			ma = j
		if mi > j:
			mi = j
		if j > mi:
			l += 1
			break
	if l == 0:
		mim.append(mi)
		mam.append(ma)
	else:
		lu += 1
s = 0
mim.sort()
mam.sort()
for i in range(len(mim)):
	s += n - bisect.bisect_right(mam, mim[i])
print(s + lu * n)


mx = []
mn = []
n = int(input())
c = 0

def f(ar, target, end):
	start = 0
	ans = -1
	while start <= end:
		mid = (start + end) // 2
		if ar[mid] <= target:
			start = mid + 1
		else:
			ans = mid
			end = mid - 1
	return ans

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 i in range(n):
	a = list(map(int, input().split()))
	an = 0
	for j in range(2, a[0] + 1):
		if a[j] > a[j - 1]:
			an = 1
			c += 1
			break
	if an == 0:
		mx.append(max(a[1:]))
		mn.append(min(a[1:]))
ans = c * n
mx.sort()
for i in range(len(mn)):
	ind = countGreater(mx, len(mx), mn[i])
	ans += c
	ans += ind
print(ans)


from sys import stdin
input = stdin.readline
n = int(input())
seq = []
pyk = [0] * n
bds = []
asc = n
for i in range(n):
	l = list(map(int, input().split()))
	for j in range(2, l[0] + 1):
		if l[j] > l[j - 1]:
			pyk[i] = 1
			break
	if pyk[i] == 0:
		asc -= 1
		bds.append([min(l[1:]), max(l[1:])])
wyn = n ** 2 - (n - asc) ** 2
k = len(bds)
le = [bds[i][0] for i in range(k)]
pra = [bds[i][1] for i in range(k)]
le.sort()
pra.sort()
p = 0
for l in range(k):
	while p < k:
		if pra[p] <= le[l]:
			p += 1
		else:
			break
	if p == k:
		break
	wyn += k - p
print(wyn)


from bisect import bisect_left
input = __import__('sys').stdin.readline
n = int(input())
ls = []
rs = []
ans = 0
vosses = 0
for _ in range(n):
	s = [*map(int, input().split())][1:]
	cmn = float('inf')
	vos = 0
	for i in s:
		cmn = min(cmn, i)
		if i > cmn:
			vos = 1
			break
	if vos:
		vosses += 1
	else:
		ls += (s[-1],)
		rs += (s[0],)
ans += vosses * n
ls.sort()
rs.sort()
i = 0
for j in range(len(rs)):
	ans += bisect_left(ls, rs[j]) + vosses
print(ans)


max_list = [0] * 1000001
min_list = list()
check_count = 0
result = 0
n = int(input())
process_list = [n] * 1000001
for _ in range(n):
	data = list(map(int, input().split()))
	length = data[0]
	min_value = data[1]
	max_value = data[1]
	check = False
	for i in data[1:]:
		if min_value < i:
			check = True
		if i < min_value:
			min_value = i
		if max_value < i:
			max_value = i
	if check:
		check_count += 1
	else:
		max_list[max_value] += 1
		min_list.append(min_value)
count = check_count
for i in range(1000001):
	count += max_list[i]
	process_list[i] -= count
result += n * check_count
result += (n - check_count) * check_count
for i in min_list:
	result += process_list[i]
print(result)


from sys import stdin
input = stdin.readline
n = int(input())
arr = list((list(map(int, input().split()))[1:] for _ in range(n)))
(res, c) = (0, 0)
(all_min, all_max) = ([], [])
for i in range(n):
	maxi = max(arr[i])
	mini = min(arr[i])
	valid = False
	for j in range(1, len(arr[i])):
		if arr[i][j] > arr[i][j - 1]:
			valid = True
	if valid:
		res += 2 * (n - c) - 1
		c += 1
	else:
		all_max.append(maxi)
		all_min.append(mini)

def binary_search(k):
	(l, r) = (0, len(all_min) - 1)
	while l <= r:
		mid = l + r >> 1
		if all_max[mid] <= k:
			l = mid + 1
		else:
			r = mid - 1
	return l
all_max.sort()
all_min.sort()
for i in range(len(all_min)):
	res += len(all_max) - binary_search(all_min[i])
print(res)


import sys
import math
input = sys.stdin.readline
n = int(input())

def check(arr):
	for i in range(1, len(arr)):
		if arr[i - 1] < arr[i]:
			return False
	return True
nonincr = 0
ones = 0
first = list()
last = list()
for i in range(n):
	arr = list(map(int, input().split()))
	if len(arr) == 2:
		ones += 1
		nonincr += 1
		first.append(arr[1])
		last.append(arr[-1])
	elif check(arr[1:]) == True:
		nonincr += 1
		first.append(arr[1])
		last.append(arr[-1])
first.sort()
last.sort()
ans = n * n
indi = [0] * 1000001
for i in range(len(first)):
	indi[first[i]] += 1
for i in range(1, 1000001):
	indi[i] += indi[i - 1]
for i in range(len(last)):
	ans -= indi[last[i]]
print(ans)


def absent(a):
	i = 0
	n = len(a)
	while i < n - 1:
		if a[i] < a[i + 1]:
			return True
		i += 1
	return False
n = int(input())
s = []
for _ in range(n):
	s.append(list(map(int, input().split()))[1:])
A = []
ab_c = 0
for seq in s:
	if absent(seq):
		ab_c += 1
	else:
		A.append((seq[0], seq[-1]))
A = sorted(A, reverse=True)
nab_c = 0
for i in range(len(A)):
	(L, R) = (0, len(A) - 1)
	x = -1
	while L <= R:
		M = (L + R) // 2
		if A[M][0] <= A[i][1]:
			R = M - 1
		else:
			x = M
			L = M + 1
	nab_c += max(0, x + 1)
x = ab_c
print(2 * n * x - x * x + nab_c)


n = int(input())
nomin = []
nomax = []
for i in range(n):
	temp = list(map(int, input().split()))
	num = temp.pop(0)
	flag = 1
	for j in range(num - 1):
		if temp[j] < temp[j + 1]:
			flag = 0
			continue
	if flag == 1:
		nomin.append(temp[-1])
		nomax.append(temp[0])
nomax.sort()
wa = 0
import bisect
for i in nomin:
	a = bisect.bisect_right(nomax, i)
	wa += a
print(n ** 2 - wa)


n = int(input())
s = []
for _ in range(n):
	s.append(list(map(int, input().split()))[1:])
ascent_count = 0
no_ascent = []
for seq in s:
	ascent = False
	for i in range(len(seq) - 1):
		if seq[i] < seq[i + 1]:
			ascent_count += 1
			break
	else:
		no_ascent.append((seq[-1], seq[0]))
ans = ascent_count * (2 * n - ascent_count)
no_ascent.sort()
for (mi, ma) in no_ascent:
	left = 0
	right = len(no_ascent)
	while left < right:
		mid = (left + right) // 2
		if no_ascent[mid][0] < ma:
			left = mid + 1
		else:
			right = mid
	ans += right
print(ans)


n = int(input())
first = []
last = []
suc = []
already = 0
for i in range(n):
	line = [int(i) for i in input().split()[1:]]
	if line == sorted(line, key=lambda x: -x):
		first.append(line[0])
		last.append(line[-1])
	else:
		already += 1
first.sort()
last.sort()
ans = max(0, already * (n - already) * 2 + already * already)
ptr = 0
for i in range(len(last)):
	while ptr < len(first) and last[i] >= first[ptr]:
		ptr += 1
	ans += len(first) - ptr
print(ans)


import bisect

def hasAscent(l):
	for i in range(1, len(l) - 1):
		if l[i] < l[i + 1]:
			return 1
	return 0
n = int(input())
non_ascent = []
ascent = 0
minimas = []
maximas = []
for j in range(n):
	l1 = list(map(int, input().split()))
	if hasAscent(l1):
		ascent += 1
	else:
		minimas.append(min(l1[1:]))
		maximas.append(max(l1[1:]))
maximas.sort()
ans = int(2 * n * ascent - ascent ** 2)
for num in minimas:
	ind = bisect.bisect_right(maximas, num)
	ans += len(maximas) - ind
print(ans)


n = int(input())
maxValues = []
minValues = []
size = 0
for i in range(n):
	l = list(map(int, input().split()))
	(maxValue, minValue) = (l[1], l[1])
	flag = True
	for j in range(1, l[0] + 1):
		maxValue = max(maxValue, l[j])
		minValue = min(minValue, l[j])
		if minValue < l[j]:
			flag = False
	if flag:
		maxValues.append(maxValue)
		minValues.append(minValue)
		size += 1
maxValues = sorted(maxValues)
minValues = sorted(minValues)
res = (n * size - size * size) * 2 + (n - size) ** 2
(i, count) = (0, 0)
while i < size and count < size:
	if maxValues[count] <= minValues[i]:
		count += 1
		res += i
	else:
		i += 1
res += (size - count) * i
print(res)


import sys

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

def mint():
	return int(minp())

def mints():
	return map(int, minp().split())

def solve():
	n = mint()
	a = [0] * int(1000000.0 + 1)
	b = [0] * int(1000000.0 + 1)
	for i in range(n):
		z = mints()
		next(z)
		z = list(z)
		w = sorted(z, reverse=True)
		if w == z:
			a[w[-1]] += 1
			b[w[0]] += 1
	r = 0
	for i in range(1, int(1000000.0 + 1)):
		b[i] += b[i - 1]
		r += b[i] * a[i]
	r += b[0] * a[0]
	print(n * n - r)
solve()


def binary(x):
	first = 0
	last = len(maxi) - 1
	while first <= last:
		mid = (first + last) // 2
		if maxi[mid] <= x:
			first = mid + 1
		else:
			last = mid - 1
	return mid
n = int(input())
tots = 0
count = 0
temp = n
mini = [] * n
maxi = [] * n
for i in range(n):
	a1 = list(map(int, input().split()))
	a = a1[1:]
	maxi.append(max(a))
	mini.append(min(a))
	for j in range(0, len(a) - 1):
		if a[j] < a[j + 1]:
			tots = tots + 2 * (temp - 1) + 1
			temp -= 1
			maxi.pop()
			mini.pop()
			break
mini.sort()
maxi.sort()
for u in mini:
	b = binary(u)
	if maxi[b] > u:
		b -= 1
	tots += len(maxi) - b - 1
print(tots)


import bisect

def ascent(a):
	n = len(a)
	for i in range(1, n):
		if a[i - 1] < a[i]:
			return 1
	return 0
n = int(input())
a = []
first = []
last = []
for _ in range(n):
	arr = [int(i) for i in input().split()]
	arr = arr[1:]
	a.append(arr)
	if not ascent(arr):
		first.append(arr[0])
		last.append(arr[-1])
first.sort()
count = n ** 2
for x in last:
	count -= bisect.bisect(first, x)
print(count)


n = int(input())
mn = []
pos = [0] * 1000005
dp = [0] * 1000005
ans = 0
gg = 0
for i in range(n):
	s = [int(x) for x in input().split()]
	s = s[1:]
	a1 = min(s)
	a2 = max(s)
	kx = -1
	flag = 0
	for j in range(len(s) - 1, -1, -1):
		if s[j] < kx:
			flag = 1
			break
		kx = max(kx, s[j])
	if flag == 0:
		mn.append(a1)
		pos[a2] += 1
	else:
		ans = ans + 2 * n - 1
		gg += 1
c = 0
for i in range(len(pos) - 1, -1, -1):
	dp[i] = c
	c += pos[i]
for i in range(0, len(mn)):
	ans += dp[mn[i]]
if gg > 0:
	ans = ans - gg * (gg - 1)
print(ans)


n = int(input())
f = 0
sx = []
ex = []
for i in range(n):
	x = list(map(int, input().split()))[1:]
	g = 0
	for i in range(1, len(x)):
		if x[i] > x[i - 1]:
			f += 1
			g = 1
			break
	if g == 0:
		sx.append(min(x))
		ex.append(max(x))
x = len(sx)
ans = f * n
sx.sort()
ex.sort()
for i in range(x):
	m = sx[i]
	start = 0
	end = x - 1
	an = -1
	while start <= end:
		mid = (start + end) // 2
		if ex[mid] > m:
			an = mid
			end = mid - 1
		else:
			start = mid + 1
	if an != -1:
		ans += x - an + f
	else:
		ans += f
print(ans)


n = int(input())
s = []
for i in range(n):
	s.append(list(map(int, input().split()))[1:])
f = sorted([e for e in s if e == sorted(e, reverse=True)], key=lambda x: -x[0])
l = sorted(f[:], key=lambda x: -x[-1])
q = ans = 0
for e in l:
	while q < len(f) and e[-1] < f[q][0]:
		q += 1
	ans += len(f) - q
print(n * n - ans)


def has_inc(l):
	for i in range(len(l) - 1):
		if l[i] < l[i + 1]:
			return True
	return False
n = int(input())
(mins, maxs) = ([], [])
has_incr = 0
for i in range(n):
	s = list(map(int, input().split(' ')))[1:]
	decres = has_inc(s)
	has_incr += decres
	if not decres:
		mins.append(s[-1])
		maxs.append(s[0])
mins = sorted(mins)
maxs = sorted(maxs)
left = 0
ans = 0
for elem in maxs:
	while left < len(maxs) and mins[left] < elem:
		left += 1
	ans += left
print(ans + (2 * n - has_incr) * has_incr)


n = int(input())
l = [list(map(int, input().split()[1:])) for _ in range(n)]

def check(i):
	for j in range(len(i) - 1):
		if i[j] < i[j + 1]:
			return True
	return False
h = [check(i) for i in l]
a = [(min(i), max(i)) for i in l]
d = sorted(((a[i][j], j, i) for i in range(n) if not h[i] for j in range(2)), reverse=True)
c = 0
ans = h.count(True)
ans = ans * n * 2 - ans ** 2
i = 0
while i < len(d):
	u = d[i][0]
	j = i
	p = c
	while j < len(d) and d[j][0] == u:
		t = d[j][1]
		if t == 1:
			c += 1
		else:
			ans += p
		j += 1
	i = j
print(ans)


import bisect
t = int(input())
minarr = []
maxarr = []
total = t * t
for test in range(t):
	a = list(map(int, input().split()))
	b = a[0]
	a = a[1:]
	c = sorted(a, reverse=True)
	if c == a:
		maxarr.append(a[0])
		minarr.append(a[b - 1])
maxarr.sort()
lenm = len(minarr)
for i in range(len(minarr)):
	index = bisect.bisect(maxarr, minarr[i])
	if index == lenm:
		total -= index
	elif maxarr[index] == minarr[i]:
		total -= index + 1
	else:
		total -= index
print(total)


from sys import stdin, stderr

def rl():
	return [int(w) for w in stdin.readline().split()]
(n,) = rl()
xs = []
R = 0
for _ in range(n):
	(l, *s) = rl()
	ss = sorted(s, reverse=True)
	if s == ss:
		xs.append((s[-1], 0))
		xs.append((s[0] - 1, 1))
	else:
		R += n
xs.sort()
r = n
for (x, t) in xs:
	if t == 1:
		r -= 1
	else:
		R += r
print(R)


def lower_bound_index_lr(seq, num, l, r):
	if l == r:
		return l
	mid = (l + r) // 2
	if seq[mid] >= num:
		return lower_bound_index_lr(seq, num, l, mid)
	else:
		return lower_bound_index_lr(seq, num, mid + 1, r)

def lower_bound_index(seq, num):
	return lower_bound_index_lr(seq, num, 0, len(seq))
seq_highs = []
seq_lows = []
n = int(input())
count_has_ascent = 0
ans = 0
for i in range(n):
	seq = list(map(int, input().split()))[1:]
	has_ascent = False
	lowest = seq[0]
	for s in seq[1:]:
		if s > lowest:
			has_ascent = True
			break
		lowest = min(lowest, s)
	if not has_ascent:
		seq_lows.append(min(seq))
		seq_highs.append(max(seq))
	else:
		ans += 2 * (n - count_has_ascent) - 1
		count_has_ascent += 1
seq_highs = sorted(seq_highs, reverse=False)
for l in seq_lows:
	h = lower_bound_index(seq_highs, l + 1)
	if h == -1:
		h = 0
	if h < len(seq_highs):
		ans += len(seq_highs) - h
print(ans)


import sys
n = int(sys.stdin.readline())
arr = [0] * (pow(10, 6) + 1)
all_arr = []
answer = 0
asc_ctr = 0
for x in range(n):
	s = [int(i) for i in sys.stdin.readline().split()]
	tmp = s[1:]
	min_i = tmp[0]
	asc = 0
	for z in range(1, len(tmp)):
		min_i = min(min_i, tmp[z])
		if tmp[z] > min_i:
			asc = 1
			break
	if asc == 0:
		arr[min(tmp)] += 1
	all_arr.append(tmp)
for g in range(1, pow(10, 6) + 1):
	arr[g] += arr[g - 1]
count = 0
for y in range(n):
	mini = all_arr[y][0]
	ascent = 0
	for z in range(1, len(all_arr[y])):
		mini = min(mini, all_arr[y][z])
		if all_arr[y][z] > mini:
			ascent = 1
			break
	if ascent == 1:
		answer += 2 * n - 1 - count * 2
		count += 1
	else:
		max_val = max(all_arr[y])
		if max_val == 0:
			num = 0
		else:
			num = arr[max_val - 1]
		answer += num
print(answer)


n = int(input())
a = [list(map(int, input().split()))[1:] for _ in range(n)]
s = sorted([q for q in a if q == sorted(q, reverse=True)], key=lambda x: -x[0])
d = sorted(s[:], key=lambda x: -x[-1])
q1 = ans = 0
for q in d:
	while q1 < len(s) and q[-1] < s[q1][0]:
		q1 += 1
	ans += len(s) - q1
print(n ** 2 - ans)


import operator
from bisect import *
n = int(input())
MaMi = []
res = 0
B = []
for i in range(n):
	(nA, *A) = [*map(int, input().split())]
	for j in range(1, nA):
		if A[j] > A[j - 1]:
			break
	else:
		MaMi.append([A[0], A[-1]])
m = n
n = len(MaMi)
MaMi = sorted(MaMi, key=operator.itemgetter(1, 0))
for i in range(n):
	B.append(MaMi[i][1])
for i in range(n):
	res += n - bisect_left(B, MaMi[i][0])
print(m * m - res)


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

def I():
	return int(input())

def S():
	return str(input())

def L():
	return list(R())
from collections import Counter
import math
import sys

def check(t):
	return [True, False][any((t[i] < t[i + 1] for i in range(1, len(t) - 1)))]
from itertools import permutations
n = I()
a = [0] * n
beg = [0] * (10 ** 6 + 1)
en = [0] * (10 ** 6 + 1)
for i in range(n):
	a = L()
	if check(a):
		beg[a[1]] += 1
		xx = len(a)
		en[a[xx - 1]] += 1
for i in range(10 ** 6):
	beg[i + 1] += beg[i]
ans = 0
for i in range(10 ** 6 + 1):
	ans += en[i] * beg[i]
print(n * n - ans)


from sys import stdin
from collections import deque
mod = 10 ** 9 + 7
import sys
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt, factorial, gcd, log2, inf, ceil
import heapq
input = lambda : sys.stdin.readline().rstrip()
from sys import stdin, stdout
from heapq import heapify, heappush, heappop

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
t = int(input())
seti = set()
la = []
ans = 0
yo = []
cnt = 0
for _ in range(t):
	l = list(map(int, input().split()))
	n = l[0]
	l = l[1:]
	flag = 0
	for i in range(n - 1):
		if l[i] < l[i + 1]:
			flag = 1
			ans += t
			cnt += 1
			break
	if not flag:
		la.append(l[0])
		yo.append((l[0], l[-1]))
ans += cnt * len(la)
la.sort()
m = len(la)
for (a, b) in yo:
	ans += countGreater(la, m, b)
print(ans)


INF = 1e+19
N = int(1000000.0 + 7)
maxn = []
minn = []
vis = []
cnt_max = []
n = input()
n = int(n)
for i in range(N):
	maxn.append(-1)
	minn.append(INF)
	vis.append(0)
	cnt_max.append(0)
for i in range(n):
	t = input().split()
	t[0] = int(t[0])
	for j in range(t[0] + 1):
		if j == 0:
			continue
		t[j] = int(t[j])
		if vis[i] == 0:
			if t[j] > minn[i]:
				vis[i] = 1
			if t[j] > maxn[i]:
				maxn[i] = t[j]
			if t[j] < minn[i]:
				minn[i] = t[j]
	if vis[i] == 0:
		cnt_max[maxn[i]] += 1
for i in range(N):
	if i == 0:
		continue
	cnt_max[i] += cnt_max[i - 1]
ans = n * n
for i in range(n):
	if vis[i] == 0:
		ans -= cnt_max[minn[i]]
print(ans)


from sys import stdin
input = stdin.readline
n = int(input())
s = cnt = 0
(v, p) = ([], [])
for _ in range(n):
	a = list(map(int, input().split()))
	l = a[0]
	del a[0]
	mx = mn = a[0]
	f = 1
	for i in range(1, l):
		if a[i] > mn:
			f = 0
			break
		else:
			mn = a[i]
	if f:
		v += (mn,)
		p += (mx,)
	else:
		s += 1
cnt = s * n + (n - s) * s
m = n - s
p = sorted(p, reverse=True)
for i in range(m):
	l = 0
	r = m - 1
	ans = -1
	while l <= r:
		md = (l + r) // 2
		if p[md] <= v[i]:
			r = md - 1
		else:
			ans = md
			l = md + 1
	cnt += ans + 1
print(cnt)


def haveAsc(s):
	min = s[1]
	l = s[0]
	for i in range(2, l + 1):
		if s[i] > min:
			return True
		min = s[i]
	return False
n = int(input())
mins = []
maxs = []
blocks = []
free = 0
for i in range(n):
	b = [int(s) for s in input().split()]
	if haveAsc(b):
		free += 1
	else:
		mins.append(b[-1])
		maxs.append(b[1])
notFree = n - free
ans = free * free + notFree * free * 2
mins.sort()
maxs.sort()
end = len(mins)
i = 0
j = 0
while i < end:
	if mins[i] >= maxs[j]:
		if j == end - 1:
			break
		j += 1
	else:
		ans += end - j
		i += 1
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')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

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
n = int(input())
ans = [0] * n
m = []
mi = []
s = 0
for i in range(n):
	l = list(map(int, input().split()))
	a = l[0]
	l = l[1:]
	f = 0
	for j in range(a - 1):
		if l[j + 1] > l[j]:
			f = 1
			break
	if f == 1:
		ans[i] = 1
		s += 1
	else:
		m.append(max(l))
		mi.append(min(l))
m.sort()
an = 0
tes = 0
for i in range(n):
	if ans[i] == 1:
		an += n
	else:
		an += countGreater(m, len(m), mi[tes]) + s
		tes += 1
print(an)


import bisect
from sys import stdin
n = int(input())
(a, b) = ([], [])
for i in range(n):
	(l, *s) = map(int, stdin.readline().split())
	if sorted(s) == s[::-1]:
		a.append(s[0])
		b.append(s[-1])
a.sort()
print(n * n - sum([bisect.bisect_right(a, bb) for bb in b]))


import bisect
a = []
b = []
count = 0
s = 0
n = int(input())
for i in range(n):
	l = list(map(int, input().split()))
	l = l[1:]
	if sorted(l, reverse=True) == l:
		a.append(l[0])
		b.append(l[-1])
	else:
		s += 1
a.sort()
b.sort()
for end in b:
	ans = bisect.bisect(a, end)
	count += n - ans
print(count + s * n)


n = int(input())
s = 0
mas = []
kol = 0
for i in range(n):
	dop = list(map(int, input().split()))
	dop = dop[1:]
	flag = 0
	for j in range(1, len(dop)):
		if dop[j - 1] < dop[j]:
			flag = 1
			break
	if flag:
		kol += 1
		continue
	mas.append([dop[0], dop[-1]])
mas.sort()
s += (n - kol) * 2 * kol + kol * kol
n = len(mas)
for i in range(n):
	x = mas[i][1]
	l = -1
	r = n
	while r - l > 1:
		m = (l + r) // 2
		if mas[m][0] <= x:
			l = m
		else:
			r = m
	s += n - r
print(s)


import sys
inf = 2 ** 30

def solution(a):
	n = len(a)
	foo = n * n
	good = [False for i in range(n)]
	for i in range(n):
		prev = inf
		for v in a[i]:
			if v < prev:
				prev = v
			elif v > prev:
				good[i] = True
				break
	a = [a[i] for i in range(n) if not good[i]]
	n = len(a)
	minv = [min(row) for row in a]
	maxv = [max(row) for row in a]
	minv = sorted(minv)
	maxv = sorted(maxv)
	j = 0
	for i in range(n):
		while j < n and minv[i] >= maxv[j]:
			j += 1
		foo -= j
	sys.stdout.write('%d\n' % foo)

def main():
	while True:
		try:
			n = int(input().strip())
			a = [[int(j) for j in input().strip().split()][1:] for i in range(n)]
			solution(a)
		except ValueError:
			continue
		except EOFError:
			break
main()


import io
from bisect import *
nim = int(input())
(array1, array2) = ([], [])
for _ in [0] * nim:
	(l, *s) = map(int, input().split())
	if all((x >= y for (x, y) in zip(s, s[1:]))):
		array1 += (s[0],)
		array2 += (s[-1],)
array1.sort()
print(nim * nim - sum((bisect(array1, x) for x in array2)))


import bisect
n = int(input())
s = []
l = []
ans = 0
ans = 0
n1 = n
for i in range(n):
	a = list(map(int, input().split()))[1:]
	if sorted(a)[::-1] == a:
		s.append(min(a))
		l.append(max(a))
	else:
		ans += n1 * 2 - 1
		n1 -= 1
s.sort()
l.sort()
j = 0
for i in range(len(s)):
	while j < len(l) and s[i] >= l[j]:
		j += 1
	ans += len(l) - j
print(ans)


def get_int():
	from sys import stdin
	return int(stdin.readline().replace('\n', ''))

def get_int_list():
	from sys import stdin
	return [int(x) for x in stdin.readline().replace('\n', '').split(' ')]

def get_str():
	from sys import stdin
	return stdin.readline().replace('\n', '')

def ascent(_list):
	for i in range(len(_list)):
		if i > 0 and _list[i] > _list[i - 1]:
			return True
	return False

def question():
	(maxs, mins) = ([], [])
	(asc, nasc) = (0, 0)
	n = get_int()
	_lists = []
	while n > 0:
		_list = get_int_list()[1:]
		n -= 1
		if ascent(_list):
			asc += 1
		else:
			nasc += 1
			maxs += [max(_list)]
			mins += [min(_list)]
	total = asc * asc + 2 * asc * nasc
	mins.sort()
	maxs.sort()
	i = 0
	for mx in maxs:
		while i < nasc and mins[i] < mx:
			i += 1
		total += i
	return total
print(question())


n = int(input())
inf = 1 + 10 ** 6
a = [0 for i in range(n)]
b = [0 for i in range(n)]
for i in range(n):
	t = list(map(int, input().split()))[1:]
	m = True
	for j in range(1, len(t)):
		if t[j - 1] < t[j]:
			(at, bt) = (-1, inf)
			m = False
			break
	if m:
		(at, bt) = (min(t), max(t))
	a[i] = at
	b[i] = bt
c = 0
a.sort()
b.sort()
cur = 0
sel = n - 1
for ii in range(n - 1, -1, -1):
	i = a[ii]
	if i == -1:
		c += n
		continue
	else:
		while sel != -1 and b[sel] > i:
			cur += 1
			sel -= 1
		c += cur
print(c)


import os
import sys
from io import BytesIO, IOBase
from bisect import bisect_left

def solution():
	pass

def main():
	n = r_int()
	(nl, nf) = ([], [])
	for _ in range(n):
		seq = r_array()
		l = seq[0]
		seq = seq[1:]
		if any((seq[i] < seq[i + 1] for i in range(len(seq) - 1))):
			continue
		else:
			nf.append(seq[0])
			nl.append(seq[-1])
	res = n ** 2
	ll = len(nf)
	nl.sort()
	for x in nf:
		res -= ll - bisect_left(nl, x)
	write(res)
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))

def input():
	return sys.stdin.readline().rstrip('\r\n')

def write(*args, end='\n'):
	for x in args[:-1]:
		sys.stdout.write(str(x) + ' ')
	sys.stdout.write(str(args[-1]))
	sys.stdout.write(end)

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

def r_int():
	return int(input())
main()


def bin_search(a, x):
	if x < a[0]:
		return 0
	if a[len(a) - 1] <= x:
		return len(a)
	left = 0
	right = len(a)
	while left + 1 < right:
		mid = (left + right) // 2
		if x < a[mid]:
			right = mid
		else:
			left = mid
	return right
n = int(input())
amin = []
amax = []
for i in range(n):
	s = [int(s) for s in input().split()]
	r = False
	minimal = s[1]
	maximal = s[1]
	last = s[1]
	for j in range(2, s[0] + 1):
		minimal = min(minimal, s[j])
		maximal = max(maximal, s[j])
		if not r:
			if s[j] > last:
				r = True
			else:
				last = s[j]
	if not r:
		amin.append(minimal)
		amax.append(maximal)
res = n ** 2 - len(amax) ** 2
amax.sort()
for i in amin:
	res += len(amax) - bin_search(amax, i)
print(res)


import bisect

def is_ascent(sequence):
	minimum = float('inf')
	for x in sequence:
		if x > minimum:
			return True
		minimum = min(x, minimum)
	return False

def find_numbers_greater_than(x, maximas):
	return len(maximas) - bisect.bisect_left(maximas, x + 1)
n = int(input())
sequences = []
for i in range(0, n):
	ls = input().split()
	l = int(ls[0])
	sequence = [int(v) for v in ls[1:]]
	sequences.append(sequence)
non_ascent_seq = []
ans = 0
asc = 0
non_asc = 0
for sequence in sequences:
	if is_ascent(sequence):
		asc += 1
	else:
		non_asc += 1
		non_ascent_seq.append(sequence)
ans += 2 * asc * non_asc + asc * asc
maximas = []
for sequence in non_ascent_seq:
	maximas.append(max(sequence))
maximas.sort()
for sequence in non_ascent_seq:
	x = min(sequence)
	ans += find_numbers_greater_than(x, maximas)
print(ans)


n = int(input(''))
asc = [0] * n
ascc = 0
mn = []
mx = []
for i in range(n):
	a = list(map(int, input('').split(' ')))
	l = int(a[0])
	mn.append(min(a[1:]))
	mx.append(max(a[1:]))
	for j in range(1, l, 1):
		if a[j + 1] > a[j]:
			asc[i] = 1
			ascc += 1
			break
d = {}
mxx = []
mnn = []
for i in range(n):
	if asc[i] == 0:
		d[i] = True
		mxx.append(mx[i])
		mnn.append(mn[i])
ans = 0
mnn.sort()
mxx.sort()
i = 0
j = 0
l = len(d)
while i < l and j < l:
	if mnn[i] < mxx[j]:
		i += 1
		ans += l - j
	else:
		j += 1
for i in range(n):
	if asc[i] == 1:
		ans += n
		continue
	ans += ascc
print(ans)


n = int(input())
lo = []
hi = []
for _ in range(n):
	l = 1000010000
	h = -1000010000
	a = 0
	for (i, x) in enumerate(map(int, input().split())):
		if i:
			if x > l:
				a = 1
			l = min(l, x)
			h = max(h, x)
	if not a:
		lo += (l,)
		hi += (h,)
h = sorted(hi)
ans = n * n
import bisect
for l in lo:
	j = bisect.bisect(h, l)
	ans -= j
print(ans)


import bisect
n = int(input())
x = []
y = []
asc = 0
ans = 0
temp_s = [list(map(int, input().split())) for i in range(n)]
for i in range(n):
	xm = 20000000
	yM = 0
	f_asc = 0
	for j in temp_s[i][1:]:
		if j > yM:
			yM = j
		if j < xm:
			xm = j
		if j > xm:
			f_asc = 1
	if f_asc == 0:
		x.append(xm)
		y.append(yM)
	else:
		asc += 1
y.sort()
x.sort()
ans += asc * (2 * len(y) + asc)
for i in y:
	ans += bisect.bisect_left(x, i)
print(ans)


import sys
n = int(input())
m = []
mm = []
c = 0
for i in range(0, n):
	line = list(map(int, input().split()))
	line.pop(0)
	blool = False
	for i in range(0, len(line) - 1):
		if line[i] < line[i + 1]:
			blool = True
	if blool:
		c += 1
	else:
		m.append(line[len(line) - 1])
		mm.append(line[0])
m.sort()
mm.sort()
i = 0
j = 0
total = 2 * c * (n - c) + c ** 2
n -= c
while i < n and j < n:
	if mm[i] > m[j]:
		j += 1
	else:
		total = total + j
		i += 1
while i < n:
	total += n
	i += 1
print(total)


def search(arr, low, high, target):
	if arr[-1] <= target:
		return -1
	while low < high:
		mid = low + (high - low) // 2
		if arr[mid] <= target:
			low = mid + 1
		else:
			high = mid
	return low

def ascending(seq):
	l = len(seq)
	_min = seq[0]
	for i in range(1, l):
		if seq[i] > _min:
			return True
		_min = min(_min, seq[i])
	return False
n = int(input())
l_list = []
s_list = []
ans = 0
ascending_list = []
for _ in range(n):
	s = list(map(int, input().split()))
	l = s[0]
	s = s[1:]
	if min(s) != max(s):
		ans += 1
	if ascending(s):
		ans += 2 * (n - 1)
		ascending_list.append(s)
	else:
		l_list.append(l)
		s_list.append(s)
n3 = len(ascending_list)
ans -= 2 * (n3 * (n3 - 1) // 2)
minlist = []
maxlist = []
for i in range(len(s_list)):
	minlist.append(min(s_list[i]))
	maxlist.append(max(s_list[i]))
minlist_sorted = sorted(minlist)
maxlist_sorted = sorted(maxlist)
n2 = len(minlist_sorted)
for i in range(n2):
	val = minlist[i]
	match = search(maxlist_sorted, 0, n2 - 1, val)
	if match >= 0:
		ans += n2 - match
		if maxlist[i] >= maxlist_sorted[match]:
			ans -= 1
print(ans)


def check(arr):
	mini = arr[0]
	for i in range(1, len(arr)):
		if mini < arr[i]:
			return True
		elif mini > arr[i]:
			mini = arr[i]
	return False
n = int(input())
arr = []
mini = []
maxi = []
ans = 0
u = 0
for i in range(n):
	temp = list(map(int, input().split(' ')))[1:]
	if check(temp):
		u += 1
	else:
		t_min = min(temp)
		t_max = max(temp)
		mini.append(t_min)
		maxi.append(t_max)
mini.sort()
maxi.sort()
i = 0
j = 0
while mini:
	if mini[i] < maxi[j]:
		if i < len(mini) - 1:
			i += 1
		else:
			ans += len(mini) * (len(maxi) - j)
			break
	elif mini[i] >= maxi[j]:
		ans += i
		if j < len(maxi) - 1:
			j += 1
		else:
			break
ans += u * n + (n - u) * u
print(ans)


import math

def input_handler():
	num_seq = int(input())
	arr_input = []
	for i in range(0, num_seq):
		arr_string = input()
		arr_string = arr_string.split(' ')
		temp_arr = []
		for i in range(0, int(arr_string[0])):
			temp_arr.append(int(arr_string[1 + i]))
		arr_input.append(temp_arr)
	return arr_input

def check_ascent(arr):
	check = False
	arr_num = len(arr)
	for i in range(1, arr_num):
		if arr[i] > arr[i - 1]:
			check = True
			break
	return check

def count00_sucess(false_val_first, false_val_last):
	false_val_last.sort()
	false_val_first.sort()
	first_index = 0
	last_index = 0
	count = 0
	while last_index < len(false_val_last) and first_index < len(false_val_first):
		if false_val_last[last_index] < false_val_first[first_index]:
			count += len(false_val_first) - first_index
			last_index += 1
		else:
			first_index += 1
	return count
arr_input = input_handler()
arr_num = len(arr_input)
false_val_last = []
false_val_first = []
result = 0
true_num = 0
for i in range(0, arr_num):
	if check_ascent(arr_input[i]) == False:
		first_el = arr_input[i][0]
		last_el = arr_input[i][len(arr_input[i]) - 1]
		false_val_last.append(last_el)
		false_val_first.append(first_el)
	else:
		result += 2 * arr_num - 1 - true_num * 2
		true_num += 1
result += count00_sucess(false_val_first, false_val_last)
print(result)


import bisect
n = int(input())
asc = 0
dec = []
decu = []
for i in range(n):
	l = input().split()
	li = [int(i) for i in l]
	z = li[0]
	poss = 1
	for j in range(2, z + 1):
		if li[j] > li[j - 1]:
			poss = 0
			break
	if poss == 0:
		asc += 1
	else:
		dec.append(li[1])
		decu.append(li[z])
dec.sort()
count = asc * n
ans = count
for i in decu:
	ans += n
	ans -= bisect.bisect_right(dec, i)
print(ans)


import sys
n = int(sys.stdin.readline().strip())
m = []
M = []
c = 0
for i in range(0, n):
	line = list(map(int, sys.stdin.readline().strip().split()))[1:]
	l = len(line)
	v = False
	for i in range(0, l - 1):
		if line[i] < line[i + 1]:
			v = True
	if v == True:
		c = c + 1
	else:
		m.append(line[-1])
		M.append(line[0])
m.sort()
M.sort()
i = 0
j = 0
ans = 2 * c * (n - c) + c ** 2
n = n - c
while i < n and j < n:
	if M[i] > m[j]:
		j = j + 1
	else:
		ans = ans + j
		i = i + 1
while i < n:
	ans = ans + n
	i = i + 1
print(ans)


n = int(input())
from bisect import bisect_left
Ms = []
ms = []
ascend = []
cnt = 0
for i in range(n):
	As = list(map(int, input().split()))
	l = As[0]
	As = As[1:]
	flg = False
	if l > 1:
		for i in range(1, l):
			if As[i - 1] < As[i]:
				flg = True
				break
	if flg:
		ascend.append(True)
		cnt += 1
	else:
		Ms.append(max(As))
		ms.append(min(As))
		ascend.append(False)
ans1 = (n - cnt) * cnt * 2 + cnt ** 2
Ms.sort()
ans = 0
for m in ms:
	ind = bisect_left(Ms, m + 1)
	ans += n - ind - cnt
print(ans + ans1)


from sys import stdin
from bisect import bisect_right

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

def intput():
	return int(input())

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

def intsput():
	return map(int, sinput())
debugging = False

def dprint(*args):
	if debugging:
		print(*args)
	else:
		pass
n = intput()
starts = []
ends = []
test = 0
for _ in range(n):
	ii = list(intsput())
	for i in range(2, len(ii)):
		if ii[i] > ii[i - 1]:
			test += 1
			break
	else:
		ends.append(ii[-1])
		starts.append(ii[1])
starts.sort()
cnt = test + (n - test) * test * 2 + test * (test - 1)
for i in range(len(ends)):
	cnt += len(starts) - bisect_right(starts, ends[i])
print(cnt)


n = int(input())
no_seqs1 = []
no_seqs2 = []
YES = 0
NO = 0
MAX_NUM = 10 ** 6 + 1
final = 0
for case in range(n):
	check = True
	l = [int(zax) for zax in input().split()]
	for i in range(1, l[0]):
		if l[i + 1] > l[i]:
			check = False
			break
	if check:
		no_seqs1.append((l[1], l[-1]))
		no_seqs2.append((l[-1], l[1]))
		NO += 1
	else:
		YES += 1
for i in range(1, YES + 1):
	val = n - i
	final += 2 * val + 1
no_seqs1.sort()
no_seqs2.sort()
dp1 = [-1 for i in range(MAX_NUM + 1)]
dp2 = [-1 for i in range(MAX_NUM + 1)]
for i in range(NO):
	if dp1[no_seqs1[i][0]] == -1:
		dp1[no_seqs1[i][0]] = i
	if dp2[no_seqs2[i][0]] == -1:
		dp2[no_seqs2[i][0]] = i
val1 = -1
val2 = -1
for i in range(MAX_NUM, -1, -1):
	if dp1[i] != -1:
		val1 = dp1[i]
	dp1[i] = val1
	if dp2[i] != -1:
		val2 = dp2[i]
	dp2[i] = val2
for i in range(NO):
	num1 = no_seqs1[i][1] + 1
	if num1 <= MAX_NUM and dp1[num1] > -1:
		final += NO - dp1[num1]
print(final)


from bisect import bisect_left as bl
n = int(input())
c = 0
mi = []
ma = []
ans = 0
for xi in range(n):
	l = list(map(int, input().split()))[1:]
	m = l[0]
	for i in range(1, len(l)):
		if l[i] > m:
			c += 1
			break
		m = min(m, l[i])
	else:
		mi.append(min(l))
		ma.append(max(l))
ans += c * n
ma.sort()
for i in mi:
	ans += n - bl(ma, i + 1)
print(ans)


import sys
input = sys.stdin.readline
from collections import Counter
n = int(input())
s = []
l = []
ans = n ** 2
for i in range(n):
	a = list(map(int, input().split()))[1:]
	if sorted(a)[::-1] == a:
		s.append(min(a))
		l.append(max(a))
s.sort()
l.sort()
c = 0
for i in range(len(s)):
	while c < len(l) and l[c] <= s[i]:
		c += 1
	ans -= c
print(ans)


import sys, os, io

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

def ri():
	return int(sys.stdin.readline())

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

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math, datetime, functools, itertools, operator, bisect
from collections import deque, defaultdict, OrderedDict
import collections

def main():
	starttime = datetime.datetime.now()
	if os.path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	for _ in range(1):
		n = ri()
		mina = []
		maxa = []
		ans = 0
		for i in range(n):
			ar = ria()
			l = ar[0]
			a = ar[1:]
			t = 0
			for i in range(l - 1):
				if a[i] < a[i + 1]:
					ans += 2 * n - 1
					n -= 1
					t = 1
					break
			if t == 0:
				mina.append(a[-1])
				maxa.append(a[0])
		maxa = sorted(maxa)
		for i in mina:
			z = bisect.bisect(maxa, i)
			ans += len(maxa) - z
		print(ans)
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
	if os.path.exists('input.txt'):
		print('Time:', time, 'ms')

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			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, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			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()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

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

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


from bisect import *
(f, l) = ([], [])
k = 0
n = int(input())
for _ in range(n):
	(le, *s) = map(int, input().split())
	if s == sorted(s, reverse=True):
		f.append(s[0])
		l.append(s[-1])
f.sort()
for x in l:
	k += bisect(f, x)
print(n * n - k)


from bisect import bisect
una = []
b = int(input())
for ii in range(b):
	a = [int(j) for j in input().split()]
	a = a[1:]
	flag = False
	for i in range(len(a) - 1):
		if a[i + 1] > a[i]:
			flag = True
			break
	if flag == False:
		una.append((a[0], a[-1]))
count = 0
l = []
chi = []
for i in una:
	l.append(i[0])
	chi.append(i[1])
l = sorted(l)
for k in chi:
	count += len(l) - bisect(l, k)
n = len(una)
print(b ** 2 - n ** 2 + count)


import bisect
nseq = int(input())
seqs = []
isasc = []
mins = []
maxs = []
cnt = 0
ascprev = 0
for i in range(nseq):
	ls = list(map(int, input().split()))[1:]
	if len(set(ls)) != 1 and ls != sorted(ls, reverse=True):
		cnt += 2 * (nseq - ascprev) - 1
		ascprev += 1
	else:
		mins.append(min(ls))
		maxs.append(max(ls))
mins.sort()
for mx in maxs:
	cnt += bisect.bisect_left(mins, mx)
print(cnt)


n = int(input())
mx = []
num = [0] * 1000005
for _ in range(n):
	ls = list(map(int, input().split()))
	ls.pop(0)
	tmp_mx = -1
	tmp_mi = 1000000.0 + 5
	flag = False
	for i in ls:
		if i > tmp_mi:
			flag = True
		tmp_mx = max(tmp_mx, i)
		tmp_mi = min(tmp_mi, i)
	if flag:
		tmp_mi = -1
		tmp_mx = 1000000
	mx.append(tmp_mx)
	num[tmp_mi + 1] += 1
for i in range(1, 1000001):
	num[i] += num[i - 1]
ans = 0
for i in mx:
	ans += num[i]
print(ans)


t = int(input())
yes = 0
lno = []
M = []
m = []
for i in range(t):
	inp = list(map(int, input().split()))[1:]
	if inp[::-1] != sorted(inp):
		yes += 1
	else:
		M.append(inp[0])
		m.append(inp[-1])
ans = 2 * yes * t - yes * yes
M.sort()
lM = len(M)
m.sort()
j = 0
for x in M:
	if j < lM:
		while m[j] < x:
			j += 1
			if j == lM:
				break
	ans += j
	i += 1
print(ans)


from bisect import bisect_left
A = []
kek_lists = 0
n = int(input())
for i in range(n):
	B = list(map(int, input().split()))
	Keklol = B.pop(0)
	T = False
	for j in range(Keklol - 1):
		if B[j] < B[j + 1]:
			T = True
	if T:
		kek_lists += 1
	else:
		A.append((B, T, min(B), max(B)))
Mi = []
for i in range(len(A)):
	Mi.append(A[i][2])
Mi.sort()
ans = 0
kek = len(A)
for i in range(kek):
	ans += bisect_left(Mi, A[i][3])
ans += 2 * kek * kek_lists
ans += kek_lists ** 2
print(ans)


n = int(input())
a = [tuple(map(int, input().split()))[1:] for _ in range(n)]
(mn, mx) = ([], [])
okCnt = 0
for (pos, sub) in enumerate(a):
	for i in range(1, len(sub)):
		if sub[i] > sub[i - 1]:
			okCnt += 1
			break
	else:
		mn.append(min(sub))
		mx.append(max(sub))
ret = 0
for i in range(1, okCnt + 1):
	ret += (n - i) * 2 + 1
mx.sort()
mxSize = len(mx)
for val in mn:
	(left, right) = (-1, mxSize)
	while left + 1 < right:
		mid = (left + right) // 2
		if mx[mid] > val:
			right = mid
		else:
			left = mid
	if right < mxSize:
		ret += mxSize - right
print(ret)


numberlist = []
lengthofnumber = int(input())
for i in range(lengthofnumber):
	inputel = list(map(int, input().split()))
	numberlist.append(inputel[1:])
ascents = 0

def ascentexist1(inputlist):
	countervariable = 0
	if len(inputlist) == 1:
		return False
	countervariable = 1
	while countervariable <= len(inputlist) - 1 and inputlist[countervariable - 1] >= inputlist[countervariable]:
		countervariable += 1
	if countervariable <= len(inputlist) - 1:
		return True
	else:
		return False

def ascentexist2(a, b):
	if min(a) < max(b):
		return True
	else:
		return False
nonascents = []
for a in numberlist:
	if ascentexist1(a):
		ascents += lengthofnumber
	else:
		nonascents.append(a)
ascents += len(nonascents) * abs(lengthofnumber - len(nonascents))
minnonascents = []
maxnonascents = []
for b in nonascents:
	minnonascents.append(min(b))
	maxnonascents.append(max(b))
minnonascents.sort()
maxnonascents.sort()

def indexmin(item, array):
	if item >= array[-1]:
		return None
	elif item < array[0]:
		return 0
	start = 0
	end = len(array) - 1
	while start <= end:
		midpoint = (start + end) // 2
		if abs(start - end) <= 1:
			return midpoint + 1
		elif item < array[midpoint]:
			end = midpoint
		elif item >= array[midpoint]:
			start = midpoint
	return None
for k in minnonascents:
	alphavalue = indexmin(k, maxnonascents)
	if alphavalue != None:
		ascents += len(maxnonascents) - alphavalue
print(ascents)


import bisect

def qsort(inlist):
	if inlist == []:
		return []
	else:
		pivot = inlist[0]
		lesser = qsort([x for x in inlist[1:] if x < pivot])
		greater = qsort([x for x in inlist[1:] if x >= pivot])
		return lesser + [pivot] + greater

def ascent(list1, len1):
	if len1 == 1:
		return False
	for i in range(len1 - 1):
		if list1[i + 1] > list1[i]:
			return True
	return False
n = int(input())
kappa = 0
nmsl = []
minList = []
maxList = []
for i in range(n):
	fulllist = [int(ele) for ele in input().split()]
	lenl = fulllist[0]
	lst = fulllist[1:]
	minL = min(lst)
	maxL = max(lst)
	ascentYN = ascent(lst, lenl)
	if ascentYN:
		kappa += 1
	else:
		nmsl.append([minL, maxL])
		minList.append(minL)
		maxList.append(maxL)
res = kappa * (2 * n - kappa)
count1 = 0
minList.sort()
maxList.sort()
minList.reverse()
maxList.reverse()
maxList.append(float('-inf'))
maxind = 0
for ele in minList:
	while ele < maxList[maxind]:
		maxind += 1
	res += maxind
print(res)


import sys
import math
import bisect
import heapq
from bisect import bisect_right
from sys import stdin, stdout

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

def get_int():
	return int(sys.stdin.readline())

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

def get_list_of_list(n):
	return [list(map(int, sys.stdin.readline().strip().split())) for _ in range(n)]

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

def myceil(x, y):
	return (x + y - 1) // y

def Solution(arr, n):
	ans = n * n
	sm = []
	mx = []
	for v in arr:
		v = list(reversed(v[1:]))
		if sorted(v) == v:
			sm.append(v[0])
			mx.append(v[-1])
	sm = sorted(sm)
	mx = sorted(mx)
	for v in sm:
		pair = bisect.bisect(mx, v)
		ans -= pair
	print(ans)

def main():
	n = get_int()
	arr = get_list_of_list(n)
	Solution(arr, n)
main()


n = int(input())
temp = 0
first = []
last = []
import bisect
for i in range(n):
	l1 = list(map(int, input().split()))[1:]
	curr = l1[0]
	flag = 0
	for x in l1:
		if x <= curr:
			curr = x
		else:
			flag = 1
			break
	if flag == 1:
		temp += 1
	else:
		first.append(l1[0])
		last.append(l1[-1])
count = 0
first.sort()
for item in last:
	count += len(first) - bisect.bisect_right(first, item)
print(count + temp * temp + 2 * len(first) * temp)


import math
import sys
input = sys.stdin.readline
n = int(input())
minn = []
maxx = []
count = 0
num = 0
for i in range(n):
	arr = list(map(int, input().split()))
	cur = arr[1]
	flag = False
	for j in range(1, len(arr)):
		if arr[j] < cur:
			cur = arr[j]
		if arr[j] > cur:
			flag = True
			break
	if flag:
		num += 1
	else:
		minn.append(min(arr[1:]))
		maxx.append(max(arr[1:]))
minn.sort()
maxx.sort()
count = n ** 2 - (n - num) ** 2
n = len(minn)
i = 0
j = 0
while i < n and j < n:
	if maxx[j] <= minn[i]:
		j += 1
	else:
		count += n - j
		i += 1
print(count)


n = int(input())
(minimos, maximos) = ([], [])
(asc, nasc) = (0, 0)
for i in range(n):
	sequencia = list(map(int, input().split(' ')))[1:]
	for j in range(len(sequencia)):
		if j > 0 and sequencia[j] > sequencia[j - 1]:
			asc += 1
			break
		elif j == len(sequencia) - 1:
			nasc += 1
			minimos.append(min(sequencia))
			maximos.append(max(sequencia))
total = asc * asc + 2 * asc * nasc
minimos.sort()
maximos.sort()
i = 0
for k in maximos:
	while i < nasc and minimos[i] < k:
		i += 1
	total += i
print(total)


from bisect import bisect_left
n = int(input())
a = 0
b = 0
m = []
M = []

def ascend(a):
	m = float('inf')
	for i in a:
		if m < i:
			return True
		m = min(m, i)
	return False
for i in range(n):
	x = list(map(int, input().split()))[1:]
	if ascend(x):
		a += 1
	else:
		m.append(min(x))
		M.append(max(x))
m.sort()
for i in M:
	b += bisect_left(m, i)
print(a * a + (n - a) * a * 2 + b)


def bs(k, li):
	(l, r) = (0, len(li) - 1)
	if li[l] > k:
		return 0
	if li[r] <= k:
		return len(li)
	while True:
		if r - l < 2:
			return r
		m = l + (r - l >> 1)
		if li[m] > k:
			r = m
		else:
			l = m
n = int(input())
sll = [list(map(int, input().split())) for _ in range(n)]
minl = []
maxl = []
for sl in sll:
	nn = sl[0]
	m = sl[1]
	ascent = False
	if nn == 1:
		minl.append(m)
		maxl.append(m)
		continue
	for i in range(2, nn + 1):
		if sl[i] > m:
			ascent = True
			break
		else:
			m = sl[i]
	if not ascent:
		minl.append(min(sl[1:]))
		maxl.append(max(sl[1:]))
maxs = sorted(maxl)
cnt = sum([bs(m, maxs) for m in minl])
print(n * n - cnt)


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

def chk(L):
	f = 0
	for i in range(1, L[0]):
		if L[i + 1] > L[i]:
			return (1000001, -1)
	return (L[1], L[-1])
N = int(input())
X = [0] * 1000002
Y = []
for _ in range(N):
	A = [int(a) for a in input().split()]
	(a, b) = chk(A)
	X[a] += 1
	Y.append(b)
for i in range(1000001)[::-1]:
	X[i] += X[i + 1]
ans = 0
for y in Y:
	ans += X[y + 1]
print(ans)


import sys, itertools, collections
N = int(sys.stdin.readline().strip())
A = []
for _ in range(N):
	A.append([int(i) for i in sys.stdin.readline().strip().split(' ')][1:])
MIN = collections.defaultdict(int)
MAX = []
ACCENT = 0
for a in A:
	s_min = 10000000000
	s_max = -1
	accent = False
	for s in a:
		s_min = min(s_min, s)
		s_max = max(s_max, s)
		if s > s_min:
			accent = True
	if accent:
		ACCENT += 1
	else:
		MIN[s_min] += 1
		MAX.append(s_max)
MIN = sorted(MIN.items())
MAX = sorted(MAX)
s = 0
mis = 0
for (m, c) in MIN:
	for i in range(mis, len(MAX)):
		if MAX[i] > m:
			mis = i
			s += c * (len(MAX) - i)
			break
if ACCENT > 0:
	s += ACCENT * N + (N - ACCENT) * ACCENT
print(s)


import sys
n = int(input())

def inp(n):
	L = []
	for i in range(n):
		L.append([int(i) for i in input().split()[1:]])
	return L

def binary(l, M):
	m = min(l)
	start = 0
	end = len(M)
	while start < end - 1:
		mid = (start + end) // 2
		if m >= M[mid]:
			start = mid
		else:
			end = mid
	if m < M[0]:
		return len(M)
	if M[start] > m:
		return len(M) - start
	else:
		return len(M) - end

def has_ascent(l):
	L = [sys.maxsize]
	for i in l:
		if i <= L[-1]:
			L.append(i)
		else:
			return True
	return False
d = 0
k = 0
K = inp(n)
L = []
for i in K:
	if has_ascent(i):
		d = d + (2 * n - 1)
		k = k + 1
	else:
		L.append(i)
M = [max(L[i]) for i in range(len(L))]
M.sort()
for l in L:
	d += binary(l, M)
d = d - k * k + k
print(d)


n = int(input())
x = []
y = []
k = 0
g = 0
for i in range(n):
	l = list(map(int, input().split()))[1:]
	for j in range(len(l)):
		if j > 0 and l[j] > l[j - 1]:
			k += 1
			break
		elif j == len(l) - 1:
			g += 1
			y.append(min(l))
			x.append(max(l))
count = k * k + 2 * k * g
x.sort()
y.sort()
j = 0
for k in x:
	while j < g and y[j] < k:
		j += 1
	count += j
print(count)


from sys import stdin
k = []

def bin_s(o):
	lo = 0
	hi = z - 1
	ans = z
	while lo <= hi:
		mid = (lo + hi) // 2
		if k[mid][0] > o:
			ans = mid
			hi = mid - 1
		else:
			lo = mid + 1
	return ans
n = int(stdin.readline())
ans = 0
s = 0
for _ in ' ' * int(n):
	z = list(map(int, stdin.readline().split()[1:]))[::-1]
	if z == sorted(z):
		k.append([max(z), min(z)])
k = sorted(k)
z = len(k)
for i in range(z):
	ans -= bin_s(k[i][1])
print(ans + n * n)


t = int(input())
l = []
for i in range(t):
	a = list(map(int, input().split()))
	l.append(a[1:])
l1 = []
for i in range(t):
	for j in range(len(l[i]) - 1):
		if l[i][j] < l[i][j + 1]:
			break
	else:
		l1.append(l[i])
upper = []
lower = []
for i in range(len(l1)):
	lower.append(l1[i][0])
	b = len(l1[i]) - 1
	upper.append(l1[i][b])
lower.sort()

def binary_search(lo, hi, k, arr):
	while lo < hi:
		mid = int(lo + (hi - lo + 1) / 2)
		if arr[mid] > k:
			hi = mid - 1
		else:
			lo = mid
	return lo
s = 0
for i in upper:
	ind = binary_search(0, len(lower) - 1, i, lower)
	if lower[ind] <= i:
		s += ind + 1
print(int(t * t - s))


import bisect
n = int(input())
r1 = []
r2 = []
ar = []
for _ in range(n):
	l = [int(i) for i in input().split()]
	l = l[1:]
	for i in range(1, len(l)):
		if l[i] > l[i - 1]:
			break
	else:
		if len(l) == 1:
			ar.append(1)
		else:
			ar.append(0)
		r1.append(l[0])
		r2.append(l[-1])
r1s = sorted(r1)
r2s = sorted(r2)
ans = 0
rl = len(r1)
for i in range(rl):
	p1 = bisect.bisect_left(r2s, r1[i])
	if ar[i] == 1:
		ans += rl - p1 - 1
	else:
		ans += rl - p1
	p2 = bisect.bisect_right(r1s, r2[i])
	if ar[i] == 1:
		ans += p2 - 1
	else:
		ans += p2
print(n ** 2 - ans // 2 - sum(ar))


import sys
input = sys.stdin.readline
import bisect
n = int(input())
(Mi, Ma) = ([], [])
As = []
for _ in range(n):
	A = [int(i) for i in input().split()][1:]
	Mi.append(min(A))
	chk = False
	cur = float('inf')
	for a in A:
		if a > cur:
			chk = True
		cur = min(cur, a)
	As.append(chk)
	if not chk:
		Ma.append(max(A))
ans = 0
Ma.sort()
for i in range(n):
	if As[i]:
		ans += n
	else:
		mi = Mi[i]
		ans += n - bisect.bisect_right(Ma, mi)
print(ans)


from bisect import bisect_right as br
maxx = []
minn = []
c = 0
n = int(input())
for _ in range(n):
	t = list(map(int, input().split()))
	t = t[1:]
	flag = False
	for k in range(len(t) - 1):
		if t[k] < t[k + 1]:
			flag = True
			break
	if not flag:
		maxx.append(max(t))
		minn.append(min(t))
	else:
		c += 1
ans = 0
maxx.sort()
minn.sort()
for k in minn:
	ans += len(maxx) - br(maxx, k)
print(pow(n, 2) - pow(n - c, 2) + 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')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from bisect import bisect
n = int(input())
l = []
for i in range(n):
	l.append(list(map(int, input().split())))
l1 = []
l2 = []
l3 = [0] * n
for i in range(n):
	c = 10 ** 6
	for j in l[i][1:]:
		if j > c:
			l3[i] = 1
			break
		c = min(c, j)
for i in range(n):
	a = min(l[i][1:])
	b = max(l[i][1:])
	l1.append(a)
	if l3[i] == 0:
		l2.append(b)
l2.sort()
ans = 0
x = l3.count(1)
for i in range(n):
	if l3[i] == 1:
		ans += n
	else:
		a = bisect(l2, l1[i])
		ans += len(l2) - a
		ans += x
print(ans)


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

def main():
	n = int(input())
	ans = n * n
	s = []
	l = []
	for _ in range(n):
		a = list(map(int, input().split()))
		a = a[1:]
		if sorted(a)[::-1] == a:
			s.append(a[-1])
			l.append(a[0])
	l.sort()
	subtract = 0
	for x in s:
		subtract += bisect.bisect(l, x)
	print(ans - subtract)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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


from operator import itemgetter

def check(l):
	for i in range(len(l) - 1):
		if l[i] < l[i + 1]:
			return True
	return False
n = int(input())
ll = []
ans = 0
ct = 0
for i in range(n):
	l = list(map(int, input().split()))
	l = l[1:]
	ascent = check(l)
	if ascent:
		ct += 1
		ans += 2 * n - 1
	else:
		ll.append([i, min(l), max(l)])
minsorted = sorted(ll, reverse=True, key=itemgetter(1))
maxsorted = sorted(ll, key=itemgetter(2))
n = len(maxsorted)
pos = n - 1
for x in minsorted:
	while pos >= 0 and x[1] < maxsorted[pos][2]:
		pos -= 1
	ans += n - 1 - pos
n = ct
val = n * n - n
print(ans - val)


from operator import itemgetter
n = int(input())
ans = 0
num = 0
ar = [[] for i in range(n)]
for i in range(n):
	si = list(map(int, input().split()))
	flag = 0
	for j in range(2, si[0] + 1):
		flag |= si[j] > si[j - 1]
	if flag != 1:
		ar[i - num] = [si[1], si[-1]]
	else:
		num += 1
ans += (2 * n - 1 + 2 * n - 1 - (num - 1) * 2) * num // 2
n2 = n - num
ar1 = sorted(ar[:n2], key=itemgetter(0))
ar2 = sorted(ar[:n2], key=itemgetter(1))
i = 0
j = 0
while i < n2 and j < n2:
	if ar1[i][0] > ar2[j][1]:
		j += 1
	elif ar2[i][0] == ar2[j][1]:
		ans += j
		i += 1
	else:
		ans += j
		i += 1
while i < n2:
	ans += n2
	i += 1
print(ans)


n = int(input())
(menores, maiores, asc, nasc) = ([], [], 0, 0)
for i in range(n):
	s = list(map(int, input().split()))[1:]
	for i in range(len(s)):
		if i > 0 and s[i] > s[i - 1]:
			asc += 1
			break
		elif i == len(s) - 1:
			nasc += 1
			menores.append(min(s))
			maiores.append(max(s))
resposta = asc * asc + 2 * asc * nasc
menores.sort()
maiores.sort()
i = 0
for x in maiores:
	while i < nasc and menores[i] < x:
		i += 1
	resposta += i
print(resposta)


n = int(input())
seq = []
aux = [0] * 1000001
asc = [0] * n
ans = 0
cont = 0
for i in range(n):
	l = list(map(int, input().split()))
	seq.append(l[1:])
	for j in range(1, l[0]):
		if l[j] < l[j + 1]:
			asc[i] = 1
			cont += 1
			ans += n
			break
	if not asc[i]:
		aux[l[1]] += 1
for i in range(1, 1000001):
	aux[i] += aux[i - 1]
for i in range(n):
	if not asc[i]:
		ans += cont
		ans += aux[-1] - aux[seq[i][-1]]
print(ans)


def check(arr):
	flag = False
	for i in range(len(arr) - 1):
		if arr[i] < arr[i + 1]:
			flag = True
			break
	return flag
n = int(input())
arr = []
for i in range(n):
	inp = list(map(lambda x: int(x), input().split(' ')))
	arr.append([inp[1:], [min(inp[1:]), max(inp[1:])]])
arr1 = []
arr2 = []
for i in arr:
	if check(i[0]) == True:
		arr1.append(i)
	else:
		arr2.append(i)
ans = n ** 2 - len(arr2) ** 2
arr_new = [i[1][0] for i in arr2]
arr_new.sort()
from bisect import bisect_left

def BinarySearch(a, x):
	i = bisect_left(a, x)
	if i:
		return i - 1
	else:
		return -1
for i in arr2:
	ans += BinarySearch(arr_new, i[1][1]) + 1
print(ans)


from bisect import bisect_right as br
n = int(input())
s = [list(map(int, input().split())) for i in range(n)]
a = []
b = []
c = 0
for i in s:
	i = i[1:]
	if list(reversed(sorted(i))) == i:
		a.append(min(i))
		b.append(max(i))
	else:
		c += 1
a = sorted(a)
b = sorted(b)
p = 0
t = len(b)
for i in a:
	p += len(b) - br(b, i)
print(n ** 2 - (n - c) ** 2 + p)


import sys
from bisect import bisect_right as br
input = sys.stdin.readline
N = int(input())
mx = []
p = []
for _ in range(N):
	a = list(map(int, input().split()))[1:]
	mna = min(a)
	mxa = max(a)
	t = float('inf')
	f = 0
	for i in range(len(a)):
		if a[i] > t:
			f = 1
		else:
			t = min(t, a[i])
	if f:
		mx.append(float('inf'))
		mna = -1
	else:
		mx.append(mxa)
	p.append((mna, mxa))
mx.sort()
res = 0
for i in range(N):
	res += N - br(mx, p[i][0])
print(res)


import bisect
n = int(input())
o = n * n
mi = []
ma = []
l = []
for i in range(n):
	(m, *q) = [*map(int, input().split())]
	w = sorted(q, reverse=1)
	if q == w:
		mi += [w[-1]]
		ma += [w[0]]
		l += [[w[-1], w[0]]]
mi.sort()
ma.sort()
r = len(ma)
for i in ma:
	o -= r - bisect.bisect_left(mi, i)
print(o)


def has_ascent(seq):
	for i in range(2, len(seq)):
		if seq[i] > seq[i - 1]:
			return True
	return False

def combine_pairs(n):
	return n ** 2

def calc_pa(n):
	return n * (n - 1) // 2
n = int(input())
seq_mins = []
seq_maxs = []
seq_with_ascents = 0
for i in range(n):
	seq = list(map(int, input().split(' ')))
	if has_ascent(seq):
		seq_with_ascents += 1
	else:
		seq_mins.append(min(seq[1:len(seq)]))
		seq_maxs.append(max(seq[1:len(seq)]))
seq_mins = sorted(seq_mins)
seq_maxs = sorted(seq_maxs)
seq_without_ascent = len(seq_maxs)
combinations = 0
k = 0
for e in seq_mins:
	while k < seq_without_ascent and seq_maxs[k] <= e:
		k += 1
	if k < seq_without_ascent:
		combinations += seq_without_ascent - k
pairs = combine_pairs(seq_with_ascents) + 2 * seq_without_ascent * seq_with_ascents + combinations
print(pairs)


import sys
input = sys.stdin.readline
n = int(input())
mi = []
ma = []
cnt = 0
ans = 0
for _ in range(n):
	a = list(map(int, input().split()))
	b = min(a[1:])
	c = max(a[1:])
	saisho = 10 ** 10
	f = 0
	for j in range(a[0]):
		saisho = min(saisho, a[j + 1])
		if saisho < a[j + 1]:
			f = 1
			ans += (n - cnt) * 2 - 1
			cnt += 1
			break
	if not f:
		mi.append(b)
		ma.append(c)
mi.sort()
ma.sort()
import bisect
for i in range(n - cnt):
	p = bisect.bisect_right(ma, mi[i])
	ans += n - cnt - p
print(ans)


n = int(input())
e = []
b = []
ok = 0
rs = 0
for _ in range(n):
	c = list(map(int, input().split()))
	l = c[1:]
	if all((l[i] >= l[i + 1] for i in range(len(l) - 1))):
		rs += 1
		b.append(l[0])
		e.append(l[len(l) - 1])
	else:
		ok += 1
ans = 0
ans += ok * n
ans += rs * ok
e.sort()
b.sort()
l = len(e)
ib = 0
ie = 0
f = True
while ie < l and f:
	while e[ie] >= b[ib]:
		ib += 1
		if ib == l:
			f = False
			print(ans)
			break
	ans += l - ib
	ie += 1
if f:
	print(ans)


import sys
from bisect import bisect_left

def readline():
	return sys.stdin.readline().strip().split(' ')

def has_ascent(seq):
	m = 1000001
	for x in seq:
		if x > m:
			return True
		else:
			m = x
	return False

def main():
	[n] = list(map(int, readline()))
	seqs = [list(map(int, readline()[1:])) for i in range(n)]
	seqs_false = [x for x in seqs if not has_ascent(x)]
	mins = list(map(min, seqs_false))
	maxs = list(map(max, seqs_false))
	maxs.sort()
	print(n * n - sum([bisect_left(maxs, x + 0.1) for x in mins]))
main()


from bisect import *
l1 = []
l2 = []
n = int(input())
for _ in range(n):
	(l, *s) = map(int, input().split())
	if sorted(s) == s[::-1]:
		l1.append(s[0])
		l2.append(s[-1])
l1.sort()
print(n ** 2 - sum((bisect(l1, x) for x in l2)))


import sys
input = sys.stdin.readline
n = int(input())
A = [list(map(int, input().split())) for i in range(n)]
B = [0] * n
for i in range(n):
	k = A[i][0]
	for j in range(2, k + 1):
		if A[i][j] > A[i][j - 1]:
			B[i] = (1 << 31, -1)
			break
	else:
		B[i] = (A[i][1], A[i][-1])
from operator import itemgetter
C = sorted(B, key=itemgetter(0))
D = sorted(B, key=itemgetter(1))
ANS = 0
ind = 0
for (_, d) in D:
	while ind < n and C[ind][0] <= d:
		ind += 1
	ANS += n - ind
print(ANS)


n = int(input())
self_ascent = 0
not_self_ascent = []
count = 0
for nn in range(n):
	s = list(map(int, input().split()))
	flag = 0
	for i in range(1, s[0]):
		if s[i] < s[i + 1]:
			flag = 1
			break
	if flag:
		self_ascent += 1
	else:
		not_self_ascent.append([s[1], s[-1]])
count += self_ascent * n + (n - self_ascent) * self_ascent
length = n - self_ascent
not_self_ascent.sort(key=lambda a: a[0])
for i in range(length):
	target = not_self_ascent[i][1]
	l = 0
	r = length
	mid = int((r + l) / 2)
	while r > l:
		mid = int((r + l) / 2)
		if target < not_self_ascent[mid][0]:
			r = mid
		else:
			l = mid + 1
	count += length - l
print(count)


from bisect import *

def checkascent(li):
	if all((li[i] <= li[i - 1] for i in range(2, li[0] + 1))):
		return 0
	else:
		return 1
(max_list, min_list) = ([], [])
n = int(input())
tot = 0
for i in range(n):
	l = list(map(int, input().split()))
	if checkascent(l) == 0:
		max_list.append(l[1])
		min_list.append(l[-1])
	else:
		tot += 2 * n - 1
		n -= 1
max_list.sort()
min_list.sort()
for i in max_list:
	tot += bisect_left(min_list, i)
print(tot)


import bisect

def main():
	n = int(input())
	seq = []
	for i in range(n):
		line = input().split()[1:]
		seq.append(list(map(int, line)))
	(f1, f2, f3) = ([float('-inf')] * n, [float('inf')] * n, [False] * n)
	for (i, x) in enumerate(seq):
		f1[i] = max(seq[i])
		f2[i] = min(seq[i])
		for j in range(1, len(seq[i])):
			if seq[i][j] > seq[i][j - 1]:
				f3[i] = True
				break
	count1 = 0
	(small, big) = ([], [])
	for i in range(n):
		if f3[i]:
			count1 += 1
		else:
			small.append(f2[i])
			big.append(f1[i])
	count2 = 0
	big.sort()
	for x in small:
		count2 += len(big) - bisect.bisect_right(big, x) + count1
	print(count1 * n + count2)
main()


n = int(input())
maxi = []
mini = []
for i in range(n):
	s = list(map(int, input().split()))[1:]
	if s == sorted(s, key=lambda x: -x):
		maxi.append(s[0])
		mini.append(s[-1])
mini.sort()
maxi.sort()
total = n * n
aux = 0
for i in range(len(mini)):
	while aux < len(maxi) and mini[i] >= maxi[aux]:
		aux += 1
	total -= aux
print(total)


import bisect
n = int(input())
(count, k) = (0, 0)
(p, l) = ([], [])
for i in range(n):
	(m, *a) = map(int, input().split())
	if sorted(a) == a[::-1]:
		l.append(a[0])
		p.append(a[-1])
l.sort()
print(n * n - sum((bisect.bisect(l, x) for x in p)))


n = int(input())
minl = []
maxl = []
ans = 0
asclen = 0
for q in range(n):
	a = list(map(int, input().split()))
	a = a[1:]
	cur = a[0]
	cur2 = a[0]
	asc = False
	for i in range(len(a)):
		if a[i] > cur:
			asc = True
		cur = min(a[i], cur)
		cur2 = max(a[i], cur2)
	if not asc:
		minl.append(cur)
		maxl.append(cur2)
	if asc:
		ans += 2 * n - 2 * asclen - 1
		asclen += 1
minl = sorted(minl)
maxl = sorted(maxl)
(i, j) = (0, 0)
while i < len(minl) and j < len(maxl):
	if minl[i] < maxl[j]:
		ans += len(minl) - j
		i += 1
	else:
		j += 1
print(ans)


import sys
input = sys.stdin.readline
read = lambda : map(int, input().split())
read_float = lambda : map(float, input().split())

def ceil(x):
	if x != int(x):
		x = int(x) + 1
	return x

def factorial(x, m):
	val = 1
	while x > 0:
		val = val * x % m
		x -= 1
	return val

def fact(x):
	val = 1
	while x > 0:
		val *= x
		x -= 1
	return val

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

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

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

def nCr(n, k):
	if k > n:
		return 0
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

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

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

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

def phi(n):
	result = n
	p = 2
	while p * p <= n:
		if n % p == 0:
			while n % p == 0:
				n = n // p
			result = result * (1.0 - 1.0 / float(p))
		p = p + 1
	if n > 1:
		result = result * (1.0 - 1.0 / float(n))
	return int(result)

def is_prime(n):
	if n == 0:
		return False
	if n == 1:
		return True
	for i in range(2, int(n ** (1 / 2)) + 1):
		if not n % i:
			return False
	return True
MAXN = int(100000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i
spf = [0 for i in range(MAXN)]

def factoriazation(x):
	res = []
	for i in range(2, int(x ** 0.5) + 1):
		while x % i == 0:
			res.append(i)
			x //= i
	if x != 1:
		res.append(x)
	return res

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

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

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

def str_array():
	return input().strip().split()

def binary_search(low, high, w, h, n):
	while low < high:
		mid = low + (high - low) // 2
		if check(mid, w, h, n):
			low = mid + 1
		else:
			high = mid
	return low

def check(councils, a, k):
	summ = 0
	for x in a:
		summ += min(x, councils)
	return summ // councils >= k
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
from itertools import permutations
import math
import bisect as bis
import random
import sys

def solve():
	n = int(input())
	(l, r) = ([], [])
	for i in range(n):
		s = list(read())
		s = s[1:]
		if s[::-1] == sorted(s):
			bis.insort(l, s[0])
			r.append(s[-1])
	print(n ** 2 - sum((bis.bisect(l, x) for x in r)))
for _ in range(1):
	solve()


n = int(input())
total = 0
mini = []
maxi = []
import bisect
count = 0
for i in range(n):
	l = list(map(int, input().split()))
	x = l[1:]
	minimum = l[1]
	flag = 0
	a = l[1]
	b = l[1]
	for j in range(1, l[0]):
		if x[j] < a:
			a = x[j]
		if x[j] > b:
			b = x[j]
		if x[j] > minimum:
			flag = 1
			break
		else:
			minimum = x[j]
	if flag == 1:
		total += 2 * n - 1
		count += 1
	else:
		mini.append(a)
		maxi.append(b)
mini.sort()
maxi.sort()
if count > 0:
	total -= count * (count - 1)
for j in mini:
	pos = bisect.bisect_right(maxi, j)
	diff = len(maxi) - pos
	total += diff
print(total)


from bisect import bisect_left
f = []
l = []
n = int(input())
for _ in range(n):
	a = list(map(int, input().split()))
	for i in range(2, a[0] + 1):
		if a[i] > a[i - 1]:
			break
	else:
		f.append(a[1])
		l.append(a[-1])
l.sort()
f.sort()
count = 0
for i in f:
	count += len(l) - bisect_left(l, i)
print(n * n - count)


import os
import sys
from io import BytesIO, IOBase
import math
from itertools import permutations
from decimal import Decimal, getcontext
getcontext().prec = 25
MOD = pow(10, 9) + 7
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')
a = 0
c = 0
n = int(input())
m = []
ml = []
for _ in range(n):
	mi = 999999999999
	ma = 0
	l = list(map(int, input().split(' ')))
	if l[0] == 1:
		m.append([l[1], l[1]])
		ml.append(l[1])
	else:
		inc = 0
		for i in range(1, l[0]):
			if l[i] < l[i + 1]:
				inc = 1
				break
			mi = min(mi, l[i])
			ma = max(ma, l[i])
		if inc:
			c += 1
		else:
			m.append([min(mi, l[l[0]]), max(ma, l[l[0]])])
			ml.append(max(ma, l[l[0]]))
m.sort(reverse=True)
ml.sort(reverse=True)
ans = c * n
bigg = 0
big = 0
x = len(ml)
for i in range(x):
	while big < x:
		if ml[big] > m[i][0]:
			big += 1
		else:
			break
	ans += big + c
print(ans)


import bisect
ans = 0
inp1 = []
inp2 = []
n = int(input())
for _ in range(n):
	(_, inp) = input().split(maxsplit=1)
	si = list(map(int, inp.split()))
	if si != sorted(si, reverse=True):
		ans += n
		n -= 1
		ans += n
	else:
		inp1.append(si[0])
		inp2.append(si[-1])
inp1.sort()
inp2.sort()
for i in range(n):
	inp_i = inp1[i]
	bs = bisect.bisect_left(inp2, inp_i)
	ans += bs
print(ans)


import bisect

def getmax(arr):
	i = 0
	mx = arr[0]
	for ind in range(1, len(arr)):
		if mx <= arr[ind]:
			mx = arr[ind]
			i = ind
	return [mx, i]

def getmin(arr):
	i = 0
	mn = arr[0]
	for ind in range(1, len(arr)):
		if mn > arr[ind]:
			mn = arr[ind]
			i = ind
	return [mn, i]

def ascend(arr):
	ans = False
	for i in range(1, len(arr)):
		if arr[i - 1] < arr[i]:
			ans = True
			break
	return ans
dc = []
c = []
minarr = []
maxarr = []
t = int(input())
for i in range(t):
	arr = [int(i) for i in input().split()]
	(mx, mxi) = getmax(arr[1:])
	(mn, mni) = getmin(arr[1:])
	if ascend(arr[1:]):
		dc.append([mn, mx])
	else:
		minarr.append(mn)
		maxarr.append(mx)
maxarr.sort()
ans = 0
ans = len(dc) * (2 * t - 1) - len(dc) * (len(dc) - 1)
for i in minarr:
	pos = bisect.bisect_right(maxarr, i)
	ans += len(maxarr) - pos
print(ans)


from bisect import bisect_right as bi
b = []
c = []
n = int(input())
ans = n ** 2
for _ in range(n):
	a = list(map(int, input().split()))
	f = 1
	for i in range(1, len(a) - 1):
		if a[i] < a[i + 1]:
			f = 0
			break
	if f or len(a) == 2:
		b.append(a[1])
		c.append(a[-1])
b.sort()
c.sort()
for i in range(len(c)):
	ans -= bi(b, c[i])
print(ans)


n = int(input())
mx = []
num = [0] * 1000005
for _ in range(n):
	ls = list(map(int, input().split()))
	tmp_mx = -1
	tmp_mi = 1000000.0 + 5
	for i in range(1, ls[0]):
		if ls[i + 1] > ls[i]:
			ls[-1] = -1
			ls[1] = 1000000
			break
	mx.append(ls[1])
	num[ls[-1] + 1] += 1
for i in range(1, 1000001):
	num[i] += num[i - 1]
ans = 0
for i in mx:
	ans += num[i]
print(ans)


n_seq = int(input())
extrema = []
special = 0
for _ in range(n_seq):
	(len_seq, *seq) = [int(i) for i in input().split()]
	if len_seq == 1:
		extrema.append([seq[0], 0])
		extrema.append([seq[0], 1])
	else:
		s = sorted(seq)[::-1]
		if seq == s:
			extrema.append([s[-1], 0])
			extrema.append([s[0], 1])
		else:
			special += 1
non_special = n_seq - special
extrema = sorted(extrema, key=lambda x: x[0] - x[1] / 2)
n_mins = 0
total = 0
for ex in extrema:
	if ex[1] == 0:
		n_mins += 1
	else:
		total += n_mins
total += n_seq ** 2 - non_special ** 2
print(total)


import sys
n = int(input())
arr = []
for i in range(n):
	arr.append(list(map(int, input().split()))[1:])
f = [0 for _ in range(n)]
max_1 = [-1 for _ in range(n)]
min_1 = [10 ** 7 for _ in range(n)]
for i in range(n):
	for j in arr[i]:
		if j > min_1[i]:
			f[i] = 1
		min_1[i] = min(min_1[i], j)
		max_1[i] = max(max_1[i], j)
min_2 = sorted(min_1)
max_2 = sorted(max_1)
res = sum(f) * (n - sum(f)) * 2 + sum(f) * sum(f)
min_3 = []
max_3 = []
for i in range(n):
	if f[i] == 0:
		max_3.append(max_1[i])
		min_3.append(min_1[i])
max_4 = sorted(max_3)
min_4 = sorted(min_3)
for i in range(len(max_4)):
	L = -1
	R = len(max_4)
	while R - L > 1:
		m = (R + L) // 2
		if max_4[m] <= min_3[i]:
			L = m
		else:
			R = m
	res += len(max_4) - R
print(res)


import sys
input = sys.stdin.buffer.readline
from bisect import bisect_left as bl
n = int(input())
allMins = []
allMaxs = []
seqHasAscentInItselfCnt = 0
for _ in range(n):
	s = [int(x) for x in input().split()][1:]
	minsofar = float('inf')
	hasAscent = False
	for x in s:
		if x > minsofar:
			hasAscent = True
			break
		minsofar = min(minsofar, x)
	if hasAscent:
		seqHasAscentInItselfCnt += 1
	else:
		(a, b) = (min(s), max(s))
		allMins.append(a)
		allMaxs.append(b)
ans = 0
allMins.sort()
for i in range(len(allMaxs)):
	maxx = allMaxs[i]
	idx = bl(allMins, maxx)
	ans += idx + seqHasAscentInItselfCnt
ans += seqHasAscentInItselfCnt * n
print(ans)


n = int(input())
maximos = []
minimos = []
x = 0
y = 0
for nn in range(n):
	s = list(map(int, input().split()))
	s = s[1:]
	for i in range(len(s)):
		if i > 0 and s[i] > s[i - 1]:
			x += 1
			break
		elif i == len(s) - 1:
			y += 1
			minimos.append(min(s))
			maximos.append(max(s))
t = x * x + 2 * x * y
minimos.sort()
maximos.sort()
i = 0
for mx in maximos:
	while i < y and minimos[i] < mx:
		i += 1
	t += i
print(t)


import bisect
n = int(input())
b = []
l = []
k = 0
for i in range(n):
	a = list(map(int, input().split()))
	f = 0
	p = a[1]
	for j in range(2, a[0] + 1):
		p = min(p, a[j])
		if a[j] > p:
			f = 1
			k += 1
			break
	if f == 0:
		l.append(a[1:])
		b.append(a[1])
x = len(b)
b.sort()
ans = 0
for i in range(k):
	ans += (n - i) * 2 - 1
for i in range(x):
	ans += max(x - bisect.bisect_right(b, l[i][-1]), 0)
print(ans)


import bisect
n = int(input())
total = 0
sequences_maxes_without_ascent = []
sequences_mins_and_maxes_without_ascent = []
seen_ascents = 0
for i in range(n):
	s = list(map(int, input().split()))
	ascent = False
	for i in range(1, len(s) - 1):
		if s[i] < s[i + 1]:
			ascent = True
			break
	if ascent:
		total += 2 * (n - seen_ascents) - 1
		seen_ascents += 1
	else:
		sequences_mins_and_maxes_without_ascent.append((s[-1], s[1]))
		sequences_maxes_without_ascent.append(s[1])
sequences_maxes_without_ascent.sort()
for (min_val, max_val) in sequences_mins_and_maxes_without_ascent:
	total += len(sequences_maxes_without_ascent) - bisect.bisect_right(sequences_maxes_without_ascent, min_val)
print(total)


n_entradas = int(input())
(n_acessoes, n_n_acessoes) = (0, 0)
(maximos, minimos) = ([], [])
for i in range(n_entradas):
	entrada = list(map(int, input().split()))[1:]
	for i in range(len(entrada)):
		if i > 0 and entrada[i] > entrada[i - 1]:
			n_acessoes += 1
			break
		if i == len(entrada) - 1:
			n_n_acessoes += 1
			maximos.append(max(entrada))
			minimos.append(min(entrada))
total = n_acessoes * n_acessoes + 2 * n_acessoes * n_n_acessoes
maximos.sort()
minimos.sort()
i = 0
for j in maximos:
	while i < n_n_acessoes and minimos[i] < j:
		i += 1
	total += i
print(total)


n = int(input())
first_elements = list()
last_elements = list()
pairs = 0

def has_ascent(ll):
	min_ll = ll[0]
	for i in range(1, len(ll)):
		if min_ll < ll[i]:
			return True
		if ll[i] < min_ll:
			min_ll = ll[i]
for _ in range(n):
	l = list(map(int, input().split()))[1:]
	if has_ascent(l):
		pairs += n * 2 - 1
		n -= 1
	else:
		first_elements.append(l[0])
		last_elements.append(l[-1])
first_elements = sorted(first_elements)
last_elements = sorted(last_elements)
found_index = 0
for element in last_elements:
	min_index = found_index
	found_index = len(first_elements)
	for index in range(min_index, len(first_elements)):
		if first_elements[index] > element:
			found_index = index
			break
	pairs += len(first_elements) - found_index
print(pairs)


import sys
input = sys.stdin.readline
import bisect
cou = 0
nn = int(input())
arr = []
se = []
for i in range(nn):
	l = list(map(int, input().split()))
	n = l[0]
	mi = 100000000000
	mx = -1
	lol = False
	for j in range(1, n + 1):
		mx = max(mx, l[j])
		mi = min(mi, l[j])
		if j > 1:
			if l[j] > l[j - 1]:
				lol = True
	if lol:
		cou += 1
	else:
		se.append(mi)
	arr.append([mi, mx, lol])
arr.sort()
se.sort()
res = 0
for i in arr:
	if i[2]:
		res += nn
	else:
		res += cou
		pos = bisect.bisect_left(se, i[1])
		res += pos
print(res)


n = int(input())
s = []
l = []
ans = n ** 2
for i in range(n):
	a = list(map(int, input().split()))[1:]
	if sorted(a)[::-1] == a:
		s.append(min(a))
		l.append(max(a))
s.sort()
l.sort()
c = 0
for i in range(len(s)):
	while c < len(l) and l[c] <= s[i]:
		c += 1
	ans -= c
print(ans)


import bisect

def possible(arr):
	max_val = 0
	arr.reverse()
	for i in arr:
		if i < max_val:
			return True
		max_val = max(max_val, i)
	return False

def main():
	n = int(input())
	min_vals = []
	max_vals = []
	pairs = 0
	already = 0
	for i in range(n):
		nums = list(map(int, input().split()))
		nums.pop(0)
		min_val = min(nums)
		max_val = max(nums)
		if possible(nums):
			pairs += n
			already += 1
		else:
			min_vals.append(min_val)
			max_vals.append(max_val)
	max_vals.sort()
	for i in min_vals:
		index = bisect.bisect(max_vals, i)
		pairs += len(max_vals) - index
		pairs += already
	print(pairs)
main()


import sys
from bisect import bisect
input = sys.stdin.buffer.readline
q = int(input())
x = []
y = []
for _ in range(q):
	a = list(map(int, input().split()))[1:]
	nice = False
	tem = 10 ** 10
	for z in a:
		if z > tem:
			nice = True
			break
		tem = z
	if not nice:
		x.append((a[0], a[-1]))
		y.append(a[-1])
y.sort()
total = 0
for xx in x:
	t = len(x) - bisect(y, xx[0] - 1)
	total += t
print(q * q - total)


def have(a):
	mi = 10 ** 10
	for i in range(len(a)):
		if a[i] > mi:
			return True
		else:
			mi = a[i]
	return False
n = int(input())
t = list()
ans = 0
k = n
for i in range(n):
	a = list(map(int, input().split()))[1:]
	if have(a):
		ans += max(0, k + k - 1)
		k -= 1
	else:
		t.append([min(a), max(a)])
t.sort()
for i in range(len(t)):
	x = t[i][1]
	l = 0
	r = len(t)
	while l < r:
		y = (l + r) // 2
		if t[y][0] >= x:
			r = y
		else:
			l = y + 1
	ans += l
print(ans)


n = int(input())
los = []
his = []
count = 0
for i in range(n):
	li = [int(s) for s in input().split()]
	(mi, ma) = (li[1], li[1])
	isasc = False
	for j in range(1, li[0] + 1):
		if li[j] > mi:
			isasc = True
			break
		if li[j] < mi:
			mi = li[j]
		elif li[j] > ma:
			ma = li[j]
	if not isasc:
		los.append(mi)
		his.append(ma)
m = len(los)
count = n * n - m * m
his.sort()
los.sort()
(i, j) = (0, 0)
while i < m and j < m:
	if his[j] > los[i]:
		count += m - j
		i += 1
	elif j + 1 < m:
		j += 1
	else:
		break
print(count)


import os
from io import BytesIO, IOBase
import sys
from collections import defaultdict, deque, Counter
from bisect import *
from math import sqrt, pi, ceil, log, inf, gcd, floor
from itertools import permutations
from copy import deepcopy
from heapq import *

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

def main():
	a = []
	m = int(input())
	a = []
	c = []
	for i in range(m):
		b = list(map(int, input().split()))
		n = len(b)
		f = 1
		for i in range(1, n - 1):
			if b[i + 1] > b[i]:
				f = 0
				break
		if f:
			a.append(b[1])
			c.append(b[-1])
	a.sort()
	ans = 0
	for i in c:
		x = bisect_right(a, i)
		ans += x
	print(m * m - ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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


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
n = int(input())
c = 0
mi = []
ma = []
for i in range(n):
	l1 = list(map(int, input().split()))
	mir = 10000000
	mar = -1
	fl = 0
	for j in range(1, len(l1)):
		if l1[j] <= mir:
			mir = l1[j]
		else:
			fl = 1
			break
	if fl == 0:
		mas = max(l1[1:])
		mis = min(l1[1:])
		ma.append(mas)
		mi.append(mis)
	else:
		c += 1
ans = 0
ans = 2 * (n - 1) * c
ans += c
su = c * (c - 1)
ans -= su
ma.sort()
mi.sort()
an = 0
for i in mi:
	c = countGreater(ma, len(ma), i)
	an += c
ans += an
print(ans)


from collections import Counter
n = int(input())
smin = []
smax = []
tot = 0
bite = -1
for i in range(n):
	ss = list(map(int, input().split()[1:]))
	if ss == sorted(ss, reverse=True):
		smin += [min(ss)]
		smax += [max(ss)]
	else:
		bite += 1
		tot += 2 * (n - bite) - 1
dmax = {}
t = 0
cmax = Counter(smax)
for i in range(10 ** 6 + 2, -10, -1):
	if i in cmax.keys():
		t += cmax[i]
	dmax[i] = t
for i in smin:
	try:
		tot += dmax[i + 1]
	except:
		pass
print(tot)


n = int(input())
mxs = []
mns = []
(cnti, cntj) = (0, 0)
for _ in range(n):
	sl = list(input().split())
	s = int(sl[0])
	l = list(map(int, sl[1:]))
	flag = False
	mx = 0
	mn = 10 ** 6
	if s > 1:
		for i in range(s - 1):
			if l[i] < l[i + 1]:
				flag = True
				cnti += 1
				break
			if l[i] > mx:
				mx = l[i]
			if l[i] < mn:
				mn = l[i]
		if not flag:
			if l[s - 1] > mx:
				mx = l[s - 1]
			if l[s - 1] < mn:
				mn = l[s - 1]
			mxs.append(mx)
			mns.append(mn)
			cntj += 1
	else:
		cntj += 1
		mn = min(l)
		mx = max(l)
		mxs.append(mx)
		mns.append(mn)
tot = cnti * cnti + 2 * cnti * cntj
mns.sort()
mxs.sort()
(mni, mxi) = (0, 0)
while mxi < cntj:
	if mni == cntj:
		pass
	else:
		while mns[mni] < mxs[mxi]:
			mni += 1
			if mni == cntj:
				break
	tot += mni
	mxi += 1
print(tot)


from array import array
from sys import stdin
import bisect
from itertools import *

def scan_gen():
	for line in stdin:
		yield from iter(line.split())
scan = scan_gen()

def nint():
	return int(next(scan))

def nintk(k):
	return tuple((nint() for _ in range(k)))

def nfloat():
	return float(next(scan))

def intar_init(size):
	return array('i', [0]) * size

def intar(size=None):
	if size == None:
		size = nint()
	arr = intar_init(size)
	for x in range(size):
		arr[x] = nint()
	return arr

def solve():
	n = nint()
	asc = 0
	m = []
	M = []
	for _ in range(n):
		A = intar()
		a = False
		for i in range(1, len(A)):
			if A[i] > A[i - 1]:
				a = True
				break
		if a:
			asc += 1
		else:
			m.append(min(A))
			M.append(max(A))
	res = asc * n
	M.sort()
	for i in range(len(M)):
		res += asc
		x = bisect.bisect_right(M, m[i])
		res += len(M) - x
	print(res)
solve()


import sys
from bisect import bisect_right
input = sys.stdin.readline
n = int(input())
mins = []
maxs = []
alreadyGood = 0
for i in range(n):
	(l, *s) = map(int, input().split())
	currMin = float('inf')
	for val in s:
		if val > currMin:
			alreadyGood += 1
			break
		currMin = min(currMin, val)
	else:
		mins.append(min(s))
		maxs.append(max(s))
m = len(mins)
maxs.sort()
goodCombos = alreadyGood * n + n * alreadyGood - alreadyGood ** 2
for mn in mins:
	k = bisect_right(maxs, mn)
	goodCombos += m - k
print(goodCombos)


import bisect
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
minn = []
maxx = []
asc = []
maxxx = []
n = int(input())
for sequence in range(n):
	delta = [int(x) for x in input().split()]
	len = delta[0]
	seq = delta[1:]
	mi = float('inf')
	ma = -1 * float('inf')
	FLAG = 0
	for i in range(len):
		if seq[i] <= mi:
			mi = seq[i]
		else:
			FLAG = 1
		if seq[i] > ma:
			ma = seq[i]
	asc.append(FLAG)
	minn.append(mi)
	maxx.append([ma, FLAG])
	maxxx.append(ma)
ans = 0
maxx.sort()
maxxx.sort()
cumsum = [0] * (n + 1)
for i in range(1, n + 1):
	cumsum[i] = cumsum[i - 1] + maxx[i - 1][1]
for i in range(n):
	if asc[i] == 1:
		ans += n
	else:
		pos = bisect.bisect_right(maxxx, minn[i])
		ans += cumsum[pos]
		ans += n - pos
print(ans)


t = int(input())
n = t
ans = 0
maxA = []
minA = []
for i in range(t):
	inp = list(map(int, input().split()))[1:]
	if sorted(inp) == inp[::-1]:
		maxA.append(inp[0])
		minA.append(inp[-1])
	else:
		ans += n * 2 - 1
		n -= 1
minA = sorted(minA)
maxA = sorted(maxA)
curr = 0
for x in maxA:
	j = curr
	while j < len(minA):
		if minA[j] < x:
			j += 1
			curr += 1
		else:
			break
	ans += curr
print(ans)


import sys
import math
import heapq
import collections

def inputnum():
	return int(input())

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

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

def inputstring():
	return [x for x in input()]

def inputstringnum():
	return [ord(x) - ord('a') for x in input()]

def inputmatrixchar(rows):
	arr2d = [[j for j in input().strip()] for i in range(rows)]
	return arr2d

def inputmatrixint(rows):
	arr2d = []
	for _ in range(rows):
		arr2d.append([int(i) for i in input().split()])
	return arr2d
n = inputnum()
good = 0
bad = 0
mins = []
maxs = []
for _ in range(n):
	s = inputlist()
	l = s[0]
	small = 10000000
	big = 0
	gud = False
	for i in range(1, l + 1):
		if i > 1 and s[i] > small and (not gud):
			good += 1
			gud = True
		small = min(small, s[i])
		big = max(big, s[i])
	if not gud:
		mins.append(small)
		maxs.append(big)
mins.sort()
maxs.sort()
mins.append(10000000)
cur = 0
for i in range(len(maxs)):
	while mins[cur] < maxs[i] and cur < len(mins):
		cur += 1
	bad += cur
print(good * good + 2 * (n - good) * good + bad)


import sys

def fastio():
	from io import StringIO
	from atexit import register
	global input
	sys.stdin = StringIO(sys.stdin.read())
	input = lambda : sys.stdin.readline().rstrip('\r\n')
	sys.stdout = StringIO()
	register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()

def debug(*var, sep=' ', end='\n'):
	print(*var, file=sys.stderr, end=end, sep=sep)
INF = 10 ** 20
MOD = 10 ** 9 + 7
I = lambda : list(map(int, input().split()))
from math import gcd
from math import ceil
from collections import defaultdict as dd, Counter
from bisect import bisect_left as bl, bisect_right as br
(n,) = I()
maxs = []
mins = []
ans = 0
elim = 0
for i in range(n):
	(m, *a) = I()
	cur_min = INF
	for j in a:
		if j > cur_min:
			ans += 2 * n - 1 - 2 * elim
			elim += 1
			break
		cur_min = min(cur_min, j)
	else:
		mins.append([min(a), i])
		maxs.append(max(a))
maxs.sort()
n = len(mins)
for i in range(len(mins)):
	ans += n - br(maxs, mins[i][0])
print(ans)


from bisect import *
n = int(input())
cnt_wh = 0
mns = []
mxs = []
correct = 0
for _ in range(n):
	(l, *sl) = map(int, input().split())
	wh = False
	for i in range(l - 1):
		if sl[i + 1] > sl[i]:
			wh = True
			break
	if wh:
		cnt_wh += 1
	else:
		mn = min(sl)
		mx = max(sl)
		mns.append(mn)
		mxs.append(mx)
		if mx > mn:
			correct += 1
mns.sort()
mxs.sort()
mm = len(mns)
res = sum((mm - bisect_right(mxs, x) for x in mns))
print(res + cnt_wh * n * 2 - cnt_wh ** 2)


import bisect
n = int(input())
ans = 0
res_min = []
res_max = []
cnt = 0
for _ in range(n):
	arr = [int(x) for x in input().split()]
	length = arr[0]
	tr = True
	for i in range(1, length):
		if arr[i] < arr[i + 1]:
			ans += 2 * (n - cnt) - 1
			cnt += 1
			tr = False
			break
	if tr:
		res_max.append(arr[1])
		res_min.append(arr[-1])
res_max.sort()
for i in range(len(res_min)):
	ind = bisect.bisect_right(res_max, res_min[i])
	ans += len(res_max) - ind
print(ans)


n = int(input())
minimos = []
maximos = []
total = 0
ascent = 0
nasc = 0
for i in range(n):
	sequencia = list(map(int, input().split()))[1:]
	for i in range(len(sequencia)):
		if i > 0 and sequencia[i] > sequencia[i - 1]:
			ascent += 1
			break
		elif i == len(sequencia) - 1:
			nasc += 1
			minimos.append(min(sequencia))
			maximos.append(max(sequencia))
total += ascent ** 2 + 2 * ascent * nasc
minimos = sorted(minimos)
maximos = sorted(maximos)
mi = 0
for maior in maximos:
	while mi < n - ascent and minimos[mi] < maior:
		mi += 1
	total += mi
print(int(total))


def binary_search(l, f, na):
	low = 0
	high = na - 1
	while low <= high:
		middle = (low + high) // 2
		if f[middle] <= l:
			low = middle + 1
		else:
			high = middle - 1
	if f[middle] <= l:
		return middle
	return middle - 1
t = int(input())
f = []
l = []
na = 0
for _ in range(t):
	mini = 1000001
	maxi = 0
	found = False
	for x in input().split()[1:]:
		temp = int(x)
		if temp > mini:
			found = True
		mini = min(mini, temp)
		maxi = max(maxi, temp)
	if not found:
		na += 1
		f.append(maxi)
		l.append(mini)
f.sort()
ans = 0
for x in l:
	s = binary_search(x, f, na)
	ans += s + 1
print(t * t - ans)


import math
from decimal import Decimal
import heapq
import copy
from collections import deque

def na():
	n = int(input())
	b = [int(x) for x in input().split()]
	return (n, b)

def nab():
	n = int(input())
	b = [int(x) for x in input().split()]
	c = [int(x) for x in input().split()]
	return (n, b, c)

def dv():
	(n, m) = map(int, input().split())
	return (n, m)

def da():
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	return (n, m, a)

def dva():
	(n, m) = map(int, input().split())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	return (n, m, b)

def eratosthenes(n):
	sieve = list(range(n + 1))
	for i in sieve:
		if i > 1:
			for j in range(i + i, len(sieve), i):
				sieve[j] = 0
	return sorted(set(sieve))

def lol(lst, k):
	k = k % len(lst)
	ret = [0] * len(lst)
	for i in range(len(lst)):
		if i + k < len(lst) and i + k >= 0:
			ret[i] = lst[i + k]
		if i + k >= len(lst):
			ret[i] = lst[i + k - len(lst)]
		if i + k < 0:
			ret[i] = lst[i + k + len(lst)]
	return ret

def nm():
	n = int(input())
	b = [int(x) for x in input().split()]
	m = int(input())
	c = [int(x) for x in input().split()]
	return (n, b, m, c)

def dvs():
	n = int(input())
	m = int(input())
	return (n, m)

def fact(a, b):
	c = []
	ans = 0
	f = int(math.sqrt(a))
	for i in range(1, f + 1):
		if a % i == 0:
			c.append(i)
	l = len(c)
	for i in range(l):
		c.append(a // c[i])
	for i in range(len(c)):
		if c[i] <= b:
			ans += 1
	if a / f == f and b >= f:
		return ans - 1
	return ans
import math
from decimal import Decimal
import heapq
from collections import deque

def na():
	n = int(input())
	b = [int(x) for x in input().split()]
	return (n, b)

def nab():
	n = int(input())
	b = [int(x) for x in input().split()]
	c = [int(x) for x in input().split()]
	return (n, b, c)

def dv():
	(n, m) = map(int, input().split())
	return (n, m)

def da():
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	return (n, m, a)

def dva():
	(n, m) = map(int, input().split())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	return (n, m, b)

def eratosthenes(n):
	sieve = list(range(n + 1))
	for i in sieve:
		if i > 1:
			for j in range(i + i, len(sieve), i):
				sieve[j] = 0
	return sorted(set(sieve))

def lol(lst, k):
	k = k % len(lst)
	ret = [0] * len(lst)
	for i in range(len(lst)):
		if i + k < len(lst) and i + k >= 0:
			ret[i] = lst[i + k]
		if i + k >= len(lst):
			ret[i] = lst[i + k - len(lst)]
		if i + k < 0:
			ret[i] = lst[i + k + len(lst)]
	return ret

def nm():
	n = int(input())
	b = [int(x) for x in input().split()]
	m = int(input())
	c = [int(x) for x in input().split()]
	return (n, b, m, c)

def dvs():
	n = int(input())
	m = int(input())
	return (n, m)

def fact(a, b):
	c = []
	ans = 0
	f = int(math.sqrt(a))
	for i in range(1, f + 1):
		if a % i == 0:
			c.append(i)
	l = len(c)
	for i in range(l):
		c.append(a // c[i])
	for i in range(len(c)):
		if c[i] <= b:
			ans += 1
	if a / f == f and b >= f:
		return ans - 1
	return ans
n = int(input())
mn = []
ans = 0
mx = []
k = 0
for i in range(n):
	b = list(map(int, input().split()))
	b = b[1:b[0] + 1]
	if sorted(b, reverse=True) != b:
		ans += n * 2
		k += 1
	else:
		mnn = min(b)
		mxx = max(b)
		mn.append((mnn, i))
		mx.append((mxx, i))
mn.sort()
ans -= k ** 2
mx.sort()
j = 0
oldn = n
n = len(mn)
tc = 0
for i in range(n):
	if j < n and mn[i][0] < mx[j][0]:
		ans += n - j
		tc += 1
	else:
		while j < n and mn[i][0] >= mx[j][0]:
			j += 1
		if j < n and mn[i][0] < mx[j][0]:
			ans += n - j
			tc += 1
print(ans)


n = int(input())
res = n ** 2
mil = []
mal = []
for i in range(n):
	s = list(map(int, input().split()))
	n = s[0]
	s = s[1:]
	(mi, ma) = (float('inf'), float('-inf'))
	for i in range(n):
		if i + 1 < n and s[i] < s[i + 1]:
			break
		mi = min(mi, s[i])
		ma = max(ma, s[i])
	else:
		mil.append(mi)
		mal.append(ma)
mil.sort(reverse=True)
mal.sort(reverse=True)
tag = 0
for i in mil:
	for index in range(tag, len(mal)):
		j = mal[index]
		if i >= j:
			tag = index
			res -= len(mal) - index
			break
print(res)


import sys, bisect
input = sys.stdin.readline

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

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

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

def invr():
	return map(int, input().rstrip().split())
n = inp()
min_l = []
max_l = []
ans = 0
for i in range(n):
	nums = inlt()
	l = nums[0]
	nums = nums[1:]
	s = nums[0]
	has = False
	for i in range(1, l):
		if nums[i] > s:
			ans += n + (n - 1)
			has = True
			break
		if nums[i] < s:
			s = nums[i]
	if not has:
		the_min = min(nums)
		the_max = max(nums)
		min_l.append((the_min, i))
		max_l.append(the_max)
	else:
		n -= 1
min_l.sort()
max_l.sort()
for i in range(n):
	result = bisect.bisect_right(max_l, min_l[i][0])
	ans += n - result
print(ans)


from sys import stdin, stdout
import sys
from bisect import bisect_left, bisect_right

def check_already(arr):
	mn = arr[0]
	for i in range(1, len(arr)):
		if mn < arr[i]:
			return True
		mn = min(arr[i], mn)
	return False

def check_diff(arr):
	return len(set(arr)) != 1

def get_max_min(arr):
	mn = mx = arr[0]
	for i in range(1, len(arr)):
		mn = min(mn, arr[i])
		mx = max(mx, arr[i])
	return (mn, mx)

def get_from_fc(fc):
	return fc + fc * (2 * (n - fc)) + fc * (fc - 1)
n = int(stdin.readline().strip())
remain = set()
count = 0
minimum = []
maximum = []
maxi = dict()
fc = 0
mini = dict()
for _ in range(n):
	arr = list(map(int, stdin.readline().split()))[1:]
	if len(arr) == 1:
		remain.add(_)
	elif check_already(arr):
		fc += 1
		continue
	else:
		remain.add(_)
	(mn, mx) = get_max_min(arr)
	minimum.append(mn)
	maximum.append(mx)
	mini[_] = mn
	maxi[_] = mx
count += get_from_fc(fc)
maximum.sort()
minimum.sort()
for i in remain:
	index2 = bisect_right(maximum, mini[i])
	count += len(maximum) - index2
print(count)


import sys
input = lambda : sys.stdin.readline()
mi = []
ma = []
n = int(input())
ans = 0
k = 0
for i in range(n):
	a = list(map(int, input().split()))
	mina = a[1]
	maxa = a[1]
	f = True
	for j in range(len(a) - 2):
		maxa = max(maxa, a[j + 2])
		mina = min(mina, a[j + 2])
		if a[j + 1] < a[j + 2]:
			ans += 2 * (n - 1 - k) + 1
			k += 1
			f = False
			break
	if f:
		mi.append(mina)
		ma.append(maxa)
mi.sort()
ma.sort()
j = 0
for i in range(len(ma)):
	while j < len(ma) and ma[i] > mi[j]:
		j += 1
	ans += j
print(ans)


def func(l1, l2, num):
	print(l1[num % len(l1) - 1] + l2[num % len(l2) - 1])

def main():
	n = int(input())
	dctmx = dict()
	to_del = 0
	dctmn = dict()
	all = 0
	for i in range(n):
		add = True
		to_add = list(map(int, input().split()))[1:]
		mn = to_add[0]
		for r in to_add:
			if r > mn:
				to_del += 1
				add = False
				break
			else:
				mn = r
		if add:
			if not max(to_add) in dctmx:
				dctmx[max(to_add)] = 1
			else:
				dctmx[max(to_add)] += 1
			if not min(to_add) in dctmn:
				dctmn[min(to_add)] = 1
			else:
				dctmn[min(to_add)] += 1
	all += to_del ** 2 + to_del * ((n - to_del) * 2)
	lstmx = []
	for i in dctmx:
		lstmx.append([i, dctmx[i]])
	lstmn = []
	for i in dctmn:
		lstmn.append([i, dctmn[i]])
	lstmx = sorted(lstmx, key=lambda x: x[0])
	lstmn = sorted(lstmn, key=lambda x: x[0])
	for i in range(len(lstmx) - 1, 0, -1):
		lstmx[i - 1][1] = lstmx[i - 1][1] + lstmx[i][1]
	mx = 0
	for i in lstmn:
		for k in range(mx, len(lstmx)):
			if i[0] < lstmx[k][0]:
				all += i[1] * lstmx[k][1]
				break
			mx = k
	print(all)
t = 1
for i in range(t):
	main()


from bisect import *
n = int(input())
(f, l) = ([], [])
k = 0
for j in range(n):
	s = []
	(t, *s) = list(map(int, input().split()))
	if s[::-1] == sorted(s):
		f += [s[0]]
		l += [s[t - 1]]
f.sort()
for x in l:
	k += bisect(f, x)
print(n * n - k)


inf = float('inf')

def bsearch(value, array):
	maxr = len(array)
	(l, r) = (0, maxr - 1)
	while 0 <= l and l <= r and (r < maxr):
		mid = (l + r) // 2
		if array[mid] == value:
			l = mid + 1
		if array[mid] > value:
			r = mid - 1
		else:
			l = mid + 1
	return l
n = int(input())
(mins, maxs, asc) = ([], [], 0)
for i in range(n):
	line = list(map(int, input().split(' ')))
	(prev, pred) = (inf, False)
	for i in range(1, len(line)):
		if line[i] > prev:
			pred = True
			break
		prev = line[i]
	if pred == True:
		asc += 1
	else:
		mins.append(line[-1])
		maxs.append(line[1])
maxs.sort()
res = asc * (2 * (n - asc) + 1) + asc * (asc - 1)
q = 0
for i in mins:
	q += len(maxs) - bsearch(i, maxs)
print(res + q)


import bisect
n = int(input())
s = [0] * n
notok1 = []
notok2 = []
sum = 0
for i in range(n):
	s[i] = [int(x) for x in input().split()]
	s[i] = s[i][1:]
	before = 1 << 30
	for j in s[i]:
		if j > before:
			sum += n
			before = -1
			break
		before = j
	if before != -1:
		notok1.append(s[i][-1])
		notok2.append(s[i][0])
notok1.sort()
notok2.sort()
for i in notok1:
	v = bisect.bisect_right(notok2, i)
	sum += len(notok2) - v + (n - len(notok2))
print(sum)


from os import path
import sys, time
mod = int(1000000000.0 + 7)
from math import ceil, floor, gcd, log, log2, factorial, sqrt
from collections import defaultdict, Counter, OrderedDict, deque
from itertools import combinations, permutations
from bisect import *
from functools import reduce
from operator import mul
maxx = float('inf')
I = lambda : int(sys.stdin.buffer.readline())
lint = lambda : [int(x) for x in sys.stdin.buffer.readline().split()]
S = lambda : sys.stdin.readline().strip('\n')
grid = lambda r: [lint() for i in range(r)]
localsys = 0
start_time = time.time()
nCr = lambda n, r: reduce(mul, range(n - r + 1, n + 1), 1) // factorial(r)

def ceill(n, x):
	return (n + x - 1) // x
T = 0

def ok(A):
	N = A[0]
	for i in range(1, A[0]):
		if A[i + 1] > A[i]:
			return (-1, -1)
	return (A[1], A[-1])

def solve():
	n = I()
	arr = [lint() for _ in range(n)]
	(s, l, ans, p) = ([], [], 0, 0)
	for i in arr:
		(a, b) = ok(i)
		if a == b == -1:
			p += 1
			continue
		l.append(a)
		s.append(b)
	ans += p * n
	s.sort()
	l.sort()
	for i in l:
		ans += bisect_left(s, i) + p
	print(ans)

def run():
	if path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
run()
T = I() if T else 1
for _ in range(T):
	solve()
if localsys:
	print('\n\nTime Elased :', time.time() - start_time, 'seconds')


S = int(input())
K = []
B = 0

def isa(A):
	m = A[0]
	for i in range(1, len(A)):
		if A[i] < m:
			m = A[i]
		elif A[i] > m:
			return True
	return False
for s in range(S):
	A = list(map(int, input().split()))[1:]
	if isa(A):
		B += 1
	else:
		K += [[A[0], True], [A[-1], False]]
T = S * S - (S - B) * (S - B)
K.sort(key=lambda x: -x[0])
D = 0
X = 1
lastT = -1
for i in range(len(K)):
	if K[i][1]:
		D += 1
		if lastT == K[i][0]:
			X += 1
		else:
			lastT = K[i][0]
			X = 1
	else:
		T += D
		if K[i][0] == lastT:
			T -= X
print(T)


import sys
import bisect

def main():
	input_list = get_input()
	input_list = [[int(y) for y in x.split(' ')] for x in input_list]
	print(solve(input_list))

def get_input():
	input_list = []
	for line in sys.stdin:
		input_list.append(line.rstrip('\n'))
	return input_list

def solve(seq_list):
	del seq_list[0]
	n = len(seq_list)
	seq_list = [x for x in seq_list if x[1:] == sorted(x[1:], reverse=True)]
	first_index_list = sorted([seq_list[x][1] for x in range(len(seq_list))])
	last_index_list = sorted([seq_list[x][-1] for x in range(len(seq_list))])
	j = len(seq_list)
	total = n ** 2 - j ** 2
	for n in last_index_list:
		total += number_larger(first_index_list, n)
	return total

def number_larger(num_list, value):
	search = bisect.bisect(num_list, value)
	if search != len(num_list):
		return len(num_list) - search
	else:
		return 0

def binary_search(num_list, lower, upper, value):
	if lower == upper:
		if num_list[lower] > value:
			return lower
		else:
			return False
	mid = lower + (upper - lower) // 2
	if num_list[mid] > value:
		return binary_search(num_list, lower, mid, value)
	else:
		return binary_search(num_list, mid + 1, upper, value)

def is_descending(seq):
	return all((seq[x] >= seq[x + 1] for x in range(len(seq) - 1)))
main()


def bisect(arr, val):
	l = -1
	r = len(arr)
	while r - l > 1:
		m = l + r >> 1
		if arr[m] <= val:
			l = m
		else:
			r = m
	return r
n = int(input())
maxs = []
mins = []
acsents = 0
for ti in range(n):
	arr = list(map(int, input().split()))
	ok = False
	for i in range(2, len(arr)):
		if arr[i] > arr[i - 1]:
			ok = True
			break
	if ok:
		acsents += 2 * n - 1
		n -= 1
	else:
		mins.append(arr[-1])
		maxs.append(arr[1])
maxs.sort()
for i in range(len(mins)):
	mn = mins[i]
	pos = bisect(maxs, mn)
	count = len(maxs) - pos
	acsents += count
print(acsents)


R = lambda : map(int, input().split())
nums = []
cnts = [0] * (10 ** 6 + 7)
n = int(input())
res = 0
for _ in range(n):
	arr = list(R())[1:]
	is_good = any((x1 < x2 for (x1, x2) in zip(arr, arr[1:])))
	(mn, mx) = (min(arr), max(arr))
	if not is_good:
		cnts[mn] += 1
		nums.append(mx)
for i in range(len(cnts) - 2, -1, -1):
	cnts[i] += cnts[i + 1]
for mx in nums:
	res += cnts[mx]
print(n * n - res)


n = int(input())
s = n * n
fi = []
la = []

def binp(seq, num):
	l = 0
	r = len(seq) - 1
	if l == r:
		if seq[0] <= num:
			return 0
		else:
			return -1
	m = (l + r) // 2
	while l < r:
		m = (l + r) // 2
		if l == r - 1:
			if seq[r] <= num:
				return r
			elif seq[l] <= num:
				return l
			else:
				return l - 1
		if seq[m] > num:
			r = m
		else:
			l = m
	return m
for i in range(n):
	(g, *L) = [int(i) for i in input().split()]
	t = 1
	for j in range(1, g):
		if L[j] > L[j - 1]:
			t = 0
			break
	if t:
		fi.append(L[0])
		la.append(L[-1])
fi.sort()
la.sort()
for i in la:
	g = binp(fi, i) + 1
	s -= g
print(s)


import math as mt
import sys, string
from bisect import *
input = sys.stdin.readline
import random
from collections import deque, defaultdict
L = lambda : list(map(int, input().split()))
Ls = lambda : list(input().split())
M = lambda : map(int, input().split())
I = lambda : int(input())

def check(l):
	for i in range(len(l) - 1):
		if l[i] < l[i + 1]:
			return True
	else:
		return False
n = I()
ans = 0
x = []
y = []
for i in range(n):
	w = L()
	w = w[1:]
	if check(w):
		continue
	else:
		x.append(w[0])
		y.append(w[-1])
x.sort()
for i in y:
	ans += bisect(x, i)
print(n ** 2 - ans)


def binarySearch(arr, l, r, x, key=lambda x, y: x[0] >= y[1]):
	if r >= l:
		mid = l + (r - l) // 2
		if key(x, arr[mid]):
			t = binarySearch(arr, mid + 1, r, x, key)
			if t == -1:
				return mid
			else:
				return t
		else:
			return binarySearch(arr, l, mid - 1, x)
	else:
		return -1
n = int(input())
ls = []

def isAscent(l):
	s = l[0]
	for i in range(1, len(l)):
		if l[i] > s:
			return True
		else:
			s = l[i]
	return False

def fully_decreasing(l):
	for i in range(1, len(l)):
		if l[i] > l[i - 1]:
			return False
	return True
s = 0
t = 0
for i in range(n):
	l = list(map(int, input().split()))[1:]
	temp = fully_decreasing(l)
	if temp:
		ls.append((l[-1], l[0]))
s = 0
ls2 = sorted(ls, key=lambda x: x[1])
for e in ls:
	t = binarySearch(ls2, 0, len(ls2) - 1, e) + 1
	s += t
print(n * n - s)


import bisect
n = int(input())
first = []
last = []
count = 0

def check(t):
	for i in range(len(t) - 1):
		if t[i + 1] > t[i]:
			return 1
	return 0
for _ in range(n):
	t = list(input().split())
	t = [int(x) for x in t]
	t = t[1:]
	if check(t) == 1:
		count += 1
	else:
		first.append(t[0])
		last.append(t[-1])
count = n ** 2 - (n - count) ** 2
first = sorted(first)
for i in range(len(first)):
	index = bisect.bisect_right(first, last[i])
	count += len(first) - index
print(count)


from sys import stdin
from bisect import *
inp = lambda : stdin.readline().strip()
n = int(inp())
arrays = []
arrays2 = []
ascent = 0
for _ in range(n):
	x = [int(x) for x in inp().split()[1:]]
	for i in range(1, len(x)):
		if x[i] > x[i - 1]:
			ascent += 1
			break
	else:
		arrays.append(x[0])
		arrays2.append(x[-1])
ans = 0
for i in range(ascent):
	ans += (n - 1) * 2 - i * 2 + 1
arrays.sort()
arrays2.sort()
for i in arrays:
	ans += bisect_right(arrays2, i - 1)
print(ans)


from sys import stdin, stdout
n = int(stdin.readline().strip())
s = [list(map(int, stdin.readline().strip().split())) for i in range(n)]
mn = []
cnt = [0 for i in range(10 ** 6 + 100)]
cc = [False for i in range(n + 10)]
x = 0
mx = []
for i in s:
	mn1 = 10 ** 8
	for j in range(1, len(i)):
		if i[j] > mn1:
			cc[x] = True
		mn1 = min(mn1, i[j])
	mn.append(mn1)
	mx.append(max(i[1:]))
	if cc[x] == True:
		cnt[10 ** 6 + 3] += 1
	else:
		cnt[mx[-1]] += 1
	x += 1
ans = 0
for i in range(len(cnt) - 2, -1, -1):
	cnt[i] += cnt[i + 1]
for i in range(n):
	if cc[i]:
		ans += n
		continue
	ans += cnt[mn[i] + 1]
print(ans)


import bisect
n = int(input())
f = []
l = []
for i in range(n):
	a = list(map(int, input().split()))
	a = a[1:]
	if sorted(a) == a[::-1]:
		f.append(a[0])
		l.append(a[-1])
f.sort()
l.sort()
ans = 0
for i in range(len(f)):
	pos = bisect.bisect_right(f, l[i])
	ans += pos
print(n * n - ans)


import math
from math import *
from collections import Counter
from operator import itemgetter
import bisect
import datetime
import calendar
ii = lambda : int(input())
iia = lambda : list(map(int, input().split()))
isa = lambda : list(input().split())
t = ii()
mini = [0] * t
maxi = [0] * t
flag = [1] * t
for i in range(t):
	(n, *a) = iia()
	for j in range(n - 1):
		if a[j] < a[j + 1]:
			flag[i] = 0
			break
	mini[i] = min(a)
	maxi[i] = max(a)
suffix = [0] * t
x = []
cnt = 0
td = t
for i in range(t):
	if flag[i] == 0:
		x.append(i)
		mini[i] = 100000000000
		maxi[i] = -100000000000
		if td > 0:
			cnt += 2 * td - 1
			td -= 1
i = 0
minis = []
maxis = []
while i < t:
	if mini[i] != 100000000000:
		minis.append(mini[i])
		maxis.append(maxi[i])
	i += 1
minis = mini.copy()
maxis = maxi.copy()
minis.sort()
maxis.sort()
k = flag.count(0)
for i in range(len(minis)):
	cnt += t - bisect.bisect_right(maxis, minis[i])
print(cnt)


import sys
import math
from collections import defaultdict, Counter
input = sys.stdin.readline

def print(x):
	sys.stdout.write(str(x) + '\n')
n = int(input())
c = [0] * n
mal = [0] * (10 ** 6 + 2)
mil = [0] * n
tot = 0
for i in range(n):
	(l, *s) = list(map(int, input().split()))
	ma = s[0]
	mi = s[0]
	for j in range(1, l):
		if s[j] > mi:
			c[i] = 1
			ma = max(ma, s[j])
		else:
			mi = min(mi, s[j])
	if c[i] == 1:
		tot += 1
	else:
		mil[i] = mi
		mal[ma] += 1
for j in range(10 ** 6, 0, -1):
	mal[j] += mal[j + 1]
ans = 0
for j in range(n):
	if c[j] == 1:
		ans += n
	else:
		ans += tot + mal[mil[j] + 1]
print(ans)


import bisect
n = int(input())
count = n
(mini, maxi) = ([], [])
same = 0

def checks(s):
	for i in range(2, len(s)):
		if s[i] > s[i - 1]:
			return False
	return True
while n > 0:
	s = list(map(int, input().split()))
	if checks(s) == True:
		mini.append(min(s[1:]))
		maxi.append(max(s[1:]))
	else:
		same += 1
	n -= 1
c = same * count
(mini, maxi) = (sorted(mini), sorted(maxi))
for i in range(len(mini)):
	c = c + (len(maxi) - bisect.bisect_right(maxi, mini[i])) + same
print(c)


import sys
from bisect import bisect_right
n = int(input())
s = []
has_ascents = [False for _ in range(n)]
firsts = []
lasts = []
for k in range(n):
	a = list(map(lambda x: int(x), sys.stdin.readline().split()[1:]))
	for i in range(0, len(a) - 1):
		if a[i] < a[i + 1]:
			has_ascents[k] = True
			break
	a.sort()
	firsts.append(a[0])
	if has_ascents[k] == False:
		lasts.append(a[-1])
lasts.sort()
c = 0
for i in range(0, n):
	if has_ascents[i] == True:
		continue
	else:
		ind = bisect_right(lasts, firsts[i])
		if ind > 0:
			c += ind
print(n * n - c)


n = int(input())
asc = 0
nasc = 0
minimos = []
maximos = []
for i in range(n):
	s = input().split()
	s = [int(e) for e in s]
	s.pop(0)
	for j in range(len(s)):
		if j > 0 and s[j] > s[j - 1]:
			asc += 1
			break
		elif j == len(s) - 1:
			nasc += 1
			minimos.append(min(s))
			maximos.append(max(s))
r = asc * asc + 2 * (asc * nasc)
minimos.sort()
maximos.sort()
i = 0
for k in maximos:
	while i < nasc and minimos[i] < k:
		i += 1
	r += i
print(r)


n = int(input())
l = []
ans = 0
minn = []
maxx = []
c = 0
for _ in range(n):
	ar = [int(x) for x in input().split()]
	ar = ar[1:]
	m = 10 ** 10
	f = 0
	for i in ar:
		if i <= m:
			m = i
		else:
			f = 1
			break
	if f == 1:
		continue
	else:
		minn.append(min(ar))
		maxx.append(max(ar))
maxx.sort()
minn.sort()
temp = len(maxx)
from bisect import bisect_left
for i in maxx:
	ind = bisect_left(minn, i)
	ans += temp - ind
print(n ** 2 - ans)


import bisect
n = int(input())
seq = []
for i in range(n):
	seq.append(list(map(int, input().split()))[1:])
ans = 0
ascent = []
c = 0
for i in range(n):
	is_ascent = False
	for j in range(1, len(seq[i])):
		if seq[i][j] > seq[i][j - 1]:
			is_ascent = True
			break
	if not is_ascent:
		ascent.append(i)
	if is_ascent:
		ans += n
		c += 1
ans += c * len(ascent)
maxi = []
for i in ascent:
	maxi.append(max(seq[i]))
mini = []
for i in ascent:
	mini.append(min(seq[i]))
maxi.sort()
for i in mini:
	ind = bisect.bisect_right(maxi, i)
	if ind == len(maxi):
		continue
	ans += len(maxi) - ind
print(ans)


import sys
input = sys.stdin.readline
a = int(input())
mini = []
maxa = []
temp = []
ca = a
from bisect import *
total = 0
for i in range(a):
	z = list(map(int, input().split()))
	z = z[1:]
	m = [z[0]]
	flag = 0
	for i in range(1, len(z)):
		if z[i] > m[-1]:
			flag = 1
			break
		else:
			m.append(z[i])
	if flag == 1:
		total += 2 * ca - 1
		ca -= 1
	else:
		temp.append(z)
		mini.append(min(z))
		maxa.append(max(z))
maxa.sort()
for i in range(len(mini)):
	x = bisect_left(maxa, mini[i] + 1)
	total += len(maxa) - x
print(total)


import bisect
n = int(input())
m1 = [0] * n
m2 = []
m3 = [0] * n
for i in range(n):
	arr = list(map(int, input().split()))[1:]
	(k1, k2, k3) = (float('inf'), float('-inf'), 0)
	for c in arr:
		if c > k1:
			k3 = 1
		k1 = min(k1, c)
		k2 = max(k2, c)
	m3[i] = k3
	if k3 == 0:
		m1[i] = k1
		m2.append(k2)
m2.sort()
ans = 0
st = sum(m3)
for i in range(n):
	if m3[i]:
		ans += n
	else:
		j = bisect.bisect_left(m2, m1[i] + 1)
		ans += len(m2) - j + st
print(ans)


n = int(input())
asc = 0
min = []
max = []
for ind in range(n):
	s = list(map(int, input().split()[1:]))
	semasc = True
	if len(s) > 1:
		for i in range(1, len(s)):
			if s[i] > s[i - 1]:
				semasc = False
				asc += 1
				break
	if semasc:
		min.append(s[-1])
		max.append(s[0])
nasc = n - asc
resp = 0
resp += asc * asc + 2 * asc * nasc
min.sort()
max.sort()
i = 0
for el in max:
	while i < nasc and min[i] < el:
		i += 1
	resp += i
print(resp)


n = int(input())
a = []
upcnt = 0
constcnt = 0
down_l = []
down_r = []
for i in range(n):
	a.append(list(map(int, input().split()))[1:])
	for j in range(1, len(a[-1])):
		if a[-1][j - 1] < a[-1][j]:
			upcnt += 1
			break
	else:
		down_l.append(a[-1][0])
		down_r.append(a[-1][-1])
		if a[-1][0] == a[-1][-1]:
			constcnt += 1
ans = upcnt ** 2 + upcnt * (n - upcnt) * 2
if upcnt < n:
	down_l.sort()
	down_r.sort()
	il = 0
	ir = 0
	while ir < n - upcnt:
		while il < n - upcnt and down_r[ir] >= down_l[il]:
			il += 1
		ans += n - upcnt - il
		ir += 1
print(ans)


N = int(input())
num_asc = 0
non_asc = []
min_vals = []
max_vals = []

def isAsc(seq):
	if len(seq) <= 1:
		return False
	for i in range(len(seq) - 1):
		if seq[i] < seq[i + 1]:
			return True
	return False

def numGt(seq, val):
	idx = -1
	jump = len(seq)
	while jump != 0:
		while idx + jump < len(seq) and seq[idx + jump] <= val:
			idx += jump
		jump //= 2
	return len(seq) - (idx + 1)
for n in range(N):
	S = list(map(int, input().split()[1:]))
	if isAsc(S):
		num_asc += 1
	else:
		minS = min(S)
		maxS = max(S)
		non_asc.append((minS, maxS))
		min_vals.append(minS)
		max_vals.append(maxS)
ans = 0
ans += num_asc * num_asc
ans += 2 * (num_asc * len(non_asc))
min_vals = sorted(min_vals)
max_vals = sorted(max_vals)
for (a, b) in non_asc:
	abcont = numGt(max_vals, a)
	ans += abcont
print(ans)


from sys import stdin, stdout
n = int(stdin.readline().strip())
(seqmin, seqmax, asccount) = ([], [], 0)
for _ in range(n):
	seq = list(map(int, stdin.readline().split()[1:]))
	(imin, imax) = (-1, -1)
	asc = False
	for i in seq:
		if imin < 0:
			imin = i
		else:
			if i > imin:
				asc = True
			imin = min(imin, i)
		if imax < 0:
			imax = i
		else:
			imax = max(imax, i)
	if asc:
		asccount += 1
	else:
		seqmin.append(imin)
		seqmax.append(imax)
seqmin.sort(reverse=True)
seqmax.sort(reverse=True)
total = asccount * n + (n - asccount) * asccount
i = 0
for imin in seqmin:
	while i < len(seqmax) and seqmax[i] > imin:
		i += 1
	total += i
stdout.write(str(total))


import math
import sys

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

def isascent(seq):
	smallest_num = seq[0]
	for num in seq:
		if num <= smallest_num:
			smallest_num = num
		else:
			return True
	return False

def binary_search(mins, num):
	l = 0
	h = len(mins)
	while abs(l - h) != 1:
		if mins[(l + h) // 2] < num:
			l = (l + h) // 2
		elif mins[(l + h) // 2] >= num:
			h = (l + h) // 2
	if mins[l] == num:
		return -1
	else:
		return l

def main():
	answer = 0
	mins = []
	maxs = []
	found = 0
	n = int(input())
	for i in range(n):
		seq = listinput()[1:]
		if isascent(seq):
			answer += 2 * n - 1 - 2 * found
			found += 1
		else:
			mins.append(min(seq))
			maxs.append(max(seq))
		pass
	mins.sort()
	for num in maxs:
		answer += binary_search(mins, num) + 1
	print(answer)
main()


N = int(input())
(mns, mxs) = ([], [])
inf = 10 ** 18
r = 0
for _ in range(N):
	(l, *As) = map(int, input().split())
	(mn, mx) = (inf, 0)
	for (b, a) in zip(As, As[1:]):
		if b < a:
			r += 2 * N - 1
			N -= 1
			break
		mn = min(mn, b)
		mx = max(mx, b)
	else:
		mn = min(mn, As[-1])
		mx = max(mx, As[-1])
		mns.append(mn)
		mxs.append(mx)
mns.sort()
mxs.sort()
M = len(mxs)
i = 0
j = 0
for i in range(M):
	while j < M and mxs[j] <= mns[i]:
		j += 1
	r += M - j
print(r)


menor = []
maior = []
cre = 0
dec = 0
cont = 0
n = int(input())
for i in range(n):
	entr = input().split()[1:]
	for j in range(len(entr)):
		entr[j] = int(entr[j])
	for j in range(len(entr)):
		if j > 0 and entr[j] > entr[j - 1]:
			cre += 1
			break
		elif j == len(entr) - 1:
			dec += 1
			maior.append(max(entr))
			menor.append(min(entr))
res = 2 * cre * dec + cre * cre
maior.sort()
menor.sort()
for x in maior:
	while cont < dec and menor[cont] < x:
		cont += 1
	res += cont
print(res)


def bin_search(l, r, x, a):
	while l <= r:
		mid = (l + r) // 2
		if a[mid] <= x:
			l = mid + 1
		else:
			r = mid - 1
	return r
t = int(input())
d = {i: 0 for i in range(t)}
t1 = []
t2 = []
for i in range(t):
	l = list(map(int, input().split()))
	l = l[1:]
	r1 = min(l)
	r2 = max(l)
	z = l[0]
	flag = 0
	for j in l:
		if j > z:
			d[i] = (1, (r1, r2))
			flag = 1
		else:
			z = min(z, j)
	if flag == 0:
		d[i] = (0, (r1, r2))
		t1.append(r1)
		t2.append(r2)
t1.sort()
t2.sort()
z = 0
k = 0
for i in range(t):
	if d[i][0] == 1:
		z = z + 2 * t
		k = k + 1
	else:
		result = bin_search(0, len(t2) - 1, d[i][1][0], t2)
		z = z + len(t2) - result - 1
if k == 0:
	print(z)
else:
	print(z - k * k)


input = __import__('sys').stdin.readline
MIS = lambda : map(int, input().split())

def has_ascent(L):
	m = 10 ** 9
	for x in L:
		if m < x:
			return True
		m = min(m, x)
	return False
n = int(input())
mins = []
maxs = []
self_asc = 0
ans = 0
for i in range(n):
	seq = list(MIS())[1:]
	if has_ascent(seq):
		self_asc += 1
		continue
	mins.append(min(seq))
	maxs.append(max(seq))
takemax = [0] * (10 ** 6 + 2)
for x in maxs:
	takemax[x] += 1
for i in range(10 ** 6, -1, -1):
	takemax[i] += takemax[i + 1]
for x in mins:
	ans += takemax[x + 1]
ans += 2 * self_asc * (n - self_asc) + self_asc ** 2
print(ans)


l = []
r = []
s = 0
from bisect import *
n = int(input())
for _ in range(n):
	(ll, *p) = list(map(int, input().split()))
	if sorted(p) == p[::-1]:
		l.append(p[-1])
		r.append(p[0])
r.sort()
print(n * n - sum((bisect(r, x) for x in l)))


import sys

def main():
	n = int(input())
	arr = []
	chk = []
	cnt = 0
	for i in range(n):
		x = get_array()[1:]
		mn = x[0]
		mx = x[0]
		flag = 0
		for p in range(1, len(x)):
			j = x[p]
			mn = min(mn, j)
			mx = max(mx, j)
			if x[p] > x[p - 1]:
				flag = 1
		if flag == 0:
			arr.append(mn)
			chk.append(mx)
		else:
			cnt += 1
	chk.sort()
	from bisect import bisect
	ans = cnt * n
	for i in range(len(arr)):
		p = bisect(chk, arr[i])
		ans += len(arr) - p
		ans += cnt
	print(ans)
get_array = lambda : list(map(int, sys.stdin.readline().split()))
get_ints = lambda : map(int, sys.stdin.readline().split())
input = lambda : sys.stdin.readline().strip()
main()


n = int(input())
s = [[0, 10 ** 6, False] for i in range(n)]
ma = [0] * n
mi = [10 ** 6] * n
d = [False] * n
for i in range(n):
	j1 = 10 ** 6
	for j in [int(x) for x in input().split()][1:]:
		s[i][1] = min(j, s[i][1])
		s[i][0] = max(j, s[i][0])
		if j1 < j:
			s[i][2] = True
			d[i] = True
		j1 = j
s.sort(key=lambda s: s[1])
ma = list(sorted([x[0] for x in s if not x[2]]))
res = 0
im = 0
k = sum(d)
for i in range(n):
	if s[i][2]:
		res += n
	else:
		while im < len(ma) and s[i][1] >= ma[im]:
			im += 1
		if im < len(ma):
			res += len(ma) - im + k
		else:
			res += k
print(res)


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

def binary(data, target, low, high):
	if low > high:
		return low
	else:
		mid = (low + high) // 2
		if data[mid] >= target:
			return binary(data, target, low, mid - 1)
		else:
			return binary(data, target, mid + 1, high)
n = int(input())
mi = []
ma = []
res = 0
cu = 0
for i in range(n):
	hh = list(map(int, input().split()))
	kk = hh[0]
	yer_min = 99 ** 9
	yer_ma = -1
	for i in range(1, kk + 1):
		el = hh[i]
		yer_min = min(yer_min, el)
		yer_ma = max(yer_ma, el)
	f = False
	for i in range(1, kk):
		if hh[i + 1] > hh[i]:
			f = True
			cu += 1
			break
	if not f:
		mi.append(yer_min)
		ma.append(yer_ma)
ma.sort()
p = n ** 2 - (n - cu) ** 2
res += p
for i in mi:
	k = binary(ma, i + 1, 0, len(ma) - 1)
	if k != n:
		res += n - k - cu
print(res)


import sys
input = sys.stdin.readline

def iin():
	return int(input())

def lin():
	return list(map(int, input().split()))
from math import factorial

def nc2(a):
	return factorial(a - 1)

def main():
	n = iin()
	(T, F, F1) = (set(), set(), list())
	ans = 0
	for _ in range(n):
		s = lin()
		mn = s[1]
		mx = s[1]
		done = 0
		for i in range(2, s[0] + 1):
			if not done:
				if s[i] > mn:
					done = 1
			mn = min(s[i], mn)
			mx = max(s[i], mx)
		if done:
			T.add(_)
		else:
			F.add(_)
			F1.append([mn, mx])
	n = len(T)
	ans += n ** 2
	ans += n * len(F) * 2
	mn = [i for (i, j) in F1]
	mn.sort()
	from bisect import bisect_left as bl
	for (i, j) in F1:
		ans += bl(mn, j)
	print(ans)
main()


import bisect
n = int(input())
s = []
l = []
ans = 0
ans = n ** 2
for i in range(n):
	a = list(map(int, input().split()))[1:]
	if sorted(a)[::-1] == a:
		s.append(min(a))
		l.append(max(a))
s.sort()
l.sort()
for x in s:
	k = bisect.bisect(l, x)
	ans -= k
print(ans)


import bisect
(l, la, fir, c) = ([], [], [], 0)

def chk(k):
	for m in range(len(k) - 1):
		if k[m] < k[m + 1]:
			return 1
	return 0
n = int(input())
for _ in range(n):
	l = list(map(int, input().split()))[1:]
	if chk(l):
		c += 1
	else:
		fir.append(l[0])
		la.append(l[-1])
c = n ** 2 - (n - c) ** 2
fir.sort()
for i in range(len(fir)):
	indx = bisect.bisect_right(fir, la[i])
	c += len(fir) - indx
print(c)


E6 = 1000000
n = int(input())
arr_more_then = [0 for i in range(E6 + 10)]
min_count = {}
count_not_up = 0
for i in range(n):
	inp = list(map(int, input().split()))
	(l, s) = (inp[0], inp[1:])
	ups = False
	for j in range(1, l):
		if s[j] > s[j - 1]:
			ups = True
	if not ups:
		count_not_up += 1
		arr_more_then[max(s)] += 1
		if min(s) in min_count:
			min_count[min(s)] += 1
		else:
			min_count[min(s)] = 1
sum_more_then = [0 for i in range(E6 + 10)]
for i in range(E6 + 10 - 2, -1, -1):
	sum_more_then[i] = sum_more_then[i + 1] + arr_more_then[i]
ans = 0
for min_item in min_count.keys():
	ans += min_count[min_item] * sum_more_then[min_item + 1]
print(n * n - count_not_up * count_not_up + ans)


from bisect import bisect
n = int(input())
cnt = [0] * n
(minE, maxE) = ([], [])
for i in range(n):
	arr = [int(p) for p in input().split()]
	arr.pop(0)
	if sorted(arr, reverse=True) != arr:
		cnt[i] += 1
	else:
		minE.append(min(arr))
		maxE.append(max(arr))
	if max(arr) != min(arr):
		cnt[i] += 1
maxE.sort()
minE.sort()
u = cnt.count(2)
cnt = 0
for i in range(len(minE)):
	j = bisect(maxE, minE[i])
	cnt += len(maxE) - j
	cnt += u
cnt += n * u
print(cnt)


from sys import stdin
input = stdin.readline
n = int(input())
s = []
count = 0
sortcount = 1
for i in range(n):
	z = list(map(int, input().split()))[1:]
	if z != sorted(z, reverse=True):
		count += 2 * n - sortcount
		sortcount += 2
	else:
		s.append([z[0], z[-1]])
s.sort(reverse=True)
if s:
	dmax = [0 for i in range(s[0][0] + 5)]
	for i in s:
		dmax[i[0]] += 1
	for i in range(len(dmax) - 1, 0, -1):
		dmax[i - 1] += dmax[i]
	for i in s:
		count += dmax[i[1] + 1]
print(count)


import bisect
INF = float('inf')
n = int(input())
(minval, maxval) = ([], [])
for i in range(n):
	s = list(map(int, input().split()))
	(cur_min, cur_max) = (INF, -INF)
	asc = False
	for j in range(1, s[0] + 1):
		if s[j] > cur_min:
			asc = True
		(cur_min, cur_max) = (min(cur_min, s[j]), max(cur_max, s[j]))
	if asc:
		(cur_min, cur_max) = (-INF, INF)
	minval.append(cur_min)
	maxval.append(cur_max)
maxval.sort()
res = 0
for i in range(n):
	pos = bisect.bisect(maxval, minval[i])
	res += n - pos
print(res)


n = int(input())
r = []
c = 0
A = 0
mm = 0
for _ in range(n):
	s = list(map(int, input().split()))
	l = s[0]
	s = s[1:]
	t = s[0]
	tf = False
	ma = s[0]
	mi = s[0]
	for i in range(1, l):
		ma = max(ma, s[i])
		mi = min(mi, s[i])
		if s[i] > t:
			tf = True
			break
		else:
			t = s[i]
	if tf:
		A += 1
	else:
		r.append([mi, ma])
		mm = max(mm, ma)
l1 = len(r)
c = A * l1 * 2 + A + A * (A - 1)
dp = [[0] * (mm + 1) for _ in range(2)]
for i in r:
	dp[0][i[0]] += 1
	dp[1][i[1]] += 1
l2 = mm
for i in range(mm - 1, -1, -1):
	dp[1][i] += dp[1][i + 1]
for i in range(mm):
	if dp[0][i] != 0:
		c += dp[0][i] * dp[1][i + 1]
print(c)


def inp(dtype=str, strip=True):
	s = input()
	res = [dtype(p) for p in s.split()]
	res = res[0] if len(res) == 1 and strip else res
	return res

def problem1():
	(n, m) = inp(int)
	s = inp(strip=False)
	t = inp(strip=False)
	q = inp(int)
	for _ in range(q):
		y = inp(int) - 1
		print(s[y % n] + t[y % m])

def problem2():
	n = inp(int)
	res = 0
	noascent_mins = [0 for _ in range(n)]
	noascent_maxs = [0 for _ in range(n)]
	noascent_cnt = 0
	for i in range(n):
		s = inp(int, strip=False)
		assert s[0] == len(s) - 1
		s = s[1:]
		ssort = sorted(s, reverse=True)
		(mn, mx) = (ssort[-1], ssort[0])
		has_ascent = s != ssort and mn < mx
		if has_ascent:
			num = 2 * (n - i + noascent_cnt) - 1
			res += num
		else:
			noascent_mins[noascent_cnt] = mn
			noascent_maxs[noascent_cnt] = mx
			noascent_cnt += 1
	noascent_maxs = noascent_maxs[:noascent_cnt]
	noascent_mins = noascent_mins[:noascent_cnt]
	noascent_mins = sorted(noascent_mins)
	noascent_maxs = sorted(noascent_maxs)
	n = noascent_cnt
	i = 0
	for j in range(n):
		while i < n and noascent_mins[i] < noascent_maxs[j]:
			i += 1
		res += i
	print(res)

def problem3():
	pass

def problem4():
	pass

def problem5():
	pass
problem2()


import bisect
import sys
input = sys.stdin.readline
n = int(input())
s = [list(map(int, input().split())) for i in range(n)]
INF = 10 ** 7
is_solo = [False] * n
min_ = [0] * n
max_ = [INF] * n
for i in range(n):
	max_tmp = 0
	min_tmp = INF
	is_ = False
	for j in range(len(s[i]) - 2):
		if s[i][j + 1] < s[i][j + 2]:
			is_ = True
	min_tmp = min(s[i][1:])
	max_tmp = max(s[i][1:])
	is_solo[i] = is_
	if not is_:
		min_[i] = min_tmp
		max_[i] = max_tmp
max_ = sorted(max_)
ans = 0
for i in range(n):
	if is_solo[i]:
		ans += n
	else:
		ans += n - bisect.bisect_right(max_, min_[i])
print(ans)


import sys
sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
import bisect
INF = 10 ** 9
n = int(input())
ascends = 0
maxima = []
minima = []
for _ in range(n):
	line = [int(item) for item in input().split()][1:]
	prev = INF
	ascending = False
	for item in line:
		if item > prev:
			ascending = True
			break
		prev = item
	if ascending:
		ascends += 1
	else:
		maxima.append(line[0])
		minima.append(line[-1])
minima.sort()
maxima.sort()
num = len(minima)
ans = ascends * ascends + ascends * (n - ascends) * 2
for item in maxima:
	ans += bisect.bisect_left(minima, item)
print(ans)


def binsearch(x, a):
	l = 0
	r = len(a) - 1
	ans = r
	while l <= r:
		mid = (l + r) // 2
		if a[mid] <= x:
			l = mid + 1
		else:
			ans = mid
			r = mid - 1
	return ans
n = int(input())
l = []
maxv = []
minv = []
count = 0
for i in range(n):
	l.append(list(map(int, input().split()))[1:])
	ans = False
	m = l[-1][0]
	M = l[-1][0]
	for j in range(1, len(l[-1])):
		if l[-1][j - 1] < l[-1][j] and (not ans):
			ans = True
			count += 1
			break
		if m > l[-1][j]:
			m = l[-1][j]
		if M < l[-1][j]:
			M = l[-1][j]
	if not ans:
		minv.append(m)
		maxv.append(M)
maxv.sort()
minv.sort()
sum = count * len(l)
sum += (len(l) - count) * count
for i in range(len(minv)):
	ind = binsearch(minv[i], maxv)
	while len(maxv) > ind and maxv[ind] == minv[i]:
		ind += 1
	sum += len(maxv) - ind
print(sum)


def arr_inp():
	return [float(x) for x in stdin.readline().split()]

def get_col(arr, i):
	return [row[i] for row in arr]
from sys import stdin
from collections import deque, defaultdict
from bisect import *
(a, mem) = ([arr_inp()[1:] for i in range(int(input()))], defaultdict(int))
for (i, j) in enumerate(a):
	(mi, ma) = (j[0], j[0])
	for k in j[1:]:
		if k > mi:
			mem[i] = 1
			break
		else:
			mi = k
maxes = sorted([[i, max(a[i]), min(a[i])] for i in range(len(a))], key=lambda x: x[1])
(deq, ans) = (deque(maxes), 0)
for i in maxes:
	if mem[i[0]]:
		deq.popleft()
		ans += len(deq) * 2 + 1
	else:
		deq.rotate(-1)
col = get_col(deq, 1)
for (i, ma, mi) in deq:
	ix = bisect_right(col, mi)
	ans += len(deq) - ix
print(ans)


import bisect

def ascent(list1, len1):
	if len1 == 1:
		return False
	for i in range(len1 - 1):
		if list1[i + 1] > list1[i]:
			return True
	return False
n = int(input())
kappa = 0
nmsl = []
minList = []
maxList = []
for i in range(n):
	fulllist = [int(ele) for ele in input().split()]
	lenl = fulllist[0]
	lst = fulllist[1:]
	minL = min(lst)
	maxL = max(lst)
	ascentYN = ascent(lst, lenl)
	if ascentYN:
		kappa += 1
	else:
		nmsl.append([minL, maxL])
		minList.append(minL)
		maxList.append(maxL)
res = kappa * (2 * n - kappa)
count1 = 0
maxList.sort()
for ele in minList:
	count = n - kappa - bisect.bisect(maxList, ele + 0.1)
	res += count
print(res)


import bisect
n = int(input())
s = []
for _ in range(n):
	x = [int(x) for x in input().split()]
	l = x[0]
	s.append(x[1:])
s.sort(key=lambda x: max(x))
a = [max(x) for x in s]
joker = [0] * n
for (i, x) in enumerate(s):
	res = 0
	for (k, v) in enumerate(x):
		if k == 0:
			continue
		if v > x[k - 1]:
			res = 1
			break
	joker[i] = res
for (k, j) in enumerate(joker):
	if k == 0:
		continue
	joker[k] += joker[k - 1]
ans = 0
for (k, v) in enumerate(s):
	if k > 0 and joker[k] - joker[k - 1] > 0:
		ans += n
		continue
	r = bisect.bisect_right(a, min(v))
	ans += n - r
	if r != 0:
		ans += joker[r - 1]
print(ans)


n = int(input())
seq = []
arr1 = [0] * 1000001
ascent = [0] * n
(ans, count) = (0, 0)
for i in range(n):
	x = list(map(int, input().split()))
	seq.append(x[1:])
	for j in range(1, x[0]):
		if x[j] < x[j + 1]:
			ascent[i] = 1
			count += 1
			ans += n
			break
	if not ascent[i]:
		arr1[x[1]] += 1
for i in range(1, len(arr1)):
	arr1[i] += arr1[i - 1]
for i in range(n):
	if not ascent[i]:
		ans += count
		ans += arr1[-1] - arr1[seq[i][-1]]
print(ans)


def bsearch(arr, x, lo, hi):
	if lo >= hi:
		return lo
	mid = (lo + hi) // 2
	if arr[mid] <= x:
		return bsearch(arr, x, mid + 1, hi)
	else:
		return bsearch(arr, x, lo, mid)
n = int(input())
a = []
for _ in range(n):
	x = [int(i) for i in input().split()]
	a.append(x[1:])
ascent = 0
min_arr = []
max_arr = []
for i in range(n):
	x = a[i]
	m = x[0]
	M = x[0]
	l = len(x)
	has_ascent = False
	for i in range(1, l):
		if m < x[i]:
			has_ascent = True
		m = min(m, x[i])
		M = max(M, x[i])
	if has_ascent:
		ascent += 1
	else:
		min_arr.append(m)
		max_arr.append(M)
min_arr.sort()
max_arr.sort()
max_arr_len = len(max_arr)
count = 2 * n * ascent - ascent ** 2
for i in min_arr:
	idx = bsearch(max_arr, i, 0, max_arr_len - 1)
	if max_arr[idx] == i:
		idx += 1
	count += max_arr_len - idx
print(count)


from bisect import bisect_left as bi
n = int(input())
a = []
c = []
d = []
for i in range(n):
	x = list(map(int, input().split()))
	a.append(x[1:])
	if a[i] == sorted(a[i], reverse=True):
		c.append([min(a[i]), max(a[i])])
		d.append(max(a[i]))
d.sort()
f = 0
for i in range(len(c)):
	e = c[i][0] + 1
	f += bi(d, e)
print(n * n - f)


import sys
import bisect
input = sys.stdin.readline
n = int(input())
mother_list = []
for i in range(n):
	l = [int(i) for i in input().split()]
	mother_list.append(l[1:])
fi = []
la = []
for i in mother_list:
	for j in range(1, len(i)):
		if i[j - 1] < i[j]:
			break
	else:
		fi.append(i[0])
		la.append(i[-1])
fi.sort()
count = 0
for i in la:
	count += bisect.bisect(fi, i)
print(n ** 2 - count)


def binsearch(x):
	first = 0
	last = len(l2) - 1
	while first <= last:
		mid = (first + last) // 2
		if l2[mid] <= x:
			first = mid + 1
		else:
			last = mid - 1
	return mid
ans = 0
n = int(input())
l1 = []
l2 = []
cnt = 0
for i in range(n):
	s = list(map(int, input().split()))
	s = s[1:]
	k = 0
	for j in range(len(s) - 1):
		if s[j] < s[j + 1]:
			k = 1
			break
	if k == 1:
		ans += (n - cnt) * 2 - 1
		cnt += 1
	else:
		l1.append(min(s))
		l2.append(max(s))
k = 0
l1.sort()
l2.sort()
for i in l1:
	b = binsearch(i)
	if l2[b] > i:
		b -= 1
	ans += len(l2) - b - 1
print(ans)


n = int(input())
cnt = 0
mxs = []
mns = []
for i in range(n):
	a = list(map(int, input().split()))
	mn = a[1]
	mx = a[1]
	flag = True
	for j in range(2, a[0] + 1):
		if a[j] > mn:
			flag = False
			cnt += 1
			break
		if a[j] > mx:
			mx = a[j]
		if a[j] < mn:
			mn = a[j]
	if flag:
		mxs.append(mx)
		mns.append(mn)
mns.sort()
mxs.sort()
ans = 0
for i in mxs:
	l = -1
	r = n - cnt
	while l + 1 < r:
		mid = (l + r) // 2
		if mns[mid] < i:
			l = mid
		else:
			r = mid
	ans += l + 1
ans += cnt * cnt + 2 * cnt * (n - cnt)
print(ans)


from bisect import bisect_right as br

def asc(p):
	mi = p[0]
	for i in range(1, len(p)):
		if mi < p[i]:
			return 1
		mi = min(mi, p[i])
	return 0
l = []
m = []
mi = []
n = int(input())
x = []
for _ in range(n):
	(a, *b) = list(map(int, input().split()))
	l.append(b)
	x.append(asc(b))
	mi.append(min(b))
	if x[-1] != 1:
		m.append(max(b))
a = 0
m.sort()
p = len(m)
y = x.count(1)
for i in range(n):
	if x[i]:
		a += n
	else:
		k = mi[i]
		k = br(m, k)
		a = a + p - k + y
print(a)


from bisect import bisect_right as ub, bisect_left as lb
n = int(input())
(mn, mx) = ([], [])
cnt = 0
ans = 0
for i in range(n):
	a = list(map(int, input().split()))
	l = a[0]
	a = a[1:]
	ok = False
	for j in range(l - 1):
		if a[j] < a[j + 1]:
			cnt += 1
			ok = True
			break
	if not ok:
		mn.append(min(a))
		mx.append(max(a))
while cnt:
	ans += 2 * n - 1
	n -= 1
	cnt -= 1
mn.sort()
mx.sort()
for i in mn:
	ans += len(mx) - ub(mx, i)
print(ans)