This problem is given in two editions, which differ exclusively in the constraints on the number $n$.

You are given an array of integers $a[1], a[2], \dots, a[n].$ A block is a sequence of contiguous (consecutive) elements $a[l], a[l+1], \dots, a[r]$ ($1 \le l \le r \le n$). Thus, a block is defined by a pair of indices $(l, r)$.

Find a set of blocks $(l_1, r_1), (l_2, r_2), \dots, (l_k, r_k)$ such that:

  They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks $(l_i, r_i)$ and $(l_j, r_j$) where $i \neq j$ either $r_i < l_j$ or $r_j < l_i$.  For each block the sum of its elements is the same. Formally, $$a[l_1]+a[l_1+1]+\dots+a[r_1]=a[l_2]+a[l_2+1]+\dots+a[r_2]=$$ $$\dots =$$ $$a[l_k]+a[l_k+1]+\dots+a[r_k].$$  The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks $(l_1', r_1'), (l_2', r_2'), \dots, (l_{k'}', r_{k'}')$ satisfying the above two requirements with $k' > k$. 

 $\left. \begin{array}{|l|l|l|l|l|l|} \hline 4 & {1} & {2} & {2} & {1} & {5} & {3} \\ \hline \end{array} \right.$ The picture corresponds to the first example. Blue boxes illustrate blocks. 

Write a program to find such a set of blocks.


-----Input-----

The first line contains integer $n$ ($1 \le n \le 50$) — the length of the given array. The second line contains the sequence of elements $a[1], a[2], \dots, a[n]$ ($-10^5 \le a_i \le 10^5$).


-----Output-----

In the first line print the integer $k$ ($1 \le k \le n$). The following $k$ lines should contain blocks, one per line. In each line print a pair of indices $l_i, r_i$ ($1 \le l_i \le r_i \le n$) — the bounds of the $i$-th block. You can print blocks in any order. If there are multiple answers, print any of them.


-----Examples-----
Input
7
4 1 2 2 1 5 3

Output
3
7 7
2 3
4 5

Input
11
-5 -4 -3 -2 -1 0 1 2 3 4 5

Output
2
3 4
1 1

Input
4
1 1 1 1

Output
4
4 4
1 1
2 2
3 3

Difficulty: HARD
Tags: Greedy algorithms
Skill types: Greedy algorithms

Starter code:

Solutions:
from collections import defaultdict

def main():
	n = int(input())
	a = list(map(int, input().split()))
	sum_dict = defaultdict(list)
	for r in range(n):
		tmp = 0
		for l in range(r, -1, -1):
			tmp += a[l]
			sum_dict[tmp].append((l + 1, r + 1))
	(ret, blocks) = (0, [])
	for (k, v) in list(sum_dict.items()):
		(right, tmp) = (-1, 0)
		curr_list = []
		for s in v:
			if s[0] > right:
				tmp += 1
				curr_list.append(s)
				right = s[1]
		if tmp > ret:
			ret = tmp
			blocks = curr_list
	print(ret)
	for s in blocks:
		print(*s)

def __starting_point():
	main()
__starting_point()


n = int(input())
arr = list(map(int, input().split()))
dict1 = {}
for i in range(n):
	val = 0
	for j in range(i, n):
		val += arr[j]
		try:
			dict1[val].append((i, j))
		except:
			KeyError
			dict1[val] = [(i, j)]
ans = 0
ansarr = []
for i in dict1.keys():
	if len(dict1[i]) > ans:
		arr2 = []
		for j in range(len(dict1[i])):
			arr2.append((dict1[i][j][1] - dict1[i][j][0], j))
		arr2.sort()
		temp = []
		for j in range(len(arr2)):
			flag = 0
			indexi = dict1[i][arr2[j][1]][0]
			indexj = dict1[i][arr2[j][1]][1]
			for k in range(len(temp)):
				if temp[k][0] <= indexi <= temp[k][1] or temp[k][0] <= indexj <= temp[k][1] or indexi <= temp[k][0] <= indexj or (indexi <= temp[k][1] <= indexj):
					flag = 1
			if flag == 0:
				temp.append((indexi, indexj))
		if len(temp) > ans:
			ans = len(temp)
			ansarr = temp
print(ans)
finalans = []
for i in range(len(ansarr)):
	finalans.append(ansarr[i][0] + 1)
	finalans.append(ansarr[i][1] + 1)
print(*finalans)


def numInterval(listInterval):
	listInterval = sorted(listInterval, key=lambda r: r[1])
	result = []
	result.append(listInterval.pop(0))
	for inv in listInterval:
		if result[-1][1] < inv[0]:
			result.append(inv)
	return result
N = int(input())
arr = list(map(int, input().split()))
pSum = [0]
for i in arr:
	pSum.append(pSum[-1] + i)
allSums = set()
for i in range(len(pSum)):
	for j in range(i + 1, len(pSum)):
		allSums.add(pSum[j] - pSum[i])
listSums = sorted(allSums)
index = 0
invMap = {}
for i in listSums:
	invMap[i] = index
	index += 1
listInterval1 = []
for i in range(len(allSums)):
	listInterval1.append([])
for i in range(len(pSum)):
	for j in range(i + 1, len(pSum)):
		diff = pSum[j] - pSum[i]
		index1 = invMap[diff]
		listInterval1[index1].append([i, j - 1])
index = 0
maxIndex = 0
maximum = -1
for vect in listInterval1:
	tArr = numInterval(vect)
	count = len(tArr)
	if count > maximum:
		maximum = count
		maxIndex = index
	listInterval1[index] = tArr
	index += 1
print(str(maximum))
for inv in listInterval1[maxIndex]:
	print(str(inv[0] + 1) + ' ' + str(inv[1] + 1))


from itertools import accumulate

def main():
	n = int(input())
	arr = list(map(int, input().split()))
	arr_sums = [0] + list(accumulate(arr))
	blocks = {}
	for i in range(1, n + 1):
		for j in range(i):
			total = arr_sums[i] - arr_sums[j]
			if total not in blocks:
				blocks[total] = [(j + 1, i)]
			elif blocks[total][-1][1] < j + 1:
				blocks[total].append((j + 1, i))
	max_block = sorted([(i, len(x)) for (i, x) in blocks.items()], key=lambda y: (-y[1], y[0]))
	print(max_block[0][1])
	for item in blocks[max_block[0][0]]:
		print(item[0], item[1])
main()


n = int(input())
ans = []
l = [int(i) for i in input().split()]
from collections import defaultdict
d = defaultdict(list)
for i in range(n):
	sm = 0
	for j in range(i, n):
		sm += l[j]
		d[sm].append([i, j])
for sm in d:
	z = d[sm]
	z.sort(key=lambda x: x[1])
	t = [z[0]]
	for i in z:
		if i[0] <= t[-1][1]:
			continue
		t.append(i)
	if len(t) > len(ans):
		ans = t
print(len(ans))
for i in range(len(ans)):
	print(ans[i][0] + 1, ans[i][1] + 1)


from collections import defaultdict
n = int(input())
nums = list(map(int, input().split()))
freq = defaultdict(list)
for i in range(n):
	for j in range(i + 1, n + 1):
		freq[sum(nums[i:j])].append((i + 1, j))
ans = []
for k in freq:
	l = freq[k]
	l.sort(key=lambda x: x[1])
	tmp = [l[0]]
	for (i, j) in l:
		if i <= tmp[-1][1]:
			continue
		tmp.append([i, j])
	if len(tmp) > len(ans):
		ans = tmp
print(len(ans))
for (i, j) in ans:
	print(i, j)


from collections import defaultdict
n = int(input())
a = list(map(int, input().split()))
rec = defaultdict(list)
for j in range(n):
	for k in range(j, n):
		rec[sum(a[j:k + 1])].append((j, k))
ans = []
for k in rec.keys():
	tmp = []
	rec[k] = sorted(rec[k], key=lambda x: x[1])
	pre = -1
	for (a, b) in rec[k]:
		if pre >= a:
			continue
		else:
			tmp.append((a + 1, b + 1))
			pre = b
	if len(tmp) > len(ans):
		ans = tmp
print(len(ans))
for (a, b) in ans:
	print(a, b)


def func(arr):
	count = 0
	biggest = -1
	store = []
	for x in range(len(arr)):
		if arr[x][0] > biggest:
			store.append(arr[x])
			biggest = arr[x][1]
			count += 1
	return (count, store)

def main():
	n = int(input())
	arr = input().split()
	store = []
	for x in range(n):
		arr[x] = int(arr[x])
		total = 0
		for y in range(x, -1, -1):
			total += arr[y]
			bo = True
			for z in range(len(store)):
				if total == store[z][0]:
					bo = False
					store[z][1].append((y, x))
			if bo:
				store.append([total, [(y, x)]])
	biggest = 0
	big_val = []
	for x in range(len(store)):
		(test, test_s) = func(store[x][1])
		if test > biggest:
			biggest = test
			big_val = test_s
	print(biggest)
	for x in range(len(big_val)):
		print(big_val[x][0] + 1, big_val[x][1] + 1)
main()


from collections import defaultdict

def main():
	n = int(input())
	a = [int(ai) for ai in input().split()]
	pref_sums = [0] * (n + 1)
	for (i, ai) in enumerate(a):
		pref_sums[i + 1] = pref_sums[i] + ai
	block_sums = defaultdict(list)
	for j in range(1, n + 1):
		for i in range(1, j + 1):
			block_sums[pref_sums[j] - pref_sums[i - 1]].append((i, j))
	ans = []
	for A in block_sums.values():
		(res, k) = ([A[0]], 0)
		for i in range(1, len(A)):
			if A[i][0] > A[k][1]:
				res.append(A[i])
				k = i
		if len(res) > len(ans):
			ans = res
	print(len(ans))
	print('\n'.join(map(lambda s: '%d %d' % s, ans)))
main()


n = int(input())
a = list(map(int, input().split(' ')))
a = [0] + a
acc = [0 for _ in range(n + 1)]
for i in range(1, n + 1):
	acc[i] = a[i] + acc[i - 1]
m = {}
for i in range(0, n + 1):
	for j in range(i + 1, n + 1):
		if acc[j] - acc[i] not in m:
			m[acc[j] - acc[i]] = [[i + 1, j]]
		else:
			m[acc[j] - acc[i]].append([i + 1, j])
sol = []
for (k, v) in m.items():
	v.sort(key=lambda x: x[1])
	r = v[0][1]
	cur = [v[0]]
	for i in range(1, len(v)):
		if v[i][0] > r:
			cur.append(v[i])
			r = v[i][1]
	if len(cur) > len(sol):
		sol = cur
print(len(sol))
for i in range(len(sol)):
	print(sol[i][0], sol[i][1])


from collections import defaultdict
import operator
import sys
import logging

def find_best_path(pairs: list, n=1500):
	dist = [1 for p in pairs]
	pred = [x for x in range(len(pairs))]
	offset = [-1 for x in range(n)]
	for (i, p) in enumerate(pairs):
		offset[p[0]] = i
	last_offset = 0
	for (i, o) in enumerate(offset):
		if o == -1:
			offset[i] = last_offset
		else:
			last_offset = o
	for i in range(len(pairs)):
		end = pairs[i][1]
		for j in range(offset[end] + 1, len(pairs)):
			if dist[j] < dist[i] + 1:
				dist[j] += 1
				pred[j] = i
	last_entry = max(range(len(pairs)), key=lambda x: dist[x])
	partitioning = []
	while True:
		entry = pairs[last_entry]
		partitioning.append([entry[0] + 1, entry[1] + 1])
		if pred[last_entry] == last_entry:
			break
		last_entry = pred[last_entry]
	del pred
	del dist
	return (len(partitioning), partitioning)

def find_partitioning(l: list):
	pairs = defaultdict(list)
	all_sum = sum(pairs)
	logging.debug('start')
	for (i, _) in enumerate(l):
		temp_pairs = {}
		val = all_sum
		for j in reversed(range(i, len(l))):
			temp_pairs[val] = (i, j)
			val -= l[j]
		for (k, v) in temp_pairs.items():
			pairs[k].append(v)
		all_sum -= l[i]
	logging.debug('s1')
	logging.debug('s2')
	maximum_partitioning_size = 0
	partitioning = []
	sorted_keys = [x[0] for x in sorted(pairs.items(), key=lambda kv: len(kv[1]), reverse=True)]
	for key in sorted_keys:
		val = pairs[key]
		if len(val) < maximum_partitioning_size:
			break
		(num_blocks, blocks) = find_best_path(val, len(l))
		if num_blocks > maximum_partitioning_size:
			maximum_partitioning_size = num_blocks
			del partitioning
			partitioning = blocks
	logging.debug('s3')
	return partitioning

def test_find_partitioning():
	l = [7, 1, 2, 2, 1, 5, 3]
	res = find_partitioning(l)
	print(res)
	assert len(res) == 3
	assert res[0] == [7, 7]
	assert res[1] == [4, 5]
	assert res[2] == [2, 3]

def test_big_partitioning():
	import numpy as np
	l = np.random.randint(-15000, 15000, 1500)
	res = find_partitioning(l)

def test_big_partitioning2():
	import numpy as np
	l = np.random.randint(0, 1, 1500)
	res = find_partitioning(l)

def test_big_partitioning3():
	import numpy as np
	l = np.arange(1500)
	res = find_partitioning(l)
	assert len(res) == 15

def test_big_partitioning4():
	import numpy as np
	l = np.arange(1, 1500 * 7 + 1, 7)
	res = find_partitioning(l)

def main():
	lines = sys.stdin.readlines()
	entries = lines[1].split()
	entries = [int(i) for i in entries]
	partitioning = find_partitioning(entries)
	print(len(partitioning))
	for p in partitioning:
		print(p[0], p[1])
logging.basicConfig(level=logging.DEBUG)
main()


from collections import defaultdict

def main():
	n = int(input())
	values = list(map(int, input().split(' ')))
	ans = defaultdict(list)
	for i in range(n):
		s = 0
		for j in range(i, -1, -1):
			s += values[j]
			ans[s].append((j + 1, i + 1))
	answer = dict()
	max = 0
	for key in ans:
		sum_pairs = ans[key]
		non_overlap_pairs = [sum_pairs[0]]
		previous_pair_second_value = sum_pairs[0][1]
		for each_pair in sum_pairs[1:]:
			if previous_pair_second_value < each_pair[0]:
				non_overlap_pairs.append(each_pair)
				previous_pair_second_value = each_pair[1]
		if len(non_overlap_pairs) > max:
			max = len(non_overlap_pairs)
			answer = {max: non_overlap_pairs}
	for key in answer.keys():
		print(key)
		for value in answer[key]:
			print(str(value[0]) + ' ' + str(value[1]))
main()


from collections import defaultdict
from itertools import accumulate
N = int(input())
H = defaultdict(lambda : [])
A = list(map(int, input().split()))
AA = [0] + list(accumulate(A))
for i in range(1, N + 1):
	for j in range(i):
		H[AA[i] - AA[j]].append((i, j))
ctr = 0
ans = []
for L in list(H.values()):
	if ctr >= len(L):
		continue
	L.sort()
	ansc = []
	pi = -1
	for (i, j) in L:
		if j >= pi:
			ansc.append((j + 1, i))
			pi = i
	if ctr < len(ansc):
		ans = ansc.copy()
		ctr = len(ans)
print(ctr)
for (j, i) in ans:
	print(j, i)


n = int(input())
a = [int(i) for i in input().split()]
pref = [0]
d = {}
for x in range(len(a)):
	pref.append(pref[x] + a[x])
for r in range(n):
	for l in range(0, r + 1):
		v = pref[r + 1] - pref[l]
		if v in d:
			d[v].append([l, r])
		else:
			d[v] = [[l, r]]
maxi = -2
max_set = []
for key in d:
	start = -1
	tmp_set = []
	ctr = 0
	for e in range(len(d[key])):
		if d[key][e][0] > start:
			tmp_set.append(d[key][e])
			start = d[key][e][1]
			ctr += 1
	if ctr > maxi:
		maxi = ctr
		max_set = tmp_set
print(maxi)
for w in range(maxi):
	print(max_set[w][0] + 1, max_set[w][1] + 1)


n = int(input())
lst = list(map(int, input().split()))
(d, res, summa) = ({}, {}, 0)
for (i, y) in enumerate(lst):
	summa += y
	s = summa
	for j in range(i + 1):
		if d.get(s) == None:
			d[s] = [0, -1]
			res[s] = []
		if d[s][1] < j:
			d[s][0] += 1
			d[s][1] = i
			res[s].append([j + 1, i + 1])
		s -= lst[j]
(ans, e) = (0, -1)
for (i, x) in enumerate(d):
	if d[x][0] > ans:
		(ans, e) = (d[x][0], x)
print(ans)
for (i, x) in enumerate(res[e]):
	print(*x)


n = int(input())
arr = list(map(int, input().split()))
sums = {0: []}
for i in range(n):
	sum = 0
	for j in range(i, -1, -1):
		sum += arr[j]
		if sum not in sums.keys():
			sums[sum] = []
		sums[sum].append((j, i))
ans = (0, [])
for k in sums:
	allblks = sums[k]
	tot = 0
	r = -1
	ll = []
	for ele in allblks:
		if ele[0] > r:
			tot += 1
			ll.append(ele)
			r = ele[1]
	if tot > ans[0]:
		ans = (tot, ll)
print(ans[0])
lt = ans[1]
for r in lt:
	print(r[0] + 1, r[1] + 1)


import sys
from collections import defaultdict
DBG = not True

def ddprint(s):
	global DBG
	if DBG:
		print(s)
n = int(input())
a = list(map(int, input().split()))
acc = [0] * (n + 1)
for i in range(n):
	acc[i] = acc[i - 1] + a[i]

def prevn(ls, j):
	if len(ls) == 0:
		return 1
	elif ls[0][1] >= j:
		return -1
	hi = len(ls)
	lo = 0
	while lo + 1 < hi:
		mid = (lo + hi) // 2
		if ls[mid][1] < j:
			lo = mid
		else:
			hi = mid
	prevsuf = lo
	if ls[prevsuf][2] + 1 <= ls[-1][2]:
		return -1
	else:
		return ls[prevsuf][2] + 1
h = defaultdict(list)
h[a[0]].append([0, 0, 1])
for i in range(1, n):
	for j in range(-1, i):
		sji = acc[i] - (0 if j == -1 else acc[j])
		pn = prevn(h[sji], j + 1)
		if pn >= 0:
			h[sji].append([j + 1, i, pn])
	ddprint('i {}'.format(i))
	ddprint(h[i])
mx = max([h[k][-1][2] if h[k] else 0 for k in h])
mxk = [k for k in h if h[k] and h[k][-1][2] == mx]
mxk = mxk[0]
if DBG:
	print('mx {} mxk {}'.format(mx, mxk))
ls = h[mxk]
p = [[ls[-1][0], ls[-1][1]]]
top = ls[-1][0]
for i in range(len(ls) - 1, -1, -1):
	if ls[i][1] < top:
		p.append([ls[i][0], ls[i][1]])
		top = ls[i][0]
print(len(p))
for x in p:
	print('{} {}'.format(x[0] + 1, x[1] + 1))


from itertools import *
from collections import *
n = int(input())
arr = [0] + [*accumulate(map(int, input().split()))]
g = defaultdict(list)
for i in range(n):
	for j in range(i + 1, n + 1):
		g[arr[j] - arr[i]].append([i + 1, j])
ans = []
maxi = []
for i in g:
	f = sorted(g[i], key=lambda x: x[1])
	ans = [f[0]]
	for (l, r) in f:
		if l > ans[-1][1]:
			ans.append([l, r])
	maxi = max(maxi, ans, key=len)
print(len(maxi))
for i in maxi:
	print(*i)


import sys, os
from io import BytesIO, IOBase
import collections, itertools, bisect, heapq, math, string
from decimal import *
BUFSIZE = 8192
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 main():
	n = int(input())
	a = list(map(int, input().split()))
	prefix = list(itertools.accumulate(a))
	d = collections.defaultdict(list)
	for i in range(n):
		for j in range(i, n):
			if i == 0:
				d[prefix[j]].append((i, j))
			else:
				v = prefix[j] - prefix[i - 1]
				d[v].append((i, j))
	ans = []
	for k in d.keys():
		v = d[k]
		cnt = []
		tmp = sorted(v, key=lambda x: (x[1], x[0]))
		if len(tmp) == 1:
			cnt.append((tmp[0][0] + 1, tmp[0][1] + 1))
		else:
			pre = tmp[0]
			cnt.append((pre[0] + 1, pre[1] + 1))
			for i in range(1, len(tmp)):
				cur = tmp[i]
				if cur[0] > pre[1]:
					cnt.append((cur[0] + 1, cur[1] + 1))
					pre = cur
		if len(cnt) > len(ans):
			ans = cnt
	print(len(ans))
	for a in ans:
		print(a[0], a[1])
main()


from bisect import bisect_left

def linear_search(arr, k):
	for i in range(0, len(arr)):
		if arr[i] == k:
			return i
	return -1
input()
arr = [int(x) for x in input().split()]
list_1 = []
list_2 = []
for i in range(0, len(arr)):
	cur_sum = 0
	j = i
	while j >= 0:
		cur_sum = cur_sum + arr[j]
		k = linear_search(list_1, cur_sum)
		if k != -1:
			list_2[k].append([j, i])
		else:
			list_1.append(cur_sum)
			list_2.append([[j, i]])
		j = j - 1
sol_list = []
for i in range(0, len(list_2)):
	r = -1
	temp_list = []
	for j in range(0, len(list_2[i])):
		if list_2[i][j][0] > r:
			temp_list.append(list_2[i][j])
			r = list_2[i][j][1]
	if len(temp_list) > len(sol_list):
		sol_list = [] + temp_list
print(len(sol_list))
for ele in sol_list:
	print(ele[0] + 1, ele[1] + 1)


import sys
from collections import defaultdict
DBG = not True
n = int(input())
a = list(map(int, input().split()))
acc = [0] * (n + 1)
for i in range(n):
	acc[i] = acc[i - 1] + a[i]
h = [defaultdict(int) for i in range(n)]
h[0][a[0]] = 1
for i in range(1, n):
	h[i][acc[i]] = 1
	for j in range(i):
		sji = acc[i] - acc[j]
		h[i][sji] = max(h[j][sji] + 1, h[i][sji])
		for k in h[j]:
			h[i][k] = max(h[j][k], h[i][k])
	if DBG:
		print('i {}'.format(i))
		print(h[i])
mx = max(h[n - 1].values())
mxk = [k for k in h[n - 1].keys() if h[n - 1][k] == mx]
mxk = mxk[0]
if DBG:
	print('mx {} mxk {}'.format(mx, mxk))
p = []
top = n - 1
while top >= 0:
	if (0 if top == 0 else h[top - 1][mxk]) < h[top][mxk]:
		s = 0
		if DBG:
			print('top {} h1 {} h2 {}'.format(top, h[top - 1][mxk], h[top][mxk]))
		for j in range(top, -1, -1):
			s += a[j]
			if DBG:
				print('s {}'.format(s))
			if s == mxk:
				p.append([j, top])
				top = j - 1
				mx -= 1
				break
		if False and DBG:
			print('NTBR')
			exit()
	else:
		top -= 1
if mx > 0:
	for i in range(n):
		if acc[i] == mxk:
			p.append([0, i])
			break
print(len(p))
for x in p:
	print('{} {}'.format(x[0] + 1, x[1] + 1))


def main():
	n = int(input())
	A = list(map(int, input().split()))
	if n == 1:
		print(1)
		print(1, 1)
		exit(0)
	prefA = [0]
	hah = {}
	for i in A:
		prefA.append(prefA[-1] + i)
	for i in range(n):
		for j in range(i + 1, n + 1):
			s = prefA[j] - prefA[i]
			if s not in hah:
				hah[s] = []
			hah[s].append([i + 1, j])

	def lol(a):
		return (a[1], a[0])
	ansq = 0
	bm = []
	for s in hah:
		Q = hah[s]
		cnt = 0
		Q.sort(key=lol)
		ans = []
		for i in Q:
			if i[0] > cnt:
				cnt = i[1]
				ans.append(i)
		if ansq < len(ans):
			ansq = len(ans)
			bm = ans
	print(ansq)
	for i in bm:
		print(i[0], i[1])
main()


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10 ** 8)
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 ** 51, func=lambda a, b: a & b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

def maxDisjointIntervals(list_):
	tot = []
	list_.sort(key=lambda x: x[1])
	tot = []
	ert = [list_[0][0], list_[0][1]]
	tot.append(ert)
	r1 = list_[0][1]
	for i in range(1, len(list_)):
		l1 = list_[i][0]
		r2 = list_[i][1]
		if l1 > r1:
			ert = [l1, r2]
			tot.append(ert)
			r1 = r2
	return tot
n = int(input())
l = list(map(int, input().split()))
d = defaultdict(list)
ma = 0
erd = []
for i in range(n):
	s = 0
	for j in range(i, n):
		s += l[j]
		d[s].append([i + 1, j + 1])
for i in d:
	tot = maxDisjointIntervals(d[i])
	if len(tot) >= ma:
		ma = len(tot)
		erd = tot + []
print(ma)
for i in erd:
	print(*i)


import time

def schedule2(times):
	result = []
	a_min = 0
	for (s, e) in times:
		if s >= a_min:
			result.append((s, e))
			a_min = e
	return result

def solve(n, a_l):
	index_by_sum = {}
	for j in range(1, n + 1):
		sum_ = 0
		for i in range(j - 1, -1, -1):
			sum_ += a_l[i]
			if sum_ in index_by_sum:
				index_by_sum[sum_].append((i, j))
			else:
				index_by_sum[sum_] = [(i, j)]
	result = []
	for (sum_, times) in index_by_sum.items():
		sub_result = schedule2(times)
		if len(sub_result) > len(result):
			result = sub_result
	return result

def test():
	n = 1500
	a_l = list(range(1, n + 1))
	tick = time.time()
	result = solve(n, a_l)
	tock = time.time()
	print(len(result))
	for (a, b) in result:
		print(a + 1, b)
	print('T:', round(tock - tick, 5))

def main():
	n = int(input())
	a_l = list(map(int, input().split()))
	result = solve(n, a_l)
	print(len(result))
	for (a, b) in result:
		print(a + 1, b)
main()


franxx = int(input())
life = input()
life = life.split()
darling = {}
oh_pay = 'I love my darling'
for i in range(franxx, 0, -1):
	tmp = 0
	for j in range(i - 1, franxx):
		tmp += int(life[j])
		if tmp in darling:
			if darling[tmp][0] > j:
				darling[tmp] = (i - 1, 1 + darling[tmp][1])
		else:
			darling[tmp] = (i - 1, 1)
		if oh_pay == 'I love my darling' or darling[tmp][1] > darling[oh_pay][1]:
			oh_pay = tmp
print(darling[oh_pay][1])
strelizia = (franxx, 0)
for i in range(franxx, 0, -1):
	tmp = 0
	for j in range(i - 1, franxx):
		tmp += int(life[j])
		if tmp != oh_pay:
			continue
		if strelizia[0] > j:
			print(i, j + 1)
			strelizia = (i - 1, 1 + strelizia[1])


import sys
input = sys.stdin.readline
n = int(input())
A = list(map(int, input().split()))
from itertools import accumulate
SUM = list(accumulate(A))
SUM.append(0)
BLIST = [[0] * n for i in range(n)]
B2 = []
for i in range(n):
	for j in range(i, n):
		BLIST[i][j] = SUM[j] - SUM[i - 1]
		B2.append(SUM[j] - SUM[i - 1])
B2 = set(B2)
ANS = []
ANSLEN = 0
for bsum in B2:
	i = 0
	j = 0
	CANDI = []
	USED = -1
	for i in range(n):
		for j in range(USED + 1, i + 1):
			if BLIST[j][i] == bsum:
				CANDI.append([j + 1, i + 1])
				USED = i
				break
	if len(CANDI) > ANSLEN:
		ANS = CANDI
		ANSLEN = len(CANDI)
print(len(ANS))
for ans in ANS:
	print(*ans)


import sys
input = sys.stdin.readline
n = int(input())
A = list(map(int, input().split()))
from itertools import accumulate
SUM = list(accumulate(A))
SUM.append(0)
BLIST = [[0] * n for i in range(n)]
B2 = []
for i in range(n):
	for j in range(i, n):
		BLIST[i][j] = SUM[j] - SUM[i - 1]
		B2.append(SUM[j] - SUM[i - 1])
B2 = sorted(set(B2))
DICT = {B2[i]: i for i in range(len(B2))}
USED = [-1] * len(B2)
ANS = [[] for i in range(len(B2))]
for i in range(n):
	for j in range(i + 1):
		x = BLIST[j][i]
		if USED[DICT[x]] < j:
			ANS[DICT[x]].append([j + 1, i + 1])
			USED[DICT[x]] = i
ANS0 = max(ANS, key=lambda x: len(x))
print(len(ANS0))
for ans in ANS0:
	print(*ans)


import os
import sys
from atexit import register
from collections import defaultdict
from io import BytesIO
sys.stdout = BytesIO()
_write = sys.stdout.write
sys.stdout.write = lambda s: _write(s.encode())
register(lambda : os.write(1, sys.stdout.getvalue()))
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline

def main():
	n = int(input())
	a = [int(ai) for ai in input().split()]
	pref_sums = [0] * (n + 1)
	for (i, ai) in enumerate(a):
		pref_sums[i + 1] = pref_sums[i] + ai
	block_sums = defaultdict(list)
	for j in range(1, n + 1):
		for i in range(1, j + 1):
			block_sums[pref_sums[j] - pref_sums[i - 1]].append((i, j))
	ans = []
	for A in block_sums.values():
		(res, k) = ([A[0]], 0)
		for i in range(1, len(A)):
			if A[i][0] > A[k][1]:
				res.append(A[i])
				k = i
		if len(res) > len(ans):
			ans = res
	print(len(ans))
	print('\n'.join(map(lambda s: '%d %d' % s, ans)))
main()


from collections import defaultdict
n = int(input())
a = list(map(int, input().split()))
sum_intervals = defaultdict(list)
for r in range(n):
	sum_range = 0
	for l in range(r, -1, -1):
		sum_range += a[l]
		sum_intervals[sum_range].append((l, r))
max_s = -1
max_s_intervals = []
for s in sum_intervals:
	intervals = sum_intervals[s]
	disjoint_intervals = [intervals[0]]
	for i in range(1, len(intervals)):
		if intervals[i][0] > disjoint_intervals[-1][1]:
			disjoint_intervals.append(intervals[i])
	if len(disjoint_intervals) > max_s:
		max_s = len(disjoint_intervals)
		max_s_intervals = disjoint_intervals
print(max_s)
for i in max_s_intervals:
	print(i[0] + 1, i[1] + 1)


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

def main():
	n = int(input())
	a = list(map(int, input().split()))
	sum_intervals = defaultdict(list)
	for r in range(n):
		sum_range = 0
		for l in range(r, -1, -1):
			sum_range += a[l]
			sum_intervals[sum_range].append((l, r))
	max_s = -1
	max_s_intervals = []
	for s in sum_intervals:
		intervals = sum_intervals[s]
		disjoint_intervals = [intervals[0]]
		for i in range(1, len(intervals)):
			if intervals[i][0] > disjoint_intervals[-1][1]:
				disjoint_intervals.append(intervals[i])
		if len(disjoint_intervals) > max_s:
			max_s = len(disjoint_intervals)
			max_s_intervals = disjoint_intervals
	print(max_s)
	for i in max_s_intervals:
		print(i[0] + 1, i[1] + 1)
main()


from collections import defaultdict
n = int(input())
a = [int(i) for i in input().split()]
z = defaultdict(list)
for i in range(n):
	csum = 0
	for j in range(i, -1, -1):
		csum += a[j]
		z[csum].append([j, i])
(best, sum) = (0, 0)
for i in z:
	cr = int(-1000000000.0)
	curr = 0
	for j in z[i]:
		if j[0] > cr:
			cr = j[1]
			curr += 1
	if best < curr:
		(best, sum) = (curr, i)
print(best)
cr = int(-1000000000.0)
for j in z[sum]:
	if j[0] > cr:
		cr = j[1]
		print('{0} {1}'.format(j[0] + 1, j[1] + 1))


import sys
from collections import defaultdict
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
kukan = []
kukan2 = []
rui = [0] * (n + 1)
for i in range(n):
	rui[i + 1] = rui[i] + a[i]
for i in range(n):
	for j in range(n):
		if i < j:
			continue
		kukan.append(rui[i + 1] - rui[j])
		kukan2.append([j, i])
d = defaultdict(list)
for i in range(len(kukan)):
	d[kukan[i]].append(kukan2[i])
ans = []
res = 0
for i in d.keys():
	c = d[i]
	tmp = []
	start = -1
	for j in range(len(c)):
		if c[j][0] > start:
			tmp.append(c[j])
			start = c[j][1]
	if len(tmp) > res:
		res = len(tmp)
		ans = tmp
print(res)
for (i, j) in ans:
	print(i + 1, j + 1)


from collections import Counter, defaultdict
n = int(input())
z = defaultdict(list)
a = [int(x) for x in input().split()]
for i in range(n):
	for j in range(i, n):
		s = 0
		for p in range(i, j + 1):
			s += a[p]
		z[s].append((i, j))
an = -1
for i in z:
	z[i] = sorted(z[i])
	dp = [1 for i in range(len(z[i]))]
	pv = [-1 for i in range(len(z[i]))]
	for p in range(len(z[i])):
		for j in range(p + 1, len(z[i])):
			if z[i][j][0] > z[i][p][1]:
				if dp[j] < dp[p] + 1:
					dp[j] = dp[p] + 1
					pv[j] = p
	if max(dp) > an:
		an = max(dp)
		q = []
		xx = dp.index(max(dp))
		while xx != -1:
			q.append((z[i][xx][0] + 1, z[i][xx][1] + 1))
			xx = pv[xx]
print(an)
for i in q:
	print(*i)


n = int(input())
a = [int(x) for x in input().split(' ')]
range_sums = {}
for i in range(n):
	s = 0
	for j in range(i, n):
		s += a[j]
		if s not in range_sums:
			range_sums[s] = []
		range_sums[s].append((i, j))
disjoint = []
for s in range_sums:
	range_sums[s].sort(key=lambda x: x[1])
	l = []
	end = -1
	for r in range_sums[s]:
		if r[0] > end:
			end = r[1]
			l.append(r)
	if len(l) > len(disjoint):
		disjoint = l
		m_s = s
print(len(disjoint))
for l in disjoint:
	print(l[0] + 1, l[1] + 1)


def get(arr):
	r = 0
	c = 0
	for i in arr:
		if i[0] > r:
			c += 1
			r = i[1]
	return c
n = int(input())
a = [int(x) for x in input().split()]
p = [0]
d = {}
for i in a:
	p.append(p[-1] + i)
for i in range(len(p)):
	for j in range(i, len(p)):
		if i != j:
			r = p[j] - p[i]
			d[r] = d.get(r, []) + [(i + 1, j)]
s = 0
for i in d:
	k = sorted(d[i], key=lambda x: x[1])
	if get(k) > s:
		s = get(k)
		ind = k
r = 0
print(s)
for i in ind:
	if i[0] > r:
		print(i[0], i[1])
		r = i[1]


n = int(input())
a = list(map(int, input().split()))
dic = {}
for i in range(n):
	sm = 0
	for j in range(i, n):
		sm += a[j]
		if sm in dic:
			dic[sm].append((i, j))
		else:
			dic[sm] = [(i, j)]
ans = 0
anskey = -1
for key in dic:
	cnt = 0
	last = -1
	for (a, b) in sorted(dic[key]):
		if a > last:
			cnt += 1
			last = b
		elif b < last:
			last = b
	if cnt > ans:
		ans = cnt
		anskey = key
last = -1
tmp = []
for (a, b) in sorted(dic[anskey]):
	if a > last:
		last = b
		tmp.append(str(a + 1) + ' ' + str(b + 1))
	elif b < last:
		last = b
		tmp.pop()
		tmp.append(str(a + 1) + ' ' + str(b + 1))
print(ans, '\n'.join(tmp), sep='\n')


import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict

def main():
	n = int(input())
	a = list(map(int, input().split()))
	b = defaultdict(list)
	for i in range(n):
		su = 0
		for j in range(i, n):
			su += a[j]
			b[su].append([i, j])
	for i in b:
		b[i].sort()
	(ma, ans) = (0, set())
	for i in b:
		(z, c) = (b[i], set())
		for j in range(len(z) - 1):
			if z[j + 1][0] <= z[j][1]:
				if z[j][1] <= z[j + 1][1]:
					z[j + 1] = z[j]
				z[j] = []
		for j in range(len(z)):
			if z[j]:
				c.add(tuple(z[j]))
		if ma < len(c):
			ma = len(c)
			ans = c
	print(ma)
	for i in ans:
		print(i[0] + 1, i[1] + 1)
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()


n = int(input())
a = list(map(int, input().split()))
d = [{} for _ in range(n)]
for i in range(n):
	cur = 0
	for j in range(i, -1, -1):
		cur += a[j]
		max_length = 1
		next_ = -1
		if cur in d[i]:
			max_length = max(max_length, d[i][cur][0])
			next_ = d[i][cur][2]
		for k in range(j - 1, -1, -1):
			if cur in d[k]:
				if d[k][cur][0] + 1 > max_length:
					max_length = d[k][cur][0] + 1
					next_ = k
					d[i][cur] = [max_length, j, next_]
		if cur not in d[i]:
			d[i][cur] = [max_length, j, next_]
index = -1
max_len = 0
val = None
for i in range(n):
	for k in d[i]:
		if d[i][k][0] > max_len:
			max_len = d[i][k][0]
			index = i
			val = k
arr = []
while index != -1:
	arr.append(str(d[index][val][1] + 1) + ' ' + str(index + 1))
	index = d[index][val][2]
print(len(arr))
print('\n'.join(arr))


n = int(input())
a = [int(x) for x in input().split()]
d = {}
for j in range(n):
	cur_sum = 0
	for i in range(j, -1, -1):
		cur_sum += a[i]
		if cur_sum not in d:
			d[cur_sum] = [(i, j)]
		else:
			(_, prev_j) = d[cur_sum][-1]
			if prev_j < i:
				d[cur_sum].append((i, j))
(mx, mx_key) = (0, 0)
for (key, value) in d.items():
	l = len(value)
	if l > mx:
		mx_key = key
		mx = l
print(mx)
for (i, j) in d[mx_key]:
	print(i + 1, j + 1)


N = int(input())
arr = input()
arr = [int(x) for x in arr.split(' ')]
data = [[0] * N for _ in range(N)]
pair = {}
for i in range(N):
	data[i][i] = arr[i]
	if data[i][i] not in pair:
		pair[data[i][i]] = []
		pair[data[i][i]].append([i, i])
	else:
		pair[data[i][i]].append([i, i])
for i in range(N):
	for j in range(i + 1, N):
		data[i][j] = data[i][j - 1] + arr[j]
		if data[i][j] not in pair:
			pair[data[i][j]] = []
			pair[data[i][j]].append([i, j])
		else:
			pair[data[i][j]].append([i, j])
res = 0
res_s = 0
for key in pair:
	d = pair[key]
	d = sorted(d, key=lambda e: e[1])
	s = 0
	blocks = 0
	for p in d:
		if p[0] >= s:
			blocks += 1
			s = p[1] + 1
	if blocks > res:
		res = blocks
		res_s = key
print(res)
key = res_s
d = pair[key]
d = sorted(d, key=lambda e: e[1])
s = 0
for p in d:
	if p[0] >= s:
		print(p[0] + 1, p[1] + 1)
		s = p[1] + 1


from collections import defaultdict
n = int(input())
nums = [int(x) for x in input().split()]
mapas = [defaultdict(list) for _ in range(n)]
for (i, nu) in enumerate(nums):
	if i:
		mapas[i] = defaultdict(list, mapas[i - 1])
	mapas[i][nu] = mapas[i][nu] + [(i + 1, i + 1)]
	su = nu
	for j in reversed(range(1, i)):
		su += nums[j]
		if len(mapas[j - 1][su]) + 1 > len(mapas[i][su]):
			mapas[i][su] = mapas[j - 1][su] + [(j + 1, i + 1)]
	if i:
		su += nums[0]
		if len(mapas[i][su]) == 0:
			mapas[i][su] = [(1, i + 1)]
(mx, my) = (-1, -1)
for (x, y) in mapas[-1].items():
	if len(y) > my:
		(mx, my) = (x, len(y))
print(my)
for (a, b) in mapas[-1][mx]:
	print(a, b)


MOD = 10 ** 9 + 7
I = lambda : list(map(int, input().split()))
from collections import defaultdict as dd
(n,) = I()
l = I()
d = dd(list)
for i in range(n):
	s = 0
	for j in range(i, n):
		s += l[j]
		d[s].append((i, j))
for i in d:
	d[i].sort(key=lambda key: key[1])
ans = 0
ansl = []
for i in d:
	last = d[i][0]
	cur = 1
	l = [last]
	for j in range(1, len(d[i])):
		if last[1] < d[i][j][0]:
			cur += 1
			l.append(d[i][j])
			last = d[i][j]
	if ans < cur:
		ans = cur
		ansl = l
print(ans)
for i in ansl:
	print(i[0] + 1, i[1] + 1)


n = int(input())
a = list(map(int, input().split()))
if n == 1:
	print(1)
	print('1 1')
else:
	d = [[]] * (n - 1)
	d[0] = a
	for i in range(1, n - 1):
		d[i] = [d[i - 1][j] + a[j + i] for j in range(0, n - i)]
	d2 = {}
	for (i, d_) in enumerate(d):
		for (j, x) in enumerate(d_):
			if x in d2:
				d2[x].append([j + 1, j + i + 1])
			else:
				d2[x] = [[j + 1, j + i + 1]]
	list_keys = list(d2.keys())
	ma = 0
	for key in list_keys:
		d2[key].sort(key=lambda x: x[1])
		after = -1
		cnt = 0
		tmp = []
		for (y, z) in d2[key]:
			if y > after:
				cnt += 1
				after = z
				tmp.append([y, z])
		if cnt > ma:
			ma = cnt
			res = tmp
	print(len(res))
	for x in res:
		print(*x)


import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
sa = [0] + [a[i] for i in range(n)]
for i in range(1, n + 1):
	sa[i] += sa[i - 1]
dd = {}
for i in range(n + 1):
	for j in range(i + 1, n + 1):
		if sa[j] - sa[i] in dd:
			dd[sa[j] - sa[i]].append([i + 1, j])
		else:
			dd[sa[j] - sa[i]] = [[i + 1, j]]
ans = []
for v in dd.keys():
	arr = dd[v]
	arr.sort(key=lambda x: x[1])
	zantei = []
	for i in range(len(arr)):
		if len(zantei) == 0:
			zantei.append(arr[i])
		elif zantei[-1][1] < arr[i][0]:
			zantei.append(arr[i])
	if len(zantei) > len(ans):
		ans = zantei
print(len(ans))
for (l, r) in ans:
	print(l, r)


import math
import os
import random
import re
import sys
from collections import defaultdict

def find_max_non_intersecting(segments):
	n = len(segments)
	r = -1
	result = []
	for i in range(n):
		(a, b) = segments[i]
		if a > r:
			result.append((a, b))
			r = b
	return result

def __starting_point():
	n = int(input())
	a = list(map(int, input().split()))
	s = []
	for ai in a:
		s.append((s[-1] if s else 0) + ai)
	d = defaultdict(list)
	for j in range(n):
		for i in range(j + 1):
			d[s[j] - (s[i - 1] if i - 1 >= 0 else 0)].append((i, j))
	vals = []
	for v in d.values():
		non_inters = find_max_non_intersecting(v)
		if len(non_inters) > len(vals):
			vals = non_inters
	print(len(vals))
	for (l, r) in vals:
		print(l + 1, r + 1)
__starting_point()


import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
b = [0]
for i in a:
	b.append(i + b[-1])
inf = 1919810
x = [[inf] * n for _ in range(n)]
for i in range(n):
	for j in range(i, n):
		x[i][j - i] = b[j + 1] - b[i]
dp = [[0] * n for _ in range(n)]
dp0 = [['?'] * n for _ in range(n)]
(ans, si, sj) = (0, -1, -1)
for i in range(n - 1, -1, -1):
	for j in range(n - i):
		xij = x[i][j]
		m = 1
		(i0, j0) = (-1, -1)
		for k in range(i + j + 1, n):
			for l in range(n):
				if x[k][l] == xij or x[k][l] == inf:
					if m <= dp[k][l] + 1:
						m = dp[k][l] + 1
						(i0, j0) = (k, l)
		dp[i][j] = m
		dp0[i][j] = (i0, j0)
		if ans < m:
			ans = m
			(si, sj) = (i, j)
k = ans
print(k)
(l, r) = (si + 1, si + sj + 1)
(i, j) = (si, sj)
print(l, r)
for _ in range(k - 1):
	(i, j) = dp0[i][j]
	(l, r) = (i + 1, i + j + 1)
	print(l, r)


from __future__ import print_function, division
import os, sys, atexit
if sys.version_info[0] < 3:
	range = xrange
	from cStringIO import StringIO as BytesIO
	sys.stdout = BytesIO()
else:
	from io import BytesIO
	sys.stdout = BytesIO()
	_write = sys.stdout.write
	sys.stdout.write = lambda s: _write(s.encode())
atexit.register(lambda : os.write(1, sys.stdout.getvalue()))
from collections import defaultdict as dd, deque
n = int(input())
A = [int(x) for x in input().split()]
cA = [0]
for a in A:
	cA.append(cA[-1] + a)
B = dd(list)
for l in range(1, n + 1):
	for i in range(n - l + 1):
		s = cA[i + l] - cA[i]
		B[s].append((i, i + l))
best = 0
bestb = None
for b in sorted(B, key=lambda b: len(B[b]), reverse=True):
	if best > len(B[b]):
		break
	A = sorted(B[b], key=lambda x: x[1])
	res = 0
	lr = -1
	for (l, r) in A:
		if lr <= l:
			lr = r
			res += 1
	if res > best:
		best = res
		bestb = b
print(best)
A = sorted(B[bestb], key=lambda x: x[1])
res = 0
lr = -1
for (l, r) in A:
	if lr <= l:
		lr = r
		res += 1
		print(l + 1, r)


from sys import stdin
from collections import defaultdict

def ip():
	return [int(i) for i in stdin.readline().split()]

def sp():
	return [str(i) for i in stdin.readline().split()]

def pp(A):
	for i in A:
		print(i)

def solve():
	n = int(input())
	A = ip()
	d = defaultdict(list)
	for i in range(n):
		rs = 0
		for j in range(i, n):
			rs += A[j]
			d[rs].append((i, j))
	ans = float('-inf')
	B = []
	for k in d:
		cnt = 0
		r = -1
		blocks = []
		d[k].sort(key=lambda x: x[1])
		for i in d[k]:
			if i[0] > r:
				cnt += 1
				r = i[1]
				blocks.append((i[0], i[1]))
		if cnt >= ans:
			ans = cnt
			B = blocks.copy()
	print(ans)
	for (i, j) in B:
		print(i + 1, j + 1)
solve()


def find(v: int, s: int):
	global d, a, n
	(left, r) = (0, v)
	if s == -5:
		print('v', v, d[s][v], d[s][:v])
	while r - left > 1:
		mid = (left + r) // 2
		if s == -5 and v == 6:
			print(d[s][v][0], d[s][mid][1])
		if d[s][v][0] > d[s][mid][1]:
			left = mid
		else:
			r = mid
	return left
n = int(input())
a = list(map(int, input().split()))
d = dict()
for i in range(n):
	s = 0
	for j in range(i, n):
		s += a[j]
		if s in d:
			d[s].append((i + 1, j + 1))
		else:
			d[s] = [(i + 1, j + 1)]
for i in d.keys():
	d[i].sort(key=lambda x: x[1])
ar = []
for el in d.keys():
	cur = []
	r = 0
	for i in d[el]:
		if i[0] > r:
			cur.append(i)
			r = i[1]
	if len(ar) < len(cur):
		ar = cur
print(len(ar))
for i in ar:
	print(*i)


import sys

def sort_dic(dic):
	new_dic = {}
	keys = sorted(dic)
	for k in keys:
		new_dic[k] = dic[k]
	return new_dic

def predicate(a):
	return (a[1], a[0])

def same_sum_block(n, array):
	dic = {}
	for i in range(n):
		for j in range(i + 1, n + 1):
			a = array[i:j]
			b = sum(a)
			if b not in dic:
				dic[b] = []
			dic[b].append([i + 1, j])
	dic = sort_dic(dic)
	n_blocks = 0
	blocks = []
	for key in dic:
		values = dic[key]
		values.sort(key=predicate)
		last_index = 0
		temp_blocks = []
		for i in values:
			if i[0] > last_index:
				last_index = i[1]
				temp_blocks.append(i)
		if n_blocks < len(temp_blocks):
			n_blocks = len(temp_blocks)
			blocks = temp_blocks
	return blocks

def blub():
	n1 = 7
	A1 = [4, 1, 2, 2, 1, 5, 3]
	same_sum_block(n1, A1)
	n2 = 11
	A2 = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
	same_sum_block(n2, A2)
	n3 = 4
	A3 = [1, 1, 1, 1]
	same_sum_block(n3, A3)

def test_big_partitioning():
	import numpy as np
	l = np.random.randint(-15000, 15000, 100)
	res = same_sum_block(len(l), l)

def test_find_partitioning():
	l = [7, 1, 2, 2, 1, 5, 3]
	res = same_sum_block(len(l), l)
	print(res)
	assert len(res) == 3
	assert res[2] == [7, 7]
	assert res[1] == [4, 5]
	assert res[0] == [2, 3]

def main():
	lines = sys.stdin.readlines()
	entries = lines[1].split()
	entries = [int(i) for i in entries]
	partitioning = same_sum_block(len(entries), entries)
	print(len(partitioning))
	for p in partitioning:
		print(p[0], p[1])
main()


from collections import defaultdict as ddict

def main():
	n = int(input())
	a = list(map(int, input().split()))
	dp = ddict(int)
	last_idx = ddict(lambda : -1)
	for i in range(len(a)):
		s = a[i]
		dp[s] += 1
		last_idx[s] = i
		for j in range(i - 1, -1, -1):
			s += a[j]
			if j > last_idx[s]:
				dp[s] += 1
				last_idx[s] = i
	k = max(dp.keys(), key=lambda x: dp[x])
	v = dp[k]
	stack = []
	last_idx = -1
	for i in range(len(a)):
		s = a[i]
		if s == k:
			last_idx = i
			stack.append((i + 1, i + 1))
		for j in range(i - 1, -1, -1):
			s += a[j]
			if j > last_idx:
				if s == k:
					last_idx = i
					stack.append((j + 1, i + 1))
	print(v)
	out_str = []
	for (ia, ib) in stack:
		out_str.append(str(ia) + ' ' + str(ib))
	print('\n'.join(out_str))
main()


def index(key, item, index):
	if key in index:
		index[key].append(item)
	else:
		index[key] = [item]

def schedule_(times, n):
	d = [None] * (n + 1)
	for (start, end) in times:
		for i in range(start + 1):
			if d[i] is None or end < d[i][1]:
				d[i] = (start, end)
	result = []
	next_ = d[0]
	while next_:
		result.append(next_)
		s = next_[1]
		next_ = d[s]
	return result

def schedule(times):
	index_by_b = {}
	for time in times:
		index(time[1], time, index_by_b)
	b_keys = sorted(list(index_by_b.keys()))
	result = []
	a_min = 0
	for end_time in b_keys:
		start = index_by_b[end_time][-1][0]
		if start >= a_min:
			result.append((start, end_time))
			a_min = end_time
	return result

def test_schedule():
	i = [(0, 4), (2, 4), (0, 2), (0, 1), (1, 2), (2, 3), (3, 4)]
	result = schedule(i)
	print('len:', len(result))
	for ele in result:
		print(ele)

def solve(n, a_l):
	index_by_sum = {}
	for i in range(n):
		sum_ = 0
		for j in range(i + 1, n + 1):
			sum_ += a_l[j - 1]
			if sum_ in index_by_sum:
				index_by_sum[sum_].append((i, j))
			else:
				index_by_sum[sum_] = [(i, j)]
	result = []
	for (sum_, times) in index_by_sum.items():
		sub_result = schedule(times)
		if len(sub_result) > len(result):
			result = sub_result
	return result

def main():
	n = int(input())
	a_l = list(map(int, input().split()))
	result = solve(n, a_l)
	print(len(result))
	for (a, b) in result:
		print(a + 1, b)
main()


from collections import defaultdict as dd, deque
n = int(input())
A = [int(x) for x in input().split()]
cA = [0]
for a in A:
	cA.append(cA[-1] + a)
B = dd(list)
for l in range(1, n + 1):
	for i in range(n - l + 1):
		s = cA[i + l] - cA[i]
		B[s].append((i, i + l))
best = 0
bestb = None
for b in sorted(B, key=lambda b: len(B[b]), reverse=True):
	if best > len(B[b]):
		break
	A = sorted(B[b], key=lambda x: x[1])
	res = 0
	lr = -1
	for (l, r) in A:
		if lr <= l:
			lr = r
			res += 1
	if res > best:
		best = res
		bestb = b
print(best)
A = sorted(B[bestb], key=lambda x: x[1])
res = 0
lr = -1
for (l, r) in A:
	if lr <= l:
		lr = r
		res += 1
		print(l + 1, r)


from collections import defaultdict
n = int(input())
arr = [int(i) for i in input().split()]
prefix = [0 for i in range(n)]
segments = defaultdict(list)
prefix[0] = arr[0]
for i in range(1, n):
	prefix[i] = prefix[i - 1] + arr[i]
long = 0
long_i = 0
for i in range(n):
	for j in range(n):
		if j + i > n - 1:
			break
		(l, r) = (i, j + i)
		res = prefix[r] - (prefix[l - 1] if l != 0 else 0)
		if res not in segments:
			segments[res].append(l)
			segments[res].append(r)
		elif r < segments[res][-1]:
			segments[res][-2] = l
			segments[res][-1] = r
		elif segments[res][-1] < l:
			segments[res].append(l)
			segments[res].append(r)
		if len(segments[res]) > long:
			long = len(segments[res])
			long_i = res
print(len(segments[long_i]) // 2)
for i in range(0, len(segments[long_i]), 2):
	print(segments[long_i][i] + 1, segments[long_i][i + 1] + 1)


import sys
from collections import defaultdict
import math
n = int(sys.stdin.readline())
arr = list(map(int, sys.stdin.readline().split()))
dp = defaultdict(list)
for i in range(n):
	s = 0
	for j in range(i, n):
		s += arr[j]
		dp[s].append([j, i])
ans = 0
rem = []
for s in dp:
	dp[s].sort()
	m = len(dp[s])
	lastj = -1
	count = 0
	temp = []
	for k in range(m):
		(j, i) = dp[s][k]
		if i > lastj:
			temp.append([i, j])
			count += 1
			lastj = j
	if ans < count:
		ans = count
		rem = [a for a in temp]
print(ans)
for i in range(ans):
	print(rem[i][0] + 1, rem[i][1] + 1)


from collections import defaultdict
import sys
input = sys.stdin.readline
n = int(input())
a = [int(item) for item in input().split()]
pre = [0] * (n + 1)
for i in range(n):
	pre[i] = pre[i - 1] + a[i]
d = defaultdict(list)
for i in range(n):
	for j in range(i, n):
		d[pre[j] - pre[i - 1]] += [(i, j)]
overall_s = []
for v in d:
	pairs = d[v]
	pairs.sort(key=lambda pair: (pair[1], pair[0]))
	last = 0
	s = [pairs[0]]
	for i in range(1, len(pairs)):
		if pairs[i][0] > pairs[last][1]:
			s.append(pairs[i])
			last = i
	if len(s) > len(overall_s):
		overall_s = s
print(len(overall_s))
for pair in overall_s:
	print(pair[0] + 1, pair[1] + 1)


def index(key, item, index):
	if key in index:
		index[key].append(item)
	else:
		index[key] = [item]

def schedule(times):
	index_by_b = {}
	for time in times:
		index(time[1], time, index_by_b)
	b_keys = sorted(list(index_by_b.keys()))
	result = []
	a_min = 0
	for end_time in b_keys:
		start = index_by_b[end_time][-1][0]
		if start >= a_min:
			result.append((start, end_time))
			a_min = end_time
	return result

def solve(n, a_l):
	index_by_sum = {}
	for i in range(n):
		sum_ = 0
		for j in range(i + 1, n + 1):
			sum_ += a_l[j - 1]
			if sum_ in index_by_sum:
				index_by_sum[sum_].append((i, j))
			else:
				index_by_sum[sum_] = [(i, j)]
	result = []
	for (sum_, times) in index_by_sum.items():
		sub_result = schedule(times)
		if len(sub_result) > len(result):
			result = sub_result
	return result

def main():
	n = int(input())
	a_l = list(map(int, input().split()))
	result = solve(n, a_l)
	print(len(result))
	for (a, b) in result:
		print(a + 1, b)
main()


from collections import defaultdict

def find_best_path(pairs: list):
	dist = [1 for p in pairs]
	pred = [x for x in range(len(pairs))]
	for i in range(len(pairs)):
		for j in range(i + 1, len(pairs)):
			if pairs[j][0] > pairs[i][1]:
				if dist[j] < dist[i] + 1:
					dist[j] += 1
					pred[j] = i
	last_entry = max(range(len(pairs)), key=lambda x: dist[x])
	partitioning = []
	while True:
		entry = pairs[last_entry]
		partitioning.append([entry[0] + 1, entry[1] + 1])
		if pred[last_entry] == last_entry:
			break
		last_entry = pred[last_entry]
	return (len(partitioning), partitioning)

def find_partitioning(l: list):
	ht = defaultdict(list)
	for (i, _) in enumerate(l):
		val = 0
		for j in range(i, len(l)):
			val += l[j]
			ht[val].append((i, j))
	maximum_partitioning_size = 0
	partitioning = []
	for (s, val) in ht.items():
		if len(val) < maximum_partitioning_size:
			continue
		(num_blocks, blocks) = find_best_path(val)
		if num_blocks > maximum_partitioning_size:
			maximum_partitioning_size = num_blocks
			partitioning = blocks
	return partitioning

def test_find_partitioning():
	l = [7, 1, 2, 2, 1, 5, 3]
	l = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
	res = find_partitioning(l)
	assert len(res) == 2
import sys
lines = sys.stdin.readlines()
entries = lines[1].split()
entries = [int(i) for i in entries]
partitioning = find_partitioning(entries)
print(len(partitioning))
for p in partitioning:
	print(p[0], p[1])


import time

def index(key, item, index):
	if key in index:
		index[key].append(item)
	else:
		index[key] = [item]

def schedule2(times):
	result = []
	a_min = 0
	for (s, e) in times:
		if s >= a_min:
			result.append((s, e))
			a_min = e
	return result

def schedule(times):
	index_by_b = {}
	for time in times:
		index(time[1], time, index_by_b)
	b_keys = sorted(list(index_by_b.keys()))
	result = []
	a_min = 0
	for end_time in b_keys:
		start = index_by_b[end_time].pop()[0]
		if start >= a_min:
			result.append((start, end_time))
			a_min = end_time
	return result

def solve(n, a_l):
	index_by_sum = {}
	for j in range(1, n + 1):
		sum_ = 0
		for i in range(j - 1, -1, -1):
			sum_ += a_l[i]
			if sum_ in index_by_sum:
				index_by_sum[sum_].append((i, j))
			else:
				index_by_sum[sum_] = [(i, j)]
	result = []
	for (sum_, times) in index_by_sum.items():
		sub_result = schedule2(times)
		if len(sub_result) > len(result):
			result = sub_result
	return result

def test():
	n = 1500
	a_l = list(range(1, n + 1))
	tick = time.time()
	result = solve(n, a_l)
	tock = time.time()
	print(len(result))
	for (a, b) in result:
		print(a + 1, b)
	print('T:', round(tock - tick, 5))

def main():
	n = int(input())
	a_l = list(map(int, input().split()))
	result = solve(n, a_l)
	print(len(result))
	for (a, b) in result:
		print(a + 1, b)
main()


from sys import stdin, stdout, setrecursionlimit
input = stdin.readline
inf = float('inf')
from functools import cmp_to_key
from collections import defaultdict as dd
from collections import Counter, deque
from heapq import *
import math
from math import floor, ceil, sqrt

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

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

def getis():
	return map(str, input().strip().split())

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

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

def geta():
	return int(input())

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

def solve():
	n = geta()
	a = getl()
	sub = dd(list)
	for i in range(n):
		temp = 0
		for j in range(i, -1, -1):
			temp += a[j]
			sub[temp].append((j, i))
	ans = 0
	res = []
	for i in sub:
		sub[i].sort(key=lambda x: x[-1])
		end = sub[i][0][-1]
		count = 1
		temp = [sub[i][0]]
		for j in range(1, len(sub[i])):
			if sub[i][j][0] > end:
				temp.append(sub[i][j])
				end = sub[i][j][-1]
				count += 1
		if count > ans:
			ans = count
			res = temp[:]
	print(ans)
	for i in res:
		print(i[0] + 1, i[1] + 1)
solve()


n = int(input())
a = [int(t) for t in input().split(' ')]
p = [0] * (n + 1)
for i in range(n):
	p[i + 1] = p[i] + a[i]
sums = set()
for i in range(n):
	for j in range(i + 1, n + 1):
		sums.add(p[j] - p[i])
INF = n + 100
best_blocks = []
for s in sums:
	blocks = []
	leftmost_p = 0
	while leftmost_p < INF:
		leftmost_j = INF
		according_i = -1
		for i in range(leftmost_p, n):
			if i >= leftmost_j:
				break
			for j in range(i + 1, n + 1):
				if j >= leftmost_j:
					break
				if p[j] - p[i] == s and j < leftmost_j:
					leftmost_j = j
					according_i = i
		leftmost_p = leftmost_j
		if leftmost_j < INF:
			blocks.append((according_i + 1, leftmost_j))
	if len(blocks) > len(best_blocks):
		best_blocks = blocks
print(len(best_blocks))
for b in best_blocks:
	print(*b)


import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192

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

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
			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')
from collections import defaultdict as dd, deque as dq
import math, string

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())
MOD = 10 ** 9 + 7

def solve():
	N = getInt()
	A = getInts()
	(P, curr) = ([0], 0)
	for a in A:
		curr += a
		P.append(curr)
	D = dd(list)
	for L in range(N):
		for R in range(L + 1, N + 1):
			D[P[R] - P[L]].append((R, L))
	best = 0
	best_key = -10 ** 9
	best_arr = []
	for (key, arr) in D.items():
		D[key].sort(reverse=True)
		tmp = []
		while D[key]:
			(R, L) = D[key].pop()
			if not tmp or L >= prev_R:
				tmp.append((L, R))
				prev_R = R
		if len(tmp) > best:
			best = len(tmp)
			best_key = key
			best_arr = tmp[:]
	print(best)
	for (L, R) in best_arr:
		print(L + 1, R)
	return
solve()


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

class SegmentTree:

	def __init__(self, data, default=-10 ** 6, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree1:

	def __init__(self, data, default=10 ** 6, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)
MOD = 10 ** 9 + 7

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod = 10 ** 9 + 7
omod = 998244353
prime = [True for i in range(50001)]
pp = []

def SieveOfEratosthenes(n=50000):
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	for i in range(50001):
		if prime[i]:
			pp.append(i)
n = int(input())
nums = list(map(int, input().split()))
freq = defaultdict(list)
for i in range(n):
	for j in range(i + 1, n + 1):
		freq[sum(nums[i:j])].append((i + 1, j))
ans = []
for k in freq:
	l = freq[k]
	l.sort(key=lambda x: x[1])
	tmp = [l[0]]
	for (i, j) in l:
		if i <= tmp[-1][1]:
			continue
		tmp.append([i, j])
	if len(tmp) > len(ans):
		ans = tmp
print(len(ans))
for (i, j) in ans:
	print(i, j)


import sys, math, queue
sys.setrecursionlimit(1000000)
n = int(input())
a = list(map(int, input().split()))
s = {}
for i in range(n):
	x = 0
	for j in range(i, n):
		x += a[j]
		if x not in s:
			s[x] = [(i + 1, j + 1)]
		else:
			s[x].append((i + 1, j + 1))
anset = []
for ss in s:
	s[ss].sort(key=lambda x: x[1])
	r = s[ss][0][1]
	tset = [s[ss][0]]
	for i in range(1, len(s[ss])):
		if r < s[ss][i][0]:
			tset.append(s[ss][i])
			r = s[ss][i][1]
	if len(tset) > len(anset):
		anset = tset[:]
print(len(anset))
for segs in anset:
	print(*segs)


n = int(input())
a = list(map(int, input().split()))
array = [None] * n
d = {}
for j in range(n):
	array[j] = [None] * n
	array[j][j] = a[j]
	if array[j][j] not in d:
		d[array[j][j]] = [(j, j)]
	else:
		d[array[j][j]].append((j, j))
	for i in range(j):
		array[i][j] = array[i][j - 1] + a[j]
		if array[i][j] not in d:
			d[array[i][j]] = [(i, j)]
		else:
			d[array[i][j]].append((i, j))
intervals = sorted(d.values(), key=lambda x: len(x), reverse=True)
max_blocks = 1
res = [(0, 0)]
for interval in intervals:
	if len(interval) <= max_blocks:
		break
	intersects = [None] * len(interval)
	for i in range(len(intersects)):
		intersects[i] = []
	number_of_intersections = [0] * len(interval)
	for i in range(len(interval)):
		block1 = interval[i]
		for j in range(0, len(interval)):
			if i == j:
				continue
			block2 = interval[j]
			if block1[1] >= block2[0] and block1[1] <= block2[1] or (block1[0] >= block2[0] and block1[0] <= block2[1]) or (block1[0] >= block2[0] and block1[1] <= block2[1]) or (block2[0] >= block1[0] and block2[1] <= block1[1]):
				intersects[i].append(j)
				number_of_intersections[i] += 1
	cur_len = len(interval)
	while cur_len > max_blocks:
		max_elem = max(number_of_intersections)
		if max_elem == 0:
			max_blocks = cur_len
			res = []
			for i in range(len(number_of_intersections)):
				if number_of_intersections[i] == 0:
					res.append(interval[i])
			break
		i = number_of_intersections.index(max_elem)
		for j in intersects[i]:
			number_of_intersections[j] -= 1
		number_of_intersections[i] = -1
		cur_len -= 1
print(max_blocks)
for block in res:
	print(block[0] + 1, block[1] + 1)


def index(key, item, index):
	if key in index:
		index[key].add(item)
	else:
		index[key] = set([item])

def schedule(times):
	index_by_a = {}
	index_by_b = {}
	result_indexs = []
	for i in range(len(times)):
		(a, b) = times[i]
		index(a, i, index_by_a)
		index(b, i, index_by_b)
	b_keys = sorted(list(index_by_b.keys()))
	a_min = 0
	while 1:
		pool = set()
		for (k, v) in index_by_a.items():
			if k >= a_min:
				pool |= v
		if not pool:
			break
		for k in (ele for ele in b_keys if ele > a_min):
			candidates = pool & index_by_b[k]
			if candidates:
				chosen = candidates.pop()
				result_indexs.append(chosen)
				(a, b) = times[chosen]
				a_min = b
				break
	return [times[i] for i in result_indexs]

def test_schedule():
	i = ((0, 4), (2, 4), (0, 2), (0, 1), (1, 2), (2, 3), (3, 4))
	result = schedule(i)
	print('len:', len(result))
	for ele in result:
		print(ele)

def solve(n, a_l):
	index_by_sum = {}
	for i in range(n):
		sum_ = 0
		for j in range(i + 1, n + 1):
			sum_ += a_l[j - 1]
			if sum_ in index_by_sum:
				index_by_sum[sum_].append((i, j))
			else:
				index_by_sum[sum_] = [(i, j)]
	result = []
	for (sum_, times) in index_by_sum.items():
		sub_result = schedule(times)
		if len(sub_result) > len(result):
			result = sub_result
	return result

def main():
	n = int(input())
	a_l = list(map(int, input().split()))
	result = solve(n, a_l)
	print(len(result))
	for (a, b) in result:
		print(a + 1, b)
main()


INF = 100000000
from collections import defaultdict
t = 1
for test in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	pre = [0 for i in range(n + 1)]
	for i in range(n):
		pre[i + 1] = pre[i] + a[i]
	Sum = defaultdict(list)
	for i in range(n):
		for j in range(i, n):
			tmp = pre[j + 1] - pre[i]
			Sum[tmp].append((i, j))
	maxVal = 0
	maxSum = -1
	for (key, val) in Sum.items():
		val.sort()
		tmp = 1
		cur = val[0][1]
		for i in range(1, len(val)):
			if val[i][0] > cur:
				tmp += 1
				cur = val[i][1]
			elif val[i][1] <= cur:
				cur = val[i][1]
		if maxVal < tmp:
			maxVal = tmp
			maxSum = key
	print(maxVal)
	val = Sum[maxSum]
	val.sort()
	ans = []
	ans.append(val[0])
	cur = val[0][1]
	for i in range(1, len(val)):
		if val[i][0] > cur:
			ans.append(val[i])
			cur = val[i][1]
		elif val[i][1] <= cur:
			ans.pop()
			ans.append(val[i])
			cur = val[i][1]
	for i in ans:
		print(i[0] + 1, i[1] + 1)


n = int(input())
a = [int(x) for x in input().split()]
res = {}
for i in range(n):
	sm = 0
	for j in range(i, n):
		sm += a[j]
		if sm in res:
			res[sm].append((i, j))
		else:
			res[sm] = [(i, j)]
best = 0
bestI = -1
for key in res:
	r = -1
	cnt = 0
	for (a, b) in sorted(res[key]):
		if a > r:
			cnt += 1
			r = b
		elif b < r:
			r = b
	if cnt > best:
		best = cnt
		bestI = key
x = []
r = -1
for (a, b) in sorted(res[bestI]):
	if a > r:
		x.append(str(a + 1) + ' ' + str(b + 1))
		r = b
	elif b < r:
		r = b
		x.pop()
		x.append(str(a + 1) + ' ' + str(b + 1))
print(best)
print('\n'.join(x))


from bisect import insort
n = int(input())
a = list(map(int, input().split()))
cm = [0] * (n + 1)
for i in range(n):
	cm[i + 1] = cm[i] + a[i]
d = dict()
for i in range(n):
	for j in range(i, n):
		sm = cm[j + 1] - cm[i]
		if sm in d:
			insort(d[sm], (j, i))
		else:
			d[sm] = [(j, i)]
ans = 0
arr = list()
tmparr = [None] * n
for sm in d:
	ct = 0
	end = -1
	for el in d[sm]:
		if el[1] > end:
			tmparr[ct] = el
			ct += 1
			end = el[0]
	if ct > ans:
		ans = ct
		arr = tmparr[:ans]
print(ans)
for el in arr:
	print(el[1] + 1, el[0] + 1)


import sys
from collections import deque
from copy import *
from bisect import *
from math import gcd, ceil, sqrt

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
sys.setrecursionlimit(10 ** 5)
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')
di = [[-1, 0], [1, 0], [0, 1], [0, -1]]

def fori(n):
	return [fi() for i in range(n)]

def inc(d, c, x=1):
	d[c] = d[c] + x if c in d else x

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

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

def fli():
	return [float(x) for x in input().split()]

def comp(a, b):
	if a > b:
		return 2
	return 2 if a == b else 0

def gi():
	return [xx for xx in input().split()]

def gtc(tc, ans):
	print('Case #' + str(tc) + ':', ans)

def cil(n, m):
	return n // m + int(n % m > 0)

def fi():
	return int(input())

def pro(a):
	return reduce(lambda a, b: a * b, a)

def swap(a, i, j):
	(a[i], a[j]) = (a[j], a[i])

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

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

def gh():
	sys.stdout.flush()

def isvalid(i, j, n, m):
	return 0 <= i < n and 0 <= j < m

def bo(i):
	return ord(i) - ord('a')

def graph(n, m):
	for i in range(m):
		(x, y) = mi()
		a[x].append(y)
		a[y].append(x)
t = 1
uu = t
dp = {}
child = {}
while t > 0:
	t -= 1
	d = {}
	n = fi()
	a = li()
	pre = [[0] * n for i in range(n)]
	for i in range(n):
		c = 0
		for j in range(i, n):
			c += a[j]
			if c not in d:
				d[c] = []
			pre[i][j] = c
			d[c].append([i, j])
	for i in d:
		d[i].sort()
	ans = []
	for i in d:
		m = len(d[i])
		suf = [0] * m
		for j in range(m - 1, -1, -1):
			(p, q) = d[i][j]
			if j == m - 1:
				suf[j] = 1
			else:
				w = bisect_left(d[i], [q + 1, -1])
				if w == m:
					suf[j] = suf[j + 1]
				else:
					suf[j] = max(suf[j + 1], suf[w] + 1)
		c = max(suf)
		r = []
		for j in range(m):
			if j == m - 1 or suf[j] > suf[j + 1]:
				r.append(d[i][j])
		ans.append([c, r])
	ans.sort()
	print(ans[-1][0])
	for i in ans[-1][1]:
		print(i[0] + 1, i[1] + 1)