Ivan is playing yet another roguelike computer game. He controls a single hero in the game. The hero has $n$ equipment slots. There is a list of $c_i$ items for the $i$-th slot, the $j$-th of them increases the hero strength by $a_{i,j}$. The items for each slot are pairwise distinct and are listed in the increasing order of their strength increase. So, $a_{i,1} < a_{i,2} < \dots < a_{i,c_i}$.

For each slot Ivan chooses exactly one item. Let the chosen item for the $i$-th slot be the $b_i$-th item in the corresponding list. The sequence of choices $[b_1, b_2, \dots, b_n]$ is called a build.

The strength of a build is the sum of the strength increases of the items in it. Some builds are banned from the game. There is a list of $m$ pairwise distinct banned builds. It's guaranteed that there's at least one build that's not banned.

What is the build with the maximum strength that is not banned from the game? If there are multiple builds with maximum strength, print any of them.


-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 10$) — the number of equipment slots.

The $i$-th of the next $n$ lines contains the description of the items for the $i$-th slot. First, one integer $c_i$ ($1 \le c_i \le 2 \cdot 10^5$) — the number of items for the $i$-th slot. Then $c_i$ integers $a_{i,1}, a_{i,2}, \dots, a_{i,c_i}$ ($1 \le a_{i,1} < a_{i,2} < \dots < a_{i,c_i} \le 10^8$).

The sum of $c_i$ doesn't exceed $2 \cdot 10^5$.

The next line contains a single integer $m$ ($0 \le m \le 10^5$) — the number of banned builds.

Each of the next $m$ lines contains a description of a banned build — a sequence of $n$ integers $b_1, b_2, \dots, b_n$ ($1 \le b_i \le c_i$).

The builds are pairwise distinct, and there's at least one build that's not banned.


-----Output-----

Print the build with the maximum strength that is not banned from the game. If there are multiple builds with maximum strength, print any of them.


-----Examples-----

Input
3
3 1 2 3
2 1 5
3 2 4 6
2
3 2 3
3 2 2
Output
2 2 3
Input
3
3 1 2 3
2 1 5
3 2 4 6
2
3 2 3
2 2 3
Output
1 2 3
Input
3
3 1 2 3
2 1 5
3 2 4 6
2
3 2 3
2 2 3
Output
3 2 2
Input
4
1 10
1 4
1 7
1 3
0
Output
1 1 1 1


-----Note-----

None

Difficulty: HARD
Tags: Graph algorithms

Graph traversal

String algorithms

Sorting

Implementation

Greedy algorithms

Complete search

Data structures
Skill types: Complete search

Sorting

Data structures

Greedy algorithms

Starter code:

Solutions:
from math import *
from collections import *
from functools import *
from bisect import *
from itertools import *
from heapq import *
import sys
inf = float('inf')
ninf = -float('inf')
ip = sys.stdin.readline
alphal = 'abcdefghijklmnopqrstuvwxyz'
alphau = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
mod = 10 ** 9 + 7

def ipl():
	return list(map(int, ip().split()))

def ipn():
	return int(ip())

def ipf():
	return float(ip())

def solve():
	n = ipn()
	a = [ipl() for _ in range(n)]
	b = set([tuple(ipl()) for _ in range(ipn())])
	h = [(-sum((i[-1] for i in a)), tuple((i[0] for i in a)))]
	s = set()
	while h:
		(ss, tu) = heappop(h)
		if tu not in b:
			print(*tu)
			break
		for i in range(n):
			if tu[i] > 1:
				l = list(tu)
				l[i] -= 1
				l = tuple(l)
				if l not in s:
					s.add(l)
					heappush(h, (ss + a[i][tu[i]] - a[i][l[i]], l))
t = 1
for _ in range(t):
	solve()


bn = 10 ** 10
n = int(input())
(c, a) = ([], [])
for _ in range(n):
	aa = list(map(int, input().split()))
	c.append(aa[0])
	aa[0] = -bn
	a.append(aa)
bs = {tuple(map(int, input().split())) for _ in range(int(input()))}
m = 0
mb = []
for b in bs:
	b = list(b)
	s = sum((a[i][b[i]] for i in range(n)))
	for i in range(n):
		s -= a[i][b[i]]
		b[i] -= 1
		s += a[i][b[i]]
		if tuple(b) not in bs and s > m:
			m = s
			mb = tuple(b)
		s -= a[i][b[i]]
		b[i] += 1
		s += a[i][b[i]]
print(*(c if tuple(c) not in bs else mb))


from heapq import heappop, heappush
import sys
input = sys.stdin.readline
n = int(input())
a = [list(map(int, input().split()))[1:] for _ in range(n)]
banned = {tuple(map(int, input().split())) for _ in range(int(input()))}
afegits = set()
pendents = [(-sum((s[-1] for s in a)), tuple((len(s) for s in a)))]
while pendents:
	(value, tp) = heappop(pendents)
	if tp not in banned:
		print(*tp)
		break
	for i in range(n):
		if tp[i] > 1:
			l = list(tp)
			l[i] -= 1
			nou_tp = tuple(l)
			if nou_tp not in afegits:
				afegits.add(nou_tp)
				nou_val = value - a[i][l[i] - 1] + a[i][l[i]]
				heappush(pendents, (nou_val, nou_tp))


