Chef organised a chess tournament, which spanned over $M$ months. There were $N$ players, and player $i$ was rated $R_i$ before the start of the tournament. To see the progress of the players, he noted their rating changes at the end of each month.
After the tournament, FIDE asked Chef to find the number of players whose peak rating and peak ranking did not occur in the same month. In other words, Chef was asked to find the ratings and ranking of each player after each of the $M$ months. Then, using this data, he should find the number of players, such that the month in which they achieved their highest rating over all the months, was different from the month in which they achieved their best rank (based on ratings), over all the months. Note that we do not consider the initial rating/ranking, but only the rating and rankings after each of the $M$ months. 
For a particular player, if there are multiple peak rating or peak ranking months, Chef was to consider the earliest of them. If multiple players had the same rating at the end of some month, they were to be given the same rank. For example, if there were $5$ players, and their ratings at the end of some month were $(2600$, $2590$, $2600$, $2600$ and $2590)$, players $1$, $3$ and $4$ were to be given the first rank, while players $2$ and $5$ should be given the fourth rank.
As Chef hates statistics, he asks you, his friend, to help him find this. Can you help Chef?

-----Input:-----
- The first line contains an integer $T$, the number of test cases.
- The first line of each test case contains two space-separated integers $N$ and $M$, the number of players and the number of months that the tournament spanned over.
- The second line of each test case contains $N$ space-separated integers, $R_1, R_2, \ldots, R_N$ denoting the initial ratings of the players, i.e., their ratings before the start of the tournament.
- The next $N$ lines each contain $M$ space-separated integers. The $j^{th}$ integer of the $i^{th}$ line, $C_{i,j}$ denotes the rating change of the $i^{th}$ player after the $j^{th}$ month.

-----Output:-----
For each test case, print the number of players whose peak ratings did not occur in the same month as their peak ranking, in a new line.

-----Constraints-----
- $1 \le T \le 10$
- $1 \le N,M \le 500$
- $1800 \le R_i \le 2800$
- $-20 \le C_{i,j} \le 20$

-----Subtasks-----
- 30 points : $1 \leq N,M \leq 50$
- 70 points : Original constraints.

-----Sample Input:-----
2
3 3
2500 2500 2520
10 -5 -20
10 15 20
-15 17 13
2 3
2125 2098
-20 10 -10
10 10 -20

-----Sample Output:-----
2
2

-----Explanation:-----
Test case 1:
- 
The ratings for player $1$ after each month are: $(2510$, $2505$ and $2485)$, while his rankings are first, third and third, respectively. Thus, his best rating and best ranking occur after the same month, i.e., after the first month.
- 
The ratings for player $2$ after each month are: $(2510$, $2525$ and $2545)$, while his rankings are first, first and first, respectively. His best rating occurs after the third month, while his best ranking occurs after the first month (we consider the first month even though his peak ranking is over all the months, because we consider only the earliest month where he attains the peak ranking).
- 
The ratings for player $3$ after each month are: $(2505$, $2522$ and $2535)$, while his rankings are third, second and second, respectively. His best rating occurs after the third month, while his best ranking occurs after the second month.
So there are two players ($2$ and $3$), whose peak ratings did not occur in the same month as their peak ranking, and hence the answer is 2.
Test case 2:
- 
The ratings for player $1$ after each month are: $(2105$, $2115$ and $2105)$, while his rankings are second, second and first, respectively. Best rating is after second month, but best ranking is after third month.
- 
The ratings for player $2$ after each month are: $(2108$, $2118$ and $2098)$, while his rankings are first, first and second, respectively. Best rating is after second month, but best ranking is after first month.
So there are two players ($1$ and $2$), whose peak ratings did not occur in the same month as their peak ranking, and hence the answer is 2.

Difficulty: MEDIUM_HARD

Solutions:
import math
try:
	for _ in range(int(input())):
		(n, m) = list(map(int, input().split()))
		p = list(map(int, input().split()))
		points = [[0 for i in range(m + 1)] for i in range(n)]
		for i in range(n):
			points[i][0] = p[i]
		mx = [[0, 0] for i in range(n)]
		arr = [[3000, 0] for i in range(n)]
		for i in range(n):
			lst = list(map(int, input().split()))
			for j in range(1, m + 1):
				points[i][j] = points[i][j - 1] + lst[j - 1]
			points[i] = points[i][1:]
			arr[i][1] = points[i][0]
		for i in range(m):
			rank = []
			for j in range(n):
				rank.append(points[j][i])
			rank = sorted(rank, reverse=True)
			for j in range(n):
				pos = rank.index(points[j][i])
				if pos < arr[j][0]:
					mx[j][1] = i
					arr[j][0] = pos
			for j in range(n):
				if points[j][i] > arr[j][1]:
					mx[j][0] = i
					arr[j][1] = points[j][i]
		ans = 0
		for x in mx:
			if x[0] != x[1]:
				ans += 1
		print(ans)
except EOFError as e:
	pass


import bisect
t = int(input())
while t > 0:
	(n, m) = input().split()
	n = int(n)
	m = int(m)
	r = [int(x) for x in input().split()]
	rat = [[0 for _ in range(n)] for j in range(m)]
	for i in range(n):
		x = [int(x) for x in input().split()]
		rat[0][i] = r[i] + x[0]
		for j in range(1, m):
			rat[j][i] = rat[j - 1][i] + x[j]
	y = []
	best_rat = [0 for i in range(n)]
	best_rank = [n + 1 for i in range(n)]
	best_ind = [0 for i in range(n)]
	for i in range(m):
		y = []
		z = []
		for j in range(n):
			if rat[i][j] > rat[best_rat[j]][j]:
				best_rat[j] = i
			y.append((-rat[i][j], j))
			z.append(-rat[i][j])
		y.sort()
		z.sort()
		for j in range(n):
			if bisect.bisect_left(z, y[j][0]) < best_rank[y[j][1]]:
				best_rank[y[j][1]] = bisect.bisect_left(z, y[j][0])
				best_ind[y[j][1]] = i
	ans = 0
	for i in range(n):
		if best_rat[i] != best_ind[i]:
			ans += 1
	print(ans)
	t -= 1


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	r = list(map(int, input().split()))
	rate = list()
	for i in range(n):
		rating = r[i]
		c = list(map(int, input().split()))
		temp = list()
		for j in c:
			rating += j
			temp.append(rating)
		rate.append(temp)
	ratings = list((-1 for i in range(n)))
	rankings = list((-1 for i in range(n)))
	bestRatings = list((-1 for i in range(n)))
	bestRankings = list((1000 for i in range(n)))
	for i in range(m):
		temp = list()
		for j in range(n):
			rating = rate[j][i]
			temp.append(rating)
		temp.sort(reverse=True)
		tempDict = dict()
		for x in range(n):
			if temp[x] not in tempDict.keys():
				tempDict[temp[x]] = x
		for j in range(n):
			if rate[j][i] > bestRatings[j]:
				bestRatings[j] = rate[j][i]
				ratings[j] = i
			if tempDict[rate[j][i]] < bestRankings[j]:
				bestRankings[j] = temp.index(rate[j][i])
				rankings[j] = i
	count = 0
	for i in range(n):
		if rankings[i] != ratings[i]:
			count += 1
	print(count)


def number_of_players_who_peak_ratings_not_same_as_peak_ranking(ratings, no_of_months, no_of_players):
	max_rating = [max(range(no_of_months), key=lambda i: (ratings[player][i], -i)) for player in range(no_of_players)]
	max_ranking = compute_max_ranking(ratings, no_of_players, no_of_months)
	return sum((max_rating[player] != max_ranking[player] for player in range(no_of_players)))

def compute_max_ranking(ratings, no_of_players, no_of_months):
	ratings_by_month = list(zip(*ratings))
	rankings = []
	for month in range(no_of_months):
		rankings.append(rank_players(list(range(no_of_players)), ratings_by_month[month]))
	return list((min(range(no_of_months), key=lambda i: (rankings[i][player], i)) for player in range(no_of_players)))

def rank_players(ids, scores):
	ids = sorted(ids, key=lambda i: scores[i], reverse=True)
	ans = [0] * len(scores)
	previous = scores[ids[0]]
	latest_ranking = 0
	for (i, player) in enumerate(ids):
		if previous != scores[player]:
			ans[player] = i
			latest_ranking = i
		else:
			ans[player] = latest_ranking
		previous = scores[player]
	return ans
T = int(input())
for _ in range(T):
	(no_of_players, no_of_months) = map(int, input().split())
	ratings = []
	initial_ratings = list(map(int, input().split()))
	for player in range(no_of_players):
		change_in_ratings = list(map(int, input().split()))
		current = initial_ratings[player]
		player_ratings = []
		for change in change_in_ratings:
			player_ratings.append(current + change)
			current += change
		ratings.append(player_ratings)
	print(number_of_players_who_peak_ratings_not_same_as_peak_ranking(ratings=ratings, no_of_months=no_of_months, no_of_players=no_of_players))


t = int(input())
for i in range(0, t):
	ans = 0
	nm = input().split()
	(n, m) = (int(nm[0]), int(nm[1]))
	(rows, cols) = (m, n)
	a = [[(0, 0) for i in range(cols)] for j in range(rows)]
	max_rating_month = [0 for i in range(cols)]
	curr_rating = list(map(int, input().strip().split()))[:n]
	for i in range(0, n):
		line = list(map(int, input().strip().split()))[:m]
		max = 0
		for j in range(0, m):
			curr_rating[i] += line[j]
			if curr_rating[i] > max:
				max_rating_month[i] = j
				max = curr_rating[i]
			a[j][i] = (i, curr_rating[i])
	ranking = [[0 for i in range(n)] for j in range(m)]
	for i in range(m):
		a[i].sort(key=lambda x: -x[1])
		rank = 1
		ranking[i][a[i][0][0]] = 1
		for j in range(1, n):
			if a[i][j - 1][1] == a[i][j][1]:
				ranking[i][a[i][j][0]] = rank
			else:
				ranking[i][a[i][j][0]] = j + 1
				rank = j + 1
	for i in range(n):
		best_rank = 501
		best_rank_month = 0
		for j in range(m):
			if ranking[j][i] < best_rank:
				best_rank = ranking[j][i]
				best_rank_month = j
		if best_rank_month != max_rating_month[i]:
			ans += 1
	print(ans)


import sys
t = int(input())
while t:
	(n, m) = map(int, sys.stdin.readline().split())
	r = list(map(int, sys.stdin.readline().split()))
	c = []
	for i in range(n):
		b = list(map(int, sys.stdin.readline().split()))
		c.append(b[:])
	for i in range(n):
		a = r[i]
		for j in range(m):
			c[i][j] += a
			a = c[i][j]
	k = []
	for i in range(n):
		u = 0
		p = -1
		for j in range(m):
			if u < c[i][j]:
				u = c[i][j]
				p = j
		k.append(p)
	for j in range(m):
		d = []
		for i in range(n):
			d.append(c[i][j])
		d.sort(reverse=True)
		b = []
		c1 = 1
		m1 = d[0]
		for i in range(len(d)):
			if m1 == d[i]:
				b.append(c1)
			else:
				c1 = i + 1
				m1 = d[i]
				b.append(c1)
		p = {}
		for i in range(n):
			p[d[i]] = b[i]
		for i in range(n):
			l = c[i][j]
			c[i][j] = p[l]
	v = []
	for i in range(n):
		u = 10000
		p = -1
		for j in range(m):
			if u > c[i][j]:
				u = c[i][j]
				p = j
		v.append(p)
	c = 0
	for i in range(len(v)):
		if v[i] != k[i]:
			c += 1
	print(c)
	t -= 1


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	rating = list(map(int, input().split()))
	arr = []
	for i in range(n):
		arr.append(list(map(int, input().split())))
	minrank = [float('inf')] * n
	index2 = [0] * n
	bestscore = [float('-inf')] * n
	index1 = [0] * n
	for i in range(m):
		for j in range(n):
			rating[j] += arr[j][i]
		st = sorted(rating, reverse=True)
		f = []
		dindex = dict()
		for j in range(len(st)):
			if st[j] in dindex:
				continue
			dindex[st[j]] = j
		for j in range(len(rating)):
			f.append(dindex[rating[j]])
		for ii in range(len(f)):
			if minrank[ii] > f[ii]:
				minrank[ii] = f[ii]
				index1[ii] = i
		for ii in range(len(rating)):
			if bestscore[ii] < rating[ii]:
				bestscore[ii] = rating[ii]
				index2[ii] = i
	count = 0
	for (i, j) in zip(index2, index1):
		if i != j:
			count += 1
	print(count)


def check(month_rat, month_rank, n):
	c = 0
	for i in range(1, n + 1):
		if month_rat[i] != month_rank[i]:
			c += 1
	return c

def ranking(r, m_rank, month_rank, m, n):
	for i in range(m):
		rank = 1
		c = 0
		for val in r[i]:
			rank += c
			c = 0
			for j in range(n):
				if val == d[i + 1, j + 1]:
					if m_rank[j + 1] > rank:
						m_rank[j + 1] = rank
						month_rank[j + 1] = i + 1
					c += 1
