Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it!

Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from left to right, and the i-th piece has a colour s_{i}, denoted by a lowercase English letter. Nadeko will repaint at most m of the pieces to give each of them an arbitrary new colour (still denoted by a lowercase English letter). After this work, she finds out all subsegments of the garland containing pieces of only colour c — Brother Koyomi's favourite one, and takes the length of the longest among them to be the Koyomity of the garland.

For instance, let's say the garland is represented by "kooomo", and Brother Koyomi's favourite colour is "o". Among all subsegments containing pieces of "o" only, "ooo" is the longest, with a length of 3. Thus the Koyomity of this garland equals 3.

But problem arises as Nadeko is unsure about Brother Koyomi's favourite colour, and has swaying ideas on the amount of work to do. She has q plans on this, each of which can be expressed as a pair of an integer m_{i} and a lowercase letter c_{i}, meanings of which are explained above. You are to find out the maximum Koyomity achievable after repainting the garland according to each plan.


-----Input-----

The first line of input contains a positive integer n (1 ≤ n ≤ 1 500) — the length of the garland.

The second line contains n lowercase English letters s_1s_2... s_{n} as a string — the initial colours of paper pieces on the garland.

The third line contains a positive integer q (1 ≤ q ≤ 200 000) — the number of plans Nadeko has.

The next q lines describe one plan each: the i-th among them contains an integer m_{i} (1 ≤ m_{i} ≤ n) — the maximum amount of pieces to repaint, followed by a space, then by a lowercase English letter c_{i} — Koyomi's possible favourite colour.


-----Output-----

Output q lines: for each work plan, output one line containing an integer — the largest Koyomity achievable after repainting the garland according to it.


-----Examples-----
Input
6
koyomi
3
1 o
4 o
4 m

Output
3
6
5

Input
15
yamatonadeshiko
10
1 a
2 a
3 a
4 a
5 a
1 b
2 b
3 b
4 b
5 b

Output
3
4
5
7
8
1
2
3
4
5

Input
10
aaaaaaaaaa
2
10 b
10 z

Output
10
10



-----Note-----

In the first sample, there are three plans:   In the first plan, at most 1 piece can be repainted. Repainting the "y" piece to become "o" results in "kooomi", whose Koyomity of 3 is the best achievable;  In the second plan, at most 4 pieces can be repainted, and "oooooo" results in a Koyomity of 6;  In the third plan, at most 4 pieces can be repainted, and "mmmmmi" and "kmmmmm" both result in a Koyomity of 5.

Source: codeforces | Difficulty: MEDIUM_HARD
Tags: Dynamic programming

Amortized analysis

Complete search

String algorithms


Solutions:
import sys
n = int(input())
s = input()
pfs = [[0 for _ in range(n + 1)] for _ in range(26)]
for i in range(n):
	ch = ord(s[i]) - ord('a')
	for j in range(26):
		if j == ch:
			pfs[j][i + 1] = pfs[j][i] + 1
		else:
			pfs[j][i + 1] = pfs[j][i]
dp = [[0 for _ in range(n + 1)] for _ in range(26)]
for c in range(26):
	for l in range(n + 1):
		for r in range(l, n + 1):
			tc = r - l - (pfs[c][r] - pfs[c][l])
			dp[c][tc] = max(dp[c][tc], r - l)
	for i in range(1, n + 1):
		dp[c][i] = max(dp[c][i], dp[c][i - 1])
A = []
for q in range(int(input())):
	(m, c) = sys.stdin.readline().split()
	m = int(m)
	c = ord(c) - ord('a')
	ans = dp[c][m]
	print(ans)


import sys
n = int(sys.stdin.readline().strip())
s = sys.stdin.readline().strip()
ans = [[-1] * (n + 1) for x in range(26)]
for c in range(26):
	for l in range(n):
		nrOfC = 0
		for r in range(l, n):
			if s[r] == chr(97 + c):
				nrOfC += 1
			ans[c][r - l + 1 - nrOfC] = max(ans[c][r - l + 1 - nrOfC], r - l + 1)
for i in range(int(sys.stdin.readline().strip())):
	(m, c) = sys.stdin.readline().strip().split()
	m = int(m)
	print(ans[ord(c) - 97][m] if ans[ord(c) - 97][m] != -1 else n)


