In a certain video game, the player controls a hero characterized by a single integer value: power. The hero will have to beat monsters that are also characterized by a single integer value: armor.

On the current level, the hero is facing $n$ caves. To pass the level, the hero must enter all the caves in some order, each cave exactly once, and exit every cave safe and sound. When the hero enters cave $i$, he will have to fight $k_i$ monsters in a row: first a monster with armor $a_{i, 1}$, then a monster with armor $a_{i, 2}$ and so on, finally, a monster with armor $a_{i, k_i}$.

The hero can beat a monster if and only if the hero's power is strictly greater than the monster's armor. If the hero can't beat the monster he's fighting, the game ends and the player loses. Note that once the hero enters a cave, he can't exit it before he fights all the monsters in it, strictly in the given order.

Each time the hero beats a monster, the hero's power increases by $1$.

Find the smallest possible power the hero must start the level with to be able to enter all the caves in some order and beat all the monsters.


-----Input-----

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^5$). Description of the test cases follows.

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

The $i$-th of the next $n$ lines contains an integer $k_i$ ($1 \le k_i \le 10^5$) — the number of monsters in the $i$-th cave, followed by $k_i$ integers $a_{i, 1}, a_{i, 2}, \ldots, a_{i, k_i}$ ($1 \le a_{i, j} \le 10^9$) — armor levels of the monsters in cave $i$ in order the hero has to fight them.

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


-----Output-----

For each test case print a single integer — the smallest possible power the hero must start the level with to be able to enter all the caves in some order and beat all the monsters.


-----Examples-----

Input
2
1
1 42
2
3 10 15 8
2 12 11
Output
43
13


-----Note-----

In the first test case, the hero has to beat a single monster with armor $42$, it's enough to have power $43$ to achieve that.

In the second test case, the hero can pass the level with initial power $13$ as follows:

enter cave $2$:

beat a monster with armor $12$, power increases to $14$;

beat a monster with armor $11$, power increases to $15$;

enter cave $1$:

beat a monster with armor $10$, power increases to $16$;

beat a monster with armor $15$, power increases to $17$;

beat a monster with armor $8$, power increases to $18$.

Difficulty: EASY
Tags: Sorting

Greedy algorithms
Skill types: Sorting

Greedy algorithms

Starter code:

Solutions:
t = int(input())
results = [None] * t
for l in range(t):
	n = int(input())
	caves = [[int(x) for x in input().split()][1:] for _ in range(n)]
	min_levels = [(max((x - i + 1 for (i, x) in enumerate(cave))), len(cave)) for cave in caves]
	min_levels.sort(key=lambda x: x[0])
	sub = 0
	for (i, x) in enumerate(min_levels):
		min_levels[i] = x[0] - sub
		sub += x[1]
	results[l] = max((x for x in min_levels))
[print(x) for x in results]


import sys, os, io
import math
from collections import defaultdict
from io import BytesIO, IOBase
from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

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

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

def solve():
	n = ii()
	l = []
	for i in range(n):
		x = li()
		k = x[0]
		x = x[1:]
		m = 0
		jj = 0
		for j in range(k):
			if x[j] - i + 1 > m:
				jj = j
			m = max(m, x[j] - j + 1)
		l.append([m, k])
	l = sorted(l, key=lambda x: x[1], reverse=True)
	l.sort()
	val = l[0][0]
	to = 0
	for i in range(len(l) - 1):
		val += l[i][1]
		if val + to < l[i + 1][0]:
			to += l[i + 1][0] - val - to
	print(l[0][0] + to)
t = 1
t = ii()
for _ in range(t):
	solve()


from collections import deque

class Solution:

	def beat_monsters(self, caves_data):
		caves_data.sort(key=lambda x: x[0])
		(total_monsters, minimum_power) = (0, caves_data[0][0])
		for (max_armor_cave, monsters) in caves_data:
			extra_power = max(max_armor_cave - total_monsters - minimum_power, 0)
			minimum_power += extra_power
			total_monsters += monsters
		print(minimum_power)
s = Solution()
cases = int(input())
for case in range(cases):
	caves_data = []
	t_caves = int(input())
	for cave in range(t_caves):
		cave_info = input().split(' ')
		(max_armor_cave, monsters_in_cave, beated_monsters) = (0, int(cave_info[0]), 0)
		for monster in range(1, monsters_in_cave + 1):
			current_monster = int(cave_info[monster])
			max_armor_cave = max(current_monster - beated_monsters + 1, max_armor_cave)
			beated_monsters += 1
		caves_data.append([max_armor_cave, monsters_in_cave])
	s.beat_monsters(caves_data)


for _ in range(int(input())):
	n = int(input())
	c = []
	for cave in range(n):
		a = list(map(int, input().split()))
		k = a[0]
		maxx = -1000000000.0
		for mon in range(k):
			maxx = max(a[1 + mon] - mon, maxx)
		c.append((maxx, k))
	c.sort()
	power = c[0][0] + 1
	power += c[0][1]
	ans = c[0][0] + 1
	for i in range(1, n):
		if power < c[i][0] + 1:
			ans += c[i][0] + 1 - power
			power += c[i][0] + 1 - power
		power += c[i][1]
	print(ans)


t = int(input())
for cycl in range(t):
	n = int(input())
	ans = 0
	power = 0
	power_list = []
	for cave in range(n):
		cave_data = list(map(int, input().split()))
		n_m = cave_data[0]
		chan_power = 0
		for m_id in range(1, n_m + 1):
			chan_power = max(cave_data[m_id] - m_id + 2, chan_power)
		power_list.append([chan_power, n_m])
	power_list.sort()
	for l in power_list:
		if l[0] > power:
			ans += l[0] - power
			power = l[0]
		power += l[1]
	print(ans)


testcase = int(input())
for _ in range(testcase):
	max_armor = []
	monsters = []
	count = 0
	cave = int(input())
	for _ in range(cave):
		level = [int(x) for x in input().split()]
		monster = level[0]
		level = level[1:]
		for i in range(monster):
			level[i] = level[i] + 1 - i
		max_armor.append(max(level))
		monsters.append(monster)
	monster_num = [x for (_, x) in sorted(zip(max_armor, monsters))]
	max_armor.sort()
	for i in range(1, len(max_armor)):
		count += monster_num[i - 1]
		max_armor[i] -= count
	print(max(max_armor))


import math
t = int(input())
for w in range(t):
	n = int(input())
	v = []
	for i in range(n):
		a = [int(x) for x in input().split()]
		count = a[1] + 1
		for j in range(1, len(a)):
			count = max(count, a[j] + 2 - j)
		v.append([count, a[0]])
	v.sort()
	val = v[0][0]
	count = v[0][0]
	for i in v:
		if i[0] > count:
			val += i[0] - count
			count = i[0]
		count += i[1]
	print(val)


t = int(input())
for _ in range(t):
	n = int(input())
	cs = []
	for _ in range(n):
		(k, *ars) = map(int, input().split())
		maxx = 0
		for i in range(k):
			if maxx < max(ars[i] - i, 0):
				maxx = max(ars[i] - i, 0)
		cs.append((maxx + 1, k))
	cs.sort()
	minn_ = 0
	p = 0
	out = 0
	for c in cs:
		if p < c[0]:
			minn_ += c[0] - p
			p = c[0] + c[1]
		else:
			p += c[1]
	print(minn_)


t = int(input())
for dalskjd in range(t):
	n = int(input())
	l = []
	ll = []
	for i in range(n):
		l.append([int(j) for j in input().split()])
	minn = 1000000000.0 + 10
	for i in l:
		tmp = i[1] + 1
		for j in range(2, i[0] + 1):
			if i[j] >= tmp + j - 1:
				tmp = i[j] + 2 - j
		ll.append([tmp, tmp + i[0]])
	ll = sorted(ll, key=lambda i: i[0])
	right = 0
	left = 0
	last = 0
	for i in ll:
		if left >= i[0]:
			left += i[1] - i[0]
		else:
			right = i[0] - (left - right)
			left = i[1]
	print(right)


import sys
input = sys.stdin.readline

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

def main():
	t = ri()[0]
	for _ in range(t):
		n = ri()[0]
		data = []
		for i in range(n):
			a = ri()
			a = a[1:]
			a_ = [a[i] - i for i in range(len(a))]
			data.append((max(a_), len(a_)))
		data.sort()
		ans = 0
		have = 0
		for (need, get) in data:
			if have <= need:
				ans += need - have + 1
				have += need - have + 1
			have += get
		print(ans)
main()


for _ in range(int(input())):
	n = int(input())
	power = []
	for _ in range(n):
		maxx = 0
		deep = list(map(int, input().split()))
		for i in range(1, deep[0] + 1):
			maxx = max(maxx, deep[i] - i + 2)
		power.append([maxx, deep[0]])
	power.sort()
	num = 0
	ans = 0
	for i in power:
		if i[0] > num:
			ans += i[0] - num
			num = i[0]
		num += i[1]
	print(ans)


t = int(input())
for i in range(t):
	n = int(input())
	entry = []
	for i in range(n):
		cave = list(map(int, input().split()))
		s = cave[0]
		m = 0
		for j in range(1, s + 1):
			m = max(m, cave[j] - j + 1)
		entry.append([m, s])
	entry.sort()
	m = 0
	a = 0
	for e in entry:
		m = max(m, e[0] - a)
		a += e[1]
	print(m + 1)


t = int(input().strip())
for _ in range(t):
	n = int(input().strip())
	levels = []
	for i in range(n):
		level = list(map(int, input().strip().split()))
		maxi = level[1] + 1
		index = 0
		for (i, e) in enumerate(level[1:]):
			if e - i + 1 > maxi:
				maxi = e - i + 1
				index = i
		d = [maxi, level[0]]
		levels.append(d)
	levels.sort(key=lambda x: x[0])
	mini = levels[0][0]
	monsters = 0
	for l in levels:
		mini = max(mini, l[0] - monsters)
		monsters += l[1]
	print(mini)


from collections import defaultdict, Counter, deque
from math import sqrt, log10, log, floor, factorial, gcd
from bisect import bisect_left, bisect_right
from itertools import permutations, combinations
import sys, io, os
input = sys.stdin.readline
inf = float('inf')
mod = 10 ** 9 + 7

def yn(a):
	print('YES' if a else 'NO')
ceil = lambda a, b: (a + b - 1) // b
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')
t = int(input())
for i in range(t):
	n = int(input())
	t = []
	for i in range(n):
		l = [int(i) for i in input().split()]
		l = [l[i] - i + 1 for i in range(1, len(l))]
		t.append([max(l) + 1, len(l)])
	t.sort()
	maxa = t[0][0]
	adder = t[0][0]
	for i in range(n):
		if maxa < t[i][0]:
			adder += t[i][0] - maxa
			maxa += t[i][0] - maxa
		maxa += t[i][1]
	print(adder)


for _ in range(int(input())):
	i = int(input())
	t = []
	for _ in range(i):
		c = list(map(int, input().split()))
		t.append([max((c[x + 1] - x + 1 for x in range(c[0]))), c[0]])
	t.sort(key=lambda test: test[0])
	ans = pans = t[0][0]
	for x in t:
		if ans < x[0]:
			pans += x[0] - ans
			ans += x[0] - ans
		ans += x[1]
	print(pans)


t = int(input())
for i in range(t):
	n = int(input())
	(w, c) = ([], [])
	for j in range(n):
		w.append([int(k) for k in input().split()][1:])
	for j in w:
		eta = 0
		mx = 0
		for k in j:
			mx = max(mx, k - eta + 1)
			eta += 1
		c.append([mx, j])
	zxc = []
	c.sort(key=lambda x: x[0])
	for j in c:
		zxc.extend(j[1])
	eta = 0
	mx = 0
	for j in zxc:
		mx = max(mx, j - eta + 1)
		eta += 1
	print(mx)


for _ in range(int(input())):
	n = int(input())
	(l, v, id) = ([], [], [])
	for i in range(n):
		l.append(list(map(int, input().split()[1:])))
		(cur, add) = (0, 0)
		for x in l[-1]:
			if cur <= x:
				add += x - cur + 1
				cur = x + 1
			cur += 1
		v.append(add)
		id.append(i)
	id.sort(key=lambda x: v[x])
	(cur, add) = (0, 0)
	for i in id:
		for x in l[i]:
			if cur <= x:
				add += x - cur + 1
				cur = x + 1
			cur += 1
	print(add)


for _ in range(int(input())):
	n = int(input())
	temp = []
	l = []
	for _ in range(n):
		temp = [i for i in map(int, input().split())]
		mn = 0
		for i in range(1, len(temp)):
			mn = max(mn, temp[i] + 1 - (i - 1))
		l.append([mn, temp[0]])
	l.sort(reverse=True)
	posbl = 0
	for i in range(len(l)):
		if posbl < l[i][0]:
			posbl = l[i][0]
		if i + 1 != len(l):
			posbl -= l[i + 1][1]
	print(posbl)


import sys
import math
t = int(sys.stdin.readline())
for _ in range(t):
	n = int(sys.stdin.readline())
	caves = [[]] * n
	sizes = [0] * n
	for i in range(n):
		line = [int(i) for i in sys.stdin.readline().split()]
		caves[i] = line[1:]
		sizes[i] = line[0]
	power_needed = [0] * n
	for i in range(n):
		for j in range(sizes[i]):
			power_needed[i] = max(power_needed[i], caves[i][j] - j + 1)
	data = sorted(zip(power_needed, sizes))
	ans = 0
	total = 0
	for i in range(n):
		ans = max(ans, data[i][0] - total)
		total += data[i][1]
	print(ans)