for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	r = list(map(int, input().split()))
	c = [list(map(int, input().split())) for i in range(n)]
	rating = []
	d = {}
	m_rank = {}
	m_rat = {}
	month_rank = {}
	month_rat = {}
	f = 1
	for i in range(m):
		x = []
		for j in range(n):
			if i == 0:
				d[i + 1, j + 1] = r[j] + c[j][i]
				x.append(d[i + 1, j + 1])
			else:
				d[i + 1, j + 1] = d[i, j + 1] + c[j][i]
				x.append(d[i + 1, j + 1])
			if f:
				m_rank[j + 1] = 501
				m_rat[j + 1] = d[i + 1, j + 1]
				month_rat[j + 1] = i + 1
			elif m_rat[j + 1] < d[i + 1, j + 1]:
				m_rat[j + 1] = d[i + 1, j + 1]
				month_rat[j + 1] = i + 1
		x = list(set(x))
		x.sort()
		rating.append(x[::-1])
		f = 0
	ranking(rating, m_rank, month_rank, m, n)
	count = check(month_rat, month_rank, n)
	print(count)


def getRanking(ratingList, n, m):
	rank = []
	array2d = [[None for i in range(n)] for j in range(m)]
	for i in range(m):
		helper2d = [[None for i in range(2)] for j in range(n)]
		for j in range(n):
			helper2d[j][0] = j + 1
			helper2d[j][1] = ratingList[j][i]
		helper2d = sorted(helper2d, reverse=True, key=lambda x: x[1])
		arr = [x for x in range(1, n + 1)]
		for k in range(1, n):
			if helper2d[k][1] == helper2d[k - 1][1]:
				arr[k] = arr[k - 1]
		for l in range(n):
			array2d[i][helper2d[l][0] - 1] = arr[l]
	for l in range(n):
		minimum = float('inf')
		minimumIndex = None
		for o in range(m):
			if minimum > array2d[o][l]:
				minimum = array2d[o][l]
				minimumIndex = o + 1
		rank.append(minimumIndex)
	return rank
t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	r = list(map(int, input().split()))
	c = [None for j in range(n)]
	for i in range(n):
		c[i] = list(map(int, input().split()))
	ratingList = [None for i in range(n)]
	for i in range(n):
		temp = []
		temp.append(r[i] + c[i][0])
		for j in range(1, m):
			temp.append(temp[j - 1] + c[i][j])
		ratingList[i] = temp
	playerRatings = []
	for i in range(n):
		maximum = float('-inf')
		maximumMonth = None
		for j in range(m):
			if ratingList[i][j] > maximum:
				maximum = ratingList[i][j]
				maximumMonth = j + 1
		playerRatings.append(maximumMonth)
	playerRanking = getRanking(ratingList, n, m)
	count = 0
	for i in range(n):
		if playerRanking[i] != playerRatings[i]:
			count += 1
	print(count)


import numpy as np
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	r = list(map(int, input().split()))
	rc = []
	rkc = []
	for i in range(n):
		st = r[i]
		t = []
		rkc.append([])
		for j in list(map(int, input().split())):
			t.append(st + j)
			st += j
		rc.append(t)
	for i in range(m):
		mr = []
		for j in range(n):
			mr.append(rc[j][i])
		nmr = np.array(mr)
		argnmr = np.argsort(nmr)
		argnmr = np.flipud(argnmr)
		mr.sort(reverse=True)
		rank = 1
		rkc[argnmr[0]].append(1)
		for j in range(1, n):
			if mr[j] == mr[j - 1]:
				rkc[argnmr[j]].append(rank)
			else:
				rank = j + 1
				rkc[argnmr[j]].append(rank)
	count = 0
	for i in range(n):
		if rc[i].index(max(rc[i])) != rkc[i].index(min(rkc[i])):
			count += 1
	print(count)


t = int(input())
while t:
	(n, m) = map(int, input().split())
	l = [[] for j in range(n)]
	k = [[0 for i in range(m)] for j in range(n)]
	ini = list(map(int, input().split()))
	peak_rate = []
	pkrm = []
	pkram = []
	peak_rank = []
	temp = []
	for j in range(n):
		rec = []
		rec = list(map(int, input().split()))
		for i in range(len(rec)):
			if len(l[j]) == 0:
				l[j].append(ini[j] + rec[i])
			else:
				l[j].append(l[j][i - 1] + rec[i])
		rec.clear()
	for i in range(m):
		for j in range(n):
			temp.append(l[j][i])
		temp.sort(reverse=True)
		count = 0
		dict_1 = {}
		dict_1[temp[0]] = 1
		for r in range(1, n):
			if temp[r] == temp[r - 1]:
				dict_1[temp[r]] = dict_1[temp[r - 1]]
				count += 1
			else:
				dict_1[temp[r]] = dict_1[temp[r - 1]] + count + 1
				count = 0
		for r in range(n):
			k[r][i] = dict_1[l[r][i]]
		temp.clear()
		dict_1.clear()
	ans = 0
	for i in range(n):
		peak_rate.append(l[i].index(max(l[i])))
		peak_rank.append(k[i].index(min(k[i])))
	for i in range(len(peak_rank)):
		if peak_rank[i] != peak_rate[i]:
			ans += 1
	print(ans)
	t -= 1


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	rating = [int(x) for x in input().split()]
	a = []
	for _ in range(n):
		a.append([int(x) for x in input().split()])
	maxrating = [float('-inf')] * n
	minrank = [float('inf')] * n
	index1 = [0] * n
	index2 = [0] * n
	for j in range(m):
		for i in range(n):
			rating[i] += a[i][j]
		st = sorted(rating, reverse=True)
		d = dict()
		curr = 0
		for i in range(len(st)):
			curr += 1
			if st[i] in d:
				continue
			d[st[i]] = curr
		ranks = [d[a] for a in rating]
		for i in range(n):
			if ranks[i] < minrank[i]:
				minrank[i] = ranks[i]
				index2[i] = j
			if rating[i] > maxrating[i]:
				maxrating[i] = rating[i]
				index1[i] = j
	count = 0
	for (i, j) in zip(index1, index2):
		if i != j:
			count += 1
	print(count)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	r = list(map(int, input().split()))
	rating = [[r[i]] * m for i in range(n)]
	ranking = [[0] * m for i in range(n)]
	for i in range(n):
		diff = list(map(int, input().split()))
		for j in range(m):
			rating[i][j] += diff[j]
			if j + 1 < m:
				rating[i][j + 1] = rating[i][j]
	for i in range(m):
		rate = [[j, rating[j][i]] for j in range(n)]
		rate = sorted(rate, key=lambda x: x[1], reverse=True)
		c = 1
		gap = 0
		for j in range(n):
			if j > 0 and rate[j - 1][1] == rate[j][1]:
				gap += 1
			if j > 0 and rate[j - 1][1] != rate[j][1]:
				c += 1 + gap
				gap = 0
			ranking[rate[j][0]][i] = c
	count = 0
	for i in range(n):
		rate = rating[i].copy()
		i1 = rate.index(max(rate))
		rank = ranking[i].copy()
		i2 = rank.index(min(rank))
		if i1 != i2:
			count += 1
	print(count)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	r = list(map(int, input().split()))
	a = []
	for i in range(n):
		b = list(map(int, input().split()))
		count = r[i]
		for j in range(m):
			count += b[j]
			b[j] = count
		a.append(b)
	b = []
	p = 0
	for i in range(n):
		p = [0] * m
		b.append(p)
	for i in range(m):
		c = []
		for j in range(n):
			c.append(a[j][i])
		c.sort(reverse=True)
		for j in range(n):
			b[j][i] = c.index(a[j][i])
	count = 0
	for i in range(n):
		p = a[i].index(max(a[i]))
		q = b[i].index(min(b[i]))
		if p != q:
			count += 1
	print(count)


from copy import copy

def solve():
	(n, m) = tuple(map(int, input().split()))
	ratings = list(map(int, input().split()))
	peak_ratings = [0] * n
	peak_rankings = [n + 1] * n
	rankings = []
	answers = ['No'] * n
	rating_changes = []
	for p in range(n):
		rating_changes.append(list(map(int, input().split())))
	for p in range(m):
		new_rankings = []
		if not rankings:
			for i in range(n):
				ratings[i] += rating_changes[i][p]
				new_rankings.append((i, ratings[i]))
		else:
			for (i, j) in rankings:
				ratings[i] += rating_changes[i][p]
				new_rankings.append((i, ratings[i]))
		new_rankings.sort(reverse=True, key=lambda x: x[1])
		prev_rating = None
		prev_rank = 0
		rank = 0
		for i in range(n):
			(x, y) = new_rankings[i]
			if prev_rating != y:
				rank = i
			if ratings[x] > peak_ratings[x] and rank < peak_rankings[x]:
				peak_ratings[x] = ratings[x]
				peak_rankings[x] = rank
				answers[x] = 'Yes'
			elif ratings[x] > peak_ratings[x]:
				peak_ratings[x] = ratings[x]
				answers[x] = 'No'
			elif rank < peak_rankings[x]:
				peak_rankings[x] = rank
				answers[x] = 'No'
			prev_rating = y
		rankings = new_rankings
	print(answers.count('No'))
t = int(input())
for i in range(t):
	solve()


import sys

def input():
	a = sys.stdin.readline()
	if a[-1] == '\n':
		a = a[:-1]
	return a

def print(*argv):
	n = len(argv)
	for i in range(n):
		if i == n - 1:
			sys.stdout.write(str(argv[i]) + '\n')
		else:
			sys.stdout.write(str(argv[i]) + ' ')

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

def maxInd(lst):
	ind = 0
	maxx = float('-inf')
	for i in range(len(lst)):
		if lst[i] > maxx:
			maxx = lst[i]
			ind = i
	return ind

def ranking(lst):
	lstS = sorted(lst, reverse=True)
	res = []
	r = {}
	for i in range(len(lstS)):
		if r.get(lstS[i]) == None:
			r[lstS[i]] = i
	for i in lst:
		res.append(r[i])
	return res

def solve(n, m, player, change):
	(rank, rank1, rate) = ([], [], [])
	for i in range(m):
		for j in range(n):
			player[j].append(player[j][-1] + change[i][j])
	for i in player:
		rate.append(maxInd(i[1:]))
	for i in range(1, m + 1):
		temp = []
		for j in range(n):
			temp.append(player[j][i])
		rank1.append(ranking(temp))
	for i in range(m):
		for j in range(n):
			rank1[i][j] = n - 1 - rank1[i][j]
	for i in range(n):
		temp = []
		for j in range(m):
			temp.append(rank1[j][i])
		rank.append(maxInd(temp))
	cnt = 0
	for i in range(len(rank)):
		if rank[i] != rate[i]:
			cnt += 1
	return cnt
for _ in range(int(input())):
	(n, m) = list(map(int, input().split()))
	p = list(map(int, input().split()))
	player = []
	for i in p:
		player.append([i])
	change = []
	a = []
	for i in range(n):
		a.append(list(map(int, input().split())))
	for i in range(m):
		change.append([])
		for j in range(n):
			change[i].append(a[j][i])
	print(solve(n, m, player, change))


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ini = list(map(int, input().split()))
	a = []
	for i in range(n):
		a.append([ini[i]] + list(map(int, input().split())))
	for i in range(n):
		for j in range(1, m + 1):
			a[i][j] = a[i][j - 1] + a[i][j]
	for i in range(n):
		a[i].append([600, a[i][1], 1, 1])
	for i in range(1, m + 1):
		a = sorted(a, key=lambda x: -x[i])
		r = 1
		temp = -1
		for j in range(n):
			if temp != a[j][i]:
				r = j + 1
			if a[j][-1][0] > r:
				a[j][-1][0] = r
				a[j][-1][2] = i
			if a[j][-1][1] < a[j][i]:
				a[j][-1][1] = a[j][i]
				a[j][-1][3] = i
			temp = a[j][i]
	res = 0
	for i in range(n):
		if a[i][-1][-1] != a[i][-1][-2]:
			res += 1
	print(res)


def check(rat, rank_mont):
	c = 0
	for i in range(len(rank_mont)):
		if rat[i] != rank_mont[i]:
			c += 1
	return c

def ranking(rat, rank_min, mont, n, m):
	rat_sort = []
	for i in range(m):
		rat_sort.append(sorted(rat[i], reverse=True, key=lambda x: x[0]))
	for i in range(m):
		(r, j) = (1, 0)
		while j < n:
			key = rat_sort[i][j][0]
			c = 0
			while j < n:
				if key == rat_sort[i][j][0]:
					if rank_min[rat_sort[i][j][1] - 1] > r:
						rank_min[rat_sort[i][j][1] - 1] = r
						mont[rat_sort[i][j][1] - 1] = i + 1
					c += 1
				else:
					break
				j += 1
			r += c