import sys
import heapq
input = sys.stdin.readline
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')
if True:
	k = int(input())
	arr = []
	brr = []
	for _ in range(k):
		crr = map(int, input().split())
		arr.append(next(crr))
		brr.append(list(crr))
	arr = tuple((x - 1 for x in arr))
	k = int(input())
	banned = set((tuple((x - 1 for x in map(int, input().split()))) for _ in range(k)))
	n = len(arr)
	queue = [[-sum((row[-1] for row in brr)), 0, tuple(arr)]]
	visited = set()
	idx = 0
	while queue:
		(score, _, comb) = heapq.heappop(queue)
		if comb not in banned:
			comb = [x + 1 for x in comb]
			res = ' '.join((str(x) for x in comb))
			print(res)
			sys.exit()
		comb = list(comb)
		for i in range(n):
			combi = comb[i]
			if combi == 0:
				continue
			diff = brr[i][combi - 1] - brr[i][combi]
			comb[i] -= 1
			score -= diff
			tuple_comb = tuple(comb)
			if tuple_comb in visited:
				comb[i] += 1
				score += diff
				continue
			idx += 1
			heapq.heappush(queue, (score, idx, tuple_comb))
			visited.add(tuple_comb)
			comb[i] += 1
			score += diff


import sys
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input())
A = []
for i in range(n):
	A.append(list(map(int, input().split()))[1:])
m = int(input())
B = set()
for i in range(m):
	x = tuple(map(int, input().split()))
	B.add(hash(x))
X = [0]
ANSX = [[-1]]

def calc(L):
	ANS = 0
	for i in range(n):
		ANS += A[i][L[i] - 1]
	if X[0] < ANS:
		X[0] = ANS
		ANSX[0] = L
L = []
for i in range(n):
	L.append(len(A[i]))
Q = [tuple(L)]
USE = set()
while Q:
	L = Q.pop()
	if hash(L) in USE:
		continue
	USE.add(hash(L))
	if hash(L) in B:
		L = list(L)
		for i in range(n):
			if L[i] >= 2:
				L[i] -= 1
				if not hash(tuple(L)) in USE:
					Q.append(tuple(L))
				L[i] += 1
	else:
		calc(L)
print(*ANSX[0])


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():
	t = tuple([0] * N)
	seen = set()
	seen.add(t)
	hq = []
	l1 = [0] * N
	heapq.heappush(hq, (-sum((A[i][0] for i in range(N))), 0))
	L = []
	L.append(t)
	while hq:
		(s, k) = heapq.heappop(hq)
		t = L[k]
		s = -s
		if t not in ban:
			return [C[i] - t[i] for i in range(N)]
		for i in range(N):
			l1[i] = t[i]
		for i in range(N):
			if l1[i] + 1 < C[i]:
				l1[i] += 1
				t1 = tuple(l1)
				if t1 not in seen:
					seen.add(t1)
					s1 = s - A[i][t[i]] + A[i][t[i] + 1]
					heapq.heappush(hq, (-s1, len(L)))
					L.append(t1)
				l1[i] -= 1
N = int(input())
C = []
A = []
for _ in range(N):
	dat = list(map(int, input().split()))
	C.append(dat[0])
	A.append(list(reversed(dat[1:])))
M = int(input())
ban = set()
for _ in range(M):
	B = list(map(int, input().split()))
	for i in range(N):
		B[i] = C[i] - B[i]
	ban.add(tuple(B))
ans = solve()
print(*ans)