from sys import stdin
n = int(stdin.readline())
s = list(stdin.readline())[:-1]
cnt = [[0] * 26 for i in range(n + 1)]
for j in range(26):
	x = chr(j + 97)
	for i in range(n):
		if s[i] == x:
			cnt[i + 1][j] += 1
	for i in range(1, n + 1):
		cnt[i][j] += cnt[i - 1][j]
d = [[0] * (n + 1) for i in range(26)]
for j in range(26):
	for r in range(1, n + 1):
		for l in range(1, r + 1):
			dx = r - l + 1 - (cnt[r][j] - cnt[l - 1][j])
			d[j][dx] = max(d[j][dx], r - l + 1)
ans = [[0] * (n + 1) for i in range(26)]
for j in range(26):
	ans[j][0] = d[j][0]
	for i in range(1, n + 1):
		ans[j][i] = max(ans[j][i - 1], d[j][i])
q = int(stdin.readline())
for _ in range(q):
	(m, c) = stdin.readline().split()
	m = int(m)
	print(ans[ord(c) - ord('a')][m])


from __future__ import division, print_function
import itertools
import sys
import os
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	input = raw_input
	range = xrange
	filter = itertools.ifilter
	map = itertools.imap
	zip = itertools.izip

def is_it_local():
	script_dir = str(os.getcwd()).split('/')
	username = 'dipta007'
	return username in script_dir

def READ(fileName):
	if is_it_local():
		sys.stdin = open(f'./{fileName}', 'r')
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')
if not is_it_local():
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	input = lambda : sys.stdin.readline().rstrip('\r\n')

def input1(type=int):
	return type(input())

def input2(type=int):
	[a, b] = list(map(type, input().split()))
	return (a, b)

def input3(type=int):
	[a, b, c] = list(map(type, input().split()))
	return (a, b, c)

def input_array(type=int):
	return list(map(type, input().split()))

def input_string():
	s = input()
	return list(s)
ltr = [[] for _ in range(26)]
memo = {}

def main():
	n = input1()
	st = input_string()
	for l in range(97, 97 + 26):
		ltr[l - 97].append(0)
		ch = chr(l)
		cum = 0
		for i in range(n):
			if st[i] == ch:
				cum += 1
			ltr[l - 97].append(cum)
	q = input1()
	for i in range(q):
		[m, c] = list(input().split())
		m = int(m)
		if c in memo and m in memo[c]:
			print(memo[c][m])
			continue
		res = m
		low = 1
		z = 0
		l = ord(c) - 97
		for high in range(0, n + 1):
			tot = high - low + 1
			now = ltr[l][high] - ltr[l][low - 1]
			need = tot - now
			while need > m:
				low += 1
				tot = high - low + 1
				now = ltr[l][high] - ltr[l][low - 1]
				need = tot - now
			res = max(res, high - low + 1)
		if c not in memo:
			memo[c] = {}
		memo[c][m] = res
		print(res)
	pass
main()


import sys
input = sys.stdin.readline
n = int(input())
s = input()[:-1]
ans = [[-1] * (n + 1) for _ in range(26)]
for c in range(26):
	for i in range(n):
		cnt = 0
		for j in range(i, n):
			if ord(s[j]) - ord('a') != c:
				cnt += 1
			ans[c][cnt] = max(ans[c][cnt], j - i + 1)
for c in range(26):
	for i in range(1, n + 1):
		ans[c][i] = max(ans[c][i], ans[c][i - 1])
for _ in range(int(input())):
	(m, c) = input().split()
	print(ans[ord(c) - ord('a')][int(m)])


from sys import stdin
from sys import stdout

def main():
	n = int(stdin.readline())
	s = stdin.readline()
	d = {chr(i): [0 for j in range(n + 1)] for i in range(97, 123)}
	for i in range(97, 123):
		for j in range(n):
			dp = 1 if s[j] == chr(i) else 0
			d[chr(i)][1 - dp] = max(d[chr(i)][1 - dp], 1)
			for u in range(j + 1, n):
				if s[u] == chr(i):
					dp += 1
				d[chr(i)][u - j + 1 - dp] = max(d[chr(i)][u - j + 1 - dp], u - j + 1)
	q = int(stdin.readline())
	for i in range(q):
		(m, c) = stdin.readline().split()
		m = int(m)
		res = d[c][m]
		if res == 0:
			res = n
		stdout.write(str(res) + '\n')
