DNA Subsequence

Time limit1sMemory limit128 MB

Summary
Find the longest common subsequence of two words where every maximal matched run must be a contiguous block of at least K characters in both words.
Level

Hard8 of 10

Topics
Dynamic programming, String, Prefix sum
Solved
No attempts yet

Problem

Sanggeun is a computer scientist studying DNA sequences, and he wants to compute a constrained longest common subsequence of two strings.

Consider a word w=a1a2⋯arw = a_1 a_2 \cdots a_r over an alphabet Σ\Sigma (each ai∈Σa_i \in \Sigma). A subsequence of ww is x=ai1ai2⋯aisx = a_{i_1} a_{i_2} \cdots a_{i_s} chosen by indices 1≤i1<i2<⋯<is≤r1 \le i_1 < i_2 < \cdots < i_s \le r. A subsequence in which ij+1=ij+1i_{j+1} = i_j + 1 for every j=1,2,…,s−1j = 1, 2, \ldots, s-1 (that is, characters taken from consecutive positions) is called a segment of ww. For example, ove is a segment of lovely, while loly is a subsequence of lovely but not a segment.

A word that is a subsequence of both w1w_1 and w2w_2 is a common subsequence; the longest such word is a longest common subsequence. The empty word of length 00 is always a common subsequence.

Now add the following restriction. The chosen common subsequence must be formed by concatenating, in order, common segments — blocks that occur contiguously in both words — and every common segment used must have length at least KK. Equivalently, when the common subsequence is aligned against each word, every maximal run of consecutively matched characters must have length at least KK.

For example, with K=3K = 3 and the two words lovxxelyxxxxx and xxxxxxxlovely, the word lovely can be split into the two common segments lov (length 33) and ely (length 33), so it satisfies the condition. On the other hand, xxxxxxx cannot be split into common segments that are all of length at least K=3K = 3, so it does not satisfy the condition.

Given the two words and KK, write a program that finds the maximum possible length of a common subsequence satisfying the above condition.

Input

The input consists of several test cases. The first line of each test case contains an integer KK (1≤K≤1001 \le K \le 100). The next two lines each contain one string consisting only of lowercase letters. Each string has length between 11 and 10001000, inclusive. The last line of the input contains a single 00, which marks the end of the input.

Output

For each test case, print on its own line the maximum length of a common subsequence that satisfies the condition. If there is no such common subsequence of positive length, print 00.

Examples1

  1. Example 1

    Input
    3
    lovxxelyxxxxx
    xxxxxxxlovely
    1
    lovxxelyxxxxx
    xxxxxxxlovely
    3
    lovxxxelxyxxxx
    xxxlovelyxxxxxxx
    4
    lovxxxelyxxx
    xxxxxxlovely
    0
    
    Expected output
    6
    7
    10
    0