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 1500$) — 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

Source: codeforces | Difficulty: HARD
Tags: Data structures

Greedy algorithms


Solutions:
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()


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


n = int(input())
A = list(map(int, input().split()))
if n == 1:
	print(1)
	print(1, 1)
	return
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])


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


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 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)
main()


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


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)


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)


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)


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)


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)


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)


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))
	(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] = []
			else:
				c.add(z[j])
		if z[-1]:
			c.add(z[-1])
		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()


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)


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


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


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)


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)


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


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


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

def __starting_point():
	main()
__starting_point()


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)


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 list(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()


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)


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)


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


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


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


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


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)

def __starting_point():
	main()
__starting_point()


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 list(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(['%d %d' % s for s in ans]))

def __starting_point():
	main()
__starting_point()


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)


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


INF = 100000000
from collections import defaultdict
t = 1
for test in range(t):
	n = int(input())
	a = list(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 list(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)


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)


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)