t = int(input())
for q in range(t):
	k = int(input())
	maxs = []
	for i in range(k):
		cp = [int(i) for i in input().split()][1:]
		massc = 0
		for i in range(len(cp)):
			if cp[i] - i > massc:
				massc = cp[i] - i
		maxs.append((massc + 1, len(cp)))
	maxs = sorted(maxs, key=lambda student: student[0])
	ms = 0
	cs = 0
	for p in maxs:
		if cs < p[0]:
			ms += p[0] - cs
			cs = p[0]
		cs += p[1]
	print(ms)


t = int(input())
for k in range(t):
	n = int(input())
	caves = []
	for i in range(n):
		x = [int(j) for j in input().split()]
		size = x[0]
		requirements = 0
		for j in range(1, len(x)):
			temp = x[j] + 2 - j
			if temp > requirements:
				requirements = temp
		caves.append((requirements, size))
	caves.sort()
	ans = 0
	power = 0
	for i in range(len(caves)):
		if power >= caves[i][0]:
			power += caves[i][1]
		else:
			ans += caves[i][0] - power
			power += caves[i][1] + caves[i][0] - power
	print(ans)


def argsort(seq):
	return sorted(range(len(seq)), key=seq.__getitem__)
ans = []
num_data = int(input())
for data in range(num_data):
	num_peser = int(input())
	pesery = []
	for peser in range(num_peser):
		pesera = list(map(int, input().split()[1:]))
		pesery.append(pesera)
	max_strengthes = []
	for (i, j) in enumerate(pesery):
		max_strengthes.append((0, 0, 0))
		for (ind, element) in enumerate(j):
			max_strength = element
			res = max_strength - ind + 1
			if res > max_strengthes[i][0]:
				max_strengthes[i] = (max_strength - ind + 1, -ind, len(j))
	new_indices = argsort(max_strengthes)
	for (i, j) in enumerate(new_indices):
		if i != 0:
			max_strengthes[j] = (max_strengthes[j][0] - max_strengthes[new_indices[i - 1]][2], max_strengthes[j][1], max_strengthes[j][2] + max_strengthes[new_indices[i - 1]][2])
	ans.append(max(max_strengthes)[0])
print('\n'.join(map(str, ans)))


solution = []

def find_least_power_cave(cave):
	values = [int(cave[i]) - int(i) for i in range(len(cave))]
	return (max(values), len(cave))

def find_least_power(order):
	possible_max = list()
	for (key, value) in order.items():
		(value, length) = find_least_power_cave(value)
		possible_max.append([value, length])
	possible_max.sort(key=lambda x: x[0])
	possible_least = []
	total = 0
	for i in range(len(possible_max)):
		if i == 0:
			possible_least.append(possible_max[i][0])
		else:
			total += possible_max[i - 1][1]
			possible_least.append(possible_max[i][0] - total)
	return max(possible_least)
test_cases = int(input())
for test in range(test_cases):
	number_of_caves = int(input())
	order = dict()
	for cave in range(number_of_caves):
		monsters = input().split()
		order[cave] = [i for i in monsters]
		del order[cave][0]
	least_power = find_least_power(order)
	solution.append(least_power)
for i in solution:
	print(i + 1)


import math
import os
import sys
from sys import *
from decimal import *
from io import BytesIO, IOBase
import itertools
from collections import *
import random
M = 10 ** 9 + 7
import heapq
import bisect
from functools import lru_cache
from queue import PriorityQueue
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

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

def out(var):
	sys.stdout.write(str(var))

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

def stringlis():
	return list(map(str, inp().split()))

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

def strsep():
	return map(str, inp().split())

def fsep():
	return map(float, inp().split())

def inpu():
	return int(inp())

def luckynumber(x, n, a):
	if x > 0:
		a.append(x)
	if x > 10 ** 9:
		return a
	elif x < 1000000000000.0:
		luckynumber(x * 10 + 4, n, a)
		luckynumber(x * 10 + 7, n, a)

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

def query1(l, r):
	if l >= r:
		return -1
	print('?', l + 1, r + 1)
	sys.stdout.flush()
	return int(input()) - 1

def answer(p):
	print('!', p + 1)
	sys.stdout.flush()
	exit()

def rse(arr, n):
	stack = []
	ans = []
	for i in range(n - 1, -1, -1):
		if len(stack) == 0:
			ans.append(n)
		else:
			while len(stack) != 0:
				if stack[-1][0] >= arr[i]:
					stack.pop()
				else:
					break
			if len(stack) == 0:
				ans.append(n)
			else:
				ans.append(stack[-1][1])
		stack.append([arr[i], i])
	ans.reverse()
	return ans

def lse(arr, n):
	stack = []
	ans = []
	for i in range(n):
		if len(stack) == 0:
			ans.append(-1)
		else:
			while len(stack) != 0:
				if stack[-1][0] >= arr[i]:
					stack.pop()
				else:
					break
			if len(stack) == 0:
				ans.append(-1)
			else:
				ans.append(stack[-1][1])
		stack.append([arr[i], i])
	return ans

def mah(arr):
	max1 = 0
	p = rse(arr, len(arr))
	q = lse(arr, len(arr))
	for i in range(len(arr)):
		a = (p[i] - q[i] - 1) * arr[i]
		max1 = max(a, max1)
	return max1

def maxSumIS(arr, n):
	msis = arr.copy()
	for i in range(1, n):
		for j in range(i):
			if arr[i] > arr[j] and msis[i] < msis[j] + arr[i]:
				msis[i] = msis[j] + arr[i]
	c = max(msis)
	p = 5
	return c

def binarysearch2(arr, target):
	lo = 0
	hi = len(arr) - 1
	while lo <= hi:
		mid = (lo + hi) // 2
		if arr[mid] == target:
			if mid != len(arr) - 1:
				if arr[mid + 1] != target:
					return mid
				else:
					lo += 1
			else:
				return mid
			continue
		if arr[mid] > target:
			hi = mid - 1
		else:
			lo = mid + 1

def nge(arr, n):
	stack = []
	ans = []
	for i in range(n - 1, -1, -1):
		if len(stack) == 0:
			ans.append(-1)
		else:
			while len(stack) > 0:
				if stack[-1][0] < arr[i]:
					stack.pop()
				else:
					break
			if len(stack) == 0:
				ans.append(-1)
			else:
				ans.append(stack[-1][1])
		stack.append([arr[i], i])
	ans.reverse()
	return ans

def alperm(nums, path, result):
	if not nums:
		result.add(tuple(path))
		return
	for i in range(0, len(nums)):
		alperm(nums[:i] + nums[i + 1:], path + [nums[i]], result)
	return result

def minsum(arr, n, m, res, l):
	if n == 1 and m == 1:
		res += arr[0][0]
		l.append(res)
	else:
		if n != 1:
			p = res + arr[n - 1][m - 1]
			minsum(arr, n - 1, m, p, l)
		if m != 1:
			p = res + arr[n - 1][m - 1]
			minsum(arr, n, m - 1, p, l)
	return min(l)

def find_shortest_path(graph, start, end, path):
	path = path + [start]
	if start == end:
		return path
	if start not in graph:
		return None
	shortest = None
	for node in graph[start]:
		if node not in path:
			newpath = find_shortest_path(graph, node, end, path)
			if newpath:
				if not shortest or len(newpath) < len(shortest):
					shortest = newpath
	return shortest

def find(arr, i):
	while i != arr[i]:
		i = arr[i]
		arr[i] = arr[arr[i]]
	return i

def union(i, j, parent):
	(u, v) = (find(parent, i), find(parent, j))
	if u != v:
		parent[u] = v

def test(n, d):
	a = random.randint(1, n - 2)
	p = pow(a, d, n)
	if p == 1 or p == n - 1:
		return True
	while d != n - 1:
		d *= 2
		p = pow(p, 2, n)
		if p == n - 1:
			return True
	return False

def isprime(n):
	if n == 1:
		return False
	if n == 2:
		return True
	if n == 3:
		return True
	d = n - 1
	while d % 2 == 0:
		d //= 2
	for i in range(5):
		if test(n, d) == False:
			return False
	return True

def check(arr, mid):
	for i in arr:
		for j in i:
			if mid > j:
				mid += 1
			else:
				return False
	return True

def main():
	t = 1
	t = inpu()
	for _ in range(t):
		n = inpu()
		l = []
		for j in range(n):
			arr = lis()
			arr.pop(0)
			p = 0
			for i in range(len(arr)):
				p = max(p, arr[i] - i)
			l.append([arr, p])
		l.sort(key=lambda x: x[1])
		m = []
		for i in l:
			m.append(i[0])
		lo = 0
		hi = 10 ** 19
		while lo <= hi:
			mid = (lo + hi) // 2
			if check(m, mid):
				hi = mid - 1
			else:
				lo = mid + 1
		print(max(lo, hi))
main()


def calc_min_power_for_cave(armors):
	return 1 + max([armor - i for (i, armor) in enumerate(armors)])

def solve_case():
	(n, _, a) = read_input()
	min_p = []
	for i in range(n):
		min_p_i = calc_min_power_for_cave(a[i])
		min_p.append(min_p_i)
	sorted_by_min_p = sorted(zip(min_p, a), key=lambda pa: pa[0])
	min_p = [first for (first, _) in sorted_by_min_p]
	a = [second for (_, second) in sorted_by_min_p]
	p0 = 0
	p = 0
	for i in range(n):
		shortage_of_power = min_p[i] - p
		if shortage_of_power > 0:
			p0 += shortage_of_power
			p += shortage_of_power
		p += len(a[i])
	print(p0)

def read_input():
	n = int(input())
	k = []
	a = []
	for i in range(n):
		ka = list(map(int, input().split()))
		k.append(ka[0])
		a.append(ka[1:])
	return (n, k, a)
T = int(input())
for t in range(T):
	solve_case()


def fun():
	n = int(input())
	All = []
	s = []
	for k in range(n):
		a = [int(x) for x in input().split()]
		x = a[0]
		del a[0]
		b = [int(a[i] + 1 - i) for i in range(x)]
		start = max(b)
		All.append([start, x])
	All.sort()
	m = All[0][0]
	total = All[0][0] + All[0][1]
	for i in range(1, n):
		if total < All[i][0]:
			m += max(0, All[i][0] - total)
		total += All[i][1] + max(0, All[i][0] - total)
	print(m)
t = int(input())
for _ in range(t):
	fun()


for t in range(int(input())):
	n = int(input())
	l = []
	for i in range(n):
		x = list(map(int, input().split()))
		k = x[0]
		x = x[1:]
		m = 0
		jj = 0
		for j in range(k):
			if x[j] - i + 1 > m:
				jj = j
			m = max(m, x[j] - j + 1)
		l.append([m, k])
	l.sort()
	openn = l[0][0]
	add = l[0][1]
	for i in range(len(l) - 1):
		openn += max(0, l[i + 1][0] - openn - add)
		add += l[i + 1][1]
	print(openn)


def solve(caves):
	for (j, cave) in enumerate(caves):
		caves[j] = [cave[i] - i for i in range(len(cave))]
	difficulty = [(max(a), len(a)) for a in caves]
	min_level = 0
	difficulty.sort(key=lambda x: x[0])
	cur = min_level
	for (diff, size) in difficulty:
		if diff >= cur:
			skill_needed = diff - cur + 1
			cur += skill_needed
			min_level += skill_needed
		cur += size
	return min_level
import os
import io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input().decode().strip())
for t in range(T):
	n = int(input().decode().strip())
	caves = []
	for i in range(n):
		armors = [int(x) for x in input().decode().strip().split(' ')]
		armors.pop(0)
		caves.append(armors)
	res = solve(caves)
	print(res)


import sys
input = sys.stdin.buffer.readline

def process(M):
	n = len(M)
	L = []
	for i in range(n):
		my_max = 0
		m = M[i][0]
		for j in range(m):
			my_max = max(my_max, M[i][j + 1] - j + 1)
		L.append([my_max, m])
	L = sorted(L)
	answer = L[0][0]
	curr = 0
	for i in range(len(L)):
		answer = max(answer, L[i][0] - curr)
		curr += L[i][1]
	return answer
t = int(input())
for i in range(t):
	n = int(input())
	M = []
	for j in range(n):
		A = [int(x) for x in input().split()]
		M.append(A)
	print(process(M))


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

class RangeQuery:

	def __init__(self, data, func=min):
		self.func = func
		self._data = _data = [list(data)]
		(i, n) = (1, len(_data[0]))
		while 2 * i <= n:
			prev = _data[-1]
			_data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)])
			i <<= 1

	def query(self, start, stop):
		depth = (stop - start).bit_length() - 1
		return self.func(self._data[depth][start], self._data[depth][stop - (1 << depth)])

	def __getitem__(self, idx):
		return self._data[0][idx]

def check(st, n, k):
	for i in range(n - k + 1):
		g = st.query(i, i + k)
		if g > 1:
			return True
	return False
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import defaultdict, deque
from math import ceil, floor, sqrt, log2, gcd, pi
from heapq import heappush, heappop
from fractions import Fraction
from bisect import bisect_left, bisect, bisect_right
from itertools import combinations_with_replacement, permutations
import sys
from copy import deepcopy
abc = 'abcdefghijklmnopqrstuvwxyz'
ABC = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for _ in range(int(input())):
	n = int(input())
	heap = []
	for _ in range(n):
		arr = list(map(int, input().split()))
		heappush(heap, (arr[0], arr[1:]))
	heap1 = []
	req = 0
	cnt = 0
	maxi = -float('inf')
	for _ in range(n):
		(val, a) = heappop(heap)
		req = 0
		cnt = 0
		maxi = -float('inf')
		for i in a:
			cnt += 1
			req = max(req, i + 1)
			req += 1
			maxi = max(maxi, req - cnt)
		heappush(heap1, (maxi, a))
	req = 0
	cnt = 0
	maxi = -float('inf')
	for _ in range(n):
		(val, a) = heappop(heap1)
		for i in a:
			cnt += 1
			req = max(req, i + 1)
			req += 1
			maxi = max(maxi, req - cnt)
	print(maxi)