for T in range(int(input())):
	(n, m) = list(map(int, input().split()))
	initial_rating = list(map(int, input().split()))
	rat = [list(map(int, input().split())) for i in range(n)]
	(rat_player, m_rat_player) = ([], [])
	for i in range(n):
		(m_rat, x) = (0, [])
		for j in range(m):
			x.append(initial_rating[i] + rat[i][j])
			initial_rating[i] = x[j]
			if m_rat < x[j]:
				m_rat = x[j]
				month = j + 1
		rat_player.append(x)
		m_rat_player.append(month)
	rat_month = []
	for i in range(m):
		x = []
		for j in range(n):
			x.append([rat_player[j][i], j + 1])
		rat_month.append(x)
	(rank_min, mont) = ([501] * n, [0] * n)
	ranking(rat_month, rank_min, mont, n, m)
	count = check(m_rat_player, mont)
	print(count)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	inis = list(map(int, input().split()))
	changes = []
	for i in range(n):
		changes.append(list(map(int, input().split())))
		changes[i][0] += inis[i]
	maxRating = [0] * n
	Ranks = [[n] * m for i in range(n)]
	temp = []
	for i in range(n):
		temp.append((changes[i][0], i))
	temp.sort(key=lambda x: x[0], reverse=True)
	Ranks[temp[0][1]][0] = 1
	prevRank = 1
	rankCtr = 0
	for i in range(1, n):
		if temp[i][0] == temp[i - 1][0]:
			rankCtr += 1
			Ranks[temp[i][1]][0] = prevRank
		else:
			prevRank += 1 + rankCtr
			Ranks[temp[i][1]][0] = prevRank
			rankCtr = 0
	for i in range(n):
		for j in range(1, m):
			changes[i][j] += changes[i][j - 1]
			if changes[i][j] > changes[i][maxRating[i]]:
				maxRating[i] = j
	for j in range(m):
		temp = []
		for i in range(n):
			temp.append((changes[i][j], i))
		temp.sort(key=lambda x: x[0], reverse=True)
		Ranks[temp[0][1]][j] = 1
		prevRank = 1
		rankCtr = 0
		for i in range(1, n):
			if temp[i][0] == temp[i - 1][0]:
				rankCtr += 1
				Ranks[temp[i][1]][j] = min(Ranks[temp[i][1]][j], prevRank)
			else:
				prevRank += 1 + rankCtr
				Ranks[temp[i][1]][j] = min(Ranks[temp[i][1]][j], prevRank)
				rankCtr = 0
	ans = 0
	maxRanks = [0] * n
	for i in range(n):
		maxRanks[i] = 0
		for j in range(m):
			if Ranks[i][j] < Ranks[i][maxRanks[i]]:
				maxRanks[i] = j
	for i in range(n):
		if maxRanks[i] != maxRating[i]:
			ans += 1
	print(ans)


try:
	t = int(input())
	for i in range(t):
		(n, m) = [int(i) for i in input().split()]
		intial = [int(i) for i in input().split()]
		lol = []
		hr_moth = []
		rate = []
		moths = [[] for _ in range(m)]
		for i in range(n):
			c = [int(o) for o in input().split()]
			shel = []
			for dd in range(m):
				if dd == 0:
					shel.append(intial[i] + c[dd])
					moths[dd].append(intial[i] + c[dd])
				else:
					shel.append(shel[dd - 1] + c[dd])
					moths[dd].append(shel[dd - 1] + c[dd])
			hr_moth.append(shel.index(max(shel)) + 1)
			rate.append(shel)
			lol.append(c)
		number = 0
		players = [[0 for _ in range(n)] for _ in range(m)]
		for i in range(m):
			x = moths[i]
			k = []
			for j in range(n):
				k.append([x[j], j])
			k = list(reversed(sorted(k, key=lambda y: y[0])))
			rank = 1
			temp = -1
			for j in range(n):
				if j == 0:
					players[i][k[j][1]] = rank
					temp = k[j][0]
				else:
					if k[j][0] < temp:
						rank = j + 1
					temp = k[j][0]
					players[i][k[j][1]] = rank
		ans = [-1 for _ in range(n)]
		for i in range(n):
			mon = -1
			hh = 10 ** 8
			for j in range(m):
				if players[j][i] < hh:
					hh = players[j][i]
					mon = j + 1
			if hr_moth[i] != mon:
				number += 1
		print(number)
except:
	pass


def ok():
	(n, m) = map(int, input().split())
	rating = list(map(int, input().split()))
	data = []
	for i in range(n):
		data.append(list(map(int, input().split())))
	max_rating = [-float('inf')] * n
	max_ranking = [float('inf')] * n
	day_rating = [0] * n
	day_ranking = [0] * n
	for i in range(m):
		hm = {}
		for j in range(n):
			rating[j] = rating[j] + data[j][i]
			if rating[j] > max_rating[j]:
				day_rating[j] = i + 1
				max_rating[j] = rating[j]
			if rating[j] in hm.keys():
				hm[rating[j]] += 1
			else:
				hm[rating[j]] = 1
		s = sorted(hm.keys())
		s.reverse()
		r = 1
		for k in s:
			count = hm[k]
			hm[k] = r
			r += count
		for j in range(n):
			if max_ranking[j] > hm[rating[j]]:
				max_ranking[j] = hm[rating[j]]
				day_ranking[j] = i + 1
	cnt = 0
	for i in range(n):
		if day_ranking[i] != day_rating[i]:
			cnt += 1
	print(cnt)
for _ in range(int(input())):
	ok()


from copy import copy

class Player:

	def __init__(self, rating, i):
		self.rating = rating
		self.ranking = None
		self.best_rate_month = 0
		self.best_rank_month = 0
		self.best_rate = 0
		self.best_Rank = 10 ** 9
		self.index = i

	def changeRating(self, inc, month):
		if self.rating + inc > self.best_rate:
			self.best_rate = self.rating + inc
			self.best_rate_month = month
		self.rating = self.rating + inc

	def changeRanking(self, ranking, month):
		if ranking < self.best_Rank:
			self.best_Rank = ranking
			self.best_rank_month = month
		self.ranking = ranking

def key_val(obj):
	return obj.rating

def solve(lst, players):
	rankings = [0] * n
	for month in range(m):
		for player in range(n):
			players[player].changeRating(lst[player][month], month + 1)
		temp = copy(players)
		temp.sort(key=key_val, reverse=True)
		for i in range(n):
			if i >= 1 and temp[i].rating == temp[i - 1].rating:
				rankings[temp[i].index] = rankings[temp[i - 1].index]
				continue
			rankings[temp[i].index] = i + 1
		for i in range(n):
			players[i].changeRanking(rankings[i], month + 1)
	count = 0
	for p in players:
		if p.best_rank_month != p.best_rate_month:
			count += 1
	return count
tc = int(input())
for _ in range(tc):
	(n, m) = map(int, input().split())
	init_rating = list(map(int, input().split()))
	players = []
	i = 0
	for x in init_rating:
		players.append(Player(x, i))
		i += 1
	lst = []
	for i in range(n):
		row = list(map(int, input().split()))
		lst.append(row)
	print(solve(lst, players))


T = int(input())
for _ in range(T):
	(N, M) = map(int, input().split())
	A = list(map(int, input().split()))
	l = []
	for i in range(N):
		l.append(list(map(int, input().split())))
	for i in range(N):
		for j in range(M):
			A[i] += l[i][j]
			l[i][j] = A[i]
	R = [[0 for i in range(M)] for j in range(N)]
	for j in range(M):
		X = []
		for i in range(N):
			X.append(l[i][j])
		X.sort()
		Y = [0 for i in range(N)]
		y = 0
		x = 1
		m = -1000000
		for i in range(N - 1, -1, -1):
			if m == X[i]:
				Y[i] = y
			else:
				y = x
				Y[i] = y
				m = X[i]
			x += 1
		d = dict()
		for i in range(N):
			d[X[i]] = Y[i]
		for i in range(N):
			R[i][j] = d[l[i][j]]
	f = 0
	for i in range(N):
		x = min(R[i])
		y = max(l[i])
		a = -1
		b = -1
		for j in range(M):
			if R[i][j] == x:
				a = j
				break
		for j in range(M):
			if l[i][j] == y:
				b = j
				break
		if a != b:
			f += 1
	print(f)


import numpy as np
import copy
for _ in range(int(input())):
	(N, M) = map(int, input().split())
	R = np.array(list(map(int, input().split())))
	C = np.array([list(map(int, input().split())) for i in range(N)])
	C[:, 0] += R
	C = C.cumsum(axis=1)
	Y = C.argmax(axis=1)
	X = np.empty((N, M), dtype=int)
	for i in range(M):
		m = C[:, i].copy()
		m.sort()
		X[:, i] = np.searchsorted(m, C[:, i], side='right')
	X = X.argmax(axis=1)
	print(N - (X == Y).sum())


t = int(input().strip())
for t_ in range(t):
	(n, m) = map(int, input().strip().split())
	r0 = list(map(int, input().strip().split()))
	ratings = [None] * n
	for i in range(n):
		ratings[i] = [None] * (m + 1)
		ratings[i][0] = r0[i]
	rankings = [None] * n
	for i in range(n):
		rankings[i] = [None] * (m + 1)
	for i in range(n):
		rd = list(map(int, input().strip().split()))
		for j in range(m):
			ratings[i][j + 1] = ratings[i][j] + rd[j]
	for j in range(1, m + 1):
		rating = []
		for i in range(n):
			rating.append((ratings[i][j], i))
		sorted_rating = sorted(rating, reverse=True)
		last_rating = None
		last_ranking = None
		ranking = [None] * n
		pos = 0
		for (current_rating, idx) in sorted_rating:
			pos += 1
			if current_rating == last_rating:
				ranking[idx] = last_ranking
			else:
				ranking[idx] = pos
			last_rating = current_rating
			last_ranking = ranking[idx]
		for i in range(n):
			rankings[i][j] = ranking[i]
	total = 0
	for i in range(n):
		rating = ratings[i][1:]
		best_rating_month = rating.index(max(rating))
		ranking = rankings[i][1:]
		best_ranking_month = ranking.index(min(ranking))
		if best_rating_month != best_ranking_month:
			total += 1
	print(total)


for _ in range(int(input())):
	(n, m) = (int(i) for i in input().split())
	r = list((int(i) for i in input().split()))
	li = [[int(i) for i in input().split()] for j in range(n)]
	for i in range(n):
		li[i][0] += r[i]
	for i in range(n):
		for j in range(1, m):
			li[i][j] += li[i][j - 1]
	lk = [[0] * m for i in range(n)]
	d = {}
	for i in range(m):
		s = sorted((li[j][i] for j in range(n)), reverse=True)
		for o in range(len(s) - 1, -1, -1):
			d[s[o]] = o + 1
		for j in range(n):
			lk[j][i] = d[li[j][i]]
	c = 0
	for i in range(n):
		ma = max(li[i])
		ind = li[i].index(ma)
		iiind = lk[i].index(min(lk[i]))
		if ind != iiind:
			c += 1
	print(c)


import heapq
import sys
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().strip().split())
	initial_rating = list(map(int, input().strip().split()))
	rating_matrix = [[None] * n for i in range(m)]
	for i in range(n):
		player_rating_change = list(map(int, input().strip().split()))
		rating_matrix[0][i] = initial_rating[i] + player_rating_change[0]
		for j in range(1, m):
			rating_matrix[j][i] = rating_matrix[j - 1][i] + player_rating_change[j]
	ranking_matrix = [[None] * n for i in range(m)]
	for i in range(m):
		player_monthly_rating = rating_matrix[i]
		curr_heap = []
		for j in range(n):
			heapq.heappush(curr_heap, [-player_monthly_rating[j], j])
		curr_rank = 0
		curr_index = 0
		prev_rating_value = None
		for j in range(n):
			(rating, index) = heapq.heappop(curr_heap)
			rating *= -1
			curr_index += 1
			if prev_rating_value != rating:
				curr_rank = curr_index
			ranking_matrix[i][index] = curr_rank
			prev_rating_value = rating
	count = 0
	for i in range(n):
		max_rank = sys.maxsize
		max_rating = -sys.maxsize
		max_rank_index = None
		max_rating_index = None
		for j in range(m):
			if rating_matrix[j][i] > max_rating:
				max_rating_index = j
				max_rating = rating_matrix[j][i]
			if ranking_matrix[j][i] < max_rank:
				max_rank_index = j
				max_rank = ranking_matrix[j][i]
		if max_rank_index != max_rating_index:
			count += 1
	print(count)


def __starting_point():
	t = int(input())
	while t > 0:
		(N, M) = map(int, input().split())
		R = list(map(int, input().split()))
		Ratings = []
		Rankings = [[float('inf') for i in range(M)] for j in range(N)]
		for i in range(N):
			temp_ratings = list(map(int, input().split()))
			temp = []
			initial_rating = R[i]
			for rate in temp_ratings:
				temp.append(initial_rating + rate)
				initial_rating += rate
			Ratings.append(temp)
		for i in range(M):
			temp = []
			for j in range(N):
				temp.append(Ratings[j][i])
			temp = sorted(temp, reverse=True)
			dic = {}
			for j in range(N):
				if temp[j] not in dic:
					dic[temp[j]] = j + 1
			for j in range(N):
				Rankings[j][i] = dic[Ratings[j][i]]
		cnt = 0
		for i in range(N):
			best_rating = 0
			best_rating_index = -1
			best_ranking = float('inf')
			best_ranking_index = -1
			for j in range(M):
				if Ratings[i][j] > best_rating:
					best_rating = Ratings[i][j]
					best_rating_index = j
				if Rankings[i][j] < best_ranking:
					best_ranking = Rankings[i][j]
					best_ranking_index = j
			if best_rating_index != best_ranking_index:
				cnt += 1
		print(cnt)
		t -= 1
__starting_point()


import sys
t = int(sys.stdin.readline().strip())

