Problem:


  MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Longest Common Subsequence

For given two sequences $X$ and $Y$, a sequence $Z$ is a common subsequence of $X$ and $Y$ if $Z$ is a subsequence of both $X$ and $Y$. For example, if $X = \{a,b,c,b,d,a,b\}$ and $Y = \{b,d,c,a,b,a\}$, the sequence $\{b,c,a\}$ is a common subsequence of both $X$ and $Y$. On the other hand, the sequence $\{b,c,a\}$ is not a longest common subsequence (LCS) of $X$ and $Y$, since it has length 3 and the sequence $\{b,c,b,a\}$, which is also common to both $X$ and $Y$, has length 4. The sequence $\{b,c,b,a\}$ is an LCS of $X$ and $Y$, since there is no common subsequence of length 5 or greater.

  Write a program which finds the length of LCS of given two sequences $X$ and $Y$. The sequence consists of alphabetical characters.

Input

  The input consists of multiple datasets. In the first line, an integer $q$ which is the number of datasets is given. In the following $2 \times q$ lines, each dataset which consists of the two sequences $X$ and $Y$ are given.

Output

  For each dataset, print the length of LCS of $X$ and $Y$ in a line.

Constraints

$1 \leq q \leq 150$

$1 \leq$ length of $X$ and $Y$ $\leq 1,000$

$q \leq 20$ if the dataset includes a sequence whose length is more than 100

Sample Input 1

3
abcbdab
bdcaba
abc
abc
abc
bc

Sample Output 1

4
3
2

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.



Sample input:
3
abcbdab
bdcaba
abc
abc
abc
bc


Sample output:
4
3
2

Submission status: Accepted

Solution code:
def longest_common_subsequence(X, Y):
    X = " " + X
    Y = " " + Y

    length_X = len(X)
    length_Y = len(Y)

    c = [0] * length_Y

    for i in range(1, length_X):
        
        c_ = c[:]

        for j in range(1, length_Y):
            if X[i] == Y[j]:
                c[j] = c_[j - 1] + 1
            elif c_[j] < c[j - 1]:
                c[j] = c[j - 1]

    return c[-1]


q = int(input())


for _ in range(q):

    X = input()
    Y = input()

    print(longest_common_subsequence(X, Y))

Submission status: Accepted

Solution code:
def lcs(X, Y):
    C = []
    for y in Y:
        bgn_idx = 0
        for i, cur_idx in enumerate(C):
            chr_idx = X.find(y, bgn_idx) + 1
            if chr_idx == 0:
                break
            C[i] = min(cur_idx, chr_idx)
            bgn_idx = cur_idx
        chr_idx = X.find(y, bgn_idx) + 1
        if chr_idx != 0:
            C.append(chr_idx)
    return len(C)

q = int(input())
for _ in range(q):
    X = input()
    Y = input()
    print(lcs(X, Y))

Submission status: Accepted

Solution code:
def lcs(s1_raw, s2_raw):
    dp = []
    for s2 in s2_raw:
        start = 0
        for i, cnt in enumerate(dp):
            index = s1_raw.find(s2, start) + 1
            if not index:
                break
            else:
                dp[i]  = min(cnt , index)
                start = cnt
        index = s1_raw.find(s2, start) + 1
        if index:
            dp.append(index)
    return len(dp)


if __name__ == "__main__":
    q = int(input())
    for _ in range(q):
        x = input()
        y = input()
        print(lcs(x, y))

Submission status: Accepted

Solution code:
def main():
    N = int(input())

    string_data = [input() for _ in range(N * 2)]

    for _ in range(N):
        s = string_data.pop(0)
        t = string_data.pop(0)

        dp = [0] * (len(t) + 1)

        for i, sc in enumerate(s):
            tmp = dp[:]
            for j, tc in enumerate(t):
                if sc == tc:
                    dp[j + 1] = tmp[j] + 1
                elif dp[j + 1] < dp[j]:
                    dp[j + 1] = dp[j]

        print(dp[-1])


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_10_C