main()


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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
a = int(input())
s = input()
count = [[0 for i in range(len(s) + 1)] for i in range(26)]
for i in range(len(s)):
	t = ord(s[i]) - 97
	for j in range(26):
		if j == t:
			count[j][i + 1] = count[j][i] + 1
		else:
			count[j][i + 1] = count[j][i]
ans = []
t1 = [0 for i in range(a + 1)]
for i in range(26):
	ans.append(t1.copy())
f = int(input())
l = 0
r = 0
for l in range(len(s)):
	for r in range(l, len(s)):
		for i in range(26):
			y = count[i][r + 1] - count[i][l]
			er = r - l + 1 - y
			ans[i][er] = max(r - l + 1, ans[i][er])
for i in range(26):
	for j in range(1, len(ans[i])):
		ans[i][j] = max(ans[i][j], ans[i][j - 1])
for i in range(f):
	(x, s) = map(str, input().split())
	print(ans[ord(s) - 97][int(x)])


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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import Counter
import heapq
from collections import Counter
from bisect import bisect_right
n = int(input())
s = input()
dp = [[0 for i in range(n + 1)] for j in range(26)]
for k in range(26):
	for i in range(n):
		cnt = 0
		for j in range(i, n):
			if s[j] != chr(k + 97):
				cnt += 1
			dp[k][cnt] = max(dp[k][cnt], j - i + 1)
	for j in range(1, n + 1):
		dp[k][j] = max(dp[k][j], dp[k][j - 1])
for i in range(int(input())):
	ls = input().split(' ')
	var = int(ls[0])
	ch = ls[1]
	print(dp[ord(ch) - 97][var])


from __future__ import print_function
from collections import *
from sys import stdin
from bisect import *
from heapq import *
from math import log2
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
rr = lambda x: reversed(range(x))
mod = int(1000000000.0) + 7
inf = float('inf')
(n,) = gil()
s = [ord(ch) - 97 for ch in g()]
(q,) = gil()
ans = [[0 for _ in range(n + 1)] for _ in range(26)]
(prev, new) = ([0] * n, [0] * n)
for ch in range(26):
	maxi = 0
	for i in range(n):
		prev[i] = (1 if s[i] == ch else 0) + (prev[i - 1] if i and s[i] == ch else 0)
		maxi = max(prev[i], maxi)
	ans[ch][0] = maxi
	for mi in range(1, n + 1):
		maxi = 0
		for i in range(n):
			(aprev, sprev) = (prev[i - 1] if i else 0, new[i - 1] if i else 0)
			if ch == s[i]:
				new[i] = sprev + 1
			else:
				new[i] = aprev + 1
			maxi = max(maxi, new[i])
		ans[ch][mi] = maxi
		(prev, new) = (new, prev)
fin = []
for _ in range(q):
	(mi, ch) = gl()
	fin.append(str(ans[ord(ch) - 97][int(mi)]))
print('\n'.join(fin))


import os
import sys
from io import BytesIO, IOBase
_str = str
str = lambda x=b'': x if type(x) is bytes else _str(x).encode()
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')
input = lambda : sys.stdin.readline().rstrip('\r\n')
for i in range(1):
	n = int(input())
	s = input()
	c = [[0 for j in range(n + 1)] for i in range(26)]
	for k in range(26):
		for i in range(n):
			rep = 0
			for j in range(i, n):
				if s[j] != chr(97 + k):
					rep += 1
				c[k][rep] = max(c[k][rep], j - i + 1)
		for j in range(1, n + 1):
			c[k][j] = max(c[k][j], c[k][j - 1])
	t = int(input())
	for i in range(t):
		(r, d) = map(str, input().split())
		print(c[ord(d) - 97][int(r)])


import sys

def solve():
	n = int(sys.stdin.readline().rstrip())
	s = sys.stdin.readline().rstrip()
	q = int(sys.stdin.readline().rstrip())
	pfs = [[0] * (n + 1) for i in range(26)]
	for i in range(n):
		ch = ord(s[i]) - ord('a')
		for j in range(26):
			if j == ch:
				pfs[j][i + 1] = pfs[j][i] + 1
			else:
				pfs[j][i + 1] = pfs[j][i]
	dp = [[0] * (n + 1) for i in range(26)]
	for c in range(26):
		for l in range(n + 1):
			for r in range(l, n + 1):
				tc = r - l - (pfs[c][r] - pfs[c][l])
				dp[c][tc] = max(dp[c][tc], r - l)
		for i in range(1, n + 1):
			dp[c][i] = max(dp[c][i], dp[c][i - 1])
	for qi in range(q):
		(mi, ci) = sys.stdin.readline().split()
		mi = int(mi)
		ci = ord(ci) - ord('a')
		ans = dp[ci][mi]
		print(ans)