def rate(l):
	sm = l[0]
	mx = l[0]
	ind = 0
	for i in range(1, len(l)):
		sm += l[i]
		if sm > mx:
			mx = sm
			ind = i
	return ind + 1

def ranking(n, m, R, ratings):
	rnk = []
	for mn in range(m):
		l = []
		for i in range(n):
			R[i] += ratings[i][mn]
			l.append(R[i])
		mxr = max(l)
		rr = []
		for k in range(n):
			if l[k] == mxr:
				rr.append(k + 1)
		rnk.append(rr)
	return rnk

def ranking2(n, m, R, ratings):
	ranks = [[] for _ in range(n)]
	for mn in range(m):
		l = []
		for i in range(n):
			R[i] += ratings[i][mn]
			l.append([R[i], i])
		l.sort(reverse=True)
		l.insert(0, [40000, -1])
		k = 0
		for i in range(1, len(l)):
			change = False
			if l[i][0] < l[i - 1][0]:
				k = i
				change = True
			ranks[l[i][1]].append(k)
	high = []
	for i in ranks:
		mr = min(i)
		high.append(i.index(mr) + 1)
	return high
for _ in range(t):
	(n, m) = map(int, sys.stdin.readline().strip().split())
	R = list(map(int, sys.stdin.readline().strip().split()))
	ratings = []
	for i in range(n):
		ratings.append(list(map(int, sys.stdin.readline().strip().split())))
	ranks2 = ranking2(n, m, R, ratings)
	maxR = []
	for j in range(n):
		r = ratings[j]
		p = rate(r)
		maxR.append(p)
	count = 0
	for i in range(n):
		if maxR[i] != ranks2[i]:
			count += 1
	print(count)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	c = {}
	ans = 0
	for i in range(n):
		c[i] = [0, 0, 100000, 0]
	d = {}
	for i in range(n):
		d[i] = []
	for i in range(n):
		b = list(map(int, input().split()))
		for j in range(m):
			a[i] += b[j]
			d[i].append(a[i])
			if a[i] > c[i][0]:
				c[i][0] = a[i]
				c[i][1] = j
	for i in range(m):
		e = sorted(d.items(), key=lambda x: x[1][i], reverse=True)
		p = 0
		(s, t) = e[0]
		if c[s][2] > p:
			c[s][2] = p
			c[s][3] = i
		for j in range(1, len(e)):
			(u, v) = e[j]
			if v[i] == e[j - 1][1][i]:
				if c[u][2] > p:
					c[u][2] = p
					c[u][3] = i
			else:
				p = j
				if c[u][2] > p:
					c[u][2] = p
					c[u][3] = i
	for (k, v) in c.items():
		if v[1] != v[3]:
			ans += 1
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	r = list(map(int, input().split()))
	mat = [[] for i in range(n)]
	ranking = [[] for i in range(n)]
	for i in range(n):
		l = list(map(int, input().split()))
		cur = r[i]
		for j in l:
			cur += j
			mat[i].append(cur)
	for i in range(m):
		ar = []
		for j in range(n):
			ar.append([mat[j][i], j])
		ar.sort(reverse=True, key=lambda x: x[0])
		prev = -1
		r = 1
		x = 1
		for j in range(n):
			if ar[j][0] != prev:
				r = x
			ranking[ar[j][1]].append(r)
			prev = ar[j][0]
			x += 1
	brt = []
	brk = []
	for i in range(n):
		brt.append(mat[i].index(max(mat[i])))
	for i in range(n):
		brk.append(ranking[i].index(min(ranking[i])))
	ans = 0
	for i in range(n):
		if brk[i] != brt[i]:
			ans += 1
	print(ans)


from collections import Counter
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	pl = list(map(int, input().split()))
	pl2 = list(pl)
	mnt = []
	for i in range(n):
		mnt.append(list(map(int, input().split())))
	bs_rating = []
	for i in range(n):
		mx = 0
		for j in range(m):
			pl[i] += mnt[i][j]
			if pl[i] > mx:
				mx = pl[i]
				pos = j
		bs_rating.append(pos + 1)
	fnl = []
	for j in range(m):
		lis = []
		for i in range(n):
			lis.append(mnt[i][j])
		fnl.append(lis)
	bs_rnk = [0] * n
	bs_month = [501] * n
	bst_rank = [0] * n
	for i in range(m):
		chk = []
		for j in range(n):
			pl2[j] += fnl[i][j]
			chk.append([pl2[j], j])
		chk = sorted(chk)[::-1]
		prev = chk[0][0]
		rnk = 1
		cnt = 0
		for j in range(n):
			if chk[j][0] == prev:
				bs_rnk[chk[j][1]] = rnk
				cnt += 1
			else:
				rnk = rnk + cnt
				bs_rnk[chk[j][1]] = rnk
				cnt = 1
			prev = chk[j][0]
		for j in range(n):
			if bs_rnk[j] < bs_month[j]:
				bs_month[j] = bs_rnk[j]
				bst_rank[j] = i + 1
	ans = 0
	for i in range(n):
		if bst_rank[i] != bs_rating[i]:
			ans += 1
	print(ans)


import sys
input = lambda : sys.stdin.readline().rstrip()
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	inl = [int(i) for i in input().split()]
	a = []
	for i in range(n):
		a.append([int(i) for i in input().split()])
	for i in range(n):
		a[i][0] += inl[i]
		for j in range(1, m):
			a[i][j] += a[i][j - 1]
	rtm = []
	for i in range(n):
		rtm.append(a[i].index(max(a[i])))
	r = [[-1] * m for i in range(n)]
	for i in range(m):
		p = []
		for j in range(n):
			p.append([a[j][i], j])
		p.sort(reverse=True)
		st = set()
		c = -1
		cur = 0
		for j in p:
			c += 1
			if j[0] not in st:
				r[j[1]][i] = c
				st.add(j[0])
				cur = c
			else:
				r[j[1]][i] = cur
	rnm = []
	for i in range(n):
		rnm.append(r[i].index(min(r[i])))
	ans = 0
	for i in range(n):
		if rnm[i] != rtm[i]:
			ans += 1
	print(ans)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	R = list(map(int, input().split()))
	matrix = []
	for i in range(n):
		temp = list(map(int, input().split()))
		matrix.append(temp)
	for (ind, i) in enumerate(R):
		last = i
		for i in range(m):
			matrix[ind][i] = matrix[ind][i] + last
			last = matrix[ind][i]
	for i in range(m):
		arr = []
		for j in range(n):
			arr.append(matrix[j][i])
		arr.sort(reverse=True)
		arr_dict = dict()
		for (ind, item) in enumerate(arr):
			if ind == 0:
				arr_dict[item] = 0
				last = item
			elif item == last:
				arr_dict[item] = arr_dict[last]
			else:
				arr_dict[item] = ind
				last = item
		for j in range(n):
			matrix[j][i] = (matrix[j][i], arr_dict[matrix[j][i]])
	count = 0
	for i in matrix:
		if i.index(max(i, key=lambda x: x[0])) != i.index(min(i, key=lambda x: x[1])):
			count += 1
	print(count)


from sys import stdin, stdout
from collections import Counter
for _ in range(int(stdin.readline())):
	(n, m) = list(map(int, stdin.readline().split()))
	rtng = list(map(int, stdin.readline().split()))
	a = []
	ans = 0
	for plr in range(n):
		l = []
		chng = list(map(int, stdin.readline().split()))
		init = rtng[plr]
		for c in chng:
			init += c
			l += [init]
		a += [l]
	rank_pm = [[0 for _ in range(m)] for _ in range(n)]
	for mm in range(m):
		rar = []
		for pp in range(n):
			rar += [a[pp][mm]]
		cntr = Counter(rar)
		dec_ranks = sorted(cntr.keys(), reverse=True)
		d = {}
		rank = 1
		for rating in dec_ranks:
			d[rating] = rank
			rank += cntr[rating]
		for pp in range(n):
			rank_pm[pp][mm] = d[a[pp][mm]]
	for pp in range(n):
		best_rating = 0
		best_rank = float('inf')
		rating_mnth = rank_mnth = 0
		for mm in range(m):
			if a[pp][mm] > best_rating:
				best_rating = a[pp][mm]
				rating_mnth = mm
			if rank_pm[pp][mm] < best_rank:
				best_rank = rank_pm[pp][mm]
				rank_mnth = mm
		if rating_mnth != rank_mnth:
			ans += 1
	print(ans)


t = int(input())
while t:
	t -= 1
	(n, m) = [int(x) for x in input().split()]
	l = [int(x) for x in input().split()]
	maxi = []
	l1 = []
	for j in range(n):
		a1 = -1
		a2 = -1
		a = [int(x) for x in input().split()]
		l1.append(a[:])
		for i in range(1, m):
			a[i] += a[i - 1]
		m1 = max(a)
		for i in range(m):
			if a[i] == m1:
				a2 = i
				break
		maxi.append(a2)
	ranksfinal = []
	k = 0
	for j in range(m):
		for i in range(n):
			l[i] += l1[i][j]
		d = {}
		for i in range(n):
			try:
				d[l[i]].append(i)
			except:
				d[l[i]] = [i]
		ranks = [0 for i in range(n)]
		p = 1
		var = sorted(d.keys())[::-1]
		for i in var:
			for j in d[i]:
				ranks[j] = p
			p += len(d[i])
		ranksfinal.append(ranks)
	ans2 = []
	for i in range(n):
		ranks = []
		for j in range(m):
			ranks.append(ranksfinal[j][i])
		m1 = min(ranks)
		for j in range(m):
			if ranks[j] == m1:
				ans2.append(j)
				break
	ans = 0
	for i in range(n):
		if ans2[i] != maxi[i]:
			ans += 1
	print(ans)


from collections import defaultdict as dd
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	l = []
	d = [[] for i in range(n)]
	for i in range(0, n):
		b = list(map(int, input().split()))
		l.append(b)
	for i in range(0, m):
		for j in range(0, n):
			a[j] += l[j][i]
			if len(d[j]) == 0:
				d[j] += [a[j], i, 10000000000, i]
		c = a[:]
		c = set(c)
		c = list(c)
		c.sort(reverse=True)
		d2 = dd(int)
		d1 = dd(int)
		for k in range(0, n):
			d2[a[k]] = d2.get(a[k], 0) + 1
		r = 0
		for k in range(0, len(c)):
			d1[c[k]] = r
			r += d2[c[k]]
		for j in range(0, n):
			r = d1[a[j]]
			if r < d[j][2]:
				d[j][2] = r
				d[j][3] = i
			if a[j] > d[j][0]:
				d[j][0] = a[j]
				d[j][1] = i
	ct = 0
	for i in range(0, n):
		if d[i][1] != d[i][3]:
			ct += 1
	print(ct)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	ini = list(map(int, input().split()))
	d = [[0 for _ in range(m)] for _ in range(n)]
	l = []
	for i in range(n):
		l.append(list(map(int, input().split())))
	for i in range(len(l)):
		for j in range(len(l[i])):
			if j == 0:
				d[i][j] = ini[i] + l[i][j]
			else:
				d[i][j] = d[i][j - 1] + l[i][j]
	rank = [[0 for _ in range(m)] for _ in range(n)]
	for j in range(m):
		l1 = []
		for i in range(n):
			l1.append([d[i][j], i])
		l1.sort()
		prev = l1[n - 1][0]
		r = 1
		c = 1
		for i in range(n - 1, -1, -1):
			if l1[i][0] == prev:
				c += 1
			else:
				r = c
				c += 1
				prev = l1[i][0]
			rank[l1[i][1]][j] = r
	c = 0
	for i in range(n):
		m1 = d[i].index(max(d[i]))
		m2 = rank[i].index(min(rank[i]))
		if m1 != m2:
			c += 1
	print(c)


t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	curr = list(map(int, input().split()))
	max_so_far = [0] * n
	scores = curr[:]
	rank_so_far = [n] * n
	best_ranking = [n] * n
	best_rating = [0] * n
	l = []
	for i in range(n):
		l.append(list(map(int, input().split())))
		x = l[i][:]
		for j in range(m):
			curr[i] += x[j]
			if curr[i] > max_so_far[i]:
				best_rating[i] = j + 1
				max_so_far[i] = curr[i]
	for i in range(m):
		for j in range(n):
			scores[j] += l[j][i]
		x = scores[:]
		p = list(set(x))
		p.sort(reverse=True)
		d = {}
		for j in x:
			if j in d:
				d[j] += 1
			else:
				d[j] = 1
		rank = 1
		v = {}
		for j in p:
			v[j] = rank
			rank += d[j]
		for j in range(n):
			if v[x[j]] < rank_so_far[j]:
				best_ranking[j] = i + 1
				rank_so_far[j] = v[x[j]]
	c = 0
	for i in range(n):
		if best_ranking[i] != best_rating[i]:
			c += 1
	print(c)