import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(2 * 10 ** 5 + 10)
write = lambda x: sys.stdout.write(x + '\n')
debug = lambda x: sys.stderr.write(x + '\n')
writef = lambda x: print('{:.12f}'.format(x))

def sub(x):
	for ind in index:
		m = ms[ind]
		v = vs[ind]
		if x < m:
			return 0
		x += v
	return 1
t = int(input())
res = []
for _ in range(t):
	n = int(input())
	ms = []
	vs = []
	M = 0
	for i in range(n):
		a = list(map(int, input().split()))
		m = -1
		for j in range(1, len(a)):
			m = max(m, a[j] - j + 2)
		ms.append(m)
		vs.append(len(a) - 1)
		M = max(M, m)
	ng = 0
	ok = M + 1
	index = list(range(len(ms)))
	index.sort(key=lambda i: ms[i])
	while abs(ng - ok) > 1:
		mm = (ng + ok) // 2
		if sub(mm):
			ok = mm
		else:
			ng = mm
	ans = ok
	res.append(ans)
write('\n'.join(map(str, res)))


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

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

def solve(N, Cave):
	T = []
	for cave in Cave:
		req_p = 0
		for i in range(len(cave)):
			req_p = max(req_p, cave[i] + 1 - i)
		T.append((req_p, len(cave)))
	T.sort()
	initial_p = 0
	current_p = 0
	for (req_p, bonus) in T:
		if current_p < req_p:
			initial_p += req_p - current_p
			current_p = req_p
		current_p += bonus
	return initial_p
T0 = int(input())
for _ in range(T0):
	N = int(input())
	Cave = []
	for _ in range(N):
		dat = list(map(int, input().split()))
		Cave.append(dat[1:])
	print(solve(N, Cave))


import itertools
from sys import maxsize, stdout, stdin, stderr
mod = int(1000000000.0 + 7)
import sys

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

def lint():
	return [int(x) for x in stdin.readline().split()]

def S():
	return list(map(str, input().strip()))

def grid(r, c):
	return [lint() for i in range(r)]
from collections import defaultdict, Counter, deque
import math
import heapq
from heapq import heappop, heappush
import bisect
from math import inf
from itertools import groupby
from itertools import permutations as comb

def gcd(a, b):
	while b:
		a %= b
		tmp = a
		a = b
		b = tmp
	return a

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

def check_prime(n):
	for i in range(2, int(n ** (1 / 2)) + 1):
		if not n % i:
			return False
	return True

def nCr(n, r):
	return fact(n) // (fact(r) * fact(n - r))

def fact(n):
	res = 1
	for i in range(2, n + 1):
		res = res * i
	return res

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

def ask(a):
	print('? {}'.format(a), flush=True)
	n = I()
	return n

def linear_sieve(n):
	is_composite = [False] * n
	prime = []
	for i in range(2, n):
		if not is_composite[i]:
			prime.append(i)
		for j in prime:
			is_composite[i * j] = True
			if i % prime == 0:
				break
	return prime

def dfs(i, p, d):
	(a, tmp) = (0, 0)
	for j in d[i]:
		if j != p:
			a += 1
			tmp += dfs(j, i)
	if a == 0:
		return 0
	return tmp / a + 1

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

def sieve(n):
	for i in range(n):
		d.append(i)
	for i in range(2, n):
		if d[i] == i:
			primes.append(i)
		j = 0
		while j < len(primes) and primes[j] <= d[i] and (primes[j] * i < n):
			d[i * primes[j]] = primes[j]
			j += 1

def primeFactors(n):
	factors = []
	while n != 1:
		factors.append(d[n])
		n //= d[n]
	return factors
t = I()
for _ in range(t):
	n = I()
	k = []
	for i in range(n):
		tmp = lint()
		res = -1
		for (j, val) in enumerate(tmp[1:]):
			res = max(res, val + 1 - j)
		k.append([res, tmp[0]])
	k.sort()
	tmp = 0
	ans = 0
	for i in range(n):
		q = max(k[i][0] - tmp, 0)
		ans += q
		tmp += q + k[i][1]
	print(ans)


from collections import defaultdict, Counter, deque
from math import sqrt, log10, log, floor, factorial, gcd
from bisect import bisect_left, bisect_right
from itertools import permutations, combinations
import sys, io, os
input = sys.stdin.readline
inf = float('inf')
mod = 10 ** 9 + 7

def yn(a):
	print('YES' if a else 'NO')
ceil = lambda a, b: (a + b - 1) // b
t = int(input())
for i in range(t):
	n = int(input())
	t = []
	for i in range(n):
		l = [int(i) for i in input().split()]
		l = [l[i] - i + 1 for i in range(1, len(l))]
		t.append([max(l) + 1, len(l)])
	t.sort()
	maxa = t[0][0]
	adder = t[0][0]
	for i in range(n):
		if maxa < t[i][0]:
			adder += t[i][0] - maxa
			maxa += t[i][0] - maxa
		maxa += t[i][1]
	print(adder)


from sys import stdin, stdout, setrecursionlimit
from io import BytesIO, IOBase
setrecursionlimit(10000)

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(stdin, stdout) = (IOWrapper(stdin), IOWrapper(stdout))
input = lambda : stdin.readline().rstrip('\r\n')
inf = float('inf')
ninf = float('-inf')
inp = lambda : int(input())
st = lambda : input().strip()
jn = lambda x, l: x.join(map(str, l))
int_arr = lambda : list(map(int, input().strip().split()))
str_arr = lambda : list(map(str, input().split()))
get_str = lambda : map(str, input().strip().split())
get_int = lambda : map(int, input().strip().split())
get_float = lambda : map(float, input().strip().split())
mod = 1000000007
for _ in range(inp()):
	n = inp()
	lst = []
	for i in range(n):
		arr = int_arr()
		mx = 0
		for j in range(1, len(arr)):
			mx = max(arr[j] - (j - 1) + 1, mx)
		lst.append([mx, arr[0]])
	lst.sort(key=lambda x: x[0])
	tot = 0
	num = 0
	for i in lst:
		if i[0] > num:
			tot += i[0] - num
			num = i[0]
		num += i[1]
	print(tot)


import os, sys
from io import BytesIO, IOBase

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

class dict(dict):

	def __missing__(self, key):
		return 0
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
inp = lambda dtype: [dtype(x) for x in input().split()]
inp_2d = lambda dtype, n: [dtype(input()) for _ in range(n)]
inp_2ds = lambda dtype, n: [inp(dtype) for _ in range(n)]
inp_enu = lambda dtype: [(i, x) for (i, x) in enumerate(inp(dtype))]
inp_enus = lambda dtype, n: [[i] + [inp(dtype)] for i in range(n)]
ceil1 = lambda a, b: (a + b - 1) // b
for _ in range(int(input())):
	(n, all) = (int(input()), [])
	for i in range(n):
		(a, ma) = (inp(int), 0)
		for j in range(1, a[0] + 1):
			a[j] -= j - 1
			ma = max(ma, a[j] + 1)
		all.append([ma, a[0]])
	all.sort()
	ans = all[0][0]
	for i in range(1, n):
		diff = all[i][0] - sum(all[i - 1])
		if diff <= 0:
			all[i][0] += abs(diff)
		else:
			ans += diff
	print(ans)


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

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

def getliststr():
	return list(stdin.readline().split())

def getint():
	return int(stdin.readline().strip())

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

def pr(s):
	stdout.write(str(s) + '\n')

def prlist(l):
	stdout.write(' '.join(list(map(str, l))) + '\n')
from sys import stdin, stdout
for _ in range(getint()):
	n = getint()
	mat = []
	for i in range(n):
		mat.append(getlistint())
		startpow = 0
		endpow = 0
		for j in range(1, len(mat[i])):
			if startpow + endpow <= mat[i][j]:
				startpow += mat[i][j] - (startpow + endpow) + 1
			endpow += 1
		mat[i] = (startpow, startpow + endpow)
	mat = sorted(mat)
	power = mat[0][1]
	s = 0
	for i in range(1, n):
		if power < mat[i][0]:
			s += mat[i][0] - power
			power = mat[i][1]
		else:
			power += mat[i][1] - mat[i][0]
	pr(mat[0][0] + s)


t = int(input())
for _ in range(t):
	n = int(input())
	M = []
	for _ in range(n):
		tmp = list(map(int, input().split()))
		k = tmp[0]
		m = 0
		for i in range(1, len(tmp)):
			m = max(m, tmp[i] - i + 2)
		M.append((m, k))
	M.sort()
	ans = 0
	tot = 0
	for (m, k) in M:
		if tot < m:
			ans += m - tot
			tot = m
		tot += k
	print(ans)


import sys
for _ in range(int(sys.stdin.readline())):
	n = int(sys.stdin.readline())
	monsters = []
	for _ in range(n):
		temp = list(map(int, sys.stdin.readline().split()))
		(need_power, level_up) = (-float('inf'), temp[0])
		for i in range(1, 1 + level_up):
			need_power = max(need_power, temp[i] - i + 1)
		monsters.append((need_power, level_up))
	monsters.sort()
	(level, need_power) = (0, -float('inf'))
	for i in range(n):
		need_power = max(need_power, monsters[i][0] - level + 1)
		level += monsters[i][1]
	print(need_power)


t = int(input())
while t > 0:
	b = []
	n = int(input())
	if n == 1:
		a = list(map(int, input().split()))
		if a[0] == 1:
			print(a[1] + 1)
		else:
			k = a[0]
			mx = a[1]
			for j in range(2, k + 1):
				mx = max(mx, a[j] - j + 1)
			print(mx + 1)
	else:
		for i in range(n):
			l = []
			a = list(map(int, input().split()))
			k = a[0]
			if k == 1:
				l.append(a[1])
				l.append(k)
			else:
				mx = a[1]
				for j in range(2, k + 1):
					mx = max(mx, a[j] - j + 1)
				l.append(mx)
				l.append(k)
			b.append(l)
		b.sort()
		j = len(b) - 1
		d = b[j][0] + 1
		while j > 0:
			j = j - 1
			d = d - b[j][1]
			if d <= b[j][0]:
				d = b[j][0] + 1
		print(d)
	t -= 1


import sys

def solve():
	need_power = [0] * N
	for i in range(N):
		power = 0
		for j in range(K[i]):
			if power + j <= Armor[i][j]:
				power = Armor[i][j] - j + 1
		need_power[i] = power
	indices = list(range(N))
	indices.sort(key=lambda i: need_power[i])
	low = need_power[indices[0]]
	high = need_power[indices[N - 1]]
	ans = high
	while low <= high:
		mid = low + high >> 1
		if can_win(mid, indices, need_power):
			ans = mid
			high = mid - 1
		else:
			low = mid + 1
	return ans

def can_win(power, indices, need_power):
	for i in indices:
		if power >= need_power[i]:
			power += K[i]
		else:
			return False
	return True
input = sys.stdin.buffer.readline
test_cases = int(input())
for test_case in range(test_cases):
	N = int(input())
	Armor = []
	K = []
	for i in range(N):
		A = list(map(int, input().split()))
		Armor.append(A[1:])
		K.append(A[0])
	print(solve())


from sys import stdin
input = lambda : stdin.readline().strip()
lin = lambda : list(map(int, input().split()))
iin = lambda : int(input())
main = lambda : map(int, input().split())
from math import ceil, sqrt, factorial, log
from collections import deque
from bisect import bisect_left
mod = 998244353
mod = 1000000007

def solve(we):
	n = iin()
	l = []
	for i in range(n):
		(a, *b) = main()
		ma = 0
		t = 0
		for j in range(a):
			ma = max(ma, b[j] - j + 1)
		l.append([ma, a])
	l.sort()
	prev = l[-1][0]
	ans = prev
	for i in range(len(l) - 2, -1, -1):
		if l[i][0] + l[i][1] >= prev:
			prev = l[i][0]
			ans = prev
		else:
			prev -= l[i][1]
			ans = prev
	print(ans)
qwe = 1
qwe = iin()
for _ in range(qwe):
	solve(_ + 1)


def argmax(iterable):
	return max(enumerate(iterable), key=lambda x: x[1])

def compare(k):
	return k[0]
T = int(input())
for t in range(T):
	N = int(input())
	if N == 1:
		L = [int(x) for x in input().split()][1:]
		max_req = max([l - i + 1 for (i, l) in enumerate(L)])
		print(max_req)
		continue
	req_list = []
	for n in range(N):
		L = [int(x) for x in input().split()][1:]
		max_req = max([l - i + 1 for (i, l) in enumerate(L)])
		req_list.append((max_req, len(L)))
	req_list = sorted(req_list, key=compare)
	cum_len_list = [r[1] for r in req_list]
	for (i, c) in enumerate(cum_len_list):
		if i == 0:
			continue
		cum_len_list[i] = c + cum_len_list[i - 1]
	find_min = max([req_list[0][0] if i == 0 else req_list[i][0] - cum_len_list[i - 1] for i in range(N)])
	print(find_min)


for t in range(int(input())):
	k_a = list()
	k = list()
	a = list()
	power_needed = list()
	power_got = list()
	min_p = list()
	for i in range(int(input())):
		ka = [int(ka) for ka in input().split()]
		k_a.append(ka)
		k.append(ka[0])
		a.append(ka[1:])
		ps_needed = max([p - id + 1 for (id, p) in enumerate(a[i])])
		power_needed.append(ps_needed)
		power_got.append(len(a[i]))
		min_p.append((power_needed[i], power_got[i]))
	sorted_min_p = sorted(min_p)
	max_p_needed = 0
	pre_power = 0
	for (p, q) in sorted_min_p:
		if p - pre_power > max_p_needed:
			max_p_needed = p - pre_power
		pre_power += q
	print(max_p_needed)


test_cases = input()

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

