Problem:


Score : 500 points

Problem Statement

Given is a string S of length N.

Find the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping.

More formally, find the maximum positive integer len such that there exist integers l_1 and l_2 ( 1 \leq l_1, l_2 \leq N - len + 1 ) that satisfy the following:

l_1 + len \leq l_2

S[l_1+i] = S[l_2+i] (i = 0, 1, ..., len - 1)

If there is no such integer len, print 0.

Constraints

2 \leq N \leq 5 \times 10^3

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping. If there is no such non-empty string, print 0 instead.

Sample Input 1

5
ababa

Sample Output 1

2

The strings satisfying the conditions are: a, b, ab, and ba. The maximum length among them is 2, which is the answer.
Note that aba occurs twice in S as contiguous substrings, but there is no pair of integers l_1 and l_2 mentioned in the statement such that l_1 + len \leq l_2.

Sample Input 2

2
xy

Sample Output 2

0

No non-empty string satisfies the conditions.

Sample Input 3

13
strangeorange

Sample Output 3

5



Sample input:
5
ababa


Sample output:
2

Submission status: Accepted

Solution code:
import random

class RollingHash(object):
    def __init__(self, S: str, MOD: int = 998244353, BASE: int = 37):
        self.S = S
        self.N = N = len(S)
        self.MOD = MOD
        self.BASE = BASE
        self.S_arr = [ord(x) for x in S]

        self.POWER = [1] * (N + 1)
        self.HASH  = [0] * (N + 1)
        p, h = 1, 0
        for i in range(N):
            self.POWER[i + 1] = p = (p * BASE) % MOD
            self.HASH[i + 1] = h = (h * BASE + self.S_arr[i]) % MOD

    def hash(self, l: int, r: int):
        # get hash for S[l:r]
        _hash = (self.HASH[r] - self.HASH[l] * self.POWER[r - l]) % self.MOD
        return _hash

# 汎用的な二分探索のテンプレ
# check_func(x) = true となるxの最小値を探索する
# left : check_func(x) = falseとなるx
# right: check_func(x) = true となるx
# search_max: check_func(x) = true となるxの"最大値"を探索する場合はTrue
# check_func: search_max = False の場合、answer <= x であればcheck_func(x) = true となるような関数
#             search_max = True  の場合、x <= answer であればcheck_func(x) = true となるような関数
def binary_search(left: int, right: int, check_func, search_max:bool=False):
    # ok と ng のどちらが大きいかわからないことを考慮
    while abs(right - left) > 1:
        mid = (left + right) // 2
    
        if check_func(mid) ^ search_max:
            right = mid
        else:
            left = mid

    return left if search_max else right

