message
stringlengths
2
23.8k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
97
109k
cluster
float64
0
0
__index_level_0__
int64
194
217k
Provide a correct Python 3 solution for this coding contest problem. You are given a string of length N. Calculate the number of distinct substrings of S. Constraints * 1 \leq N \leq 500,000 * S consists of lowercase English letters. Input Input is given from Standard Input in the following format: S Output Print the answer. Examples Input abcbcba Output 21 Input mississippi Output 53 Input ababacaca Output 33 Input aaaaa Output 5
instruction
0
52,825
0
105,650
"Correct Solution: ``` class StrAlg: @staticmethod def sa_naive(s): n = len(s) sa = list(range(n)) sa.sort(key=lambda x: s[x:]) return sa @staticmethod def sa_doubling(s): n = len(s) sa = list(range(n)) rnk = s tmp = [0] * n k = 1 while k < n: sa.sort(key=lambda x: (rnk[x], rnk[x + k]) if x + k < n else (rnk[x], -1)) tmp[sa[0]] = 0 for i in range(1, n): tmp[sa[i]] = tmp[sa[i - 1]] x = (rnk[sa[i - 1]], rnk[sa[i - 1] + k]) if sa[i - 1] + \ k < n else (rnk[sa[i - 1]], -1) y = (rnk[sa[i]], rnk[sa[i] + k]) if sa[i] + \ k < n else (rnk[sa[i]], -1) if x < y: tmp[sa[i]] += 1 k *= 2 tmp, rnk = rnk, tmp return sa @staticmethod def sa_is(s, upper): n = len(s) if n == 0: return [] if n == 1: return [0] if n == 2: if s[0] < s[1]: return [0, 1] else: return [1, 0] if n < 10: return StrAlg.sa_naive(s) if n < 50: return StrAlg.sa_doubling(s) ls = [0] * n for i in range(n - 1)[::-1]: ls[i] = ls[i + 1] if s[i] == s[i + 1] else s[i] < s[i + 1] sum_l = [0] * (upper + 1) sum_s = [0] * (upper + 1) for i in range(n): if ls[i]: sum_l[s[i] + 1] += 1 else: sum_s[s[i]] += 1 for i in range(upper): sum_s[i] += sum_l[i] if i < upper: sum_l[i + 1] += sum_s[i] lms_map = [-1] * (n + 1) m = 0 for i in range(1, n): if not ls[i - 1] and ls[i]: lms_map[i] = m m += 1 lms = [] for i in range(1, n): if not ls[i - 1] and ls[i]: lms.append(i) sa = [-1] * n buf = sum_s.copy() for d in lms: if d == n: continue sa[buf[s[d]]] = d buf[s[d]] += 1 buf = sum_l.copy() sa[buf[s[n - 1]]] = n - 1 buf[s[n - 1]] += 1 for i in range(n): v = sa[i] if v >= 1 and not ls[v - 1]: sa[buf[s[v - 1]]] = v - 1 buf[s[v - 1]] += 1 buf = sum_l.copy() for i in range(n)[::-1]: v = sa[i] if v >= 1 and ls[v - 1]: buf[s[v - 1] + 1] -= 1 sa[buf[s[v - 1] + 1]] = v - 1 if m: sorted_lms = [] for v in sa: if lms_map[v] != -1: sorted_lms.append(v) rec_s = [0] * m rec_upper = 0 rec_s[lms_map[sorted_lms[0]]] = 0 for i in range(1, m): l = sorted_lms[i - 1] r = sorted_lms[i] end_l = lms[lms_map[l] + 1] if lms_map[l] + 1 < m else n end_r = lms[lms_map[r] + 1] if lms_map[r] + 1 < m else n same = True if end_l - l != end_r - r: same = False else: while l < end_l: if s[l] != s[r]: break l += 1 r += 1 if l == n or s[l] != s[r]: same = False if not same: rec_upper += 1 rec_s[lms_map[sorted_lms[i]]] = rec_upper rec_sa = StrAlg.sa_is(rec_s, rec_upper) for i in range(m): sorted_lms[i] = lms[rec_sa[i]] sa = [-1] * n buf = sum_s.copy() for d in sorted_lms: if d == n: continue sa[buf[s[d]]] = d buf[s[d]] += 1 buf = sum_l.copy() sa[buf[s[n - 1]]] = n - 1 buf[s[n - 1]] += 1 for i in range(n): v = sa[i] if v >= 1 and not ls[v - 1]: sa[buf[s[v - 1]]] = v - 1 buf[s[v - 1]] += 1 buf = sum_l.copy() for i in range(n)[::-1]: v = sa[i] if v >= 1 and ls[v - 1]: buf[s[v - 1] + 1] -= 1 sa[buf[s[v - 1] + 1]] = v - 1 return sa @staticmethod def suffix_array(s, upper=255): if type(s) is str: s = [ord(c) for c in s] return StrAlg.sa_is(s, upper) @staticmethod def lcp_array(s, sa): n = len(s) rnk = [0] * n for i in range(n): rnk[sa[i]] = i lcp = [0] * (n - 1) h = 0 for i in range(n): if h > 0: h -= 1 if rnk[i] == 0: continue j = sa[rnk[i] - 1] while j + h < n and i + h < n: if s[j + h] != s[i + h]: break h += 1 lcp[rnk[i] - 1] = h return lcp @staticmethod def z_algorithm(s): n = len(s) if n == 0: return [] z = [0] * n j = 0 for i in range(1, n): z[i] = 0 if j + z[j] <= i else min(j + z[j] - i, z[i - j]) while i + z[i] < n and s[z[i]] == s[i + z[i]]: z[i] += 1 if j + z[j] < i + z[i]: j = i z[0] = n return z def atcoder_practice2_i(): S = input() n = len(S) ans = (n+1)*n // 2 sa = StrAlg.suffix_array(S) ans -= sum(StrAlg.lcp_array(S, sa)) print(ans) if __name__ == "__main__": atcoder_practice2_i() ```
output
1
52,825
0
105,651
Provide a correct Python 3 solution for this coding contest problem. You are given a string of length N. Calculate the number of distinct substrings of S. Constraints * 1 \leq N \leq 500,000 * S consists of lowercase English letters. Input Input is given from Standard Input in the following format: S Output Print the answer. Examples Input abcbcba Output 21 Input mississippi Output 53 Input ababacaca Output 33 Input aaaaa Output 5
instruction
0
52,826
0
105,652
"Correct Solution: ``` class StrAlg: @staticmethod def sa_naive(s): n = len(s) sa = list(range(n)) sa.sort(key=lambda x: s[x:]) return sa @staticmethod def sa_doubling(s): n = len(s) sa = list(range(n)) rnk = s tmp = [0] * n k = 1 while k < n: sa.sort(key=lambda x: (rnk[x], rnk[x + k]) if x + k < n else (rnk[x], -1)) tmp[sa[0]] = 0 for i in range(1, n): tmp[sa[i]] = tmp[sa[i - 1]] if sa[i - 1] + k < n: x = (rnk[sa[i - 1]], rnk[sa[i - 1] + k]) else: x = (rnk[sa[i - 1]], -1) if sa[i] + k < n: y = (rnk[sa[i]], rnk[sa[i] + k]) else: y = (rnk[sa[i]], -1) if x < y: tmp[sa[i]] += 1 k *= 2 tmp, rnk = rnk, tmp return sa @staticmethod def sa_is(s, upper): n = len(s) if n == 0: return [] if n == 1: return [0] if n == 2: if s[0] < s[1]: return [0, 1] else: return [1, 0] if n < 10: return StrAlg.sa_naive(s) if n < 50: return StrAlg.sa_doubling(s) ls = [0] * n for i in range(n - 1)[::-1]: ls[i] = ls[i + 1] if s[i] == s[i + 1] else s[i] < s[i + 1] sum_l = [0] * (upper + 1) sum_s = [0] * (upper + 1) for i in range(n): if ls[i]: sum_l[s[i] + 1] += 1 else: sum_s[s[i]] += 1 for i in range(upper): sum_s[i] += sum_l[i] if i < upper: sum_l[i + 1] += sum_s[i] lms_map = [-1] * (n + 1) m = 0 for i in range(1, n): if not ls[i - 1] and ls[i]: lms_map[i] = m m += 1 lms = [] for i in range(1, n): if not ls[i - 1] and ls[i]: lms.append(i) sa = [-1] * n buf = sum_s.copy() for d in lms: if d == n: continue sa[buf[s[d]]] = d buf[s[d]] += 1 buf = sum_l.copy() sa[buf[s[n - 1]]] = n - 1 buf[s[n - 1]] += 1 for i in range(n): v = sa[i] if v >= 1 and not ls[v - 1]: sa[buf[s[v - 1]]] = v - 1 buf[s[v - 1]] += 1 buf = sum_l.copy() for i in range(n)[::-1]: v = sa[i] if v >= 1 and ls[v - 1]: buf[s[v - 1] + 1] -= 1 sa[buf[s[v - 1] + 1]] = v - 1 if m: sorted_lms = [] for v in sa: if lms_map[v] != -1: sorted_lms.append(v) rec_s = [0] * m rec_upper = 0 rec_s[lms_map[sorted_lms[0]]] = 0 for i in range(1, m): l = sorted_lms[i - 1] r = sorted_lms[i] end_l = lms[lms_map[l] + 1] if lms_map[l] + 1 < m else n end_r = lms[lms_map[r] + 1] if lms_map[r] + 1 < m else n same = True if end_l - l != end_r - r: same = False else: while l < end_l: if s[l] != s[r]: break l += 1 r += 1 if l == n or s[l] != s[r]: same = False if not same: rec_upper += 1 rec_s[lms_map[sorted_lms[i]]] = rec_upper rec_sa = StrAlg.sa_is(rec_s, rec_upper) for i in range(m): sorted_lms[i] = lms[rec_sa[i]] sa = [-1] * n buf = sum_s.copy() for d in sorted_lms: if d == n: continue sa[buf[s[d]]] = d buf[s[d]] += 1 buf = sum_l.copy() sa[buf[s[n - 1]]] = n - 1 buf[s[n - 1]] += 1 for i in range(n): v = sa[i] if v >= 1 and not ls[v - 1]: sa[buf[s[v - 1]]] = v - 1 buf[s[v - 1]] += 1 buf = sum_l.copy() for i in range(n)[::-1]: v = sa[i] if v >= 1 and ls[v - 1]: buf[s[v - 1] + 1] -= 1 sa[buf[s[v - 1] + 1]] = v - 1 return sa @staticmethod def suffix_array(s, upper=255): if type(s) is str: s = [ord(c) for c in s] return StrAlg.sa_is(s, upper) @staticmethod def lcp_array(s, sa): n = len(s) rnk = [0] * n for i in range(n): rnk[sa[i]] = i lcp = [0] * (n - 1) h = 0 for i in range(n): if h > 0: h -= 1 if rnk[i] == 0: continue j = sa[rnk[i] - 1] while j + h < n and i + h < n: if s[j + h] != s[i + h]: break h += 1 lcp[rnk[i] - 1] = h return lcp @staticmethod def z_algorithm(s): n = len(s) if n == 0: return [] z = [0] * n j = 0 for i in range(1, n): z[i] = 0 if j + z[j] <= i else min(j + z[j] - i, z[i - j]) while i + z[i] < n and s[z[i]] == s[i + z[i]]: z[i] += 1 if j + z[j] < i + z[i]: j = i z[0] = n return z def atcoder_practice2_i(): S = input() n = len(S) ans = (n+1)*n // 2 sa = StrAlg.suffix_array(S) ans -= sum(StrAlg.lcp_array(S, sa)) print(ans) if __name__ == "__main__": atcoder_practice2_i() ```
output
1
52,826
0
105,653
Provide a correct Python 3 solution for this coding contest problem. You are given a string of length N. Calculate the number of distinct substrings of S. Constraints * 1 \leq N \leq 500,000 * S consists of lowercase English letters. Input Input is given from Standard Input in the following format: S Output Print the answer. Examples Input abcbcba Output 21 Input mississippi Output 53 Input ababacaca Output 33 Input aaaaa Output 5
instruction
0
52,827
0
105,654
"Correct Solution: ``` #ord: $->36, 0->48, 9->57, A->65, Z->90, a->97, z->122 def SA_IS(s, upper=127): n = len(s) sa = [-1 for _ in range(n)] bucket = [0 for _ in range(upper + 1)] smaller = [True for _ in range(n)] #leftmost L-type is_lms = [False for _ in range(n)] lmss = [] #make indices of buckets #range of x's bucket is [bucket[x], bucket[x+1]) for x in s: bucket[x+1] += 1 for i in range(upper): bucket[i+1] += bucket[i] #step 1:decide whether s[i:n] is a S-type(smaller) or L-type(larger) # and whether it's an LMS for i in range(n-2, -1, -1): if s[i] > s[i+1] or (s[i] == s[i+1] and not smaller[i+1]): smaller[i] = False if smaller[i+1]: is_lms[i+1] = True lmss.append(i+1) #step 2-1: fill LMSs from the bottom count = [0 for _ in range(upper + 1)] for i in lmss: sa[bucket[s[i] + 1] - 1 - count[s[i] + 1]] = i count[s[i] + 1] += 1 #step 2-2: fill Ls from the beginning count = [0 for _ in range(upper + 1)] for i in range(n): if sa[i] > 0 and not smaller[sa[i] - 1]: sa[bucket[s[sa[i] - 1]] + count[s[sa[i] - 1] + 1]] = sa[i] - 1 count[s[sa[i] - 1] + 1] += 1 #step 2-3: fill Ss from the bottom count = [0 for _ in range(upper + 1)] for i in range(n-1, -1, -1): if sa[i] > 0 and smaller[sa[i] - 1]: sa[bucket[s[sa[i] - 1] + 1] - 1 - count[s[sa[i] - 1] + 1]] = sa[i] - 1 count[s[sa[i] - 1] + 1] += 1 #step 3: form reduced string from LMS blocks new_num = 0 new_array = [-1 for _ in range(len(lmss))] lms_to_ind = dict() for i, x in enumerate(lmss): lms_to_ind[x] = len(lmss) - 1 - i last = sa[0] new_array[lms_to_ind[sa[0]]] = 0 for i in range(1, n): if is_lms[sa[i]]: tmp, j = sa[i], 0 while True: if s[last + j] != s[tmp + j]: new_num += 1 break if j > 0 and (is_lms[last + j] or is_lms[tmp + j]): break j += 1 new_array[lms_to_ind[tmp]] = new_num last = tmp #step 4: sort LMS blocks #if all LMS blocks are different, recursion is not needed if new_num == len(lmss) - 1: seed = [-1 for _ in range(len(lmss))] for i, x in enumerate(new_array): seed[x] = i #call recursive function else: seed = SA_IS(new_array, upper=new_num + 1) new_lmss = [-1 for _ in range(len(lmss))] for i, x in enumerate(seed): new_lmss[len(lmss) - 1 - i] = lmss[len(lmss) - 1 - x] #step 5-1: fill LMSs from the bottom sa = [-1 for _ in range(n)] count = [0 for _ in range(upper + 1)] for i in new_lmss: sa[bucket[s[i] + 1] - 1 - count[s[i] + 1]] = i count[s[i] + 1] += 1 #step 5-2: fill Ls from the beginning count = [0 for _ in range(upper + 1)] for i in range(n): if sa[i] > 0 and not smaller[sa[i] - 1]: sa[bucket[s[sa[i] - 1]] + count[s[sa[i] - 1] + 1]] = sa[i] - 1 count[s[sa[i] - 1] + 1] += 1 #step 5-3: fill Ss from the bottom count = [0 for _ in range(upper + 1)] for i in range(n-1, -1, -1): if sa[i] > 0 and smaller[sa[i] - 1]: sa[bucket[s[sa[i] - 1] + 1] - 1 - count[s[sa[i] - 1] + 1]] = sa[i] - 1 count[s[sa[i] - 1] + 1] += 1 return sa def LCP_Array(s, sa): n = len(s)-1 rank = [-1 for _ in range(n)] for i, x in enumerate(sa): rank[x] = i lcp = [-1 for _ in range(n-1)] i = 0 for x in rank: if x == n-1: continue while sa[x] + i < n and sa[x+1] + i < n and s[sa[x] + i] == s[sa[x+1] + i]: i += 1 lcp[x] = i i = max(0, i-1) return lcp s = input() s = [ord(x)-96 for x in s] + [0] sa = SA_IS(s, 30)[1:] lcp = LCP_Array(s, sa) n = len(s)-1 print(n * (n+1) // 2 - sum(lcp)) ```
output
1
52,827
0
105,655
Provide a correct Python 3 solution for this coding contest problem. You are given a string of length N. Calculate the number of distinct substrings of S. Constraints * 1 \leq N \leq 500,000 * S consists of lowercase English letters. Input Input is given from Standard Input in the following format: S Output Print the answer. Examples Input abcbcba Output 21 Input mississippi Output 53 Input ababacaca Output 33 Input aaaaa Output 5
instruction
0
52,828
0
105,656
"Correct Solution: ``` #!/usr/bin/env python3 import sys sys.setrecursionlimit(10**6) INF = 10 ** 9 + 1 # sys.maxsize # float("inf") MOD = 10 ** 9 + 7 # suffix_array, lcp_array """ SA-IS Suffix Array Construction (derived from https://mametter.hatenablog.com/entry/20180130/p1) Construction of LCP array (derived from http://www.nct9.ne.jp/m_hiroi/light/pyalgo60.html) """ SMALLER = 0 LARGER = 1 def get_ls(seq): "smaller: 0, larger: 1" N = len(seq) ls = [SMALLER] * N # sentinel is the smallest # ls[-1] = SMALLER for i in range(N - 2, -1, -1): # s[i] < s[i+1] なら明らかに s[i..] < s[i+1..] => i は S 型 # s[i] > s[i+1] なら明らかに s[i..] > s[i+1..] => i は L 型 # s[i] == s[i+1] の場合、s[i..] <=> s[i+1..] の比較結果は # s[i+1..] <=> s[i+2..] に準ずる (つまり ls[i + 1] と同じ) if seq[i] < seq[i + 1]: ls[i] = SMALLER elif seq[i] > seq[i + 1]: ls[i] = LARGER else: ls[i] = ls[i + 1] return ls def get_lmss(ls): """ >>> get_lmss(get_ls("mmiissiissiippii$")) [2, 6, 10, 16] """ return [i for i in range(len(ls)) if is_lms(ls, i)] def is_lms(ls, i): # インデックス i が LMS かどうか return (i > 0 and ls[i - 1] == LARGER and ls[i] == SMALLER) def sa_is(seq, K=256): """ >>> sa_is(b"mmiissiissiippii$", 256) [16, 15, 14, 10, 6, 2, 11, 7, 3, 1, 0, 13, 12, 9, 5, 8, 4] >>> sa_is([2, 2, 1, 0], 3) [3, 2, 1, 0] """ # L 型か S 型かのテーブル ls = get_ls(seq) # LMS のインデックスだけを集めた配列 lmss = get_lmss(ls) # 適当な「種」:seed = lmss.shuffle でもよい seed = lmss # 1 回目の induced sort sa = induced_sort(seq, K, ls, seed) # induced sort の結果から LMS の suffix だけ取り出す sa = [i for i in sa if is_lms(ls, i)] # LMS のインデックス i に対して番号 nums[i] を振る nums = [None] * len(seq) # sa[0] の LMS は $ と決まっているので、番号 0 を振っておく nums[sa[0]] = num = 0 # 隣り合う LMS を比べる for index in range(1, len(sa)): i = sa[index - 1] j = sa[index] isDifferent = False # 隣り合う LMS 部分文字列の比較 for d in range(len(seq)): if seq[i + d] != seq[j + d] or is_lms(ls, i + d) != is_lms(ls, j + d): # LMS 部分文字列の範囲で異なる文字があった isDifferent = True break if d > 0 and (is_lms(ls, i + d) or is_lms(ls, j + d)): # LMS 部分文字列の終端に至った break # 隣り合う LMS 部分文字列が異なる場合は、番号を増やす if isDifferent: num += 1 # LMS のインデックス j に番号 num を振る nums[j] = num # nums の中に出現する番号のみを並べると、LMS 部分文字列を番号に置き換えた列が得られる # remove None from nums nums = list(filter(lambda x: x is not None, nums)) if num + 1 < len(nums): # 番号の重複があるので再帰 sa = sa_is(nums, num + 1) else: # 番号の重複がない場合、suffix array を容易に求められる sa = [None] * len(nums) for i, c in enumerate(nums): sa[c] = i # 正しい「種」 seed = [lmss[i] for i in sa] # 2 回目の induced sort sa = induced_sort(seq, K, ls, seed) return sa def induced_sort(seq, K, ls, lmss, verbose=False): """ >>> seq = b"mmiissiissiippii$" >>> ls = get_ls(seq) >>> lmss = get_lmss(ls) >>> induced_sort(seq, 256, ls, lmss, verbose=True) step1: [16, None, None, None, None, None, 2, 6, 10, None, None, None, None, None, None, None, None] step2: [16, 15, 14, None, None, None, 2, 6, 10, 1, 0, 13, 12, 5, 9, 4, 8] step3: [16, 15, 14, 10, 2, 6, 11, 3, 7, 1, 0, 13, 12, 5, 9, 4, 8] """ # 作業領域 sa = [None] * len(seq) # seq に出現する文字種ごとのカウント count = [0] * K for c in seq: count[c] += 1 # 累積和することで bin の境界インデックスを決める # 文字種cのbinはbin[c - 1] <= i < bin[c] # c is 0-origin from itertools import accumulate bin = list(accumulate(count)) + [0] # ステップ 1: LMS のインデックスをビンの終わりの方から入れる # ビンごとにすでに挿入した数をカウントする count_in_bin = [0] * K for lms in reversed(lmss): c = seq[lms] # c を入れるビンの終わり (bin[c] - 1) から詰めていれる pos = bin[c] - 1 - count_in_bin[c] sa[pos] = lms count_in_bin[c] += 1 if verbose: print("step1:", sa) # ステップ 2: sa を昇順に走査していく # ビンごとにすでに挿入した数をカウントする count_in_bin = [0] * K for i in sa: if i is None: continue if i == 0: continue if ls[i - 1] == SMALLER: continue # sa に入っているインデックス i について、i - 1 が L 型であるとき、 # 文字 seq[i - 1] に対応するビンに i - 1 を頭から詰めていれる c = seq[i - 1] pos = bin[c - 1] + count_in_bin[c] sa[pos] = i - 1 count_in_bin[c] += 1 if verbose: print("step2:", sa) # ステップ 3: sa を逆順に走査していく # ビンごとにすでに挿入した数をカウントする count_in_bin = [0] * K for i in reversed(sa): if i is None: continue if i == 0: continue if ls[i - 1] == LARGER: continue # sa に入っているインデックス i について、i - 1 が S 型であるとき、 # 文字 seq[i - 1] に対応するビンに i - 1 を終わりから詰めていれる c = seq[i - 1] pos = bin[c] - 1 - count_in_bin[c] sa[pos] = i - 1 # 上書きすることもある count_in_bin[c] += 1 if verbose: print("step3:", end=" ") return sa def get_height(seq, sa): """ Kasai method >>> s = b"banana$" >>> sa = sa_is(s, 256) >>> get_height(s, sa) [0, 1, 3, 0, 0, 2, -1] >>> get_height_naive(s, sa) == get_height(s, sa) True """ N = len(sa) rsa = [0] * N for i in range(N): rsa[sa[i]] = i def lcp(i, j): d = 0 while seq[i + d] == seq[j + d]: d += 1 return d height = [0] * N h = 0 for i in range(N): j = rsa[i] if j == N - 1: # last height[j] = -1 h = 0 continue k = sa[j + 1] if h > 0: h = h - 1 + lcp(i + h - 1, k + h - 1) else: h = lcp(i, k) height[j] = h return height def suffix_array(seq, K): return sa_is(seq, K) def lcp_array(seq, sa): return get_height(seq, sa) # --- def debug(*x): print(*x, file=sys.stderr) def solve(S): diff = ord("a") - 1 N = len(S) S = [c - diff for c in S] S.append(0) lcp = lcp_array(S, suffix_array(S, 27)) return N * (N + 1) // 2 - sum(lcp) - 1 def main(): # parse input S = input().strip() print(solve(S)) # tests T1 = """ abcbcba """ TEST_T1 = """ >>> as_input(T1) >>> main() 21 """ T2 = """ mississippi """ TEST_T2 = """ >>> as_input(T2) >>> main() 53 """ T3 = """ ababacaca """ TEST_T3 = """ >>> as_input(T3) >>> main() 33 """ T4 = """ aaaaa """ TEST_T4 = """ >>> as_input(T4) >>> main() 5 """ def _test(): import doctest doctest.testmod() g = globals() for k in sorted(g): if k.startswith("TEST_"): doctest.run_docstring_examples(g[k], g, name=k) def as_input(s): "use in test, use given string as input file" import io f = io.StringIO(s.strip()) g = globals() g["input"] = lambda: bytes(f.readline(), "ascii") g["read"] = lambda: bytes(f.read(), "ascii") input = sys.stdin.buffer.readline read = sys.stdin.buffer.read if sys.argv[-1] == "-t": print("testing") _test() sys.exit() main() ```
output
1
52,828
0
105,657
Provide a correct Python 3 solution for this coding contest problem. You are given a string of length N. Calculate the number of distinct substrings of S. Constraints * 1 \leq N \leq 500,000 * S consists of lowercase English letters. Input Input is given from Standard Input in the following format: S Output Print the answer. Examples Input abcbcba Output 21 Input mississippi Output 53 Input ababacaca Output 33 Input aaaaa Output 5
instruction
0
52,829
0
105,658
"Correct Solution: ``` def sa_naive(s: list): n = len(s) sa = list(range(n)) sa.sort(key=lambda x: s[x:]) return sa def sa_doubling(s: list): n = len(s) n_plus = n + 10 sa = list(range(n)) rnk = s[::] tmp = [0] * n k = 1 while(k < n): def cmp(x): first = rnk[x] * n_plus second = -1 if (x + k >= n) else rnk[x + k] return first + second sa.sort(key=cmp) tmp[sa[0]] = 0 for i in range(1, n): tmp[sa[i]] = tmp[sa[i - 1]] + (cmp(sa[i]) > cmp(sa[i - 1])) rnk, tmp = tmp, rnk k *= 2 return sa def sa_is(s: list, upper: int): THRESHOLD_NAIVE = 10 THRESHOLD_DOUBLING = 40 n = len(s) if(n == 0): return [] elif(n == 1): return [0] elif(n == 2): if(s[0] < s[1]): return [0, 1] else: return [1, 0] if(n < THRESHOLD_NAIVE): return sa_naive(s) elif(n < THRESHOLD_DOUBLING): return sa_doubling(s) sa = [0] * n ls = [0] * n for i in range(n - 2, -1, -1): ls[i] = ls[i + 1] if s[i] == s[i + 1] else s[i] < s[i + 1] sum_l = [0] * (upper + 1) sum_s = [0] * (upper + 1) for i in range(n): if(not ls[i]): sum_s[s[i]] += 1 else: sum_l[s[i] + 1] += 1 for i in range(upper): sum_s[i] += sum_l[i] if(i < upper): sum_l[i + 1] += sum_s[i] def induce(lms: list): nonlocal sa, sum_s, sum_l sa = [-1] * n buf = sum_s[::] for d in lms: if(d == n): continue sa[buf[s[d]]] = d buf[s[d]] += 1 buf = sum_l[::] sa[buf[s[n - 1]]] = n - 1 buf[s[n - 1]] += 1 for i in range(n): v = sa[i] if(v >= 1) & (not ls[v - 1]): sa[buf[s[v - 1]]] = v - 1 buf[s[v - 1]] += 1 buf = sum_l[::] for i in range(n - 1, -1, -1): v = sa[i] if(v >= 1) & (ls[v - 1]): buf[s[v - 1] + 1] -= 1 sa[buf[s[v - 1] + 1]] = v - 1 lms_map = [-1] * (n + 1) m = 0 for i in range(1, n): if(not ls[i - 1]) & (ls[i]): lms_map[i] = m m += 1 lms = [] for i in range(1, n): if(not ls[i - 1]) & (ls[i]): lms.append(i) induce(lms) if(m): sorted_lms = [] for v in sa: if(lms_map[v] != -1): sorted_lms.append(v) rec_s = [0] * m rec_upper = 0 rec_s[lms_map[sorted_lms[0]]] = 0 for i in range(1, m): l, r = sorted_lms[i - 1:i + 1] end_l = lms[lms_map[l] + 1] if (lms_map[l] + 1 < m) else n end_r = lms[lms_map[r] + 1] if (lms_map[r] + 1 < m) else n same = True if(end_l - l != end_r - r): same = False else: while(l < end_l): if(s[l] != s[r]): break l += 1 r += 1 if(l == n): same = False elif(s[l] != s[r]): same = False if(not same): rec_upper += 1 rec_s[lms_map[sorted_lms[i]]] = rec_upper rec_sa = sa_is(rec_s, rec_upper) for i in range(m): sorted_lms[i] = lms[rec_sa[i]] induce(sorted_lms) return sa def suffix_array(s, upper: int = -1): n = len(s) if(type(s) is list) & (upper >= 0): assert (0 <= min(s)) & (max(s) <= upper) return sa_is(s, upper) elif(type(s) is list) & (upper == -1): idx = list(range(n)) idx.sort(key=lambda x: s[x]) s2 = [0] * n now = 0 s2[idx[0]] = now for i in range(1, n): if(s[idx[i - 1]] != s[idx[i]]): now += 1 s[idx[i]] = now return sa_is(s2, now) elif(type(s) is str): s2 = [0] * n for i, si in enumerate(s): s2[i] = ord(si) return sa_is(s2, max(s2)) else: print('type error') assert 0 == 1 def lcp_array(s, sa: list): n = len(s) assert n >= 1 if(type(s) is str): s2 = [0] * n for i, si in enumerate(s): s2[i] = ord(si) s = s2 rnk = [0] * n for i, sai in enumerate(sa): rnk[sai] = i lcp = [0] * (n-1) h = 0 for i in range(n): if(h > 0): h -= 1 if(rnk[i] == 0): continue j = sa[rnk[i] - 1] while(j+h < n) & (i+h < n): if(s[j+h] != s[i+h]): break h += 1 lcp[rnk[i] - 1] = h return lcp s = input() n = len(s) sa = suffix_array(s) la = lcp_array(s,sa) ans = n*(n+1)//2 - sum(la) print(ans) ```
output
1
52,829
0
105,659
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string of length N. Calculate the number of distinct substrings of S. Constraints * 1 \leq N \leq 500,000 * S consists of lowercase English letters. Input Input is given from Standard Input in the following format: S Output Print the answer. Examples Input abcbcba Output 21 Input mississippi Output 53 Input ababacaca Output 33 Input aaaaa Output 5 Submitted Solution: ``` class StrAlg: @staticmethod def sa_naive(s): n = len(s) sa = list(range(n)) sa.sort(key=lambda x: s[x:]) return sa @staticmethod def sa_doubling(s): n = len(s) sa = list(range(n)) rnk = s tmp = [0] * n k = 1 while k < n: sa.sort(key=lambda x: (rnk[x], rnk[x + k]) if x + k < n else (rnk[x], -1)) tmp[sa[0]] = 0 for i in range(1, n): tmp[sa[i]] = tmp[sa[i - 1]] if sa[i - 1] + k < n: x = (rnk[sa[i - 1]], rnk[sa[i - 1] + k]) else: x = (rnk[sa[i - 1]], -1) if sa[i] + k < n: y = (rnk[sa[i]], rnk[sa[i] + k]) else: y = (rnk[sa[i]], -1) if x < y: tmp[sa[i]] += 1 k *= 2 tmp, rnk = rnk, tmp return sa @staticmethod def sa_is(s, upper): n = len(s) if n == 0: return [] if n == 1: return [0] if n == 2: if s[0] < s[1]: return [0, 1] else: return [1, 0] if n < 10: return StrAlg.sa_naive(s) if n < 50: return StrAlg.sa_doubling(s) ls = [0] * n for i in range(n-2, -1, -1): ls[i] = ls[i + 1] if s[i] == s[i + 1] else s[i] < s[i + 1] sum_l = [0] * (upper + 1) sum_s = [0] * (upper + 1) for i in range(n): if ls[i]: sum_l[s[i] + 1] += 1 else: sum_s[s[i]] += 1 for i in range(upper): sum_s[i] += sum_l[i] if i < upper: sum_l[i + 1] += sum_s[i] lms_map = [-1] * (n + 1) m = 0 for i in range(1, n): if not ls[i - 1] and ls[i]: lms_map[i] = m m += 1 lms = [] for i in range(1, n): if not ls[i - 1] and ls[i]: lms.append(i) sa = [-1] * n buf = sum_s.copy() for d in lms: if d == n: continue sa[buf[s[d]]] = d buf[s[d]] += 1 buf = sum_l.copy() sa[buf[s[n - 1]]] = n - 1 buf[s[n - 1]] += 1 for i in range(n): v = sa[i] if v >= 1 and not ls[v - 1]: sa[buf[s[v - 1]]] = v - 1 buf[s[v - 1]] += 1 buf = sum_l.copy() for i in range(n-1, -1, -1): v = sa[i] if v >= 1 and ls[v - 1]: buf[s[v - 1] + 1] -= 1 sa[buf[s[v - 1] + 1]] = v - 1 if m: sorted_lms = [] for v in sa: if lms_map[v] != -1: sorted_lms.append(v) rec_s = [0] * m rec_upper = 0 rec_s[lms_map[sorted_lms[0]]] = 0 for i in range(1, m): l = sorted_lms[i - 1] r = sorted_lms[i] end_l = lms[lms_map[l] + 1] if lms_map[l] + 1 < m else n end_r = lms[lms_map[r] + 1] if lms_map[r] + 1 < m else n same = True if end_l - l != end_r - r: same = False else: while l < end_l: if s[l] != s[r]: break l += 1 r += 1 if l == n or s[l] != s[r]: same = False if not same: rec_upper += 1 rec_s[lms_map[sorted_lms[i]]] = rec_upper rec_sa = StrAlg.sa_is(rec_s, rec_upper) for i in range(m): sorted_lms[i] = lms[rec_sa[i]] sa = [-1] * n buf = sum_s.copy() for d in sorted_lms: if d == n: continue sa[buf[s[d]]] = d buf[s[d]] += 1 buf = sum_l.copy() sa[buf[s[n - 1]]] = n - 1 buf[s[n - 1]] += 1 for i in range(n): v = sa[i] if v >= 1 and not ls[v - 1]: sa[buf[s[v - 1]]] = v - 1 buf[s[v - 1]] += 1 buf = sum_l.copy() for i in range(n-1, -1, -1): v = sa[i] if v >= 1 and ls[v - 1]: buf[s[v - 1] + 1] -= 1 sa[buf[s[v - 1] + 1]] = v - 1 return sa @staticmethod def suffix_array(s, upper=255): if type(s) is str: s = [ord(c) for c in s] return StrAlg.sa_is(s, upper) @staticmethod def lcp_array(s, sa): n = len(s) rnk = [0] * n for i in range(n): rnk[sa[i]] = i lcp = [0] * (n - 1) h = 0 for i in range(n): if h > 0: h -= 1 if rnk[i] == 0: continue j = sa[rnk[i] - 1] while j + h < n and i + h < n: if s[j + h] != s[i + h]: break h += 1 lcp[rnk[i] - 1] = h return lcp @staticmethod def z_algorithm(s): n = len(s) if n == 0: return [] z = [0] * n j = 0 for i in range(1, n): z[i] = 0 if j + z[j] <= i else min(j + z[j] - i, z[i - j]) while i + z[i] < n and s[z[i]] == s[i + z[i]]: z[i] += 1 if j + z[j] < i + z[i]: j = i z[0] = n return z def atcoder_practice2_i(): S = input() n = len(S) ans = (n+1)*n // 2 sa = StrAlg.suffix_array(S) ans -= sum(StrAlg.lcp_array(S, sa)) print(ans) if __name__ == "__main__": atcoder_practice2_i() ```
instruction
0
52,830
0
105,660
Yes
output
1
52,830
0
105,661
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string of length N. Calculate the number of distinct substrings of S. Constraints * 1 \leq N \leq 500,000 * S consists of lowercase English letters. Input Input is given from Standard Input in the following format: S Output Print the answer. Examples Input abcbcba Output 21 Input mississippi Output 53 Input ababacaca Output 33 Input aaaaa Output 5 Submitted Solution: ``` import copy import functools import typing def _sa_naive(s: typing.List[int]) -> typing.List[int]: sa = list(range(len(s))) return sorted(sa, key=lambda i: s[i:]) def _sa_doubling(s: typing.List[int]) -> typing.List[int]: n = len(s) sa = list(range(n)) rnk = copy.deepcopy(s) tmp = [0] * n k = 1 while k < n: def cmp(x: int, y: int) -> bool: if rnk[x] != rnk[y]: return rnk[x] - rnk[y] rx = rnk[x + k] if x + k < n else -1 ry = rnk[y + k] if y + k < n else -1 return rx - ry sa.sort(key=functools.cmp_to_key(cmp)) tmp[sa[0]] = 0 for i in range(1, n): tmp[sa[i]] = tmp[sa[i - 1]] + (1 if cmp(sa[i - 1], sa[i]) else 0) tmp, rnk = rnk, tmp k *= 2 return sa def _sa_is(s: typing.List[int], upper: int) -> typing.List[int]: ''' SA-IS, linear-time suffix array construction Reference: G. Nong, S. Zhang, and W. H. Chan, Two Efficient Algorithms for Linear Time Suffix Array Construction ''' threshold_naive = 10 threshold_doubling = 40 n = len(s) if n == 0: return [] if n == 1: return [0] if n == 2: if s[0] < s[1]: return [0, 1] else: return [1, 0] if n < threshold_naive: return _sa_naive(s) if n < threshold_doubling: return _sa_doubling(s) sa = [0] * n ls = [False] * n for i in range(n - 2, -1, -1): if s[i] == s[i + 1]: ls[i] = ls[i + 1] else: ls[i] = s[i] < s[i + 1] sum_l = [0] * (upper + 1) sum_s = [0] * (upper + 1) for i in range(n): if not ls[i]: sum_s[s[i]] += 1 else: sum_l[s[i] + 1] += 1 for i in range(upper + 1): sum_s[i] += sum_l[i] if i < upper: sum_l[i + 1] += sum_s[i] def induce(lms: typing.List[int]) -> None: nonlocal sa sa = [-1] * n buf = copy.deepcopy(sum_s) for d in lms: if d == n: continue sa[buf[s[d]]] = d buf[s[d]] += 1 buf = copy.deepcopy(sum_l) sa[buf[s[n - 1]]] = n - 1 buf[s[n - 1]] += 1 for i in range(n): v = sa[i] if v >= 1 and not ls[v - 1]: sa[buf[s[v - 1]]] = v - 1 buf[s[v - 1]] += 1 buf = copy.deepcopy(sum_l) for i in range(n - 1, -1, -1): v = sa[i] if v >= 1 and ls[v - 1]: buf[s[v - 1] + 1] -= 1 sa[buf[s[v - 1] + 1]] = v - 1 lms_map = [-1] * (n + 1) m = 0 for i in range(1, n): if not ls[i - 1] and ls[i]: lms_map[i] = m m += 1 lms = [] for i in range(1, n): if not ls[i - 1] and ls[i]: lms.append(i) induce(lms) if m: sorted_lms = [] for v in sa: if lms_map[v] != -1: sorted_lms.append(v) rec_s = [0] * m rec_upper = 0 rec_s[lms_map[sorted_lms[0]]] = 0 for i in range(1, m): left = sorted_lms[i - 1] right = sorted_lms[i] if lms_map[left] + 1 < m: end_l = lms[lms_map[left] + 1] else: end_l = n if lms_map[right] + 1 < m: end_r = lms[lms_map[right] + 1] else: end_r = n same = True if end_l - left != end_r - right: same = False else: while left < end_l: if s[left] != s[right]: break left += 1 right += 1 if left == n or s[left] != s[right]: same = False if not same: rec_upper += 1 rec_s[lms_map[sorted_lms[i]]] = rec_upper rec_sa = _sa_is(rec_s, rec_upper) for i in range(m): sorted_lms[i] = lms[rec_sa[i]] induce(sorted_lms) return sa def suffix_array(s: typing.Union[str, typing.List[int]], upper: typing.Optional[int] = None) -> typing.List[int]: if isinstance(s, str): return _sa_is([ord(c) for c in s], 255) elif upper is None: n = len(s) idx = list(range(n)) idx.sort(key=functools.cmp_to_key(lambda l, r: s[l] - s[r])) s2 = [0] * n now = 0 for i in range(n): if i and s[idx[i - 1]] != s[idx[i]]: now += 1 s2[idx[i]] = now return _sa_is(s2, now) else: assert 0 <= upper for d in s: assert 0 <= d <= upper return _sa_is(s, upper) def lcp_array(s: typing.Union[str, typing.List[int]], sa: typing.List[int]) -> typing.List[int]: ''' Reference: T. Kasai, G. Lee, H. Arimura, S. Arikawa, and K. Park, Linear-Time Longest-Common-Prefix Computation in Suffix Arrays and Its Applications ''' if isinstance(s, str): s = [ord(c) for c in s] n = len(s) assert n >= 1 rnk = [0] * n for i in range(n): rnk[sa[i]] = i lcp = [0] * (n - 1) h = 0 for i in range(n): if h > 0: h -= 1 if rnk[i] == 0: continue j = sa[rnk[i] - 1] while j + h < n and i + h < n: if s[j + h] != s[i + h]: break h += 1 lcp[rnk[i] - 1] = h return lcp def z_algorithm(s: typing.Union[str, typing.List[int]]) -> typing.List[int]: ''' Reference: D. Gusfield, Algorithms on Strings, Trees, and Sequences: Computer Science and Computational Biology ''' if isinstance(s, str): s = [ord(c) for c in s] n = len(s) if n == 0: return [] z = [0] * n j = 0 for i in range(1, n): z[i] = 0 if j + z[j] <= i else min(j + z[j] - i, z[i - j]) while i + z[i] < n and s[z[i]] == s[i + z[i]]: z[i] += 1 if j + z[j] < i + z[i]: j = i z[0] = n return z S = input() N = len(S) sa = suffix_array(S) lcp = lcp_array(S,sa) res = N*(N+1)//2 for tmp in lcp: res -= tmp print(res) ```
instruction
0
52,831
0
105,662
Yes
output
1
52,831
0
105,663
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string of length N. Calculate the number of distinct substrings of S. Constraints * 1 \leq N \leq 500,000 * S consists of lowercase English letters. Input Input is given from Standard Input in the following format: S Output Print the answer. Examples Input abcbcba Output 21 Input mississippi Output 53 Input ababacaca Output 33 Input aaaaa Output 5 Submitted Solution: ``` import sys input = sys.stdin.readline S = input()[: -1] N = len(S) def SuffixArray(n, s): order = [n - 1 - i for i in range(n)] order.sort(key = lambda x: s[x]) sa = [0] * n classes = [0] * n for i in range(n): sa[i] = order[i] classes[i] = S[i] k = 1 while k < n: c = classes[: ] for i in range(n): if i > 0 and (c[sa[i - 1]] == c[sa[i]]) and ((sa[i - 1] + k) < n) and ((c[sa[i - 1] + k // 2]) == c[sa[i] + k // 2]): classes[sa[i]] = classes[sa[i - 1]] else: classes[sa[i]] = i cc = [i for i in range(n)] ss = sa[: ] for i in range(n): if ss[i] - k >= 0: sa[cc[classes[ss[i] - k]]] = ss[i] - k cc[classes[ss[i] - k]] += 1 k <<= 1 return sa def LCPArray(n, s, sa): r = [0] * n for i in range(n): r[sa[i]] = i lcp = [0] * (n - 1) x = 0 for i in range(n): if x > 0: x -= 1 if r[i] == 0: continue j = sa[r[i] - 1] while max(i, j) + x < n: if s[i + x] != s[j + x]: break x += 1 lcp[r[i] - 1] = x return lcp sa = SuffixArray(N, S) lcp = LCPArray(N, S, sa) print(N * (N + 1) // 2 - sum(lcp)) ```
instruction
0
52,832
0
105,664
Yes
output
1
52,832
0
105,665
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string of length N. Calculate the number of distinct substrings of S. Constraints * 1 \leq N \leq 500,000 * S consists of lowercase English letters. Input Input is given from Standard Input in the following format: S Output Print the answer. Examples Input abcbcba Output 21 Input mississippi Output 53 Input ababacaca Output 33 Input aaaaa Output 5 Submitted Solution: ``` # Date [ 2020-09-09 16:51:26 ] # Problem [ i.py ] # Author Koki_tkg import sys # import math # import bisect # import numpy as np # from decimal import Decimal # from numba import njit, i8, u1, b1 #JIT compiler # from itertools import combinations, product # from collections import Counter, deque, defaultdict # sys.setrecursionlimit(10 ** 6) MOD = 10 ** 9 + 7 INF = 10 ** 9 PI = 3.14159265358979323846 def read_str(): return sys.stdin.readline().strip() def read_int(): return int(sys.stdin.readline().strip()) def read_ints(): return map(int, sys.stdin.readline().strip().split()) def read_ints2(x): return map(lambda num: int(num) - x, sys.stdin.readline().strip().split()) def read_str_list(): return list(sys.stdin.readline().strip().split()) def read_int_list(): return list(map(int, sys.stdin.readline().strip().split())) def GCD(a: int, b: int) -> int: return b if a%b==0 else GCD(b, a%b) def LCM(a: int, b: int) -> int: return (a * b) // GCD(a, b) # Converted AC Library from C++ to python def sa_native(s: list): from functools import cmp_to_key def mycmp(r, l): if l == r: return -1 while l < n and r < n: if s[l] != s[r]: return 1 if s[l] < s[r] else -1 l += 1 r += 1 return 1 if l == n else -1 n = len(s) sa = [i for i in range(n)] sa.sort(key=cmp_to_key(mycmp)) return sa def sa_doubling(s: list): from functools import cmp_to_key def mycmp(y, x): if rnk[x] != rnk[y]: return 1 if rnk[x] < rnk[y] else -1 rx = rnk[x + k] if x + k < n else -1 ry = rnk[y + k] if y + k < n else -1 return 1 if rx < ry else -1 n = len(s) sa = [i for i in range(n)]; rnk = s; tmp = [0] * n; k = 1 while k < n: sa.sort(key=cmp_to_key(mycmp)) tmp[sa[0]] = 0 for i in range(1, n): tmp[sa[i]] = tmp[sa[i - 1]] if mycmp(sa[i], sa[i - 1]) == 1: tmp[sa[i]] += 1 tmp, rnk = rnk, tmp k *= 2 return sa def sa_is(s: list, upper: int): ''' SA-IS, linear-time suffix array construction Reference: G. Nong, S. Zhang, and W. H. Chan, Two Efficient Algorithms for Linear Time Suffix Array Construction ''' THRESHOLD_NATIVE = 10 THRESHOLD_DOUBLING = 40 n = len(s) if n == 0: return [] if n == 1: return [0] if n == 2: if s[0] < s[1]: return [0, 1] else: return [1, 0] if n < THRESHOLD_NATIVE: return sa_native(s) if n < THRESHOLD_DOUBLING: return sa_doubling(s) sa = [0] * n ls = [False] * n for i in range(n - 2, -1, -1): ls[i] = ls[i + 1] if s[i] == s[i + 1] else s[i] < s[i + 1] sum_l = [0] * (upper + 1); sum_s = [0] * (upper + 1) for i in range(n): if not ls[i]: sum_s[s[i]] += 1 else: sum_l[s[i] + 1] += 1 for i in range(upper + 1): sum_s[i] += sum_l[i] if i < upper: sum_l[i + 1] += sum_s[i] def induce(lms: list): from copy import copy # ループより速く感じる for i in range(n): sa[i] = -1 # [-1]*n にするとバグる buf = [0] * (upper + 1) buf = copy(sum_s) for d in lms: if d == n: continue sa[buf[s[d]]] = d; buf[s[d]] += 1 buf = copy(sum_l) sa[buf[s[n - 1]]] = n - 1; buf[s[n - 1]] += 1 for i in range(n): v = sa[i] if v >= 1 and not ls[v - 1]: sa[buf[s[v - 1]]] = v - 1; buf[s[v - 1]] += 1 buf = copy(sum_l) for i in range(n - 1, -1, -1): v = sa[i] if v >= 1 and ls[v - 1]: buf[s[v - 1] + 1] -= 1; sa[buf[s[v - 1] + 1]] = v - 1 lms_map = [-1] * (n + 1) m = 0 for i in range(1, n): if not ls[i - 1] and ls[i]: lms_map[i] = m; m += 1 lms = [i for i in range(1, n) if not ls[i - 1] and ls[i]] induce(lms) if m: sorted_lms = [v for v in sa if lms_map[v] != -1] rec_s = [0] * m rec_upper = 0 rec_s[lms_map[sorted_lms[0]]] = 0 for i in range(1, m): l = sorted_lms[i - 1]; r = sorted_lms[i] end_l = lms[lms_map[l] + 1] if lms_map[l] + 1 < m else n end_r = lms[lms_map[r] + 1] if lms_map[r] + 1 < m else n same = True if end_l - l != end_r - r: same = False else: while l < end_l: if s[l] != s[r]: break l += 1 r += 1 if l == n or s[l] != s[r]: same = False if not same: rec_upper += 1 rec_s[lms_map[sorted_lms[i]]] = rec_upper rec_sa = sa_is(rec_s, rec_upper) for i in range(m): sorted_lms[i] = lms[rec_sa[i]] induce(sorted_lms) return sa def suffix_array(s: list, upper: int): assert 0 <= upper for d in s: assert 0 <= d and d <= upper sa = sa_is(s, upper) return sa def suffix_array2(s: list): from functools import cmp_to_key n = len(s) idx = [i for i in range(n)] idx.sort(key=cmp_to_key(lambda l, r: s[l] < s[r])) s2 = [0] * n now = 0 for i in range(n): if i and s[idx[i - 1]] != s[idx[i]]: now += 1 s2[idx[i]] = now return sa_is(s2, now) def suffix_array3(s: str): n = len(s) s2 = list(map(ord, s)) return sa_is(s2, 255) def lcp_array(s: list, sa: list): ''' Reference: T. Kasai, G. Lee, H. Arimura, S. Arikawa, and K. Park, Linear-Time Longest-Common-Prefix Computation in Suffix Arrays and Its Applications ''' n = len(s) assert n >= 1 rnk = [0] * n for i in range(n): rnk[sa[i]] = i lcp = [0] * (n - 1) h = 0 for i in range(n): if h > 0: h -= 1 if rnk[i] == 0: continue j = sa[rnk[i] - 1] while j + h < n and i + h < n: if s[j + h] != s[i + h]: break h += 1 lcp[rnk[i] - 1] = h return lcp def lcp_array2(s: str, sa: list): n = len(s) s2 = list(map(ord, s)) return lcp_array(s2, sa) def z_algorithm(s: list): ''' Reference: D. Gusfield, Algorithms on Strings, Trees, and Sequences: Computer Science and Computational Biology ''' n = len(s) if n == 0: return [] z = [-1] * n z[0] = 0; j = 0 for i in range(1, n): k = z[i] = 0 if j + z[j] <= i else min(j + z[j] - i, z[i - j]) while i + k < n and s[k] == s[i + k]: k += 1 z[i] = k if j + z[j] < i + z[i]: j = i z[0] = n return z def z_algorithm2(s: str): n = len(s) s2 = list(map(ord, s)) return z_algorithm(s2) def Main(): s = read_str() sa = suffix_array3(s) ans = len(s) * (len(s) + 1) // 2 for x in lcp_array2(s, sa): ans -= x print(ans) if __name__ == '__main__': Main() ```
instruction
0
52,833
0
105,666
Yes
output
1
52,833
0
105,667
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string of length N. Calculate the number of distinct substrings of S. Constraints * 1 \leq N \leq 500,000 * S consists of lowercase English letters. Input Input is given from Standard Input in the following format: S Output Print the answer. Examples Input abcbcba Output 21 Input mississippi Output 53 Input ababacaca Output 33 Input aaaaa Output 5 Submitted Solution: ``` mod = 1000000007 eps = 10**-9 def main(): import sys input = sys.stdin.readline # O(NlogN) # return suffix array and lcp array # 0th index of SA is |S| def SuffixArray(S): S = S + "$" N = len(S) LV = N.bit_length() # 0th sort P = [] C = [0] * N cnt = [[] for _ in range(256)] for i, s in enumerate(S): cnt[ord(s)].append(i) cnt_c = 0 for i_list in cnt: for i in i_list: P.append(i) C[i] = cnt_c if i_list: cnt_c += 1 # doubling for k in range(LV): P_new = [] C_new = [0] * N cnt = [[] for _ in range(N)] for i in range(N): P[i] = (P[i] - (1 << k)) % N cnt[C[P[i]]].append(P[i]) for i_list in cnt: for i in i_list: P_new.append(i) cnt_c = -1 prev = -1 for p in P_new: new = C[p] * N + C[(p + (1 << k)) % N] if new != prev: cnt_c += 1 prev = new C_new[p] = cnt_c P = P_new C = C_new # lcp rank = [0] * N for i in range(N): rank[P[i]] = i LCP = [0] * (N - 1) h = 0 for i in range(N - 1): j = P[rank[i] - 1] if h > 0: h -= 1 while i + h < N and j + h < N: if S[i + h] == S[j + h]: h += 1 else: break LCP[rank[i] - 1] = h return P, LCP S = input().rstrip('\n') N = len(S) SA, LCP = SuffixArray(S) print(N * (N+1) // 2 - sum(LCP)) if __name__ == '__main__': main() ```
instruction
0
52,834
0
105,668
No
output
1
52,834
0
105,669
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string of length N. Calculate the number of distinct substrings of S. Constraints * 1 \leq N \leq 500,000 * S consists of lowercase English letters. Input Input is given from Standard Input in the following format: S Output Print the answer. Examples Input abcbcba Output 21 Input mississippi Output 53 Input ababacaca Output 33 Input aaaaa Output 5 Submitted Solution: ``` import sys def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)] def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') sys.setrecursionlimit(10**9) INF = 10**19 MOD = 10**9 + 7 EPS = 10**-10 class SuffixArray: class SparseTable: def __init__(self, A, func): self.N = len(A) self.func = func h = 0 while 1<<h <= self.N: h += 1 self.dat = list2d(h, 1<<h, 0) self.height = [0] * (self.N+1) for i in range(2, self.N+1): self.height[i] = self.height[i>>1] + 1 for i in range(self.N): self.dat[0][i] = A[i] for i in range(1, h): for j in range(self.N): self.dat[i][j] = self.func(self.dat[i-1][j], self.dat[i-1][min(j+(1<<(i-1)), self.N-1)]) def get(self, l, r): """ 区間[l,r)でのmin,maxを取得 """ if l >= r: raise Exception a = self.height[r-l] return self.func(self.dat[a][l], self.dat[a][r-(1<<a)]) def __init__(self, S): self.k = 1 if S and type(S[0]) == str: self.S = [ord(s) for s in S] else: self.S = S self.N = len(S) self.rank = [0] * (self.N+1) self.tmp = [0] * (self.N+1) self.sa = [0] * (self.N+1) self.build_sa() # def compare_sa(self, i, j): # if self.rank[i] != self.rank[j]: # return self.rank[i] < self.rank[j] # else: # ri = self.rank[i+self.k] if i + self.k <= self.N else -1 # rj = self.rank[j+self.k] if j + self.k <= self.N else -1 # return ri < rj def compare_sa(self, i, j): """ saの比較関数 """ # 第1キー if self.rank[i] == self.rank[j]: res1 = 0 elif self.rank[i] < self.rank[j]: res1 = -1 else: res1 = 1 # 第2キー ri = self.rank[i+self.k] if i + self.k <= self.N else -1 rj = self.rank[j+self.k] if j + self.k <= self.N else -1 if ri == rj: res2 = 0 elif ri < rj: res2 = -1 else: res2 = 1 # 比較 return res1 or res2 def build_sa(self): """ Suffix Arrayの構築 """ from functools import cmp_to_key # 最初は1文字、ランクは文字コード for i in range(self.N+1): self.sa[i] = i self.rank[i] = self.S[i] if i < self.N else -1 # k文字についてソートされているところから、2k文字でソートする k = 1 while k <= self.N: self.k = k self.sa = sorted(self.sa, key=cmp_to_key(self.compare_sa)) k *= 2 # いったんtmpに次のランクを計算し、それからrankに移す self.tmp[self.sa[0]] = 0 for i in range(1, self.N+1): self.tmp[self.sa[i]] = self.tmp[self.sa[i-1]] + (1 if self.compare_sa(self.sa[i-1], self.sa[i]) else 0) for i in range(self.N+1): self.rank[i] = self.tmp[i] # 文字列が陽に持てる量ならこっちのが速い # from operator import itemgetter # suffix_arr = [(self.S[i:], i) for i in range(self.N+1)] # suffix_arr.sort(key=itemgetter(0)) # for i in range(self.N+1): # self.sa[i] = suffix_arr[i][1] def build_lcp(self): """ LCP配列の構築 """ self.lcp = [0] * (self.N+1) self.rsa = [0] * (self.N+1) for i in range(self.N+1): self.rsa[self.sa[i]] = i h = 0 self.lcp[0] = 0 for i in range(self.N): # 文字列内での位置iの接尾辞と、接尾辞配列内でその1つ前の接尾辞のLCPを求める j = self.sa[self.rsa[i]-1] # hを先頭の分1減らし、後ろが一致しているだけ増やす if h > 0: h -= 1 while j+h < self.N and i+h < self.N: if self.S[j+h] != self.S[i+h]: break h += 1 self.lcp[self.rsa[i]-1] = h def build_st(self): """ 区間取得のためSparseTableを構築 """ self.st = self.SparseTable(self.lcp, min) def getLCP(self, i, j): """ S[i:]とS[j:]の共通文字数を取得 """ return self.st.get(min(self.rsa[i], self.rsa[j]), max(self.rsa[i], self.rsa[j])) S = input() N = len(S) sa = SuffixArray(S) sa.build_lcp() ans = N*(N+1) // 2 for i in range(N): ans -= sa.lcp[i] print(ans) ```
instruction
0
52,835
0
105,670
No
output
1
52,835
0
105,671
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string of length N. Calculate the number of distinct substrings of S. Constraints * 1 \leq N \leq 500,000 * S consists of lowercase English letters. Input Input is given from Standard Input in the following format: S Output Print the answer. Examples Input abcbcba Output 21 Input mississippi Output 53 Input ababacaca Output 33 Input aaaaa Output 5 Submitted Solution: ``` def calc_lcp(s1,s2): count=0 for i in range(min(len(s1), len(s2))): if s1[i] == s2[i]: count += 1 else: break return count def suffix_array(s, lcp=True): sa = sorted([(i,s[i:]) for i in range(len(s))], key=lambda x: x[1]) if lcp: return sa,[calc_lcp(sa[i-1][1], sa[i][1]) for i in range(1,len(s))] else: return sa S = input() N = len(S) _,lcp = suffix_array(S) print(N*(N+1)//2-sum(lcp)) ```
instruction
0
52,836
0
105,672
No
output
1
52,836
0
105,673
Provide tags and a correct Python 3 solution for this coding contest problem. Bob has a string s consisting of lowercase English letters. He defines s' to be the string after removing all "a" characters from s (keeping all other characters in the same order). He then generates a new string t by concatenating s and s'. In other words, t=s+s' (look at notes for an example). You are given a string t. Your task is to find some s that Bob could have used to generate t. It can be shown that if an answer exists, it will be unique. Input The first line of input contains a string t (1 ≤ |t| ≤ 10^5) consisting of lowercase English letters. Output Print a string s that could have generated t. It can be shown if an answer exists, it is unique. If no string exists, print ":(" (without double quotes, there is no space between the characters). Examples Input aaaaa Output aaaaa Input aacaababc Output :( Input ababacacbbcc Output ababacac Input baba Output :( Note In the first example, we have s = "aaaaa", and s' = "". In the second example, no such s can work that will generate the given t. In the third example, we have s = "ababacac", and s' = "bbcc", and t = s + s' = "ababacacbbcc".
instruction
0
53,102
0
106,204
Tags: implementation, strings Correct Solution: ``` t=input() len1=len(t) new="" for ch in t: if ch!='a': new+=ch n=len(new) if n%2!=0: print(":(") else: half=n//2 s1=new[:half] s2=new[half:] if s1!=s2: print(":(") else: str=t[:len1-half] s="" for ch in str: if ch!='a': s+=ch new_str=str+s if t!=new_str: print(":(") else: print(str) ```
output
1
53,102
0
106,205
Provide tags and a correct Python 3 solution for this coding contest problem. Bob has a string s consisting of lowercase English letters. He defines s' to be the string after removing all "a" characters from s (keeping all other characters in the same order). He then generates a new string t by concatenating s and s'. In other words, t=s+s' (look at notes for an example). You are given a string t. Your task is to find some s that Bob could have used to generate t. It can be shown that if an answer exists, it will be unique. Input The first line of input contains a string t (1 ≤ |t| ≤ 10^5) consisting of lowercase English letters. Output Print a string s that could have generated t. It can be shown if an answer exists, it is unique. If no string exists, print ":(" (without double quotes, there is no space between the characters). Examples Input aaaaa Output aaaaa Input aacaababc Output :( Input ababacacbbcc Output ababacac Input baba Output :( Note In the first example, we have s = "aaaaa", and s' = "". In the second example, no such s can work that will generate the given t. In the third example, we have s = "ababacac", and s' = "bbcc", and t = s + s' = "ababacacbbcc".
instruction
0
53,103
0
106,206
Tags: implementation, strings Correct Solution: ``` # -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ x = input() numAs = x.count('a') sLength = (len(x) - numAs)//2 + numAs s = x[:sLength] sPrime = x[sLength:] s = s.replace('a', '') if (s == sPrime): print(x[:sLength]) else: print(':(') ```
output
1
53,103
0
106,207
Provide tags and a correct Python 3 solution for this coding contest problem. Bob has a string s consisting of lowercase English letters. He defines s' to be the string after removing all "a" characters from s (keeping all other characters in the same order). He then generates a new string t by concatenating s and s'. In other words, t=s+s' (look at notes for an example). You are given a string t. Your task is to find some s that Bob could have used to generate t. It can be shown that if an answer exists, it will be unique. Input The first line of input contains a string t (1 ≤ |t| ≤ 10^5) consisting of lowercase English letters. Output Print a string s that could have generated t. It can be shown if an answer exists, it is unique. If no string exists, print ":(" (without double quotes, there is no space between the characters). Examples Input aaaaa Output aaaaa Input aacaababc Output :( Input ababacacbbcc Output ababacac Input baba Output :( Note In the first example, we have s = "aaaaa", and s' = "". In the second example, no such s can work that will generate the given t. In the third example, we have s = "ababacac", and s' = "bbcc", and t = s + s' = "ababacacbbcc".
instruction
0
53,104
0
106,208
Tags: implementation, strings Correct Solution: ``` from queue import Queue line = input() dic = {} arr = [] last = -1 q = Queue() c = 0 s = [] for i in range(0, len(line)): s.append(line[i]) if line[i] == 'a': c += 1 last = i else: arr.append(line[i]) dic[line[i]] = i if len(arr) % 2 != 0: print(":(") else: X = False temp1 = arr[0:int(len(arr) / 2)] temp2 = arr[int(len(arr) / 2):len(arr)] flag3 = False lst = 0 for x, y in list(zip(temp1, temp2)): if not flag3: flag3 = True lst = dic[y] if x != y: print(":(") X = True break if dic[y] <= last: print(":(") X = True break if not X: for p in range(0, int(((len(s) - c) / 2) + c)): print(s[p], end='') ```
output
1
53,104
0
106,209
Provide tags and a correct Python 3 solution for this coding contest problem. Bob has a string s consisting of lowercase English letters. He defines s' to be the string after removing all "a" characters from s (keeping all other characters in the same order). He then generates a new string t by concatenating s and s'. In other words, t=s+s' (look at notes for an example). You are given a string t. Your task is to find some s that Bob could have used to generate t. It can be shown that if an answer exists, it will be unique. Input The first line of input contains a string t (1 ≤ |t| ≤ 10^5) consisting of lowercase English letters. Output Print a string s that could have generated t. It can be shown if an answer exists, it is unique. If no string exists, print ":(" (without double quotes, there is no space between the characters). Examples Input aaaaa Output aaaaa Input aacaababc Output :( Input ababacacbbcc Output ababacac Input baba Output :( Note In the first example, we have s = "aaaaa", and s' = "". In the second example, no such s can work that will generate the given t. In the third example, we have s = "ababacac", and s' = "bbcc", and t = s + s' = "ababacacbbcc".
instruction
0
53,105
0
106,210
Tags: implementation, strings Correct Solution: ``` def sv(): T = input() TnoA = ''.join(c for c in T if c != 'a') N = len(TnoA) if N == 0: print(T) return if N % 2 or T[-N//2:] != TnoA[:N//2]: print(':(') return print(T[:-N//2]) return sv() ```
output
1
53,105
0
106,211
Provide tags and a correct Python 3 solution for this coding contest problem. Bob has a string s consisting of lowercase English letters. He defines s' to be the string after removing all "a" characters from s (keeping all other characters in the same order). He then generates a new string t by concatenating s and s'. In other words, t=s+s' (look at notes for an example). You are given a string t. Your task is to find some s that Bob could have used to generate t. It can be shown that if an answer exists, it will be unique. Input The first line of input contains a string t (1 ≤ |t| ≤ 10^5) consisting of lowercase English letters. Output Print a string s that could have generated t. It can be shown if an answer exists, it is unique. If no string exists, print ":(" (without double quotes, there is no space between the characters). Examples Input aaaaa Output aaaaa Input aacaababc Output :( Input ababacacbbcc Output ababacac Input baba Output :( Note In the first example, we have s = "aaaaa", and s' = "". In the second example, no such s can work that will generate the given t. In the third example, we have s = "ababacac", and s' = "bbcc", and t = s + s' = "ababacacbbcc".
instruction
0
53,106
0
106,212
Tags: implementation, strings Correct Solution: ``` s = input() cnta = len(s.split('a')) - 1 len_no_a = len(s) - cnta; if len_no_a % 2 == 1: print (":(") exit(0) len_no_a //= 2 then_1 = s[:len(s)-len_no_a] then_2 = s[len(s)-len_no_a:len(s)] if (''.join(then_1.split('a')) != then_2): print (":(") else: print (then_1) ```
output
1
53,106
0
106,213
Provide tags and a correct Python 3 solution for this coding contest problem. Bob has a string s consisting of lowercase English letters. He defines s' to be the string after removing all "a" characters from s (keeping all other characters in the same order). He then generates a new string t by concatenating s and s'. In other words, t=s+s' (look at notes for an example). You are given a string t. Your task is to find some s that Bob could have used to generate t. It can be shown that if an answer exists, it will be unique. Input The first line of input contains a string t (1 ≤ |t| ≤ 10^5) consisting of lowercase English letters. Output Print a string s that could have generated t. It can be shown if an answer exists, it is unique. If no string exists, print ":(" (without double quotes, there is no space between the characters). Examples Input aaaaa Output aaaaa Input aacaababc Output :( Input ababacacbbcc Output ababacac Input baba Output :( Note In the first example, we have s = "aaaaa", and s' = "". In the second example, no such s can work that will generate the given t. In the third example, we have s = "ababacac", and s' = "bbcc", and t = s + s' = "ababacacbbcc".
instruction
0
53,107
0
106,214
Tags: implementation, strings Correct Solution: ``` a = input()[::-1] b, i = a.replace('a',''), 0 for i in range(len(a)): if a[:i] == b[i:]: print(a[i:][::-1]) break else: print(':(') ```
output
1
53,107
0
106,215
Provide tags and a correct Python 3 solution for this coding contest problem. Bob has a string s consisting of lowercase English letters. He defines s' to be the string after removing all "a" characters from s (keeping all other characters in the same order). He then generates a new string t by concatenating s and s'. In other words, t=s+s' (look at notes for an example). You are given a string t. Your task is to find some s that Bob could have used to generate t. It can be shown that if an answer exists, it will be unique. Input The first line of input contains a string t (1 ≤ |t| ≤ 10^5) consisting of lowercase English letters. Output Print a string s that could have generated t. It can be shown if an answer exists, it is unique. If no string exists, print ":(" (without double quotes, there is no space between the characters). Examples Input aaaaa Output aaaaa Input aacaababc Output :( Input ababacacbbcc Output ababacac Input baba Output :( Note In the first example, we have s = "aaaaa", and s' = "". In the second example, no such s can work that will generate the given t. In the third example, we have s = "ababacac", and s' = "bbcc", and t = s + s' = "ababacacbbcc".
instruction
0
53,108
0
106,216
Tags: implementation, strings Correct Solution: ``` s = input() k = set(s) if len(k) == 1 and s[0] == "a": print(s) else: c1, c2 = 0, 0 for i in s: if i == "a": c1 += 1 else: c2 += 1 if c2 % 2 != 0: print(":(") else: k = c2//2 f = s[-k:] z = "" n = len(s) for i in range(n-k): if s[i] != "a": z += s[i] if f == z: print(s[:n-k]) else: print(":(") ```
output
1
53,108
0
106,217
Provide tags and a correct Python 3 solution for this coding contest problem. Bob has a string s consisting of lowercase English letters. He defines s' to be the string after removing all "a" characters from s (keeping all other characters in the same order). He then generates a new string t by concatenating s and s'. In other words, t=s+s' (look at notes for an example). You are given a string t. Your task is to find some s that Bob could have used to generate t. It can be shown that if an answer exists, it will be unique. Input The first line of input contains a string t (1 ≤ |t| ≤ 10^5) consisting of lowercase English letters. Output Print a string s that could have generated t. It can be shown if an answer exists, it is unique. If no string exists, print ":(" (without double quotes, there is no space between the characters). Examples Input aaaaa Output aaaaa Input aacaababc Output :( Input ababacacbbcc Output ababacac Input baba Output :( Note In the first example, we have s = "aaaaa", and s' = "". In the second example, no such s can work that will generate the given t. In the third example, we have s = "ababacac", and s' = "bbcc", and t = s + s' = "ababacacbbcc".
instruction
0
53,109
0
106,218
Tags: implementation, strings Correct Solution: ``` t = input() countOfAs = t.count("a") if (len(t)+countOfAs)%2: print(":(") else: lenOfS = int((len(t)+countOfAs)/2) if t[:lenOfS].replace("a", "") == t[lenOfS:]: print(t[:lenOfS]) else: print(":(") ```
output
1
53,109
0
106,219
Provide tags and a correct Python 3 solution for this coding contest problem. One day Polycarpus got hold of two non-empty strings s and t, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "x y" are there, such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. Two pairs are considered different, if they contain different substrings of string s or different subsequences of string t. Read the whole statement to understand the definition of different substrings and subsequences. The length of string s is the number of characters in it. If we denote the length of the string s as |s|, we can write the string as s = s1s2... s|s|. A substring of s is a non-empty string x = s[a... b] = sasa + 1... sb (1 ≤ a ≤ b ≤ |s|). For example, "code" and "force" are substrings or "codeforces", while "coders" is not. Two substrings s[a... b] and s[c... d] are considered to be different if a ≠ c or b ≠ d. For example, if s="codeforces", s[2...2] and s[6...6] are different, though their content is the same. A subsequence of s is a non-empty string y = s[p1p2... p|y|] = sp1sp2... sp|y| (1 ≤ p1 < p2 < ... < p|y| ≤ |s|). For example, "coders" is a subsequence of "codeforces". Two subsequences u = s[p1p2... p|u|] and v = s[q1q2... q|v|] are considered different if the sequences p and q are different. Input The input consists of two lines. The first of them contains s (1 ≤ |s| ≤ 5000), and the second one contains t (1 ≤ |t| ≤ 5000). Both strings consist of lowercase Latin letters. Output Print a single number — the number of different pairs "x y" such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. As the answer can be rather large, print it modulo 1000000007 (109 + 7). Examples Input aa aa Output 5 Input codeforces forceofcode Output 60 Note Let's write down all pairs "x y" that form the answer in the first sample: "s[1...1] t[1]", "s[2...2] t[1]", "s[1...1] t[2]","s[2...2] t[2]", "s[1...2] t[1 2]".
instruction
0
53,335
0
106,670
Tags: dp Correct Solution: ``` from sys import stdin s=[ord(i)-97 for i in stdin.readline().strip()] s1=[ord(i)-97 for i in stdin.readline().strip()] n=len(s) m=len(s1) mod=1000000007 dp=[[0 for i in range(n)] for j in range(26)] for i in range(m): arr=[0 for j in range(n)] for j in range(n): if s1[i]==s[j] : arr[j]=1 if j>0 : arr[j]=(arr[j]+dp[s[j-1]][j-1])%mod for j in range(n): dp[s1[i]][j]=(arr[j] +dp[s1[i]][j]) %mod x=0 for i in dp: for j in i: x=(x+j)%mod print(x) ```
output
1
53,335
0
106,671
Provide tags and a correct Python 3 solution for this coding contest problem. One day Polycarpus got hold of two non-empty strings s and t, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "x y" are there, such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. Two pairs are considered different, if they contain different substrings of string s or different subsequences of string t. Read the whole statement to understand the definition of different substrings and subsequences. The length of string s is the number of characters in it. If we denote the length of the string s as |s|, we can write the string as s = s1s2... s|s|. A substring of s is a non-empty string x = s[a... b] = sasa + 1... sb (1 ≤ a ≤ b ≤ |s|). For example, "code" and "force" are substrings or "codeforces", while "coders" is not. Two substrings s[a... b] and s[c... d] are considered to be different if a ≠ c or b ≠ d. For example, if s="codeforces", s[2...2] and s[6...6] are different, though their content is the same. A subsequence of s is a non-empty string y = s[p1p2... p|y|] = sp1sp2... sp|y| (1 ≤ p1 < p2 < ... < p|y| ≤ |s|). For example, "coders" is a subsequence of "codeforces". Two subsequences u = s[p1p2... p|u|] and v = s[q1q2... q|v|] are considered different if the sequences p and q are different. Input The input consists of two lines. The first of them contains s (1 ≤ |s| ≤ 5000), and the second one contains t (1 ≤ |t| ≤ 5000). Both strings consist of lowercase Latin letters. Output Print a single number — the number of different pairs "x y" such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. As the answer can be rather large, print it modulo 1000000007 (109 + 7). Examples Input aa aa Output 5 Input codeforces forceofcode Output 60 Note Let's write down all pairs "x y" that form the answer in the first sample: "s[1...1] t[1]", "s[2...2] t[1]", "s[1...1] t[2]","s[2...2] t[2]", "s[1...2] t[1 2]".
instruction
0
53,336
0
106,672
Tags: dp Correct Solution: ``` def f(a,b): dp=[[0]*(len(b)+1) for i in range(len(a)+1)] for i in range(len(a)): for j in range(len(b)): dp[i+1][j+1]=(dp[i+1][j]+(a[i]==b[j])*(dp[i][j]+1))%(10**9+7) ans=0 for i in range(0,len(a)): ans=(ans+dp[i+1][-1])%(10**9+7) return ans a=input() b=input() print(f(a,b)) ```
output
1
53,336
0
106,673
Provide tags and a correct Python 3 solution for this coding contest problem. One day Polycarpus got hold of two non-empty strings s and t, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "x y" are there, such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. Two pairs are considered different, if they contain different substrings of string s or different subsequences of string t. Read the whole statement to understand the definition of different substrings and subsequences. The length of string s is the number of characters in it. If we denote the length of the string s as |s|, we can write the string as s = s1s2... s|s|. A substring of s is a non-empty string x = s[a... b] = sasa + 1... sb (1 ≤ a ≤ b ≤ |s|). For example, "code" and "force" are substrings or "codeforces", while "coders" is not. Two substrings s[a... b] and s[c... d] are considered to be different if a ≠ c or b ≠ d. For example, if s="codeforces", s[2...2] and s[6...6] are different, though their content is the same. A subsequence of s is a non-empty string y = s[p1p2... p|y|] = sp1sp2... sp|y| (1 ≤ p1 < p2 < ... < p|y| ≤ |s|). For example, "coders" is a subsequence of "codeforces". Two subsequences u = s[p1p2... p|u|] and v = s[q1q2... q|v|] are considered different if the sequences p and q are different. Input The input consists of two lines. The first of them contains s (1 ≤ |s| ≤ 5000), and the second one contains t (1 ≤ |t| ≤ 5000). Both strings consist of lowercase Latin letters. Output Print a single number — the number of different pairs "x y" such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. As the answer can be rather large, print it modulo 1000000007 (109 + 7). Examples Input aa aa Output 5 Input codeforces forceofcode Output 60 Note Let's write down all pairs "x y" that form the answer in the first sample: "s[1...1] t[1]", "s[2...2] t[1]", "s[1...1] t[2]","s[2...2] t[2]", "s[1...2] t[1 2]".
instruction
0
53,337
0
106,674
Tags: dp Correct Solution: ``` s=input().strip() t=input().strip() n,m=len(s),len(t) mod=10**9+7 dp12=[[0 for i in range(m)]for j in range(n) ] #print(dp) dp12[0][0]=int(s[0]==t[0]) for i in range(1,n): if t[0]==s[i]: dp12[i][0]=1 for i in range(1,m): if s[0]==t[i] : dp12[0][i]=(dp12[0][i-1]+1)%mod else: dp12[0][i]=(dp12[0][i-1])%mod for i in range(1,n): for j in range(1,m): if s[i]==t[j]: dp12[i][j]=(max(1,dp12[i][j], (dp12[i-1][j-1]+dp12[i][j-1]+1)))%mod else: dp12[i][j]=(dp12[i][j-1])%mod an=0 for i in range(n): an=(an+dp12[i][-1])%mod print(an) ```
output
1
53,337
0
106,675
Provide tags and a correct Python 3 solution for this coding contest problem. One day Polycarpus got hold of two non-empty strings s and t, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "x y" are there, such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. Two pairs are considered different, if they contain different substrings of string s or different subsequences of string t. Read the whole statement to understand the definition of different substrings and subsequences. The length of string s is the number of characters in it. If we denote the length of the string s as |s|, we can write the string as s = s1s2... s|s|. A substring of s is a non-empty string x = s[a... b] = sasa + 1... sb (1 ≤ a ≤ b ≤ |s|). For example, "code" and "force" are substrings or "codeforces", while "coders" is not. Two substrings s[a... b] and s[c... d] are considered to be different if a ≠ c or b ≠ d. For example, if s="codeforces", s[2...2] and s[6...6] are different, though their content is the same. A subsequence of s is a non-empty string y = s[p1p2... p|y|] = sp1sp2... sp|y| (1 ≤ p1 < p2 < ... < p|y| ≤ |s|). For example, "coders" is a subsequence of "codeforces". Two subsequences u = s[p1p2... p|u|] and v = s[q1q2... q|v|] are considered different if the sequences p and q are different. Input The input consists of two lines. The first of them contains s (1 ≤ |s| ≤ 5000), and the second one contains t (1 ≤ |t| ≤ 5000). Both strings consist of lowercase Latin letters. Output Print a single number — the number of different pairs "x y" such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. As the answer can be rather large, print it modulo 1000000007 (109 + 7). Examples Input aa aa Output 5 Input codeforces forceofcode Output 60 Note Let's write down all pairs "x y" that form the answer in the first sample: "s[1...1] t[1]", "s[2...2] t[1]", "s[1...1] t[2]","s[2...2] t[2]", "s[1...2] t[1 2]".
instruction
0
53,338
0
106,676
Tags: dp Correct Solution: ``` from sys import stdin s=[ord(i)-97 for i in stdin.readline().strip()] s1=[ord(i)-97 for i in stdin.readline().strip()] n=len(s) m=len(s1) ans=0 mod=10**9+7 dp=[[0 for i in range(n)] for j in range(26)] for i in range(m): arr=[0 for j in range(n)] for j in range(n): if s1[i]==s[j] : arr[j]=1 if j>0 : arr[j]=(arr[j]+dp[s[j-1]][j-1])%mod for j in range(n): dp[s1[i]][j]=(arr[j] +dp[s1[i]][j]) %mod x=0 for i in dp: x=(x+sum(i))%mod print(x) ```
output
1
53,338
0
106,677
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Polycarpus got hold of two non-empty strings s and t, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "x y" are there, such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. Two pairs are considered different, if they contain different substrings of string s or different subsequences of string t. Read the whole statement to understand the definition of different substrings and subsequences. The length of string s is the number of characters in it. If we denote the length of the string s as |s|, we can write the string as s = s1s2... s|s|. A substring of s is a non-empty string x = s[a... b] = sasa + 1... sb (1 ≤ a ≤ b ≤ |s|). For example, "code" and "force" are substrings or "codeforces", while "coders" is not. Two substrings s[a... b] and s[c... d] are considered to be different if a ≠ c or b ≠ d. For example, if s="codeforces", s[2...2] and s[6...6] are different, though their content is the same. A subsequence of s is a non-empty string y = s[p1p2... p|y|] = sp1sp2... sp|y| (1 ≤ p1 < p2 < ... < p|y| ≤ |s|). For example, "coders" is a subsequence of "codeforces". Two subsequences u = s[p1p2... p|u|] and v = s[q1q2... q|v|] are considered different if the sequences p and q are different. Input The input consists of two lines. The first of them contains s (1 ≤ |s| ≤ 5000), and the second one contains t (1 ≤ |t| ≤ 5000). Both strings consist of lowercase Latin letters. Output Print a single number — the number of different pairs "x y" such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. As the answer can be rather large, print it modulo 1000000007 (109 + 7). Examples Input aa aa Output 5 Input codeforces forceofcode Output 60 Note Let's write down all pairs "x y" that form the answer in the first sample: "s[1...1] t[1]", "s[2...2] t[1]", "s[1...1] t[2]","s[2...2] t[2]", "s[1...2] t[1 2]". Submitted Solution: ``` s = " "+input().strip() t = " "+input().strip() print(s,t) ls = len(s) lt = len(t) mod = 1000000007 ans = 0 dp = [[ 0 for j in range(lt) ] for i in range(ls)] for i in range(1,ls): for j in range(1,lt): dp[i][j]=dp[i][j-1] if t[j]==s[i]: dp[i][j]+=(1+dp[i-1][j-1]) dp[i][j]%=mod ans += dp[i][-1] ans %= mod print((ans+mod)%mod) ```
instruction
0
53,339
0
106,678
No
output
1
53,339
0
106,679
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Polycarpus got hold of two non-empty strings s and t, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "x y" are there, such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. Two pairs are considered different, if they contain different substrings of string s or different subsequences of string t. Read the whole statement to understand the definition of different substrings and subsequences. The length of string s is the number of characters in it. If we denote the length of the string s as |s|, we can write the string as s = s1s2... s|s|. A substring of s is a non-empty string x = s[a... b] = sasa + 1... sb (1 ≤ a ≤ b ≤ |s|). For example, "code" and "force" are substrings or "codeforces", while "coders" is not. Two substrings s[a... b] and s[c... d] are considered to be different if a ≠ c or b ≠ d. For example, if s="codeforces", s[2...2] and s[6...6] are different, though their content is the same. A subsequence of s is a non-empty string y = s[p1p2... p|y|] = sp1sp2... sp|y| (1 ≤ p1 < p2 < ... < p|y| ≤ |s|). For example, "coders" is a subsequence of "codeforces". Two subsequences u = s[p1p2... p|u|] and v = s[q1q2... q|v|] are considered different if the sequences p and q are different. Input The input consists of two lines. The first of them contains s (1 ≤ |s| ≤ 5000), and the second one contains t (1 ≤ |t| ≤ 5000). Both strings consist of lowercase Latin letters. Output Print a single number — the number of different pairs "x y" such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. As the answer can be rather large, print it modulo 1000000007 (109 + 7). Examples Input aa aa Output 5 Input codeforces forceofcode Output 60 Note Let's write down all pairs "x y" that form the answer in the first sample: "s[1...1] t[1]", "s[2...2] t[1]", "s[1...1] t[2]","s[2...2] t[2]", "s[1...2] t[1 2]". Submitted Solution: ``` s=input().strip() t=input().strip() n,m=len(s),len(t) mod=10**9+7 dp12=[[0 for i in range(m)]for j in range(n) ] #print(dp) for i in range(n): if t[0]==s[i]: dp12[i][0]=1 for i in range(m): if s[0]==t[i] : dp12[0][i]=(dp12[0][i-1]+1)%mod else: dp12[0][i]=(dp12[0][i-1])%mod for i in range(1,n): for j in range(1,m): if s[i]==t[j]: dp12[i][j]=(max(1,dp12[i][j], (dp12[i-1][j-1]+dp12[i][j-1]+1)))%mod else: dp12[i][j]=(dp12[i][j-1])%mod an=0 for i in range(n): an=(an+dp12[i][-1])%mod print(an) ```
instruction
0
53,340
0
106,680
No
output
1
53,340
0
106,681
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Polycarpus got hold of two non-empty strings s and t, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "x y" are there, such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. Two pairs are considered different, if they contain different substrings of string s or different subsequences of string t. Read the whole statement to understand the definition of different substrings and subsequences. The length of string s is the number of characters in it. If we denote the length of the string s as |s|, we can write the string as s = s1s2... s|s|. A substring of s is a non-empty string x = s[a... b] = sasa + 1... sb (1 ≤ a ≤ b ≤ |s|). For example, "code" and "force" are substrings or "codeforces", while "coders" is not. Two substrings s[a... b] and s[c... d] are considered to be different if a ≠ c or b ≠ d. For example, if s="codeforces", s[2...2] and s[6...6] are different, though their content is the same. A subsequence of s is a non-empty string y = s[p1p2... p|y|] = sp1sp2... sp|y| (1 ≤ p1 < p2 < ... < p|y| ≤ |s|). For example, "coders" is a subsequence of "codeforces". Two subsequences u = s[p1p2... p|u|] and v = s[q1q2... q|v|] are considered different if the sequences p and q are different. Input The input consists of two lines. The first of them contains s (1 ≤ |s| ≤ 5000), and the second one contains t (1 ≤ |t| ≤ 5000). Both strings consist of lowercase Latin letters. Output Print a single number — the number of different pairs "x y" such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. As the answer can be rather large, print it modulo 1000000007 (109 + 7). Examples Input aa aa Output 5 Input codeforces forceofcode Output 60 Note Let's write down all pairs "x y" that form the answer in the first sample: "s[1...1] t[1]", "s[2...2] t[1]", "s[1...1] t[2]","s[2...2] t[2]", "s[1...2] t[1 2]". Submitted Solution: ``` s = " "+input().strip() t = " "+input().strip() ls = len(s) lt = len(t) if ls==1 or lt==1: print(0) else: mod = 1000000007 ans = 0 dp = [[ 0 for j in range(lt) ] for i in range(ls)] for i in range(1,ls): for j in range(1,lt): dp[i][j]=dp[i][j-1] if t[j]==s[i]: dp[i][j] = (dp[i][j] + dp[i-1][j-1])%mod for i in range(ls): ans = (ans + dp[i][-1])%mod print(ans) ```
instruction
0
53,341
0
106,682
No
output
1
53,341
0
106,683
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Polycarpus got hold of two non-empty strings s and t, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "x y" are there, such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. Two pairs are considered different, if they contain different substrings of string s or different subsequences of string t. Read the whole statement to understand the definition of different substrings and subsequences. The length of string s is the number of characters in it. If we denote the length of the string s as |s|, we can write the string as s = s1s2... s|s|. A substring of s is a non-empty string x = s[a... b] = sasa + 1... sb (1 ≤ a ≤ b ≤ |s|). For example, "code" and "force" are substrings or "codeforces", while "coders" is not. Two substrings s[a... b] and s[c... d] are considered to be different if a ≠ c or b ≠ d. For example, if s="codeforces", s[2...2] and s[6...6] are different, though their content is the same. A subsequence of s is a non-empty string y = s[p1p2... p|y|] = sp1sp2... sp|y| (1 ≤ p1 < p2 < ... < p|y| ≤ |s|). For example, "coders" is a subsequence of "codeforces". Two subsequences u = s[p1p2... p|u|] and v = s[q1q2... q|v|] are considered different if the sequences p and q are different. Input The input consists of two lines. The first of them contains s (1 ≤ |s| ≤ 5000), and the second one contains t (1 ≤ |t| ≤ 5000). Both strings consist of lowercase Latin letters. Output Print a single number — the number of different pairs "x y" such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. As the answer can be rather large, print it modulo 1000000007 (109 + 7). Examples Input aa aa Output 5 Input codeforces forceofcode Output 60 Note Let's write down all pairs "x y" that form the answer in the first sample: "s[1...1] t[1]", "s[2...2] t[1]", "s[1...1] t[2]","s[2...2] t[2]", "s[1...2] t[1 2]". Submitted Solution: ``` s,t,dp=input(),input(),[] for i in range(5001): dp.append([]) for j in range(5001): dp[i].append(0) for i in range(len(s)): for j in range(len(t)): if s[i]==t[j]: dp[i+1][j+1]=(dp[i][j]+1+dp[i+1][j])%1000000007 else: dp[i+1][j+1]=dp[i+1][j]%1000000007 ans=0 for i in range(len(s)): ans+=dp[i+1][len(t)]%1000000007 print(ans) ```
instruction
0
53,342
0
106,684
No
output
1
53,342
0
106,685
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s of length n, consisting of first k lowercase English letters. We define a c-repeat of some string q as a string, consisting of c copies of the string q. For example, string "acbacbacbacb" is a 4-repeat of the string "acb". Let's say that string a contains string b as a subsequence, if string b can be obtained from a by erasing some symbols. Let p be a string that represents some permutation of the first k lowercase English letters. We define function d(p) as the smallest integer such that a d(p)-repeat of the string p contains string s as a subsequence. There are m operations of one of two types that can be applied to string s: 1. Replace all characters at positions from li to ri by a character ci. 2. For the given p, that is a permutation of first k lowercase English letters, find the value of function d(p). All operations are performed sequentially, in the order they appear in the input. Your task is to determine the values of function d(p) for all operations of the second type. Input The first line contains three positive integers n, m and k (1 ≤ n ≤ 200 000, 1 ≤ m ≤ 20000, 1 ≤ k ≤ 10) — the length of the string s, the number of operations and the size of the alphabet respectively. The second line contains the string s itself. Each of the following lines m contains a description of some operation: 1. Operation of the first type starts with 1 followed by a triple li, ri and ci, that denotes replacement of all characters at positions from li to ri by character ci (1 ≤ li ≤ ri ≤ n, ci is one of the first k lowercase English letters). 2. Operation of the second type starts with 2 followed by a permutation of the first k lowercase English letters. Output For each query of the second type the value of function d(p). Examples Input 7 4 3 abacaba 1 3 5 b 2 abc 1 4 4 c 2 cba Output 6 5 Note After the first operation the string s will be abbbbba. In the second operation the answer is 6-repeat of abc: ABcaBcaBcaBcaBcAbc. After the third operation the string s will be abbcbba. In the fourth operation the answer is 5-repeat of cba: cbAcBacBaCBacBA. Uppercase letters means the occurrences of symbols from the string s. Submitted Solution: ``` def replace(string, src , dest, char): for i in range(src-1,dest): string[i]=char return string def timesRep(string, newstr): check = [] for i in string: check.append(i) cnt = 0 while check.count('*')!=len(check): cnt += 1 for k in newstr: if k in check: ind = check.index(k) check[ind]='*' return cnt+1 if __name__=='__main__': n,m,k = map(int,input().split()) string = list(input()) for _ in range(m): Q=list(map(str,input().split())) if Q[0]=='1': src = int(Q[1]) dest = int(Q[2]) char = Q[3] string = replace(string, src , dest, char) else: newstr = Q[1] #newstr = Q[1] print(timesRep(string, newstr)) ```
instruction
0
53,493
0
106,986
No
output
1
53,493
0
106,987
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s of length n, consisting of first k lowercase English letters. We define a c-repeat of some string q as a string, consisting of c copies of the string q. For example, string "acbacbacbacb" is a 4-repeat of the string "acb". Let's say that string a contains string b as a subsequence, if string b can be obtained from a by erasing some symbols. Let p be a string that represents some permutation of the first k lowercase English letters. We define function d(p) as the smallest integer such that a d(p)-repeat of the string p contains string s as a subsequence. There are m operations of one of two types that can be applied to string s: 1. Replace all characters at positions from li to ri by a character ci. 2. For the given p, that is a permutation of first k lowercase English letters, find the value of function d(p). All operations are performed sequentially, in the order they appear in the input. Your task is to determine the values of function d(p) for all operations of the second type. Input The first line contains three positive integers n, m and k (1 ≤ n ≤ 200 000, 1 ≤ m ≤ 20000, 1 ≤ k ≤ 10) — the length of the string s, the number of operations and the size of the alphabet respectively. The second line contains the string s itself. Each of the following lines m contains a description of some operation: 1. Operation of the first type starts with 1 followed by a triple li, ri and ci, that denotes replacement of all characters at positions from li to ri by character ci (1 ≤ li ≤ ri ≤ n, ci is one of the first k lowercase English letters). 2. Operation of the second type starts with 2 followed by a permutation of the first k lowercase English letters. Output For each query of the second type the value of function d(p). Examples Input 7 4 3 abacaba 1 3 5 b 2 abc 1 4 4 c 2 cba Output 6 5 Note After the first operation the string s will be abbbbba. In the second operation the answer is 6-repeat of abc: ABcaBcaBcaBcaBcAbc. After the third operation the string s will be abbcbba. In the fourth operation the answer is 5-repeat of cba: cbAcBacBaCBacBA. Uppercase letters means the occurrences of symbols from the string s. Submitted Solution: ``` if __name__=='__main__': n,q,k = map(int,input().split()) string = list(input()) for _ in range(q): lst = list(map(str,input().split())) if lst[0]=='1': src = int(lst[1]) dest = int(lst[2]) str1 = lst[3] for i in range(src-1,dest): string[i]=str1 st = '' for i in string: st += i #print("string",st) else: str1 = lst[1] mystring = [] for j in string: mystring.append(j) cnt = 0 while mystring.count('*')!=len(mystring): #print("in") cnt += 1 for k in str1: if k in mystring: pos = mystring.index(k) mystring[pos]='*' print(cnt+1) ```
instruction
0
53,494
0
106,988
No
output
1
53,494
0
106,989
Provide tags and a correct Python 3 solution for this coding contest problem. After returned from forest, Alyona started reading a book. She noticed strings s and t, lengths of which are n and m respectively. As usual, reading bored Alyona and she decided to pay her attention to strings s and t, which she considered very similar. Alyona has her favourite positive integer k and because she is too small, k does not exceed 10. The girl wants now to choose k disjoint non-empty substrings of string s such that these strings appear as disjoint substrings of string t and in the same order as they do in string s. She is also interested in that their length is maximum possible among all variants. Formally, Alyona wants to find a sequence of k non-empty strings p1, p2, p3, ..., pk satisfying following conditions: * s can be represented as concatenation a1p1a2p2... akpkak + 1, where a1, a2, ..., ak + 1 is a sequence of arbitrary strings (some of them may be possibly empty); * t can be represented as concatenation b1p1b2p2... bkpkbk + 1, where b1, b2, ..., bk + 1 is a sequence of arbitrary strings (some of them may be possibly empty); * sum of the lengths of strings in sequence is maximum possible. Please help Alyona solve this complicated problem and find at least the sum of the lengths of the strings in a desired sequence. A substring of a string is a subsequence of consecutive characters of the string. Input In the first line of the input three integers n, m, k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 10) are given — the length of the string s, the length of the string t and Alyona's favourite number respectively. The second line of the input contains string s, consisting of lowercase English letters. The third line of the input contains string t, consisting of lowercase English letters. Output In the only line print the only non-negative integer — the sum of the lengths of the strings in a desired sequence. It is guaranteed, that at least one desired sequence exists. Examples Input 3 2 2 abc ab Output 2 Input 9 12 4 bbaaababb abbbabbaaaba Output 7 Note The following image describes the answer for the second sample case: <image>
instruction
0
53,514
0
107,028
Tags: dp, strings Correct Solution: ``` n, m, k = map(int, input().split()) s, t = input(), input() n += 1 m += 1 p = [i for i in range(n * m - n) if (i + 1) % n] r = p[::-1] d = [0] * n * m for i in p: if s[i % n] == t[i // n]: d[i] = d[i - n - 1] + 1 f = d[:] for y in range(k - 1): for i in p: f[i] = max(f[i], f[i - 1], f[i - n]) for i in r: f[i] = f[i - d[i] * (n + 1)] + d[i] print(max(f)) ```
output
1
53,514
0
107,029
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After returned from forest, Alyona started reading a book. She noticed strings s and t, lengths of which are n and m respectively. As usual, reading bored Alyona and she decided to pay her attention to strings s and t, which she considered very similar. Alyona has her favourite positive integer k and because she is too small, k does not exceed 10. The girl wants now to choose k disjoint non-empty substrings of string s such that these strings appear as disjoint substrings of string t and in the same order as they do in string s. She is also interested in that their length is maximum possible among all variants. Formally, Alyona wants to find a sequence of k non-empty strings p1, p2, p3, ..., pk satisfying following conditions: * s can be represented as concatenation a1p1a2p2... akpkak + 1, where a1, a2, ..., ak + 1 is a sequence of arbitrary strings (some of them may be possibly empty); * t can be represented as concatenation b1p1b2p2... bkpkbk + 1, where b1, b2, ..., bk + 1 is a sequence of arbitrary strings (some of them may be possibly empty); * sum of the lengths of strings in sequence is maximum possible. Please help Alyona solve this complicated problem and find at least the sum of the lengths of the strings in a desired sequence. A substring of a string is a subsequence of consecutive characters of the string. Input In the first line of the input three integers n, m, k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 10) are given — the length of the string s, the length of the string t and Alyona's favourite number respectively. The second line of the input contains string s, consisting of lowercase English letters. The third line of the input contains string t, consisting of lowercase English letters. Output In the only line print the only non-negative integer — the sum of the lengths of the strings in a desired sequence. It is guaranteed, that at least one desired sequence exists. Examples Input 3 2 2 abc ab Output 2 Input 9 12 4 bbaaababb abbbabbaaaba Output 7 Note The following image describes the answer for the second sample case: <image> Submitted Solution: ``` from functools import lru_cache m,n,K = list(map(int, input().split())) s1 = input() s2 = input() #9 12 4 #bbaaababb #abbbabbaaaba #13 9 1 #oaflomxegekyv #bgwwqizfo @lru_cache(None) def go(idx1, idx2, k, cont): if idx1 == m or idx2 == n: if k == 0: return 0 else: return -float('inf') r1 = r2 = r3 = 0 if cont == 1: r1 = go(idx1 + 1, idx2, k, 0) r2 = go(idx1, idx2 + 1, k, 0) if s1[idx1] == s2[idx2]: r3 = 1 + go(idx1 + 1, idx2 + 1, k, 1) else: r1 = go(idx1 + 1, idx2, k, 0) r2 = go(idx1, idx2 + 1, k, 0) if s1[idx1] == s2[idx2]: r3 = 1 + go(idx1 + 1, idx2 + 1, k - 1, 1) return max(r1, r2, r3) ans = go(0, 0, K, 0) print(ans) ```
instruction
0
53,515
0
107,030
No
output
1
53,515
0
107,031
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After returned from forest, Alyona started reading a book. She noticed strings s and t, lengths of which are n and m respectively. As usual, reading bored Alyona and she decided to pay her attention to strings s and t, which she considered very similar. Alyona has her favourite positive integer k and because she is too small, k does not exceed 10. The girl wants now to choose k disjoint non-empty substrings of string s such that these strings appear as disjoint substrings of string t and in the same order as they do in string s. She is also interested in that their length is maximum possible among all variants. Formally, Alyona wants to find a sequence of k non-empty strings p1, p2, p3, ..., pk satisfying following conditions: * s can be represented as concatenation a1p1a2p2... akpkak + 1, where a1, a2, ..., ak + 1 is a sequence of arbitrary strings (some of them may be possibly empty); * t can be represented as concatenation b1p1b2p2... bkpkbk + 1, where b1, b2, ..., bk + 1 is a sequence of arbitrary strings (some of them may be possibly empty); * sum of the lengths of strings in sequence is maximum possible. Please help Alyona solve this complicated problem and find at least the sum of the lengths of the strings in a desired sequence. A substring of a string is a subsequence of consecutive characters of the string. Input In the first line of the input three integers n, m, k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 10) are given — the length of the string s, the length of the string t and Alyona's favourite number respectively. The second line of the input contains string s, consisting of lowercase English letters. The third line of the input contains string t, consisting of lowercase English letters. Output In the only line print the only non-negative integer — the sum of the lengths of the strings in a desired sequence. It is guaranteed, that at least one desired sequence exists. Examples Input 3 2 2 abc ab Output 2 Input 9 12 4 bbaaababb abbbabbaaaba Output 7 Note The following image describes the answer for the second sample case: <image> Submitted Solution: ``` from functools import lru_cache m,n,K = list(map(int, input().split())) s1 = input() s2 = input() #9 12 4 #bbaaababb #abbbabbaaaba #13 9 1 #oaflomxegekyv #bgwwqizfo @lru_cache(None) def go(idx1, idx2, k, cont): if idx1 == m or idx2 == n: if k == 0: return 0 else: return -float('inf') if k < 0: return -float('inf') r1 = r2 = r3 = 0 if cont == 1: r1 = go(idx1 + 1, idx2, k, False) r2 = go(idx1, idx2 + 1, k, False) if s1[idx1] == s2[idx2]: r3 = 1 + go(idx1 + 1, idx2 + 1, k, True) else: r1 = go(idx1 + 1, idx2, k, False) r2 = go(idx1, idx2 + 1, k, False) if s1[idx1] == s2[idx2]: r3 = 1 + go(idx1 + 1, idx2 + 1, k - 1, True) return max(r1, r2, r3) ans = go(0, 0, K, False) print(ans) ```
instruction
0
53,516
0
107,032
No
output
1
53,516
0
107,033
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After returned from forest, Alyona started reading a book. She noticed strings s and t, lengths of which are n and m respectively. As usual, reading bored Alyona and she decided to pay her attention to strings s and t, which she considered very similar. Alyona has her favourite positive integer k and because she is too small, k does not exceed 10. The girl wants now to choose k disjoint non-empty substrings of string s such that these strings appear as disjoint substrings of string t and in the same order as they do in string s. She is also interested in that their length is maximum possible among all variants. Formally, Alyona wants to find a sequence of k non-empty strings p1, p2, p3, ..., pk satisfying following conditions: * s can be represented as concatenation a1p1a2p2... akpkak + 1, where a1, a2, ..., ak + 1 is a sequence of arbitrary strings (some of them may be possibly empty); * t can be represented as concatenation b1p1b2p2... bkpkbk + 1, where b1, b2, ..., bk + 1 is a sequence of arbitrary strings (some of them may be possibly empty); * sum of the lengths of strings in sequence is maximum possible. Please help Alyona solve this complicated problem and find at least the sum of the lengths of the strings in a desired sequence. A substring of a string is a subsequence of consecutive characters of the string. Input In the first line of the input three integers n, m, k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 10) are given — the length of the string s, the length of the string t and Alyona's favourite number respectively. The second line of the input contains string s, consisting of lowercase English letters. The third line of the input contains string t, consisting of lowercase English letters. Output In the only line print the only non-negative integer — the sum of the lengths of the strings in a desired sequence. It is guaranteed, that at least one desired sequence exists. Examples Input 3 2 2 abc ab Output 2 Input 9 12 4 bbaaababb abbbabbaaaba Output 7 Note The following image describes the answer for the second sample case: <image> Submitted Solution: ``` from functools import lru_cache m,n,K = list(map(int, input().split())) s1 = input() s2 = input() #9 12 4 #bbaaababb #abbbabbaaaba #13 9 1 #oaflomxegekyv #bgwwqizfo @lru_cache(None) def go(idx1, idx2, k, cont): if idx1 == m or idx2 == n: if cont == 1: k -= 1 if k == 0: return 0 else: return -float('inf') r1 = r2 = r3 = 0 if cont == 1: r1 = go(idx1 + 1, idx2, k, 0) r2 = go(idx1, idx2 + 1, k, 0) if s1[idx1] == s2[idx2]: r3 = 1 + go(idx1 + 1, idx2 + 1, k, 1) else: r1 = go(idx1 + 1, idx2, k, 0) r2 = go(idx1, idx2 + 1, k, 0) if s1[idx1] == s2[idx2]: r3 = 1 + go(idx1 + 1, idx2 + 1, k - 1, 1) return max(r1, r2, r3) ans = go(0, 0, K, 0) print(ans) ```
instruction
0
53,517
0
107,034
No
output
1
53,517
0
107,035
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After returned from forest, Alyona started reading a book. She noticed strings s and t, lengths of which are n and m respectively. As usual, reading bored Alyona and she decided to pay her attention to strings s and t, which she considered very similar. Alyona has her favourite positive integer k and because she is too small, k does not exceed 10. The girl wants now to choose k disjoint non-empty substrings of string s such that these strings appear as disjoint substrings of string t and in the same order as they do in string s. She is also interested in that their length is maximum possible among all variants. Formally, Alyona wants to find a sequence of k non-empty strings p1, p2, p3, ..., pk satisfying following conditions: * s can be represented as concatenation a1p1a2p2... akpkak + 1, where a1, a2, ..., ak + 1 is a sequence of arbitrary strings (some of them may be possibly empty); * t can be represented as concatenation b1p1b2p2... bkpkbk + 1, where b1, b2, ..., bk + 1 is a sequence of arbitrary strings (some of them may be possibly empty); * sum of the lengths of strings in sequence is maximum possible. Please help Alyona solve this complicated problem and find at least the sum of the lengths of the strings in a desired sequence. A substring of a string is a subsequence of consecutive characters of the string. Input In the first line of the input three integers n, m, k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 10) are given — the length of the string s, the length of the string t and Alyona's favourite number respectively. The second line of the input contains string s, consisting of lowercase English letters. The third line of the input contains string t, consisting of lowercase English letters. Output In the only line print the only non-negative integer — the sum of the lengths of the strings in a desired sequence. It is guaranteed, that at least one desired sequence exists. Examples Input 3 2 2 abc ab Output 2 Input 9 12 4 bbaaababb abbbabbaaaba Output 7 Note The following image describes the answer for the second sample case: <image> Submitted Solution: ``` from functools import lru_cache m,n,K = list(map(int, input().split())) s1 = input() s2 = input() #9 12 4 #bbaaababb #abbbabbaaaba #13 9 1 #oaflomxegekyv #bgwwqizfo @lru_cache(None) def go(idx1, idx2, k, cont): if idx1 == m or idx2 == n: if k == 0: return 0 else: return -float('inf') r1 = r2 = r3 = 0 if cont == 1: r1 = go(idx1 + 1, idx2, k, 0) r2 = go(idx1, idx2 + 1, k, 0) if s1[idx1] == s2[idx2]: r3 = go(idx1 + 1, idx2 + 1, k, 1) else: r1 = go(idx1 + 1, idx2, k, 0) r2 = go(idx1, idx2 + 1, k, 0) if s1[idx1] == s2[idx2]: r3 = go(idx1 + 1, idx2 + 1, k - 1, 1) return max(r1, r2, r3) ans = go(0, 0, K, 0) print(ans) ```
instruction
0
53,518
0
107,036
No
output
1
53,518
0
107,037
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya had three strings a, b and s, which consist of lowercase English letters. The lengths of strings a and b are equal to n, the length of the string s is equal to m. Vasya decided to choose a substring of the string a, then choose a substring of the string b and concatenate them. Formally, he chooses a segment [l_1, r_1] (1 ≤ l_1 ≤ r_1 ≤ n) and a segment [l_2, r_2] (1 ≤ l_2 ≤ r_2 ≤ n), and after concatenation he obtains a string a[l_1, r_1] + b[l_2, r_2] = a_{l_1} a_{l_1 + 1} … a_{r_1} b_{l_2} b_{l_2 + 1} … b_{r_2}. Now, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions: * segments [l_1, r_1] and [l_2, r_2] have non-empty intersection, i.e. there exists at least one integer x, such that l_1 ≤ x ≤ r_1 and l_2 ≤ x ≤ r_2; * the string a[l_1, r_1] + b[l_2, r_2] is equal to the string s. Input The first line contains integers n and m (1 ≤ n ≤ 500 000, 2 ≤ m ≤ 2 ⋅ n) — the length of strings a and b and the length of the string s. The next three lines contain strings a, b and s, respectively. The length of the strings a and b is n, while the length of the string s is m. All strings consist of lowercase English letters. Output Print one integer — the number of ways to choose a pair of segments, which satisfy Vasya's conditions. Examples Input 6 5 aabbaa baaaab aaaaa Output 4 Input 5 4 azaza zazaz azaz Output 11 Input 9 12 abcabcabc xyzxyzxyz abcabcayzxyz Output 2 Note Let's list all the pairs of segments that Vasya could choose in the first example: 1. [2, 2] and [2, 5]; 2. [1, 2] and [2, 4]; 3. [5, 5] and [2, 5]; 4. [5, 6] and [3, 5];
instruction
0
54,910
0
109,820
Tags: data structures, hashing, strings, two pointers Correct Solution: ``` import sys, logging logging.basicConfig(level=logging.INFO) logging.disable(logging.INFO) def build(S, n): Z = [0 for i in range(3 * n + 3)] #logging.info(S) n = len(S) L = 0 R = 0 Z[0] = n for i in range(1, n): if(i > R): L = R = i while(R < n and S[R] == S[R - L]): R += 1 Z[i] = R - L R -= 1 else: k = i - L if(Z[k] < R - i + 1): Z[i] = Z[k] else: L = i while(R < n and S[R] == S[R - L]): R += 1 Z[i] = R - L R -= 1 return Z def update1(n, x, val): while(x <= n + 1): bit1[x] += val x += x & -x def get1(n, x): ans = 0 while(x > 0): ans += bit1[x] x -= x & -x return ans def update2(n, x, val): while(x <= n + 1): bit2[x] += val x += x & -x def get2(n, x): ans = 0 while(x > 0): ans += bit2[x] x -= x & -x return ans def process(n, m, fa, fb): r2 = int(1) ans = 0 for l1 in range(1, n + 1): while(r2 <= min(n, l1 + m - 2)): update1(n, m - fb[r2] + 1, 1) update2(n, m - fb[r2] + 1, fb[r2] - m + 1) r2 += 1 ans += get1(n, fa[l1] + 1) * fa[l1] + get2(n, fa[l1] + 1) update1(n, m - fb[l1] + 1, -1) update2(n, m - fb[l1] + 1, m - 1 - fb[l1]) print(ans) def main(): n, m = map(int, sys.stdin.readline().split()) a = sys.stdin.readline() b = sys.stdin.readline() s = sys.stdin.readline() a = a[:(len(a) - 1)] b = b[:(len(b) - 1)] s = s[:(len(s) - 1)] fa = build(s + a, n) kb = build(s[::-1] + b[::-1], n) fb = [0 for k in range(n + 2)] for i in range(m, m + n): fa[i - m + 1] = fa[i] if(fa[i - m + 1] >= m): fa[i - m + 1] = m - 1 fb[m + n - i] = kb[i] if(fb[m + n - i] >= m): fb[m + n - i] = m - 1 logging.info(fa[1:(n + 1)]) logging.info(fb[1:(n + 1)]) process(n, m, fa, fb) bit1 = [0 for i in range(500004)] bit2 = [0 for i in range(500004)] if __name__ == "__main__": try: sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') except: pass main() ```
output
1
54,910
0
109,821
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya had three strings a, b and s, which consist of lowercase English letters. The lengths of strings a and b are equal to n, the length of the string s is equal to m. Vasya decided to choose a substring of the string a, then choose a substring of the string b and concatenate them. Formally, he chooses a segment [l_1, r_1] (1 ≤ l_1 ≤ r_1 ≤ n) and a segment [l_2, r_2] (1 ≤ l_2 ≤ r_2 ≤ n), and after concatenation he obtains a string a[l_1, r_1] + b[l_2, r_2] = a_{l_1} a_{l_1 + 1} … a_{r_1} b_{l_2} b_{l_2 + 1} … b_{r_2}. Now, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions: * segments [l_1, r_1] and [l_2, r_2] have non-empty intersection, i.e. there exists at least one integer x, such that l_1 ≤ x ≤ r_1 and l_2 ≤ x ≤ r_2; * the string a[l_1, r_1] + b[l_2, r_2] is equal to the string s. Input The first line contains integers n and m (1 ≤ n ≤ 500 000, 2 ≤ m ≤ 2 ⋅ n) — the length of strings a and b and the length of the string s. The next three lines contain strings a, b and s, respectively. The length of the strings a and b is n, while the length of the string s is m. All strings consist of lowercase English letters. Output Print one integer — the number of ways to choose a pair of segments, which satisfy Vasya's conditions. Examples Input 6 5 aabbaa baaaab aaaaa Output 4 Input 5 4 azaza zazaz azaz Output 11 Input 9 12 abcabcabc xyzxyzxyz abcabcayzxyz Output 2 Note Let's list all the pairs of segments that Vasya could choose in the first example: 1. [2, 2] and [2, 5]; 2. [1, 2] and [2, 4]; 3. [5, 5] and [2, 5]; 4. [5, 6] and [3, 5]; Submitted Solution: ``` li=input().split(' ') n=int(li[0]) m=int(li[1]) a=input() b=input() s=input() count=0 #a[2:2]=' ' for i in range(0,n+1): for j in range(i+1,n+1): for k in range(0,j): for l in range(k+1,n+1): if(i<l and j-i+l-k==m): if(a[i:j]+b[k:l]==s): #print(i+1,j,k+1,l) #print(a[i:j],b[k:l]) count+=1 else: break print(count) ```
instruction
0
54,911
0
109,822
No
output
1
54,911
0
109,823
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya had three strings a, b and s, which consist of lowercase English letters. The lengths of strings a and b are equal to n, the length of the string s is equal to m. Vasya decided to choose a substring of the string a, then choose a substring of the string b and concatenate them. Formally, he chooses a segment [l_1, r_1] (1 ≤ l_1 ≤ r_1 ≤ n) and a segment [l_2, r_2] (1 ≤ l_2 ≤ r_2 ≤ n), and after concatenation he obtains a string a[l_1, r_1] + b[l_2, r_2] = a_{l_1} a_{l_1 + 1} … a_{r_1} b_{l_2} b_{l_2 + 1} … b_{r_2}. Now, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions: * segments [l_1, r_1] and [l_2, r_2] have non-empty intersection, i.e. there exists at least one integer x, such that l_1 ≤ x ≤ r_1 and l_2 ≤ x ≤ r_2; * the string a[l_1, r_1] + b[l_2, r_2] is equal to the string s. Input The first line contains integers n and m (1 ≤ n ≤ 500 000, 2 ≤ m ≤ 2 ⋅ n) — the length of strings a and b and the length of the string s. The next three lines contain strings a, b and s, respectively. The length of the strings a and b is n, while the length of the string s is m. All strings consist of lowercase English letters. Output Print one integer — the number of ways to choose a pair of segments, which satisfy Vasya's conditions. Examples Input 6 5 aabbaa baaaab aaaaa Output 4 Input 5 4 azaza zazaz azaz Output 11 Input 9 12 abcabcabc xyzxyzxyz abcabcayzxyz Output 2 Note Let's list all the pairs of segments that Vasya could choose in the first example: 1. [2, 2] and [2, 5]; 2. [1, 2] and [2, 4]; 3. [5, 5] and [2, 5]; 4. [5, 6] and [3, 5]; Submitted Solution: ``` li=input().split(' ') n=int(li[0]) m=int(li[1]) a=input() b=input() s=input() count=0 for i in range(0,n): for j in range(i,n): for k in range(0,j): for l in range(k,n): if(a[i:j]+b[k:l]==s): count+=1 print(count) ```
instruction
0
54,912
0
109,824
No
output
1
54,912
0
109,825
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya had three strings a, b and s, which consist of lowercase English letters. The lengths of strings a and b are equal to n, the length of the string s is equal to m. Vasya decided to choose a substring of the string a, then choose a substring of the string b and concatenate them. Formally, he chooses a segment [l_1, r_1] (1 ≤ l_1 ≤ r_1 ≤ n) and a segment [l_2, r_2] (1 ≤ l_2 ≤ r_2 ≤ n), and after concatenation he obtains a string a[l_1, r_1] + b[l_2, r_2] = a_{l_1} a_{l_1 + 1} … a_{r_1} b_{l_2} b_{l_2 + 1} … b_{r_2}. Now, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions: * segments [l_1, r_1] and [l_2, r_2] have non-empty intersection, i.e. there exists at least one integer x, such that l_1 ≤ x ≤ r_1 and l_2 ≤ x ≤ r_2; * the string a[l_1, r_1] + b[l_2, r_2] is equal to the string s. Input The first line contains integers n and m (1 ≤ n ≤ 500 000, 2 ≤ m ≤ 2 ⋅ n) — the length of strings a and b and the length of the string s. The next three lines contain strings a, b and s, respectively. The length of the strings a and b is n, while the length of the string s is m. All strings consist of lowercase English letters. Output Print one integer — the number of ways to choose a pair of segments, which satisfy Vasya's conditions. Examples Input 6 5 aabbaa baaaab aaaaa Output 4 Input 5 4 azaza zazaz azaz Output 11 Input 9 12 abcabcabc xyzxyzxyz abcabcayzxyz Output 2 Note Let's list all the pairs of segments that Vasya could choose in the first example: 1. [2, 2] and [2, 5]; 2. [1, 2] and [2, 4]; 3. [5, 5] and [2, 5]; 4. [5, 6] and [3, 5]; Submitted Solution: ``` li=input().split(' ') n=int(li[0]) m=int(li[1]) a=input() b=input() s=input() count=0 for i in range(0,n): for j in range(i,n): for k in range(j+1): for l in range(j+1,n): if(a[i:j]+b[k:l]==s): count+=1 print(count) ```
instruction
0
54,913
0
109,826
No
output
1
54,913
0
109,827
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya had three strings a, b and s, which consist of lowercase English letters. The lengths of strings a and b are equal to n, the length of the string s is equal to m. Vasya decided to choose a substring of the string a, then choose a substring of the string b and concatenate them. Formally, he chooses a segment [l_1, r_1] (1 ≤ l_1 ≤ r_1 ≤ n) and a segment [l_2, r_2] (1 ≤ l_2 ≤ r_2 ≤ n), and after concatenation he obtains a string a[l_1, r_1] + b[l_2, r_2] = a_{l_1} a_{l_1 + 1} … a_{r_1} b_{l_2} b_{l_2 + 1} … b_{r_2}. Now, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions: * segments [l_1, r_1] and [l_2, r_2] have non-empty intersection, i.e. there exists at least one integer x, such that l_1 ≤ x ≤ r_1 and l_2 ≤ x ≤ r_2; * the string a[l_1, r_1] + b[l_2, r_2] is equal to the string s. Input The first line contains integers n and m (1 ≤ n ≤ 500 000, 2 ≤ m ≤ 2 ⋅ n) — the length of strings a and b and the length of the string s. The next three lines contain strings a, b and s, respectively. The length of the strings a and b is n, while the length of the string s is m. All strings consist of lowercase English letters. Output Print one integer — the number of ways to choose a pair of segments, which satisfy Vasya's conditions. Examples Input 6 5 aabbaa baaaab aaaaa Output 4 Input 5 4 azaza zazaz azaz Output 11 Input 9 12 abcabcabc xyzxyzxyz abcabcayzxyz Output 2 Note Let's list all the pairs of segments that Vasya could choose in the first example: 1. [2, 2] and [2, 5]; 2. [1, 2] and [2, 4]; 3. [5, 5] and [2, 5]; 4. [5, 6] and [3, 5]; Submitted Solution: ``` li=input().split(' ') n=int(li[0]) m=int(li[1]) a=input() b=input() s=input() count=0 #a[2:2]=' ' #if a no. from say i to j is not similar to string s it should break as i to j+1 can never be == for i in range(0,n+1): if(a[i]!=s[0]): break else: for j in range(0,n+1): for k in range(0,n+1): for l in range(0,n+1): if(i<j and k<l and k<j and i<l): if(a[i:j]+b[k:l]==s): #print(i+1,j,k+1,l) #print(a[i:j],b[k:l]) count+=1 print(count) ```
instruction
0
54,914
0
109,828
No
output
1
54,914
0
109,829
Provide tags and a correct Python 3 solution for this coding contest problem. Kaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future. <image> Kaavi has a string T of length m and all the strings with the prefix T are magic spells. Kaavi also has a string S of length n and an empty string A. During the divination, Kaavi needs to perform a sequence of operations. There are two different operations: * Delete the first character of S and add it at the front of A. * Delete the first character of S and add it at the back of A. Kaavi can perform no more than n operations. To finish the divination, she wants to know the number of different operation sequences to make A a magic spell (i.e. with the prefix T). As her assistant, can you help her? The answer might be huge, so Kaavi only needs to know the answer modulo 998 244 353. Two operation sequences are considered different if they are different in length or there exists an i that their i-th operation is different. A substring is a contiguous sequence of characters within a string. A prefix of a string S is a substring of S that occurs at the beginning of S. Input The first line contains a string S of length n (1 ≤ n ≤ 3000). The second line contains a string T of length m (1 ≤ m ≤ n). Both strings contain only lowercase Latin letters. Output The output contains only one integer — the answer modulo 998 244 353. Examples Input abab ba Output 12 Input defineintlonglong signedmain Output 0 Input rotator rotator Output 4 Input cacdcdbbbb bdcaccdbbb Output 24 Note The first test: <image> The red ones are the magic spells. In the first operation, Kaavi can either add the first character "a" at the front or the back of A, although the results are the same, they are considered as different operations. So the answer is 6×2=12.
instruction
0
54,915
0
109,830
Tags: dp, strings Correct Solution: ``` import sys from array import array # noqa: F401 from typing import List, Tuple, TypeVar, Generic, Sequence, Union # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') def solve(): s, t = input().rstrip(), '*' + input().rstrip() n, m = len(s), len(t) mod = 998244353 dp = [array('i', [0]) * (n + 2) for _ in range(n + 2)] for i in range(1, n + 2): dp[i][i - 1] = 1 for slen, c in enumerate(s): for i, j in zip(range(n + 2), range(slen, n + 2)): if 0 < i < m and t[i] == c or m <= i <= n: dp[i][j] += dp[i + 1][j] if dp[i][j] >= mod: dp[i][j] -= mod if 0 < j < m and t[j] == c or m <= j <= n: dp[i][j] += dp[i][j - 1] if dp[i][j] >= mod: dp[i][j] -= mod print(sum(dp[1][m - 1:]) % mod) if __name__ == '__main__': solve() ```
output
1
54,915
0
109,831
Provide tags and a correct Python 3 solution for this coding contest problem. Kaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future. <image> Kaavi has a string T of length m and all the strings with the prefix T are magic spells. Kaavi also has a string S of length n and an empty string A. During the divination, Kaavi needs to perform a sequence of operations. There are two different operations: * Delete the first character of S and add it at the front of A. * Delete the first character of S and add it at the back of A. Kaavi can perform no more than n operations. To finish the divination, she wants to know the number of different operation sequences to make A a magic spell (i.e. with the prefix T). As her assistant, can you help her? The answer might be huge, so Kaavi only needs to know the answer modulo 998 244 353. Two operation sequences are considered different if they are different in length or there exists an i that their i-th operation is different. A substring is a contiguous sequence of characters within a string. A prefix of a string S is a substring of S that occurs at the beginning of S. Input The first line contains a string S of length n (1 ≤ n ≤ 3000). The second line contains a string T of length m (1 ≤ m ≤ n). Both strings contain only lowercase Latin letters. Output The output contains only one integer — the answer modulo 998 244 353. Examples Input abab ba Output 12 Input defineintlonglong signedmain Output 0 Input rotator rotator Output 4 Input cacdcdbbbb bdcaccdbbb Output 24 Note The first test: <image> The red ones are the magic spells. In the first operation, Kaavi can either add the first character "a" at the front or the back of A, although the results are the same, they are considered as different operations. So the answer is 6×2=12.
instruction
0
54,916
0
109,832
Tags: dp, strings Correct Solution: ``` # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- from math import gcd, ceil def prod(a, mod=10**9+7): ans = 1 for each in a: ans = (ans * each) % mod return ans def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y for _ in range(int(input()) if not True else 1): s = input() t = input() mod = 998244353 n, m = len(s), len(t) lim = 3001 dp = [[0]*lim for i in range(lim)] for i in range(m-1, n): if i > m or s[i] == t[-1]: dp[i+1][0] = 1 if s[i] == t[0]: dp[i+1][1] = 1 # dp[i][j] -> # use left move exactly j times till i -> going reverse #print(dp) for i in range(n-1, 0, -1): for j in range(n-i+1): if j >= m or s[i-1] == t[j]: # if left move has been used j times # use left move again # then s[i] will be j+1'th character dp[i][j+1] += dp[i+1][j] dp[i][j+1] %= mod # right move # j letters have been used # (i -> 1) + j = (i + j)'th character if i+j-1 >= m or s[i-1] == t[i+j-1]: dp[i][j] += dp[i+1][j] dp[i][j] %= mod print(sum(dp[1]) % mod) ```
output
1
54,916
0
109,833
Provide tags and a correct Python 3 solution for this coding contest problem. Kaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future. <image> Kaavi has a string T of length m and all the strings with the prefix T are magic spells. Kaavi also has a string S of length n and an empty string A. During the divination, Kaavi needs to perform a sequence of operations. There are two different operations: * Delete the first character of S and add it at the front of A. * Delete the first character of S and add it at the back of A. Kaavi can perform no more than n operations. To finish the divination, she wants to know the number of different operation sequences to make A a magic spell (i.e. with the prefix T). As her assistant, can you help her? The answer might be huge, so Kaavi only needs to know the answer modulo 998 244 353. Two operation sequences are considered different if they are different in length or there exists an i that their i-th operation is different. A substring is a contiguous sequence of characters within a string. A prefix of a string S is a substring of S that occurs at the beginning of S. Input The first line contains a string S of length n (1 ≤ n ≤ 3000). The second line contains a string T of length m (1 ≤ m ≤ n). Both strings contain only lowercase Latin letters. Output The output contains only one integer — the answer modulo 998 244 353. Examples Input abab ba Output 12 Input defineintlonglong signedmain Output 0 Input rotator rotator Output 4 Input cacdcdbbbb bdcaccdbbb Output 24 Note The first test: <image> The red ones are the magic spells. In the first operation, Kaavi can either add the first character "a" at the front or the back of A, although the results are the same, they are considered as different operations. So the answer is 6×2=12.
instruction
0
54,917
0
109,834
Tags: dp, strings Correct Solution: ``` '''input cbaabccadacadbaacbadddcdabcacdbbabccbbcbbcbbaadcabadcbdcadddccbbbbdacdbcbaddacaadbcddadbabbdbbacabdd cccdacdabbacbbcacdca ''' from typing import List import sys dp = [[0 for i in range(3005)] for i in range(3005)] a = input() pref = input() mod = 998244353 for lx in range(1, len(a) + 1): for l in range(0, len(a)): r = l + lx - 1 if r >= len(a): break cur = a[r - l] if l == r: dp[l][r] = 2 if ((l < len(pref) and cur == pref[l]) or l >= len(pref)) else 0 continue if l >= len(pref) or (l < len(pref) and cur == pref[l]): dp[l][r] += dp[l + 1][r] if r >= len(pref) or (r < len(pref) and cur == pref[r]): dp[l][r] += dp[l][r - 1] dp[l][r] %= mod ans = 0 for i in range(len(pref) - 1, len(a)): ans += dp[0][i] ans %= mod print(ans) ```
output
1
54,917
0
109,835
Provide tags and a correct Python 3 solution for this coding contest problem. Kaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future. <image> Kaavi has a string T of length m and all the strings with the prefix T are magic spells. Kaavi also has a string S of length n and an empty string A. During the divination, Kaavi needs to perform a sequence of operations. There are two different operations: * Delete the first character of S and add it at the front of A. * Delete the first character of S and add it at the back of A. Kaavi can perform no more than n operations. To finish the divination, she wants to know the number of different operation sequences to make A a magic spell (i.e. with the prefix T). As her assistant, can you help her? The answer might be huge, so Kaavi only needs to know the answer modulo 998 244 353. Two operation sequences are considered different if they are different in length or there exists an i that their i-th operation is different. A substring is a contiguous sequence of characters within a string. A prefix of a string S is a substring of S that occurs at the beginning of S. Input The first line contains a string S of length n (1 ≤ n ≤ 3000). The second line contains a string T of length m (1 ≤ m ≤ n). Both strings contain only lowercase Latin letters. Output The output contains only one integer — the answer modulo 998 244 353. Examples Input abab ba Output 12 Input defineintlonglong signedmain Output 0 Input rotator rotator Output 4 Input cacdcdbbbb bdcaccdbbb Output 24 Note The first test: <image> The red ones are the magic spells. In the first operation, Kaavi can either add the first character "a" at the front or the back of A, although the results are the same, they are considered as different operations. So the answer is 6×2=12.
instruction
0
54,918
0
109,836
Tags: dp, strings Correct Solution: ``` from sys import stdin, stdout def kaavi_and_magic_spell(S, T): MOD = 998244353 n = len(S) m = len(T) dp = [[0 for _ in range(n)] for _ in range(n)] for i in range(n): if comp(S, T, 0, i): dp[i][i] = 1 for l in range(2, n+1): for i in range(n - l + 1): if comp(S, T, l-1, i): # front dp[i][i+l-1] += dp[i+1][i+l-1] dp[i][i+l-1] %= MOD if comp(S, T, l-1, i+l-1): # back dp[i][i+l-1] += dp[i][i+l-2] dp[i][i+l-1] %= MOD r = 0 for j in range(m-1, n): r += dp[0][j] r %= MOD r *= 2 r %= MOD return r def comp(S, T, i, j): if j >= len(T): return True return S[i] == T[j] S = stdin.readline().strip() T = stdin.readline().strip() r = kaavi_and_magic_spell(S, T) stdout.write(str(r) + '\n') ```
output
1
54,918
0
109,837
Provide tags and a correct Python 3 solution for this coding contest problem. Kaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future. <image> Kaavi has a string T of length m and all the strings with the prefix T are magic spells. Kaavi also has a string S of length n and an empty string A. During the divination, Kaavi needs to perform a sequence of operations. There are two different operations: * Delete the first character of S and add it at the front of A. * Delete the first character of S and add it at the back of A. Kaavi can perform no more than n operations. To finish the divination, she wants to know the number of different operation sequences to make A a magic spell (i.e. with the prefix T). As her assistant, can you help her? The answer might be huge, so Kaavi only needs to know the answer modulo 998 244 353. Two operation sequences are considered different if they are different in length or there exists an i that their i-th operation is different. A substring is a contiguous sequence of characters within a string. A prefix of a string S is a substring of S that occurs at the beginning of S. Input The first line contains a string S of length n (1 ≤ n ≤ 3000). The second line contains a string T of length m (1 ≤ m ≤ n). Both strings contain only lowercase Latin letters. Output The output contains only one integer — the answer modulo 998 244 353. Examples Input abab ba Output 12 Input defineintlonglong signedmain Output 0 Input rotator rotator Output 4 Input cacdcdbbbb bdcaccdbbb Output 24 Note The first test: <image> The red ones are the magic spells. In the first operation, Kaavi can either add the first character "a" at the front or the back of A, although the results are the same, they are considered as different operations. So the answer is 6×2=12.
instruction
0
54,919
0
109,838
Tags: dp, strings Correct Solution: ``` s = input() t = input() n, m = len(s), len(t) dp = [[0 for _ in range (n+1)] for _ in range(n+1) ] for i in range(n+1): for j in range(n+1): if i == j: dp[i][j] = 1 for i in range(n-1, -1, -1): for j in range(i+1, n+1): if(i >= m or t[i] == s[j-i-1]): # add to the back <- should be front dp[i][j] += dp[i+1][j] % 998244353 if(j-1 >= m or t[j-1] == s[j-i-1]): # out of range here. why? # add to the front <- not t[i] == s[j-i-1] dp[i][j] += dp[i][j-1] % 998244353 # what's the difference between the two again? total = 0 for i in range(m, n+1): # i was wrong here!, shouldn't be range(m, n) total += dp[0][i] % 998244353 print(total % 998244353) # wrong again! when input (cacdcdbbbb, bdcaccdbbb) got 0 instead of 24 why? # i+j-1 >= m in line 14? should be j-1 >=m instead and t[j-1] == s[j-i-1] #okay ```
output
1
54,919
0
109,839
Provide tags and a correct Python 3 solution for this coding contest problem. Kaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future. <image> Kaavi has a string T of length m and all the strings with the prefix T are magic spells. Kaavi also has a string S of length n and an empty string A. During the divination, Kaavi needs to perform a sequence of operations. There are two different operations: * Delete the first character of S and add it at the front of A. * Delete the first character of S and add it at the back of A. Kaavi can perform no more than n operations. To finish the divination, she wants to know the number of different operation sequences to make A a magic spell (i.e. with the prefix T). As her assistant, can you help her? The answer might be huge, so Kaavi only needs to know the answer modulo 998 244 353. Two operation sequences are considered different if they are different in length or there exists an i that their i-th operation is different. A substring is a contiguous sequence of characters within a string. A prefix of a string S is a substring of S that occurs at the beginning of S. Input The first line contains a string S of length n (1 ≤ n ≤ 3000). The second line contains a string T of length m (1 ≤ m ≤ n). Both strings contain only lowercase Latin letters. Output The output contains only one integer — the answer modulo 998 244 353. Examples Input abab ba Output 12 Input defineintlonglong signedmain Output 0 Input rotator rotator Output 4 Input cacdcdbbbb bdcaccdbbb Output 24 Note The first test: <image> The red ones are the magic spells. In the first operation, Kaavi can either add the first character "a" at the front or the back of A, although the results are the same, they are considered as different operations. So the answer is 6×2=12.
instruction
0
54,920
0
109,840
Tags: dp, strings Correct Solution: ``` import sys input = sys.stdin.readline sys.setrecursionlimit(10 ** 5) s = input()[:-1] t = input()[:-1] MOD = 998244353 r_lim = len(t) n = len(s) dp = [[0] * (n + 1) for i in range(n + 1)] for length in range(1, n + 1): for l in range(n + 1): r = l + length if r > n: break if length == 1: if l >= r_lim or s[0] == t[l]: dp[l][r] = 2 else: dp[l][r] = 0 continue if l >= r_lim or s[length - 1] == t[l]: dp[l][r] += dp[l + 1][r] dp[l][r] %= MOD if r - 1 >= r_lim or s[length - 1] == t[r - 1]: dp[l][r] += dp[l][r - 1] dp[l][r] %= MOD ans = 0 for i in range(r_lim, n + 1): ans += dp[0][i] ans %= MOD print(ans) ```
output
1
54,920
0
109,841
Provide tags and a correct Python 3 solution for this coding contest problem. Kaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future. <image> Kaavi has a string T of length m and all the strings with the prefix T are magic spells. Kaavi also has a string S of length n and an empty string A. During the divination, Kaavi needs to perform a sequence of operations. There are two different operations: * Delete the first character of S and add it at the front of A. * Delete the first character of S and add it at the back of A. Kaavi can perform no more than n operations. To finish the divination, she wants to know the number of different operation sequences to make A a magic spell (i.e. with the prefix T). As her assistant, can you help her? The answer might be huge, so Kaavi only needs to know the answer modulo 998 244 353. Two operation sequences are considered different if they are different in length or there exists an i that their i-th operation is different. A substring is a contiguous sequence of characters within a string. A prefix of a string S is a substring of S that occurs at the beginning of S. Input The first line contains a string S of length n (1 ≤ n ≤ 3000). The second line contains a string T of length m (1 ≤ m ≤ n). Both strings contain only lowercase Latin letters. Output The output contains only one integer — the answer modulo 998 244 353. Examples Input abab ba Output 12 Input defineintlonglong signedmain Output 0 Input rotator rotator Output 4 Input cacdcdbbbb bdcaccdbbb Output 24 Note The first test: <image> The red ones are the magic spells. In the first operation, Kaavi can either add the first character "a" at the front or the back of A, although the results are the same, they are considered as different operations. So the answer is 6×2=12.
instruction
0
54,921
0
109,842
Tags: dp, strings Correct Solution: ``` mod = 998244353 eps = 10**-9 def main(): import sys input = sys.stdin.readline S = input().rstrip('\n') S = S[::-1] T = input().rstrip('\n') NS = len(S) NT = len(T) dp = [[0] * (NT+1) for _ in range(NS+1)] dp[0][0] = 1 for i in range(NS): s = S[i] for j in range(NT+1): # front if j == 0: if i != NS-1: if T[0] == s and dp[i][0]: dp[i+1][1] = (dp[i+1][1] + dp[i][0] + min(i, NS-NT))%mod else: if T[0] == s and dp[i][0]: dp[i+1][-1] = (dp[i+1][-1] + dp[i][0] + NS-NT)%mod elif j == NT: dp[i+1][j] = (dp[i+1][j] + dp[i][j])%mod else: if i != NS-1: if s == T[j]: dp[i+1][j+1] = (dp[i+1][j+1] + dp[i][j])%mod else: if s == T[j]: dp[i + 1][-1] = (dp[i + 1][-1] + dp[i][j]) % mod # back k = NS - (i-j) - 1 if k >= NT: dp[i+1][j] = (dp[i+1][j] + dp[i][j])%mod else: if T[k] == s: if i != NS-1: dp[i + 1][j] = (dp[i + 1][j] + dp[i][j]) % mod else: dp[i + 1][-1] = (dp[i + 1][-1] + dp[i][j]) % mod if k == 0 and dp[i][j]: dp[i+1][-1] = (dp[i+1][-1] + (NS-NT))%mod print(dp[-1][-1]%mod) #[print(i, dp[i]) for i in range(NS+1)] if __name__ == '__main__': main() ```
output
1
54,921
0
109,843
Provide tags and a correct Python 3 solution for this coding contest problem. Kaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future. <image> Kaavi has a string T of length m and all the strings with the prefix T are magic spells. Kaavi also has a string S of length n and an empty string A. During the divination, Kaavi needs to perform a sequence of operations. There are two different operations: * Delete the first character of S and add it at the front of A. * Delete the first character of S and add it at the back of A. Kaavi can perform no more than n operations. To finish the divination, she wants to know the number of different operation sequences to make A a magic spell (i.e. with the prefix T). As her assistant, can you help her? The answer might be huge, so Kaavi only needs to know the answer modulo 998 244 353. Two operation sequences are considered different if they are different in length or there exists an i that their i-th operation is different. A substring is a contiguous sequence of characters within a string. A prefix of a string S is a substring of S that occurs at the beginning of S. Input The first line contains a string S of length n (1 ≤ n ≤ 3000). The second line contains a string T of length m (1 ≤ m ≤ n). Both strings contain only lowercase Latin letters. Output The output contains only one integer — the answer modulo 998 244 353. Examples Input abab ba Output 12 Input defineintlonglong signedmain Output 0 Input rotator rotator Output 4 Input cacdcdbbbb bdcaccdbbb Output 24 Note The first test: <image> The red ones are the magic spells. In the first operation, Kaavi can either add the first character "a" at the front or the back of A, although the results are the same, they are considered as different operations. So the answer is 6×2=12.
instruction
0
54,922
0
109,844
Tags: dp, strings Correct Solution: ``` # -*- coding:utf-8 -*- """ created by shuangquan.huang at 2020/7/1 """ import collections import time import os import sys import bisect import heapq from typing import List MOD = 998244353 def solve(s, t): n, m = len(s), len(t) dp = [[0 for _ in range(m+1)] for _ in range(n+1)] dp[n][0] = 1 for i in range(n-1, 0, -1): for j in range(m+1): if j == 0: if i >= m: dp[i][0] = n - i + 1 elif s[i] == t[i]: dp[i][0] = dp[i+1][0] elif j == m: dp[i][m] = 2 * dp[i+1][m] % MOD if s[i] == t[m-1]: dp[i][m] = (dp[i][m] + dp[i+1][m-1]) % MOD else: if i + j >= m or s[i] == t[i+j]: dp[i][j] = dp[i+1][j] if s[i] == t[j-1]: dp[i][j] = (dp[i][j] + dp[i+1][j-1]) % MOD ans = dp[1][m] for i in range(m): if t[i] == s[0]: ans = (ans + dp[1][i]) % MOD ans *= 2 ans %= MOD return ans if __name__ == '__main__': s = input() t = input() print(solve(s, t)) ```
output
1
54,922
0
109,845
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Kaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future. <image> Kaavi has a string T of length m and all the strings with the prefix T are magic spells. Kaavi also has a string S of length n and an empty string A. During the divination, Kaavi needs to perform a sequence of operations. There are two different operations: * Delete the first character of S and add it at the front of A. * Delete the first character of S and add it at the back of A. Kaavi can perform no more than n operations. To finish the divination, she wants to know the number of different operation sequences to make A a magic spell (i.e. with the prefix T). As her assistant, can you help her? The answer might be huge, so Kaavi only needs to know the answer modulo 998 244 353. Two operation sequences are considered different if they are different in length or there exists an i that their i-th operation is different. A substring is a contiguous sequence of characters within a string. A prefix of a string S is a substring of S that occurs at the beginning of S. Input The first line contains a string S of length n (1 ≤ n ≤ 3000). The second line contains a string T of length m (1 ≤ m ≤ n). Both strings contain only lowercase Latin letters. Output The output contains only one integer — the answer modulo 998 244 353. Examples Input abab ba Output 12 Input defineintlonglong signedmain Output 0 Input rotator rotator Output 4 Input cacdcdbbbb bdcaccdbbb Output 24 Note The first test: <image> The red ones are the magic spells. In the first operation, Kaavi can either add the first character "a" at the front or the back of A, although the results are the same, they are considered as different operations. So the answer is 6×2=12. Submitted Solution: ``` import os def solve(S, T): """ with help of https://codeforces.com/contest/1336/submission/86403680 dp[i, k] = how many ways can arrange S[:k-i] characters to be T[i:k] solution = how many ways can arrange S = S[:n] to be T[0:n] = dp[i, n] """ MOD = 998244353 N = len(S) M = len(T) dp = [[0] * (N + 1) for _ in range(N)] for r in range(N): if r >= M or S[0] == T[r]: dp[r][r + 1] = 2 for s_size in range(2, N + 1): for t_start in range(N - s_size + 1): t_end = t_start + s_size s = S[s_size - 1] if t_start >= M or T[t_start] == s: # ...s|abc # T[t_start+1:t_end] = abc # T[t_start:t_end] = xabc # OR # T[t_start:t_end] = "" dp[t_start][t_end] = (dp[t_start][t_end] + dp[t_start + 1][t_end]) % MOD if t_end > M or T[t_end - 1] == s: # ...s|abc # T[t_start:t_end - 1] = abc # T[t_start:t_end] = abc|s # OR # T[t_start:t_end] = abc dp[t_start][t_end] = (dp[t_start][t_end] + dp[t_start][t_end - 1]) % MOD ans = 0 for i in range(M, N + 1): ans = (ans + dp[0][i]) % MOD return ans def pp(input): S = input().strip() T = input().strip() print(solve(S, T)) if "paalto" in os.getcwd(): from string_source import string_source pp( string_source( """cacdcdbbbb bdcaccdbbb""" ) ) else: pp(input) ```
instruction
0
54,923
0
109,846
Yes
output
1
54,923
0
109,847
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Kaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future. <image> Kaavi has a string T of length m and all the strings with the prefix T are magic spells. Kaavi also has a string S of length n and an empty string A. During the divination, Kaavi needs to perform a sequence of operations. There are two different operations: * Delete the first character of S and add it at the front of A. * Delete the first character of S and add it at the back of A. Kaavi can perform no more than n operations. To finish the divination, she wants to know the number of different operation sequences to make A a magic spell (i.e. with the prefix T). As her assistant, can you help her? The answer might be huge, so Kaavi only needs to know the answer modulo 998 244 353. Two operation sequences are considered different if they are different in length or there exists an i that their i-th operation is different. A substring is a contiguous sequence of characters within a string. A prefix of a string S is a substring of S that occurs at the beginning of S. Input The first line contains a string S of length n (1 ≤ n ≤ 3000). The second line contains a string T of length m (1 ≤ m ≤ n). Both strings contain only lowercase Latin letters. Output The output contains only one integer — the answer modulo 998 244 353. Examples Input abab ba Output 12 Input defineintlonglong signedmain Output 0 Input rotator rotator Output 4 Input cacdcdbbbb bdcaccdbbb Output 24 Note The first test: <image> The red ones are the magic spells. In the first operation, Kaavi can either add the first character "a" at the front or the back of A, although the results are the same, they are considered as different operations. So the answer is 6×2=12. Submitted Solution: ``` # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase def main(): mod = 998244353 s = input().strip() t = input().strip() dp = [0]*len(s) # no of favourable strings starting from index x for i in range(len(s)): if (i < len(t) and s[0] == t[i]) or i >= len(t): dp[i] = 2 cnt = (dp[0] if len(t) == 1 else 0) for i in range(1,len(s)): dp1 = [0]*len(s) for j in range(len(s)): if j: # adding to the front if (j <= len(t) and s[i] == t[j-1]) or j > len(t): dp1[j-1] = (dp1[j-1]+dp[j])%mod if j+i < len(s): # adding to the back if (j+i < len(t) and s[i] == t[j+i]) or j+i >= len(t): dp1[j] = (dp1[j]+dp[j])%mod dp = dp1 if i+1 >= len(t): cnt = (cnt+dp[0])%mod print(cnt) # Fast IO Region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": main() ```
instruction
0
54,924
0
109,848
Yes
output
1
54,924
0
109,849