import sys
from collections import defaultdict
t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	adj = []
	for _ in range(n):
		x = list(map(int, input().split()))
		adj.append(x)
	rating = defaultdict(lambda : -1)
	rank = [[-1 for i in range(m + 1)] for j in range(n)]
	b = [[-1 for i in range(m + 1)] for j in range(n)]
	for i in range(n):
		b[i][0] = a[i]
	for i in range(0, n):
		for j in range(1, m + 1):
			b[i][j] = b[i][j - 1] + adj[i][j - 1]
	for j in range(1, m + 1):
		g = []
		d = {}
		for i in range(n):
			g.append(b[i][j])
		z = sorted(g, reverse=True)
		c = 0
		for i in z:
			if i not in d:
				c += 1
				d[i] = c
			else:
				c += 1
		for i in range(n):
			rank[i][j] = d[b[i][j]]
	for i in range(n):
		mx = -1
		for x in range(1, m + 1):
			mx = max(mx, b[i][x])
		for j in range(1, m + 1):
			if b[i][j] == mx:
				rating[i] = j
				break
	c = 0
	for i in range(n):
		ans = []
		mi = sys.maxsize
		for x in range(1, m + 1):
			mi = min(mi, rank[i][x])
		for j in range(1, m + 1):
			if rank[i][j] == mi:
				if j != rating[i]:
					c += 1
				break
	print(c)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	scores = list(map(int, input().split()))
	usr_mnthly = {}
	usr_ranks = {}
	for i in range(n):
		scrs = list(map(int, input().split()))
		usr_mnthly[i] = [scores[i]]
		usr_ranks[i] = []
		for j in scrs:
			usr_mnthly[i].append(usr_mnthly[i][-1] + j)
	for mnth in range(1, m + 1):
		mnthly = {i: usr_mnthly[i][mnth] for i in range(n)}
		mnthly = sorted(mnthly.items(), key=lambda x: x[1], reverse=True)
		prev = -9999999999
		rank = 0
		pos = 1
		for (key, value) in mnthly:
			if value == prev:
				usr_ranks[key].append(rank)
				pos += 1
			else:
				rank += pos
				usr_ranks[key].append(rank)
				pos = 1
			prev = value
	ans = 0
	for i in range(n):
		mnths = usr_mnthly[i][1:]
		ranks = usr_ranks[i]
		if ranks.index(min(ranks)) != mnths.index(max(mnths)):
			ans += 1
	print(ans)


for _ in range(int(input())):
	(p, m) = tuple(map(int, input().split()))
	rates = list(map(int, input().split()))
	changesPM = [list(map(int, input().split())) for i in range(p)]
	temp = 0
	ranksMP = []
	bestrate = [0 for i in range(p)]
	bestratemon = [0 for i in range(p)]
	for i in range(m):
		ratesM = []
		for j in range(p):
			changesPM[j][i] += changesPM[j][i - 1] if i else rates[j]
			ratesM.append(changesPM[j][i])
			if changesPM[j][i] > bestrate[j]:
				bestrate[j] = changesPM[j][i]
				bestratemon[j] = i + 1
		new_lis = sorted(ratesM, reverse=True)
		di = dict()
		for i in range(len(new_lis)):
			if new_lis[i] not in di:
				di[new_lis[i]] = i + 1
		ranksMP.append([di[ratesM[i]] for i in range(len(new_lis))])
	bestranks = []
	bestrankmons = []
	for i in range(p):
		bestrank = ranksMP[0][i]
		bestrankmon = 1
		for j in range(m):
			if ranksMP[j][i] < bestrank:
				bestrank = ranksMP[j][i]
				bestrankmon = j + 1
		bestranks.append(bestrank)
		bestrankmons.append(bestrankmon)
	count = 0
	for i in range(p):
		count += int(bestrankmons[i] != bestratemon[i])
	print(count)


int_input = lambda : int(input())
list_input = lambda : list(map(int, input().split()))
for _ in range(int(input())):
	(n, m) = list_input()
	initial = list_input()
	players = []
	for i in range(n):
		l = list_input()
		players.append([])
		x = initial[i]
		for j in l:
			x += j
			players[i].append(x)
	ranks = [[-1 for i in range(len(players[0]))] for j in range(len(players))]
	for i in range(m):
		l = []
		for j in range(n):
			l.append([players[j][i], j + 1])
		l.sort(reverse=True, key=lambda x: x[0])
		for ind in range(len(l)):
			if ind == 0:
				pos = 1
			elif l[ind][0] == l[ind - 1][0]:
				pos = ranks[l[ind - 1][1] - 1][i]
			else:
				pos = ind + 1
			ranks[l[ind][1] - 1][i] = pos
	max_ranking = []
	for i in range(n):
		a = float('inf')
		month = -1
		for j in range(m):
			if ranks[i][j] < a:
				a = ranks[i][j]
				month = j + 1
		max_ranking.append(month)
	peaks = []
	for i in range(n):
		a = float('-inf')
		month = -1
		for j in range(m):
			if players[i][j] > a:
				a = players[i][j]
				month = j + 1
		peaks.append(month)
	count = 0
	for i in range(n):
		if peaks[i] != max_ranking[i]:
			count += 1
	print(count)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	inr = []
	inr = list(map(int, input().split()))
	ratchan = []
	for i in range(n):
		l = list(map(int, input().split()))
		ratchan.append(l)
	change = [[-1, -1, n] for i in range(n)]
	for i in range(n):
		l1 = ratchan[i]
		mx = -10 ** 10
		tmp = 0
		for j in range(len(l1)):
			tmp += l1[j]
			mx = max(mx, tmp)
		tmp = 0
		for j in range(len(l1)):
			tmp += l1[j]
			if tmp == mx:
				change[i][0] = j + 1
				break
	start = inr[:]
	for i in range(m):
		mx = -10 ** 10
		temp = []
		for j in range(n):
			start[j] += ratchan[j][i]
			temp.append([j, start[j]])
		temp = sorted(temp, key=lambda x: x[1], reverse=True)
		rank = 1
		rate = temp[0][1]
		for j in range(n):
			if rate > temp[j][1]:
				rank = j + 1
				rate = temp[j][1]
			if change[temp[j][0]][2] > rank:
				change[temp[j][0]][2] = rank
				change[temp[j][0]][1] = i + 1
	ans = 0
	for i in range(len(change)):
		if change[i][0] != change[i][1]:
			ans += 1
	print(ans)


def satisfy(ratings, ranks):
	max_rating = max(ratings)
	min_rank = min(ranks)
	for (i, rank) in enumerate(ranks):
		if rank == min_rank:
			earliest_rank = i
			break
	for (i, rating) in enumerate(ratings):
		if rating == max_rating:
			earliest_rating = i
			break
	if earliest_rating == earliest_rank:
		return False
	return True

def magic(n, m, rating_dict):
	ranking_dict = {}
	for month in range(m):
		rating_list = []
		for (key, val) in rating_dict.items():
			rating_list.append((key, val[month]))
		rating_list.sort(key=lambda x: x[1], reverse=True)
		current_rank = 0
		global_rank = 0
		current_rating = 0
		for (key, rating) in rating_list:
			global_rank += 1
			if rating != current_rating:
				current_rating = rating
				current_rank = global_rank
			if key not in ranking_dict:
				ranking_dict[key] = [current_rank]
			else:
				ranking_dict[key].append(current_rank)
	count = 0
	for (key, ratings) in rating_dict.items():
		ranks = ranking_dict[key]
		if satisfy(ratings, ranks):
			count += 1
	return count
t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().strip().split()))
	initial_rating = list(map(int, input().strip().split()))
	rating_dict = {}
	for i in range(n):
		ratings = list(map(int, input().strip().split()))
		for rate in ratings:
			if i not in rating_dict:
				rating_dict[i] = [initial_rating[i] + rate]
			else:
				rating_dict[i].append(rating_dict[i][-1] + rate)
	print(magic(n, m, rating_dict))


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	org_ratings = list(map(int, input().split()))
	l = []
	count = 0
	for i in range(n):
		l.append(list(map(int, input().split())))
	for i in range(n):
		for j in range(m):
			if j == 0:
				l[i][j] = l[i][j] + org_ratings[i]
			else:
				l[i][j] = l[i][j] + l[i][j - 1]
	ranks = [[-1 for i in range(len(l[0]))] for j in range(len(l))]
	for i in range(m):
		l2 = []
		for j in range(n):
			l2.append([l[j][i], j + 1])
		l2.sort(reverse=True, key=lambda x: x[0])
		for ind in range(len(l2)):
			if ind == 0:
				pos = 1
			elif l2[ind][0] == l2[ind - 1][0]:
				pos = ranks[l2[ind - 1][1] - 1][i]
			else:
				pos = ind + 1
			ranks[l2[ind][1] - 1][i] = pos
	for i in range(n):
		if l[i].index(max(l[i])) != ranks[i].index(min(ranks[i])):
			count += 1
	print(count)


t = int(input())
for z in range(t):
	(n, m) = map(int, input().split())
	initial = list(map(int, input().split()))
	rating = [[0 for i in range(m)] for j in range(n)]
	highest_rating = [0] * n
	for i in range(n):
		inp = list(map(int, input().split()))
		for j in range(m):
			initial[i] += inp[j]
			rating[i][j] = initial[i]
			if rating[i][j] > rating[i][highest_rating[i]]:
				highest_rating[i] = j
	ranking = [[0 for i in range(m)] for j in range(n)]
	for i in range(m):
		s = []
		for j in range(n):
			s.append(rating[j][i])
		s.sort(reverse=True)
		d = dict()
		for j in range(n):
			if s[j] not in d:
				d[s[j]] = j
		for j in range(n):
			ranking[j][i] = d[rating[j][i]]
	best_ranking = [0] * n
	for i in range(n):
		for j in range(1, m):
			if ranking[i][j] < ranking[i][best_ranking[i]]:
				best_ranking[i] = j
	count = 0
	for i in range(n):
		if highest_rating[i] != best_ranking[i]:
			count += 1
	print(count)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	rating = list(map(int, input().split()))
	track = [[] for i in range(n)]
	cng = []
	for i in range(n):
		cng.append(list(map(int, input().split())))
	for i in range(m):
		for j in range(n):
			rating[j] += cng[j][i]
		x = sorted(enumerate(rating), key=lambda x: x[1], reverse=True)
		r = 1
		if i != 0:
			if x[0][1] > track[x[0][0]][0] or r < track[x[0][0]][1]:
				if x[0][1] > track[x[0][0]][0] and r < track[x[0][0]][1]:
					track[x[0][0]][2] = False
				else:
					track[x[0][0]][2] = True
				if x[0][1] > track[x[0][0]][0]:
					track[x[0][0]][0] = x[0][1]
				if r < track[x[0][0]][1]:
					track[x[0][0]][1] = r
			for k in range(1, n):
				if x[k][1] != x[k - 1][1]:
					r = k + 1
				if x[k][1] > track[x[k][0]][0] or r < track[x[k][0]][1]:
					if x[k][1] > track[x[k][0]][0] and r < track[x[k][0]][1]:
						track[x[k][0]][2] = False
					else:
						track[x[k][0]][2] = True
					if x[k][1] > track[x[k][0]][0]:
						track[x[k][0]][0] = x[k][1]
					if r < track[x[k][0]][1]:
						track[x[k][0]][1] = r
		else:
			track[x[0][0]].append(x[0][1])
			track[x[0][0]].append(1)
			track[x[0][0]].append(False)
			for k in range(1, n):
				if x[k][1] != x[k - 1][1]:
					r = k + 1
				track[x[k][0]].append(x[k][1])
				track[x[k][0]].append(r)
				track[x[k][0]].append(False)
	out = 0
	for i in track:
		if i[2]:
			out += 1
	print(out)


t = int(input())

def rank(l):
	g = l[:]
	g.sort(reverse=True)
	ranks = {g[0]: 1}
	for i in range(1, len(g)):
		if g[i] != g[i - 1]:
			ranks.update({g[i]: i + 1})
	ret = [ranks[x] for x in l]
	return ret
for _ in range(t):
	(n, m) = map(int, input().split())
	ri = list(map(int, input().split()))
	rc = []
	for p in range(n):
		rc.append(list(map(int, input().split())))
	cumu = [0] * n
	prat = [1] * n
	tmax = [0] * n
	rmax = [-1] * n
	pran = [1] * n
	for i in range(m):
		for j in range(n):
			ri[j] += rc[j][i]
			if ri[j] > tmax[j]:
				tmax[j] = ri[j]
				prat[j] = i + 1
		rnks = rank(ri)
		for j in range(n):
			if rnks[j] < rmax[j] or rmax[j] < 0:
				pran[j] = i + 1
				rmax[j] = rnks[j]
	ans = 0
	for i in range(n):
		if pran[i] != prat[i]:
			ans += 1
	print(ans)


from sys import stdin, stdout
from collections import defaultdict
import math
from bisect import bisect
input = stdin.readline
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l = list(map(int, input().split()))
	cur = [[-100000, n + 1] for i in range(n)]
	l1 = [[] for i in range(m)]
	ans = [[0, 0] for i in range(n)]
	for i in range(n):
		l2 = list(map(int, input().split()))
		for j in range(m):
			l[i] += l2[j]
			l1[j].append([l[i], i])
	for i in l1:
		i.sort(reverse=True)
	for i in range(m):
		c = 1
		c3 = 1
		num = l1[i][0][1]
		rat = cur[num][0]
		rank = cur[num][1]
		c1 = l1[i][0][0]
		c2 = 1
		if c1 > rat:
			cur[num][0] = c1
			ans[num][0] = i
		if c2 < rank:
			cur[num][1] = c2
			ans[num][1] = i
		for j in range(1, n):
			if l1[i][j - 1][0] > l1[i][j][0]:
				c += c3
				c3 = 1
			else:
				c3 += 1
			num = l1[i][j][1]
			rat = cur[num][0]
			rank = cur[num][1]
			c1 = l1[i][j][0]
			c2 = c
			if c1 > rat:
				cur[num][0] = c1
				ans[num][0] = i
			if c2 < rank:
				cur[num][1] = c2
				ans[num][1] = i
	c = 0
	for i in ans:
		if i[0] != i[1]:
			c += 1
	print(c)