def __starting_point():
	solve()
__starting_point()


import sys
ii = lambda : sys.stdin.readline().strip()
idata = lambda : [int(x) for x in ii().split()]
n = int(ii())
s = ii()
slov = {}
for i in range(97, 97 + 26):
	slov[chr(i)] = [[], [1]]
slov[s[0]] = [[1], [0, 0]]
for j in range(1, n):
	if slov[s[j]][1][-1] == 0:
		slov[s[j]][0][-1] += 1
	else:
		slov[s[j]][0] += [1]
		slov[s[j]][1] += [0]
	for i in range(97, 97 + 26):
		if chr(i) != s[j]:
			slov[chr(i)][1][-1] += 1
for t in range(int(ii())):
	(m, c) = ii().split()
	m = int(m)
	(a, b) = slov[c]
	if sum(b) <= m:
		print(n)
	elif not bool(a):
		print(m)
	elif len(a) == 1:
		print(a[0] + m)
	else:
		(l, r) = (0, 0)
		ans = 0
		(summ_a, summ_b) = (0, 0)
		used = 0
		b1 = b[:]
		(b1[0], b1[-1]) = (0, 0)
		count = 0
		while r != len(a):
			if summ_b + b1[r] <= m:
				summ_b += b1[r]
				summ_a += a[r]
				r += 1
				ans = max(ans, m + summ_a)
			else:
				summ_a -= a[l]
				l += 1
				summ_b -= b1[l]
		print(ans)


import sys
n = int(sys.stdin.readline().strip())
s = sys.stdin.readline().strip()
dp = [[-1] * (n + 1) for i in range(26)]
for c in range(26):
	for j in range(n):
		tst = 1 if s[j] == chr(c + 97) else 0
		dp[c][1 - tst] = max(dp[c][1 - tst], 1)
		for k in range(j + 1, n):
			if s[k] == chr(c + 97):
				tst += 1
			dp[c][k - j + 1 - tst] = max(dp[c][k - j + 1 - tst], k - j + 1)
q = int(sys.stdin.readline().strip())
for i in range(q):
	(m, c) = [item for item in sys.stdin.readline().strip().split()]
	m = int(m)
	print(dp[ord(c) - 97][m]) if dp[ord(c) - 97][m] != -1 else print(n)


import sys
input = sys.stdin.buffer.readline
n = int(input())
s = str(input().strip())[2:-1]
ans = [[0] * (n + 1) for i in range(26)]
segs = [[[0, -1]] for i in range(26)]
for i in range(n):
	c = ord(s[i]) - ord('a')
	if i > 0 and s[i] != s[i - 1]:
		segs[c].append([i, i])
	else:
		segs[c][-1][1] = i
for c in range(26):
	for start in range(len(segs[c])):
		lst_seg = start
		tot = segs[c][start][1] - segs[c][start][0] + 1
		left = 0
		l = segs[c][start][0]
		for m in range(1, n + 1):
			if segs[c][lst_seg][1] + left + 1 < n:
				left += 1
				tot += 1
				if lst_seg != len(segs[c]) - 1 and segs[c][lst_seg][1] + left == segs[c][lst_seg + 1][0] - 1:
					lst_seg += 1
					tot += segs[c][lst_seg][1] - segs[c][lst_seg][0] + 1
					left = 0
			elif start != 0 and l > segs[c][start - 1][1] + 2:
				l -= 1
				tot += 1
			ans[c][m] = max(ans[c][m], tot)
q = int(input())
for i in range(q):
	(m, c) = input().split()
	m = int(str(m)[2:-1])
	c = ord(str(c)[2:-1]) - ord('a')
	print(ans[c][m])


import sys
from array import array
from typing import List, Tuple, TypeVar, Generic, Sequence, Union

def input():
	return sys.stdin.buffer.readline().decode('utf-8')

