Problem:


Score : 600 points

Problem Statement

Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite.

There exists a non-negative integer j such that the concatenation of i copies of t is a substring of the concatenation of j copies of s.

Notes

A string a is a substring of another string b if and only if there exists an integer x (0 \leq x \leq |b| - |a|) such that, for any y (1 \leq y \leq |a|), a_y = b_{x+y} holds.

We assume that the concatenation of zero copies of any string is the empty string. From the definition above, the empty string is a substring of any string. Thus, for any two strings s and t, i = 0 satisfies the condition in the problem statement.

Constraints

1 \leq |s| \leq 5 \times 10^5

1 \leq |t| \leq 5 \times 10^5

s and t consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s
t

Output

If the number of non-negative integers i satisfying the following condition is finite, print the maximum value of such i; if the number is infinite, print -1.

Sample Input 1

abcabab
ab

Sample Output 1

3

The concatenation of three copies of t, ababab, is a substring of the concatenation of two copies of s, abcabababcabab, so i = 3 satisfies the condition.

On the other hand, the concatenation of four copies of t, abababab, is not a substring of the concatenation of any number of copies of s, so i = 4 does not satisfy the condition.

Similarly, any integer greater than 4 does not satisfy the condition, either. Thus, the number of non-negative integers i satisfying the condition is finite, and the maximum value of such i is 3.

Sample Input 2

aa
aaaaaaa

Sample Output 2

-1

For any non-negative integer i, the concatenation of i copies of t is a substring of the concatenation of 4i copies of s. Thus, there are infinitely many non-negative integers i that satisfy the condition.

Sample Input 3

aba
baaab

Sample Output 3

0

As stated in Notes, i = 0 always satisfies the condition.



Sample input:
abcabab
ab


Sample output:
3

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

class RollingHash:
  def __init__(self, s):
    self.base1 = 1009
    self.base2 = 1007
    self.mod1 = pow(10,9)+7
    self.mod2 = pow(10,9)+9
    self.hash1 = [0 for _ in range(len(s)+1)]
    self.hash2 = [0 for _ in range(len(s)+1)]
    self.pow1 = [1 for _ in range(len(s)+1)]
    self.pow2 = [1 for _ in range(len(s)+1)]
    for i in range(len(s)):
      self.hash1[i+1] = (self.hash1[i] * self.base1 + ord(s[i])) % self.mod1
      self.hash2[i+1] = (self.hash2[i] * self.base2 + ord(s[i])) % self.mod2
      self.pow1[i+1] = self.pow1[i] * self.base1 % self.mod1
      self.pow2[i+1] = self.pow2[i] * self.base2 % self.mod2

  def get(self, l, r):
    t1 = (self.hash1[r] - self.hash1[l] * self.pow1[r-l]) % self.mod1
    t2 = (self.hash2[r] - self.hash2[l] * self.pow2[r-l]) % self.mod2
    return t1, t2

  def add(self, t):
    offset = len(self.hash1)
    self.hash1 += [0 for _ in range(len(t))]
    self.hash2 += [0 for _ in range(len(t))]
    self.pow1 += [0 for _ in range(len(t))]
    self.pow2 += [0 for _ in range(len(t))]
    for i in range(offset, offset + len(t)):
      self.hash1[i] = (self.hash1[i-1] * self.base1 + t[i]) % self.mod1
      self.hash2[i] = (self.hash2[i-1] * self.base2 + t[i]) % self.mod2
      self.pow1[i] = self.pow1[i-1] * self.base1 % self.mod1
      self.pow2[i] = self.pow2[i-1] * self.base2 % self.mod2


class UnionFind:
  def __init__(self, size):
    self.parent = [i for i in range(size)]  # i番目の親ノードを表す
    self.height = [1 for _ in range(size)]  # 高さ
    self.size = [1 for _ in range(size)]  # 集合のサイズ

  def root(self, x):
    """
    xの親ノードを返す
    """
    if self.parent[x] != x:
      self.parent[x] = self.root(self.parent[x])  # 辺の縮約
    return self.parent[x]

  def union(self, x, y):
    """
    xとyの併合
    """
    px, py = self.root(x), self.root(y)
    if px == py:
      return
    if self.height[px] <= self.height[py]:
      self.parent[px] = py
      self.size[py] += self.size[px]
      if self.height[px] == self.height[py]:
        self.height[py] += 1
    else:
      self.parent[py] = px
      self.size[px] += self.size[py]