def main():
    N = int(input())
    S = input()
    MOD = 10 ** 18 + 3
    # BASEはMOD未満で1でない奇数とする
    BASE = random.randint(2, MOD // 2 - 1) * 2 + 1
    rs = RollingHash(S, MOD=MOD, BASE=BASE)

    D = [0] * N
    # 長さLの部分文字列同士が、範囲を重ねず同じ文字列となる場合はTrue,
    # そうでない場合はFalseを返す関数
    def isOK(L):
        if L == 0:
            return True
        
        for i in range(min(L, N - 2 * L + 1)):
            D[i] = rs.hash(i, i + L)
        hashes = set()
        for i in range(L, N - L + 1):
            # 自分より開始点がL以上前の文字列のハッシュを検索対象に追加
            hashes.add(D[i - L])
            D[i] = v = rs.hash(i, i + L)
            # ハッシュが衝突したら、範囲を重ねず同じ文字列となる文字列が存在することになる
            if v in hashes:
                return True
        return False

    # 範囲が重ならないことが条件にあるので、答えは最大でもN // 2（文字列の長さの半分）となる。
    # ただし、二分探索する上で絶対に答えとならない範囲を含めたいので、
    # 探索範囲としてはN // 2 + 1 と、+1しておく。
    ans = binary_search(0, N // 2 + 1, isOK, search_max=True)
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import random

class RollingHash(object):
    def __init__(self, S: str, MOD: int = 10 ** 9 + 7, BASE: int = 10 ** 5 + 7):
        self.S = S
        self.N = N = len(S)
        self.MOD = MOD
        self.BASE = BASE
        self.S_arr = [ord(x) for x in S]

        self.POWER = [1] * (N + 1)
        self.HASH  = [0] * (N + 1)
        p, h = 1, 0
        for i in range(N):
            self.POWER[i + 1] = p = (p * BASE) % MOD
            self.HASH[i + 1] = h = (h * BASE + self.S_arr[i]) % MOD

    def hash(self, l: int, r: int):
        # get hash for S[l:r]
        _hash = (self.HASH[r] - self.HASH[l] * self.POWER[r - l]) % self.MOD
        return _hash

# 汎用的な二分探索のテンプレ
# check_func(x) = true となるxの最小値を探索する
# left : check_func(x) = falseとなるx
# right: check_func(x) = true となるx
# search_max: check_func(x) = true となるxの"最大値"を探索する場合はTrue
# check_func: answer <= x であればcheck_func(x) = true となるような関数
def binary_search(left: int, right: int, check_func, search_max:bool=False):
    # ok と ng のどちらが大きいかわからないことを考慮
    while abs(right - left) > 1:
        mid = (left + right) // 2
    
        if check_func(mid) ^ search_max:
            right = mid
        else:
            left = mid

    return left if search_max else right

def main():
    N = int(input())
    S = input()
    MOD = 998244353
    # BASEはMOD未満で1でない奇数とする
    BASE = random.randint(2, MOD // 2 - 1) * 2 + 1
    rs = RollingHash(S, MOD=MOD, BASE=BASE)

    D = [0] * N
    # 長さLの部分文字列同士が、範囲を重ねず同じ文字列となる場合はTrue,
    # そうでない場合はFalseを返す関数
    def isOK(L):
        if L == 0:
            return True
        
        for i in range(min(L, N - 2 * L + 1)):
            D[i] = rs.hash(i, i + L)
        hashes = set()
        for i in range(L, N - L + 1):
            # 自分より開始点がL以上前の文字列のハッシュを検索対象に追加
            hashes.add(D[i - L])
            D[i] = v = rs.hash(i, i + L)
            # ハッシュが衝突したら、範囲を重ねず同じ文字列となる文字列が存在することになる
            if v in hashes:
                return True
        return False

    # 範囲が重ならないことが条件にあるので、答えは最大でもN // 2（文字列の長さの半分）となる。
    # ただし、二分探索する上で絶対に答えとならない範囲を含めたいので、
    # 探索範囲としてはN // 2 + 1 と、+1しておく。
    ans = binary_search(0, N // 2 + 1, isOK, search_max=True)
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import random

class RollingHash(object):
    def __init__(self, S: str, MOD: int = 10 ** 9 + 7, BASE: int = 10 ** 5 + 7):
        self.S = S
        self.N = N = len(S)
        self.MOD = MOD
        self.BASE = BASE
        self.S_arr = [ord(x) for x in S]

        self.POWER = [1] * (N + 1)
        self.HASH  = [0] * (N + 1)
        p, h = 1, 0
        for i in range(N):
            self.POWER[i + 1] = p = (p * BASE) % MOD
            self.HASH[i + 1] = h = (h * BASE + self.S_arr[i]) % MOD

    def hash(self, l: int, r: int):
        # get hash for S[l:r]
        _hash = (self.HASH[r] - self.HASH[l] * self.POWER[r - l]) % self.MOD
        return _hash

# 汎用的な二分探索のテンプレ
# check_func(x) = true となるxの最小値を探索する
# left : check_func(x) = falseとなるx
# right: check_func(x) = true となるx
# search_max: check_func(x) = true となるxの"最大値"を探索する場合はTrue
# check_func: answer <= x であればcheck_func(x) = true となるような関数
def binary_search(left: int, right: int, check_func, search_max:bool=False):
    # ok と ng のどちらが大きいかわからないことを考慮
    while abs(right - left) > 1:
        mid = (left + right) // 2
    
        if check_func(mid) ^ search_max:
            right = mid
            # print(left, right, mid, 't')
        else:
            left = mid
            # print(left, right, mid, 'f')

    return left if search_max else right

def main():
    N = int(input())
    S = input()
    MOD = 998244353
    BASE = 37 # random.randint(2, MOD-1)
    rs = RollingHash(S, MOD=MOD, BASE=BASE)

    D = [0] * N
    # 長さLの部分文字列同士が、範囲を重ねず同じ文字列となる場合はTrue,
    # そうでない場合はFalseを返す関数
    def isOK(L):
        if L == 0:
            return True
        
        for i in range(min(L, N - 2 * L + 1)):
            D[i] = rs.hash(i, i + L)
        hashes = set()
        for i in range(L, N - L + 1):
            # 自分より開始点がL以上前の文字列のハッシュを検索対象に追加
            hashes.add(D[i - L])
            D[i] = v = rs.hash(i, i + L)
            # ハッシュが衝突したら、範囲を重ねず同じ文字列となる文字列が存在することになる
            if v in hashes:
                return True
        return False

    # 範囲が重ならないことが条件にあるので、答えは最大でもN // 2（文字列の長さの半分）となる。
    # ただし、二分探索する上で絶対に答えとならない範囲を含めたいので、
    # 探索範囲としてはN // 2 + 1 と、+1しておく。
    ans = binary_search(0, N // 2 + 1, isOK, search_max=True)
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict

class RollingHash(object):
    def __init__(self, S: str, MOD: int = 10 ** 9 + 7, BASE: int = 10 ** 5 + 7):
        self.S = S
        self.N = N = len(S)
        self.MOD = MOD
        self.BASE = BASE
        
        S_arr = [ord(x) for x in S]
        POWER = [1] * (N + 1)
        HASH  = [0] * (N + 1)
        p, h = 1, 0
        for i in range(N):
            POWER[i + 1] = p = (p * BASE) % MOD
            HASH[i + 1] = h = (h * BASE + S_arr[i]) % MOD
        self.S_arr = S_arr
        self.POWER = POWER
        self.HASH = HASH

    def hash(self, l: int, r: int):
        # get hash for S[l:r]
        _hash = (self.HASH[r] - self.HASH[l] * self.POWER[r - l]) % self.MOD
        return _hash

def main():
    N = int(input())
    S = input()
    MOD = 998244353
    rs = RollingHash(S, MOD=MOD, BASE=37)
    h, p = rs.HASH, rs.POWER

    left, right = 0, N // 2 + 1
    D = [0] * N
    while abs(right - left) > 1:
        mid = (left + right) // 2
        # hash_to_left = defaultdict(list)
        hashes = set()
        L = mid
        P = p[L]
        for i in range(min(L, N-2*L+1)):
            D[i] = (h[L+i] - h[i]*P) % MOD
        hashes = set()
        ok = False
        for i in range(L, N-L+1):
            hashes.add(D[i-L])
            D[i] = v = (h[L+i] - h[i]*P) % MOD
            if v in hashes:
                ok = True
                break
        if ok:
            left = mid
        else:
            right = mid

    print(left)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def solve():
    N = int(input())
    S = input()

    def rolling_hash(s, mod, base = 37):
        l = len(s)
        h = [0]*(l + 1)
        v = 0
        for i in range(l):
            h[i+1] = v = (v * base + ord(s[i])) % mod
        pw = [1]*(l + 1)
        v = 1
        for i in range(l):
            pw[i+1] = v = v * base % mod
        return h, pw

    def chk(S, mod, D = [0]*N):
        h, pw = rolling_hash(S, mod)
        left = 0; right = N//2+1
        while left+1 < right:
            l = mid = (left + right) >> 1
            p = pw[l]
            for i in range(min(l, N-2*l+1)):
                D[i] = (h[l+i] - h[i]*p) % mod
            s = set()
            ok = 0
            for i in range(l, N-l+1):
                s.add(D[i-l])
                D[i] = v = (h[l+i] - h[i]*p) % mod
                if v in s:
                    ok = 1
                    break
            if ok:
                left = mid
            else:
                right = mid
        return left

    print(chk(S, 10**9 + 9))
solve()

Submission status: Accepted

Solution code:
from collections import defaultdict

class RollingHash(object):
    def __init__(self, S: str, MOD: int = 10 ** 9 + 7, BASE: int = 10 ** 5 + 7):
        self.S = S
        self.N = N = len(S)
        self.MOD = MOD
        self.BASE = BASE
        self.S_arr = [ord(x) for x in S]

        self.POWER = [1] * (N + 1)
        self.HASH  = [0] * (N + 1)
        p, h = 1, 0
        for i in range(N):
            self.POWER[i + 1] = p = (p * BASE) % MOD
            self.HASH[i + 1] = h = (h * BASE + self.S_arr[i]) % MOD

    def hash(self, l: int, r: int):
        # get hash for S[l:r]
        _hash = (self.HASH[r] - self.HASH[l] * self.POWER[r - l]) % self.MOD
        return _hash

def main():
    N = int(input())
    S = input()
    MOD = 998244353
    rs = RollingHash(S, MOD=MOD, BASE=37)
    h, p = rs.HASH, rs.POWER

    left, right = 0, N // 2 + 1

    while abs(right - left) > 1:
        mid = (left + right) // 2
        ok = False
        hash_to_left = defaultdict(list)
        L = mid
        for i in range(N - L + 1):
            _hash = (h[i+L] - h[i] * p[L]) % MOD
            # hashが衝突しても文字列が完全に一致するか分からないので、
            # 衝突した場合は文字列が完全に一致するか調べ、かつ
            # 文字列同士がSの中で重なるような範囲にない場合はOKとする
            for j in hash_to_left[_hash]:
                if j+L <= i and S[i:i+L] == S[j:j+L]:
                    ok = True
                    break
            if ok:
                break
            hash_to_left[_hash].append(i)

    
        if ok:
            left = mid
        else:
            right = mid

    print(left)
    # # 長さLの部分文字列同士が、範囲を重ねず同じ文字列となる場合はTrue,
    # # そうでない場合はFalseを返す関数
    # def isOK(L):
    #     if L == 0:
    #         return True
    #     hash_to_left = defaultdict(list)
    #     for i in range(N - L + 1):
    #         _hash = rs.hash(i, i + L)
    #         # hashが衝突しても文字列が完全に一致するか分からないので、
    #         # 衝突した場合は文字列が完全に一致するか調べ、かつ
    #         # 文字列同士がSの中で重なるような範囲にない場合はOKとする
    #         for j in hash_to_left[_hash]:
    #             if j+L <= i and S[i:i+L] == S[j:j+L]:
    #                 return True
    #         hash_to_left[_hash].append(i)

    #     return False
    # # 範囲が重ならないことが条件にあるので、答えは最大でもN // 2（文字列の長さの半分）となる。
    # # ただし、二分探索する上で絶対に答えとならない範囲を含めたいので、
    # # 探索範囲としてはN // 2 + 1 と、+1しておく。
    # ans = binary_search(0, N // 2 + 1, isOK, search_max=True)
    # print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict

class RollingHash(object):
    def __init__(self, S: str, MOD: int = 10 ** 9 + 7, BASE: int = 10 ** 5 + 7):
        self.S = S
        self.N = N = len(S)
        self.MOD = MOD
        self.BASE = BASE
        self.S_arr = [ord(x) for x in S]

        self.POWER = [1] * (N + 1)
        self.HASH  = [0] * (N + 1)
        p, h = 1, 0
        for i in range(N):
            self.POWER[i + 1] = p = (p * BASE) % MOD
            self.HASH[i + 1] = h = (h * BASE + self.S_arr[i]) % MOD

    def hash(self, l: int, r: int):
        # get hash for S[l:r]
        _hash = (self.HASH[r] - self.HASH[l] * self.POWER[r - l]) % self.MOD
        # if _hash < 0:
        #     _hash += self.MOD
        return _hash

# 汎用的な二分探索のテンプレ
# check_func(x) = true となるxの最小値を探索する
# left : check_func(x) = falseとなるx
# right: check_func(x) = true となるx
# search_max: check_func(x) = true となるxの"最大値"を探索する場合はTrue
# check_func: answer <= x であればcheck_func(x) = true となるような関数
def binary_search(left: int, right: int, check_func, search_max:bool=False):
    # ok と ng のどちらが大きいかわからないことを考慮
    while abs(right - left) > 1:
        mid = (left + right) // 2
    
        if check_func(mid) ^ search_max:
            right = mid
            # print(left, right, mid, 't')
        else:
            left = mid
            # print(left, right, mid, 'f')

    return left if search_max else right

def main():
    N = int(input())
    S = input()

    rs = RollingHash(S, MOD=998244353, BASE=37)

    # 長さLの部分文字列同士が、範囲を重ねず同じ文字列となる場合はTrue,
    # そうでない場合はFalseを返す関数
    def isOK(L):
        if L == 0:
            return True
        hash_to_left = defaultdict(list)
        for i in range(N - L + 1):
            _hash = rs.hash(i, i + L)
            # hashが衝突しても文字列が完全に一致するか分からないので、
            # 衝突した場合は文字列が完全に一致するか調べ、かつ
            # 文字列同士がSの中で重なるような範囲にない場合はOKとする
            for j in hash_to_left[_hash]:
                if j+L <= i:
                    return True
            hash_to_left[_hash].append(i)

        return False
    # 範囲が重ならないことが条件にあるので、答えは最大でもN // 2（文字列の長さの半分）となる。
    # ただし、二分探索する上で絶対に答えとならない範囲を含めたいので、
    # 探索範囲としてはN // 2 + 1 と、+1しておく。
    ans = binary_search(0, N // 2 + 1, isOK, search_max=True)
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict

class RollingHash(object):
    def __init__(self, S: str, MOD: int = 10 ** 9 + 7, BASE: int = 10 ** 5 + 7):
        self.S = S
        self.N = N = len(S)
        self.MOD = MOD
        self.BASE = BASE
        self.S_arr = [ord(x) for x in S]

        self.POWER = [1] * (N + 1)
        self.HASH  = [0] * (N + 1)
        p, h = 1, 0
        for i in range(N):
            self.POWER[i + 1] = p = (p * BASE) % MOD
            self.HASH[i + 1] = h = (h * BASE + self.S_arr[i]) % MOD

    def hash(self, l: int, r: int):
        # get hash for S[l:r]
        _hash = self.HASH[r] - (self.HASH[l] * self.POWER[r - l] % self.MOD)
        if _hash < 0:
            _hash += self.MOD
        return _hash

# 汎用的な二分探索のテンプレ
# check_func(x) = true となるxの最小値を探索する
# left : check_func(x) = falseとなるx
# right: check_func(x) = true となるx
# search_max: check_func(x) = true となるxの"最大値"を探索する場合はTrue
# check_func: answer <= x であればcheck_func(x) = true となるような関数
def binary_search(left: int, right: int, check_func, search_max:bool=False):
    # ok と ng のどちらが大きいかわからないことを考慮
    while abs(right - left) > 1:
        mid = (left + right) // 2
    
        if check_func(mid) ^ search_max:
            right = mid
            # print(left, right, mid, 't')
        else:
            left = mid
            # print(left, right, mid, 'f')

    return left if search_max else right

def main():
    N = int(input())
    S = input()

    rs = RollingHash(S, MOD=998244353, BASE=37)

    # 長さLの部分文字列同士が、範囲を重ねず同じ文字列となる場合はTrue,
    # そうでない場合はFalseを返す関数
    def isOK(L):
        if L == 0:
            return True
        hash_to_left = defaultdict(list)
        for i in range(N - L + 1):
            _hash = rs.hash(i, i + L)
            # hashが衝突しても文字列が完全に一致するか分からないので、
            # 衝突した場合は文字列が完全に一致するか調べ、かつ
            # 文字列同士がSの中で重なるような範囲にない場合はOKとする
            for j in hash_to_left[_hash]:
                if j+L <= i and S[i:i+L] == S[j:j+L]:
                    return True
            hash_to_left[_hash].append(i)

        return False
    # 範囲が重ならないことが条件にあるので、答えは最大でもN // 2（文字列の長さの半分）となる。
    # ただし、二分探索する上で絶対に答えとならない範囲を含めたいので、
    # 探索範囲としてはN // 2 + 1 と、+1しておく。
    ans = binary_search(0, N // 2 + 1, isOK, search_max=True)
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict

class RollingHash(object):
    def __init__(self, S: str, MOD: int = 10 ** 9 + 7, BASE: int = 10 ** 5 + 7):
        self.S = S
        self.N = N = len(S)
        self.MOD = MOD
        self.BASE = BASE
        self.S_arr = [ord(x) for x in S]

        self.POWER = [1] * (N + 1)
        self.HASH  = [0] * (N + 1)
        p, h = 1, 0
        for i in range(N):
            self.POWER[i + 1] = p = (p * BASE) % MOD
            self.HASH[i + 1] = h = (h * BASE + self.S_arr[i]) % MOD

    def hash(self, l: int, r: int):
        # get hash for S[l:r]
        _hash = self.HASH[r] - (self.HASH[l] * self.POWER[r - l] % self.MOD)
        if _hash < 0:
            _hash += self.MOD
        return _hash

# 汎用的な二分探索のテンプレ
# check_func(x) = true となるxの最小値を探索する
# left : check_func(x) = falseとなるx
# right: check_func(x) = true となるx
# search_max: check_func(x) = true となるxの"最大値"を探索する場合はTrue
# check_func: answer <= x であればcheck_func(x) = true となるような関数
def binary_search(left: int, right: int, check_func, search_max:bool=False):
    # ok と ng のどちらが大きいかわからないことを考慮
    while abs(right - left) > 1:
        mid = (left + right) // 2
    
        if check_func(mid) ^ search_max:
            right = mid
            # print(left, right, mid, 't')
        else:
            left = mid
            # print(left, right, mid, 'f')

    return left if search_max else right

def main():
    N = int(input())
    S = input()

    rs = RollingHash(S)

    # 長さLの部分文字列同士が、範囲を重ねず同じ文字列となる場合はTrue,
    # そうでない場合はFalseを返す関数
    def isOK(L):
        if L == 0:
            return True
        hash_to_left = defaultdict(list)
        for i in range(N - L + 1):
            _hash = rs.hash(i, i + L)
            # hashが衝突しても文字列が完全に一致するか分からないので、
            # 衝突した場合は文字列が完全に一致するか調べ、かつ
            # 文字列同士がSの中で重なるような範囲にない場合はOKとする
            for j in hash_to_left[_hash]:
                if j+L <= i and S[i:i+L] == S[j:j+L]:
                    return True
            hash_to_left[_hash].append(i)

        return False
    # 範囲が重ならないことが条件にあるので、答えは最大でもN // 2（文字列の長さの半分）となる。
    # ただし、二分探索する上で絶対に答えとならない範囲を含めたいので、
    # 探索範囲としてはN // 2 + 1 と、+1しておく。
    ans = binary_search(0, N // 2 + 1, isOK, search_max=True)
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**9)

def main():
    N = int(input())
    S = input()

    ans = 0
    dp = [[0]*(N+1) for _ in range(N+1)]
    for i in reversed(range(N)):
        for j in reversed(range(N)):
            dp[i][j] = dp[i+1][j+1] + 1 if S[i] == S[j] else 0
            if not i+dp[i][j]-1 < j:
                dp[i][j] = 0
            ans = max(ans, dp[i][j])

    print(ans)

if __name__ == "__main__":
  main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**9)


class RollingHash:

    def __init__(self,string):
        base1 = 1007
        mod1 = 10**9+7

        base2 = 2009
        mod2 = 10**9+9

        self.string = string
        n = len(string)
        hash1 = [0]*(n+1)
        power1 = [1]*(n+1)

        hash2 = [0]*(n+1)
        power2 = [1]*(n+1)
        for i,e in enumerate(string):
            hash1[i+1] = (hash1[i]*base1 + ord(e))%mod1
            power1[i+1] = (power1[i]*base1)%mod1
            hash2[i+1] = (hash2[i]*base2 + ord(e))%mod2
            power2[i+1] = (power2[i]*base2)%mod2

        self.hash1 = hash1
        self.power1 = power1
        self.hash2 = hash2
        self.power2 = power2
        self.base1 = base1
        self.mod1 = mod1
        self.base2 = base2
        self.mod2 = mod2

    def calc(self,i,j):
        ans = ((self.hash1[j]-self.hash1[i]*self.power1[j-i]%self.mod1)%self.mod1)*(10**10)
        ans += (self.hash2[j]-self.hash2[i]*self.power2[j-i]%self.mod2)%self.mod2
        return ans

def main():
    N = int(input())
    S = input()

    rh = RollingHash(S)


    ans = 0
    l = 0
    r = N


    while r-l > 1:
        mid = (l+r)//2
        seen = set()
        dic = {}
        found = False
        for i in range(N-mid+1):
            if not i < i+mid-1: continue

            hash = rh.calc(i,i+mid-1)
            # print(hash,i,i+mid-1,mid)
            if hash in seen:
                for _i,j in dic[hash]:
                    if j < i and S[_i:j+1] == S[i:i+mid]:
                        ans = max(ans,mid)
                        found = True
                        break
                else: continue

                dic[hash].append((i,i+mid-1))
                break
            else:
                dic[hash] = [(i,i+mid-1)]
                seen.add(hash)


        if found:
            l = mid
        else:
            r = mid

    print(ans)



if __name__ == "__main__":
  main()

Submission status: Accepted

Solution code:
N = int(input())
S = str(input())

dp = [[0 for _ in range(N)] for _ in range(N)]
#dp[i][j]:= i 文字目からと j 文字目からとで一致する最長の長さ
#(この時点では文字列がかぶっても OK とする)

for i in range(N):
  for j in range(i+1,N):
    if S[i] != S[j]:
      dp[i][j] = 0
    else:
      if i == 0:
        dp[i][j] = 1
      else:
        dp[i][j] = dp[i-1][j-1]+1
ans = 0
for i in range(N):
  for j in range(N):
    temp = min(dp[i][j],j-i)
    ans = max(ans,temp)
print(ans)

Submission status: Accepted

Solution code:
class RollingHash():
    def __init__(self, s, base, mod):
        self.mod = mod
        self.pw = pw = [1]*(len(s)+1)

        l = len(s)
        self.h = h = [0]*(l+1)

        v = 0
        for i in range(l):
            h[i+1] = v = (v * base + ord(s[i])) % mod
        v = 1
        for i in range(l):
            pw[i+1] = v = v * base % mod
    def get(self, l, r): #S[l:r]indexでいうl文字目からr-l文字目。r-l文字。
        return (self.h[r] - self.h[l] * self.pw[r-l]) % self.mod

    def check(self, d):
        ma = {}
        for i in range(N-d+1): #0からN-dまで
            p = self.get(i,i+d)
            if p in ma:
                if i - ma[p] >= d: #d文字以上離れているか
                  return True
            else:
                ma[p] = i
        return False
            
              
N =int(input())
S = str(input())

base1 = 1007
mod1 = 10**9+7

RH = RollingHash(S,base1,mod1)

left = 0
right = N//2+1
while right - left >1:
  mid = (left+right)//2
  if RH.check(mid): #こちらがokの方
    left = mid
  else:
    right = mid

print(left)

Submission status: Accepted

Solution code:
n = int(input())
s = input()
dp = [[0]*5005 for _ in range(5005)]
for i in range(n)[::-1]:
    for j in range(n)[::-1]:
        if s[i]!=s[j]:
            dp[i][j] = 0
        else:
            dp[i][j] = dp[i+1][j+1] + 1
ans = 0
for i in range(n):
    for j in range(n):
        if i >= j:
            continue
        now = min(dp[i][j], j-i)
        ans = max(ans, now)
print(ans)

Submission status: Accepted

Solution code:
N=int(input())
S=input()
ans=0
for i in range(1,N):
 ct=0
 ansa=0
 for j in range(N-i):
  if S[j]==S[j+i]:
   ct+=1
   ansa=max(ct,ansa)
  else:
   ct=0
 ans=max(ans,min(ansa,i))
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
def z_algo(S):
    N = len(S)
    A = [0]*N
    i = 1; j = 0
    A[0] = l = len(S)
    while i < l:
        while i+j < l and S[j] == S[i+j]:
            j += 1
        if not j:
            i += 1
            continue
        A[i] = j
        k = 1
        while l-i > k < j - A[k]:
            A[i+k] = A[k]
            k += 1
        i += k; j -= k
    return A
ans = 0
s = input()
for i in range(n):
    string = z_algo(s[i:])
    for j in range(len(string)):
        if j  >= string[j]:
            ans = max(ans, string[j])
print(ans)

Submission status: Accepted

Solution code:
import math
#import numpy as np
import queue
from collections import deque,defaultdict
import heapq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    n = int(ipt())
    s = input()
    ma = 0
    for i in range(n):
        pf = z_algorithm(s[i::])
        if pf > ma:
            ma = pf
    print(ma)

def z_algorithm(s):
    ma = 0
    prefix = [0]*len(s)
    j = 0
    for i in range(1,len(s)):
        if i+prefix[i-j] < j+prefix[j]:
            prefix[i] = prefix[i-j]
        else:
            k = max(0,j+prefix[j]-i)
            while i+k < len(s) and s[k] == s[i+k]:
                k += 1
            prefix[i] = k
            j = i
    for i,pi in enumerate(prefix):
        if i < pi:
            prefix[i] = i
    for pi in prefix:
        if ma < pi:
            ma = pi
    return ma

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def z_algo(s):
    """https://www.youtube.com/watch?v=f6ct5PQHqM0
    """
    n = len(s)
    ret = [0] * n

    ref_frm, ref_tail = -1, -1  # 一番末尾まで探索したケースの起点と終点
    for frm in range(1, n):
        cont = max(0, min(ret[frm - ref_frm], ref_tail - frm)) if ~ref_frm else 0

        while (frm + cont < n) and (s[cont] == s[frm + cont]): cont += 1
        ret[frm] = cont
        if ref_tail < frm + cont:
            ref_tail = frm + cont
            ref_frm = frm
    ret[0] = n
    return ret


def main():
    N = int(input())
    S = input()

    ret = 0
    t = ''
    for c in reversed(S):
        # zalgoは[0,i]の比較で
        # 先頭が固定されているので
        # 末尾から文字を増やしていくことで
        # 先頭をSの各文字にしている
        t = c + t
        lcp = z_algo(t)
        for diff, len_ in enumerate(lcp):
            ret = max(ret, min(diff, len_))
    print(ret)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N = int(input())
S = list(input())
dp = [[0]*(N) for _ in range(N)]
for i in range(N-1):
    if S[i] == S[N-1]:
        dp[i][N-1] = 1

for i in range(N-2, -1, -1):
    for j in range(N-1, -1, -1):
        if j < i:
            if S[j] == S[i]:
                dp[j][i] = min(dp[j+1][i+1] + 1, i-j)
            else:
                dp[j][i] = 0

ans = 0
for i in range(N):
    for j in range(N):
        ans = max(ans, dp[i][j])
print(ans)

Submission status: Accepted

Solution code:
def Z(S):
    n = len(S)
    LCP = [0]*n
    i = 1
    j = c = 0
    # c : 最も末尾側までLCPを求めたインデックス
    for i in range(1, n):
        # i番目からのLCPが以前計算したcからのLCPに含まれている場合
        if i+LCP[i-c] < c+LCP[c]:
            LCP[i] = LCP[i-c]
        else:
            j = max(0, c+LCP[c]-i)
            while i+j < n and S[j] == S[i+j]: j+=1
            LCP[i] = j
            c = i
    LCP[0] = n
    return LCP

a = 0
n, s = open(0)
for i in range(int(n)):
    for j, l in enumerate(Z(s[i:])):
        a = max(a, min(l, j))
print(a)

Submission status: Accepted

Solution code:
n = int(input())
s = input()

def z_algorithm(S):
    N = len(S)
    A = [0]*N
    i = 1; j = 0
    A[0] = l = len(S)
    while i < l:
        while i+j < l and S[j] == S[i+j]:
            j += 1
        if not j:
            i += 1
            continue
        A[i] = j
        k = 1
        while l-i > k < j - A[k]:
            A[i+k] = A[k]
            k += 1
        i += k; j -= k
    return A


length = n

ans = 0
for i in range(length):
    temp = z_algorithm(s[i:])
    for j in range(len(temp)):
        if min(temp[j],j) > ans:
            ans = min(temp[j],j)
print(ans)

Submission status: Accepted

Solution code:
def Z_algo(S):
    N = len(S)
    result = 0
    c = 0
    Z = [0]*N
    for i in range(1, N):
        l = i - c
        if (i + Z[l] < c + Z[c]):
            Z[i] = Z[l]
        else:
            j = max(0, c + Z[c] - i)
            if i + j >= N:
                j = min(j, N-i-1)
            while(S[j] == S[i + j]):
                j += 1
                if i + j >= N:
                    break
            Z[i] = j
            c = i
        result = max(result, min(Z[i], i))
    return result

L = int(input())
P = list(input())
ans = 0

for k in range(L):
    ans = max(ans, Z_algo(P[k:]))

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = list(input())
dp = [[0]*(N) for _ in range(N)]
for i in range(N):
  if S[-1] == S[i]:
    dp[-1][i] = 1
    dp[i][-1] = 1
  

for i in range(N-2, -1, -1):
  for j in range(N-2, -1, -1):
    if S[i] == S[j]:
      dp[i][j] = dp[i+1][j+1] + 1
ans = 0
for i in range(N):
  for j in range(N):
    if i + dp[i][j] <= j:
      ans = max(ans, dp[i][j])
print(ans)

Submission status: Accepted

Solution code:
import collections
n,s = int(raw_input()), raw_input()

def f(k, s):	
 	cc,q = collections.Counter(), collections.deque()
	for j in range(k - 1, len(s)):
		q.append(s[j - k + 1:j+1])
		if len(q) == k + 1: cc[q.popleft()] += 1
		if q[-1] in cc: return True	
	return False

lo,hi = 0, n/2
while(lo < hi):
	med = (lo + hi + 1) / 2
	if f(med, s):  lo = med
	else:hi = med - 1
print lo

Submission status: Accepted

Solution code:
import collections
n = int(raw_input())
s = raw_input()

def f(k, s):	
	if k == 0:
		return True
 	cc = collections.Counter()
	q = collections.deque()
	for j in range(k - 1, len(s)):
		q.append(s[j - k + 1:j+1])
		if len(q) == k + 1:
			u = q.popleft()
			cc[u] += 1
		if s[j- k+1:j+1] in cc:
			return True	
	return False
lo,hi = 0, n/2 + 1
while(lo < hi):
	med = (lo + hi + 1) / 2
	if f(med, s):
		lo = med
	else:
		hi = med - 1

print lo

Submission status: Accepted

Solution code:
import collections
n = int(raw_input())
s = raw_input()

def f(k, s):	
	if k == 0:
		return True
 	cc = collections.Counter()
	q = collections.deque()
	for j in range(k - 1, len(s)):
		q.append(s[j - k + 1:j+1])
		if len(q) == k + 1:
			u = q.popleft()
			cc[u] += 1
		if s[j- k+1:j+1] in cc:
			return True	
	return False
lo,hi = 0, n
while(lo < hi):
	med = (lo + hi + 1) / 2
	if f(med, s):
		lo = med
	else:
		hi = med - 1

print lo