import numpy as np

def rate(arr):
	d = {}
	for i in range(len(arr)):
		if arr[i] in d:
			d[arr[i]].append(i + 1)
		else:
			d[arr[i]] = [i + 1]
	nd = {}
	rank = 1
	for item in sorted(d, reverse=True):
		for i in d[item]:
			nd[i] = rank
		rank = rank + len(d[item])
	return nd
for test in range(int(input())):
	(n, m) = map(int, input().split())
	start = list(map(int, input().split()))
	month_changes = []
	for _ in range(n):
		changes = list(map(int, input().split()))
		month_changes.append(changes)
	month_changes = np.array(month_changes)
	players = np.zeros((n, m))
	players[:, 0] = start + month_changes[:, 0]
	for i in range(1, m):
		players[:, i] = players[:, i - 1] + month_changes[:, i]
	max_ratings = [np.argmax(players[i]) + 1 for i in range(n)]
	ratings_each_month = [rate(players[:, i]) for i in range(m)]
	l = []
	for player in range(n):
		l.append([(ratings_each_month[j][player + 1], j + 1) for j in range(m)])
	gogo = []
	for player in l:
		gogo.append(min(player, key=lambda x: x[0] + 1e-05 * x[1])[1])
	ct = 0
	for i in range(len(gogo)):
		ct += int(gogo[i] != max_ratings[i])
	print(ct)


t = int(input())
while t > 0:
	t = t - 1
	[n, m] = input().split()
	n = int(n)
	m = int(m)
	r = input().split()
	a = []
	b = []
	peak_rate = [0] * n
	peak_rank = [0] * n
	for i in range(0, n):
		r[i] = int(r[i])
	for j in range(0, n):
		x = input().split()
		for i in range(0, m):
			x[i] = int(x[i])
		x[0] = r[j] + x[0]
		for i in range(1, m):
			x[i] = x[i - 1] + x[i]
		peak_rate[j] = x.index(max(x))
		a.append(x)
	for i in range(0, n):
		b.append([0] * m)
	x = []
	for i in range(0, m):
		x = []
		for j in range(0, n):
			x.append([a[j][i], j])
		x.sort(key=lambda k: k[0], reverse=True)
		b[x[0][1]][i] = 0
		for j in range(1, n):
			if x[j][0] == x[j - 1][0]:
				b[x[j][1]][i] = b[x[j - 1][1]][i]
			else:
				b[x[j][1]][i] = j
	count = 0
	for i in range(0, n):
		if b[i].index(min(b[i])) == peak_rate[i]:
			count = count + 1
	print(n - count)


n = int(input())
for k in range(n):
	lst = input().split()
	N = int(lst[0])
	M = int(lst[1])
	rating = []
	rating.append(list(map(int, input().split())))
	change = []
	for i in range(N):
		change.append([])
		change[i] = list(map(int, input().split()))
	for i in range(1, M + 1):
		rating.append([])
		for j in range(0, N):
			rating[i].append(rating[i - 1][j] + change[j][i - 1])
	MaxRating = []
	MaxRatingMonth = []
	for j in range(N):
		MaxRating.append(rating[1][j])
		MaxRatingMonth.append(1)
		for i in range(2, M + 1):
			if rating[i][j] > MaxRating[j]:
				MaxRating[j] = rating[i][j]
				MaxRatingMonth[j] = i
	Ranking = []
	MaxRankingMonth = []
	newrating = []
	for i in range(1, M + 1):
		newrating.append(sorted(rating[i], reverse=True))
		Ranking.append([])
		for j in range(N):
			Ranking[i - 1].append(newrating[i - 1].index(rating[i][j]) + 1)
	MaxRankingMonth = []
	MaxRanking = []
	for j in range(N):
		MaxRankingMonth.append(1)
		MaxRanking.append(Ranking[0][j])
		for i in range(2, M + 1):
			if Ranking[i - 1][j] < MaxRanking[j]:
				MaxRanking[j] = Ranking[i - 1][j]
				MaxRankingMonth[j] = i
	count = 0
	for i in range(N):
		if MaxRankingMonth[i] != MaxRatingMonth[i]:
			count += 1
	print(count)


def sortSecond(val):
	return val[0]
t = int(input())
while t:
	t -= 1
	(n, m) = map(int, input().split())
	R = list(map(int, input().split()))
	tt = n
	i = 0
	j = 0
	mat = []
	while tt:
		tt -= 1
		l = list(map(int, input().split()))
		mat.append(l)
	high_rate = [0] * n
	high_rank_month = [[0 for a in range(0, m)] for b in range(0, n)]
	count = 0
	for i in range(0, n):
		flag = 0
		maxi = -1
		current = 0
		for j in range(0, m):
			if j == 0:
				current = R[i] + mat[i][j]
				mat[i][j] = current
			else:
				current += mat[i][j]
				mat[i][j] = current
			if current > maxi:
				maxi = current
				flag = j
		high_rate[i] = flag
	for i in range(0, m):
		maxi = -1
		copy = []
		l = []
		for j in range(0, n):
			l.append((mat[j][i], j))
		l.sort(reverse=True, key=sortSecond)
		kk = 1
		high_rank_month[l[0][1]][i] = kk
		for a in range(1, n):
			kk += 1
			if l[a][0] != l[a - 1][0]:
				high_rank_month[l[a][1]][i] = kk
			else:
				high_rank_month[l[a][1]][i] = high_rank_month[l[a - 1][1]][i]
	count = 0
	for i in range(0, n):
		temp = high_rate[i]
		ind = 0
		mini = 184564513215
		for j in range(0, m):
			if mini > high_rank_month[i][j]:
				mini = high_rank_month[i][j]
				ind = j
		if temp != ind:
			count += 1
	print(count)


import sys
import heapq
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().strip().split())
	rt = list(map(int, input().strip().split()))
	cg = [[None] * n for i in range(m)]
	for i in range(n):
		plRt = list(map(int, input().strip().split()))
		cg[0][i] = rt[i] + plRt[0]
		for j in range(1, m):
			cg[j][i] = cg[j - 1][i] + plRt[j]
	rank = [[None] * n for i in range(m)]
	for i in range(m):
		monthRt = cg[i]
		hp = []
		for j in range(n):
			heapq.heappush(hp, [-monthRt[j], j])
		rnk = 0
		ind = 0
		oldRating = None
		for j in range(n):
			(rating, index) = heapq.heappop(hp)
			rating *= -1
			ind += 1
			if oldRating != rating:
				rnk = ind
			rank[i][index] = rnk
			oldRating = rating
	c = 0
	for i in range(n):
		mxr_index = None
		mx_index = None
		mxr = -sys.maxsize
		mx = sys.maxsize
		for j in range(m):
			if cg[j][i] > mxr:
				mxr_index = j
				mxr = cg[j][i]
			if rank[j][i] < mx:
				mx_index = j
				mx = rank[j][i]
		if mx_index != mxr_index:
			c += 1
	print(c)


import sys
t = int(input())
for _ in range(t):
	(N, M) = list(map(int, input().split()))
	C = [[0 for x in range(N)] for y in range(M + 1)]
	C[0] = list(map(int, input().split()))
	rating = [0 for x in range(N)]
	rank = [sys.maxsize for x in range(N)]
	for i in range(N):
		change = list(map(int, input().split()))
		rate = 0
		month = 0
		for j in range(1, M + 1):
			C[j][i] = C[j - 1][i] + change[j - 1]
			if C[j][i] > rate:
				rate = C[j][i]
				month = j
		rating[i] = month
	mon = [0 for x in range(N)]
	for i in range(1, M + 1):
		X = sorted(C[i], reverse=True)
		for j in range(N):
			temp = X.index(C[i][j])
			if temp < rank[j]:
				rank[j] = temp
				mon[j] = i
	pl = 0
	for i in range(N):
		if mon[i] == rating[i]:
			pl += 1
	print(N - pl)


for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ir = list(map(int, input().split()))
	grid = []
	prat = []
	pran = []
	for i in range(n):
		rc = list(map(int, input().split()))
		temp = [ir[i]]
		for x in rc:
			temp.append(temp[-1] + x)
		grid.append(temp)
		maxi = float('-inf')
		for (idx, j) in enumerate(temp[1:]):
			if maxi < j:
				maxi = j
				month = idx + 1
		prat.append(month)
	tgrid = list(zip(*grid))
	tr = []
	for (idx, each) in enumerate(tgrid[1:]):
		temp = sorted(each, reverse=True)
		rank = dict()
		rank[temp[0]] = 1
		prev = [temp[0], 1]
		for i in temp[1:]:
			prev[1] += 1
			if i != prev[0]:
				prev[0] = i
				rank[i] = prev[1]
		if not tr:
			for x in each:
				tr.append(rank[x])
				pran.append(1)
		else:
			for (e, x) in enumerate(each):
				if tr[e] > rank[x]:
					tr[e] = rank[x]
					pran[e] = idx + 1
	ans = 0
	for i in range(n):
		if prat[i] != pran[i]:
			ans += 1
	print(ans)


t = int(input())
while t:
	t = t - 1
	(n, m) = map(int, input().split())
	R = list(map(int, input().split()))
	a = []
	for i in range(n):
		Temp = list(map(int, input().split()))
		a.append(Temp)
	RI = []
	peakrating = [-1 * float('inf') for x in range(n)]
	peakrating_month = [-1 for x in range(n)]
	peakrank = [float('inf') for x in range(n)]
	peakrank_month = [-1 for x in range(n)]
	for i in range(len(R)):
		RI.append([R[i], i])
	for i in range(m):
		for j in range(n):
			RI[j][0] += a[RI[j][1]][i]
		RI = sorted(RI, key=lambda x: x[0])
		RI = RI[::-1]
		prev = None
		prev_index = None
		for k in range(len(RI)):
			if RI[k][0] != prev:
				prev = RI[k][0]
				prev_index = k
				rnk = k
			else:
				rnk = prev_index
			x = RI[k]
			if peakrank[x[1]] > rnk:
				peakrank[x[1]] = rnk
				peakrank_month[x[1]] = i
			if peakrating[x[1]] < x[0]:
				peakrating[x[1]] = x[0]
				peakrating_month[x[1]] = i
	ans = 0
	for i in range(n):
		if peakrating_month[i] != peakrank_month[i]:
			ans += 1
	print(ans)


from sys import stdin, stdout, setrecursionlimit
from math import gcd, ceil, sqrt
from collections import Counter, deque
from bisect import bisect_left, bisect_right
ii1 = lambda : int(stdin.readline().strip())
is1 = lambda : stdin.readline().strip()
iia = lambda : list(map(int, stdin.readline().strip().split()))
isa = lambda : stdin.readline().strip().split()
setrecursionlimit(100000)
mod = 1000000007
tc = ii1()
for _ in range(tc):
	(n, m) = iia()
	init = iia()
	arr = []
	for i in range(n):
		arr.append(iia())
	for i in range(n):
		cur = init[i]
		for j in range(m):
			arr[i][j] += cur
			cur = arr[i][j]
	rank = [[0 for i in range(m)] for j in range(n)]
	for i in range(m):
		temp = []
		for j in range(n):
			temp.append(arr[j][i])
		temp = sorted(list(temp), reverse=True)
		d = {}
		for k in range(len(temp)):
			if temp[k] not in d:
				d[temp[k]] = k + 1
		cur = 1
		for j in range(n):
			rank[j][i] = d[arr[j][i]]
	count = 0
	for i in range(n):
		if arr[i].index(max(arr[i])) != rank[i].index(min(rank[i])):
			count += 1
	print(count)


for i in range(int(input())):
	(n, m) = map(int, input().split())
	ratings = list(map(int, input().split()))
	ratings_after = [[] for _ in range(m)]
	max_rating_months = []
	for i in range(n):
		curr_changes = list(map(int, input().split()))
		best_rating = ratings[i] + curr_changes[0]
		(curr_r, rat_month) = (best_rating, 0)
		ratings_after[0].append(curr_r)
		for k in range(1, m):
			curr_r += curr_changes[k]
			if curr_changes[k] > 0:
				if curr_r > best_rating:
					best_rating = curr_r
					rat_month = k
			ratings_after[k].append(curr_r)
		max_rating_months.append(rat_month)
	rankings = [[] for _ in range(n)]
	for x in range(m):
		month = ratings_after[x]
		new_mon = sorted(month, reverse=True)
		for y in range(n):
			rankings[y].append(new_mon.index(month[y]))
	(index, counter) = (0, 0)
	for player in rankings:
		best = player.index(min(player))
		if best != max_rating_months[index]:
			counter += 1
		index += 1
	print(counter)


from collections import Counter