def solve(arr, caves):
	max_ = []
	for i in arr:
		max_power = i[0] + 1
		exit_power = max_power + len(i)
		for j in range(len(i)):
			if max_power < i[j] + 1 - j:
				max_power = i[j] + 1 - j
				exit_power = max_power + len(i)
		max_.append([max_power, exit_power])
	max_.sort(key=lambda max_: max_[0])
	for i in range(len(max_)):
		if max_[-i][0] < max_[-1 - i][1]:
			continue
		elif max_[-i][0] >= max_[-1 - i][1]:
			diff = max_[-i][0] - max_[-1 - i][1]
			max_[-1 - i][1] = max_[-1 - i][1] + diff
			max_[-1 - i][0] = max_[-1 - i][0] + diff
	return max_[0][0]
ans = []
for i in range(int(test_cases)):
	lis = []
	caves = int(input())
	for i in range(caves):
		lis.append(inlt()[1:])
	ans.append(solve(lis, caves))
for i in ans:
	print(i)


import sys
import math
import operator as op
from functools import reduce
import decimal
loop = int(sys.stdin.readline().strip())
for _ in range(loop):
	num = int(sys.stdin.readline().strip())
	dungeon_li = []
	dungeon_idx = []
	for idx in range(num):
		li = list(map(int, sys.stdin.readline().strip().split()))
		for inner_idx in range(1, li[0] + 1):
			li[inner_idx] -= inner_idx - 1
		dungeon_idx.append([li[0], max(li[1:]), idx])
		li.remove(li[0])
		dungeon_li.append(li)
	dungeon_idx = sorted(dungeon_idx, key=lambda a: a[1])
	count = 0
	answer = 0
	for idx in range(num):
		if answer < dungeon_idx[idx][1] - count:
			answer = dungeon_idx[idx][1] - count
		count += dungeon_idx[idx][0]
	print(answer + 1)


import traceback
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 = IOWrapper(sys.stdin)
input = lambda : sys.stdin.readline().rstrip('\r\n')
import math
from collections import defaultdict as dfd, Counter, deque
from functools import lru_cache
from itertools import accumulate
from heapq import *
from bisect import *

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

def gets():
	return input()

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

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

def getinps(s):
	inps = s.split()
	m = {'i': geti, 's': gets, 'il': getil, 'sl': getsl}
	if len(inps) == 1:
		return m[s]()
	return [m[k]() for k in inps]

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

def get_acc(a):
	return list(accumulate(a))

def get_ncr(n, r, mod=10 ** 9 + 7):
	num = den = 1
	r = min(r, n - r)
	for i in range(r):
		num = num * (n - i) % mod
		den = den * (i + 1) % mod
	return num * pow(den, mod - 2, mod) % mod

def get_nc2(n):
	return n * (n - 1) // 2

def get_npr(n, r):
	if n < r:
		return 0
	return math.factorial(n) // math.factorial(r)

def put(a):
	return ' '.join(map(str, a))
inf = float('inf')
mod = 10 ** 9 + 7

def main():
	(N,) = getil()
	b = []
	for _ in range(N):
		a = getil()
		b.append(a[1:])

	def solve(a):
		k = 0
		ans = 0
		for x in a:
			ans = max(ans, x - k + 1)
			k += 1
		return (ans, ans + k)
	c = []
	for i in range(N):
		(x, y) = solve(b[i])
		c.append([x, y, i])
	c.sort()
	(ans, cur, ln) = (0, 0, 0)
	for (x, y, i) in c:
		if x <= cur:
			cur += len(b[i])
		else:
			ans = x - ln
			cur = y
		ln += len(b[i])
	print(ans)
try:
	Test = geti()
	answers = []
	for _ in range(Test):
		ans = main()
except Exception as e:
	print(e)
	traceback.print_exc()


for _ in range(int(input())):
	n = int(input())
	t = []
	for _ in range(n):
		c = list(map(int, input().split()))
		t.append([max((c[x + 1] - x + 1 for x in range(c[0]))), c[0]])
	t.sort(key=lambda x: x[0])
	ans = res = t[0][0]
	for x in t:
		if ans < x[0]:
			res += x[0] - ans
			ans += x[0] - ans
		ans += x[1]
	print(res)


from sys import stdin
input = stdin.readline
rn = lambda : int(input())
rns = lambda : map(int, input().split())
rl = lambda : list(map(int, input().split()))
rs = lambda : input().strip()
YN = lambda x: print('YES') if x else print('NO')
mod = 10 ** 9 + 7
for _ in range(rn()):
	n = rn()
	caves = []
	for i in range(n):
		a = rl()[1:]
		a = [a[i] - i for i in range(len(a))]
		caves.append([max(a), len(a)])
	caves.sort()
	ans = 0
	acc = 0
	for i in range(n):
		ans = max(ans, caves[i][0] - acc + 1)
		acc += caves[i][1]
	print(ans)


def I():
	return [*map(int, input().split())]
for _ in ' ' * I()[0]:
	n = I()[0]
	l = []
	for i in range(n):
		(m, *p) = I()
		for j in range(m):
			p[j] = p[j] - j + 1
		l.append([max(p), m])
	l = sorted(l)
	ans = l[0][0]
	c = l[0][1]
	for j in range(1, n):
		ans += max(0, l[j][0] - ans - c)
		c += l[j][1]
	print(ans)


import os
import sys
from io import BytesIO, IOBase
from collections import Counter, deque, defaultdict
from heapq import heappush, heappop
nmbr = lambda : int(input())
lst = lambda : list(map(int, input().split()))

def main():

	def fn(x):
		prev = x
		for (start, sz) in l:
			if start <= prev:
				prev += sz
			else:
				return False
		return True
	for _ in range(nmbr()):
		n = nmbr()
		l = []
		for q in range(n):
			a = lst()
			sz = a[0]
			mx = 0
			for i in range(1, sz + 1):
				mx = max(mx, a[i] - i + 2)
			l += [[mx, sz]]
		l.sort()
		(left, right) = (1, 10 ** 15)
		while left <= right:
			mid = left + right >> 1
			if fn(mid) == False:
				left = mid + 1
			else:
				right = mid - 1
		sys.stdout.write(str(left) + '\n')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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


def run():
	t = int(input())
	for i in range(t):
		P = []
		n = int(input())
		k = []
		for j in range(n):
			L = input().split(' ')
			L = [int(i) for i in L]
			k += [L[0]]
			L = [L[i] - i + 1 for i in range(1, k[j] + 1)]
			m = max(L)
			P += [[m, L, j]]
		P.sort(key=fn)
		s = 0
		for j in range(1, len(P)):
			s += k[P[j - 1][2]]
			P[j][0] = P[j][0] - s
		P.sort(key=fn)
		print(P[-1][0] + 1)

def fn(x):
	return x[0]
run()


n = int(input())
for i in range(n):
	k = int(input())
	delta = []
	for i in range(k):
		arr = list(map(int, input().split()))
		kol = arr[0]
		a = 1
		minhp = arr[1] + 1
		for j in range(2, kol + 1):
			minhp = max(arr[j] + 1 - a, minhp)
			a += 1
		delta.append([minhp, kol])
	delta.sort(key=lambda x: x[0])
	minhp = delta[0][0]
	hp = minhp + delta[0][1]
	for i in range(1, len(delta)):
		if delta[i][0] - hp > 0:
			sum = delta[i][0] - hp
			hp += sum
			minhp += sum
		hp += delta[i][1]
	print(minhp)


import os
import sys
from io import BytesIO, IOBase
import math
from queue import Queue
import collections
import itertools
import bisect
import heapq
import random

def main():
	pass
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

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

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

def pow2(n):
	p = 0
	while n > 1:
		n //= 2
		p += 1
	return p

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

def primeFactorsCount(n):
	cnt = 0
	while n % 2 == 0:
		cnt += 1
		n = n // 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			cnt += 1
			n = n // i
	if n > 2:
		cnt += 1
	return cnt

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

def maxPrimeFactors(n):
	maxPrime = -1
	while n % 2 == 0:
		maxPrime = 2
		n >>= 1
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			maxPrime = i
			n = n / i
	if n > 2:
		maxPrime = n
	return int(maxPrime)

def countcon(s, i):
	c = 0
	ch = s[i]
	for i in range(i, len(s)):
		if s[i] == ch:
			c += 1
		else:
			break
	return c

def lis(arr):
	n = len(arr)
	lis = [1] * n
	for i in range(1, n):
		for j in range(0, i):
			if arr[i] > arr[j] and lis[i] < lis[j] + 1:
				lis[i] = lis[j] + 1
	maximum = 0
	for i in range(n):
		maximum = max(maximum, lis[i])
	return maximum

def isSubSequence(str1, str2):
	m = len(str1)
	n = len(str2)
	j = 0
	i = 0
	while j < m and i < n:
		if str1[j] == str2[i]:
			j = j + 1
		i = i + 1
	return j == m

def maxfac(n):
	root = int(n ** 0.5)
	for i in range(2, root + 1):
		if n % i == 0:
			return n // i
	return n

def p2(n):
	c = 0
	while n % 2 == 0:
		n //= 2
		c += 1
	return c

def seive(n):
	primes = [True] * (n + 1)
	primes[1] = primes[0] = False
	i = 2
	while i * i <= n:
		if primes[i] == True:
			for j in range(i * i, n + 1, i):
				primes[j] = False
		i += 1
	pr = []
	for i in range(0, n + 1):
		if primes[i]:
			pr.append(i)
	return pr

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

def denofactinverse(n, m):
	fac = 1
	for i in range(1, n + 1):
		fac = fac * i % m
	return pow(fac, m - 2, m)

def numofact(n, m):
	fac = 1
	for i in range(1, n + 1):
		fac = fac * i % m
	return fac

def sod(n):
	s = 0
	while n > 0:
		s += n % 10
		n //= 10
	return s

def CanWin(val):
	for i in range(0, len(le)):
		if val > le[i][0]:
			val += le[i][1]
		else:
			return False
	return True
for xyz in range(0, int(input())):
	n = int(input())
	le = []
	for i in range(0, n):
		l = list(map(int, input().split()))
		temp = l[1:]
		minp = 0
		for j in range(0, l[0]):
			minp = max(minp, temp[j] - j + 1)
		le.append((minp, l[0]))
	le.sort()
	ps = 0
	ans = 0
	for i in range(0, n):
		ans = max(ans, le[i][0] - ps)
		ps += le[i][1]
	print(ans)


def main():
	test = int(input())
	for _ in range(test):
		n = int(input())
		caves = []
		for _ in range(n):
			a = list(map(int, input().split()))
			m = a[0]
			maxv = 0
			minp = 0
			for i in range(1, m + 1):
				minp = max(minp, a[i] + 2 - i)
			caves.append([minp, m])
		caves.sort()

		def check(x):
			st = x
			for i in range(n):
				if st >= caves[i][0]:
					st += caves[i][1]
				else:
					return False
			return True
		ans = caves[-1][0]
		(l, r) = (caves[0][0], caves[-1][0])
		while l < r:
			mid = l + r >> 1
			if check(mid):
				r = mid
			else:
				l = mid + 1
		ans = min(ans, l)
		print(ans)
	return
main()


for _ in range(int(input())):
	n = int(input())
	arr = []
	for _ in range(n):
		temp = [int(w) for w in input().split(' ')]
		x = temp[0]
		temp = temp[1:]
		b = 0
		for i in range(x):
			b = max(temp[i] - i, b)
		arr.append([b, x])
	arr.sort()
	ans = arr[0][0]
	prev = arr[0][1]
	for (x, y) in arr[1:]:
		ans = max(ans, x - prev)
		prev = prev + y
	print(ans + 1)


def naiveSolve():
	return

def solve():
	return

def main():
	t = int(input())
	allans = []
	for _ in range(t):
		n = int(input())
		minStartingPower = []
		ks = []
		for __ in range(n):
			temp = readIntArr()
			k = temp[0]
			armor = temp[1:]
			powerFromZero = 0
			requiredPower = 0
			for i in range(k):
				requiredPower = max(requiredPower, armor[i] - powerFromZero + 1)
				powerFromZero += 1
			minStartingPower.append(requiredPower)
			ks.append(k)
		startPowAndK = []
		for i in range(n):
			startPowAndK.append((minStartingPower[i], ks[i]))
		startPowAndK.sort()
		powerChange = 0
		ans = 0
		for (minStartPower, k) in startPowAndK:
			ans = max(ans, minStartPower - powerChange)
			powerChange += k
		allans.append(ans)
	multiLineArrayPrint(allans)
	return
import sys
input = sys.stdin.buffer.readline

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

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

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

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

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

def queryInteractive(x):
	print('{}'.format(x))
	sys.stdout.flush()
	return int(input())

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


for i in range(int(input())):
	n = int(input())
	a = []
	for j in range(n):
		b = list(map(int, input().split()))
		ans = 0
		for k in range(b[0]):
			ans = max(ans, b[k + 1] - k + 1)
		a.append((ans, b[0]))
	a.sort()
	final = a[0][0]
	c = final
	for j in range(1, n):
		c += a[j - 1][1]
		if a[j][0] >= c:
			inc = a[j][0] - c
			final += inc
			c += inc
	print(final)


def tmp_sort(n):
	return n[0]
t = int(input())
for i in range(t):
	num_caves = int(input())
	monsters = []
	strongest = []
	for j in range(num_caves):
		lst = [int(x) for x in input().split()]
		monsters.append(lst[1:])
	for cave in monsters:
		strong = 0
		for j in range(len(cave)):
			cave[j] -= j
			if cave[j] > strong:
				strong = cave[j]
		strongest.append((strong, len(cave)))
	strongest.sort(key=tmp_sort)
	min_start = strongest[0][0] + 1
	current = min_start
	for strong in strongest:
		if current <= strong[0]:
			tmp = strong[0] + 1 - current
			min_start += tmp
			current += tmp
		current += strong[1]
	print(min_start)


