We are given a problem: For each query (m_i, c_i), we have a string s of length n (n <= 1500). We can change at most m_i characters (any positions) to any letters (but presumably to maximize the longest contiguous segment consisting of only character c_i). Actually, we want to consider subsegments that consist entirely of color c after repainting. We can change up to m characters anywhere. The goal: maximize the length L such that there exists a subsegment [l, r] where after we repaint at most m characters (maybe less) we can make all characters in [l, r] equal to c, while outside we don't care? Wait careful: The description: "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."
Interpretation: We are allowed to repaint at most m pieces (any positions) arbitrarily. After we finish repainting, the garland becomes a new string s' (with at most m changes from original). Then we look at all contiguous subsegments that consist only of character c. The length of the longest such subsegment is the Koyomity. We want to maximize this Koyomity by choosing which positions to repaint (subject to at most m changes) and also the new colors (but obviously we will set them to c to help form long segments of c). However, repainting pieces that are already c might be wasteful, but we might repaint them to other colors? No, we wouldn't. So effectively, we can choose to change up to m positions to c (or other colors, but for maximizing longest c segment, we likely change non-c to c). But careful: Repainting a position to something else could help? For example, we might want to break a segment? The Koyomity is maximum length of a contiguous segment consisting of only c. If we change a character to non-c, that could split a long segment, so that would be detrimental. So optimal strategy: only change characters to c (since we want to maximize the longest contiguous run of c). Possibly we might also change some characters that are already c to something else to allow merging with other segments? No, merging would require those in between become c, not the opposite. So best is to convert some non-c to c, never convert c to non-c. So essentially, given a string s, for each query (m, c), we can change up to m characters (any positions) to c. Then find the longest contiguous segment that consists entirely of c after these changes. This is equivalent to: find the maximum length L such that there exists a subarray of length L that contains at most m characters that are not c originally. Because we can change those non-c to c (up to m changes). The subarray may also contain original c characters that we don't need to change. So problem reduces to: For each query (m, c), compute the maximum length of a subarray (contiguous) where the number of positions where s[i] != c is <= m.
Since n is only 1500, but q up to 200k, we need to answer queries efficiently. We can preprocess for each character c (26 letters) an array of positions where s[i] != c? Actually we can compute for each character c, the maximum length for each possible budget m (0..n) perhaps and store answers. Then each query we can answer in O(1). Since n <= 1500, we have 26 characters. For each character, we can compute the maximum subarray length with at most k mismatches (non-c) using two pointers technique for all k? But we need answers for all possible m (0 to n) for each c. Since n is small, we can compute for each c, for each left index, expand right and track mismatches, and compute longest length for each possible mismatch count? That would be O(n^2) per character if done carefully, total O(26 * n^2) ~ 26*2.25M = ~58.5M, acceptable. Alternatively, we could do for each c, run two pointers to compute for each left the maximum right such that mismatches <= some threshold, then update answers for mismatches? But we need to answer for any m. Precompute array best[c][m] = maximum length achievable with at most m changes to c. Then for each query (m, c) we output best[c][m].
How to compute best[c][m] efficiently for all m? Since n <= 1500, we can do for each c, for each left l from 0 to n-1, we iterate r from l to n-1, count mismatches (if s[r] != c) increment count. For each (l, r), length = r-l+1, mismatches = count. Then for this mismatches value, we could update best[c][mismatches] = max(best[c][mismatches], length). And since for any m' >= mismatches, the segment is also achievable with m' changes (because we can change up to m', more than mismatches). So after we have best for exact mismatches, we can do a suffix max: for m from n-1 down to 0, best[c][m] = max(best[c][m], best[c][m+1])? Actually we want for each m, the maximum length with at most m changes. So we can compute for each exact mismatches k, we have length L. Then for any m >= k, L is achievable. So we can take an array max_len[m] = maximum length over all segments with mismatches <= m. So we can compute an array exact[k] = max length with exactly k mismatches? But more precisely, for each segment, it contributes to all m >= mismatches. We could do for each left, as we extend right, we have mismatches count, and we could update best for that mismatches count with current length, but then later for larger mismatches we need to combine. After we collect all contributions, we can compute best_at_most[m] = max_{k <= m} exact_max[k]. However, there might be segments with mismatches less than some k that we haven't recorded as exact mismatches but we record for each mismatches count the max length observed with that exact mismatches. Then we can do a prefix maximum over k. But careful: Suppose we have a segment with mismatches = 2 and length = 10, and another with mismatches = 1 and length = 8. Then for m=1, max length = 8, for m=2, max = max(8,10)=10. So after we have an array best_exact[k] (maximum length for segments with exactly k mismatches), we then do for m from 0 to n: best_at_most[m] = max(best_at_most[m-1], best_exact[m])? But careful: "exactly k mismatches" might not be needed; we can also compute directly: For each m, we can compute the longest segment with <= m mismatches using sliding window, but since n is small, we can just do O(n^2) for each c and update an array for all m.
Simpler: For each c, initialize array ans[m] = 0 for m=0..n. Then for each left l, iterate r = l..n-1, maintain mismatches. For each (l, r) we have length len = r-l+1, mismatches = miss. Then set ans[miss] = max(ans[miss], len). After processing all pairs, we then compute final ans for at most m: for m from 1 to n: ans[m] = max(ans[m], ans[m-1]) (since if we can achieve length L with <= m-1 mismatches, we can also achieve it with m mismatches). Actually we need to make sure ans[m] = max length for at most m mismatches. So after the updates for exact mismatches, we have for each miss we store the max length for segments that have exactly that many mismatches. Then do a running max: for m in 1..n: ans[m] = max(ans[m], ans[m-1]). This yields the answer for each m. Complexity: For each c, we iterate all O(n^2) segments: 1500^2 = 2.25M. For 26 characters, total 58.5M, which is fine in C++ and Python? Python may be slower but still possibly okay? 58.5 million operations might be borderline in Python but with optimization and n=1500, 26 * (1500*1500)/2 ~ 26 * 1.125M = 29.25M if we only do each pair once? Actually nested loops: for left in range(n): miss = 0; for right in range(left, n): if s[right] != c: miss++; then update ans[miss] with len = right-left+1. That's about sum_{left} (n-left) = n(n+1)/2 ~ 1.125M per c. For 26 c => ~29.25M. That's definitely okay in Python (30 million simple operations). However we need to do for each query answer from a precomputed table. q up to 200k, just output.
But careful: We need to update ans for each c separately. We could also compute for each c on the fly by analyzing the string for each query, but q is large, so precompute.
One more nuance: m_i can be up to n (given), and it can be more than the number of mismatches in the whole string. But we already handle up to n.
Edge case: If m >= n, we can change all to c and get length n. Our ans array after prefix max will have ans[n] = n (since we can have a segment covering the whole string with mismatches = number of non-c in whole string, which might be less than n but we update ans[miss] and then prefix max will propagate). Actually we must ensure ans[m] for m >= max mismatches is n. Since the whole string segment length n, mismatches = count_non_c. So ans[count_non_c] = n (if we update). Then for m > count_non_c, prefix max will carry. So it's fine.
Implementation: We'll store an array best[26][n+1] (since m from 0 to n inclusive). For each c_index from 0 to 25, we compute.
Pseudo:
n = int(input())
s = input().strip()
q = int(input())
best = [[0]*(n+1) for _ in range(26)]
for ci in range(26):
target = chr(ord('a')+ci)
ans = [0]*(n+1)
for left in range(n):
miss = 0
for right in range(left, n):
if s[right] != target:
miss += 1
length = right - left + 1
if length > ans[miss]:
ans[miss] = length
# prefix max
for m in range(1, n+1):
if ans[m] < ans[m-1]:
ans[m] = ans[m-1]
best[ci] = ans
Then for each query:
m, c = input().split()
m = int(m)
ci = ord(c) - ord('a')
# note: if m > n, but m <= n per constraints, but just in case min(m, n)
print(best[ci][m])
But careful: In ans after prefix max, ans[m] should be the answer for at most m changes? Let's test: For each exact miss, we store max length for segments with exactly that many mismatches. Then we do prefix max from 0 to n. After prefix max, ans[m] = max_{k <= m} ans_exact[k]. That's indeed the answer for at most m mismatches. However, note that for m=0, we need ans[0] to be max length of segment with no mismatches (i.e., all c). That works.
But we also must consider that we might have segments with mismatches less than miss but longer length? The prefix max takes care.
One nuance: The algorithm as described updates ans[miss] only when length > current ans[miss]. But it's possible that for a given miss value, a longer segment exists with a smaller miss? Actually the prefix max later will propagate the larger length from smaller miss to larger m. However, consider a segment with miss=5 length=10, and another segment with miss=2 length=9. Then after prefix max, ans[5] will become max(ans[5], ans[4]), but ans[4] might be from miss=2? Actually ans[2] = 9, ans[3] maybe from some other? We do prefix max sequentially: after step, ans[1] = max(ans[0], ans[1]), ans[2] = max(ans[1], ans[2]), etc. So ans[5] ends up as max over all k <=5 of ans_exact[k]. So it will include length 9 from miss=2. So it's correct.
We could also directly, during expansion, for each left, we can know for each miss, the max right we can go? But this O(n^2) method is simpler.
But is there any hidden catch? The queries have m up to n (given), and we output best[c][m]. Since best array length is n+1, we have indices 0..n.
Complexities: O(26 * n^2) = 26 * 2.25M = 58.5M if we do loops for each left and right for each c. Actually n=1500 => n(n+1)/2 = 1.125M per c. Times 26 = 29.25M. That's the total number of inner loop iterations. In Python, 30 million loops is okay if efficient (use local variables, avoid function calls). Might be borderline but typically okay for 2 seconds? Let's estimate: 30 million simple operations, Python can handle maybe 50 million per second? Actually Python does about 30-100 million simple operations per second depending on hardware, but careful with overhead. Could be around 0.5-1 second. Also reading input and output for 200k queries is fine.
But we can also do for each c, we can compute the longest segment for each possible m using two pointers: For each left, we can find the farthest right such that mismatches <= some threshold. However, to get for all m, we might still need O(n^2) anyway? Actually we can compute an array of best lengths for each m by scanning with two pointers for each left? But we could compute for each m separately: for each m, use sliding window to compute longest segment with at most m mismatches. That would be O(26 * n * n) again? Since for each m (0..n) sliding window O(n) => O(26*n^2). That's similar. So O(n^2) per c is acceptable.
We need to be careful about memory: best[26][n+1] is small.
Now test with examples.
Example 1:
n=6, s="koyomi"
Compute for c='o':
We'll get ans[0]? longest segment with all 'o'? None? Actually there is 'o' at position 2? Wait string: k o y o m i? indices 1-based: 1:k,2:o,3:y,4:o,5:m,6:i. Segments with only 'o'? Single 'o's length 1. So ans[0]=1? Actually there is also contiguous? positions 2 is 'o', 3 is not, 4 is 'o', but not contiguous. So max length of all-o segment is 1. But we can repaint. For m=1: we can repaint y to o giving "kooomi" -> longest o segment "ooo" length 3. Our algorithm: For each segment, we count mismatches (non-o). For segment [2,4] (positions 2-4): s[2]='o', s[3]='y', s[4]='o': mismatches=1 (only 'y'), length=3 -> update ans[1]=3. For segment [1,6] mismatches=4? Actually non-o: k,y,m,i = 4 mismatches, length=6 -> ans[4]=6. For segment [1,5] length=5 mismatches: k,y,m? Actually s[1]=k,2=o,3=y,4=o,5=m => non-o: k,y,m => 3 mismatches => ans[3]=5. Also segment [2,5] length=4 mismatches: y,m =>2? Actually s[2]=o,3=y,4=o,5=m => non-o: y,m =>2 mismatches => ans[2]=4. So after prefix max: ans[0]=1, ans[1]=max(1,3)=3, ans[2]=max(3,4)=4, ans[3]=max(4,5)=5, ans[4]=max(5,6)=6, ans[5]=6, ans[6]=6. Then query (1,o) -> ans[1]=3 correct; (4,o)-> ans[4]=6 correct; (4,m) will have ans[4]=5? Let's check for c='m': original s: mismatches for m? We'll compute similarly; presumably ans[4]=5 as in example. Good.
Example 2: n=15, s="yamatonadeshiko". We'll trust.
Thus solution works.
But note: There is subtlety: The repaint at most m pieces: Are we allowed to repaint any pieces, not necessarily within the subsegment? Actually the definition: Nadeko repaints at most m pieces arbitrarily. Then after repainting, she finds the longest subsegment containing only c. So the repainting can be done anywhere, not necessarily confined to the subsegment. However, when we consider a candidate subsegment of length L, we need to ensure that we can make that entire subsegment be c by repainting at most m pieces. But we might also repaint some pieces outside the subsegment, but that wouldn't affect the subsegment. So the condition to achieve a subsegment of all c after repainting is exactly that within that subsegment, the number of positions not already c is <= m (since we can repaint those to c). Repainting outside does not help or hinder. So our reduction is correct.
One nuance: Could repainting pieces outside the subsegment allow a longer subsegment that includes those outside after repaint? But that would be captured by considering a larger subsegment that includes them. So effectively, we are looking for the longest contiguous segment where we can turn all non-c to c with at most m changes. That is exactly our reduction.
Thus solution stands.
Now we must implement in Python.
We can possibly speed up by computing for each character in a single pass? But not necessary.
Implementation details:
Read n, s, q.
n = int(input())
s = input().strip()
q = int(input())
Initialize best = [[0]*(n+1) for _ in range(26)]
For each character index ch_idx from 0 to 25:
target = chr(ord('a')+ch_idx)
ans = [0]*(n+1)
for left in range(n):
miss = 0
# iterate right
for right in range(left, n):
if s[right] != target:
miss += 1
length = right - left + 1
if length > ans[miss]:
ans[miss] = length
# prefix max
for m in range(1, n+1):
if ans[m] < ans[m-1]:
ans[m] = ans[m-1]
best[ch_idx] = ans
Then for each query:
line = input().split()
m = int(line[0])
c = line[1]
ch_idx = ord(c)-97
# Ensure m does not exceed n, but m <= n per constraints.
print(best[ch_idx][m])
Complexities: O(26 * n^2) about 30M loops. In Python, we need to make loops as fast as possible: Use local variable references, maybe convert s to list of chars? Or we can precompute for each character a boolean array of whether s[i] == that character? But then for each left and right we need to check condition; we can precompute an array of 0/1 for mismatch for each character. That could reduce the per-iteration cost: For each character, we can have a list diff of length n where diff[i] = 0 if s[i]==c else 1. Then during nested loops, we just sum diff[right] as we go. That might be faster because the condition becomes integer addition instead of char comparison. Since we loop over each c separately, we can precompute diff once per c, then nested loops just add diff[r]. This would be similar to constructing a binary array for each c. We can compute diff = [1 if s[i] != target else 0 for i in range(n)] before the left loop. Then inside inner loop: miss += diff[right]. This should be faster than char compare each time.
We can further optimize by using cumulative sums? Actually we can compute all subarray mismatches quickly? But O(n^2) is fine.
Given n=1500, 2615001500 = 58.5M inner loop operations with integer addition, plus prefix max. Should be okay.
But wait: The nested loops: for left in range(n): miss = 0; for right in range(left, n): miss += diff[right]; ... So each c we will have about n*(n+1)/2 = 1.125M iterations. 26*1.125M = 29.25M. Actually earlier I said 30M, that's fine.
We also need to compute diff array for each c, which is O(n) each, negligible.
Thus overall about 30M additions and comparisons, plus updates to ans list. Python can handle that within 2 seconds? Possibly yes with PyPy. But if time limit is strict, we can further micro-optimizations: Use list of integers for ans, but updating ans[miss] with max might be a little heavy. But it's just an if statement.
Alternatively, we can compute answer for each c using two-pointer technique for each possible left? Actually there is known method: For each left, we can find for each possible miss count, the max right? Not simpler.
Better: We can use the approach that for each c, we can compute longest subarray with at most k mismatches using sliding window for each k from 0..n. That would be O(26*n^2) as well. So comparable.
But we can also compute for each c a list of positions where s[i] != c (the mismatches). Then for each left, we can compute the right such that we have at most some mismatches by binary search. However, we would need to compute for all m, which is again O(n^2 log n) perhaps.
Given small n, simple is fine.
But note: The number of queries is up to 200k. Precomputation for each character yields a table of size 26*(n+1) = ~39k. Then answering queries is O(1).
Edge Cases:
- If m > n? Per constraints m ≤ n. So fine.
- If m=0, we output longest run of c originally.
Testing with example 3: all 'a's, for any c != 'a', mismatches = 10 for whole segment. For c='a', mismatches=0 for whole segment? Actually s all 'a', for c='a', whole segment has 0 mismatches, so ans[0] = 10 after update, then prefix max yields ans[0]=10, ans[1]=10,... So for query (10, 'b'), mismatches for whole segment = 10, so ans[10] after prefix max = 10? Since we have segment with miss=10 length=10, so ans[10] will be 10. So output 10. Works.
Thus solution correct.
But we need to be careful: For each left, we recompute miss from scratch. Could we precompute prefix sum of diff for each c? Then for each left, right we could compute miss = prefix[right+1]-prefix[left]. But then still double loop. However, we can then compute lengths for all subarrays quickly but we would still need to iterate all subarrays O(n^2). So not better.
Alternative: For each c, we can compute the maximum length for each possible m using two-pointer technique with O(n) per m, but that would be O(26n^2) also, but maybe less constant factor? Actually sliding window for each m: For fixed m, we can compute longest segment with at most m mismatches in O(n) by moving two pointers. If we do that for m=0..n, that's O(26n^2). That's same as O(26 * n^2) but we would run 2615001500 = 58.5M operations for sliding windows? Actually sliding window for each m would be: for each m, we run a two-pointer over n, performing about O(2n) operations per m, so total O(26 * n * (n+1)) = O(26 * n^2) = same order. But the inner operations might be simpler: For each m, we maintain count of mismatches in window, and we slide. That is 26 * n * n = 262.25M = 58.5M (since we have n+1 values of m, each O(n)). So about double our previous loops? Actually our nested loops were n(n+1)/2 per c = 1.125M per c. That is half of 2.25M per c (since n(n+1)/2 ~ n^2/2). So our method is roughly half the operations compared to sliding window for each m. So ours is better.
However, our method for each c: for each left (1500), we iterate over right from left to n-1, which totals ~1.125M per c. The sliding window for each m would be for each m (1501) we iterate over the whole array with two pointers, roughly 2n per m => ~215001501 = 4.5M per c. So ours is about 4 times less operations. So we should stick with nested loops.
Now, can we further reduce? We can also compute for each c the array of mismatches as diff. Then we can precompute prefix sums of diff to quickly compute mismatches for any subarray: miss = pref[r+1]-pref[l]. Then we could iterate over all l and r, but that still O(n^2). But using prefix sums would require subtraction each time; but our incremental approach (adding as we move right) is already efficient.
But we must be careful with Python loops: The inner loop does miss += diff[right] and then an if ans[miss] < length: ans[miss] = length. That's two operations per inner iteration. 30M * 2 = 60M operations. That's still okay. But we might also update ans[miss] for each (l, r). That could be many updates. But each update is just a conditional and maybe assignment.
We can micro-opt: assign ans_local = ans (list) and then update. But ans is a list of length n+1; updating by index is fine.
We can also use array module or numpy? Not needed.
Given time limit, should be okay.
But we must consider worst-case memory and time. Let's implement.
Potential improvement: For each c, we can compute the maximum length for each exact miss using two pointers? Actually we can compute for each left the max right for each miss? Not needed.
Implementation steps:
- Read n.
- Read s.
- Precompute best = [ [0]*(n+1) for _ in range(26) ]
- For each c in range(26):
target_char = chr(ord('a')+c)
diff = [1 if ch != target_char else 0 for ch in s] # list of 0/1
ans = [0]*(n+1)
for i in range(n):
miss = 0
# inner loop
for j in range(i, n):
miss += diff[j]
length = j - i + 1
if ans[miss] < length:
ans[miss] = length
prefix max
for k in range(1, n+1):
if ans[k] < ans[k-1]:
ans[k] = ans[k-1]
best[c] = ans
Alternatively, we can combine the prefix max into the same array.
Now answer queries:
for _ in range(q):
line = input().split()
m = int(line[0])
c = line[1]
idx = ord(c)-97
print(best[idx][m])
Check: For m possibly > n? Not per constraints, but safe to clamp m = min(m, n) if needed.
But note: There is a nuance: For some c, ans[m] after prefix max may not be defined for m > n? but m <= n. So fine.
Now test with given examples.
We'll simulate quickly.
Example 1:
n=6, s="koyomi"
Compute for c='o':
diff = [1,0,1,0,1,1]? Actually s: k (not o) ->1, o->0, y->1, o->0, m->1, i->1. So diff = [1,0,1,0,1,1]
Now loops:
i=0 (left=0)
j=0: miss=1, len=1 -> ans[1]=max(?,1) =>1
j=1: miss=1 (since diff[1]=0), len=2 -> ans[1]=max(1,2)=>2
j=2: miss=2, len=3 -> ans[2]=3
j=3: miss=2, len=4 -> ans[2]=max(3,4)=4
j=4: miss=3, len=5 -> ans[3]=5
j=5: miss=4, len=6 -> ans[4]=6
i=1 (left=1):
miss=0
j=1: diff[1]=0, miss=0, len=1 -> ans[0]=1
j=2: diff[2]=1, miss=1, len=2 -> ans[1]=max(2,2)=2 (already 2)
j=3: diff[3]=0, miss=1, len=3 -> ans[1]=max(2,3)=3
j=4: diff[4]=1, miss=2, len=4 -> ans[2]=max(4,4)=4
j=5: diff[5]=1, miss=3, len=5 -> ans[3]=max(5,5)=5
i=2:
miss=0
j=2: diff[2]=1, miss=1, len=1 -> ans[1]=max(3,1)=3
j=3: diff[3]=0, miss=1, len=2 -> ans[1]=3
j=4: diff[4]=1, miss=2, len=3 -> ans[2]=max(4,3)=4
j=5: diff[5]=1, miss=3, len=4 -> ans[3]=max(5,4)=5
i=3:
miss=0
j=3: diff[3]=0, miss=0, len=1 -> ans[0]=max(1,1)=1
j=4: diff[4]=1, miss=1, len=2 -> ans[1]=3
j=5: diff[5]=1, miss=2, len=3 -> ans[2]=4
i=4:
miss=0
j=4: diff[4]=1, miss=1, len=1 -> ans[1]=3
j=5: diff[5]=1, miss=2, len=2 -> ans[2]=4
i=5:
miss=0
j=5: diff[5]=1, miss=1, len=1 -> ans[1]=3
After loops, ans = [1,3,4,5,6,0,0]? Actually ans[5] and ans[6] remain 0 because we never got mismatches 5 or 6? For this string, maximum mismatches is 4? Actually the whole string has mismatches 4? Wait count of non-'o' in whole string is 4? Let's see: k,y,m,i = 4. So ans[4]=6. So ans[5] and ans[6] are 0. Then prefix max: For m=1: ans[1]=max(1,3)=3; m=2: ans[2]=max(3,4)=4; m=3: ans[3]=max(4,5)=5; m=4: ans[4]=max(5,6)=6; m=5: ans[5]=max(6,0)=6; m=6: ans[6]=max(6,0)=6. So best[ord('o')] = [1,3,4,5,6,6,6]? Actually length 7? n=6 so indices 0..6. So for query (1,o) -> ans[1]=3 correct; (4,o) -> ans[4]=6 correct.
Now for c='m':
s: koyomi, target m. diff: k!=m? 1, o!=m?1, y!=m?1, o!=m?1, m==m?0, i!=m?1 => [1,1,1,1,0,1]
Now compute max lengths for mismatches:
Whole string: mismatches 5? Actually there are 5 non-m: k,o,y,o,i =5. So ans[5]=6.
Segment [1..5] (0-index 0..4): mismatches: 1+1+1+1+0=4? Actually sum diff[0..4]=1+1+1+1+0=4, length=5 -> ans[4]=5.
Segment [1..6]? That's whole.
Segment [2..5] (1..4): diff[1]=1,2=1,3=1,4=0 => 3 mismatches, length=4 -> ans[3]=4? Actually we will see.
But after prefix max, for m=4: ans[4] gets max of ans[0..4] etc. Should be 5 as example says (4,m) outputs 5. So works.
Thus solution correct.
But there is a small nuance: The answer for m can be larger than n? No, m ≤ n. ans array up to n.
Now confirm that we cover all segments? Our loops cover all subsegments [l, r]. Good.
Now time: 26 * (n*(n+1)/2) = 26*1.125M = 29.25M loops. Inside each loop: miss += diff[j]; length = j-i+1; if ans[miss] < length: ans[miss] = length. That's about 3 operations. 30M * 3 = 90M operations maybe. But Python may manage 100M operations? Possibly borderline but we can try to optimize:
- Use local variables: For each c, we can store diff as a list, ans as a list, n as local.
- In inner loop, we can avoid recomputing length each time? we can maintain length as j-i+1; but j increments, so we can have a counter like cur_len = 0 and increment each iteration? Actually we can start with length = 0 and increment each iteration: length += 1. So:
for i in range(n):
miss = 0
length = 0
for j in range(i, n):
miss += diff[j]
length += 1
if ans[miss] < length:
ans[miss] = length
That's slightly faster.
-
Use enumerate? Not needed.
-
Use while loops? Not needed.
-
Use built-in functions? Not helpful.
Also, we can precompute for each c the diff array as a list of ints (0/1). That's fine.
Now prefix max: for i in range(1, n+1): if ans[i] < ans[i-1]: ans[i] = ans[i-1]. That's O(n) per c, negligible.
Thus total operations: For each c: ~1.125M inner loops * (1 addition for miss, 1 addition for length, 1 comparison and maybe assignment). That's about 3-4 operations per iteration. 30M*4=120M. Python can handle 120M operations? Possibly with PyPy it might be okay; with CPython maybe 2-3 seconds. But we must also account for 200k queries I/O. The problem may have time limit typical for Codeforces (2 seconds). However, this problem appears from Codeforces Round #... I recall the solution uses two pointers with precomputation for each character because n=1500 is small. Many Python solutions passed. But we can maybe reduce constant factors further.
We could compute for all characters in a single nested loop? For each left and right, we can iterate over characters? That would be O(n^2 * 26) = 1500^226 = 58.5M again but then we could update ans for each character simultaneously. That might be similar but with less overhead of outer character loop? Actually we have 26 loops over left-right anyway. But if we combine, we can reduce the number of loops over i and j? Currently, we have 26 * (n(n+1)/2) ~ 30M inner loops. If we combine, we still have (n*(n+1)/2) loops over (i,j) but inside each we loop over 26 characters to update ans for that character. That's 1.125M * 26 = 29.25M again. So similar. But then we have to maintain for each character a running mismatches count. That would be 26 counters per left, which could be heavy. But we could maintain an array of mismatches for each char as we extend right: For each left, we reset an array of mismatches for each char to 0, then as we extend right, we increment mismatches for each character that is not equal to the character? Actually we need diff per character: for each character c, we want to know if s[j] != c. That is equivalent to: for each c, mismatches[c] += (s[j] != c). So we can update all 26 counters each inner iteration. That would be 26 checks per inner iteration, making total operations ~29M * 26 = 754M, which is worse. So not good.
Thus the per-character nested loops approach is better.
We could also consider using bitsets? Not necessary.
Given n small, maybe we can also compute for each character using two-pointer for each possible left? Actually there is a known technique: For each left, we can compute the maximum right for each allowed mismatches by scanning. But our current method is essentially that.
We might also precompute for each character the positions of mismatches, then for each left we can binary search to find for each mismatches count the maximal right. However, we would then need to compute longest segment for each exact m? That would be O(n * number_of_mismatches) maybe less than O(n^2). But with n=1500, it's fine.
Alternatively, we can compute for each character the maximum length for each m using a DP or two-pointer by increasing m? There's another approach: For each character, we can transform the string into a binary array (1 if not equal to c). Then the problem becomes: given binary array, for each budget m, find longest subarray with sum <= m. That's a classic problem that can be solved for each m using two pointers in O(n) per m, but we need all m. Another approach: for each left, we can compute cumulative sum as we go right; but to compute best for all m, we can record for each left the mismatches and length, then for each mismatches value we keep max length, then take prefix max. That's exactly our O(n^2) method.
Now, can we do O(n^2) overall for all characters by using prefix sums and then for each left and right compute mismatches for all characters? That would be heavy.
Thus our method is acceptable.
But we must ensure that memory usage for best is correct: 26*(n+1) integers, each up to 1500, fine.
Now, I'll write final solution.
But before finalizing, let's double-check the constraints: q up to 200k, reading input must be efficient: use sys.stdin.read() to read all lines quickly.
Implementation plan:
import sys
def main():
data = sys.stdin.read().split()
it = iter(data)
n = int(next(it))
s = next(it).strip()
q = int(next(it))
# Precompute best
best = [[0](n+1) for _ in range(26)]
# Precompute for each character
for ci in range(26):
target = chr(ord('a')+ci)
diff = [1 if ch != target else 0 for ch in s] # list of ints
ans = [0](n+1)
# iterate left
for i in range(n):
miss = 0
length = 0
# Since we want to increment length each iteration, we can use for j in range(i, n):
for j in range(i, n):
miss += diff[j]
length += 1
if ans[miss] < length:
ans[miss] = length
# prefix max
for m in range(1, n+1):
if ans[m] < ans[m-1]:
ans[m] = ans[m-1]
best[ci] = ans
out_lines = []
for _ in range(q):
m = int(next(it))
c = next(it)
ci = ord(c)-97
# m could be > n? but not per constraints, but we can clamp: m = min(m, n)
if m > n:
m = n
out_lines.append(str(best[ci][m]))
sys.stdout.write("\n".join(out_lines))
if name == "main":
main()
Now test with sample:
Input:
6
koyomi
3
1 o
4 o
4 m
Our output:
3
6
5
Matches.
Edge Cases: When m is larger than any mismatches count we recorded, ans[m] after prefix max should be n. For example, m=n, ans[n] = n (since ans[miss_max] = n and prefix max will propagate). But if we never updated ans[n] (since miss_max could be < n), ans[n] after prefix max becomes the maximum over lower mismatches, which is n. So fine.
But we should ensure that for m=0, if there is no c at all, ans[0] remains 0? That would be correct: longest segment of only c with 0 changes is 0. But is that valid? The problem: subsegments containing pieces of only colour c. If there is no c at all, the longest subsegment length is 0? However, is it allowed to have subsegment length 0? Usually Koyomity would be the length of the longest subsegment containing pieces of only colour c; if there is none, length could be 0. But in examples, it seems there is always at least one occurrence? Not guaranteed. But the problem says "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". If there are none, then the maximum length is 0. However, can it be 0? The problem statements didn't explicitly forbid, but typical interpretation would allow 0 if no such segment. However, can we achieve a segment of length 0 after repainting? Actually we could repaint at most m pieces, but we might choose not to repaint anything. If there is no c originally, we could repaint some pieces to c, so then there will be segments after repaint. But for m=0 and no c originally, the answer should be 0. That seems plausible. Our algorithm would set ans[0] = length of longest all-c segment with zero mismatches; if there are no c, then longest all-c segment length is 0. So ans[0] = 0. That's correct.
Now, we need to be careful about the ans list initialization: we set ans = [0]*(n+1). That works.
Now, check memory: best is 26*(n+1) ints, fine.
Now, let's consider possible micro-optimizations: Instead of building diff for each character by list comprehension each time, we could precompute for each character a list of 0/1? Actually we could precompute a 2D array mismatch[26][n] where mismatch[ci][i] = 1 if s[i] != chr(ci+'a') else 0. That would be 26 * 1500 = 39k booleans, trivial. Then for each ci, we can just reference that array. But building it once might be faster than recomputing diff for each ci using list comprehension (which loops over n 26 times anyway). But we are already looping over n 26 times in the nested loops anyway. However, precomputing could reduce the overhead of checking condition each time we create diff. But we can create diff inside the character loop; we still need to iterate over n to build diff. That's O(26*n) which is negligible. So it's fine.
Alternatively, we could compute the nested loops directly without diff: for i in range(n): miss=0; for j in range(i, n): if s[j] != target: miss+=1; length+=1; ... This avoids diff list allocation but adds a character comparison each time. Which is faster? Character comparison vs integer addition from a list? In Python, char comparison might be slower than integer list access? But both are fairly fast. I'd try to use diff list to avoid repeated char comparisons and attribute lookups? Actually each iteration we'd have to index s and compare to target; that's a Python string indexing and comparison. Might be slightly slower than accessing a small list of ints. But we can test both. Since n is small, it might not matter.
But we can further optimize by precomputing for each character the positions of non-c, but not needed.
Given typical Codeforces Python solutions for this problem (CF 629C? Actually problem 629C? Not sure) I recall many Python solutions used O(26*n^2) precomputation and passed. So it's fine.
One more improvement: Instead of updating ans[miss] inside the inner loop for every (i,j), we could compute for each left, the mismatches as we expand and record the maximum length for each miss value encountered. However, we need the max over all segments. Since we are updating for each segment, it's fine.
Potential memory: ans array of size n+1 per c, we allocate new each time and assign to best[ci]. That's okay.
Now, ensure we handle input reading for large q: Use sys.stdin.read().split() to quickly read tokens.
Now, let's think about correctness more formally: For each c, we consider all subsegments. For a subsegment [l, r], let k = number of characters not equal to c. After repainting at most k characters (to c), we can turn the whole segment to c. So the segment length is achievable with budget k. Therefore, for each budget m >= k, this segment length is achievable. Therefore, the maximum length for a given budget m is the maximum length over all segments with k <= m. Our precomputation: For each exact k, we store the maximum length of a segment with exactly k mismatches. Then we compute prefix max to get for each m the maximum length for at most m mismatches. This yields correct answer.
One nuance: The repainting budget is at most m, so we can also change fewer than m. So indeed we can achieve any segment with k <= m.
Edge case: Could there be a segment that we can achieve by repainting some characters inside it to c, but also repainting some characters outside to c? That would be a larger segment if we repaint outside as well, but that's captured by considering that larger segment with possibly more mismatches. For example, we have a segment with many non-c inside, but by repainting some outside we might extend it further? But that would be part of a larger contiguous segment that includes those outside positions. So we consider all segments. Thus our method is complete.
Thus solution is correct.
Now, check for possible overflow: n up to 1500, lengths up to 1500, int.
Now, test with a random case to ensure.
Time complexity: O(26 * n^2 + q). For n=1500, 262.25M=58.5M? Wait we earlier computed 26 * n(n+1)/2 = 261.125M = 29.25M. But our code has nested loops: for i in range(n): for j in range(i, n): ... That's exactly n(n+1)/2 iterations per character. So total about 29.25M iterations. That's less than 58.5M. So good.
But we also have building diff per c: 26*n = 39k, trivial.
Thus the solution should pass.
Now, implement.
One minor improvement: Instead of recomputing ans list from scratch each time, we can reuse but not needed.
Now, I'll write final answer.
But before final, note that we should use fast I/O. We'll read all tokens with sys.stdin.buffer.read().split().
Now, sample tests.
Let's run mental test for second example to verify.
Second example: n=15, s="yamatonadeshiko". We'll compute for a and b. Probably matches.
Now, consider potential off-by-one: ans array indices from 0 to n inclusive. mismatches count can be up to n (if all mismatches). So ans size n+1 is fine.
But we must note: In nested loops, when we update ans[miss], miss could be up to n (e.g., if all mismatches). However, ans has indices 0..n, so it's safe.
Now, prefix max: for m in range(1, n+1): if ans[m] < ans[m-1]: ans[m] = ans[m-1]. This ensures ans[m] is the maximum length for at most m mismatches.
Now, answer queries: print(best[ci][m]).
Now, we may need to consider that m may be 0. That's fine.
Now, is there any case where the answer for m larger than n might be asked? Per constraints m <= n, so fine.
Thus solution ready.
But perhaps we can do even faster: For each c, we can compute the longest segment for each m using two-pointer technique but only for each left? But it's fine.
Alternative: For each c, we can compute for each left the longest right for each possible number of changes? That would be O(n^2) anyway.
Now, I'll finalize.
Edge Cases:
-
n=1: Then for each c, diff: 0 if s[0]==c else 1. For left i=0, j=0: miss=diff[0], length=1. ans[0] or ans[1] gets 1. Prefix max: ans[0] maybe 1 if s[0]==c else 0? Actually if s[0]==c, diff[0]=0, so ans[0]=1; ans[1] initially 0; after prefix max, ans[1]=1. So for m=0, answer 1 if matches, else 0; for m=1, answer 1. That's correct.
-
All characters same: For that character, diff all zeros. Then for each left, we will update ans[0] with length. For i=0, j from 0..n-1: lengths 1..n, miss=0, so ans[0] becomes n after final j. So ans[0]=n. Prefix max: ans[m]=n for all m. For other characters, diff all ones, so for each segment, miss = length, so ans[miss] updated with length. So ans[0]=0; ans[1]=1 (from segment length1), ans[2]=2,... ans[n]=n. After prefix max: ans[0]=0, ans[1]=1, ans[2]=2,... ans[n]=n. So for m=10 with all a's and c='b', ans[10]=10 if n>=10, which matches example 3.
So correct.
Now, about reading input: Use sys.stdin.buffer.read().split() to get tokens. The string s is given as a line. We'll read it.
Now, we need to ensure that s is stripped of newline, but .split() will handle it.
Now, output: use sys.stdout.write.
Now, one more thought: Could there be any scenario where the answer is not simply the longest segment with at most m mismatches? What about the ability to repaint characters to c outside the segment? That could create a longer segment only if we also repaint inside to c, but that is captured by considering a larger segment that includes those outside. Since we can repaint anywhere, if we repaint some positions outside a segment to c, they could merge with the segment to create a larger contiguous c segment. But that larger segment would have been considered in our enumeration of all possible contiguous segments after repainting. Because we are allowed to repaint any positions, the final string can have any configuration with at most m changes. So we can consider any segment in the final string that consists of only c. The positions in that segment may have been repainted or originally c. The condition for existence of such a final string with a given segment as all c is that the number of positions in that segment that are not originally c is <= m (we can change them), regardless of what happens outside. So the maximum length of such a segment over all possible final strings is exactly the maximum over all initial segments of length L where the number of non-c <= m. Because we can choose to repaint exactly those non-c positions within the segment, and do nothing else, achieving that segment all c. So it's correct.
Thus final solution.
Now, code.
Potential micro-optimizations: Use array of ints? Not needed.
We can also compute best using a two-pointer approach per c that computes longest segment for each left? But we already have a good one.
Given that n=1500, we can also compute for each c the prefix sums of mismatches, then for each l, we can binary search for each m? But that would be O(n^2 log n) maybe similar.
We'll implement as described.
Now, test with sample input:
Input:
6
koyomi
3
1 o
4 o
4 m
Our code:
Read tokens: ["6","koyomi","3","1","o","4","o","4","m"]
n=6, s="koyomi", q=3.
Precompute best:
For c='o', ans after loops: as we computed earlier, after prefix max ans = [1,3,4,5,6,6,6] (size 7). best[14? Actually 'o' is index 14? ord('o')-97 = 14. So best[14][1]=3, best[14][4]=6.
For c='m' index 12: ans after prefix max should give best[12][4]=5.
Then output lines: 3,6,5.
Matches.
Now second example: We'll quickly test with code mental: Should output as expected.
Now, third example: n=10, s="aaaaaaaaaa", q=2, (10 b,