def changeArr(input1):
	newArray = input1.copy()
	newArray.sort(reverse=True)
	ranks = {}
	for i in range(0, len(newArray)):
		element = newArray[i]
		if element not in ranks:
			ranks[element] = i + 1
	for index in range(len(input1)):
		element = input1[index]
		input1[index] = ranks[input1[index]]
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	r = list(map(int, input().split()))
	c = [list(map(int, input().split())) for i in range(n)]
	for i in range(n):
		for j in range(m):
			if j == 0:
				c[i][j] += r[i]
			else:
				c[i][j] += c[i][j - 1]
	m1 = []
	for i in range(n):
		m1.append(c[i].index(max(c[i])) + 1)
	m2 = []
	g = []
	for i in range(m):
		temp = []
		for j in range(n):
			temp.append(c[j][i])
		changeArr(temp)
		g.append(temp)

	def transpose(A, B):
		for i in range(n):
			for j in range(m):
				B[i][j] = A[j][i]
	B = [[0 for x in range(m)] for y in range(n)]
	transpose(g, B)
	for i in range(n):
		m2.append(B[i].index(min(B[i])) + 1)
	count = 0
	for i in range(n):
		if m1[i] != m2[i]:
			count += 1
	print(count)


for _ in range(int(input())):
	(n, m) = (int(x) for x in input().split())
	ini_data = [int(x) for x in input().split()]
	data = []
	ans = {}
	for i in range(n):
		data.append([i])
		ini_1 = [int(x) for x in input().split()]
		data[i] += [ini_data[i] + ini_1[0]]
		for j in range(1, m):
			data[i] += [data[i][j] + ini_1[j]]
	for i in range(n):
		ans[i] = [data[i][1:].index(max(data[i][1:])) + 1]
	for i in range(1, m + 1):
		data.sort(key=lambda x: x[i], reverse=True)
		if len(ans[data[0][0]]) == 1:
			ans[data[0][0]].append(1)
			ans[data[0][0]].append(i)
		elif ans[data[0][0]][1] > 1:
			ans[data[0][0]][1] = 1
			ans[data[0][0]][2] = i
		rank = 1
		for j in range(1, n):
			if len(ans[data[j][0]]) == 1:
				if data[j][i] == data[j - 1][i]:
					ans[data[j][0]].append(ans[data[j - 1][0]][1])
					ans[data[j][0]].append(i)
				else:
					ans[data[j][0]].append(j + 1)
					ans[data[j][0]].append(i)
			elif data[j][i] == data[j - 1][i] and rank < ans[data[j][0]][1]:
				ans[data[j][0]][1] = rank
				ans[data[j][0]][2] = i
			elif data[j][i] < data[j - 1][i]:
				if j + 1 < ans[data[j][0]][1]:
					ans[data[j][0]][1] = j + 1
					ans[data[j][0]][2] = i
				rank = j + 1
	t = 0
	for i in ans.values():
		if i[0] != i[2]:
			t += 1
	print(t)


import sys
t = int(input())
while t:
	(n, m) = map(int, input().split())
	initr = list(map(int, input().split()))
	a = []
	for i in range(n):
		b = list(map(int, input().split()))
		a.append(b)
	for i in range(n):
		for j in range(m):
			if j == 0:
				a[i][j] = initr[i] + a[i][j]
			else:
				a[i][j] = a[i][j - 1] + a[i][j]
	bestr = []
	for i in range(n):
		maxi = -1 * (sys.maxsize + 1)
		mapp = -1
		for j in range(m):
			if maxi < a[i][j]:
				maxi = a[i][j]
				mapp = j
		bestr.append(mapp)
	d = dict()
	rm = []
	for i in range(m):
		ll = []
		for j in range(n):
			ll.append(a[j][i])
		ll = sorted(ll, reverse=1)
		rank = 1
		prev = ll[0]
		d[ll[0]] = 1
		count = 1
		for k in range(1, n):
			if prev != ll[k]:
				rank += count
				d[ll[k]] = rank
				prev = ll[k]
				count = 1
			else:
				count += 1
		z = []
		for j in range(n):
			z.append(d[a[j][i]])
		rm.append(z)
	bestrank = []
	for i in range(n):
		mi = sys.maxsize
		mappr = -1
		for j in range(m):
			if mi > rm[j][i]:
				mi = rm[j][i]
				mappr = j
		bestrank.append(mappr)
	ans = 0
	for i in range(n):
		if bestr[i] != bestrank[i]:
			ans += 1
	print(ans)
	t -= 1


from collections import defaultdict
import math
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = [[0] * n for i in range(m + 1)]
	b = list(map(int, input().split()))
	hrank = [float('inf')] * n
	hrating = [0] * n
	hrankm = [0] * n
	hratingm = [0] * n
	for i in range(n):
		a[0][i] = b[i]
	for i in range(n):
		b = list(map(int, input().split()))
		for j in range(1, m + 1):
			a[j][i] = b[j - 1] + a[j - 1][i]
	for i in range(1, m + 1):
		b = a[i]
		b = list(enumerate(b))
		b.sort(key=lambda x: x[1], reverse=True)
		rank = 1
		for j in range(n):
			if j == 0:
				rank = 1
			elif b[j][1] != b[j - 1][1]:
				rank = j + 1
			if hrank[b[j][0]] > rank:
				hrank[b[j][0]] = rank
				hrankm[b[j][0]] = i
			if hrating[b[j][0]] < b[j][1]:
				hrating[b[j][0]] = b[j][1]
				hratingm[b[j][0]] = i
	coun = 0
	for i in range(n):
		if hratingm[i] != hrankm[i]:
			coun += 1
	print(coun)


from collections import Counter
import heapq

def checkUser(change, n, m):
	count = 0
	for i in range(n):
		x = min(change[i][0])
		x = change[i][0].index(x)
		y = max(change[i][1])
		y = change[i][1].index(y)
		if x != y:
			count += 1
	return count

def rr():
	(n, m) = input().split()
	n = int(n)
	m = int(m)
	ir = list(map(int, input().split()))
	change = []
	for i in range(n):
		x = list(map(int, input().split()))
		change.append([[-1] * m, x])
	for mon in range(m):
		currRating = []
		for u in range(n):
			if mon == 0:
				ur = ir[u]
			else:
				ur = change[u][1][mon - 1]
			change[u][1][mon] += ur
			currRating.append(change[u][1][mon])
		count = Counter(currRating)
		heap = []
		for (i, j) in count.items():
			heapq.heappush(heap, [-i, j])
		currRating = {}
		count = 1
		for i in range(len(heap)):
			x = heapq.heappop(heap)
			currRating[-x[0]] = count
			count += x[1]
		for u in range(n):
			change[u][0][mon] = currRating[change[u][1][mon]]
	return checkUser(change, n, m)
for _ in range(int(input())):
	print(rr())


t = int(input())
import math

def fun(l):
	ind = [i for i in range(len(l))]
	sind = zip(l, ind)
	sind = sorted(sind, reverse=True)
	l = [x for (x, y) in sind]
	ind = [x for (y, x) in sind]
	r = 1
	count = 1
	res = {}
	res[ind[0]] = 1
	score = l[0]
	for i in range(1, len(l)):
		if l[i] == score:
			res[ind[i]] = r
		else:
			r = count + 1
			res[ind[i]] = r
			score = l[i]
		count += 1
	return res
while t != 0:
	t -= 1
	(n, m) = map(int, input().split())
	init = list(map(int, input().split()))
	M = []
	for i in range(n):
		temp = list(map(int, input().split()))
		M.append(temp)
	for i in range(n):
		s = init[i]
		for j in range(m):
			s += M[i][j]
			M[i][j] = s
	l1 = [0] * n
	for i in range(n):
		mi = -1
		for j in range(m):
			if M[i][j] > mi:
				l1[i] = j
				mi = M[i][j]
	l2 = [0] * n
	mi = [math.inf] * n
	for i in range(m):
		l3 = [row[i] for row in M]
		res = fun(l3)
		for j in range(n):
			if res[j] < mi[j]:
				mi[j] = res[j]
				l2[j] = i
	count = 0
	for i in range(n):
		if l1[i] != l2[i]:
			count += 1
	print(count)


class Student:

	def __init__(self, rating):
		self.initial_rating = rating
		self.ratings = []
		self.ranks = []
for _ in range(int(input())):
	(N, M) = list(map(int, input().split()))
	_list = []
	ratings = list(map(int, input().split()))
	for i in ratings:
		tmp = Student(i)
		_list.append(tmp)
	for i in range(N):
		_list2 = list(map(int, input().split()))
		for j in range(M):
			if len(_list[i].ratings) == 0:
				_list[i].ratings.append(_list[i].initial_rating + _list2[j])
			else:
				_list[i].ratings.append(_list[i].ratings[-1] + _list2[j])
	for i in range(M):
		_l = sorted(_list, key=lambda x: x.ratings[i], reverse=True)
		_l[0].ranks.append(1)
		for k in range(1, N):
			if _l[k].ratings[i] < _l[k - 1].ratings[i]:
				_l[k].ranks.append(k + 1)
			else:
				_l[k].ranks.append(_l[k - 1].ranks[i])
	count = 0
	for i in _list:
		if i.ratings.index(max(i.ratings)) != i.ranks.index(min(i.ranks)):
			count += 1
	print(count)


t = int(input())
for i in range(t):
	in_ = input().split()
	n = int(in_[0])
	m = int(in_[1])
	rank = n * [-1]
	rat = n * [-1]
	in_rat = [int(e) for e in input().split()]
	ra = []
	for e in range(m):
		ra.append([])
	for e in range(n):
		a = [int(ee) for ee in input().split()]
		in_ = in_rat[e]
		lc = float('-inf')
		max_rat = 0
		for el in range(len(a)):
			in_ = in_ + a[el]
			ra[el].append(in_)
			if in_ > lc:
				lc = in_
				max_rat = el
		rat[e] = max_rat
	rank_c = n * [n + 1]
	for ind in range(len(ra)):
		e = ra[ind]
		T = [[e[i], i] for i in range(len(e))]
		T.sort(key=lambda x: x[0], reverse=True)
		T[0].append(1)
		for el in range(1, len(T)):
			if T[el][0] == T[el - 1][0]:
				T[el].append(T[el - 1][2])
			else:
				T[el].append(el + 1)
		for el in T:
			inde = el[1]
			cur = el[2]
			if rank_c[inde] > cur:
				rank_c[inde] = cur
				rank[inde] = ind
	res = 0
	for e in range(n):
		if rank[e] != rat[e]:
			res += 1
	print(res)


import sys
import math

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

def fin():
	return sys.stdin.readline().strip()
mod = pow(10, 9) + 7
t = int(fin())
while t > 0:
	t -= 1
	(n, m) = map(int, fin().split())
	init = [(int(x), 1) for x in fin().split()]
	temp = []
	temp.append(init)
	for i in range(m):
		temp.append([0] * n)
	ans = {}
	for i in range(n):
		end = [int(x) for x in fin().split()]
		ans[i] = [temp[1][i], 1]
		for j in range(1, m + 1):
			temp[j][i] = (temp[j - 1][i][0] + end[j - 1], i)
			if temp[j][i][0] > ans[i][0]:
				ans[i][0] = temp[j][i][0]
				ans[i][1] = j
	ranking = {}
	for i in range(1, m + 1):
		rank = 1
		freq = 1
		temp[i].sort(reverse=True)
		curr = temp[i][0][1]
		if curr not in ranking:
			ranking[curr] = [rank, i]
		elif ranking[curr][0] > rank:
			ranking[curr] = [rank, i]
		for j in range(1, n):
			if temp[i][j][0] == temp[i][j - 1][0]:
				freq += 1
				curr = temp[i][j][1]
				if curr not in ranking:
					ranking[curr] = [rank, i]
				elif ranking[curr][0] > rank:
					ranking[curr] = [rank, i]
			else:
				rank += freq
				freq = 1
				curr = temp[i][j][1]
				if curr not in ranking:
					ranking[curr] = [rank, i]
				elif ranking[curr][0] > rank:
					ranking[curr] = [rank, i]
	fa = 0
	for i in range(n):
		if ranking[i][1] != ans[i][1]:
			fa += 1
	print(fa)


def fun(rankings, n, m):
	best_rating_month = [max(range(m), key=lambda x: (player[x], -x)) for player in rankings]
	best_rank_month = fun2(rankings, n, m)
	count = 0
	for i in range(n):
		if best_rank_month[i] != best_rating_month[i]:
			count += 1
	return count

def fun2(rankings, n, m):
	month_wise = list(zip(*rankings))
	player = []
	rank = [[-1 for j in range(m)] for i in range(n)]
	month = []
	for j in range(m):
		pseudorank = sorted(range(n), reverse=True, key=lambda x: (month_wise[j][x], -x))
		lastranking = 0
		rank[pseudorank[0]][j] = 0
		for i_ in range(1, n):
			if month_wise[j][pseudorank[i_]] == month_wise[j][pseudorank[i_ - 1]]:
				rank[pseudorank[i_]][j] = lastranking
			else:
				rank[pseudorank[i_]][j] = i_
				lastranking = i_
	ans = [min(range(m), key=lambda i: (player[i], i)) for player in rank]
	return ans
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ini_r = list(map(int, input().split()))
	rankings = []
	for i in range(n):
		player = []
		change = list(map(int, input().split()))
		curr_r = ini_r[i]
		for j in range(m):
			curr_r += change[j]
			player.append(curr_r)
		rankings.append(player)
	print(fun(rankings, n, m))