def main():
	n = int(input())
	a = [-1] + [ord(c) - 97 for c in input().rstrip()]
	char_cnt = [array('h', [0]) * (n + 1) for _ in range(26)]
	for i in range(1, n + 1):
		for j in range(26):
			char_cnt[j][i] = char_cnt[j][i - 1]
		char_cnt[a[i]][i] += 1
	q = int(input())
	ans = array('h', [0]) * q
	dp = [array('h', [0]) * (n + 1) for _ in range(26)]
	for qi in range(q):
		(m, c) = input().split()
		m = int(m)
		c = ord(c) - 97
		if dp[c][m]:
			ans[qi] = dp[c][m]
			continue
		(ok, ng) = (m, n + 1)
		while abs(ok - ng) > 1:
			mid = ok + ng >> 1
			for (l, r) in zip(range(n), range(mid, n + 1)):
				if char_cnt[c][r] - char_cnt[c][l] + m >= mid:
					ok = mid
					break
			else:
				ng = mid
		dp[c][m] = ans[qi] = ok
	sys.stdout.buffer.write('\n'.join(map(str, ans)).encode('utf-8'))
main()


import sys
input = sys.stdin.readline
N = int(input())
S = list(map(lambda x: ord(x) - ord('a'), list(input())[:-1]))
res = [[0] * (N + 1) for _ in range(26)]
for c in range(26):
	for l in range(N):
		x = 0
		for r in range(l + 1, N + 1):
			x += S[r - 1] != c
			res[c][x] = max(res[c][x], r - l)
	for i in range(N):
		res[c][i + 1] = max(res[c][i + 1], res[c][i])
for _ in range(int(input())):
	(x, s) = input().split()
	x = int(x)
	s = ord(s) - ord('a')
	print(res[s][x])


import string
import bisect
import sys

def main():
	lines = sys.stdin.readlines()
	n = int(lines[0])
	s = lines[1]
	vals = {}
	for c in string.ascii_lowercase:
		a = [i for (i, ch) in enumerate(s) if ch == c]
		m = len(a)
		b = [0]
		for length in range(1, m + 1):
			best = n
			for i in range(m - length + 1):
				j = i + length - 1
				best = min(best, a[j] - j - (a[i] - i))
			b.append(best)
		vals[c] = b
	q = int(lines[2])
	r = []
	idx = 3
	while q > 0:
		q -= 1
		query = lines[idx].split()
		idx += 1
		m = int(query[0])
		c = query[1]
		i = bisect.bisect_right(vals[c], m)
		r.append(str(min(n, i + m - 1)))
	print('\n'.join(r))
main()


import sys
from math import log2, floor, ceil, sqrt
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()

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

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

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

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
n = int(ri())
st = ri()
st = [ord(st[i]) - ord('a') for i in range(len(st))]
dp = list2d(26, n + 1, 0)
for i in range(0, 26):
	for j in range(n):
		cnt = 0
		for k in range(j, n):
			if st[k] != i:
				cnt += 1
			dp[i][cnt] = max(k - j + 1, dp[i][cnt])
for i in range(26):
	for j in range(1, n + 1):
		dp[i][j] = max(dp[i][j - 1], dp[i][j])
qq = int(ri())
for i in range(qq):
	temp = ri().split()
	ch = ord(temp[1]) - ord('a')
	m = int(temp[0])
	if m > n:
		m = n
	print(dp[ch][m])


n = int(input())
s = input()
dp = [[-1] * (n + 1) for x in range(26)]
for c in range(26):
	for l in range(n):
		n_c = 0
		for r in range(l, n):
			if s[r] == chr(ord('a') + c):
				n_c += 1
			dp[c][r - l + 1 - n_c] = max(dp[c][r - l + 1 - n_c], r - l + 1)
all_res = []
for i in range(int(input())):
	(m, c) = input().split()
	m = int(m)
	idx = ord(c) - ord('a')
	all_res.append(dp[idx][m] if dp[idx][m] != -1 else n)
print('\n'.join(map(str, all_res)))


import sys
input = sys.stdin.readline

def getCons(string, m, c):
	n = len(string)
	ans = 0
	(st, end) = (0, 0)
	while end < n:
		if string[end] == c:
			end += 1
		elif m:
			m -= 1
			end += 1
		else:
			while st < end and string[st] == c:
				st += 1
			st += 1
			m += 1
		ans = max(ans, end - st)
	return ans
t = 1
while t:
	t -= 1
	n = int(input())
	s = input().strip()
	dp = {}
	q = int(input())
	for _ in range(q):
		(m, c) = input().split()
		if (m, c) in dp:
			print(dp[m, c])
			continue
		dp[m, c] = getCons(s, int(m), c)
		print(dp[m, c])