import sys, os
from io import BytesIO, IOBase
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(stdin, stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
mod = pow(10, 9) + 7
mod2 = 998244353

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

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

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

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

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

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

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

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

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

def isprime(x):
	if x <= 1:
		return False
	if x in (2, 3):
		return True
	if x % 2 == 0:
		return False
	for i in range(3, int(sqrt(x)) + 1, 2):
		if x % i == 0:
			return False
	return True
n = iinp()
builds = [lmp()[1:] for i in range(n)]
m = iinp()
wrong = set([tuple(mp()) for i in range(m)])
tup = tuple((len(i) for i in builds))
hp = [(-sum(tup), tup)]
tot = set([tup])
while hp:
	(sm1, tup) = heappop(hp)
	if tup not in wrong:
		print(*tup)
		break
	l = list(tup)
	for i in range(n):
		sm = -sm1
		lis = l.copy()
		if lis[i] == 1:
			continue
		lis[i] -= 1
		sm += builds[i][lis[i] - 1] - builds[i][lis[i]]
		tup = tuple(lis)
		if tup not in tot:
			tot.add(tup)
			heappush(hp, (-sm, tup))


from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
import os, sys
input = lambda : sys.stdin.buffer.readline().rstrip(b'\r\n')

def dbp(*args, **kwargs):
	print(*args, file=sys.stderr, **kwargs)
a_str = lambda : input().decode('ascii')
get_int_list = lambda : [int(x) for x in input().split()]
join_str = lambda l, ch=' ': ch.join((str(x) for x in l))

def do_thing():
	n = int(input())
	items = [get_int_list()[1:] for i in range(n)]
	m = int(input())
	bans = set([tuple(get_int_list()) for i in range(m)])
	tried = set()
	build = [len(il) for il in items]
	tried.add(tuple(build))
	qi = [-sum((items[i][build[i] - 1] for i in range(n))), build]
	q = [qi]
	while q:
		(negpower, build) = heappop(q)
		if tuple(build) in bans:
			for i in range(n):
				if build[i] > 1:
					sb = list(build)
					sp = negpower + items[i][sb[i] - 1]
					sb[i] -= 1
					if tuple(sb) in tried:
						continue
					tried.add(tuple(sb))
					sp -= items[i][sb[i] - 1]
					heappush(q, [sp, sb])
		else:
			break
	return join_str(build)
maxcc = 1
for cc in range(maxcc):
	print(do_thing())


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

def dbg(*args, **kwargs):
	_print('\x1b[95m', end='')
	_print(*args, **kwargs)
	_print('\x1b[0m', end='')

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 inp():
	return sys.stdin.readline().rstrip()

def mpint():
	return map(int, inp().split(' '))

def itg():
	return int(inp())
from heapq import *

def solve():
	n = itg()
	data = []
	sizes = []
	for _ in range(n):
		(size, *nums) = mpint()
		data.append(nums)
		sizes.append(size)
	ban = {tuple([idx - 1 for idx in mpint()]) for _ in range(itg())}
	visited = set()
	build = tuple([size - 1 for size in sizes])
	strength = sum([data[j][idx] for (j, idx) in zip(range(n), build)])
	heap = [(-strength, build)]
	while heap[0][1] in ban:
		(_, build) = heappop(heap)
		for i in range(n):
			if not build[i]:
				continue
			new_build = list(build)
			new_build[i] -= 1
			new_build = tuple(new_build)
			if new_build in visited:
				continue
			visited.add(new_build)
			strength = sum([data[j][idx] for (j, idx) in zip(range(n), new_build)])
			heappush(heap, (-strength, new_build))
	return [idx + 1 for idx in heap[0][1]]

def main():
	print(*solve())
DEBUG = 0
URL = 'https://codeforces.com/contest/1574/problem/D'
if DEBUG == 1:
	import requests
	from ACgenerator.Y_Test_Case_Runner import TestCaseRunner
	runner = TestCaseRunner(main, URL)
	inp = runner.input_stream
	print = runner.output_stream
	runner.checking()
else:
	if DEBUG != 2:
		dbg = lambda *args, **kwargs: ...
		(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	if DEBUG == 3:

		def print(*args, **kwargs):
			_print(*args, **kwargs)
			sys.stdout.flush()
	main()


import heapq
import sys
input = sys.stdin.readline
n = int(input())
a = [[] for _ in range(n)]
for i in range(n):
	a[i] = [int(j) for j in input().split()]
builds = [(-sum((a[i][-1] for i in range(n))), tuple((a[i][0] for i in range(n))))]
m = int(input())
banned = set()
for _ in range(m):
	banned.add(tuple((int(i) for i in input().split())))
done = False
seen = set()
while not done:
	(c_sum, c) = heapq.heappop(builds)
	if c not in banned:
		done = True
	else:
		for i in range(n):
			if c[i] > 1:
				d = tuple((c[j] - 1 if j == i else c[j] for j in range(n)))
				if d not in seen:
					seen.add(d)
					d_sum = sum((a[j][d[j]] for j in range(n)))
					heapq.heappush(builds, (-d_sum, d))
print(*c)


from sys import stdin, stdout
MOD = 1000000007
P = 200001

def get_key(ka):
	k = 0
	for i in range(len(ka)):
		k *= P
		k += ka[i]
		k %= MOD
	return k

def pow(a, b):
	if b == 0:
		return 1
	c = pow(a, b // 2)
	c *= c
	c %= MOD
	if b % 2 == 1:
		c *= a
		c %= MOD
	return c
n = int(stdin.readline())
c_a = []
res = 0
key = 0
r_a = []
for _ in range(n):
	c_a.append(list(map(int, stdin.readline().split())))
	res += c_a[-1][-1]
	key *= P
	key += len(c_a[-1]) - 1
	key %= MOD
	r_a.append(len(c_a[-1]) - 1)
m = int(stdin.readline())
b_a = []
b_s = set()
for _ in range(m):
	b_a.append(list(map(int, stdin.readline().split())))
	b_s.add(get_key(b_a[-1]))
if key in b_s:
	res = 0
	r_a = []
	for b in b_a:
		bsum = 0
		for i in range(n):
			bsum += c_a[i][b[i]]
		bk = get_key(b)
		for i in range(n):
			idx = b[i]
			if idx > 1:
				k = bk - pow(P, n - 1 - i)
				k %= MOD
				if k not in b_s:
					lres = bsum - c_a[i][b[i]] + c_a[i][b[i] - 1]
					if lres > res:
						b[i] -= 1
						r_a = b.copy()
						res = lres
						b[i] += 1
			if idx < len(c_a[i]) - 1:
				k = bk + pow(P, n - 1 - i)
				k %= MOD
				if k not in b_s:
					lres = bsum - c_a[i][b[i]] + c_a[i][b[i] + 1]
					if lres > res:
						b[i] += 1
						r_a = b.copy()
						res = lres
						b[i] -= 1
stdout.write(' '.join(map(str, r_a)))


import sys
from sys import stdin
mod = 300000

def encode(blis):
	ret = 0
	for i in blis:
		ret *= mod
		ret += i
	return ret

def inc(x):
	return x + 1
n = int(stdin.readline())
a = []
for i in range(n):
	ca = list(map(int, stdin.readline().split()))
	a.append(ca[1:])
m = int(stdin.readline())
b = []
s = set()
for i in range(m):
	tb = list(map(int, stdin.readline().split()))
	for j in range(n):
		tb[j] -= 1
	b.append(tb)
	s.add(encode(tb))
tb = []
for i in range(n):
	tb.append(len(a[i]) - 1)
if encode(tb) not in s:
	print(*list(map(inc, tb)))
	sys.exit()
cost = 0
ansb = None
for tb in b:
	for j in range(n):
		tb[j] -= 1
		if tb[j] >= 0 and encode(tb) not in s:
			ncost = 0
			for k in range(n):
				ncost += a[k][tb[k]]
			if ncost > cost:
				cost = ncost
				ansb = tuple(tb)
		tb[j] += 1
print(*list(map(inc, ansb)))


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

class BIT:

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

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

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

class dancinglink:

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

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

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

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

class SparseTable:

	def __init__(self, A, merge_func, ide_ele):
		N = len(A)
		self.merge_func = merge_func
		self.lg = [0] * (N + 1)
		for i in range(2, N + 1):
			self.lg[i] = self.lg[i >> 1] + 1
		self.pow_2 = [pow(2, i) for i in range(20)]
		self.table = [None] * (self.lg[N] + 1)
		st0 = self.table[0] = [a for a in A]
		b = 1
		for i in range(self.lg[N]):
			st0 = self.table[i + 1] = [self.merge_func(u, v) for (u, v) in zip(st0, st0[b:])]
			b <<= 1

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

class BinaryTrie:

	class node:

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

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

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

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

def solveequation(edge, ans, n, m):

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

class slope_trick:

	def __init__(self):
		self.L = [10 ** 17]
		self.R = [10 ** 17]
		self.min_f = 0
		self.x_left = 0
		self.x_right = 0

	def add_right(self, a):
		a -= self.x_left
		l0 = -self.L[0]
		self.min_f = self.min_f + max(0, l0 - a)
		if l0 <= a:
			a += self.x_left
			a -= self.x_right
			heappush(self.R, a)
		else:
			heappush(self.L, -a)
			a = -heappop(self.L)
			a += self.x_left
			a -= self.x_right
			heappush(self.R, a)

	def add_left(self, a):
		a -= self.x_right
		r0 = self.R[0]
		self.min_f = self.min_f + max(0, a - r0)
		if a <= r0:
			a += self.x_right
			a -= self.x_left
			heappush(self.L, -a)
		else:
			heappush(self.R, a)
			a = heappop(self.R)
			a += self.x_right
			a -= self.x_left
			heappush(self.L, -a)

	def add_abs(self, a):
		self.add_left(a)
		self.add_right(a)

	def change_min_slide(self, a, b):
		self.x_left += a
		self.x_right += b

	def get_val(self, x):
		L = [-l + self.x_left for l in self.L]
		L.sort()
		R = [r + self.x_right for r in self.R]
		R.sort()
		res = self.min_f
		if 0 < L[-1]:
			L = L[::-1]
			n = len(L)
			for i in range(n):
				c0 = L[i]
				c1 = L[i + 1]
				if c1 <= x <= c0:
					res += (i + 1) * (c0 - x)
					break
				else:
					res += (i + 1) * (c0 - c1)
			return res
		elif L[-1] <= x <= R[0]:
			return res
		else:
			n = len(R)
			for i in range(n):
				c0 = R[i]
				c1 = R[i + 1]
				if c0 <= x <= c1:
					res += (i + 1) * (x - c0)
					break
				else:
					res += (i + 1) * (c1 - c0)
			return res

class SegmentTree:

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

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

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

	def bisect_l(self, l, r, x):
		l += self.num
		r += self.num
		Lmin = -1
		Rmin = -1
		while l < r:
			if l & 1:
				if self.tree[l] <= x and Lmin == -1:
					Lmin = l
				l += 1
			if r & 1:
				if self.tree[r - 1] <= x:
					Rmin = r - 1
			l >>= 1
			r >>= 1
		if Lmin != -1:
			pos = Lmin
			while pos < self.num:
				if self.tree[2 * pos] <= x:
					pos = 2 * pos
				else:
					pos = 2 * pos + 1
			return pos - self.num
		elif Rmin != -1:
			pos = Rmin
			while pos < self.num:
				if self.tree[2 * pos] <= x:
					pos = 2 * pos
				else:
					pos = 2 * pos + 1
			return pos - self.num
		else:
			return -1
import sys, random, bisect
from collections import deque, defaultdict
from heapq import heapify, heappop, heappush
from itertools import permutations
from math import gcd, log
input = lambda : sys.stdin.buffer.readline()
mi = lambda : map(int, input().split())
li = lambda : list(mi())
N = int(input())
slot = []
for i in range(N):
	(c, *a) = li()
	slot.append(a)
m = int(input())
ban = set()
for i in range(m):
	b = li()
	for j in range(N):
		b[j] -= 1
	ban.add(tuple(b))
score = sum((max(a) for a in slot))
b = [len(a) - 1 for a in slot]
b = tuple(b)
que = [(-score, b, 0)]
while que:
	(score, b, idx) = heappop(que)
	score *= -1
	if b not in ban:
		b = [b[i] + 1 for i in range(N)]
		exit(print(*b))
	for i in range(idx + 1, N):
		tmp_b = [b[j] for j in range(N)]
		tmp_b[i] = b[i] - 1
		if tmp_b[i] == -1:
			continue
		for j in range(i + 1, N):
			tmp_b[j] = len(slot[j]) - 1
		next_score = sum((slot[i][tmp_b[i]] for i in range(N)))
		heappush(que, (-next_score, tuple(tmp_b), i))
	tmp_b = [b[j] for j in range(N)]
	tmp_b[idx] -= 1
	if tmp_b[idx] != -1:
		next_score = sum((slot[i][tmp_b[i]] for i in range(N)))
		heappush(que, (-next_score, tuple(tmp_b), idx))


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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

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

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

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

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

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

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

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

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

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

def solve_a():
	n = get_int()
	for i in range(1, n + 1):
		r = []
		for j in range(i):
			r.append('(')
		for j in range(i):
			r.append(')')
		for j in range(n - i):
			r.append('()')
		print(''.join(r))
	return

def solve_b():
	(a, b, c, m) = get_ints()
	n = a + b + c
	if m > a + b + c - 3:
		return 'NO'
	if max(a, b, c) > n - n // 2:
		if m < 2 * max(a, b, c) - n - 1:
			return 'NO'
	return 'YES'

def solve_c():
	n = get_int()
	a = get_ints()
	m = get_int()
	a.sort()
	S = sum(a)
	for d in range(m):
		(x, y) = get_ints()
		best = float('inf')
		j = bisect.bisect_right(a, x)
		for i in range(max(0, j - 1), min(n, j + 2)):
			h = a[i]
			curr = max(0, x - h) + max(0, y - (S - h))
			best = min(curr, best)
		print(best)
	return

def solve_d():
	n = get_int()
	a = []
	c = []
	for _ in range(n):
		(ci, *aij) = get_ints()
		c.append(ci)
		a.append(aij)
	m = get_int()
	b = [get_ints() for _ in range(m)]
	set_b = set([tuple(x) for x in b])

	def sum_tup(x):
		S = 0
		for (i, j) in enumerate(x):
			S += a[i][j - 1]
		return S
	ans = -1
	res = None
	tup = tuple(c)
	if tuple(c) not in set_b:
		return tup
	for z in b:
		for i in range(n):
			if z[i] == 1:
				continue
			zc = z[:]
			zc[i] -= 1
			tup = tuple(zc)
			S = sum_tup(tup)
			if tup not in set_b and S > ans:
				ans = S
				res = tup
	return res
print(*solve_d())


import sys
input = sys.stdin.readline
N = int(input())
C = []
A = []
for _ in range(N):
	(c, *a) = map(int, input().split())
	C.append(c)
	A.append(a)
bests = [0] * (N + 1)
for i in range(N - 1, -1, -1):
	bests[i] = bests[i + 1] + A[i][-1]
from collections import defaultdict

def Node():
	return defaultdict(Node)
root = Node()
for _ in range(int(input())):
	B = list(map(lambda s: int(s) - 1, input().split()))
	n = root
	for b in B:
		n = n[b]
INF = 10 ** 18

def f(n, depth: int):
	if depth == N:
		return (-INF, ())
	best = -INF
	besti = ()
	for j in range(C[depth] - 1, -1, -1):
		if j in n:
			(rs, ri) = f(n[j], depth + 1)
			ns = A[depth][j] + rs
			if ns > best:
				best = ns
				besti = (j + 1,) + ri
		else:
			ns = A[depth][j] + bests[depth + 1]
			if ns > best:
				best = ns
				besti = (j + 1,) + tuple((C[i] for i in range(depth + 1, N)))
			break
	return (best, besti)
print(*f(root, 0)[1])


from heapq import heapify, heappush, heappop

def solve(items, builds):
	inf = 10 ** 12
	sol = [0] * len(items)
	scores = []
	heapify(scores)
	max_score = -sum([items[i][sol[i]][1] for i in range(len(items))])
	heappush(scores, max_score)
	score_to_build = {}
	score_to_build[max_score] = set([' '.join([str(x) for x in sol])])
	for _ in range(len(builds) + 1):
		cur_score = heappop(scores)
		while len(score_to_build[cur_score]) > 0:
			b = [int(x) for x in score_to_build[cur_score].pop().split(' ')]
			build = get_build(items, b)
			if build not in builds:
				return build
			for (i, x) in enumerate(b):
				new_sol = b[:]
				if x < len(items[i]) - 1:
					new_sol[i] = x + 1
					this_score = cur_score - (items[i][x + 1][0] - items[i][x][0])
					if this_score not in score_to_build:
						score_to_build[this_score] = set()
						heappush(scores, this_score)
					new_b = ' '.join([str(x) for x in new_sol])
					score_to_build[this_score].add(new_b)

def get_build(items, sol):
	build = ' '.join([str(items[i][sol[i]][1]) for i in range(len(items))])
	return build
import os
import io
import time
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input().decode().strip())
items = []
for i in range(n):
	ci = [int(x) for x in input().decode().strip().split(' ')]
	ci.pop(0)
	ci = [(ci[j], j + 1) for j in range(len(ci))]
	ci.sort(reverse=True)
	items.append(ci)
m = int(input().decode().strip())
builds = set()
for i in range(m):
	b = input().decode().strip()
	builds.add(b)
a = solve(items, builds)
print(a)


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
from heapq import heappop, heappush
for _ in range(int(input()) if not True else 1):
	n = int(input())
	a = []
	cur = []
	total = 0
	for i in range(n):
		b = [0] + list(map(int, input().split()))[1:]
		total += b[-1]
		a += [b]
		cur += [len(b) - 1]
	queue = []
	heappush(queue, (-total, list(cur)))
	st = set()
	considered = set()
	for __ in range(int(input())):
		x = list(map(int, input().split()))
		st.add(str(x))
	while queue:
		(total, b) = heappop(queue)
		if str(b) not in st:
			print(*b)
			quit()
		for i in range(n):
			if b[i] > 1:
				b[i] -= 1
				if str(b) not in considered:
					considered.add(str(b))
					heappush(queue, (total + a[i][b[i] + 1] - a[i][b[i]], list(b)))
				b[i] += 1


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

def solve():
	n = int(input())
	vals = [[] for i in range(n)]
	for i in range(n):
		vals[i] = [int(x) for x in input().split()]
	m = int(input())
	banned = set()
	vis = set()
	for i in range(m):
		banned.add(tuple([int(x) for x in input().split()]))
	val = 0
	ideal = []
	for i in range(n):
		val += vals[i][-1]
		ideal.append(vals[i][0])
	all = [(-val, tuple(ideal))]
	heapq.heapify(all)
	while len(all):
		top = heapq.heappop(all)
		ss = -top[0]
		lis = top[1]
		if lis not in banned:
			print(*lis)
			break
		for i in range(n):
			if lis[i] - 1 >= 1:
				temp = list(lis)
				temp[i] -= 1
				temp = tuple(temp)
				if temp in vis:
					continue
				heapq.heappush(all, (-(ss - vals[i][lis[i]] + vals[i][lis[i] - 1]), temp))
				vis.add(temp)

def main():
	t = 1
	for _ in range(t):
		solve()
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 naiveSolve():
	return

def solve():
	return

def main():

	def calculateTotal(build):
		ans = 0
		for i in range(n):
			ans += strength[i][build[i] - 1]
		return ans
	n = int(input())
	strength = [[] for _ in range(n)]
	for i in range(n):
		temp = readIntArr()
		temp.pop(0)
		strength[i] = temp
	bannedBuilds = set()
	bannedArr = []
	m = int(input())
	for _ in range(m):
		build = readIntArr()
		bannedArr.append(build)
		bannedBuilds.add(hash(tuple(build)))
	initialBuild = [len(x) for x in strength]
	if hash(tuple(initialBuild)) not in bannedBuilds:
		oneLineArrayPrint(initialBuild)
		return
	bestScore = 0
	bestAns = []
	for build in bannedArr:
		for i in range(n):
			if build[i] - 1 >= 1:
				build[i] -= 1
				if hash(tuple(build)) not in bannedBuilds:
					score = calculateTotal(build)
					if score > bestScore:
						bestScore = score
						bestAns = build.copy()
				build[i] += 1
	oneLineArrayPrint(bestAns)
	return
import sys
input = sys.stdin.buffer.readline

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

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

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

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

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

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

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


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

def main(t):
	n = int(input())
	grid = []
	minimum = 0
	for i in range(n):
		temp = list(map(int, input().split()))
		grid.append([])
		for i in range(temp[0], 0, -1):
			grid[-1].append(-temp[i])
		minimum += grid[-1][0]
	banned = {}
	visited = {}
	m = int(input())
	for i in range(m):
		temp = list(map(int, input().split()))
		for j in range(n):
			temp[j] = len(grid[j]) - temp[j]
		banned[tuple(temp)] = 1
	heap = []
	heapq.heappush(heap, [minimum] + [0] * n)
	visited[tuple([0] * n)] = 1
	while heap:
		indexes = heapq.heappop(heap)
		if tuple(indexes[1:]) not in banned:
			ans = indexes[1:]
			break
		for i in range(n):
			indexes[i + 1] += 1
			if indexes[i + 1] == len(grid[i]):
				indexes[i + 1] -= 1
				continue
			if tuple(indexes[1:]) in visited:
				indexes[i + 1] -= 1
				continue
			visited[tuple(indexes[1:])] = 1
			newindex = indexes[i + 1]
			diff = grid[i][newindex] - grid[i][newindex - 1]
			indexes[0] += diff
			heapq.heappush(heap, list(indexes))
			indexes[i + 1] -= 1
			indexes[0] -= diff
	for i in range(n):
		ans[i] = len(grid[i]) - ans[i]
	print(' '.join(map(str, ans)))
T = 1
t = 1
while t <= T:
	main(t)
	t += 1


N = int(input())
start = []
cur = 0
arr = []
for _ in range(N):
	sub = [int(x) for x in input().split(' ')[1:]]
	cur += sub[-1]
	start.append(len(sub) - 1)
	arr.append(sub)
ban = set([])
M = int(input())
for _ in range(M):
	sub = tuple([int(x) - 1 for x in input().split(' ')])
	ban.add(sub)
import heapq as hq
start = tuple(start)
queue = [(-cur, start)]
visited = set([start])
while queue:
	(q, lis) = hq.heappop(queue)
	q = -q
	if lis not in ban:
		print(' '.join([str(pick + 1) for pick in lis]))
		break
	for i in range(N):
		index = lis[i]
		if index > 0:
			state = list(lis)
			state[i] = index - 1
			state = tuple(state)
			if state not in visited:
				cs = q - arr[i][index] + arr[i][index - 1]
				hq.heappush(queue, (-cs, state))
				visited.add(state)


import heapq
import sys
read = lambda : sys.stdin.readline()
from heapq import heapify, heappop, heappush
from bisect import bisect_left
items = [list(map(int, read().split()))[1:] for _ in range(int(read()))]
bannedBuilds = {tuple(map(int, read().split())) for _ in range(int(read()))}
visited = set([])
heap = [(-sum((s[-1] for s in items)), list((len(s) for s in items)))]
while heap:
	(value, build) = heappop(heap)
	if tuple(build) not in bannedBuilds:
		print(*build)
		exit(0)
	for i in range(len(items)):
		if build[i] > 1:
			new_build = build.copy()
			new_build[i] -= 1
			if tuple(new_build) not in visited:
				visited.add(tuple(new_build))
				new_val = value - items[i][new_build[i] - 1] + items[i][new_build[i]]
				heappush(heap, (new_val, new_build))


import sys
input = sys.stdin.readline

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

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

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

def input_int_gen():
	return map(int, input().split())
from heapq import heapify, heappop, heappush, heapreplace
tests = 1
for _ in range(tests):
	n = inp()
	avail = []
	items_count = []
	banned = set()
	for _ in range(n):
		c = input_list()
		m = c[0]
		del c[0]
		avail.append(c)
		items_count.append(m)
	m = inp()
	for _ in range(m):
		banned.add(tuple(input_list()))

	def strength(idyes):
		return sum((avail[x][idyes[x] - 1] for x in range(n)))
	first = tuple(items_count)
	nexts = [(-strength(first), first)]
	visited = {first}
	maxi = 0
	while nexts:
		(strn, idyes) = heappop(nexts)
		strn = -strn
		if idyes not in banned:
			print(' '.join((str(y) for y in idyes)))
			break
		else:
			idyes = list(idyes)
			for i in range(n):
				if idyes[i] != 1:
					idyes[i] -= 1
					kk = tuple(idyes)
					if kk not in visited:
						visited.add(kk)
						strn_new = strn - avail[i][idyes[i]] + avail[i][idyes[i] - 1]
						if strn_new > maxi:
							heappush(nexts, (-strn_new, kk))
							if kk not in banned:
								maxi = strn_new
					idyes[i] += 1


import decimal
import math
import os
import sys
from collections import Counter
from io import BytesIO, IOBase
import bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

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

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

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

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

def ipn():
	return int(input())

def main():
	n = ipn()
	arr = [list_get() for i in range(n)]
	m = ipn()
	block = list((tuple(list_get()) for i in range(m)))
	s = set(block)
	ma = 0
	ans = []
	if tuple((len(a) - 1 for a in arr)) not in s:
		print(*[len(a) - 1 for a in arr])
		exit()
	for a1 in block:
		a = list(a1)
		for i in range(n):
			if a[i] > 1:
				a[i] -= 1
				if tuple(a) not in s:
					k = sum((arr[i][a[i]] for i in range(n)))
					if k > ma:
						ma = k
						ans = a[:]
				a[i] += 1
	print(*ans)
	return
main()


import heapq
import sys
input = sys.stdin.buffer.readline
n = int(input())
c = [list(map(int, input().split()))[1:] for i in range(n)]
m = int(input())
b = [list(map(int, input().split())) for i in range(m)]
set_ = set([])
for bb in b:
	set_.add(tuple(bb))
sum_ = 0
for i in range(n):
	sum_ += c[i][-1]
ans = -1
res = None
tup = tuple([len(c[i]) for i in range(n)])
if tup not in set_:
	ans = sum_
	res = tup
for idxs in b:
	for i in range(n):
		if idxs[i] == 1:
			continue
		new_idxs = idxs[:]
		new_idxs[i] -= 1
		tup = tuple(new_idxs)
		sum_ = 0
		for j in range(n):
			sum_ += c[j][tup[j] - 1]
		if tup not in set_ and sum_ > ans:
			ans = sum_
			res = tup
print(*res)


from sys import stdin, stdout

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

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

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

def read_int():
	return int(input())
from heapq import *

def neighbours(tup):
	ret = []
	for i in range(len(tup)):
		if tup[i] > 0:
			c = list(tup)
			c[i] -= 1
			ret += [c]
	return ret

def score2(elems, tup):
	ret = 0
	for (idx, elem) in zip(tup, elems):
		ret -= elem[idx]
	return ret

def combinations(elems):

	def score(tup):
		return score2(elems, tup)
	start = tuple((len(x) - 1 for x in elems))
	yield start
	candidates = []
	for tup in neighbours(start):
		heappush(candidates, [score(tup)] + tup)
	yielded = set()
	yielded.add(start)
	while len(candidates):
		tup = heappop(candidates)[1:]
		yield tup
		yielded.add(tuple(tup))
		for n in neighbours(tup):
			if tuple(n) in yielded:
				continue
			heappush(candidates, [score(n)] + n)

def ans(equipments, banned):
	start = tuple((len(x) - 1 for x in equipments))
	if start not in banned:
		return start
	candidates = []
	for tup in banned:
		for n in neighbours(tup):
			if tuple(n) not in banned:
				candidates += [(-score2(equipments, n), n)]
	return max(candidates)[1]
if False:
	r = list(range(100))
	for (i, c) in enumerate(combinations([r, r, r, r, r])):
		if i == 10 ** 5:
			print(c)
			break
else:
	equipments = []
	banned = set()
	for _ in range(read_int()):
		equipments += [read_int_list()[1:]]
	for _ in range(read_int()):
		b = read_int_list()
		b = [i - 1 for i in b]
		banned.add(tuple(b))
	r = ans(equipments, banned)
	r = [x + 1 for x in r]
	print(*r)


import sys
import heapq
input = sys.stdin.readline

def main():
	pq = []
	n = int(input())
	g = [[] for _ in range(n)]
	big = [0] * n
	bigs = 0
	for i in range(n):
		ar = list(map(int, input().split()))
		g[i] = ar[1:]
		big[i] = ar[0]
		bigs += ar[-1]
	m = int(input())
	banned = set()
	for _ in range(m):
		banned.add(tuple(map(int, input().split())))
	visited = set()
	pq.append((-bigs, tuple(big)))
	for x in range(m + 1):
		cand = heapq.heappop(pq)
		tup = cand[1]
		if tup not in banned:
			print(*tup)
			sys.exit()
		ltup = list(tup)
		stup = -cand[0]
		for i in range(n):
			if ltup[i] > 1:
				ltup[i] -= 1
				newtup = tuple(ltup)
				if newtup in visited:
					pass
				else:
					visited.add(newtup)
					newstup = stup + g[i][ltup[i] - 1] - g[i][ltup[i]]
					heapq.heappush(pq, (-newstup, newtup))
				ltup[i] += 1
main()


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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
n = int(input())
a = [None] * n
for i in range(n):
	a[i] = list(map(int, input().split()))
m = int(input())
b = [None] * m
for i in range(m):
	b[i] = tuple(map(int, input().split()))
s = set(b)
if tuple((a[i][0] for i in range(n))) not in s:
	print(*tuple((a[i][0] for i in range(n))))
	exit()
mx = 0
ans = None
for choice in b:
	choice = list(choice)
	for i in range(n):
		if choice[i] > 1:
			choice[i] -= 1
			if tuple(choice) not in s:
				case = sum((a[i0][choice[i0]] for i0 in range(n)))
				if case > mx:
					mx = case
					ans = choice[:]
			choice[i] += 1
print(*ans)


import sys
input = sys.stdin.readline
from collections import *
from heapq import *

def tohash(idx):
	res = 0
	for i in range(n):
		res = res * pow(10, le[i]) + idx[i]
	return res

def decode(has):
	res = []
	for i in range(n - 1, -1, -1):
		(s, a) = divmod(has, pow(10, le[i]))
		res.append(a)
		has = s
	return res[::-1]
n = int(input())
A = []
for _ in range(n):
	a = list(map(int, input().split()))
	A.append(a[1:])
le = [len(str(len(Ai))) for Ai in A]
ban = defaultdict(bool)
m = int(input())
for _ in range(m):
	b = list(map(int, input().split()))
	b = list(map(lambda x: x - 1, b))
	ban[tohash(b)] = True
pq = []
v = sum((a[-1] for a in A))
h = tohash([len(a) - 1 for a in A])
heappush(pq, (-v, h))
already = defaultdict(bool)
already[h] = True
while pq:
	(v, h) = heappop(pq)
	v *= -1
	if not ban[h]:
		ans = decode(h)
		ans = list(map(lambda x: x + 1, ans))
		print(*ans)
		exit()
	idx = decode(h)
	for i in range(n):
		if idx[i] == 0:
			continue
		next_idx = idx[:]
		next_idx[i] -= 1
		next_h = tohash(next_idx)
		if already[next_h]:
			continue
		heappush(pq, (-(v - A[i][idx[i]] + A[i][idx[i] - 1]), next_h))
		already[next_h] = True


n = int(input())
arr = [list(map(int, input().split())) for i in range(n)]
m = int(input())
block = list((tuple(map(int, input().split())) for i in range(m)))
s = set(block)
ma = 0
ans = []
if tuple((len(a) - 1 for a in arr)) not in s:
	print(*[len(a) - 1 for a in arr])
	exit()
for a1 in block:
	a = list(a1)
	for i in range(n):
		if a[i] > 1:
			a[i] -= 1
			if tuple(a) not in s:
				k = sum((arr[i][a[i]] for i in range(n)))
				if k > ma:
					ma = k
					ans = a[:]
			a[i] += 1
print(*ans)


import sys
import io
from io import BytesIO, IOBase
import os
import heapq
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')
INF = 10 ** 10

def solve():
	t = tuple([0] * N)
	seen = set()
	seen.add(t)
	hq = []
	l1 = [0] * N
	heapq.heappush(hq, (-sum((A[i][0] for i in range(N))), 0))
	L = []
	L.append(t)
	while hq:
		(s, k) = heapq.heappop(hq)
		t = L[k]
		s = -s
		if t not in ban:
			return [C[i] - t[i] for i in range(N)]
		for i in range(N):
			l1[i] = t[i]
		for i in range(N):
			if l1[i] + 1 < C[i]:
				l1[i] += 1
				t1 = tuple(l1)
				if t1 not in seen:
					seen.add(t1)
					s1 = s - A[i][t[i]] + A[i][t[i] + 1]
					heapq.heappush(hq, (-s1, len(L)))
					L.append(t1)
				l1[i] -= 1
N = int(input())
C = []
A = []
for _ in range(N):
	dat = list(map(int, input().split()))
	C.append(dat[0])
	A.append(list(reversed(dat[1:])))
M = int(input())
ban = set()
for _ in range(M):
	B = list(map(int, input().split()))
	for i in range(N):
		B[i] = C[i] - B[i]
	ban.add(tuple(B))
ans = solve()
print(*ans)


import math
import random
import sys
import heapq

def main(n, arr, invalid, m):
	invalid = set(invalid)
	curr = tuple([len(arr[i]) - 1 for i in range(len(arr))])
	s = sum([arr[i][-1] for i in range(len(arr))])
	best = [(-1 * s, curr)]
	heapq.heapify(best)
	(s, curr) = heapq.heappop(best)
	seen = set()
	while m != 0:
		if curr not in invalid:
			break
		for i in range(len(curr)):
			l = list(curr)
			if l[i] != 0:
				l[i] -= 1
				t_l = tuple(l)
				if t_l not in seen:
					next_val = -1 * s
					next_val -= arr[i][l[i] + 1]
					next_val += arr[i][l[i]]
					next_val *= -1
					heapq.heappush(best, (next_val, t_l))
					seen.add(t_l)
		(s, curr) = heapq.heappop(best)
		m -= 1
	curr = [curr[i] + 1 for i in range(len(curr))]
	print(*curr)
	return
n = int(input())
arr = []
for i in range(n):
	temp = list(map(int, input().split()))
	temp.pop(0)
	arr.append(temp)
m = int(input())
arr2 = []
for i in range(m):
	temp = list(map(int, input().split()))
	temp = [temp[i] - 1 for i in range(len(temp))]
	temp = tuple(temp)
	arr2.append(temp)
main(n, arr, arr2, m)


import sys
from math import factorial, gcd
from collections import Counter, deque, defaultdict
from bisect import bisect_left, bisect_right
from heapq import heappop, heappush, heapify, nlargest, nsmallest
from itertools import groupby
from copy import deepcopy
MOD = 10 ** 9 + 7
INF = float('inf')
rl = lambda : list(map(int, sys.stdin.readline().split()))
rs = lambda : sys.stdin.readline().strip()
n = int(input())
items = [rl() for _ in range(n)]
m = int(input())
banned = set([tuple(rl()) for _ in range(m)])
heap = [(-sum((a[-1] for a in items)), tuple((len(a) - 1 for a in items)))]
seen = set()
while heap:
	(val, tp) = heappop(heap)
	if tp not in banned:
		print(*tp)
		break
	for i in range(n):
		if tp[i] > 1:
			l = list(tp)
			l[i] -= 1
			l = tuple(l)
			if l not in seen:
				seen.add(l)
				newVal = val - items[i][l[i]] + items[i][tp[i]]
				heappush(heap, (newVal, l))


import sys
input = sys.stdin.readline
from collections import defaultdict, deque
from bisect import bisect_left

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

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

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

def totstr(li, temp):
	s = 0
	n = len(temp)
	for i in range(1, n + 1):
		s += li[i][temp[i - 1]]
	return s
n = ii()
li = [()]
temp = []
dd = defaultdict(lambda : 0)
for i in range(n):
	li.append(il())
	temp.append(li[-1][0])
m = ii()
for i in range(m):
	dd[il()] = -1
mx = 0
q = deque()
lq = 0
if dd[tuple(temp)] != -1:
	ans = tuple(temp)
else:
	q.append(tuple(temp))
	dd[tuple(temp)] = -2
	lq = 1
while lq > 0:
	curr = q.popleft()
	lq -= 1
	if dd[curr] < 0:
		curr = list(curr)
		for i in range(n):
			if curr[i] > 1:
				curr[i] -= 1
				cr = tuple(curr)
				if dd[cr] == 0:
					q.append(cr)
					dd[cr] = 1
					lq += 1
				elif dd[cr] == -1:
					q.append(cr)
					dd[cr] = -2
					lq += 1
				curr[i] += 1
	else:
		x = totstr(li, curr)
		if x > mx:
			mx = x
			ans = curr
print(*ans)