try:
	import sys
	MAX = sys.maxsize

	def rankUpdater(d):
		x = list(d.values())
		y = list(d.keys())
		y.sort(key=lambda x: d[x][0], reverse=True)
		rank = 1
		for i in range(len(y)):
			if i == 0:
				d[y[i]][1] = rank
			elif d[y[i]][0] == d[y[i - 1]][0]:
				d[y[i]][1] = d[y[i - 1]][1]
			else:
				d[y[i]][1] = rank
			rank += 1

	def sol(initial, changes):
		hash = {}
		mainData = {}
		maxData = {}
		for i in range(len(initial)):
			maxData[i] = [-1, -1, -1, MAX]
		for j in range(len(changes[0])):
			for i in range(len(changes)):
				if j == 0:
					mainData[i] = [initial[i] + changes[i][j], 0]
				else:
					mainData[i][0] += changes[i][j]
			rankUpdater(mainData)
			for i in mainData:
				if maxData[i][2] < mainData[i][0]:
					maxData[i][2] = mainData[i][0]
					maxData[i][0] = j + 1
				if maxData[i][3] > mainData[i][1]:
					maxData[i][3] = mainData[i][1]
					maxData[i][1] = j + 1
		ans = 0
		for i in maxData:
			if maxData[i][0] != maxData[i][1]:
				ans += 1
		print(ans)
	k = int(input())
	for i in range(k):
		(n, m) = list(map(int, input().split(' ')))
		initial = list(map(int, input().split(' ')))
		changes = []
		for i in range(n):
			x = list(map(int, input().split(' ')))
			changes.append(x)
		sol(initial, changes)
except:
	pass


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

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

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

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

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

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

def solve():
	for _ in range(ii()):
		(n, m) = mi()
		a = li()
		ratting = [[] for i in range(n)]
		ranking = [[] for i in range(n)]
		for i in range(n):
			x = a[i]
			b = li()
			mx = -inf
			for j in range(m):
				x += b[j]
				ratting[i].append(x)
		for i in range(m):
			a = []
			for j in range(n):
				a.append(ratting[j][i])
			freq = {}
			for j in a:
				if j not in freq:
					freq[j] = 0
				freq[j] += 1
			x = []
			for j in freq.keys():
				x.append([j, freq[j]])
			x.sort(reverse=True)
			c = 1
			m1 = {}
			for j in x:
				m1[j[0]] = c
				c += j[1]
			for j in range(n):
				ranking[j].append(m1[a[j]])
		c = 0
		for i in range(n):
			mx1 = -inf
			for j in ratting[i]:
				mx1 = max(mx1, j)
			mx2 = inf
			for j in ranking[i]:
				mx2 = min(mx2, j)
			f = 1
			f1 = 0
			for j in range(m):
				if ratting[i][j] == mx1 and ranking[i][j] == mx2 and (f1 == 0):
					f = 0
					break
				if ranking[i][j] == mx2 or ratting[i][j] == mx1:
					f1 = 1
			c += f
		print(c)
if file:
	if path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	else:
		input = sys.stdin.readline
solve()


t = int(input())
while t:
	t -= 1
	(n, m) = input().split()
	(n, m) = (int(n), int(m))
	R = [int(ri) for ri in input().split()]
	delR = [0] * n
	for i in range(0, n):
		delR[i] = [int(ai) for ai in input().split()]
	peakR = []
	for i in range(0, n):
		peakR.append([-1, -1])
	peakRn = []
	for i in range(0, n):
		peakRn.append([n + 1, -1])
	for mon in range(0, m):
		currR = []
		for p in range(0, n):
			R[p] += delR[p][mon]
			if R[p] > peakR[p][0]:
				peakR[p] = [R[p], mon]
			currR.append([R[p], p])
		currR.sort(reverse=True)
		pranks = [0] * n
		pranks[currR[0][1]] = 1
		for i in range(1, len(currR)):
			if currR[i][0] == currR[i - 1][0]:
				pranks[currR[i][1]] = pranks[currR[i - 1][1]]
				continue
			pranks[currR[i][1]] = i + 1
		for i in range(0, n):
			if pranks[i] < peakRn[i][0]:
				peakRn[i] = [pranks[i], mon]
	ans = 0
	for i in range(0, n):
		if peakR[i][1] != peakRn[i][1]:
			ans += 1
	print(ans)


from typing import List

def ratingsAndRankings(N: int, initial_ratings: List[int], changes: List[List[int]]) -> int:
	max_ratings = [[1799, -1] for _ in range(N)]
	max_rankings = [[501, -1] for _ in range(N)]
	for i in range(M):
		for j in range(N):
			initial_ratings[j] += changes[j][i]
			if initial_ratings[j] > max_ratings[j][0]:
				max_ratings[j][0] = initial_ratings[j]
				max_ratings[j][1] = i + 1
		copy = initial_ratings[:]
		copy.sort(reverse=True)
		dic = {}
		for j in range(len(copy)):
			if copy[j] not in dic:
				dic[copy[j]] = j + 1
		for j in range(len(initial_ratings)):
			if dic[initial_ratings[j]] < max_rankings[j][0]:
				max_rankings[j][0] = dic[initial_ratings[j]]
				max_rankings[j][1] = i + 1
	count = 0
	for i in range(N):
		if max_ratings[i][1] != max_rankings[i][1]:
			count += 1
	return count
test_cases = int(input())
for _ in range(test_cases):
	first_line = list(map(int, input().split(' ')))
	(N, M) = (first_line[0], first_line[1])
	initial_ratings = list(map(int, input().split(' ')))
	changes = []
	for i in range(N):
		changes.append(list(map(int, input().split(' '))))
	print(ratingsAndRankings(N, initial_ratings, changes))


def bestrating(l):
	mx = float('-inf')
	mxid = -1
	for (i, v) in enumerate(l):
		if v > mx:
			mx = v
			mxid = i
	return mxid

def bestranking(l):
	mn = float('inf')
	mnid = -1
	for (i, v) in enumerate(l):
		if v < mn:
			mn = v
			mnid = i
	return mnid

def calculate_rank(vector):
	a = {}
	rank = 1
	for num in reversed(sorted(vector)):
		if num not in a:
			a[num] = rank
		rank = rank + 1
	return [a[i] for i in vector]
t = int(input())
for i in range(t):
	(n, m) = map(int, input().split())
	initials = list(map(int, input().split()))
	pdata = {i: [[], []] for i in range(n)}
	mdata = {i: [] for i in range(m)}
	for i in range(n):
		io = list(map(int, input().split()))
		prev = initials[i]
		for (idx, change) in enumerate(io):
			pdata[i][0].append(prev + change)
			prev = pdata[i][0][-1]
			mdata[idx].append(prev)
	for i in range(m):
		l = mdata[i]
		rk = calculate_rank(l)
		for j in range(n):
			pdata[j][1].append(rk[j])
	finalcount = 0
	for player in pdata.keys():
		rat = bestrating(pdata[player][0])
		rank = bestranking(pdata[player][1])
		if rat != rank:
			finalcount += 1
	print(finalcount)


from sys import stdin, stdout
from bisect import *
from itertools import accumulate
for i in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	r = []
	for i in range(n):
		b = list(accumulate(map(int, input().split())))
		r.append(list((b[x] + a[i] for x in range(m))))
	a = []
	for i in range(m):
		b = []
		for j in range(n):
			b.append(-r[j][i])
		a.append(sorted(b))
	c = {}
	for i in range(n):
		for j in range(m):
			k = bisect_left(a[j], -r[i][j]) + 1
			try:
				if c[i][0] > k:
					c[i] = (k, j)
			except:
				c[i] = (k, j)
	ans = 0
	for i in range(n):
		m1 = max(r[i])
		if c[i][1] != r[i].index(m1):
			ans += 1
	print(ans)


from collections import Counter
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	a = list(map(int, input().split()))
	ratings = []
	for i in range(n):
		r = list(map(int, input().split()))
		ratings.append(r)
	for j in range(n):
		k = a[j]
		for i in range(m):
			ratings[j][i] = k + ratings[j][i]
			k = ratings[j][i]
	rank = []
	for i in range(n):
		p = ratings[i].copy()
		rank.append(p)
	for j in range(m):
		res = []
		for i in range(n):
			res.append(rank[i][j])
		res.sort(reverse=True)
		p = Counter(res)
		k = 1
		for i in p:
			s = p[i]
			p[i] = k
			k = k + s
		for i in range(n):
			rank[i][j] = p[rank[i][j]]
	ans = 0
	for i in range(n):
		if rank[i].index(min(rank[i])) != ratings[i].index(max(ratings[i])):
			ans += 1
	print(ans)


from collections import defaultdict
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	l = list(map(int, input().split()))
	l1 = []
	best_rating = []
	best_rank = []
	for i in range(n):
		k = list(map(int, input().split()))
		l1.append(k)
		best_rating.append([-10 ** 18, -10 ** 18])
		best_rank.append([10 ** 18, 10 ** 18])
	ans = 0
	for i in range(m):
		la = []
		for j in range(n):
			s = l1[j][i] + l[j]
			z = best_rating[j][0]
			best_rating[j][0] = max(s, best_rating[j][0])
			if best_rating[j][0] != z:
				best_rating[j][1] = i
			la.append((s, j))
			l[j] += l1[j][i]
		la.sort(reverse=True)
		(a, b) = la[0]
		rank = 0
		if best_rank[b][0] > rank:
			best_rank[b][1] = i
			best_rank[b][0] = rank
		prev = 0
		for k in range(1, len(la)):
			(a, b) = la[k]
			(c, d) = la[k - 1]
			if c > a:
				if best_rank[b][0] > k:
					best_rank[b][1] = i
					best_rank[b][0] = k
				prev = k
			elif best_rank[b][0] > prev:
				best_rank[b][1] = i
				best_rank[b][0] = prev
	for i in range(n):
		(z1, z2) = (best_rating[i][1], best_rank[i][1])
		if z1 != z2:
			ans += 1
	print(ans)


def rankit(arr, n):
	arr = list(arr)
	for i in range(n):
		arr[i] = [i, arr[i]]
	arr.sort(key=lambda x: x[1], reverse=True)
	sp = 1
	x = [0] * n
	for i in range(n):
		if i and arr[i - 1][1] == arr[i][1]:
			x[arr[i][0]] = x[arr[i - 1][0]]
		else:
			x[arr[i][0]] = i + 1
	return x
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	ir = list(map(int, input().split()))
	rl = list()
	rankl = list()
	for i in range(n):
		tem = list(map(int, input().split()))
		s = 0
		mx = -999999
		trac = 0
		for x in range(m):
			s += tem[x]
			tem[x] = s
			if s > mx:
				mx = s
				trac = x + 1
		rl.append(trac)
		for x in range(m):
			tem[x] += ir[i]
		rankl.append(tem)
	rankl = list(zip(*rankl))
	p = list()
	for i in range(m):
		p.append(rankit(rankl[i], n))
	rankl = list(zip(*p))
	p.clear()
	for i in range(n):
		mn = 99999
		trac = 0
		for x in range(m):
			if rankl[i][x] < mn:
				mn = rankl[i][x]
				trac = x + 1
			if mn == 1:
				break
		p.append(trac)
	xc = 0
	for i in range(n):
		if p[i] != rl[i]:
			xc += 1
	print(xc)


from sys import stdin, stdout
from math import gcd, log2
import math
from collections import defaultdict
input = stdin.readline

def giveranks(l):
	res = [0] * len(l)
	dict = defaultdict(int)
	lcopy = l.copy()
	lcopy.sort(reverse=True)
	dict[lcopy[0]] = 1
	for i in range(1, len(l)):
		if lcopy[i] == lcopy[i - 1]:
			dict[lcopy[i]] = dict[lcopy[i - 1]]
		else:
			dict[lcopy[i]] = i + 1
	for i in range(len(l)):
		res[i] = dict[l[i]]
	return res
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	l = []
	ratingmonth = []
	for i in range(n):
		templist = []
		for j in range(m):
			templist.append(0)
		l.append(templist)
	for i in range(m):
		templist = []
		for j in range(n):
			templist.append(0)
		ratingmonth.append(templist)
	a = list(map(int, input().split()))
	for i in range(n):
		l[i][0] = a[i]
	for i in range(n):
		a = list(map(int, input().split()))
		for j in range(m):
			if j == 0:
				l[i][j] += a[j]
			else:
				l[i][j] = l[i][j - 1] + a[j]
	bestrankmonth = [0] * n
	for i in range(n):
		bestrankmonth[i] = 1 + l[i].index(max(l[i]))
	for i in range(m):
		templist = []
		for j in range(n):
			templist.append(l[j][i])
		ratingmonth[i] = giveranks(templist)
	ratingmonthreverse = []
	for i in range(n):
		temp = []
		for j in range(m):
			temp.append(ratingmonth[j][i])
		ratingmonthreverse.append(temp)
	bestrankingmonth = [0] * n
	for i in range(n):
		bestrankingmonth[i] = 1 + ratingmonthreverse[i].index(min(ratingmonthreverse[i]))
	count = 0
	for i in range(n):
		if bestrankmonth[i] != bestrankingmonth[i]:
			count += 1
	print(count)