def main():
  s = input().strip()
  t = input().strip()
  ns = len(s)
  nt = len(t)
  s = s * (len(t) // len(s) + 1) * 2
  srol = RollingHash(s)
  trol = RollingHash(t)
  uni = UnionFind(ns)
  same = [False for _ in range(ns)]
  for i in range(len(s) - len(t) + 1):
    if srol.get(i, i+nt) == trol.get(0, nt):
      same[i % ns] = True

  for i in range(ns):
    if same[i] and same[(i+nt)%ns]:
      if uni.root(i) == uni.root((i+nt)%ns):
        print(-1)
        sys.exit(0)
      else:
        uni.union(i, (i+nt)%ns)

  ans = 0
  for i in range(ns):
    if same[i]:
      ans = max(ans, uni.size[i])

  print(ans)


if __name__ == '__main__':
  main()

Submission status: Time Limit Exceeded

Solution code:
import os
import sys
import math

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7

S = sys.stdin.readline().rstrip()
T = sys.stdin.readline().rstrip()


LS = len(S)
LT = len(T)
S *= 3
S *= max(math.ceil(LT / LS * 3), 1)


def solve():
    i = 0
    ret = 0
    seen = [0] * len(S)
    while i < len(S):
        if not seen[i]:
            j = 0
            while S.startswith(T, i + j * LT):
                seen[i + j * LT] = j
                if j * LT >= LS:
                    return -1
                j += 1
            ret = max(j, ret)
        i += 1
    return ret


ans = solve()
print(ans)

Submission status: Time Limit Exceeded

Solution code:
s = input()
t = input()

def z_algorithm(s):

    a = [0] * len(s)
    i = 1
    j = 0
    a[0] = len(s)
    while i < len(s):
        while i + j < len(s) and s[j] == s[i+j]:
            j += 1
        a[i] = j
        if j == 0:
            i += 1
            continue
        k = 1
        while i + k < len(s) and k + a[k] < j:
            a[i+k] = a[k]
            k += 1
        i += k
        j -= k
    return a

def solve(i, li):
    ans = 0
    while True:
        if i < 0 or len(li) <= i:
            break
        if visited[i]:
            break
        if li[i] < len(t):
            visited[i] = True
            break
        if li[i] >= len(t):
            visited[i] = True
            ans += 1
            i += len(t)
    return ans

#sを伸ばす
new_s = ""
while True:
    new_s += s
    if len(new_s) > len(t):
        s = new_s
        break

s = s*3
li = z_algorithm(t + s)[len(t):]
visited = [False] * len(li)
ans1 = 0
for i in range(len(li)):
    ans1 = max(ans1, solve(i, li))

s += s
li = z_algorithm(t + s)[len(t):]
visited = [False] * len(li)
ans2 = 0
for i in range(len(li)):
    ans2 = max(ans2, solve(i, li))

if ans1 == ans2:
    print(ans1)
else:
    print(-1)

Submission status: Time Limit Exceeded

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


s = input()
t = input()

def z_algorithm(s):

    a = [0] * len(s)
    i = 1
    j = 0
    a[0] = len(s)
    while i < len(s):
        while i + j < len(s) and s[j] == s[i+j]:
            j += 1
        a[i] = j
        if j == 0:
            i += 1
            continue
        k = 1
        while i + k < len(s) and k + a[k] < j:
            a[i+k] = a[k]
            k += 1
        i += k
        j -= k
    return a

new_s = ""
while True:
    new_s += s
    if len(new_s) > len(t):
        break

def solve(i, li):
    ans = 0
    if i < 0 or len(li) <= i:
        return 0
    if visited[i]:
        return 0
    if li[i] >= len(t):
        visited[i] = True
        ans += 1 + solve(i+len(t), li)
    if li[i] < len(t):
        visited[i] = True
    return ans

s = new_s*3
li = z_algorithm(t + s)[len(t):]
visited = [False] * len(li)
ans1 = 0
for i in range(len(li)):
    ans1 = max(ans1, solve(i, li))

s += s
li = z_algorithm(t + s)[len(t):]
visited = [False] * len(li)
ans2 = 0
for i in range(len(li)):
    ans2 = max(ans2, solve(i, li))

if ans1 == ans2:
    print(ans1)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
import math
from collections import defaultdict
sys.setrecursionlimit(10*6)
INF = float("inf")


def z_algorithm(S):
    """Zアルゴリズム
    https://snuke.hatenablog.com/entry/2014/12/03/214243 の二番目のコード
    """
    N = len(S)
    Z = [0]*N

    c = 0
    for i in range(1, N):
        if i+Z[i-c] < c+Z[c]:
            Z[i] = Z[i-c]
        else:
            j = max(0, c+Z[c]-i)
            while i+j < N and S[j] == S[i+j]:
                j += 1
            Z[i] = j
            c = i
    Z[0] = len(S)
    return Z


def zfindall(text, pattern, separator="$"):
    """テキストからパターンと一致する部分文字列を探す。
    開始インデックスを返す
    Zアルゴリズムを利用する
    """
    N = len(pattern)
    conc = pattern+separator+text
    Z = z_algorithm(conc)
    return [i-N-1 for i in range(len(conc)) if Z[i] == N]


def solve(s: str, t: str):
    S = len(s)
    T = len(t)

    # Sの方が長くなるように
    if T > S:
        s *= int(math.ceil(T/S))

    s2 = s+s
    match = zfindall(s2, t)

    if len(match) == 0:
        print(0)
        return

    # グラフを構成し、最長パスが答え。ループがあれば-1
    # グラフは辞書で表現
    edges = {}
    rev_edges = {}
    for i, m in enumerate(match):
        if m >= S:
            continue
        edges[m] = (m+T) % S
        rev_edges[(m+T) % S] = m

    # 何度も同じ経路を確認するのを改善しうる
    maxlenpath = 1
    visitted = defaultdict(int)
    for k in edges:
        # kが含まれるパスを考える。
        # 逆向きにはったグラフを利用して、双方向の長さを求める
        if visitted[k]:
            continue
        counter = 0
        b = k
        while b in edges:
            counter += 1
            b = edges[b]
            if visitted[b]:
                print(-1)
                return
            else:
                visitted[b] = 1
        b = k
        while b in rev_edges:
            counter += 1
            b = rev_edges[b]
            if visitted[b]:
                print(-1)
                return
            else:
                visitted[b] = 1
        if maxlenpath < counter:
            maxlenpath = counter
    print(maxlenpath)
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    s = next(tokens)  # type: str
    t = next(tokens)  # type: str
    solve(s, t)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
import math
from collections import defaultdict
sys.setrecursionlimit(10*6)
INF = float("inf")


def z_algorithm(S):
    """Zアルゴリズム
    https://snuke.hatenablog.com/entry/2014/12/03/214243 の二番目のコード
    """
    N = len(S)
    Z = [0]*N

    c = 0
    for i in range(1, N):
        if i+Z[i-c] < c+Z[c]:
            Z[i] = Z[i-c]
        else:
            j = max(0, c+Z[c]-i)
            while i+j < N and S[j] == S[i+j]:
                j += 1
            Z[i] = j
            c = i
    Z[0] = len(S)
    return Z


def zfindall(text, pattern, separator="$"):
    """テキストからパターンと一致する部分文字列を探す。
    開始インデックスを返す
    Zアルゴリズムを利用する
    """
    N = len(pattern)
    conc = pattern+separator+text
    Z = z_algorithm(conc)
    return [i-N-1 for i in range(len(conc)) if Z[i] == N]


def solve(s: str, t: str):
    S = len(s)
    T = len(t)

    # Sの方が長くなるように
    if T > S:
        s *= int(math.ceil(T/S))

    s2 = s+s
    match = zfindall(s2, t)

    if len(match) == 0:
        print(0)
        return

    # グラフを構成し、最長パスが答え。ループがあれば-1
    # グラフは辞書で表現
    edges = {}
    for i, m in enumerate(match):
        if m >= S:
            continue
        edges[m] = (m+T) % S

    maxlenpath = 1
    for k in edges:
        # k始まりの路を考える。分岐はない。
        counter = 0
        visitted = defaultdict(int)
        while k in edges:
            visitted[k] = 1
            counter += 1
            k = edges[k]
            if visitted[k]:
                print(-1)
                return
        if maxlenpath < counter:
            maxlenpath = counter
    print(maxlenpath)
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    s = next(tokens)  # type: str
    t = next(tokens)  # type: str
    solve(s, t)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
import math
from collections import deque
sys.setrecursionlimit(10*6)
INF = float("inf")


def z_algorithm(S):
    """Zアルゴリズム
    https://snuke.hatenablog.com/entry/2014/12/03/214243 の二番目のコード
    """
    N = len(S)
    Z = [0]*N

    c = 0
    for i in range(1, N):
        if i+Z[i-c] < c+Z[c]:
            Z[i] = Z[i-c]
        else:
            j = max(0, c+Z[c]-i)
            while i+j < N and S[j] == S[i+j]:
                j += 1
            Z[i] = j
            c = i
    Z[0] = len(S)
    return Z


def zfindall(text, pattern, separator="$"):
    """テキストからパターンと一致する部分文字列を探す。
    開始インデックスを返す
    Zアルゴリズムを利用する
    """
    N = len(pattern)
    conc = pattern+separator+text
    Z = z_algorithm(conc)
    return [i-N-1 for i in range(len(conc)) if Z[i] == N]


def solve(s: str, t: str):
    S = len(s)
    T = len(t)

    # Sの方が長くなるように
    if T > S:
        s *= int(math.ceil(T/S))

    s2 = s+s
    match = zfindall(s2, t)

    if len(match) == 0:
        print(0)
        return

    # グラフを構成する
    match = [m for m in match if m < S]
    mapping = {}
    for i, m in enumerate(match):
        mapping[m] = (m+T) % S
    # print(mapping)

    maxlenpath = 1
    zero = [0]*S
    visitted = zero[:]
    for k in mapping:
        # k始まりの路を考える。分岐はない。
        b = k
        counter = 0
        visitted[:] = zero
        while b in mapping:
            visitted[b] = 1
            b = mapping[b]
            counter += 1
            if visitted[b] == 1:
                print(-1)
                return
        if maxlenpath < counter:
            maxlenpath = counter
    print(maxlenpath)
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    s = next(tokens)  # type: str
    t = next(tokens)  # type: str
    solve(s, t)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
import math
from collections import deque
sys.setrecursionlimit(10*6)
INF = float("inf")


def GCD(a, b):
    if a == 0:
        return b
    else:
        return GCD(b % a, a)


def z_algorithm(S):
    """Zアルゴリズム
    https://snuke.hatenablog.com/entry/2014/12/03/214243 の二番目のコード
    """
    N = len(S)
    Z = [0]*N

    c = 0
    for i in range(1, N):
        if i+Z[i-c] < c+Z[c]:
            Z[i] = Z[i-c]
        else:
            j = max(0, c+Z[c]-i)
            while i+j < N and S[j] == S[i+j]:
                j += 1
            Z[i] = j
            c = i
    Z[0] = len(S)
    return Z


def zfindall(text, pattern, separator="$"):
    """テキストからパターンと一致する部分文字列を探す。
    開始インデックスを返す
    Zアルゴリズムを利用する
    """
    N = len(pattern)
    conc = pattern+separator+text
    Z = z_algorithm(conc)
    return [i-N-1 for i in range(len(conc)) if Z[i] == N]


def solve(s: str, t: str):
    S = len(s)
    T = len(t)

    # Sの方が長くなるように
    if T > S:
        s *= int(math.ceil(T/S))

    s2 = s+s
    match = zfindall(s2, t)

    if len(match) == 0:
        print(0)
        return

    # グラフを構成する
    match = [m for m in match if m < S]
    mapping = {}
    for i, m in enumerate(match):
        mapping[m] = (m+T) % S
    # print(mapping)

    maxlenpath = 1
    for k in mapping:
        # k始まりの路を考える。分岐はない。
        b = k
        counter = 0
        visitted = set()
        while b in mapping:
            visitted.add(b)
            b = mapping[b]
            counter += 1
            if b in visitted:
                print(-1)
                return
        if maxlenpath < counter:
            maxlenpath = counter
    print(maxlenpath)
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    s = next(tokens)  # type: str
    t = next(tokens)  # type: str
    solve(s, t)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
S=list(input())
T=list(input())
len0=len(S)
S=S*(len(T)//len0+1)

S=S+S

p=26
mod=(1<<31)+7# 互いに素なものを指定

TABLE=[0]# Rolling Hashのテーブル. 最初は0
LEN=len(S)

for i in range(LEN):
    TABLE.append((p*TABLE[-1]%mod+ord(S[i])-97)%mod)# テーブルを埋める

NOW=0
LEN2=len(T)

for i in range(LEN2):
    NOW=(p*NOW%mod+ord(T[i])-97)%mod

TH=NOW

def hash_ij(i,j): # [i,j)のハッシュ値を求める
    return (TABLE[j]-TABLE[i]*pow(p,j-i,mod))%mod

OK=[0]*LEN

for i in range(LEN2,LEN):
    if hash_ij(i-LEN2,i)==TH:
        OK[i-LEN2]=1

OK=OK[:len0]

ANS=0

ST=[-1]*len0

for i in range(len0):
    if OK[i]==1 and ST[i]==-1:

        j=i
        count=0

        while OK[j]==1:
            
            if ST[j]!=-1:
                count+=ST[j]
                break
            
            count+=1
            ST[j]=1
            j=(j+LEN2)%len0
            if j==i:
                print(-1)
                import sys
                sys.exit()

        ST[i]=count
        ANS=max(ANS,count)

print(ANS)

Submission status: Time Limit Exceeded

Solution code:
S=list(input())
T=list(input())
len0=len(S)
while len(S)<len(T):
    S=S+S

S=S+S

p=26
mod=(1<<40)+1# 互いに素なものを指定

TABLE=[0]# Rolling Hashのテーブル. 最初は0
LEN=len(S)

for i in range(LEN):
    TABLE.append((p*TABLE[-1]%mod+ord(S[i])-97)%mod)# テーブルを埋める

NOW=0
LEN2=len(T)

for i in range(LEN2):
    NOW=(p*NOW%mod+ord(T[i])-97)%mod

TH=NOW

def hash_ij(i,j): # [i,j)のハッシュ値を求める
    return (TABLE[j]-TABLE[i]*pow(p,j-i,mod))%mod

OK=[0]*LEN

for i in range(LEN2,LEN):
    if hash_ij(i-LEN2,i)==TH:
        OK[i-LEN2]=1

OK=OK[:len0]

ANS=0

ST=[-1]*len0

for i in range(len0):
    if OK[i]==1 and ST[i]==-1:

        j=i
        count=0

        while OK[j]==1:
            
            if ST[j]!=-1:
                count+=ST[j]
                break
            
            count+=1
            ST[j]=1
            j=(j+LEN2)%len0
            if j==i:
                print(-1)
                import sys
                sys.exit()

        ST[i]=count
        ANS=max(ANS,count)

print(ANS)

Submission status: Time Limit Exceeded

Solution code:
S=list(input())
T=list(input())
len0=len(S)
while len(S)<len(T)*2:
    S=S+S

S=S+S

p=26
mod=(1<<50)+1# 互いに素なものを指定

TABLE=[0]# Rolling Hashのテーブル. 最初は0
LEN=len(S)

for i in range(LEN):
    TABLE.append((p*TABLE[-1]%mod+ord(S[i])-97)%mod)# テーブルを埋める

TABLE2=[0]# Rolling Hashのテーブル. 最初は0
LEN2=len(T)

for i in range(LEN2):
    TABLE2.append((p*TABLE2[-1]%mod+ord(T[i])-97)%mod)# テーブルを埋める

TH=TABLE2[-1]

def hash_ij(i,j): # [i,j)のハッシュ値を求める
    return (TABLE[j]-TABLE[i]*pow(p,j-i,mod))%mod

OK=[0]*LEN

for i in range(LEN2,LEN):
    if hash_ij(i-LEN2,i)==TH:
        OK[i-LEN2]=1

OK=OK[:len0]

ANS=0

ST=[-1]*len0

for i in range(len0):
    if OK[i]==1 and ST[i]==-1:

        j=i
        count=0

        while OK[j]==1:
            
            if ST[j]!=-1:
                count+=ST[j]
                break
            
            count+=1
            ST[j]=1
            j=(j+LEN2)%len0
            if j==i:
                print(-1)
                import sys
                sys.exit()

        ST[i]=count
        ANS=max(ANS,count)

print(ANS)

Submission status: Time Limit Exceeded

Solution code:
S=input()
T=input()
len0=len(S)
while len(S)<len(T)*2:
    S=S+S

S=S+S

p=26
mod=(1<<50)+1# 互いに素なものを指定

TABLE=[0]# Rolling Hashのテーブル. 最初は0
LEN=len(S)

for i in range(LEN):
    TABLE.append((p*TABLE[-1]%mod+ord(S[i])-97)%mod)# テーブルを埋める

TABLE2=[0]# Rolling Hashのテーブル. 最初は0
LEN2=len(T)

for i in range(LEN2):
    TABLE2.append((p*TABLE2[-1]%mod+ord(T[i])-97)%mod)# テーブルを埋める

TH=TABLE2[-1]

def hash_ij(i,j): # [i,j)のハッシュ値を求める
    return (TABLE[j]-TABLE[i]*pow(p,j-i,mod))%mod

OK=[0]*LEN

for i in range(LEN2,LEN):
    if hash_ij(i-LEN2,i)==TH:
        OK[i-LEN2]=1

OK=OK[:len0]

ANS=0

ST=[-1]*len0

for i in range(len0):
    if OK[i]==1 and ST[i]==-1:

        j=i
        count=0

        while OK[j]==1:
            
            if ST[j]!=-1:
                count+=ST[j]
                break
            
            count+=1
            ST[j]=1
            j=(j+LEN2)%len0
            if j==i:
                print(-1)
                import sys
                sys.exit()

        ST[i]=count
        ANS=max(ANS,count)

print(ANS)

Submission status: Time Limit Exceeded

Solution code:
S=input()
T=input()
len0=len(S)
while len(S)<len(T)*2:
    S=S+S

S=S+S

p=26
mod=(1<<50)+1# 互いに素なものを指定

TABLE=[0]# Rolling Hashのテーブル. 最初は0
LEN=len(S)

for i in range(LEN):
    TABLE.append((p*TABLE[-1]%mod+ord(S[i])-97)%mod)# テーブルを埋める

TABLE2=[0]# Rolling Hashのテーブル. 最初は0
LEN2=len(T)

for i in range(LEN2):
    TABLE2.append((p*TABLE2[-1]%mod+ord(T[i])-97)%mod)# テーブルを埋める

TH=TABLE2[-1]

def hash_ij(i,j): # [i,j)のハッシュ値を求める
    return (TABLE[j]-TABLE[i]*pow(p,j-i,mod))%mod

OK=[0]*LEN

for i in range(LEN2,LEN):
    if hash_ij(i-LEN2,i)==TH:
        OK[i-LEN2]=1

OK=OK[:len0]

ANS=0

for i in range(len0):
    if OK[i]==1:
        USED=[0]*len0

        j=i
        count=0

        while OK[j]==1:
            if USED[j]==1:
                print(-1)
                import sys
                sys.exit()
            count+=1
            USED[j]=1
            j=(j+LEN2)%len0

        ANS=max(ANS,count)

print(ANS)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
def Z(S):
    res = [0]*len(S)
    res[0] = len(S)
    i = 1
    j = 0
    while i < len(S):
        while i+j < len(S) and S[j] == S[i+j]:
            j += 1
        res[i] = j
        if j == 0:
            i += 1
            continue
        k = 1
        while i+k < len(S) and k+res[k] < j:
            res[i+k] = res[k]
            k += 1
        i += k
        j -= k
    return res

class UnionFind:
    def __init__(self, num):
        self.table = [-1 for _ in range(num)]

    def find(self, x):
        if self.table[x] < 0:
            return x
        else:
            self.table[x] = self.find(self.table[x])
            return self.table[x]

    def union(self, x, y):
        s1 = self.find(x)
        s2 = self.find(y)

        if s1 != s2:
            if self.table[s1] <= self.table[s2]:
                self.table[s1] += self.table[s2]
                self.table[s2] = s1
            else:
                self.table[s2] += self.table[s1]
                self.table[s1] = s2
            return True
        return False

s = input()
t = input()

S = s*(len(t)//len(s)+2)
z = Z(t+'*'+S)
z = z[len(t)+1:]

u = UnionFind(len(s))

loop = False
for i in range(len(s)):
    j = (i+len(t))%len(s)
    if z[i] == len(t) and z[j] == len(t):
        loop = (not u.union(i,j)) or loop
        
d = defaultdict(list)
for i in range(len(s)):
    if z[i] == len(t):
        d[u.find(i)].append(i)

if loop:
    ans = -1
else:
    ans = 0
    for k in d:
        ans = max(ans,len(d[k]))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
def Z(S):
    res = [0]*len(S)
    res[0] = len(S)
    i = 1
    j = 0
    while i < len(S):
        while i+j < len(S) and S[j] == S[i+j]:
            j += 1
        res[i] = j
        if j == 0:
            i += 1
            continue
        k = 1
        while i+k < len(S) and k+res[k] < j:
            res[i+k] = res[k]
            k += 1
        i += k
        j -= k
    return res

class UnionFind:
    def __init__(self, num):
        self.table = [-1 for _ in range(num)]

    def find(self, x):
        if self.table[x] < 0:
            return x
        else:
            self.table[x] = self.find(self.table[x])
            return self.table[x]

    def union(self, x, y):
        s1 = self.find(x)
        s2 = self.find(y)

        if s1 != s2:
            if self.table[s1] <= self.table[s2]:
                self.table[s1] += self.table[s2]
                self.table[s2] = s1
            else:
                self.table[s2] += self.table[s1]
                self.table[s1] = s2
            return True
        return False

s = input()
t = input()

S = s*(len(t)//len(s)+2)
z = Z(t+'*'+S)
z = z[len(t)+1:]

u = UnionFind(len(s))

for i in range(len(s)):
    j = (i+len(t))%len(s)
    if z[i] == len(t) and z[j] == len(t):
        u.union(i,j)

d = defaultdict(list)
for i in range(len(s)):
    if z[i] == len(t):
        d[u.find(i)].append(i)

ans = 0
for k in d:
    loop = True
    if len(d[k])==1:
        loop = len(t)%len(s)==0
    else:
        for i in d[k]:
            j = (i+len(t)*(len(d[k])-1))%len(s)
            loop = z[j]==len(t) and loop
    if loop:
        ans = -1
        break
    ans = max(ans,len(d[k]))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
def Z(S):
    res = [0]*len(S)
    res[0] = len(S)
    i = 1
    j = 0
    while i < len(S):
        while i+j < len(S) and S[j] == S[i+j]:
            j += 1
        res[i] = j
        if j == 0:
            i += 1
            continue
        k = 1
        while i+k < len(S) and k+res[k] < j:
            res[i+k] = res[k]
            k += 1
        i += k
        j -= k
    return res

from collections import defaultdict
class UnionFind:
    def __init__(self, num):
        self.table = [-1 for _ in range(num)]
        self.sz = defaultdict(lambda:1)

    def find(self, x):
        if self.table[x] < 0:
            return x
        else:
            self.table[x] = self.find(self.table[x])
            return self.table[x]

    def union(self, x, y):
        s1 = self.find(x)
        s2 = self.find(y)

        if s1 != s2:
            size = self.sz[s1]+self.sz[s2]
            if self.table[s1] <= self.table[s2]:
                self.table[s1] += self.table[s2]
                self.table[s2] = s1
            else:
                self.table[s2] += self.table[s1]
                self.table[s1] = s2
            s = self.find(x)
            self.sz[s] = size
            return True
        return False

    def size(self, x):
        s = self.find(x)
        return self.sz[s]

s = input()
t = input()

s = s*(len(t)//len(s)+2)
s = s+s

z = Z(t+'*'+s)
z = z[len(t)+1:]
u = UnionFind(len(z)+len(s))
for i in range(len(z)-len(t)):
    if z[i]==len(t) and z[i+len(t)]==len(t):
        u.union(i,i+len(t))

ans = 0
for i in range(len(z)):
    ans = max(u.sz[i],ans)

if ans >= 2:
    z = Z(t+'*'+s+s)
    z = z[len(t)+1:]
    for i in range(len(s)-len(t),len(z)-len(t)):
        if z[i]==len(t) and z[i+len(t)]==len(t):
            u.union(i,i+len(t))

    for i in range(len(z)):
        if u.sz[i] > ans:
            ans = -1

if max(z) != len(t):
    ans = 0

print(ans)

Submission status: Time Limit Exceeded

Solution code:
def Z(S):
    res = [0]*len(S)
    res[0] = len(S)
    i = 1
    j = 0
    while i < len(S):
        while i+j < len(S) and S[j] == S[i+j]:
            j += 1
        res[i] = j
        if j == 0:
            i += 1
            continue
        k = 1
        while i+k < len(S) and k+res[k] < j:
            res[i+k] = res[k]
            k += 1
        i += k
        j -= k
    return res

from collections import defaultdict
class UnionFind:
    def __init__(self, num):
        self.table = [-1 for _ in range(num)]
        self.sz = defaultdict(lambda:1)

    def find(self, x):
        if self.table[x] < 0:
            return x
        else:
            self.table[x] = self.find(self.table[x])
            return self.table[x]

    def union(self, x, y):
        s1 = self.find(x)
        s2 = self.find(y)

        if s1 != s2:
            size = self.sz[s1]+self.sz[s2]
            if self.table[s1] <= self.table[s2]:
                self.table[s1] += self.table[s2]
                self.table[s2] = s1
            else:
                self.table[s2] += self.table[s1]
                self.table[s1] = s2
            s = self.find(x)
            self.sz[s] = size
            return True
        return False

    def size(self, x):
        s = self.find(x)
        return self.sz[s]

s = input()
t = input()

s = s*(len(t)//len(s)+2)
s = s+s

z = Z(t+'*'+s)
z = z[len(t)+1:]
u = UnionFind(len(z)+len(s))
for i in range(len(z)-len(t)):
    if z[i]==len(t) and z[i+len(t)]==len(t):
        u.union(i,i+len(t))

ans = 0
for i in range(len(z)):
    ans = max(u.sz[i],ans)


z = Z(t+'*'+s+s)
z = z[len(t)+1:]
for i in range(len(s)-len(t),len(z)-len(t)):
    if z[i]==len(t) and z[i+len(t)]==len(t):
        u.union(i,i+len(t))

for i in range(len(z)):
    if u.sz[i] > ans:
        ans = -1

if max(z) != len(t):
    ans = 0

print(ans)

Submission status: Time Limit Exceeded

Solution code:
def Z(S):
    res = [0]*len(S)
    res[0] = len(S)
    i = 1
    j = 0
    while i < len(S):
        while i+j < len(S) and S[j] == S[i+j]:
            j += 1
        res[i] = j
        if j == 0:
            i += 1
            continue
        k = 1
        while i+k < len(S) and k+res[k] < j:
            res[i+k] = res[k]
            k += 1
        i += k
        j -= k
    return res

from collections import defaultdict
class UnionFind:
    def __init__(self, num):
        self.table = [-1 for _ in range(num)]
        self.sz = defaultdict(lambda:1)

    def find(self, x):
        if self.table[x] < 0:
            return x
        else:
            self.table[x] = self.find(self.table[x])
            return self.table[x]

    def union(self, x, y):
        s1 = self.find(x)
        s2 = self.find(y)

        if s1 != s2:
            size = self.sz[s1]+self.sz[s2]
            if self.table[s1] <= self.table[s2]:
                self.table[s1] += self.table[s2]
                self.table[s2] = s1
            else:
                self.table[s2] += self.table[s1]
                self.table[s1] = s2
            s = self.find(x)
            self.sz[s] = size
            return True
        return False

    def size(self, x):
        s = self.find(x)
        return self.sz[s]

s = input()
t = input()

s = s*(len(t)//len(s)+2)
s = s+s

z = Z(t+'*'+s)
z = z[len(t)+1:]
u = UnionFind(len(z)+len(s))
for i in range(len(z)-len(t)):
    if z[i]==len(t) and z[i+len(t)]==len(t):
        u.union(i,i+len(t))

ans = 0
for i in range(len(z)):
    ans = max(u.sz[i],ans)


z = Z(t+'*'+s+s)
z = z[len(t)+1:]
u = UnionFind(len(z)+len(s))
for i in range(len(s)-len(t),len(z)-len(t)):
    if z[i]==len(t) and z[i+len(t)]==len(t):
        u.union(i,i+len(t))

for i in range(len(z)):
    if u.sz[i] > ans:
        ans = -1

if max(z) != len(t):
    ans = 0

print(ans)