def hail(arr):
	tr = arr[-1] + 1
	n = len(arr)
	te = tr + 1
	for i in range(n - 1, -1, -1):
		entry = arr[i] + 1
		ex = entry + 1
		if ex < tr:
			te = tr
			tr = tr - 1
		else:
			tr = entry
			te = ex
	return [tr, tr + n]
import os
import sys
from io import BytesIO, IOBase

def main():
	T = int(input())
	for t in range(T):
		c = int(input())
		caves = [list(map(int, input().split())) for i in range(c)]
		lp = []
		for i in range(c):
			lp.append(hail(caves[i][1:]))
		lp.sort()
		lst = lp[-1]
		for i in range(c - 2, -1, -1):
			if lp[i][1] >= lst[0]:
				pass
			else:
				d = lp[i][1] - lp[i][0]
				lp[i][1] = lst[0]
				lp[i][0] = lst[0] - d
			lst = lp[i]
		print(lp[0][0])
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 minp(l, n):
	minpow = l[0] + 1
	for i in range(n):
		if l[i] - minpow - i < 0:
			continue
		else:
			minpow = l[i] - i + 1
	return minpow
for t in range(int(input())):
	n = int(input())
	l = []
	for i in range(n):
		l2 = list(map(int, input().split()))
		kt = l2[0]
		l2 = l2[1:]
		l.append([minp(l2, kt), kt])
	l.sort()
	ans = l[0][0]
	tpow = 0
	for i in range(0, n - 1):
		if ans + tpow + l[i][1] >= l[i + 1][0]:
			tpow += l[i][1]
		else:
			ans = l[i + 1][0] - tpow - l[i][1]
			tpow += l[i][1]
	print(ans)


for _ in range(int(input())):
	dem = []
	n = int(input())
	for _ in range(n):
		a = list(map(int, input().split()))
		temp = []
		for i in range(1, a[0] + 1):
			temp.append(a[i] - (i - 1))
		dem.append((max(temp) + 1, a[0]))
	dem.sort()
	ans = dem[0][0]
	cont = dem[0][1]
	for i in range(1, n):
		d = dem[i]
		current = ans + cont
		if current < d[0]:
			ans += d[0] - current
		cont += d[1]
	print(ans)


def giveLast(array):
	return array[-1]

def deepDownBelow(n, grid):
	for x in range(n):
		m = 0
		for y in range(1, grid[x][0] + 1):
			e = grid[x][y] + (2 - y)
			if e > m:
				m = e
		grid[x].append(m)
	grid.sort(key=giveLast)
	ans = 0
	k = 1
	for x in range(n):
		for y in range(1, grid[x][0] + 1):
			if grid[x][y] + k > ans:
				ans = grid[x][y] + k
			k -= 1
	return ans
t = int(input())
for _ in range(t):
	n = int(input())
	grid = []
	for x in range(n):
		grid.append(list(map(int, input().split())))
	print(deepDownBelow(n, grid))


def main():
	import sys
	input = sys.stdin.buffer.readline
	for _ in range(int(input())):
		n = int(input())
		l = []
		for i in range(n):
			(k, *a) = map(int, input().split())
			a = list(a)
			for j in range(k):
				a[j] -= j
			a.sort(reverse=True)
			l.append(a)
		l.sort(key=lambda x: x[0])
		(ng, ok) = (0, 10 ** 10)
		while abs(ok - ng) > 1:
			mid = (ok + ng) // 2
			cur = mid
			f = True
			for i in range(n):
				if cur <= l[i][0]:
					f = False
					break
				cur += len(l[i])
			if f:
				ok = mid
			else:
				ng = mid
		print(ok)
main()


for _ in range(int(input())):
	n = int(input())
	p = []
	for q in range(n):
		a = list(map(int, input().split()))
		b = []
		ind = 0
		for i in range(1, a[0] + 1):
			b.append(a[i] - ind)
			ind += 1
		p.append([max(b), a[0]])
	p.sort()
	k = p[0][1]
	for i in range(1, len(p)):
		p[i][0] = p[i][0] - k
		k += p[i][1]
	ans = max(p)
	print(ans[0] + 1)


for _ in range(int(input())):
	size = int(input())
	arr_arr = []
	for dungeon in range(size):
		(mass, *arr) = list(map(int, input().split()))
		for ind in range(mass):
			arr[ind] -= ind
		arr_arr.append([max(arr) + 1, mass])
	arr_arr = sorted(arr_arr)
	ans = arr_arr[0][0]
	take = arr_arr[0][1]
	for ind in range(1, len(arr_arr)):
		ans += max(0, arr_arr[ind][0] - ans - take)
		take += arr_arr[ind][1]
	print(ans)


def minpower(a):
	(mi, i) = ([], 0)
	for k in a[1:]:
		mi += [k + 1 - i]
		i += 1
	return [(max(mi), a[0])]
for _ in range(int(input())):
	res = []
	n = int(input())
	for _ in range(n):
		a = [int(i) for i in input().split()]
		res += minpower(a)
	res = sorted(res)
	s = res[0]
	p = 0
	for k in res:
		if k[0] > s[0] + p:
			s = (s[0] + (k[0] - s[0] - p), k[1])
		p += k[1]
	print(s[0])


t = int(input())
for i in range(t):
	n = int(input())
	l1 = []
	for j in range(n):
		l = [int(x) for x in input().split()]
		m = l[0]
		l.pop(0)
		c = 0
		current = 0
		for i in range(m):
			if l[i] + 1 > current:
				c = c + l[i] + 1 - current
				current = c + i + 1
			else:
				current += 1
		l1.append([c, m])
	l1.sort()
	current = l1[0][1] + l1[0][0]
	c = l1[0][0]
	for i in range(1, n):
		if current < l1[i][0]:
			c = c + l1[i][0] - current
			current = l1[i][0]
		current = current + l1[i][1]
	print(c)


import math

def solve():
	n = int(input())
	L = []
	for i in range(n):
		row = list(map(int, input().split()))
		req = 0
		for j in range(1, len(row)):
			req = max(req, row[j] - j + 2)
		L.append((req, len(row) - 1))
	L.sort()
	a = L[0][0]
	k = 0
	for i in range(1, n):
		k += L[i - 1][1]
		a = max(a, L[i][0] - k)
	print(a)
for _ in range(int(input())):
	solve()


t = int(input())
for tc in range(t):
	n = int(input())
	L = []
	for i in range(n):
		row = list(map(int, input().split()))
		req = 0
		for j in range(1, len(row)):
			req = max(req, row[j] - j + 2)
		L.append((req, len(row) - 1))
	enter = 0
	now = 0
	L.sort()
	for row in L:
		if now < row[0]:
			enter += row[0] - now
			now = row[0]
		now += row[1]
	print(enter)


t = int(input())
for _ in range(t):
	n = int(input())
	ar2 = []
	ar4 = []
	final = 5000000000
	initialfinal = 50000000000
	cpower = 0
	clen = 0
	index = 0
	minind = 0
	for i in range(n):
		ar2 = list(map(int, input().split()))
		ar2 = ar2[1:]
		power = 0
		initial = 0
		for i in range(len(ar2)):
			if ar2[i] >= power:
				power = ar2[i] + 1
				if power - i > initial:
					initial = power - i
			power += 1
		ar4.append([initial, len(ar2)])
		if initial < initialfinal:
			initialfinal = initial
			minind = index
		index += 1
	ar4 = sorted(ar4)
	cpower = initialfinal
	for i in range(n):
		if cpower >= ar4[i][0]:
			cpower += ar4[i][1]
		else:
			initialfinal += ar4[i][0] - cpower
			cpower += ar4[i][1] + (ar4[i][0] - cpower)
	print(initialfinal)


import math, bisect, heapq, random, sys, itertools
sys.setrecursionlimit(10 ** 6 + 10)
input = sys.stdin.readline
ints = lambda : list(map(int, input().split()))
p = 10 ** 9 + 7
alpha = 'abcdefghijklmnopqrstuvwxyz'
p2 = [1]
for i in range(30):
	p2.append(p2[i] * 2)
for t in range(int(input())):
	(n,) = ints()
	a = [ints()[1:] for i in range(n)]
	b = []
	for i in a:
		x = 0
		for j in range(len(i)):
			x = max(i[j] - j + 1, x)
		b.append([x, len(i)])
	b.sort()
	ans = 0
	x = 0
	for i in b:
		if x < i[0]:
			ans += i[0] - x
			x = i[0]
		x += i[1]
	print(ans)


import itertools as _itertools
import sys as _sys

def find_minimum_power_hero_needs(monsters_armors_groups):
	required_power_and_power_gain_for_every_group = []
	for armors_group in monsters_armors_groups:
		powers_need = [armor - i_armor + 1 for (i_armor, armor) in enumerate(armors_group)]
		required_power_and_power_gain = (max(powers_need), len(powers_need))
		required_power_and_power_gain_for_every_group.append(required_power_and_power_gain)
	required_power_and_power_gain_for_every_group.sort()
	(required_powers, power_gains) = zip(*required_power_and_power_gain_for_every_group)
	accumulated_power_gains = _itertools.accumulate(power_gains)
	assert required_powers
	max_power_required = required_powers[0]
	for (power_required, current_gain) in zip(required_powers[1:], accumulated_power_gains):
		power_required -= current_gain
		if power_required > max_power_required:
			max_power_required = power_required
	return max_power_required

def _main():
	[tests_n] = _read_ints()
	for i_test in range(tests_n):
		[caves_n] = _read_ints()
		monsters_armors_groups = [_read_cave_data() for i_cave in range(caves_n)]
		result = find_minimum_power_hero_needs(monsters_armors_groups)
		print(result)

def _read_cave_data():
	[k, *monsters_armors] = tuple(_read_ints())
	assert len(monsters_armors) == k
	return monsters_armors

def _read_ints():
	return map(int, _sys.stdin.readline().split())
_main()


for t in range(int(input())):
	n = int(input())
	a = [list(map(int, input().split())) for _ in range(n)]
	b = []
	for i in range(n):
		start = 0
		cur = 0
		for j in range(1, len(a[i])):
			if cur <= a[i][j]:
				delta = a[i][j] + 1 - cur
				cur += 1 + delta
				start += delta
			else:
				cur += 1
		b.append([start, cur])
	b.sort()
	start = 0
	cur = 0
	for i in range(n):
		if cur < b[i][0]:
			delta = b[i][0] - cur
			cur = b[i][1]
			start += delta
		else:
			cur += b[i][1] - b[i][0]
	print(start)


t = int(input())
for w in range(t):
	n = int(input())
	Minimums = []
	find = False
	for i in range(n):
		Data = input().split()
		candidate = int(Data[1]) + 1
		for j in range(1, int(Data[0])):
			if int(Data[j + 1]) - j + 1 > candidate:
				candidate = int(Data[j + 1]) - j + 1
		Minimums.append((candidate, candidate + int(Data[0]), int(Data[0])))
	Minimums.sort()
	answer = Minimums[0][0]
	count = 0
	for i in range(len(Minimums) - 1):
		count += Minimums[i][2]
		if answer + count < Minimums[i + 1][0]:
			answer = Minimums[i + 1][0] - count
	print(answer)


from collections import deque
import heapq
from math import sqrt
import operator
from operator import itemgetter
import sys
import copy
inf_var = 0
if inf_var == 1:
	inf = open('input.txt', 'r')
else:
	inf = sys.stdin
input = inf.readline

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

def read_one_float():
	return float(input().rstrip('\n'))

def read_list_of_ints():
	res = [int(val) for val in input().rstrip('\n').split(' ')]
	return res

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

def main():
	tests = read_one_int()
	for _ in range(tests):
		n = read_one_int()
		stat = []
		for _ in range(n):
			elements = read_list_of_ints()
			m = elements[0]
			armors = elements[1:]
			for i in range(m):
				armors[i] -= i
			enter = max(armors) + 1
			out = enter + m
			stat.append((enter, out))
		stat.sort()
		res = stat[0][0]
		power = stat[0][1]
		for i in range(1, len(stat)):
			(enter, out) = stat[i]
			if enter > power:
				res += enter - power
				power = out
			else:
				power += out - enter
		print(res)
main()


import sys
import math
from collections import Counter
input = sys.stdin.readline
T = int(input().strip())
for t in range(T):
	n = int(input().strip())
	need = []
	for c in range(n):
		lst = [int(hp) for hp in input().strip().split()]
		ch = 0
		for i in range(1, lst[0] + 1):
			ch = max(ch, lst[i] - i + 1)
		need.append((ch + 1, lst[0]))
	need.sort()
	(ans, last) = (need[0][0], need[0][1])
	for i in range(1, n):
		ans = need[i][0] - last if need[i][0] - last > ans else ans
		last = last + need[i][1]
	print(ans)


tt = int(input())
for _ in range(tt):
	n = int(input())
	k = []
	c = []
	for i in range(n):
		cave = list(map(int, input().split()))
		k.append(cave[0])
		sh = cave[1] + 1
		for j in range(2, k[-1] + 1):
			sh = max(sh, cave[j] - j + 2)
		c.append((sh, i))
	c.sort(key=lambda x: x[0])
	ans = c[0][0]
	strength = ans + k[c[0][1]]
	for i in range(1, n):
		j = c[i][1]
		add = 0 if strength > c[i][0] else c[i][0] - strength
		ans += add
		strength += add + k[j]
	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')