最長共通部分列
"""


c = []
def prep_array(X, Y):
    global c
    """ 値が0の2次元配列を用意する。サイズは入力データの最大値を想定して縦横(1000+1)以上必要。 """
    # from array import array
    # c = [array('I', [0] * (len(X)+1)) for _ in range(len(Y)+1)]  #  arrayで用意
    c = [[0]*(len(Y)+2) for _ in range(len(X)+2)] #  リストで用意
    return c


def check_max(array):
    """ 2次元配列の中の最大の値を返す """
    max_lcs = 0
    for row in array:
        temp_max = max(row)
        if temp_max > max_lcs:
            max_lcs = temp_max
    return max_lcs


def calc_lcs4(X, Y, c):
    """
    Y[j]のアクセス方法を変更
    リストの値を一旦変数に保存するように変更
    最長共通部分長を関数内で計算するように変更
    4/5 のテストデータを使用してプロファイリングすると実効時間は 5.6秒
    """
    X = ' ' + X
    Y = ' ' + Y
    m = len(X)
    n = len(Y)
    max_lcs = 0

    pre_row = c[0]
    for i in range(1, m):
        row = c[i]
        XX = X[i]
        for j, YY in enumerate(Y):
            if XX == YY:
                pr_j1 = pre_row[j - 1]
                row[j] = pr_j1 + 1
                if pr_j1+1 > max_lcs:
                   max_lcs = pr_j1 + 1
            else:
                pr_j = pre_row[j]
                r_j1 = row[j-1]
                if pr_j >= r_j1:
                    row[j] = pr_j
                else:
                    row[j] = r_j1
        pre_row = row
    return max_lcs


if __name__ == '__main__':
    # データの入力
    num = int(input())
    #f = open('input.txt')
    #num = int(f.readline())

    for _ in range(num):
        X = input().strip()
        Y = input().strip()

        # 処理の実行
        result = calc_lcs4(X, Y, prep_array(X, Y))

        # 結果の表示
        print(result)

Submission status: Accepted

Solution code:
# coding: utf-8

def lcs(str1, str2):
    # dp[i][j]: str1のi番目までとstr2のj番目までを使って作れるlcs
    dp = [[0 for _ in range(len(str2)+10)] for _ in range(len(str1)+10)]
    # 計算量は1000*1000=10^6なんだけど時間切れ？
    for i in range(0,len(str1)):
        for j in range(0,len(str2)):
            v = max(dp[i+1][j],dp[i][j+1])
            if str1[i] == str2[j]:
                dp[i+1][j+1] = max(v,dp[i][j] + 1)
            else:
                dp[i+1][j+1] = max(v,dp[i][j])
    return dp[len(str1)][len(str2)]

# てか、普通のdpじゃ通らないってどんだけシビアなんだ
def lcs_another(str1, str2):
    # str1の中の文字列とstr2の中の文字列が一致したらその位置から先を＋１するだけ
    # なんか自然には思い浮かばないなあ
    dp = [0 for _ in range(len(str2)+10)]
    for c1 in str1:
        tmp = dp[:]
        for i, c2 in enumerate(str2):
            if c1 == c2:
                dp[i+1] = tmp[i]+1
            elif dp[i+1] < dp[i]:
                dp[i+1] = dp[i]
    return dp[len(str2)]

p = int(input().rstrip())
for _ in range(p):
    line1 = input().rstrip()
    line2 = input().rstrip()
    print(lcs_another(line1,line2))

Submission status: Accepted

Solution code:
import bisect

INF = float('inf')
q = int(input())
for i in range(q):
    x = input()
    y = input()
    dic = {}
    for i,xx in enumerate(x):
        if xx in dic : dic[xx].append(i)
        else : dic[xx] = [i]
    inc = []
    size = -1
    for j,yy in enumerate(y):
        if not (yy in dic):continue
        inc.append([])
        size += 1
        for k in dic[yy]:
            inc[size].append(k)
    #incのLISを求めればよい
    n = len(inc)
    dp =  [INF for i in range(n)]
    temp = [INF for i in range(n)]

    for ii in inc:
        for i in ii:
            p = bisect.bisect_left(dp, i)
            temp[p] = min(i,temp[p])
        dp = temp[:]


    print(bisect.bisect_left(dp, INF))

Submission status: Accepted

Solution code:
def lcs(s1, s2):
    dp = []
    for s2_k in s2:
        bgn_idx = 0
        for i, cur_idx in enumerate(dp):
            chr_idx = s1.find(s2_k, bgn_idx) + 1
            if not chr_idx:
                break
            dp[i] = min(cur_idx, chr_idx)
            bgn_idx = cur_idx
        else:
            chr_idx = s1.find(s2_k, bgn_idx) + 1
            if chr_idx:
                dp.append(chr_idx)
    return len(dp)


n = int(input())
for _ in range(n):
    x = input()
    y = input()
    print(lcs(x, y))

Submission status: Accepted

Solution code:
import sys
def longest_common_subsequence(line1, line2):
    n_rows = len(line2) + 1
    array = [0] * n_rows

    ix_ = [x for x in range(n_rows)]
    ix = [x+1 for x in range(n_rows)]

    for l1_letter in line1:
        prev_array = array[:]
        for i_row_, i_row, l2_letter in zip(ix_, ix, line2):
            if l1_letter == l2_letter:
                array[i_row] = prev_array[i_row_] + 1
            else:
                up = prev_array[i_row]
                left = array[i_row_]
                array[i_row] = up if up > left else left
    return array[-1]

calc_time = False
if calc_time: import time; start = time.time()
def main():
    n = int(input())
    lines = sys.stdin.readlines()
    for i in range(0, 2*n, 2):
        ans = longest_common_subsequence(lines[i].rstrip(), lines[i+1].rstrip())
        print(ans)
    return

main()
if calc_time:print("elapsed:",time.time()-start)

Submission status: Accepted

Solution code:
def LCS(X, Y):
    n = len(X)
    m = len(Y)
    T = [0]*(n+1)
    
    for j in range(m):
        T_old = T[:]
        c = Y[j]
        for i in range(n):
            if X[i] == c:
                T[i] = T_old[i-1] + 1
            elif T[i-1] > T[i]:
                T[i] = T[i-1]            
    return T[len(X)-1] 



q = int(input())
for cnt in range(q):
    X = input()
    Y = input()
    print(LCS(X, Y))

Submission status: Accepted

Solution code:
#! /usr/bin/env python3
# -*- coding: utf-8 -*-

from sys import setrecursionlimit
from functools import lru_cache


def lcs(s1, s2):
    cost = [0]
    for c in s2:
        #print("c=", c)
        for i in reversed(range(len(cost))):
            index = s1.find(c, cost[i]) + 1
            if index:
                if i + 1 < len(cost):
                    cost[i + 1] = min(cost[i + 1], index)
                else:
                    cost.append(index)
            #print("i={}, index={}, cost={}".format(i, index, cost))
    return len(cost) - 1


def main():
    setrecursionlimit(10000)

    q = int(input())

    for _ in range(q):
        x = input()
        y = input()
        print(lcs(x, y))


if __name__ == '__main__':
    # print("TCCAGATGG")
    # print("TCACA")
    #print(lcs("TCCAGATGG", "TCACA"))
    main()

Submission status: Accepted

Solution code:
# 最長共通部分列

def lcs(x, y):
    m = len(x)
    n = len(y)
    c = [0] * (n + 1)
    for i in range(m):
        c2 = c[:]
        for j in range(n):
            if x[i] == y[j]:
                c[j + 1] = c2[j] + 1
            elif c[j + 1] < c[j]:
                c[j + 1] = c[j]
    return c[-1]


n = int(input())
Z = [0] * n
for i in range(n):
    X = input()
    Y = input()
    Z[i] = lcs(X, Y)
for z in Z:
    print(z)

Submission status: Accepted

Solution code:
def longest_common(x, y):
  cost = [0]
  for c in y:
    for i in range(len(cost)-1, -1, -1):
      index = x.find(c, cost[i]) + 1
      if index:
        if i + 1 < len(cost):
          cost[i + 1] = min(cost[i+1], index)
        else:
          cost.append(index)
  return len(cost) -1

n = int(input())
for _ in range(n):
  x = input()
  y = input()
  print(longest_common(x, y))

Submission status: Accepted

Solution code:
def common(x,y):
    n = len(x)
    m = len(y)
    c1 = [0for i in range(m+1)]
    for i in range(n):
        e1 = x[i]
        c2 = c1[:]
        for j in range(m):
            if (e1 == y[j]):
                c1[j+1] = c2[j] + 1
            elif (c1[j+1] < c1[j]):
                c1[j+1] = c1[j]
    return(c1[-1])


t = int(input())
for w in range(t):
    fseq = str(input()) ##Xk
    sseq = str(input()) ##Yl
    print(common(fseq,sseq))

Submission status: Accepted

Solution code:
def lcs(x, y):
    a = len(x)
    b = len(y)
    c1 = [0] * (b + 1)
    for i in range(a):
        e1 = x[i]
        c2 = c1[:]#スライス
        for j in range(b):
            if e1 == y[j]:
                c1[j+1] = c2[j] + 1
            elif c1[j+1] < c1[j]:
                c1[j+1] = c1[j]
    return c1[-1]
    
n = int(input().rstrip())#rstripで余計な空白削除
ret = []
for i in range(n):
    s1 = input().rstrip()
    s2 = input().rstrip()
    ret.append(lcs(s1, s2))
print(*ret, sep="\n")

Submission status: Accepted

Solution code:
# Dynamic Programming - Longest Common Subsequence
def lcs_len(X,Y):
    m,n = len(X),len(Y)
    LCS_r = [0 for _ in range(m+1)]
    for y in Y:
        previous = LCS_r[:]
        for i,x in enumerate(X):
            if x == y:
                LCS_r[i+1] = previous[i] + 1
            elif LCS_r[i] > previous[i+1]:
                LCS_r[i+1] = LCS_r[i]
    return LCS_r[-1]

q = int(input())
for _ in range(q):
    X = input()
    Y = input()
    print(lcs_len(X,Y))

Submission status: Runtime Error

Solution code:
from string import ascii_letters

def llcs(x, y):
    pm = dict((zip(ascii_letters, [0] * 52)))
    for c in pm:
        for i, xc in enumerate(x):
            if c == xc:
                pm[c] |= (1 << i)
    
    V = (1 << len(x)) - 1
    
    for yc in y:
        V = ((V + (V & pm[yc])) | (V & ~pm[yc]))
    
    ans = bin(V)[-len(x):].count('0')
    
    return ans

from sys import stdin

def solve():
    file_input == stdin
    q = int(file_input.readline())
    for i in range(q):
        s1 = file_input.readline().rstrip()
        s2 = file_input.readline().rstrip()
        print(llcs(s1, s2))

solve()

Submission status: Runtime Error

Solution code:
ascii_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

def llcs(x, y):
    pm = dict((zip(ascii_letters, [0] * 52)))
    for c in pm:
        for i, xc in enumerate(x):
            if c == xc:
                pm[c] |= (1 << i)
    
    V = (1 << len(x)) - 1
    
    for yc in y:
        V = ((V + (V & pm[yc])) | (V & ~pm[yc]))
    
    ans = bin(V)[-len(x):].count('0')
    
    return ans

from sys import stdin

def solve():
    #file_input = stdin
    file_input = open("ALDS1_10_C_in_4", 'r')
    q = int(file_input.readline())
    for i in range(q):
        s1 = file_input.readline().rstrip()
        s2 = file_input.readline().rstrip()
        print(llcs(s1, s2))

solve()

Submission status: Runtime Error

Solution code:
n=int(input())
x=[0 for i in range(n)]
y=[0 for i in range(n)]
for i in range(n):
    x[i]=input()
    y[i]=input()

for i in range(n):
    X=list(x[i])
    Y=list(y[i])
    a=[int(0) for i in range(len(X))]
    for j in range(len(X)):
        b=-1
        for l in range(j,len(X)):
            for k in range(len(Y)):
                if X[l]==Y[k] and b<k:
                    b=k
                    a[j]+=1
                    break
                
    print(max(a))
a=[0 for i in range(n)]a=[0 for i in range(n)]

Submission status: Runtime Error

Solution code:
def main():
    n=int(input())
    result=[]
    for i in range(n):
        a=input()
        b=input()
        array=[[1 for i in range(len(a))] for j in range(len(b))]
        for i in range(1,len(a)):
            for j in range(1,len(b)):
                c=0
                if a[j] == b[i]:
                    c=1
                array[i][j]=max(array[i-1][j],array[i][j-1],array[i-1][j-1]+c)
        result.append(array[len(a)-1][len(b)-1])
    for i in result:
        print(i)
if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
def main():
    n = int(input())
    result = []
    for i in range(n):
        a = input()
        b = input()
        array = [[1 for i in range(len(a))] for j in range(len(b))]
        for i in range(1, len(a)):
            for j in range(1, len(b)):
                c = 0
                if a[j] == b[i]:
                    c = 1
                array[i][j] = max(
                                    array[i-1][j],
                                    array[i][j-1],
                                    array[i-1][j-1]+c)
        result.append(array[len(a)-1][len(b)-1])
    for i in result:
        print(i)
if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
n=int(input())
ans=[]
for k in range(n):
    s1=input()
    s2=input()
    dp=[[0 for i in range(len(s2)+1)] for j in range(len(s1)+1)]
    for i in range(1,len(s1)+1):
        for j in range(1,len(s2)+1):
            if s1[i-1]==s2[j-1]:
                dp[i][j]=dp[i-1][j-1]+1
            else:
                dp[i][j]=max(dp[i-1][j],dp[i][j-1])


    ans.append(dp[len(s1+1)][len(s2+1)])
for a in ans:
    print(a)

Submission status: Runtime Error

Solution code:
import java.util.*;
public class Main{
    public static void main(String[] args){
	Scanner sc=new Scanner(System.in);
	int q=sc.nextInt();
	int[] ans=new int[q];
	for(int n=0;n<q;n++){
	    String X=sc.next();
	    String Y=sc.next();
	    int[][] A=new int[X.length()+1][Y.length()+1];
	    for(int i=1;i<X.length()+1;i++){
		for(int j=1;j<Y.length()+1;j++){
		    if((X.substring(i-1,i)).equals(Y.substring(j-1,j))){
			A[i][j]=A[i-1][j-1]+1;
		    }else{
			if(A[i-1][j]<A[i][j-1]){
			    A[i][j]=A[i][j-1];
			}else{
			    A[i][j]=A[i-1][j];
			}
		    }
			
		}
	    }
	    ans[n]=A[X.length()][Y.length()];
	}
	for(int num:ans){
	    System.out.println(num);
	}
    }
}

Submission status: Runtime Error

Solution code:
def lcs(list1,list2):
    f=[[0 for x in range(len(list1)+1)]for y in range(len(list2)+1)]#表の確保

    for j in range(len(list1)):
        if list1[j]==list2[0]:
            f[j][0]=1
    for j in range(len(list2)):
        if list1[0]==list2[j]:
            f[0][j]=1
            
    for j in range(1,len(list1)):
        for k in range(1,len(list2)):
            if list1[j]==list2[k]:
                f[j][k]=f[j-1][k-1]+1
            else:
                f[j][k]=max(f[j-1][k],f[j][k-1])

    print(f[len(list1)-1][len(list2)-1])



n=int(input())
l=[]

for i in range(n*2):
    str=input()
    l+=[list(str)]
l[0].pop()

i=0
while True:#(文字列の数/2)回繰り返す
    if i>2*n-2:
        break
    lcs(l[i],l[i+1])
    i+=2

Submission status: Runtime Error

Solution code:
m = int(input())
for i in range(m):
    str1 = input()
    str2 = input()
    A = [0 for j in range(len(str2)+1)]
    for char1 in str1:
        A_copy = A[:]
        for char2 in str2:
            if(char1==char2):
                A[k+1] = A_copy[k]+1
            elif(A[k] > A[k+1]):
                A[k+1] = A[k]
    print(A[-1])

Submission status: Runtime Error

Solution code:
def LCS(str1,str2):
    A = [0 for _ in range(len(str2)+1)]
    for i in range(len(str1)):
        A_copy = A[:]
        for j in range(len(str2)):
            if(str1[i]==str2[j]):
                (int)A[j+1] = (int)A_copy[j]+1
            elif((int)A[j] > (int)A[j+1]):
                (int)A[j+1] = (int)A[j]
    print(A[-1])


m = int(input())
for i in range(m):
    str1 = input()
    str2 = input()
    LCS(str1,str2)

Submission status: Runtime Error

Solution code:

def f(x,y):
	list=[0]
	for z in y:
		for i in range(len(list)-1,-1,-1):
			tmp=x.find(z,list[i])+1
			if tmp:
				if i+1 < len(list):
					list[i+1]=min(list[i+1],tmp)
				else:
					list.append(tmp)
	return len(list)-1
 
n=int(input())
for i in range(q):
	x=input()
	y=input()
	print(f(x,y))

Submission status: Runtime Error

Solution code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void input(string &x,string &y){
	cin>>x>>y;
}
int lcs(string x,string y){
	vector<vector<int>> tb(vector<vector<int>>((int)x.size()+1,vector<int>(y.size()+1,0)));
	for(int i=1;i<(int)x.size()+1;i++){
		for(int j=1;j<(int)y.size()+1;j++){
			if(x[i]==y[j])  tb[i][j]=tb[i-1][j-1]+1;
			else tb[i][j]=max(tb[i-1][j],tb[i][j-1]);
		}
	}
	return tb[(int)x.size()][(int)y.size()];
}
int main(){
	int q;
	cin>>q;
	string x,y;
	for(int i=0;i<q;i++){
		input(x,y);
		cout<<lcs(x,y)<<endl;
	}
	return 0;
}

Submission status: Runtime Error

Solution code:

def main():
    n = int(input())
    for i in range(n):
        a = input()
        b = input()
        na=len(a)
        nb=len(b)
        array = [[[0]*nb]**na]
        #array = [0 for i in range(nb)] for j in range(na)]
        for i in range(na):
            for j in range(nb):
                if i==0:
                    if a[i]==b[j]:
                        array[i][j]=1
                elif j==0:
                    if a[i]==b[j]:
                        array[i][j]=1
                else:
                    c = 0
                    if a[i] == b[j]:
                        c = 1
                    array[i][j] = array[i-1][j-1]+c 
                    max(
                            array[i-1][j],
                            array[i][j-1],
                            array[i-1][j-1]+c)
        print(array[na-1][nb-1])
if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
from pprint import pprint
def main():
    fp=open("result.txt","w")
    n = int(input())
    for i in range(n):
        a = input()
        b = input()
        na=len(a)
        nb=len(b)
        array = [[0]*nb for i in range(na)]
        #array = [[0 for i in range(nb)] for j in range(na)]
        for i in range(na):
            for j in range(nb):
                c = 0
                if i==0:
                    if a[i]==b[j]:
                        array[i][j]=1
                elif j==0:
                    if a[i]==b[j]:
                        array[i][j]=1
                else:
                    if a[i] == b[j]:
                        c = 1
                        array[i][j] = max(
                            array[i-1][j],
                            array[i][j-1],
                            array[i-1][j-1]+c)
        print(array[na-1][nb-1])
    fp.close()
if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
def ask(X,Y):
 cost=[0]
 for j in Y:
  for i in range(len(cost)-1,-1,-1):
   a=X.find(c,cost[i])+1
   if a:
    if i+1<len(cost):
     cost[i+1]=min(cost[i+1],a)
    else:
     cost.append(a)
 return len(cost)-1
 


q=int(input())
Z=[]
for p in range(q):
 X=input()
 Y=input()
 z=ask(X,Y)
 Z.append(z)

for p in range(q):
 print(Z[p])

Submission status: Runtime Error

Solution code:
#dj 16D8101012J ito jun
def search(a,b):
    na=len(a)
    nb=len(b)
    array = [[0]*(nb+1) for _ in range(na+1)]
    for i,x in enumerate(a,1):
        prerow=array[i-1]
        row=array[i]
        for j,y in enumerate(b,1):
            if x == y:
                row[j]=prerow[j-1]+1
            elif prerow[j] < row[j-1]+1:
                row[j] = row[j-1]
            else:
                row[j] = prerow[j]
    return array[-1][-1]

n = int(input())
strs = [list(i) for i in input()]
result = [search(strs[i*2], strs[i*2+1]) for i in range(n)]
print(*result, sep="\n")

Submission status: Runtime Error

Solution code:

 e=input
 a=''
 for _ in[0]*int(e()):
  X,z=e(),[]
  for y in e():
   s=i=0
   for k in z:
    t=X.find(y,s)+1
    if t<1:break
    if t<k:z[i]=t
    s=k;i+=1
   else:
    t=X.find(y,s)+1
    if t:z+=[t]
  a+=f'\n{len(z)}'
 print(a[1:]

Submission status: Runtime Error

Solution code:
def lcs(x,y,l,j,k):
	if(x[j-1]==y[k-1]):
		lcs(x,y,l,j-1,k-1)
		global c
		c+=1
	else:
		if l[j-1][k]>=l[j][k-1]:
			lcs(x,y,l,j-1,k)
		else:
			lcs(x,y,l,j,k-1)

q=int(input())
c=0
for i in range(q):
	x=list(input())
	y=list(input())
	l=[[0 for i in range(len(y)+1)] for j in range(len(x)+1)]

for j in range(1, len(x) + 1):
    for k in range(1, len(y) + 1):
        if x[j - 1] == y[k - 1]:
            a = 1
        else:
            a = 0
        l[j][k] = max(l[j-1][k-1] + a, l[j-1][k], l[j][k-1])
lcs(x,y,l,len(x),len(y))
print(c)

Submission status: Runtime Error

Solution code:
import numpy as np
def f(i,j):
    if i == 0 or j == 0:
        if s1[i] == s2[j]:
            x[i][j] = 1
        else:
            if i == 0:
                x[i][j] = x[i][j-1]
            else:
                x[i][j] = x[i-1][j]
    elif s1[i] == s2[j]:
        x[i][j] = max(x[i-1][j-1]+1,x[i][j-1],x[i-1][j])
    else:
        x[i][j] = max(x[i-1][j-1],x[i][j-1],x[i-1][j])

n = int(input())
for i in range(n):
    s1 = input()
    s2 = input()
    x = np.zeros((len(s1),len(s2)))
    for j in range(len(s1)):
        for k in range(len(s2)):
            f(j,k)
            
    print(x[len(s1)-1][len(s2)-1])
#print(*x)

Submission status: Runtime Error

Solution code:
import numpy as np
def f(i,j):
    if i == 0 or j == 0:
        if s1[i] == s2[j]:
            x[i][j] = 1
        else:
            if i == 0:
                x[i][j] = x[i][j-1]
            else:
                x[i][j] = x[i-1][j]
    elif s1[i] == s2[j]:
        x[i][j] = max(x[i-1][j-1]+1,x[i][j-1],x[i-1][j])
    else:
        x[i][j] = max(x[i-1][j-1],x[i][j-1],x[i-1][j])

n = int(input())
for i in range(n):
    s1 = input()
    s2 = input()
    x = np.zeros((len(s1),len(s2)))
    for j in range(len(s1)):
        for k in range(len(s2)):
            f(j,k)
            
    print(int(x[len(s1)-1][len(s2)-1]))
#print(*x)

Submission status: Runtime Error

Solution code:
import numpy as np
import time
def f(i,j):
    if i == 0 or j == 0:
        if s1[i] == s2[j]:
            x[i][j] = 1
        else:
            if i == 0:
                x[i][j] = x[i][j-1]
            else:
                x[i][j] = x[i-1][j]
    elif s1[i] == s2[j]:
        x[i][j] = max(x[i-1][j-1]+1,x[i][j-1],x[i-1][j])
    else:
        x[i][j] = max(x[i-1][j-1],x[i][j-1],x[i-1][j])

t1 = time.time()
n = int(input())
for i in range(n):
    s1 = input()
    s2 = input()
    x = np.zeros((len(s1),len(s2)))
    for j in range(len(s1)):
        for k in range(len(s2)):
            f(j,k)
            
    print(int(x[len(s1)-1][len(s2)-1]))
t2 = time.time()

Submission status: Runtime Error

Solution code:
def calc(x,y):
    i = len(x)
    j = len(y)
    if d[i][j]:
        return d[i][j]
    else:
        if i == 1:
            if x in y:
                d[i][j] = 1
                return 1
            else:
                d[i][j] = 0
                return 0
        elif j == 1:
            if y in x:
                d[i][j] = 1
                return 1
            else:
                d[i][j] = 0
                return 0
        else:
            if x[-1] == y[-1]:
                tmp = max(calc(x[:-1],y[:-1])+1,calc(x[:-1],y),calc(x,y[:-1]))
                d[i][j] = tmp
                return tmp
            else:
                tmp = max(calc(x[:-1],y),calc(x,y[:-1]))
                d[i][j] = tmp
                return tmp
        
q = int(input())
for i in range(q):
    x = input()
    y = input()
    d = [[None for _ in range(len(y)+1)] for _ in range(len(x)+1)]
    print(calc(x,y))

Submission status: Runtime Error

Solution code:
def calc(x,y):
    i = len(x)
    j = len(y)
    if not d[i][j] == None:
        return d[i][j]
    else:
        if x[-1] == y[-1]:
            tmp = calc(x[:-1],y[:-1])+1
            d[i][j] = tmp
            return tmp
        else:
            tmp = max(calc(x[:-1],y),calc(x,y[:-1]))
            d[i][j] = tmp
            return tmp
        
q = int(input())
for i in range(q):
    x = input()
    y = input()
    d = [[0 if i == 0 or j == 0 else None for i in range(len(y)+1)] for j in range(len(x)+1)]
    print(calc(x,y))

Submission status: Runtime Error

Solution code:
import sys

def lcm(c,i, j):
    if c[i][j]>0: return c[i][j]        
    if i==0 or j==0:
        return 0
    elif x[i]==y[j]:
        c[i][j] = lcm(c,i-1,j-1)+1
        return c[i][j]
    else:
        c[i][j] = max(lcm(c,i,j-1), lcm(c,i-1,j))
        return c[i][j]

for _ in range(int(sys.stdin.readline())):
    x = sys.stdin.readline()
    y = sys.stdin.readline()
    c = [[0 for _ in range(len(x)+2)] for _ in range(len(y)+2)] 
    print(lcm(c,len(x)-1,len(y)-1))

Submission status: Runtime Error

Solution code:
import sys

def lcm(c, i, j):
    if c[i][j]>=0: return c[i][j]
    if i==0 or j==0:
        c[i][j]=0
        return 0
    elif i>0 and j>0 and x[i-1]==y[j-1]:
        c[i][j] = lcm(c,i-1,j-1)+1
        return c[i][j]
    else:
        c[i][j] = max(lcm(c,i,j-1), lcm(c,i-1,j))
        return c[i][j]

for _ in range(int(sys.stdin.readline())):
    x = sys.stdin.readline()
    y = sys.stdin.readline()
    c = [[-1 for _ in range(len(y))] for _ in range(len(x))] 
    print(lcm(c,len(x)-1,len(y)-1))

Submission status: Runtime Error

Solution code:
#include <stdio.h>
#include <string.h>

int main()
{
  int n, i, j, k, xlen, ylen;
  char x[1003], y[1003];
  int c[1001][1001];
  scanf("%d\n", &n);
  for (k=0; k<n; k++) {
    fgets(x, 1002, stdin);
    xlen = strlen(x);
    if (x[xlen-1]=='\n') x[xlen-- -1]='\0';
    fgets(y, 1002, stdin);
    ylen = strlen(y);
    if (y[ylen-1]=='\n') y[ylen-- -1]='\0';

    c[0][0]=0;
    
    for (i=0; i<xlen; i++) {
      for (j=0; j<ylen; j++) {
        if (x[i]==y[j]) 
          c[i+1][j+1] = c[i][j]+1;
        else
          c[i+1][j+1] = c[i][j+1] > c[i+1][j] ? c[i][j+1] : c[i+1][j];
      }
    }
    printf("%d\n", c[xlen][ylen]);
  }
  return 0;
}

Submission status: Runtime Error

Solution code:
#include <stdio.h>
#include <string.h>

int main()
{
  int n, i, j, k, xlen, ylen;
  char x[1003], y[1003];
  int c[1001][1001];
  char buf[20];
  buf[19]='\0';
  scanf("%d\n", &n);
  for (k=0; k<n; k++) {
    fgets(x, 1002, stdin);
    xlen = strlen(x);
    if (x[xlen-1]=='\n') x[xlen-- -1]='\0';
    fgets(y, 1002, stdin);
    ylen = strlen(y);
    if (y[ylen-1]=='\n') y[ylen-- -1]='\0';

    c[0][0]=0;
    
    for (i=0; i<xlen; i++) {
      for (j=0; j<ylen; j++) {
        if (x[i]==y[j]) 
          c[i+1][j+1] = c[i][j]+1;
        else
          c[i+1][j+1] = c[i][j+1] > c[i+1][j] ? c[i][j+1] : c[i+1][j];
      }
    }
    if (c[xlen][ylen]==0) puts("0");
    else {
    for (i=18; c[xlen][ylen]>0; c[xlen][ylen]/=10) buf[i--]=(c[xlen][ylen]%10)+'0';
    puts(buf+i+1);
    }
  }
  return 0;
}

Submission status: Runtime Error

Solution code:
import sys

def dp_init(m, n):
    return [[0] * n] * m

def solve(str_a, str_b):
    dp = dp_init(len(str_a), len(str_b))
    return rec(len(str_a), len(str_b), str_a, str_b, dp)

def rec(i, j, str_a, str_b, dp):
    if i == 0 or j == 0:
        return 0
    if dp[i][j] > 0:
        return dp[i][j]
    if str_a[i-1] == str_b[j-1]:
        dp[i][j] = rec(i-1, j-1, str_a, str_b, dp) + 1
        return dp[i][j]
    dp[i][j] = max(rec(i, j-1, str_a, str_b, dp), rec(i-1, j, str_a, str_b, dp))
    return dp[i][j]

nb_pairs = int(input())
pairs = []
for i in range(0, nb_pairs):
    pairs.append((input(), input()))

for i in range(0, nb_pairs):
    str_a, str_b = pairs[i]
    print(solve(str_a, str_b))

Submission status: Runtime Error

Solution code:
import sys

def dp_init(m, n):
    ret = []
    for i in range(m):
        ret.append([None] * n)
    return ret

def solve(str_a, str_b):
    dp = dp_init(len(str_a)+1, len(str_b)+1)
    #pring(dp)
    return rec(len(str_a), len(str_b), str_a, str_b, dp, 0)

def rec(i, j, str_a, str_b, dp, depth):
    if dp[i][j] is not None:
        #pring(" "*depth + "(%d, %d) : %d - hit" % (i, j, dp[i][j]))
        return dp[i][j]
    if i == 0 or j == 0:
        dp[i][j] = 0
        #pring(" "*depth + "(%d, %d) : %d - zero" % (i, j, dp[i][j]))
        return 0
    if str_a[i-1] == str_b[j-1]:
        dp[i][j] = rec(i-1, j-1, str_a, str_b, dp, depth+1) + 1
        #pring(" "*depth + "(%d, %d) : %d" % (i, j, dp[i][j]))
        return dp[i][j]

    dp[i][j] = max(rec(i, j-1, str_a, str_b, dp, depth+1), rec(i-1, j, str_a, str_b, dp, depth+1))
    #pring(" "*depth + "(%d, %d) : %d" % (i, j, dp[i][j]))
    return dp[i][j]

nb_pairs = int(input())
pairs = []
for i in range(0, nb_pairs):
    pairs.append((input(), input()))

for i in range(0, nb_pairs):
    str_a, str_b = pairs[i]
    print(solve(str_a, str_b))