from math import ceil

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

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

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

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
for _ in range(int(input()) if True else 1):
	n = int(input())
	v = []
	for i in range(n):
		a = list(map(int, input().split()))
		req = 0
		for j in range(1, len(a)):
			req = max(req, a[j] - (j - 1) + 1)
		v += [(req, a[0])]
	v = sorted(v, key=lambda x: (x[0], -x[1]))
	ans = 0
	extra = 0
	for (health, d) in v:
		if ans + extra >= health:
			extra += d
			continue
		ans += health - (ans + extra)
		extra += d
	print(ans)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	valors = []
	for _ in range(n):
		ip = map(int, input().split())
		guany = next(ip)
		minim = 0
		for (i, v) in enumerate(ip):
			val = v - i
			minim = max(minim, val)
		valors.append([minim, guany])
	valors.sort()
	(power, extra) = (0, 0)
	for (cost, guany) in valors:
		if power <= cost:
			extra += cost + 1 - power
			power = cost + 1
		power += guany
	print(extra)


for _ in range(int(input())):
	n = int(input())
	mons = []
	for i in range(n):
		temp = list(map(int, input().split()))
		mons.append(temp)
	atleast = []
	for i in range(n):
		start = mons[i][1] + 1
		curr = mons[i][1] + 2
		for j in range(2, mons[i][0] + 1):
			if curr > mons[i][j]:
				curr += 1
			else:
				diff = mons[i][j] + 1 - curr
				start += diff
				curr = mons[i][j] + 2
		atleast.append([start, mons[i][0]])
	atleast.sort()
	ans = atleast[0][0]
	curr = atleast[0][0] + atleast[0][1]
	for i in range(1, n):
		if curr >= atleast[i][0]:
			curr += atleast[i][1]
		else:
			diff = atleast[i][0] - curr
			ans += diff
			curr = atleast[i][0] + atleast[i][1]
	print(ans)


T = int(input())
for _ in range(T):
	N = int(input())
	powers = []
	for i in range(N):
		(M, *cave) = list(map(int, input().split()))
		for j in range(M):
			cave[j] = cave[j] - j + 1
		powers.append((max(cave), M))
	powers.sort()
	power = powers[0][0]
	output = power
	for (p, n) in powers:
		if power >= p:
			power += n
		else:
			output += p - power
			power = p + n
	print(output)


import math
import sys
import collections
import bisect
import time
import random
import itertools
from collections import Counter, defaultdict

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

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

def get_string():
	return sys.stdin.readline().strip()
for t in range(int(input())):
	n = int(input())
	arr = []
	order = []
	for i in range(n):
		row = get_list()
		maxim = 0
		for j in range(1, len(row)):
			v = row[j] - (j - 1)
			maxim = max(maxim, v)
		order.append([maxim, i])
		arr.append(row[1:])
	order.sort()
	defeated = 0
	ans = 0
	for (maxim_power, pos) in order:
		curr = ans
		for monster_power in arr[pos]:
			if curr + defeated > monster_power:
				defeated += 1
				continue
			diff = monster_power - (curr + defeated)
			curr += diff + 1
			defeated += 1
		ans = max(ans, curr)
	print(ans)


for _ in range(int(input())):
	n_cave = int(input())
	dun = []
	for __ in range(n_cave):
		a = list(map(int, input().split()))
		dun.append([max((a[i + 1] - i + 1 for i in range(a[0]))), a[0]])
	dun.sort(key=lambda x: x[0])
	ans = dun[0][0]
	power = dun[0][0]
	for hero in dun:
		if power < hero[0]:
			ans += hero[0] - power
			power = hero[0] + hero[1]
		else:
			power += hero[1]
	print(ans)


from sys import stdin
input = stdin.readline
import math
t = int(input())
for i in range(t):
	n = int(input())
	arr = []
	for i in range(n):
		l = [int(x) for x in input().split()]
		m = -math.inf
		for i in range(1, l[0] + 1):
			m = max(m, l[i] - i + 1)
		l.append(m)
		arr.append(l)
	arr.sort(key=lambda x: x[-1])
	ans = math.inf
	start = 1
	end = 10 ** 9 + 1
	while start <= end:
		mid = (start + end) // 2
		x = mid
		flag = True
		for i in range(n):
			for j in range(1, arr[i][0] + 1):
				if x <= arr[i][j]:
					flag = False
					break
				x = x + 1
			if flag == False:
				break
		if flag:
			ans = mid
			end = mid - 1
		else:
			start = mid + 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	vp = []
	for i in range(n):
		v = list(map(int, input().split()))
		ma = 0
		for j in range(v[0]):
			ma = max(v[j + 1] - j, ma)
		vp.append((ma, v[0]))
	vp.sort()
	ans = 0
	c = 0
	for x in range(n):
		ans = max(ans, vp[x][0] - c)
		c += vp[x][1]
	print(ans + 1)


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

def func():
	keys = list(game.keys())
	ans = defaultdict(list)
	for key in keys:
		for cave in game[key]:
			start = 0
			wins = 0
			begin = 0
			for enemy in cave:
				if start <= enemy:
					start = enemy + 1
				begin = start - wins
				wins += 1
				start += 1
			ans[begin].append(wins)
	k = list(ans)
	k.sort()
	lol = k[0]
	haha = lol
	wins = 0
	for i in k:
		for j in ans[i]:
			if lol < i:
				lol = i
			haha = lol - wins
			wins += j
			lol += j
	print(haha)
for _ in range(int(input())):
	n = int(input())
	game = defaultdict(list)
	for __ in range(n):
		lst = list(map(int, input().split()))[1:]
		game[max(lst)].append(lst)
	func()


import sys
from sys import stdin, stdout
from math import ceil, floor, sqrt, log, log2, log10
from collections import Counter
int_max = float('inf')
int_min = -float('inf')
ANS = []
input = stdin.readline

def solve():
	pass
t = int(input())
for i in range(t):
	n = int(input())
	monsters = []
	for i in range(n):
		a = list(map(int, input().split()))
		monsters.append(a)
	b = []
	for i in range(n):
		maxx = int_min
		for j in range(1, monsters[i][0] + 1):
			maxx = max(maxx, monsters[i][j] - j + 1)
		b.append([maxx, monsters[i][0]])
	b.sort()
	total = 0
	ans = int_min
	for i in range(n):
		ans = max(b[i][0] - total, ans)
		total += b[i][1]
	print(ans + 1)
print('\n'.join(ANS))


import os
import sys
from io import BytesIO, IOBase

def main():
	for _ in range(int(input())):
		n = int(input())
		a = []
		c = []
		for j in range(n):
			b = list(map(int, input().split()))
			a.append(b[1:])
			(z, ans) = (0, 0)
			for i in range(1, len(b)):
				if z <= b[i]:
					ans += b[i] + 1 - z
					z = b[i] + 1
				z += 1
			c.append(ans)
		d = sorted(range(n), key=lambda x: c[x])
		(ans, z) = (0, 0)
		for i in d:
			for j in a[i]:
				if z <= j:
					ans += j + 1 - z
					z = j + 1
				z += 1
		print(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()


count = int(input())
data = []
for i in range(count):
	n = int(input())
	test = []
	for j in range(n):
		test.append([int(k) for k in input().split()])
	data.append([n, test])
for d in data:
	n = d[0]
	caves = d[1]
	maxes = []
	for cave in caves:
		length = cave[0]
		maximum = 1
		for i in range(length):
			s = cave[i + 1] - i
			if s > maximum:
				maximum = s
		maxes.append([maximum, length])
	maxes = sorted(maxes, key=lambda x: x[0])
	for i in range(n):
		if i >= 1:
			maxes[i][1] = maxes[i][1] + maxes[i - 1][1]
	res = []
	m = 1
	for i in range(n):
		if i > 0:
			s = maxes[i][0] - maxes[i - 1][1]
			if s > m:
				m = s
		else:
			s = maxes[i][0]
			if s > m:
				m = s
	print(m + 1)


from collections import defaultdict, deque, Counter
import sys
import bisect
import math
input = sys.stdin.readline
mod = 1000000007

def count(arr):
	l = []
	for j in range(1, arr[0] + 1):
		l.append(arr[j] - j + 1)
	return max(l)

def check(num):
	for i in range(len(req)):
		if num > req[i][0]:
			num += req[i][1]
		else:
			return False
	return True
t = int(input())
for i in range(t):
	n = int(input())
	(req, mon) = ([], [0])
	for i in range(n):
		l = [int(i) for i in input().split()]
		req.append([count(l), l[0]])
	req.sort(key=lambda x: (x[0], -x[1]))
	(lo, hi) = (0, 10 ** 9 + 1)
	ans = hi
	while lo < hi:
		mid = (lo + hi) // 2
		if check(mid):
			ans = mid
			hi = mid
		else:
			lo = mid + 1
	print(ans)


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

def solve():
	n = int(input())
	caves = []
	for _ in range(n):
		cave = list(map(int, input().split()))
		size = cave.pop(0)
		difficulty = max((health - i for (i, health) in enumerate(cave))) + 1
		caves.append((difficulty, size, cave))
	caves.sort()
	power_needed = 0
	current_power = 0
	for (difficulty, size, cave) in caves:
		if current_power < difficulty:
			power_needed += difficulty - current_power
			current_power = difficulty
		current_power += size
	return power_needed
t = int(input())
output = []
for _ in range(t):
	output.append(solve())
print(*output, sep='\n')


import sys
t = int(input())
for _ in range(t):
	k = int(input())
	bossMList = []
	for _ in range(k):
		caves = list(map(int, sys.stdin.readline().strip().split()))
		n = caves.pop(0)
		maxMonstr = 0
		for pos in range(n):
			maxMonstr = max(maxMonstr, caves[pos] - pos)
		bossMList.append((maxMonstr, n))
	bossMList.sort(key=lambda x: x[0])
	hPower = 0
	mCount = 0
	for (m, c) in bossMList:
		hPower = max(hPower, m - mCount)
		mCount += c
	print(hPower + 1)


import math

def solve():
	n = int(input())
	l = []
	for i in range(n):
		a = list(map(int, input().split()))
		mx = 0
		for j in range(1, a[0] + 1):
			mx = max(a[j] + 2 - j, mx)
		l.append([mx, a[0]])
	l.sort()
	ans = 0
	s = 0
	for i in range(n):
		ans = max(ans, l[i][0] - s)
		s += l[i][1]
	print(ans)
	return
t = int(input())
while t:
	t -= 1
	solve()


t = int(input())
for _ in range(t):
	K = []
	K2 = []
	n = int(input())
	for i in range(n):
		temp = list(map(int, input().split()))
		l = temp[0]
		Max = 0
		for k in range(l):
			Max = max(temp[k + 1] - k + 1, Max)
		K.append((Max, l))
	K.sort()
	Max = 0
	S = 0
	for k in range(n):
		Max = max(K[k][0] - S, Max)
		S += K[k][1]
	print(Max)


t = int(input())
for z in range(t):
	n = int(input())
	en = []
	for x in range(n):
		k = list(map(int, input().split()))
		s = k[0]
		m = 0
		for j in range(1, s + 1):
			m = max(m, k[j] - j + 1)
		en.append([m, s])
	en.sort()
	m = 0
	b = 0
	for l in en:
		m = max(m, l[0] - b)
		b += l[1]
	print(m + 1)


from operator import itemgetter
t = int(input())
for _ in range(t):
	n = int(input())
	caves = []
	for _ in range(n):
		(k, *armor_values) = list(map(int, input().split()))
		total_req_strength = armor_values[0] + 1
		for i in range(1, k):
			req_strength = armor_values[i] + 1 - i
			if req_strength > total_req_strength:
				total_req_strength = req_strength
		cave = (total_req_strength, armor_values)
		caves.append(cave)
	caves.sort(key=itemgetter(0))
	res = caves[0][0]
	accumulated_length = len(caves[0][1])
	for (req_strength, armor_values) in caves[1:]:
		updated_req_strength = req_strength - accumulated_length
		if updated_req_strength > res:
			res = updated_req_strength
		accumulated_length += len(armor_values)
	print(res)


for _ in range(int(input())):
	n = int(input())
	arr = []
	for i in range(n):
		a = list(map(int, input().split()))
		ma = 0
		for j in range(a[0]):
			ma = max(a[j + 1] - j, ma)
		arr.append((ma, a[0]))
	arr.sort()
	ans = 0
	s = 0
	for x in range(n):
		ans = max(ans, arr[x][0] - s)
		s += arr[x][1]
	print(ans + 1)


def get_min_energy(monsters: list):
	return max((a - i + 1 for (i, a) in enumerate(monsters)))

def solve_one():
	n = int(input())
	min_energy_list = []
	for _ in range(n):
		(monster_num, *monsters) = [int(x) for x in input().split()]
		min_energy = get_min_energy(monsters)
		min_energy_list.append((min_energy, monster_num))
	min_energy_list.sort()
	global_min_energy = min_energy_list[0][0]
	cur_energy = global_min_energy
	for (min_energy, monster_num) in min_energy_list:
		if cur_energy < min_energy:
			gap = min_energy - cur_energy
			global_min_energy += gap
			cur_energy += gap
		cur_energy += monster_num
	print(global_min_energy)

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


t = int(input())
for _ in range(t):
	l = []
	n = int(input())
	for _ in range(n):
		a = [int(s) for s in input().split()]
		an = a[0]
		m = 0
		for (i, e) in enumerate(a[1:]):
			m = max(e - i + 1, m)
		l.append((m, an))
	l.sort()
	ss = 0
	res = l[0][0]
	curSum = l[0][1]
	curVal = res + curSum
	for e in l[1:]:
		if e[0] > curVal:
			res = e[0] - curSum
			curVal = e[0]
		curVal = curVal + e[1]
		curSum += e[1]
	print(res)


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

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

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

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

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

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

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

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

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

def si():
	return input()

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

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

def cmax(a, l):
	m = 0
	for i in range(l):
		if a[i] - i > m:
			m = a[i] - i
	return m

def solve():
	n = II()
	call = []
	m_ind = []
	for _ in range(n):
		x = LI()
		k = x[0]
		a = x[1:]
		m_ind.append(cmax(a, k))
		call.append(a)
	fcall = [x for (_, x) in sorted(zip(m_ind, call))]
	fa = []
	for i in fcall:
		fa += i
	ini = m = fa[0]
	for i in range(len(fa)):
		if m <= fa[i]:
			ini += fa[i] - m + 1
			m = ini + i + 1
		else:
			m += 1
	return ini

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


from __future__ import division, print_function
import math
import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

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

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

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

def invr():
	return map(int, input().split())
for _ in range(inp()):
	n = inp()
	l = []
	for i in range(n):
		tmp = inlt()
		l.append(tmp[1:])
	d = []
	for each in l:
		d.append([])
		for (i, every) in enumerate(each):
			d[-1].append(every + 1 - i)
	d.sort(key=lambda l: max(l))
	ln = []
	for i in range(len(d)):
		ln.append(len(d[i]))
	cnt = 0
	idx = 0
	mx = 0
	for each in d:
		for every in each:
			mx = max(mx, every - cnt)
		cnt += ln[idx]
		idx += 1
	print(mx)


import sys, math
from collections import deque, defaultdict
import operator as op
from functools import reduce
from itertools import permutations
import heapq
I = sys.stdin.readline
alpha = 'abcdefghijklmnopqrstuvwxyz'
mod = 10 ** 9 + 7

def ii():
	return int(I().strip())

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

def mi():
	return map(int, I().strip().split())

def ncr(n, r):
	r = min(r, n - r)
	numer = reduce(op.mul, range(n, n - r, -1), 1)
	denom = reduce(op.mul, range(1, r + 1), 1)
	return numer // denom

def ispali(s):
	i = 0
	j = len(s) - 1
	while i < j:
		if s[i] != s[j]:
			return False
		i += 1
		j -= 1
	return True

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

def f(all_mons):
	min_power = 0
	curr_power = 0
	for i in all_mons:
		if curr_power <= i:
			min_power += i - curr_power + 1
			curr_power = i + 1
		curr_power += 1
	return min_power

def main():
	ans = ''
	for _ in range(ii()):
		n = ii()
		caves = []
		arr = []
		for i in range(n):
			mons = li()
			arr.append([f(mons[1:]), i])
			caves.append(mons[1:])
		arr.sort()
		all_mons = []
		for i in arr:
			idx = i[1]
			all_mons += caves[idx]
		min_power = f(all_mons)
		ans += str(min_power) + '\n'
	print(ans)
main()


def min_power(N, nums):
	output = nums[-1] + 1
	for i in range(N - 2, -1, -1):
		output = max(output - 1, nums[i] + 1)
	return output
T = int(input())
for i in range(T):
	N = int(input())
	powers = []
	for j in range(N):
		cave = list(map(int, input().split()))
		powers.append((min_power(cave[0], cave[1:]), cave[0]))
	powers.sort()
	power = powers[0][0]
	output = power
	for (p, n) in powers:
		if power >= p:
			power += n
		else:
			output += p - power
			power = p + n
	print(output)


t = int(input())

def check_min_entry(lst):
	min = 0
	extra = 0
	for i in lst:
		if min + extra <= i:
			min = i - extra + 1
		extra += 1
	return min

def check_main_entry(lst):
	min = 0
	extra = 0
	for i in lst:
		if min + extra < i[0]:
			min = i[0] - extra
		extra += i[1]
	return min
while t != 0:
	n = int(input())
	array = []
	min_entry = []
	for i in range(n):
		temp = list(map(int, input().split()))
		temp.pop(0)
		array.append(temp)
	for i in array:
		temp = [check_min_entry(i), len(i)]
		min_entry.append(temp)
	min_entry.sort(key=lambda x: x[0])
	print(check_main_entry(min_entry))
	t -= 1


_ = int(input())
for __ in range(_):
	n = int(input())
	a = []
	for ___ in range(n):
		tmp_l = list(map(int, input().split()))
		a.append(tmp_l[1:])
	for z in a:
		c_val = z[0] + 1
		beg_val = z[0] + 1
		for zz in range(1, len(z)):
			c_val += 1
			if z[zz] >= c_val:
				beg_val = z[zz] + 1 - zz
				c_val = z[zz] + 1
		z.append(beg_val)
		z.append(len(z) - 1)
	a = sorted(a, key=lambda x: (x[-2], -x[-1]))
	if len(a) == 1:
		print(a[0][-2])
		continue
	beg_val = a[0][-2] + len(a[0]) - 2
	wyn = a[0][-2]
	for z in range(1, len(a), +1):
		if beg_val < a[z][-2]:
			wyn += a[z][-2] - beg_val
			beg_val = a[z][-2]
		beg_val += len(a[z]) - 2
	print(wyn)


t = int(input())
for _ in range(t):
	n = int(input())
	d = []
	for i in range(n):
		a = list(map(int, input().split()))
		k = a.pop(0)
		mx = a[0]
		for j in range(1, k):
			mx = max(mx, a[j] - j)
		d.append([mx + 1, k])
	d.sort(key=lambda x: (x[0], x[1]))
	res = d[0][0]
	plus_power = d[0][1]
	for i in range(1, n):
		if plus_power + res < d[i][0]:
			res = d[i][0] - plus_power
		plus_power += d[i][1]
	print(res)


import sys
from collections import deque

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

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

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

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

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

def solve(n, arr):
	final = []
	bonus = []
	for ele in arr:
		k = ele[0]
		temp = ele[1:]
		best = 0
		for i in range(k):
			best = max(best, temp[i] - i)
		final.append([best, -k])
	final.sort()
	best = final[0][0]
	k = abs(final[0][1])
	for i in range(1, n):
		best = max(best, final[i][0] - k)
		k += abs(final[i][1])
	ans = best + 1
	sys.stdout.write(str(ans) + '\n')
T = get_int()
while T:
	n = get_int()
	arr = []
	tempN = n
	while tempN:
		arr1 = get_list()
		arr.append(arr1)
		tempN -= 1
	solve(n, arr)
	T -= 1


def solve(n, c):
	se = []
	for i in range(n):
		l = c[i]
		initial = c[i][1] + 1
		cur = initial
		for j in range(1, c[i][0] + 1):
			if l[j] > cur:
				initial = initial + (l[j] - cur + 1)
				cur = l[j] + 1
			elif l[j] == cur:
				initial += 1
				cur = l[j] + 1
			cur += 1
		se.append([initial, c[i][0]])
	se.sort()
	initial = se[0][0]
	cur = initial
	for i in range(n):
		if se[i][0] > cur:
			initial += se[i][0] - cur
			cur += se[i][0] - cur
		cur += se[i][1]
	return initial
for _ in range(int(input())):
	n = int(input())
	c = []
	for i in range(n):
		arr = list(map(int, input().split()))
		c.append(arr)
	print(solve(n, c))


from sys import stdin
read = lambda : stdin.readline()
for _ in range(int(read())):
	n = int(read())
	levels = []
	main = []
	for i in range(n):
		main.append(list(map(int, read().split())))
	main.sort(reverse=True)
	op = []
	for temp in main:
		ans = 0
		s = 0
		for num in temp[1:]:
			if s <= num:
				ans += num - s + 1
				s = num + 2
			else:
				s += 1
		op.append((ans, temp[0]))
	op.sort()
	ans = 0
	s = ans
	tot = 0
	for (minpow, inc) in op:
		if s < minpow:
			ans = minpow - tot
			s = minpow
		s += inc
		tot += inc
	print(ans)


import sys
input = sys.stdin.readline

def func(ai):
	ct = 0
	val = ai[0] + 1
	ret = ai[0] + 1
	for iii in range(len(ai)):
		if val > ai[iii]:
			val += 1
		else:
			val = ai[iii] + 1
			ret = max(ret, val - ct)
		ct += 1
	return [ret, -len(ai)]
for x in range(int(input())):
	n = int(input())
	li = []
	for _ in range(n):
		ki = list(map(int, input().split()))[1:]
		li.append(ki)
	li.sort(key=lambda i: func(i))
	mini = li[0][0] + 1
	ans = li[0][0] + 1
	ct = 0
	for i in li:
		for ii in range(len(i)):
			if mini > i[ii]:
				mini += 1
			else:
				mini = i[ii] + 1
				ans = max(ans, mini - ct)
				mini += 1
			ct += 1
	print(ans)


for _ in range(int(input())):
	D = []
	N = int(input())
	for _ in range(N):
		A = list(map(int, input().split()))
		tmp = []
		for i in range(1, A[0] + 1):
			tmp.append(A[i] - (i - 1))
		D.append((max(tmp) + 1, A[0]))
	D.sort()
	ans = D[0][0]
	cnt = D[0][1]
	for i in range(1, N):
		d = D[i]
		cur = ans + cnt
		if cur < d[0]:
			ans += d[0] - cur
		cnt += d[1]
	print(ans)


def func():
	t = int(input().strip())
	cases = []
	for _ in range(t):
		n = int(input().strip())
		caves = []
		for _ in range(n):
			a = list(map(int, input().split()))
			tmp = []
			for i in range(1, a[0] + 1):
				tmp.append(a[i] - (i - 1))
			caves.append((max(tmp) + 1, a[0]))
		cases.append(caves)
	for case in cases:
		print(video_game(case))

def video_game(caves):
	caves.sort()
	(ans, cnt) = (caves[0][0], caves[0][1])
	for i in range(1, len(caves)):
		cave = caves[i]
		curr = ans + cnt
		if curr < cave[0]:
			ans += cave[0] - curr
		cnt += cave[1]
	return ans
func()


from sys import stdin
ii = lambda : int(input())
li = lambda : list(map(int, stdin.readline().strip().split()))
for _ in range(ii()):
	n = ii()
	l = []
	for i in range(n):
		c = li()
		pw = 0
		for j in range(1, c[0] + 1):
			pw = max(pw, c[j] - j + 2)
		l.append([pw, c[0]])
	l.sort()
	(ans, s) = (0, 0)
	for i in range(n):
		ans = max(ans, l[i][0] - s)
		s += l[i][1]
	print(ans)


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

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

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

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

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

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

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

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

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

def f(arr):
	maxi = 0
	for i in range(len(arr)):
		maxi = max(maxi, arr[i] - i + 1)
	return maxi

def solve():
	for _ in range(nin()):
		n = nin()
		heap = []
		for i in range(n):
			arr = read()
			k = arr[0]
			heap.append((f(arr[1:]), k))
		ans = 0
		k_sum = 0
		heap.sort()
		for (curr, k) in heap:
			if ans + k_sum < curr:
				ans += curr - (ans + k_sum)
			k_sum += k
		ans_.append(ans)
solve()
for i in ans_:
	print(i)


t = int(input())
for _ in range(t):
	(n, ipowers) = (int(input()), [])
	for i in range(n):
		ls = [int(x) for x in input().split()]
		k = ls[0]
		ipowers.append((max((ls[j] - j + 1 for j in range(1, k + 1))) + 1, k))
	ipowers.sort()
	basepower = power = ipowers[0][0]
	for j in range(1, n):
		power += ipowers[j - 1][1]
		if power < ipowers[j][0]:
			basepower += ipowers[j][0] - power
			power = ipowers[j][0]
	print(basepower)


exec('\nimport sys\n\ninput = sys.stdin.readline\n\n\n\n\ndef give(a):\n    m = len(a)\n    c = a[0] + 1\n    for i in range(m):\n        #print(c, a[i])\n        if c <= a[i]:\n            c = a[i] + 2\n        else:\n            c += 1\n    return [c - m, c]\n\n\ndef solve(res):\n    ans = res[0][0]\n    c = res[0][1]\n    for i in range(1, len(res)):\n        if res[i][0] > c:\n            ans += res[i][0] - c\n            c = res[i][1]\n        else:\n            c = res[i][1] + c - res[i][0]\n    return ans\n\n\n\nfor _ in range(int(input())):\n    n = int(input())\n    mat = []\n    res = []\n    for i in range(n):\n        a = list(map(int, input().split()))\n        res.append(give(a[1:]))\n    #print(res)\n    #t1 = sorted(res, key=lambda x:x[1])\n    t2 = sorted(res, key=lambda x:x[0])\n    sys.stdout.write(str(solve(t2)) + "\\n")\n')


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	A = [list(map(int, input().split()))[1:] for _ in range(n)]
	cnt = [len(a) for a in A]
	B = []
	for a in A:
		cur = 0
		for (i, x) in enumerate(a):
			tmp = x + 1 - i
			cur = max(cur, tmp)
		B.append(cur)
	cand = sorted(range(n), key=lambda x: (B[x], -cnt[x]))
	pre = 0
	ans = 0
	for idx in cand:
		ans = max(ans, B[idx] - pre)
		pre += cnt[idx]
	print(ans)


t = int(input())
for tt in range(t):
	n = int(input())
	size = []
	monsters = []
	for i in range(n):
		temp = list(map(int, input().split()))
		strongest = max([temp[i] - i + 1 for i in range(1, temp[0] + 1)])
		monsters.append((strongest, temp[0]))
	monsters.sort()
	ans = 0
	curr = 0
	for ele in monsters:
		ans = max(ans, ele[0] - curr)
		curr += ele[1]
	print(ans + 1)


for i in range(int(input())):
	n = int(input())
	res = []
	for j in range(n):
		l = list(map(int, input().split()))
		s = l[0]
		max_t = 0
		for k in range(1, s + 1):
			max_t = max(max_t, l[k] - k + 2)
		res.append((max_t, s))
	res.sort()
	f_ans = 0
	a = 0
	for i in range(len(res)):
		f_ans = max(f_ans, res[i][0] - a)
		a += res[i][1]
	print(f_ans)


from collections import defaultdict
for _ in range(int(input())):
	n = int(input())
	dic = []
	for i in range(n):
		lst = list(map(int, input().split()))
		k = lst[0]
		mx = 0
		for j in range(1, k + 1):
			mx = max(mx, lst[j] - j + 1)
		dic.append([mx, 0, k])
	ls = []
	dic.sort()
	ls = dic.copy()
	ans = []
	prev = 0
	for i in ls:
		val = i[0] - prev
		ans.append(val)
		prev += i[2]
	print(max(ans) + 1)


t = int(input())
for _ in range(t):
	n = int(input())
	table = []
	for i in range(n):
		a = [int(f) for f in input().split()]
		k = a[0]
		a = a[1:]
		entry_lvl = a[0] + 1
		for j in range(1, k):
			entry_lvl = max(entry_lvl, a[j] - j + 1)
		bonus_lvl = k
		table.append((entry_lvl, bonus_lvl))
	table.sort()
	lvl = table[0][0]
	start = lvl
	rewards = 0
	for i in range(n - 1):
		rewards += table[i][1]
		lvl += table[i][1]
		if lvl < table[i + 1][0]:
			start = table[i + 1][0] - rewards
			lvl = table[i + 1][0]
	print(start)


import collections
import math
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')
for _ in range(int(input())):
	n = int(input())
	arr2 = []
	for __ in range(n):
		arr = list(map(int, input().split()))
		m = -1
		z = arr.pop(0)
		for (k, kk) in enumerate(arr):
			m = max(m, kk - k)
		arr2.append((m, z))
	arr2.sort()
	ans = -1
	prev = 0
	for jj in arr2:
		ans = max(ans, jj[0] - prev)
		prev += jj[1]
	print(ans + 1)


T = int(input())
for t in range(T):
	n = int(input())
	need = []
	for c in range(n):
		lst = [int(hp) for hp in input().split()]
		ch = 0
		for i in range(1, lst[0] + 1):
			ch = max(ch, lst[i] - i + 1)
		need.append((ch + 1, lst[0]))
	need.sort()
	(ans, last) = (need[0][0], need[0][1])
	for i in range(1, n):
		ans = need[i][0] - last if need[i][0] - last > ans else ans
		last = last + need[i][1]
	print(ans)


def check(M):
	x = M
	for i in range(n):
		if x <= u[i][0]:
			return False
		x += u[i][1]
	return True
from sys import stdin
input = stdin.readline
ans = []
for _ in range(int(input())):
	n = int(input())
	u = []
	for _ in range(n):
		p = list(map(int, input().split()))[1:]
		cur = 0
		for i in range(len(p)):
			cur = max(cur, p[i] - i)
		u.append((cur, len(p)))
	u.sort()
	L = 0
	R = 10 ** 9 + 1
	while R - L > 1:
		M = (L + R) // 2
		if check(M):
			R = M
		else:
			L = M
	ans.append(R)
print('\n'.join(map(str, ans)))


def fight():
	cnt_caves = int(input())
	caves = []
	for i in range(cnt_caves):
		inputs = [int(x) for x in input().split(' ')]
		caves.append(inputs[1:])
	gmap = []
	for c in caves:
		(p, n) = stats_caves(c)
		gmap.append((p, n))
	gmap.sort(key=lambda k: k[0])
	cur_p = min_p = sum = 0
	l = len(gmap)
	for i in range(l):
		if cur_p < gmap[i][0]:
			cur_p = gmap[i][0] + gmap[i][1]
			min_p = gmap[i][0] - sum
		else:
			cur_p += gmap[i][1]
		sum += gmap[i][1]
	return min_p

def stats_caves(mns):
	cnt = 0
	min_p = 0
	cur_p = 0
	for m in mns:
		if cur_p <= m:
			cur_p = m + 1
			min_p = cur_p - cnt
		else:
			cur_p += 1
		cnt += 1
	return (min_p, len(mns))
test_count = int(input())
for i in range(test_count):
	print(fight())


def process_cave(a):
	k = a[0]
	min_start = max([ai - i + 1 for (i, ai) in enumerate(a[1:])])
	gain = k
	return (min_start, gain)
t = int(input())
for i in range(t):
	n = int(input())
	l = []
	pmin = 0
	pneeded = 0
	for j in range(n):
		a = [int(c) for c in input().split(' ')]
		l.append(process_cave(a))
	ls = sorted(l, key=lambda x: x[0])
	for cave in ls:
		needed = max(0, cave[0] - pmin)
		pmin += needed
		pneeded += needed
		pmin += cave[1]
	print(pneeded)


for _ in range(int(input())):
	n = int(input())
	powers = []
	for i in range(n):
		arr = list(map(int, input().split()))
		for a in range(1, arr[0] + 1):
			arr[a] -= a - 2
		m = max(arr[1:])
		p = m
		powers.append([p, p + arr[0]])
	powers.sort(key=lambda x: x[0])
	ans = powers[0][0]
	curval = powers[0][1]
	for p in powers[1:]:
		if p[0] > curval:
			ans += p[0] - curval
			curval = p[1]
		else:
			curval += p[1] - p[0]
	print(ans)


import heapq
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	h = []
	for _ in range(n):
		a = list(map(int, input().split()))
		k = a[0]
		m = 0
		for i in range(1, k + 1):
			m = max(m, a[i] - i + 2)
		heapq.heappush(h, (m, k))
	ans = 0
	now = 0
	while h:
		(m, k) = heapq.heappop(h)
		if now < m:
			ans += m - now
			now = m
		now += k
	print(ans)


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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

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

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

def list_inp(v_type):
	return list(map_inp(v_type))

def cmp(x, y):
	a = 0
	b = 0
	for (val, ind) in zip(x, range(len(x))):
		a = max(a, val - ind)
	for (val, ind) in zip(y, range(len(y))):
		b = max(b, val - ind)
	if a > b:
		return 1
	else:
		return -1
for _ in range(int(inp())):
	n = int(inp())
	caves = []
	for i in range(n):
		temp = list_inp(int)
		caves.append(temp[1:])
	order = list(sorted(caves, key=functools.cmp_to_key(cmp)))
	i = 0
	ans = 0
	for item in order:
		for it in item:
			ans = max(ans, it + 1 - i)
			i += 1
	print(ans)


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

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

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

def getints():
	return map(int, inputt().split())
for _ in range(getint()):
	n = getint()
	cave = []
	for _ in range(n):
		a = list(getints())
		k = a[0]
		a = a[1:]
		aa = [m - i for (i, m) in enumerate(a)]
		minlvl = max(aa) + 1
		cave.append((minlvl, k))
	cave.sort(reverse=True)
	lvl = cave[0][0]
	for (minlvl, k) in cave[1:]:
		lvl = max(lvl - k, minlvl)
	print(lvl)


t = int(input())
for _ in range(t):
	n = int(input())
	l = []
	for i in range(n):
		lst = list(map(int, input().split()))
		k = lst[0]
		Xarmor = 0
		temp = 1
		for delta in range(1, k + 1):
			armor = lst[delta]
			Xarmor = max(Xarmor, armor + temp)
			temp -= 1
		l.append([Xarmor, k])
	l.sort()
	ans = l[0][0]
	c = l[0][1]
	for j in range(1, n):
		ans += max(0, l[j][0] - ans - c)
		c += l[j][1]
	print(ans)


from sys import stdin
input = stdin.readline

def check(p):
	for i in range(n):
		if a[i][0] > p:
			return False
		p += a[i][1]
	return True

def answer():
	(l, r) = (0, 10 ** 9 + 1)
	while l <= r:
		mid = (l + r) // 2
		yes = check(mid)
		if yes:
			r = mid - 1
			ans = mid
		else:
			l = mid + 1
	return ans
for T in range(int(input())):
	n = int(input())
	a = []
	for i in range(n):
		x = list(map(int, input().split()))
		m = 0
		for i in range(1, x[0] + 1):
			m = max(m, x[i] - i + 2)
		a.append([m, x[0]])
	a.sort(key=lambda x: [x[0], -x[1]])
	print(answer())


import sys
from math import sqrt, ceil, floor, gcd
from collections import Counter
input = lambda : sys.stdin.readline()

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

def str_arr():
	return list(map(str, input().split()))

def get_str():
	return map(str, input().split())

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

def get_flo():
	return map(float, input().split())

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

def solve(n, mat):
	pass
for _ in range(int(input())):
	n = int(input())
	tmp = []
	for i in range(n):
		arr = int_arr()
		maxx = 0
		for j in range(1, arr[0] + 1):
			maxx = max(maxx, arr[j] - j + 2)
		tmp.append([maxx, arr[0]])
	tmp.sort(key=lambda x: x[0])
	ans = 0
	num = 0
	for i in tmp:
		if i[0] > num:
			ans += i[0] - num
			num = i[0]
		num += i[1]
	print(ans)


from io import BytesIO, IOBase
import sys
import math
import os
import heapq
from collections import defaultdict, deque
from math import ceil
from bisect import bisect_left, bisect_left
from time import perf_counter
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 mint():
	return map(int, input().split())

def mfloat():
	return map(float, input().split())

def intin():
	return int(input())

class Cave:

	def __init__(self, arr):
		(self.n, *self.a) = arr
		self.needed = self.a[0] + 1
		for i in range(self.n):
			self.needed = max(self.needed, self.a[i] - i + 1)

def solve():
	n = int(input())
	caves = [Cave(map(int, input().split())) for i in range(n)]
	caves.sort(key=lambda c: c.needed)
	start = 0
	boost = 0
	for i in caves:
		if i.needed > boost + start:
			start += i.needed - boost - start
		boost += i.n
	print(start)

def main():
	t = 1
	t = int(input())
	for _ in range(t):
		solve()
start_time = perf_counter()
main()
print(perf_counter() - start_time, file=sys.stderr)


for _ in range(int(input())):
	n = int(input())
	caves = []
	for i in range(n):
		_x = 0
		cave = input().split()
		for j in range(1, len(cave)):
			e = int(cave[j])
			e -= j - 1
			if e > _x:
				_x = e
		caves.append([_x, len(cave) - 1])
	caves.sort()
	initial = caves[0][0] + 1
	current = initial
	for i in range(len(caves)):
		if current <= caves[i][0]:
			initial += caves[i][0] + 1 - current
			current = caves[i][0] + 1
		current += caves[i][1]
	print(initial)


t = int(input())
for i in range(t):
	n = int(input())
	cl = []
	for j in range(n):
		a = list(map(int, input().split()))
		c = -69420
		for k in range(1, a[0] + 1):
			c = max(a[k] - k + 2, c)
		cl.append([c, a[0]])
	cl.sort()
	ex = cl[0][1]
	for j in range(1, len(cl)):
		cl[j][0] -= ex
		ex += cl[j][1]
	cl.sort()
	print(cl[len(cl) - 1][0])


tests = int(input())
for t in range(tests):
	n = int(input())
	inp = []
	for i in range(n):
		line = input()
		inp.append([int(x) for x in line.split()])
	m_ent = []
	for i in range(n):
		mx = 0
		for j in range(1, len(inp[i])):
			mx = max(mx, inp[i][j] - j + 2)
		m_ent.append((mx, len(inp[i]) - 1))
	m_ent.sort()
	(ans, armor) = (0, 0)
	for i in range(n):
		if armor < m_ent[i][0]:
			ans += m_ent[i][0] - armor
			armor = m_ent[i][0]
		armor += m_ent[i][1]
	print(ans)


def find_power(lst):
	powers = []
	power = 0
	chambers = 0
	for a in lst:
		power = 0
		for (i, item) in enumerate(a):
			if item >= power:
				power = item + 1
			power += 1
		powers.append([power - len(a), len(a)])
	powers.sort()
	res = powers[0][0]
	current_power = powers[0][0]
	for i in range(len(powers) - 1):
		current_power += powers[i][1]
		chambers += powers[i][1]
		if current_power < powers[i + 1][0]:
			res = powers[i + 1][0] - chambers
			current_power = powers[i + 1][0]
	return res
n = int(input())
lst = []
for item in range(n):
	p = int(input())
	lst_sub = []
	for i in range(p):
		lst_sub.append([int(item) for item in input().split()[1:]])
	lst.append(find_power(lst_sub))
print(*lst, sep='\n')


for _ in range(int(input())):
	n = int(input())
	l = []
	for i in range(n):
		(m, *p) = [int(x) for x in input().split()]
		for j in range(m):
			p[j] = p[j] - j + 1
		l.append([max(p), m])
	l = sorted(l)
	ans = l[0][0]
	c = l[0][1]
	for j in range(1, n):
		ans += max(0, l[j][0] - ans - c)
		c += l[j][1]
	print(ans)


import heapq
tst = int(input())
for _ in range(tst):
	n = int(input())
	q = []
	for i in range(n):
		arr = list(map(int, input().split(' ')))
		k = arr[0]
		arr = arr[1:]
		current = arr[0] + 1
		need = arr[0] + 1
		for i in range(1, k):
			current += 1
			if current <= arr[i]:
				excessneed = arr[i] + 1 - current
				need += excessneed
				current = arr[i] + 1
		heapq.heappush(q, (need, k, i))
	(power, up, i) = heapq.heappop(q)
	result = power
	power += up
	while q:
		(cavepower, caveup, i) = heapq.heappop(q)
		if power >= cavepower:
			power += caveup
		else:
			result += cavepower - power
			power = cavepower
			power += caveup
	print(result)


import math, io, os, sys
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
for _ in range(t):
	n = int(input())
	caves = []
	for i in range(n):
		(k, *a) = list(map(int, input().split()))
		mx = 0
		for (ind, i) in enumerate(a):
			mx = max(mx, i + 1 - ind)
		caves.append((k, a, mx))
	caves.sort(key=lambda t: t[2])
	maxi = 0
	c = 0
	for i in caves:
		maxi = max(maxi, i[2] - c)
		c += i[0]
	sys.stdout.write(str(maxi) + '\n')