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 tags and a correct Python 3 solution for this coding contest problem. A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not. You are given a string s of length n, consisting of digits. In one operation you can delete any character from string s. For example, it is possible to obtain strings 112, 111 or 121 from string 1121. You need to determine whether there is such a sequence of operations (possibly empty), after which the string s becomes a telephone number. Input The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 100) — the length of string s. The second line of each test case contains the string s (|s| = n) consisting of digits. Output For each test print one line. If there is a sequence of operations, after which s becomes a telephone number, print YES. Otherwise, print NO. Example Input 2 13 7818005553535 11 31415926535 Output YES NO Note In the first test case you need to delete the first and the third digits. Then the string 7818005553535 becomes 88005553535.
instruction
0
51,379
0
102,758
Tags: brute force, greedy, strings Correct Solution: ``` T=int(input()) for _ in range(T): n=int(input()) strng=input().strip() if (n<11): print('NO') else: if('8' in strng[:n-10]): print('YES') else: print('NO') ```
output
1
51,379
0
102,759
Provide tags and a correct Python 3 solution for this coding contest problem. A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not. You are given a string s of length n, consisting of digits. In one operation you can delete any character from string s. For example, it is possible to obtain strings 112, 111 or 121 from string 1121. You need to determine whether there is such a sequence of operations (possibly empty), after which the string s becomes a telephone number. Input The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 100) — the length of string s. The second line of each test case contains the string s (|s| = n) consisting of digits. Output For each test print one line. If there is a sequence of operations, after which s becomes a telephone number, print YES. Otherwise, print NO. Example Input 2 13 7818005553535 11 31415926535 Output YES NO Note In the first test case you need to delete the first and the third digits. Then the string 7818005553535 becomes 88005553535.
instruction
0
51,380
0
102,760
Tags: brute force, greedy, strings Correct Solution: ``` import sys import re def main(): inp = sys.stdin.read().strip().split()[2::2] out = [] for s in inp: out.append(('NO', 'YES')[bool(re.search('8\d{10}', s))]) return out print(*main(), sep='\n') ```
output
1
51,380
0
102,761
Provide tags and a correct Python 3 solution for this coding contest problem. A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not. You are given a string s of length n, consisting of digits. In one operation you can delete any character from string s. For example, it is possible to obtain strings 112, 111 or 121 from string 1121. You need to determine whether there is such a sequence of operations (possibly empty), after which the string s becomes a telephone number. Input The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 100) — the length of string s. The second line of each test case contains the string s (|s| = n) consisting of digits. Output For each test print one line. If there is a sequence of operations, after which s becomes a telephone number, print YES. Otherwise, print NO. Example Input 2 13 7818005553535 11 31415926535 Output YES NO Note In the first test case you need to delete the first and the third digits. Then the string 7818005553535 becomes 88005553535.
instruction
0
51,381
0
102,762
Tags: brute force, greedy, strings Correct Solution: ``` for _ in range(int(input())): n = int(input()) s = input() if n>=11 and '8' in s[:-10]: print('YES') else: print('NO') ```
output
1
51,381
0
102,763
Provide tags and a correct Python 3 solution for this coding contest problem. A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not. You are given a string s of length n, consisting of digits. In one operation you can delete any character from string s. For example, it is possible to obtain strings 112, 111 or 121 from string 1121. You need to determine whether there is such a sequence of operations (possibly empty), after which the string s becomes a telephone number. Input The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 100) — the length of string s. The second line of each test case contains the string s (|s| = n) consisting of digits. Output For each test print one line. If there is a sequence of operations, after which s becomes a telephone number, print YES. Otherwise, print NO. Example Input 2 13 7818005553535 11 31415926535 Output YES NO Note In the first test case you need to delete the first and the third digits. Then the string 7818005553535 becomes 88005553535.
instruction
0
51,382
0
102,764
Tags: brute force, greedy, strings Correct Solution: ``` [[print('YES' if n >= n - input().find('8') >= 11 else 'NO') for n in [int(input())]] for _ in range(int(input()))] ```
output
1
51,382
0
102,765
Provide tags and a correct Python 3 solution for this coding contest problem. A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not. You are given a string s of length n, consisting of digits. In one operation you can delete any character from string s. For example, it is possible to obtain strings 112, 111 or 121 from string 1121. You need to determine whether there is such a sequence of operations (possibly empty), after which the string s becomes a telephone number. Input The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 100) — the length of string s. The second line of each test case contains the string s (|s| = n) consisting of digits. Output For each test print one line. If there is a sequence of operations, after which s becomes a telephone number, print YES. Otherwise, print NO. Example Input 2 13 7818005553535 11 31415926535 Output YES NO Note In the first test case you need to delete the first and the third digits. Then the string 7818005553535 becomes 88005553535.
instruction
0
51,383
0
102,766
Tags: brute force, greedy, strings Correct Solution: ``` t = int(input()) for i in range(t): n = int(input()) s = input() if n < 11: print("NO") else: a = s.find('8') if -1 == a: print("NO") else: if n - a >= 11: print("YES") else: print("NO") ```
output
1
51,383
0
102,767
Provide tags and a correct Python 3 solution for this coding contest problem. A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not. You are given a string s of length n, consisting of digits. In one operation you can delete any character from string s. For example, it is possible to obtain strings 112, 111 or 121 from string 1121. You need to determine whether there is such a sequence of operations (possibly empty), after which the string s becomes a telephone number. Input The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 100) — the length of string s. The second line of each test case contains the string s (|s| = n) consisting of digits. Output For each test print one line. If there is a sequence of operations, after which s becomes a telephone number, print YES. Otherwise, print NO. Example Input 2 13 7818005553535 11 31415926535 Output YES NO Note In the first test case you need to delete the first and the third digits. Then the string 7818005553535 becomes 88005553535.
instruction
0
51,384
0
102,768
Tags: brute force, greedy, strings Correct Solution: ``` def solve(s): if len(s) == 11 and s[0] == '8': return True if len(s) < 11: return False if len(s) > 11: i = 0 while i < len(s): if s[i] == '8': break i += 1 if len(s)-i >= 11: return True return False t = int(input()) for _ in range(t): n = int(input()) s = input() print('YES' if solve(s) else 'NO') ```
output
1
51,384
0
102,769
Provide tags and a correct Python 3 solution for this coding contest problem. A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not. You are given a string s of length n, consisting of digits. In one operation you can delete any character from string s. For example, it is possible to obtain strings 112, 111 or 121 from string 1121. You need to determine whether there is such a sequence of operations (possibly empty), after which the string s becomes a telephone number. Input The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 100) — the length of string s. The second line of each test case contains the string s (|s| = n) consisting of digits. Output For each test print one line. If there is a sequence of operations, after which s becomes a telephone number, print YES. Otherwise, print NO. Example Input 2 13 7818005553535 11 31415926535 Output YES NO Note In the first test case you need to delete the first and the third digits. Then the string 7818005553535 becomes 88005553535.
instruction
0
51,385
0
102,770
Tags: brute force, greedy, strings Correct Solution: ``` t = int(input()) output = [] for _ in range(t): n = int(input()) s = input() p = s.find("8") ans = "YES" if (p >= 0) and (p + 10 < n) else "NO" output.append(ans) print("\n".join(output)) ```
output
1
51,385
0
102,771
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not. You are given a string s of length n, consisting of digits. In one operation you can delete any character from string s. For example, it is possible to obtain strings 112, 111 or 121 from string 1121. You need to determine whether there is such a sequence of operations (possibly empty), after which the string s becomes a telephone number. Input The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 100) — the length of string s. The second line of each test case contains the string s (|s| = n) consisting of digits. Output For each test print one line. If there is a sequence of operations, after which s becomes a telephone number, print YES. Otherwise, print NO. Example Input 2 13 7818005553535 11 31415926535 Output YES NO Note In the first test case you need to delete the first and the third digits. Then the string 7818005553535 becomes 88005553535. Submitted Solution: ``` a = int(input()) p = 0 for i in range(a): p = 0 b = int(input()) c = input() if(c[0]=="8" and b>=11): print("YES") else: while(len(c)>=11): c = c[1:] if(c[0]=="8" and b>=11): print("YES") p = 1 break if(p==0): print("NO") ```
instruction
0
51,390
0
102,780
No
output
1
51,390
0
102,781
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not. You are given a string s of length n, consisting of digits. In one operation you can delete any character from string s. For example, it is possible to obtain strings 112, 111 or 121 from string 1121. You need to determine whether there is such a sequence of operations (possibly empty), after which the string s becomes a telephone number. Input The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 100) — the length of string s. The second line of each test case contains the string s (|s| = n) consisting of digits. Output For each test print one line. If there is a sequence of operations, after which s becomes a telephone number, print YES. Otherwise, print NO. Example Input 2 13 7818005553535 11 31415926535 Output YES NO Note In the first test case you need to delete the first and the third digits. Then the string 7818005553535 becomes 88005553535. Submitted Solution: ``` n = input() n = int(n) x = 0 yes_no = [] for j in range(n): lol = int(input()) a = input() a = list(a) a = list(map(int,a)) if 8 not in a: x = 0 yes_no.append("NO") else: if len(a)<11: x = 0 if len(a) == 11: if a[0] != 8: x = 0 else: x = 1 if len(a)>11: for i in a: if i == 8: temp = a.index(i) if (len(a) - temp) >= 11: x = 1 break else: x = 0 break else: pass if x == 1: yes_no.append("YES") else: yes_no.append("NO") for i in yes_no: print(i) ```
instruction
0
51,392
0
102,784
No
output
1
51,392
0
102,785
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not. You are given a string s of length n, consisting of digits. In one operation you can delete any character from string s. For example, it is possible to obtain strings 112, 111 or 121 from string 1121. You need to determine whether there is such a sequence of operations (possibly empty), after which the string s becomes a telephone number. Input The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains one integer n (1 ≤ n ≤ 100) — the length of string s. The second line of each test case contains the string s (|s| = n) consisting of digits. Output For each test print one line. If there is a sequence of operations, after which s becomes a telephone number, print YES. Otherwise, print NO. Example Input 2 13 7818005553535 11 31415926535 Output YES NO Note In the first test case you need to delete the first and the third digits. Then the string 7818005553535 becomes 88005553535. Submitted Solution: ``` t = int(input()) for _ in range(t): n = int(input()) s = list(input()) d = n - 11 if d == 0 and s[0] == "8": print("YES") else: for i in range(d): if s[0] != "8": s.pop(0) else: s.pop(-1) if s[0] =="8": print("YES") else: print("NO") ```
instruction
0
51,393
0
102,786
No
output
1
51,393
0
102,787
Provide tags and a correct Python 3 solution for this coding contest problem. Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside. The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 1, 3, and 5, which form an arithmetic progression with a common difference of 2. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of S are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message! For example, in the string aaabb, a is hidden 3 times, b is hidden 2 times, ab is hidden 6 times, aa is hidden 3 times, bb is hidden 1 time, aab is hidden 2 times, aaa is hidden 1 time, abb is hidden 1 time, aaab is hidden 1 time, aabb is hidden 1 time, and aaabb is hidden 1 time. The number of occurrences of the secret message is 6. Input The first line contains a string s of lowercase Latin letters (1 ≤ |s| ≤ 10^5) — the text that Bessie intercepted. Output Output a single integer — the number of occurrences of the secret message. Examples Input aaabb Output 6 Input usaco Output 1 Input lol Output 2 Note In the first example, these are all the hidden strings and their indice sets: * a occurs at (1), (2), (3) * b occurs at (4), (5) * ab occurs at (1,4), (1,5), (2,4), (2,5), (3,4), (3,5) * aa occurs at (1,2), (1,3), (2,3) * bb occurs at (4,5) * aab occurs at (1,3,5), (2,3,4) * aaa occurs at (1,2,3) * abb occurs at (3,4,5) * aaab occurs at (1,2,3,4) * aabb occurs at (2,3,4,5) * aaabb occurs at (1,2,3,4,5) Note that all the sets of indices are arithmetic progressions. In the second example, no hidden string occurs more than once. In the third example, the hidden string is the letter l.
instruction
0
51,464
0
102,928
Tags: brute force, dp, math, strings Correct Solution: ``` from collections import Counter a = list(map(lambda c: ord(c)-97, input())) dp = [0]*26 dp2 = Counter() for c in a: for i in range(26): if i == c: continue dp2[i, c] += dp[i] dp[c] += 1 ans = max( max(dp), max(dp) * (max(dp)-1) // 2, dp2.most_common(1)[0][1] ) print(ans) ```
output
1
51,464
0
102,929
Provide tags and a correct Python 3 solution for this coding contest problem. Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside. The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 1, 3, and 5, which form an arithmetic progression with a common difference of 2. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of S are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message! For example, in the string aaabb, a is hidden 3 times, b is hidden 2 times, ab is hidden 6 times, aa is hidden 3 times, bb is hidden 1 time, aab is hidden 2 times, aaa is hidden 1 time, abb is hidden 1 time, aaab is hidden 1 time, aabb is hidden 1 time, and aaabb is hidden 1 time. The number of occurrences of the secret message is 6. Input The first line contains a string s of lowercase Latin letters (1 ≤ |s| ≤ 10^5) — the text that Bessie intercepted. Output Output a single integer — the number of occurrences of the secret message. Examples Input aaabb Output 6 Input usaco Output 1 Input lol Output 2 Note In the first example, these are all the hidden strings and their indice sets: * a occurs at (1), (2), (3) * b occurs at (4), (5) * ab occurs at (1,4), (1,5), (2,4), (2,5), (3,4), (3,5) * aa occurs at (1,2), (1,3), (2,3) * bb occurs at (4,5) * aab occurs at (1,3,5), (2,3,4) * aaa occurs at (1,2,3) * abb occurs at (3,4,5) * aaab occurs at (1,2,3,4) * aabb occurs at (2,3,4,5) * aaabb occurs at (1,2,3,4,5) Note that all the sets of indices are arithmetic progressions. In the second example, no hidden string occurs more than once. In the third example, the hidden string is the letter l.
instruction
0
51,465
0
102,930
Tags: brute force, dp, math, strings Correct Solution: ``` from collections import * l = list(input()) n = len(l) arr = [[0]*30 for i in range(30)] array = [0]*30 for i in range(n): val = ord(l[i]) - ord('a') + 1 for j in range(1,27): arr[j][val] += array[j] array[val] += 1 ans = 0 for i in range(1,27): for j in range(1,27): ans = max(ans,arr[i][j]) for i in range(1,27): ans = max(ans,array[i]) print(ans) ```
output
1
51,465
0
102,931
Provide tags and a correct Python 3 solution for this coding contest problem. Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside. The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 1, 3, and 5, which form an arithmetic progression with a common difference of 2. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of S are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message! For example, in the string aaabb, a is hidden 3 times, b is hidden 2 times, ab is hidden 6 times, aa is hidden 3 times, bb is hidden 1 time, aab is hidden 2 times, aaa is hidden 1 time, abb is hidden 1 time, aaab is hidden 1 time, aabb is hidden 1 time, and aaabb is hidden 1 time. The number of occurrences of the secret message is 6. Input The first line contains a string s of lowercase Latin letters (1 ≤ |s| ≤ 10^5) — the text that Bessie intercepted. Output Output a single integer — the number of occurrences of the secret message. Examples Input aaabb Output 6 Input usaco Output 1 Input lol Output 2 Note In the first example, these are all the hidden strings and their indice sets: * a occurs at (1), (2), (3) * b occurs at (4), (5) * ab occurs at (1,4), (1,5), (2,4), (2,5), (3,4), (3,5) * aa occurs at (1,2), (1,3), (2,3) * bb occurs at (4,5) * aab occurs at (1,3,5), (2,3,4) * aaa occurs at (1,2,3) * abb occurs at (3,4,5) * aaab occurs at (1,2,3,4) * aabb occurs at (2,3,4,5) * aaabb occurs at (1,2,3,4,5) Note that all the sets of indices are arithmetic progressions. In the second example, no hidden string occurs more than once. In the third example, the hidden string is the letter l.
instruction
0
51,466
0
102,932
Tags: brute force, dp, math, strings Correct Solution: ``` d={} s={0} for x in input(""): for y in s:d[x,y]=d.get((x,y),0)+d.get(y,0) s|={x};d[x]=d.get(x,0)+1 print(max(d.values())) ```
output
1
51,466
0
102,933
Provide tags and a correct Python 3 solution for this coding contest problem. Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside. The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 1, 3, and 5, which form an arithmetic progression with a common difference of 2. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of S are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message! For example, in the string aaabb, a is hidden 3 times, b is hidden 2 times, ab is hidden 6 times, aa is hidden 3 times, bb is hidden 1 time, aab is hidden 2 times, aaa is hidden 1 time, abb is hidden 1 time, aaab is hidden 1 time, aabb is hidden 1 time, and aaabb is hidden 1 time. The number of occurrences of the secret message is 6. Input The first line contains a string s of lowercase Latin letters (1 ≤ |s| ≤ 10^5) — the text that Bessie intercepted. Output Output a single integer — the number of occurrences of the secret message. Examples Input aaabb Output 6 Input usaco Output 1 Input lol Output 2 Note In the first example, these are all the hidden strings and their indice sets: * a occurs at (1), (2), (3) * b occurs at (4), (5) * ab occurs at (1,4), (1,5), (2,4), (2,5), (3,4), (3,5) * aa occurs at (1,2), (1,3), (2,3) * bb occurs at (4,5) * aab occurs at (1,3,5), (2,3,4) * aaa occurs at (1,2,3) * abb occurs at (3,4,5) * aaab occurs at (1,2,3,4) * aabb occurs at (2,3,4,5) * aaabb occurs at (1,2,3,4,5) Note that all the sets of indices are arithmetic progressions. In the second example, no hidden string occurs more than once. In the third example, the hidden string is the letter l.
instruction
0
51,467
0
102,934
Tags: brute force, dp, math, strings Correct Solution: ``` def main(): s = input() cnt = [s.count(chr(ord('a') + i)) for i in range(26)] an = max(cnt) for i in range(26): lol = [0] * 26 kek = cnt[::] for c in s: kek[ord(c) - ord('a')] -= 1 if ord(c) - ord('a') == i: for j in range(26): lol[j] += kek[j] an = max(an, max(lol)) print(an) if __name__ == "__main__": main() ```
output
1
51,467
0
102,935
Provide tags and a correct Python 3 solution for this coding contest problem. Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside. The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 1, 3, and 5, which form an arithmetic progression with a common difference of 2. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of S are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message! For example, in the string aaabb, a is hidden 3 times, b is hidden 2 times, ab is hidden 6 times, aa is hidden 3 times, bb is hidden 1 time, aab is hidden 2 times, aaa is hidden 1 time, abb is hidden 1 time, aaab is hidden 1 time, aabb is hidden 1 time, and aaabb is hidden 1 time. The number of occurrences of the secret message is 6. Input The first line contains a string s of lowercase Latin letters (1 ≤ |s| ≤ 10^5) — the text that Bessie intercepted. Output Output a single integer — the number of occurrences of the secret message. Examples Input aaabb Output 6 Input usaco Output 1 Input lol Output 2 Note In the first example, these are all the hidden strings and their indice sets: * a occurs at (1), (2), (3) * b occurs at (4), (5) * ab occurs at (1,4), (1,5), (2,4), (2,5), (3,4), (3,5) * aa occurs at (1,2), (1,3), (2,3) * bb occurs at (4,5) * aab occurs at (1,3,5), (2,3,4) * aaa occurs at (1,2,3) * abb occurs at (3,4,5) * aaab occurs at (1,2,3,4) * aabb occurs at (2,3,4,5) * aaabb occurs at (1,2,3,4,5) Note that all the sets of indices are arithmetic progressions. In the second example, no hidden string occurs more than once. In the third example, the hidden string is the letter l.
instruction
0
51,468
0
102,936
Tags: brute force, dp, math, strings Correct Solution: ``` 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") s = set() dp = {} c = {} n = len(s) for x in input(): dp[x] = dp.get(x, 0) + 1 for y in s: dp[(x, y)] = dp.get((x, y), 0) + c[y] s.add(x) c[x] = c.get(x,0) + 1 print(max(dp.values())) ```
output
1
51,468
0
102,937
Provide tags and a correct Python 3 solution for this coding contest problem. Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside. The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 1, 3, and 5, which form an arithmetic progression with a common difference of 2. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of S are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message! For example, in the string aaabb, a is hidden 3 times, b is hidden 2 times, ab is hidden 6 times, aa is hidden 3 times, bb is hidden 1 time, aab is hidden 2 times, aaa is hidden 1 time, abb is hidden 1 time, aaab is hidden 1 time, aabb is hidden 1 time, and aaabb is hidden 1 time. The number of occurrences of the secret message is 6. Input The first line contains a string s of lowercase Latin letters (1 ≤ |s| ≤ 10^5) — the text that Bessie intercepted. Output Output a single integer — the number of occurrences of the secret message. Examples Input aaabb Output 6 Input usaco Output 1 Input lol Output 2 Note In the first example, these are all the hidden strings and their indice sets: * a occurs at (1), (2), (3) * b occurs at (4), (5) * ab occurs at (1,4), (1,5), (2,4), (2,5), (3,4), (3,5) * aa occurs at (1,2), (1,3), (2,3) * bb occurs at (4,5) * aab occurs at (1,3,5), (2,3,4) * aaa occurs at (1,2,3) * abb occurs at (3,4,5) * aaab occurs at (1,2,3,4) * aabb occurs at (2,3,4,5) * aaabb occurs at (1,2,3,4,5) Note that all the sets of indices are arithmetic progressions. In the second example, no hidden string occurs more than once. In the third example, the hidden string is the letter l.
instruction
0
51,469
0
102,938
Tags: brute force, dp, math, strings Correct Solution: ``` import sys input = lambda: sys.stdin.readline().rstrip() ans=[0]*26 a=[ord(i)-97 for i in input()] cnt=[0]*26 ; maxx=[0]*26 ; ans=[0]*26 for i in a: cnt[i]+=1 for i in range(len(ans)): z=cnt[i]*(cnt[i]+1)//2-cnt[i] for j in range(len(a)-1,-1,-1): if a[j]==i: ans[a[j]]+=1 cnt[i]-=1 else: ans[a[j]]+=cnt[i] maxx[i]=max(max(ans),z) ans=[0]*26 print(max(maxx)) ```
output
1
51,469
0
102,939
Provide tags and a correct Python 3 solution for this coding contest problem. Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside. The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 1, 3, and 5, which form an arithmetic progression with a common difference of 2. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of S are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message! For example, in the string aaabb, a is hidden 3 times, b is hidden 2 times, ab is hidden 6 times, aa is hidden 3 times, bb is hidden 1 time, aab is hidden 2 times, aaa is hidden 1 time, abb is hidden 1 time, aaab is hidden 1 time, aabb is hidden 1 time, and aaabb is hidden 1 time. The number of occurrences of the secret message is 6. Input The first line contains a string s of lowercase Latin letters (1 ≤ |s| ≤ 10^5) — the text that Bessie intercepted. Output Output a single integer — the number of occurrences of the secret message. Examples Input aaabb Output 6 Input usaco Output 1 Input lol Output 2 Note In the first example, these are all the hidden strings and their indice sets: * a occurs at (1), (2), (3) * b occurs at (4), (5) * ab occurs at (1,4), (1,5), (2,4), (2,5), (3,4), (3,5) * aa occurs at (1,2), (1,3), (2,3) * bb occurs at (4,5) * aab occurs at (1,3,5), (2,3,4) * aaa occurs at (1,2,3) * abb occurs at (3,4,5) * aaab occurs at (1,2,3,4) * aabb occurs at (2,3,4,5) * aaabb occurs at (1,2,3,4,5) Note that all the sets of indices are arithmetic progressions. In the second example, no hidden string occurs more than once. In the third example, the hidden string is the letter l.
instruction
0
51,470
0
102,940
Tags: brute force, dp, math, strings Correct Solution: ``` from collections import defaultdict s = list(input()) arr = [0 for j in range(26)] index = defaultdict(int) for j in range(len(s)): for k in range(26): v = chr(k+97)+s[j] index[v]+=arr[k] arr[ord(s[j])-97]+=1 maximum = max(arr) for j in index: maximum = max(index[j],maximum) print(maximum) ```
output
1
51,470
0
102,941
Provide tags and a correct Python 3 solution for this coding contest problem. Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside. The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 1, 3, and 5, which form an arithmetic progression with a common difference of 2. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of S are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message! For example, in the string aaabb, a is hidden 3 times, b is hidden 2 times, ab is hidden 6 times, aa is hidden 3 times, bb is hidden 1 time, aab is hidden 2 times, aaa is hidden 1 time, abb is hidden 1 time, aaab is hidden 1 time, aabb is hidden 1 time, and aaabb is hidden 1 time. The number of occurrences of the secret message is 6. Input The first line contains a string s of lowercase Latin letters (1 ≤ |s| ≤ 10^5) — the text that Bessie intercepted. Output Output a single integer — the number of occurrences of the secret message. Examples Input aaabb Output 6 Input usaco Output 1 Input lol Output 2 Note In the first example, these are all the hidden strings and their indice sets: * a occurs at (1), (2), (3) * b occurs at (4), (5) * ab occurs at (1,4), (1,5), (2,4), (2,5), (3,4), (3,5) * aa occurs at (1,2), (1,3), (2,3) * bb occurs at (4,5) * aab occurs at (1,3,5), (2,3,4) * aaa occurs at (1,2,3) * abb occurs at (3,4,5) * aaab occurs at (1,2,3,4) * aabb occurs at (2,3,4,5) * aaabb occurs at (1,2,3,4,5) Note that all the sets of indices are arithmetic progressions. In the second example, no hidden string occurs more than once. In the third example, the hidden string is the letter l.
instruction
0
51,471
0
102,942
Tags: brute force, dp, math, strings Correct Solution: ``` s=str(input()) cml=[[0 for i in range(len(s)+1)] for j in range(26)] c=1 for i in s: k=ord(i)-ord("a") cml[k][c]=cml[k][c-1]+1 for j in range(26): if j!=k:cml[j][c]=cml[j][c-1] c+=1 ab=[[0 for i in range(26)] for j in range(26)] c=1 for k in s: i=ord(k)-ord("a") for j in range(26): ab[i][j]+=cml[j][-1]-cml[j][c] c+=1 ans=0 res=0 for i in range(26): res=max(res,cml[i][-1]) for j in range(26): ans=max(ans,ab[i][j]) print(max(ans,res)) ```
output
1
51,471
0
102,943
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside. The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 1, 3, and 5, which form an arithmetic progression with a common difference of 2. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of S are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message! For example, in the string aaabb, a is hidden 3 times, b is hidden 2 times, ab is hidden 6 times, aa is hidden 3 times, bb is hidden 1 time, aab is hidden 2 times, aaa is hidden 1 time, abb is hidden 1 time, aaab is hidden 1 time, aabb is hidden 1 time, and aaabb is hidden 1 time. The number of occurrences of the secret message is 6. Input The first line contains a string s of lowercase Latin letters (1 ≤ |s| ≤ 10^5) — the text that Bessie intercepted. Output Output a single integer — the number of occurrences of the secret message. Examples Input aaabb Output 6 Input usaco Output 1 Input lol Output 2 Note In the first example, these are all the hidden strings and their indice sets: * a occurs at (1), (2), (3) * b occurs at (4), (5) * ab occurs at (1,4), (1,5), (2,4), (2,5), (3,4), (3,5) * aa occurs at (1,2), (1,3), (2,3) * bb occurs at (4,5) * aab occurs at (1,3,5), (2,3,4) * aaa occurs at (1,2,3) * abb occurs at (3,4,5) * aaab occurs at (1,2,3,4) * aabb occurs at (2,3,4,5) * aaabb occurs at (1,2,3,4,5) Note that all the sets of indices are arithmetic progressions. In the second example, no hidden string occurs more than once. In the third example, the hidden string is the letter l. Submitted Solution: ``` s = list(input()) arr1 = [0 for i in range(26)] arr2 = [[0 for i in range(26)] for j in range(26)] for i in range(len(s)): c = ord(s[i])-97 for j in range(26): arr2[j][c] += arr1[j] arr1[c] += 1 a = max([max(i) for i in arr2]) print(max(a, max(arr1))) ```
instruction
0
51,472
0
102,944
Yes
output
1
51,472
0
102,945
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside. The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 1, 3, and 5, which form an arithmetic progression with a common difference of 2. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of S are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message! For example, in the string aaabb, a is hidden 3 times, b is hidden 2 times, ab is hidden 6 times, aa is hidden 3 times, bb is hidden 1 time, aab is hidden 2 times, aaa is hidden 1 time, abb is hidden 1 time, aaab is hidden 1 time, aabb is hidden 1 time, and aaabb is hidden 1 time. The number of occurrences of the secret message is 6. Input The first line contains a string s of lowercase Latin letters (1 ≤ |s| ≤ 10^5) — the text that Bessie intercepted. Output Output a single integer — the number of occurrences of the secret message. Examples Input aaabb Output 6 Input usaco Output 1 Input lol Output 2 Note In the first example, these are all the hidden strings and their indice sets: * a occurs at (1), (2), (3) * b occurs at (4), (5) * ab occurs at (1,4), (1,5), (2,4), (2,5), (3,4), (3,5) * aa occurs at (1,2), (1,3), (2,3) * bb occurs at (4,5) * aab occurs at (1,3,5), (2,3,4) * aaa occurs at (1,2,3) * abb occurs at (3,4,5) * aaab occurs at (1,2,3,4) * aabb occurs at (2,3,4,5) * aaabb occurs at (1,2,3,4,5) Note that all the sets of indices are arithmetic progressions. In the second example, no hidden string occurs more than once. In the third example, the hidden string is the letter l. Submitted Solution: ``` import bisect s=input() idx={} for i in range(len(s)): if s[i] not in idx: idx[s[i]]=[] idx[s[i]].append(i) ans=0 for i in idx: ans=max(ans,len(idx[i])) for j in idx: ans=max(ans,len(idx[j])) cv=0 for fi in idx[i]: freq=len(idx[j])-bisect.bisect_right(idx[j],fi) cv+=freq ans=max(ans,cv) print(ans) ```
instruction
0
51,473
0
102,946
Yes
output
1
51,473
0
102,947
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside. The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 1, 3, and 5, which form an arithmetic progression with a common difference of 2. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of S are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message! For example, in the string aaabb, a is hidden 3 times, b is hidden 2 times, ab is hidden 6 times, aa is hidden 3 times, bb is hidden 1 time, aab is hidden 2 times, aaa is hidden 1 time, abb is hidden 1 time, aaab is hidden 1 time, aabb is hidden 1 time, and aaabb is hidden 1 time. The number of occurrences of the secret message is 6. Input The first line contains a string s of lowercase Latin letters (1 ≤ |s| ≤ 10^5) — the text that Bessie intercepted. Output Output a single integer — the number of occurrences of the secret message. Examples Input aaabb Output 6 Input usaco Output 1 Input lol Output 2 Note In the first example, these are all the hidden strings and their indice sets: * a occurs at (1), (2), (3) * b occurs at (4), (5) * ab occurs at (1,4), (1,5), (2,4), (2,5), (3,4), (3,5) * aa occurs at (1,2), (1,3), (2,3) * bb occurs at (4,5) * aab occurs at (1,3,5), (2,3,4) * aaa occurs at (1,2,3) * abb occurs at (3,4,5) * aaab occurs at (1,2,3,4) * aabb occurs at (2,3,4,5) * aaabb occurs at (1,2,3,4,5) Note that all the sets of indices are arithmetic progressions. In the second example, no hidden string occurs more than once. In the third example, the hidden string is the letter l. Submitted Solution: ``` from collections import Counter s = [i for i in input()] mx = Counter(s).most_common()[0][1] for i in range(26): for j in range(26): if i != j: m = 0 ct = 0 for k in range(len(s)): if s[k] == chr(97+i): m += 1 if s[k] == chr(97+j): ct += m mx = max(mx, ct) m = 0 ct = 0 for k in range(len(s)): if s[k] == chr(97+j): m += 1 if s[k] == chr(97+i): ct += m mx = max(mx, ct) print(max(mx, Counter(s).most_common()[0][1]*(Counter(s).most_common()[0][1]-1)//2)) ```
instruction
0
51,474
0
102,948
Yes
output
1
51,474
0
102,949
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside. The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 1, 3, and 5, which form an arithmetic progression with a common difference of 2. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of S are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message! For example, in the string aaabb, a is hidden 3 times, b is hidden 2 times, ab is hidden 6 times, aa is hidden 3 times, bb is hidden 1 time, aab is hidden 2 times, aaa is hidden 1 time, abb is hidden 1 time, aaab is hidden 1 time, aabb is hidden 1 time, and aaabb is hidden 1 time. The number of occurrences of the secret message is 6. Input The first line contains a string s of lowercase Latin letters (1 ≤ |s| ≤ 10^5) — the text that Bessie intercepted. Output Output a single integer — the number of occurrences of the secret message. Examples Input aaabb Output 6 Input usaco Output 1 Input lol Output 2 Note In the first example, these are all the hidden strings and their indice sets: * a occurs at (1), (2), (3) * b occurs at (4), (5) * ab occurs at (1,4), (1,5), (2,4), (2,5), (3,4), (3,5) * aa occurs at (1,2), (1,3), (2,3) * bb occurs at (4,5) * aab occurs at (1,3,5), (2,3,4) * aaa occurs at (1,2,3) * abb occurs at (3,4,5) * aaab occurs at (1,2,3,4) * aabb occurs at (2,3,4,5) * aaabb occurs at (1,2,3,4,5) Note that all the sets of indices are arithmetic progressions. In the second example, no hidden string occurs more than once. In the third example, the hidden string is the letter l. Submitted Solution: ``` a,b={},{} for x in input(): for y in a:b[x,y]=b.get((x,y),0)+a.get(y,0) a[x]=a.get(x,0)+1 print(max(0,0,*a.values(),*b.values())) ```
instruction
0
51,475
0
102,950
Yes
output
1
51,475
0
102,951
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside. The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 1, 3, and 5, which form an arithmetic progression with a common difference of 2. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of S are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message! For example, in the string aaabb, a is hidden 3 times, b is hidden 2 times, ab is hidden 6 times, aa is hidden 3 times, bb is hidden 1 time, aab is hidden 2 times, aaa is hidden 1 time, abb is hidden 1 time, aaab is hidden 1 time, aabb is hidden 1 time, and aaabb is hidden 1 time. The number of occurrences of the secret message is 6. Input The first line contains a string s of lowercase Latin letters (1 ≤ |s| ≤ 10^5) — the text that Bessie intercepted. Output Output a single integer — the number of occurrences of the secret message. Examples Input aaabb Output 6 Input usaco Output 1 Input lol Output 2 Note In the first example, these are all the hidden strings and their indice sets: * a occurs at (1), (2), (3) * b occurs at (4), (5) * ab occurs at (1,4), (1,5), (2,4), (2,5), (3,4), (3,5) * aa occurs at (1,2), (1,3), (2,3) * bb occurs at (4,5) * aab occurs at (1,3,5), (2,3,4) * aaa occurs at (1,2,3) * abb occurs at (3,4,5) * aaab occurs at (1,2,3,4) * aabb occurs at (2,3,4,5) * aaabb occurs at (1,2,3,4,5) Note that all the sets of indices are arithmetic progressions. In the second example, no hidden string occurs more than once. In the third example, the hidden string is the letter l. Submitted Solution: ``` lis = ['#']+list(input()) c=1 ans=1 has=[0]*26 n = len(lis) for i in range(1,n): has[ord(lis[i])-ord('a')]+=1 if lis[i]==lis[i-1]: c+=1 else: ans*=c c=1 ans*=c print(max(ans,max(has))) ```
instruction
0
51,476
0
102,952
No
output
1
51,476
0
102,953
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside. The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 1, 3, and 5, which form an arithmetic progression with a common difference of 2. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of S are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message! For example, in the string aaabb, a is hidden 3 times, b is hidden 2 times, ab is hidden 6 times, aa is hidden 3 times, bb is hidden 1 time, aab is hidden 2 times, aaa is hidden 1 time, abb is hidden 1 time, aaab is hidden 1 time, aabb is hidden 1 time, and aaabb is hidden 1 time. The number of occurrences of the secret message is 6. Input The first line contains a string s of lowercase Latin letters (1 ≤ |s| ≤ 10^5) — the text that Bessie intercepted. Output Output a single integer — the number of occurrences of the secret message. Examples Input aaabb Output 6 Input usaco Output 1 Input lol Output 2 Note In the first example, these are all the hidden strings and their indice sets: * a occurs at (1), (2), (3) * b occurs at (4), (5) * ab occurs at (1,4), (1,5), (2,4), (2,5), (3,4), (3,5) * aa occurs at (1,2), (1,3), (2,3) * bb occurs at (4,5) * aab occurs at (1,3,5), (2,3,4) * aaa occurs at (1,2,3) * abb occurs at (3,4,5) * aaab occurs at (1,2,3,4) * aabb occurs at (2,3,4,5) * aaabb occurs at (1,2,3,4,5) Note that all the sets of indices are arithmetic progressions. In the second example, no hidden string occurs more than once. In the third example, the hidden string is the letter l. Submitted Solution: ``` import math class Read: @staticmethod def string(): return input() @staticmethod def int(): return int(input()) @staticmethod def list(sep=' '): return input().split(sep) @staticmethod def list_int(sep=' '): return list(map(int, input().split(sep))) def solve(): s = input() if len(s) == 1: print(1) return t = {} mx = 0 alph = '' last = False gh = [1] gh_index = 0 for i in s: if i in t: t[i] += 1 if t[i] > mx: mx = t[i] else: t[i] = 1 alph += i if last: if last == i: gh[gh_index] += 1 else: gh_index += 1 gh.append(1) last = i print(gh) res = {} t2 = {} for i in s: if i in t2: t2[i] += 1 else: t2[i] = 1 for j in alph: if i != j: k = str(i + j) if k not in res: res[k] = 0 res[k] += t[j] - (t2[j] if j in t2 else 0) if len(res.values()) == 0: r = 0 for i in range(1, mx): r += i print(r) return r = 0 for i in range(1, max(gh)): r += i print(max(max(res.values()), mx, r)) #accafafaf query_count = 1 # query_count = Read.int() while query_count: query_count -= 1 solve() ```
instruction
0
51,477
0
102,954
No
output
1
51,477
0
102,955
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside. The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 1, 3, and 5, which form an arithmetic progression with a common difference of 2. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of S are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message! For example, in the string aaabb, a is hidden 3 times, b is hidden 2 times, ab is hidden 6 times, aa is hidden 3 times, bb is hidden 1 time, aab is hidden 2 times, aaa is hidden 1 time, abb is hidden 1 time, aaab is hidden 1 time, aabb is hidden 1 time, and aaabb is hidden 1 time. The number of occurrences of the secret message is 6. Input The first line contains a string s of lowercase Latin letters (1 ≤ |s| ≤ 10^5) — the text that Bessie intercepted. Output Output a single integer — the number of occurrences of the secret message. Examples Input aaabb Output 6 Input usaco Output 1 Input lol Output 2 Note In the first example, these are all the hidden strings and their indice sets: * a occurs at (1), (2), (3) * b occurs at (4), (5) * ab occurs at (1,4), (1,5), (2,4), (2,5), (3,4), (3,5) * aa occurs at (1,2), (1,3), (2,3) * bb occurs at (4,5) * aab occurs at (1,3,5), (2,3,4) * aaa occurs at (1,2,3) * abb occurs at (3,4,5) * aaab occurs at (1,2,3,4) * aabb occurs at (2,3,4,5) * aaabb occurs at (1,2,3,4,5) Note that all the sets of indices are arithmetic progressions. In the second example, no hidden string occurs more than once. In the third example, the hidden string is the letter l. Submitted Solution: ``` s=input() d={} ans=0 for i in s: d[i]=d.get(i,0)+1 for i in d: ans=max(ans,d[i],(d[i]*(d[i]-1))//2) n=len(s) x=[] i=0 while i<n: t=s[i] c=0 while t==s[i]: c=c+1 i=i+1 if i==n: break x.append(c) ans=max(ans,max(x)) m=[] for i in range(len(x)-1,-1,-1): if i==len(x)-1: m.append(x[i]) else: m.append(max(m[-1],x[i])) m=m[::-1] for i in range(len(x)-1): ans=max(ans,x[i]*m[i+1]) print(ans) ```
instruction
0
51,478
0
102,956
No
output
1
51,478
0
102,957
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside. The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 1, 3, and 5, which form an arithmetic progression with a common difference of 2. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of S are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message! For example, in the string aaabb, a is hidden 3 times, b is hidden 2 times, ab is hidden 6 times, aa is hidden 3 times, bb is hidden 1 time, aab is hidden 2 times, aaa is hidden 1 time, abb is hidden 1 time, aaab is hidden 1 time, aabb is hidden 1 time, and aaabb is hidden 1 time. The number of occurrences of the secret message is 6. Input The first line contains a string s of lowercase Latin letters (1 ≤ |s| ≤ 10^5) — the text that Bessie intercepted. Output Output a single integer — the number of occurrences of the secret message. Examples Input aaabb Output 6 Input usaco Output 1 Input lol Output 2 Note In the first example, these are all the hidden strings and their indice sets: * a occurs at (1), (2), (3) * b occurs at (4), (5) * ab occurs at (1,4), (1,5), (2,4), (2,5), (3,4), (3,5) * aa occurs at (1,2), (1,3), (2,3) * bb occurs at (4,5) * aab occurs at (1,3,5), (2,3,4) * aaa occurs at (1,2,3) * abb occurs at (3,4,5) * aaab occurs at (1,2,3,4) * aabb occurs at (2,3,4,5) * aaabb occurs at (1,2,3,4,5) Note that all the sets of indices are arithmetic progressions. In the second example, no hidden string occurs more than once. In the third example, the hidden string is the letter l. Submitted Solution: ``` from collections import defaultdict from itertools import combinations text = input() unq = defaultdict(int) for i in list(text): unq[i]+=1 best = max(unq.values()) if best==1: print(1); exit(0) best = (best*(best-1))//2 for a,b in combinations(unq.keys(),2): cnt_ab,cnt_ba = 0,0 a_enc, b_enc = 0,0 for x in list(text): if x==a: a_enc+=1 cnt_ba += b_enc elif x==b: b_enc+=1 cnt_ab += a_enc best = max(best, cnt_ab, cnt_ba) print(best) ```
instruction
0
51,479
0
102,958
No
output
1
51,479
0
102,959
Provide a correct Python 3 solution for this coding contest problem. We have N strings of lowercase English letters: S_1, S_2, \cdots, S_N. Takahashi wants to make a string that is a palindrome by choosing one or more of these strings - the same string can be chosen more than once - and concatenating them in some order of his choice. The cost of using the string S_i once is C_i, and the cost of using it multiple times is C_i multiplied by that number of times. Find the minimum total cost needed to choose strings so that Takahashi can make a palindrome. If there is no choice of strings in which he can make a palindrome, print -1. Constraints * 1 \leq N \leq 50 * 1 \leq |S_i| \leq 20 * S_i consists of lowercase English letters. * 1 \leq C_i \leq 10^9 Input Input is given from Standard Input in the following format: N S_1 C_1 S_2 C_2 : S_N C_N Output Print the minimum total cost needed to choose strings so that Takahashi can make a palindrome, or -1 if there is no such choice. Examples Input 3 ba 3 abc 4 cbaa 5 Output 7 Input 2 abcab 5 cba 3 Output 11 Input 4 ab 5 cba 3 a 12 ab 10 Output 8 Input 2 abc 1 ab 2 Output -1
instruction
0
51,916
0
103,832
"Correct Solution: ``` import sys INF = 1 << 60 MOD = 10**9 + 7 # 998244353 sys.setrecursionlimit(2147483647) input = lambda:sys.stdin.readline().rstrip() from itertools import product from heapq import heappop, heappush def resolve(): n = int(input()) S = [None] * n C = [None] * n for i in range(n): S[i], C[i] = input().split() C[i] = int(C[i]) for i in range(n): S.append(S[i][::-1]) C.append(C[i]) # id[i][j] : index of S[i][-j:] id = [[] for _ in range(2 * n)] N = 1 for i in range(2 * n): for j in range(len(S[i])): id[i].append(N) N += 1 # make graph E = [[] for _ in range(N)] for i, ni in product(range(2 * n), repeat = 2): if i // n == ni // n: continue for j in range(len(S[i])): now = S[i][j:] edge = S[ni] l = min(len(now), len(edge)) if now[:l] != edge[:l]: continue c = C[ni] v = id[i][j] nv = None if len(now) > len(edge): E[id[i][j]].append((id[i][j + len(edge)], c)) elif len(now) < len(edge): E[id[i][j]].append((id[ni][len(now)], c)) else: E[id[i][j]].append((0, c)) # Dijkstra dist = [INF] * N queue = [] for i, c in enumerate(C): dist[id[i][0]] = c heappush(queue, (c, id[i][0])) while queue: d, v = heappop(queue) if d != dist[v]: continue for nv, w in E[v]: if dist[nv] > dist[v] + w: dist[nv] = dist[v] + w heappush(queue, (dist[nv], nv)) ans = dist[0] for i in range(2 * n): for j in range(len(S[i])): T = S[i][j:] if T == T[::-1]: ans = min(ans, dist[id[i][j]]) if ans == INF: ans = -1 print(ans) resolve() ```
output
1
51,916
0
103,833
Provide a correct Python 3 solution for this coding contest problem. We have N strings of lowercase English letters: S_1, S_2, \cdots, S_N. Takahashi wants to make a string that is a palindrome by choosing one or more of these strings - the same string can be chosen more than once - and concatenating them in some order of his choice. The cost of using the string S_i once is C_i, and the cost of using it multiple times is C_i multiplied by that number of times. Find the minimum total cost needed to choose strings so that Takahashi can make a palindrome. If there is no choice of strings in which he can make a palindrome, print -1. Constraints * 1 \leq N \leq 50 * 1 \leq |S_i| \leq 20 * S_i consists of lowercase English letters. * 1 \leq C_i \leq 10^9 Input Input is given from Standard Input in the following format: N S_1 C_1 S_2 C_2 : S_N C_N Output Print the minimum total cost needed to choose strings so that Takahashi can make a palindrome, or -1 if there is no such choice. Examples Input 3 ba 3 abc 4 cbaa 5 Output 7 Input 2 abcab 5 cba 3 Output 11 Input 4 ab 5 cba 3 a 12 ab 10 Output 8 Input 2 abc 1 ab 2 Output -1
instruction
0
51,917
0
103,834
"Correct Solution: ``` import sys import queue input_methods=['clipboard','file','key'] using_method=0 input_method=input_methods[using_method] tin=lambda : map(int, input().split()) lin=lambda : list(tin()) mod=1000000007 #+++++ def is_kaibun(s): if len(s) <= 1: return True for c, cc in zip(s,s[::-1]): if c != cc: return False return True def mk_sub(s, other, s_is_front): #pa((s,other,s[:len(other)],other[:len(s)])) if len(s) <= len(other) and s == other[:len(s)]: return True, other[len(s):], not s_is_front elif len(s)>len(other) and s[:len(other)] == other: return True, s[len(other):], s_is_front return False, '', False def main(): n = int(input()) #b , c = tin() #s = input() dd_f = {} dd_b = {} for _ in range(n): s, v = input().split() v = int(v) if s in dd_f: v = min(v, dd_f[s]) dd_f[s] = v dd_b[s[::-1]]=v front=True open_list=queue.PriorityQueue() close_list_f = set() close_list_b = set() for k in dd_f: open_list.put((dd_f[k], (k, front))) while not open_list.empty(): #pa('rrrr') #return cost, (s, is_front) = open_list.get() #pa((cost,s,is_front)) #pa(s if is_front else s[::-1]) if is_kaibun(s): return cost if (is_front and s in close_list_f) or (not is_front and s in close_list_b): continue if is_front: close_list_f.add(s) else: close_list_b.add(s) dic = dd_b if is_front else dd_f for k in dic: is_ok, next_s, r_is_front=mk_sub(s, k, is_front) #pa((is_ok,next_s,r_is_front,k)) if not is_ok: continue elif r_is_front and next_s in close_list_f: continue elif not r_is_front and next_s in close_list_b: continue else: open_list.put((cost + dic[k], (next_s, r_is_front))) return -1 #+++++ isTest=False def pa(v): if isTest: print(v) def input_clipboard(): import clipboard input_text=clipboard.get() input_l=input_text.splitlines() for l in input_l: yield l if __name__ == "__main__": if sys.platform =='ios': if input_method==input_methods[0]: ic=input_clipboard() input = lambda : ic.__next__() elif input_method==input_methods[1]: sys.stdin=open('inputFile.txt') else: pass isTest=True else: pass #input = sys.stdin.readline ret = main() if ret is not None: print(ret) ```
output
1
51,917
0
103,835
Provide a correct Python 3 solution for this coding contest problem. We have N strings of lowercase English letters: S_1, S_2, \cdots, S_N. Takahashi wants to make a string that is a palindrome by choosing one or more of these strings - the same string can be chosen more than once - and concatenating them in some order of his choice. The cost of using the string S_i once is C_i, and the cost of using it multiple times is C_i multiplied by that number of times. Find the minimum total cost needed to choose strings so that Takahashi can make a palindrome. If there is no choice of strings in which he can make a palindrome, print -1. Constraints * 1 \leq N \leq 50 * 1 \leq |S_i| \leq 20 * S_i consists of lowercase English letters. * 1 \leq C_i \leq 10^9 Input Input is given from Standard Input in the following format: N S_1 C_1 S_2 C_2 : S_N C_N Output Print the minimum total cost needed to choose strings so that Takahashi can make a palindrome, or -1 if there is no such choice. Examples Input 3 ba 3 abc 4 cbaa 5 Output 7 Input 2 abcab 5 cba 3 Output 11 Input 4 ab 5 cba 3 a 12 ab 10 Output 8 Input 2 abc 1 ab 2 Output -1
instruction
0
51,918
0
103,836
"Correct Solution: ``` from heapq import heappush, heappop inf = float('inf') def dijkstra(graph:list, node:int, start:int) -> list: dist = [inf]*node dist[start] = 0 heap = [(0,start)] while heap: cost,thisNode = heappop(heap) for NextCost,NextNode in graph[thisNode]: dist_cand = dist[thisNode]+NextCost if dist_cand < dist[NextNode]: dist[NextNode] = dist_cand heappush(heap,(dist[NextNode],NextNode)) return dist N = int(input()) S1 = [] S2 = [] C = [] for i in range(N): s,c = input().split() S1.append(s) S2.append(s[::-1]) C.append(int(c)) d_v = {('',''):0,('l',''):1,('r',''):2} idx = 3 for i in range(N): s = S1[i] for j in range(len(s)): for k in range(j,len(s)): ss_l = s[j:k+1] ss_r = ss_l[::-1] if ss_l != ss_r: if ('l',ss_l) not in d_v: d_v[('l',ss_l)] = idx idx += 1 if ('r',ss_r) not in d_v: d_v[('r',ss_r)] = idx idx += 1 edge = [[] for _ in range(len(d_v))] for i in range(N): s_l = S1[i] s_r = S2[i] c = C[i] for lr,ss in d_v: if ss == '': if lr == '': t = s_l if t==t[::-1]: t = '' edge[0].append((c,d_v[('l',t)])) else: continue if lr == 'l': if ss.startswith(s_r): t = ss[len(s_r):] if t==t[::-1]: t = '' edge[d_v[(lr,ss)]].append((c,d_v[('l',t)])) if s_r.startswith(ss): t = s_r[len(ss):] if t==t[::-1]: t = '' edge[d_v[(lr,ss)]].append((c,d_v[('r',t)])) elif lr == 'r': if ss.startswith(s_l): t = ss[len(s_l):] if t==t[::-1]: t = '' edge[d_v[(lr,ss)]].append((c,d_v[('r',t)])) if s_l.startswith(ss): t = s_l[len(ss):] if t==t[::-1]: t = '' edge[d_v[(lr,ss)]].append((c,d_v[('l',t)])) dist = dijkstra(edge,len(d_v),0) ans = min(dist[1],dist[2]) if ans == inf: ans = -1 print(ans) ```
output
1
51,918
0
103,837
Provide a correct Python 3 solution for this coding contest problem. We have N strings of lowercase English letters: S_1, S_2, \cdots, S_N. Takahashi wants to make a string that is a palindrome by choosing one or more of these strings - the same string can be chosen more than once - and concatenating them in some order of his choice. The cost of using the string S_i once is C_i, and the cost of using it multiple times is C_i multiplied by that number of times. Find the minimum total cost needed to choose strings so that Takahashi can make a palindrome. If there is no choice of strings in which he can make a palindrome, print -1. Constraints * 1 \leq N \leq 50 * 1 \leq |S_i| \leq 20 * S_i consists of lowercase English letters. * 1 \leq C_i \leq 10^9 Input Input is given from Standard Input in the following format: N S_1 C_1 S_2 C_2 : S_N C_N Output Print the minimum total cost needed to choose strings so that Takahashi can make a palindrome, or -1 if there is no such choice. Examples Input 3 ba 3 abc 4 cbaa 5 Output 7 Input 2 abcab 5 cba 3 Output 11 Input 4 ab 5 cba 3 a 12 ab 10 Output 8 Input 2 abc 1 ab 2 Output -1
instruction
0
51,919
0
103,838
"Correct Solution: ``` ''' 自宅用PCでの解答 ''' import math #import numpy as np import itertools import queue import bisect from collections import deque,defaultdict import heapq as hpq from sys import stdin,setrecursionlimit #from scipy.sparse.csgraph import dijkstra #from scipy.sparse import csr_matrix ipt = stdin.readline setrecursionlimit(10**7) mod = 10**9+7 # mod = 998244353 dir = [(-1,0),(0,-1),(1,0),(0,1)] alp = "abcdefghijklmnopqrstuvwxyz" INF = 1<<32-1 # INF = 10**18 def main(): n = int(ipt()) wrds = [] hq = [] usd = set() for i in range(n): s,c = input().split() c = int(c) wrds.append((s,c)) hpq.heappush(hq,(c,s,1)) while hq: hc,hs,hp = hpq.heappop(hq) usd.add((hs,hp)) ls = len(hs) if hs == hs[::-1]: print(hc) exit() for si,ci in wrds: lsi = len(si) if lsi > ls: if hp == 1: wt = si[::-1] # print(wt) if hs == wt[:ls:] and not (wt[ls::],-1) in usd: hpq.heappush(hq,(hc+ci,wt[ls::],-1)) else: if hs == si[:ls:] and not (si[ls::],1) in usd: hpq.heappush(hq,(hc+ci,si[ls::],1)) else: if hp == 1: wt = si[::-1] if wt == hs[:lsi:] and not (hs[lsi::],1) in usd: hpq.heappush(hq,(hc+ci,hs[lsi::],1)) else: if si == hs[:lsi:] and not (hs[lsi::],-1) in usd: hpq.heappush(hq,(hc+ci,hs[lsi::],-1)) # print(hq) print(-1) return None if __name__ == '__main__': main() ```
output
1
51,919
0
103,839
Provide a correct Python 3 solution for this coding contest problem. We have N strings of lowercase English letters: S_1, S_2, \cdots, S_N. Takahashi wants to make a string that is a palindrome by choosing one or more of these strings - the same string can be chosen more than once - and concatenating them in some order of his choice. The cost of using the string S_i once is C_i, and the cost of using it multiple times is C_i multiplied by that number of times. Find the minimum total cost needed to choose strings so that Takahashi can make a palindrome. If there is no choice of strings in which he can make a palindrome, print -1. Constraints * 1 \leq N \leq 50 * 1 \leq |S_i| \leq 20 * S_i consists of lowercase English letters. * 1 \leq C_i \leq 10^9 Input Input is given from Standard Input in the following format: N S_1 C_1 S_2 C_2 : S_N C_N Output Print the minimum total cost needed to choose strings so that Takahashi can make a palindrome, or -1 if there is no such choice. Examples Input 3 ba 3 abc 4 cbaa 5 Output 7 Input 2 abcab 5 cba 3 Output 11 Input 4 ab 5 cba 3 a 12 ab 10 Output 8 Input 2 abc 1 ab 2 Output -1
instruction
0
51,920
0
103,840
"Correct Solution: ``` from collections import deque def isPalindrome(s): L = len(s) rst = True if L: for i in range(L // 2): if s[i] != s[L - 1 - i]: rst = False break return rst N = int(input()) S = [] for _ in range(N): s, c = input().split() S.append((s, int(c))) path = [dict() for _ in range(2)] q = deque() S.sort(key=lambda x: x[1]) for s, c in S: if s not in path[0] or path[0][s] > c: path[0][s] = c q.append((0, s, c)) ans = float('inf') isPossible = False while q: side, s0, c0 = q.popleft() if isPalindrome(s0): ans = min(ans, c0) isPossible |= True else: for s1, c1 in S: if side == 0: l = s0 r = s1 else: l = s1 r = s0 if len(l) > len(r): for i in range(len(r)): if l[i] != r[-1 - i]: break else: ns = l[len(r):] nc = c0 + c1 nside = 0 if (ns not in path[nside]) or path[nside][ns] > nc: path[nside][ns] = nc q.append((nside, ns, nc)) elif len(l) < len(r): for i in range(len(l)): if l[i] != r[-1 - i]: break else: ns = r[:-len(l)] nc = c0 + c1 nside = 1 if (ns not in path[nside]) or path[nside][ns] > nc: path[nside][ns] = nc q.append((nside, ns, nc)) else: for i in range(len(l)): if l[i] != r[-1 - i]: break else: ns = '' nc = c0 + c1 nside = 0 if (ns not in path[nside]) or path[nside][ns] > nc: path[nside][ns] = nc q.append((nside, ns, nc)) if isPossible: print(ans) else: print(-1) ```
output
1
51,920
0
103,841
Provide a correct Python 3 solution for this coding contest problem. We have N strings of lowercase English letters: S_1, S_2, \cdots, S_N. Takahashi wants to make a string that is a palindrome by choosing one or more of these strings - the same string can be chosen more than once - and concatenating them in some order of his choice. The cost of using the string S_i once is C_i, and the cost of using it multiple times is C_i multiplied by that number of times. Find the minimum total cost needed to choose strings so that Takahashi can make a palindrome. If there is no choice of strings in which he can make a palindrome, print -1. Constraints * 1 \leq N \leq 50 * 1 \leq |S_i| \leq 20 * S_i consists of lowercase English letters. * 1 \leq C_i \leq 10^9 Input Input is given from Standard Input in the following format: N S_1 C_1 S_2 C_2 : S_N C_N Output Print the minimum total cost needed to choose strings so that Takahashi can make a palindrome, or -1 if there is no such choice. Examples Input 3 ba 3 abc 4 cbaa 5 Output 7 Input 2 abcab 5 cba 3 Output 11 Input 4 ab 5 cba 3 a 12 ab 10 Output 8 Input 2 abc 1 ab 2 Output -1
instruction
0
51,921
0
103,842
"Correct Solution: ``` # -*- coding: utf-8 -*- ############# # Libraries # ############# import sys input = sys.stdin.readline import math #from math import gcd import bisect import heapq from collections import defaultdict from collections import deque from collections import Counter from functools import lru_cache ############# # Constants # ############# MOD = 10**9+7 INF = float('inf') AZ = "abcdefghijklmnopqrstuvwxyz" ############# # Functions # ############# ######INPUT###### def I(): return int(input().strip()) def S(): return input().strip() def IL(): return list(map(int,input().split())) def SL(): return list(map(str,input().split())) def ILs(n): return list(int(input()) for _ in range(n)) def SLs(n): return list(input().strip() for _ in range(n)) def ILL(n): return [list(map(int, input().split())) for _ in range(n)] def SLL(n): return [list(map(str, input().split())) for _ in range(n)] #####Shorten##### def DD(arg): return defaultdict(arg) #####Inverse##### def inv(n): return pow(n, MOD-2, MOD) ######Combination###### kaijo_memo = [] def kaijo(n): if(len(kaijo_memo) > n): return kaijo_memo[n] if(len(kaijo_memo) == 0): kaijo_memo.append(1) while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD) return kaijo_memo[n] gyaku_kaijo_memo = [] def gyaku_kaijo(n): if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n] if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1) while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD) return gyaku_kaijo_memo[n] def nCr(n,r): if n == r: return 1 if n < r or r < 0: return 0 ret = 1 ret = ret * kaijo(n) % MOD ret = ret * gyaku_kaijo(r) % MOD ret = ret * gyaku_kaijo(n-r) % MOD return ret ######Factorization###### def factorization(n): arr = [] temp = n for i in range(2, int(-(-n**0.5//1))+1): if temp%i==0: cnt=0 while temp%i==0: cnt+=1 temp //= i arr.append([i, cnt]) if temp!=1: arr.append([temp, 1]) if arr==[]: arr.append([n, 1]) return arr #####MakeDivisors###### def make_divisors(n): divisors = [] for i in range(1, int(n**0.5)+1): if n % i == 0: divisors.append(i) if i != n // i: divisors.append(n//i) return divisors #####MakePrimes###### def make_primes(N): max = int(math.sqrt(N)) seachList = [i for i in range(2,N+1)] primeNum = [] while seachList[0] <= max: primeNum.append(seachList[0]) tmp = seachList[0] seachList = [i for i in seachList if i % tmp != 0] primeNum.extend(seachList) return primeNum #####GCD##### def gcd(a, b): while b: a, b = b, a % b return a #####LCM##### def lcm(a, b): return a * b // gcd (a, b) #####BitCount##### def count_bit(n): count = 0 while n: n &= n-1 count += 1 return count #####ChangeBase##### def base_10_to_n(X, n): if X//n: return base_10_to_n(X//n, n)+[X%n] return [X%n] def base_n_to_10(X, n): return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X)))) def base_10_to_n_without_0(X, n): X -= 1 if X//n: return base_10_to_n_without_0(X//n, n)+[X%n] return [X%n] #####IntLog##### def int_log(n, a): count = 0 while n>=a: n //= a count += 1 return count ############# # Main Code # ############# N = I() data = SLL(N) words = [] costs = [] nodes = {("",0),("",1)} best = INF for d in data: word = d[0] cost = int(d[1]) if word == word[::-1]: best = min(best,cost) continue words.append(word) costs.append(cost) for j in range(len(word)): nodes.add((word[:j+1],1)) nodes.add((word[j:],0)) graph = {k:[] for k in nodes} graph[("",1)].append((0,("",0))) for k in nodes: amari = k[0] t = k[1] if amari == amari[::-1]: if amari: graph[k].append((0,("",0))) else: n = len(amari) for i in range(len(words)): word = words[i] cost = costs[i] if t == 0: if len(word)>n: if amari == word[::-1][:n]: graph[k].append((cost,(word[:-n],1))) else: if amari[:len(word)] == word[::-1]: graph[k].append((cost,(amari[len(word):],0))) else: if len(word)>n: if amari[::-1] == word[:n]: graph[k].append((cost,(word[n:],0))) else: if amari[::-1][:len(word)] == word: graph[k].append((cost,(amari[:-len(word)],1))) def dijkstra(graph, start,cost): N = len(graph) d = {k:INF for k in nodes} d[start] = cost f = {k:False for k in nodes} q = [(cost, start)] while q: c,u = heapq.heappop(q) if f[u]: continue d[u] = c f[u] = True for c,v in graph[u]: if not f[v]: heapq.heappush(q, (c + d[u], v)) return d for i in range(len(words)): word = words[i] cost = costs[i] best = min(best,dijkstra(graph,(word,0),cost)[("",0)]) best = min(best,dijkstra(graph,(word,1),cost)[("",0)]) if best == INF: print(-1) else: print(best) ```
output
1
51,921
0
103,843
Provide a correct Python 3 solution for this coding contest problem. We have N strings of lowercase English letters: S_1, S_2, \cdots, S_N. Takahashi wants to make a string that is a palindrome by choosing one or more of these strings - the same string can be chosen more than once - and concatenating them in some order of his choice. The cost of using the string S_i once is C_i, and the cost of using it multiple times is C_i multiplied by that number of times. Find the minimum total cost needed to choose strings so that Takahashi can make a palindrome. If there is no choice of strings in which he can make a palindrome, print -1. Constraints * 1 \leq N \leq 50 * 1 \leq |S_i| \leq 20 * S_i consists of lowercase English letters. * 1 \leq C_i \leq 10^9 Input Input is given from Standard Input in the following format: N S_1 C_1 S_2 C_2 : S_N C_N Output Print the minimum total cost needed to choose strings so that Takahashi can make a palindrome, or -1 if there is no such choice. Examples Input 3 ba 3 abc 4 cbaa 5 Output 7 Input 2 abcab 5 cba 3 Output 11 Input 4 ab 5 cba 3 a 12 ab 10 Output 8 Input 2 abc 1 ab 2 Output -1
instruction
0
51,922
0
103,844
"Correct Solution: ``` it = lambda: list(map(int, input().strip().split())) INF = float('inf') def solve(): N = int(input()) S = [] R = [] C = [] for _ in range(N): s, c = input().strip().split() S.append(s) R.append(s[::-1]) C.append(int(c)) vis = set() mem = dict() def dp(s, p): if (s, p) in mem: return mem[s, p] if s == s[::-1]: return 0 if (s, p) in vis: return INF ans = INF vis.add((s, p)) for i, t in enumerate(S if p else R): if len(t) >= len(s) and t.startswith(s): ans = min(ans, dp(t[len(s):], p ^ 1) + C[i]) elif len(s) > len(t) and s.startswith(t): ans = min(ans, dp(s[len(t):], p) + C[i]) vis.discard((s, p)) mem[s, p] = ans return ans ans = INF for i in range(N): ans = min(ans, dp(S[i], 0) + C[i]) return -1 if ans == INF else ans if __name__ == '__main__': ans = solve() print(ans) ```
output
1
51,922
0
103,845
Provide a correct Python 3 solution for this coding contest problem. We have N strings of lowercase English letters: S_1, S_2, \cdots, S_N. Takahashi wants to make a string that is a palindrome by choosing one or more of these strings - the same string can be chosen more than once - and concatenating them in some order of his choice. The cost of using the string S_i once is C_i, and the cost of using it multiple times is C_i multiplied by that number of times. Find the minimum total cost needed to choose strings so that Takahashi can make a palindrome. If there is no choice of strings in which he can make a palindrome, print -1. Constraints * 1 \leq N \leq 50 * 1 \leq |S_i| \leq 20 * S_i consists of lowercase English letters. * 1 \leq C_i \leq 10^9 Input Input is given from Standard Input in the following format: N S_1 C_1 S_2 C_2 : S_N C_N Output Print the minimum total cost needed to choose strings so that Takahashi can make a palindrome, or -1 if there is no such choice. Examples Input 3 ba 3 abc 4 cbaa 5 Output 7 Input 2 abcab 5 cba 3 Output 11 Input 4 ab 5 cba 3 a 12 ab 10 Output 8 Input 2 abc 1 ab 2 Output -1
instruction
0
51,923
0
103,846
"Correct Solution: ``` from collections import deque def isPalindrome(s): L = len(s) return all(s[i] == s[L - 1 - i] for i in range(L // 2)) N = int(input()) S = [] for _ in range(N): s, c = input().split() S.append((s, int(c))) path = [dict() for _ in range(2)] q = deque() # S.sort(key=lambda x: x[1]) for s, c in S: if s not in path[0] or path[0][s] > c: path[0][s] = c q.append((0, s, c)) INF = 10 ** 15 ans = INF while q: side, s0, c0 = q.popleft() if isPalindrome(s0): ans = min(ans, c0) else: for s1, c1 in S: if side == 0: l, r = s0, s1 else: l, r = s1, s0 L = len(l) R = len(r) isCandidate = False if L > R: if all(l[i] == r[-1 - i] for i in range(R)): ns = l[len(r):] nc = c0 + c1 nside = 0 isCandidate |= True elif L < R: if all(l[i] == r[-1 - i] for i in range(L)): ns = r[:-len(l)] nc = c0 + c1 nside = 1 isCandidate |= True else: if all(l[i] == r[-1 - i] for i in range(L)): ns = '' nc = c0 + c1 nside = 0 isCandidate |= True if isCandidate and (ns not in path[nside] or path[nside][ns] > nc): path[nside][ns] = nc q.append((nside, ns, nc)) if ans < INF: print(ans) else: print(-1) ```
output
1
51,923
0
103,847
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have N strings of lowercase English letters: S_1, S_2, \cdots, S_N. Takahashi wants to make a string that is a palindrome by choosing one or more of these strings - the same string can be chosen more than once - and concatenating them in some order of his choice. The cost of using the string S_i once is C_i, and the cost of using it multiple times is C_i multiplied by that number of times. Find the minimum total cost needed to choose strings so that Takahashi can make a palindrome. If there is no choice of strings in which he can make a palindrome, print -1. Constraints * 1 \leq N \leq 50 * 1 \leq |S_i| \leq 20 * S_i consists of lowercase English letters. * 1 \leq C_i \leq 10^9 Input Input is given from Standard Input in the following format: N S_1 C_1 S_2 C_2 : S_N C_N Output Print the minimum total cost needed to choose strings so that Takahashi can make a palindrome, or -1 if there is no such choice. Examples Input 3 ba 3 abc 4 cbaa 5 Output 7 Input 2 abcab 5 cba 3 Output 11 Input 4 ab 5 cba 3 a 12 ab 10 Output 8 Input 2 abc 1 ab 2 Output -1 Submitted Solution: ``` from random import randrange from heapq import heapify, heappush, heappop from time import time K = 60 rand = lambda: randrange(1 << K) sTime = time() N = int(input()) S, IS, C = [], [], [] for _ in range(N): s, c = input().split() S.append(s) IS.append(s[::-1]) C.append(int(c)) D = {} done = [set(), set()] r = rand() D[r] = (0, "", 0) H = [r] ans = 1 << K while H: r = heappop(H) if time() - sTime > 1.7: break d, s, c = D[r] if s in done[d]: continue done[d].add(s) if d == 0: for ss, cc in zip(S, C): m = min(len(s), len(ss)) if s[:m] == ss[:m]: if abs(len(s) - len(ss)) <= 1 or len(ss) > len(s) and ss[m:] == ss[m:][::-1]: ans = min(ans, c + cc) else: if len(s) < len(ss): r = rand() + (c + cc << K) D[r] = (1, ss[m:], c + cc) heappush(H, r) else: r = rand() + (c + cc << K) D[r] = (0, s[m:], c + cc) heappush(H, r) else: for ss, cc in zip(IS, C): m = min(len(s), len(ss)) if s[:m] == ss[:m]: if abs(len(s) - len(ss)) <= 1 or len(ss) > len(s) and ss[m:] == ss[m:][::-1]: ans = min(ans, c + cc) else: if len(s) < len(ss): r = rand() + (c + cc << K) D[r] = (0, ss[m:], c + cc) heappush(H, r) else: r = rand() + (c + cc << K) D[r] = (1, s[m:], c + cc) heappush(H, r) print(ans if ans < 1 << K - 2 else -1) ```
instruction
0
51,924
0
103,848
Yes
output
1
51,924
0
103,849
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have N strings of lowercase English letters: S_1, S_2, \cdots, S_N. Takahashi wants to make a string that is a palindrome by choosing one or more of these strings - the same string can be chosen more than once - and concatenating them in some order of his choice. The cost of using the string S_i once is C_i, and the cost of using it multiple times is C_i multiplied by that number of times. Find the minimum total cost needed to choose strings so that Takahashi can make a palindrome. If there is no choice of strings in which he can make a palindrome, print -1. Constraints * 1 \leq N \leq 50 * 1 \leq |S_i| \leq 20 * S_i consists of lowercase English letters. * 1 \leq C_i \leq 10^9 Input Input is given from Standard Input in the following format: N S_1 C_1 S_2 C_2 : S_N C_N Output Print the minimum total cost needed to choose strings so that Takahashi can make a palindrome, or -1 if there is no such choice. Examples Input 3 ba 3 abc 4 cbaa 5 Output 7 Input 2 abcab 5 cba 3 Output 11 Input 4 ab 5 cba 3 a 12 ab 10 Output 8 Input 2 abc 1 ab 2 Output -1 Submitted Solution: ``` import sys from heapq import heappush, heappop def input(): return sys.stdin.readline().strip() def main(): """ 回文文字列を左右からそれぞれ構成していく。 左の文字列と右の文字列のうち短い方に文字を足していく。 例えば左に文字列をくっつけたとすると、一般に左側が数文字余る。 この数文字が回文になっていれば全体も回文。 そうでなければ左側の余り文字列を含むようないい文字列を右側にくっつければ良い。 この手法だと回文が生成可能かどうかが多項式時間で判定可能。 なぜなら左右を見て余る文字列はS1,...,SNのprefixないしsuffixに限定されるから。 最後にコスト最小の回文をどう発見するかだが、これは余った文字列の状態を頂点とする グラフを構成してダイクストラをすれば良い。 """ N = int(input()) string = [] cost = [] for _ in range(N): s, c = input().split() string.append(s) cost.append(int(c)) length = [len(string[i]) for i in range(N)] # グラフ頂点の構成(余りなしの文字列の状態をn = 0番目とする) # string_to_id[d][i][j] = (Siの先頭(d=0)もしくは末尾(d=1)からj文字とった部分文字列) string_to_id = [[[0] * (length[i] + 1) for i in range(N)] for _ in range(2)] id_to_string = {} # id_to_string[id] = (d, i, j) n = 1 for d in range(2): for i in range(N): for j in range(1, length[i] + 1): string_to_id[d][i][j] = n id_to_string[n] = (d, i, j) n += 1 #print("n={}".format(n)) #print("string_to_id={}".format(string_to_id)) #print("id_to_string={}".format(id_to_string)) # グラフ辺の構成 repn = [[] for _ in range(n)] for i in range(N): repn[0].append((string_to_id[0][i][length[i]], cost[i])) repn[0].append((string_to_id[1][i][length[i]], cost[i])) for v in range(1, n): d, i, j = id_to_string[v] if d == 0: # 先頭が余っている=右の文字列が長い場合 for ni in range(N): if j <= length[ni]: # 左に文字列を追加して左側が長くなる場合 if string[ni][:j] != (string[i][:j])[::-1]: continue id = string_to_id[1][ni][length[ni] - j] else: # 左側に文字列を追加してもまだ右側が長い場合 if string[ni] != (string[i][(j - length[ni]):j])[::-1]: continue id = string_to_id[0][i][j - length[ni]] repn[v].append((id, cost[ni])) else: # 末尾が余っている=左の文字列が長い場合 for ni in range(N): if j <= length[ni]: # 右に文字列を追加して右側が長くなる場合 if (string[i][-j:])[::-1] != string[ni][-j:]: continue id = string_to_id[0][ni][length[ni] - j] else: # 右側に文字列を追加してもまだ左側が長い場合 if (string[i][-j:(-j + length[ni])])[::-1] != string[ni]: continue id = string_to_id[1][i][j - length[ni]] repn[v].append((id, cost[ni])) #print("repn[{}]={}".format(v, repn[v])) # ダイクストラ(キューの中身は辺のコストじゃなくてそこまでの合計コストですよ!!!!!!) # あとキューに入れる時に距離を確定(「コスト最初距離候補」ではなく「距離確定の中の最小」から進めるから) min_cost = [10**18] * n q = [] # (qの中身)=(dist, to) for v, cos in repn[0]: min_cost[v] = cos heappush(q, (cos, v)) while q: dist, v = heappop(q) if min_cost[v] != dist: continue # 枝刈り1回目 for nv, ncos in repn[v]: if min_cost[nv] <= dist + ncos: continue # 枝刈り2回目 min_cost[nv] = dist + ncos heappush(q, (dist + ncos, nv)) #for v in range(n): print("min_cost[{}]={}".format(v, min_cost[v])) # 最小コストを探索 ans = 10**18 ans = min(ans, min_cost[0]) # きれいに終わる場合を忘れてた for v in range(1, n): d, i, j = id_to_string[v] if d == 0: substring = string[i][:j] else: substring = string[i][-j:] if substring == substring[::-1]: ans = min(ans, min_cost[v]) if ans == 10**18: print(-1) else: print(ans) if __name__ == "__main__": main() ```
instruction
0
51,925
0
103,850
Yes
output
1
51,925
0
103,851
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have N strings of lowercase English letters: S_1, S_2, \cdots, S_N. Takahashi wants to make a string that is a palindrome by choosing one or more of these strings - the same string can be chosen more than once - and concatenating them in some order of his choice. The cost of using the string S_i once is C_i, and the cost of using it multiple times is C_i multiplied by that number of times. Find the minimum total cost needed to choose strings so that Takahashi can make a palindrome. If there is no choice of strings in which he can make a palindrome, print -1. Constraints * 1 \leq N \leq 50 * 1 \leq |S_i| \leq 20 * S_i consists of lowercase English letters. * 1 \leq C_i \leq 10^9 Input Input is given from Standard Input in the following format: N S_1 C_1 S_2 C_2 : S_N C_N Output Print the minimum total cost needed to choose strings so that Takahashi can make a palindrome, or -1 if there is no such choice. Examples Input 3 ba 3 abc 4 cbaa 5 Output 7 Input 2 abcab 5 cba 3 Output 11 Input 4 ab 5 cba 3 a 12 ab 10 Output 8 Input 2 abc 1 ab 2 Output -1 Submitted Solution: ``` class Dijkstra(): class Edge(): def __init__(self, _to, _cost): self.to = _to self.cost = _cost def __init__(self, V): self.G = [[] for i in range(V)] self._E = 0 self._V = V @property def E(self): return self._E @property def V(self): return self._V def add(self, _from, _to, _cost): self.G[_from].append(self.Edge(_to, _cost)) self._E += 1 def shortest_path(self, start): import heapq que = [] d = [float("inf")] * self.V for s in start: d[s]=0 heapq.heappush(que, (0, s)) while len(que) != 0: cost, v = heapq.heappop(que) if d[v] < cost: continue for i in range(len(self.G[v])): e = self.G[v][i] if d[e.to] > d[v] + e.cost: d[e.to] = d[v] + e.cost heapq.heappush(que, (d[e.to], e.to)) return d N=int(input()) string=[] for i in range(N): s,c=input().split() string.append((s,int(c))) node=[(0,""),(1,"")] for s,c in string: for j in range(len(s)): node.append((0,s[j:])) for j in range(len(s)-1,-1,-1): node.append((1,s[:j+1])) node=list(set(node)) iddata={i:e for e,i in enumerate(node)} n=len(iddata) edge=[[] for i in range(n)] for i in range(n): if node[i][0]==0: S=node[i][1] for s,c in string: if len(s)<=len(S): check=all(S[j]==s[-j-1] for j in range(len(s))) if check: if len(s)==len(S): next_node=(0,"") else: next_node=(0,S[len(s):]) next_id=iddata[next_node] edge[i].append((next_id,c)) else: check=all(S[j]==s[-j-1] for j in range(len(S))) if check: if len(s)==len(S): next_node=(1,"") else: next_node=(1,s[:len(s)-len(S)]) next_id=iddata[next_node] edge[i].append((next_id,c)) else: S=node[i][1] for s,c in string: if len(s)<=len(S): check=all(s[j]==S[-j-1] for j in range(len(s))) if check: if len(s)==len(S): next_node=(1,"") else: next_node=(1,S[:len(S)-len(s)]) next_id=iddata[next_node] edge[i].append((next_id,c)) else: check=all(s[j]==S[-j-1] for j in range(len(S))) if check: if len(s)==len(S): next_node=(0,"") else: next_node=(0,s[len(S):]) next_id=iddata[next_node] edge[i].append((next_id,c)) palindrome=Dijkstra(n+1) for i in range(n): for j,c in edge[i]: palindrome.add(j,i,c) start=[] for i in range(n): s=node[i][1] if len(s)==0: start.append(i) else: check=all(s[j]==s[-1-j] for j in range(len(s))) if check: start.append(i) for s,c in string: id=iddata[0,s] palindrome.add(id,n,c) id=iddata[1,s] palindrome.add(id,n,c) res=palindrome.shortest_path(start) ans=res[n] #print(list(map(lambda x:node[x],start))) #for i in range(n): #if node[i][1]=="abc": #print(node[i]) #print(list(map(lambda x:(node[x[0]],x[1]),edge[i]))) if ans!=float("inf"): print(ans) else: print(-1) ```
instruction
0
51,926
0
103,852
Yes
output
1
51,926
0
103,853
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have N strings of lowercase English letters: S_1, S_2, \cdots, S_N. Takahashi wants to make a string that is a palindrome by choosing one or more of these strings - the same string can be chosen more than once - and concatenating them in some order of his choice. The cost of using the string S_i once is C_i, and the cost of using it multiple times is C_i multiplied by that number of times. Find the minimum total cost needed to choose strings so that Takahashi can make a palindrome. If there is no choice of strings in which he can make a palindrome, print -1. Constraints * 1 \leq N \leq 50 * 1 \leq |S_i| \leq 20 * S_i consists of lowercase English letters. * 1 \leq C_i \leq 10^9 Input Input is given from Standard Input in the following format: N S_1 C_1 S_2 C_2 : S_N C_N Output Print the minimum total cost needed to choose strings so that Takahashi can make a palindrome, or -1 if there is no such choice. Examples Input 3 ba 3 abc 4 cbaa 5 Output 7 Input 2 abcab 5 cba 3 Output 11 Input 4 ab 5 cba 3 a 12 ab 10 Output 8 Input 2 abc 1 ab 2 Output -1 Submitted Solution: ``` from random import randrange from heapq import heapify, heappush, heappop from time import time K = 60 rand = lambda: randrange(1 << K) sTime = time() N = int(input()) S, IS, C = [], [], [] for _ in range(N): s, c = input().split() S.append(s) IS.append(s[::-1]) C.append(int(c)) D = {} done = set() r = rand() D[r] = (0, "", 0) H = [r] ans = 1 << K while H: r = heappop(H) if r in done: continue done.add(r) if time() - sTime > 1.7: break d, s, c = D[r] if d == 0: for ss, cc in zip(S, C): m = min(len(s), len(ss)) if s[:m] == ss[:m]: if abs(len(s) - len(ss)) <= 1 or len(ss) > len(s) and ss[m:] == ss[m:][::-1]: ans = min(ans, c + cc) else: if len(s) < len(ss): r = rand() + (c + cc << K) D[r] = (1, ss[m:], c + cc) heappush(H, r) else: r = rand() + (c + cc << K) D[r] = (0, s[m:], c + cc) heappush(H, r) else: for ss, cc in zip(IS, C): m = min(len(s), len(ss)) if s[:m] == ss[:m]: if abs(len(s) - len(ss)) <= 1 or len(ss) > len(s) and ss[m:] == ss[m:][::-1]: ans = min(ans, c + cc) else: if len(s) < len(ss): r = rand() + (c + cc << K) D[r] = (0, ss[m:], c + cc) heappush(H, r) else: r = rand() + (c + cc << K) D[r] = (1, s[m:], c + cc) heappush(H, r) print(ans if ans < 1 << K - 2 else -1) ```
instruction
0
51,927
0
103,854
Yes
output
1
51,927
0
103,855
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have N strings of lowercase English letters: S_1, S_2, \cdots, S_N. Takahashi wants to make a string that is a palindrome by choosing one or more of these strings - the same string can be chosen more than once - and concatenating them in some order of his choice. The cost of using the string S_i once is C_i, and the cost of using it multiple times is C_i multiplied by that number of times. Find the minimum total cost needed to choose strings so that Takahashi can make a palindrome. If there is no choice of strings in which he can make a palindrome, print -1. Constraints * 1 \leq N \leq 50 * 1 \leq |S_i| \leq 20 * S_i consists of lowercase English letters. * 1 \leq C_i \leq 10^9 Input Input is given from Standard Input in the following format: N S_1 C_1 S_2 C_2 : S_N C_N Output Print the minimum total cost needed to choose strings so that Takahashi can make a palindrome, or -1 if there is no such choice. Examples Input 3 ba 3 abc 4 cbaa 5 Output 7 Input 2 abcab 5 cba 3 Output 11 Input 4 ab 5 cba 3 a 12 ab 10 Output 8 Input 2 abc 1 ab 2 Output -1 Submitted Solution: ``` import sys sys.setrecursionlimit(10 ** 6) int1 = lambda x: int(x) - 1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.readline()) def MI(): return map(int, sys.stdin.readline().split()) def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def SI(): return sys.stdin.readline()[:-1] from heapq import * def solve(): for s, c in sc: for i in range(len(s)): pre = s[:i + 1] suf = s[i:] ll.add(pre[::-1]) ll.add(suf) rr.add(pre) rr.add(suf[::-1]) #print(ll) #print(rr) ln = len(ll) rn = len(rr) ltou = {l: u for u, l in enumerate(ll)} rtou = {r: u + ln for u, r in enumerate(rr)} ispal = [False] * (ln + rn) for l, u in ltou.items(): ispal[u] = l == l[::-1] for r, u in rtou.items(): ispal[u] = r == r[::-1] #print("ltou", ltou) #print("rtou", rtou) to = [[] for _ in range(ln + rn)] for s, c in sc: c = int(c) for l in ll: u = ltou[l] v = -1 if l == s: v = ltou[""] elif l[:len(s)] == s: v = ltou[l[len(s):]] elif l == s[:len(l)]: v = rtou[s[len(l):][::-1]] if v != -1: to[u].append((v, c)) for r in rr: u = rtou[r] v = -1 if r == s: v = ltou[""] elif r[-len(s):] == s: v = rtou[r[:-len(s)]] elif r == s[-len(r):]: v = ltou[s[:-len(r)][::-1]] if v != -1: to[u].append((v, c)) #print(to) inf = 10 ** 16 dist = [inf] * (ln + rn) hp = [] for s, c in sc: u = rtou[s[::-1]] heappush(hp, (int(c), u)) dist[u] = int(c) while hp: d, u = heappop(hp) if d > dist[u]: continue for v, c in to[u]: if dist[v] <= d + c: continue dist[v] = d + c heappush(hp, (d + c, v)) #print(dist) ans = min(dist[u] for u in range(ln + rn) if ispal[u]) if ans == inf: print(-1) else: print(ans) n = II() sc = [SI().split() for _ in range(n)] ll = set([""]) rr = set() solve() ```
instruction
0
51,928
0
103,856
No
output
1
51,928
0
103,857
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have N strings of lowercase English letters: S_1, S_2, \cdots, S_N. Takahashi wants to make a string that is a palindrome by choosing one or more of these strings - the same string can be chosen more than once - and concatenating them in some order of his choice. The cost of using the string S_i once is C_i, and the cost of using it multiple times is C_i multiplied by that number of times. Find the minimum total cost needed to choose strings so that Takahashi can make a palindrome. If there is no choice of strings in which he can make a palindrome, print -1. Constraints * 1 \leq N \leq 50 * 1 \leq |S_i| \leq 20 * S_i consists of lowercase English letters. * 1 \leq C_i \leq 10^9 Input Input is given from Standard Input in the following format: N S_1 C_1 S_2 C_2 : S_N C_N Output Print the minimum total cost needed to choose strings so that Takahashi can make a palindrome, or -1 if there is no such choice. Examples Input 3 ba 3 abc 4 cbaa 5 Output 7 Input 2 abcab 5 cba 3 Output 11 Input 4 ab 5 cba 3 a 12 ab 10 Output 8 Input 2 abc 1 ab 2 Output -1 Submitted Solution: ``` import sys input = sys.stdin.readline N=int(input()) ST=[input().split() for i in range(N)] for i in range(N): ST[i][1]=int(ST[i][1]) ST.sort() ST2=[] for i in range(N): if i>0 and ST[i][0]==ST[i-1][0]: continue ST2.append((ST[i][0],ST[i][1])) ST=ST2 FDICT=dict() BDICT=dict() for s,i in ST: FDICT[s[::-1]]=i BDICT[s[::-1]]=i for j in range(1,len(s)): if not(s[:j][::-1] in BDICT): BDICT[s[:j][::-1]]=1<<60 if not(s[-j:][::-1] in FDICT): FDICT[s[-j:][::-1]]=1<<60 ANS=1<<100 for rep in range(2100): for f in FDICT: lf=len(f) for s,i in ST: ls=len(s) if lf == ls: if s==f: ANS=min(ANS,FDICT[f]+i) elif ls>lf: if s[-lf:]==f: BDICT[s[:-lf][::-1]]=min(BDICT[s[:-lf][::-1]],FDICT[f]+i) else: if f[-ls:]==s: FDICT[f[:-ls]]=min(FDICT[f[:-ls]],FDICT[f]+i) for b in BDICT: lb=len(b) for s,i in ST: ls=len(s) if lb == ls: if s==b: ANS=min(ANS,BDICT[b]+i) elif ls>lb: if s[:lb]==b: FDICT[s[-lb:][::-1]]=min(FDICT[s[-lb:][::-1]],BDICT[b]+i) else: if b[:ls]==s: BDICT[b[ls:]]=min(BDICT[b[ls:]],BDICT[b]+i) for f in FDICT: if f==f[::-1]: ANS=min(ANS,FDICT[f]) for b in BDICT: if b==b[::-1]: ANS=min(ANS,BDICT[b]) if ANS==1<<60: print(-1) else: print(ANS) ```
instruction
0
51,929
0
103,858
No
output
1
51,929
0
103,859
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have N strings of lowercase English letters: S_1, S_2, \cdots, S_N. Takahashi wants to make a string that is a palindrome by choosing one or more of these strings - the same string can be chosen more than once - and concatenating them in some order of his choice. The cost of using the string S_i once is C_i, and the cost of using it multiple times is C_i multiplied by that number of times. Find the minimum total cost needed to choose strings so that Takahashi can make a palindrome. If there is no choice of strings in which he can make a palindrome, print -1. Constraints * 1 \leq N \leq 50 * 1 \leq |S_i| \leq 20 * S_i consists of lowercase English letters. * 1 \leq C_i \leq 10^9 Input Input is given from Standard Input in the following format: N S_1 C_1 S_2 C_2 : S_N C_N Output Print the minimum total cost needed to choose strings so that Takahashi can make a palindrome, or -1 if there is no such choice. Examples Input 3 ba 3 abc 4 cbaa 5 Output 7 Input 2 abcab 5 cba 3 Output 11 Input 4 ab 5 cba 3 a 12 ab 10 Output 8 Input 2 abc 1 ab 2 Output -1 Submitted Solution: ``` import heapq import copy n = int(input()) original = [] for _ in range(n): s,c = input().split();c=int(c) original.append((c,s)) heapq.heapify(original) hp = copy.deepcopy(original) flag = 0 answer = 0 while not len(hp)==0: #print(hp) if flag: break c_temp,s_temp = heapq.heappop(hp) if len(s_temp)==1: flag = 1 answer = c_temp else: for c,s in original: if len(s_temp)==len(s): if s_temp == s[::-1]: flag = 1 answer = c_temp+c elif len(s_temp) > len(s): if s_temp[:len(s)]==s[::-1]: heapq.heappush(hp,(c_temp+c,s_temp[:len(s)])) else: if s_temp == s[::-1][:len(s_temp)]: heapq.heappush(hp,(c_temp+c,s[:len(s)-len(s_temp)])) if flag: print(answer) else: print(-1) ```
instruction
0
51,930
0
103,860
No
output
1
51,930
0
103,861
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have N strings of lowercase English letters: S_1, S_2, \cdots, S_N. Takahashi wants to make a string that is a palindrome by choosing one or more of these strings - the same string can be chosen more than once - and concatenating them in some order of his choice. The cost of using the string S_i once is C_i, and the cost of using it multiple times is C_i multiplied by that number of times. Find the minimum total cost needed to choose strings so that Takahashi can make a palindrome. If there is no choice of strings in which he can make a palindrome, print -1. Constraints * 1 \leq N \leq 50 * 1 \leq |S_i| \leq 20 * S_i consists of lowercase English letters. * 1 \leq C_i \leq 10^9 Input Input is given from Standard Input in the following format: N S_1 C_1 S_2 C_2 : S_N C_N Output Print the minimum total cost needed to choose strings so that Takahashi can make a palindrome, or -1 if there is no such choice. Examples Input 3 ba 3 abc 4 cbaa 5 Output 7 Input 2 abcab 5 cba 3 Output 11 Input 4 ab 5 cba 3 a 12 ab 10 Output 8 Input 2 abc 1 ab 2 Output -1 Submitted Solution: ``` from heapq import heappush, heappop from collections import defaultdict import sys def input(): return sys.stdin.readline()[:-1] def is_palindrome(x): m = len(x) for i in range(m//2): if x[i] != x[m-1-i]: return False return True INF = 10**18 n = int(input()) adj = defaultdict(list) dp = defaultdict(lambda: INF) dp["S"] = 0 #start: "S", goal: "T" S = [] T = [] for _ in range(n): s, c = input().split() c = int(c) S.append((s, c)) T.append((s[::-1], c)) adj["S"].append((s, c)) for s, _ in S: for y in range(1, len(s)+1): pre = s[:y] if is_palindrome(pre): adj[pre].append(("T", 0)) else: for t, c in T: if y > len(t): if pre[-len(t):] == t: adj[pre].append((pre[:-len(t)], c)) elif y < len(t): if pre == t[-y:]: adj[pre].append((t[:-y][::-1], c)) else: if pre == t: adj[pre].append(("T", c)) suf = s[-y:] if is_palindrome(suf): adj[suf].append(("T", 0)) else: for t, c in T: if y > len(t): if suf[:len(t)] == t: adj[suf].append((suf[len(t):], c)) elif y < len(t): if suf == t[:y]: adj[suf].append((t[y:][::-1], c)) else: if suf == t: adj[suf].append(("T", c)) que = [(0, "S")] while que and que[0][1] != "T": tmp, s = heappop(que) dp[s] = tmp for t, c in adj[s]: if dp[t] > tmp+c: heappush(que, (tmp+c, t)) if que: print(que[0][0]) else: print(-1) ```
instruction
0
51,931
0
103,862
No
output
1
51,931
0
103,863
Provide a correct Python 3 solution for this coding contest problem. You are given a string $S$, which is balanced parentheses with a star symbol '*' inserted. Any balanced parentheses can be constructed using the following rules: * An empty string is balanced. * Concatenation of two balanced parentheses is balanced. * If $T$ is balanced parentheses, concatenation of '(', $T$, and ')' in this order is balanced. For example, '()()' and '(()())' are balanced parentheses. ')(' and ')()(()' are not balanced parentheses. Your task is to count how many matching pairs of parentheses surround the star. Let $S_i$be the $i$-th character of a string $S$. The pair of $S_l$ and $S_r$ ($l < r$) is called a matching pair of parentheses if $S_l$ is '(', $S_r$ is ')' and the surrounded string by them is balanced when ignoring a star symbol. Input The input consists of a single test case formatted as follows. $S$ $S$ is balanced parentheses with exactly one '*' inserted somewhere. The length of $S$ is between 1 and 100, inclusive. Output Print the answer in one line. Examples Input ((*)()) Output 2 Input (*) Output 1 Input (()())* Output 0 Input ()*() Output 0 Input ((((((((((*)))))))))) Output 10 Input * Output 0
instruction
0
52,148
0
104,296
"Correct Solution: ``` S = list(input()) S_l = len(S) n=0 l = [] r = [] f_l, f_r = 0,0 for n in range(S.index('*')): if S[n]== '(': f_l += 1 elif S[n]== ')': f_l -= 1 for n in range(S_l - S.index('*')): if S[S_l-n-1] == ')': f_r += 1 elif S[S_l-n-1]== '(': f_r -= 1 print(min(f_r, f_l)) ```
output
1
52,148
0
104,297
Provide a correct Python 3 solution for this coding contest problem. You are given a string $S$, which is balanced parentheses with a star symbol '*' inserted. Any balanced parentheses can be constructed using the following rules: * An empty string is balanced. * Concatenation of two balanced parentheses is balanced. * If $T$ is balanced parentheses, concatenation of '(', $T$, and ')' in this order is balanced. For example, '()()' and '(()())' are balanced parentheses. ')(' and ')()(()' are not balanced parentheses. Your task is to count how many matching pairs of parentheses surround the star. Let $S_i$be the $i$-th character of a string $S$. The pair of $S_l$ and $S_r$ ($l < r$) is called a matching pair of parentheses if $S_l$ is '(', $S_r$ is ')' and the surrounded string by them is balanced when ignoring a star symbol. Input The input consists of a single test case formatted as follows. $S$ $S$ is balanced parentheses with exactly one '*' inserted somewhere. The length of $S$ is between 1 and 100, inclusive. Output Print the answer in one line. Examples Input ((*)()) Output 2 Input (*) Output 1 Input (()())* Output 0 Input ()*() Output 0 Input ((((((((((*)))))))))) Output 10 Input * Output 0
instruction
0
52,149
0
104,298
"Correct Solution: ``` S=list(input()) N=S.index('*') P=abs(S[0:N].count('(')-S[0:N].count(')')) Q=abs(S[N+1:len(S)].count('(')-S[N+1:len(S)].count(')')) print(min(P,Q)) ```
output
1
52,149
0
104,299
Provide a correct Python 3 solution for this coding contest problem. You are given a string $S$, which is balanced parentheses with a star symbol '*' inserted. Any balanced parentheses can be constructed using the following rules: * An empty string is balanced. * Concatenation of two balanced parentheses is balanced. * If $T$ is balanced parentheses, concatenation of '(', $T$, and ')' in this order is balanced. For example, '()()' and '(()())' are balanced parentheses. ')(' and ')()(()' are not balanced parentheses. Your task is to count how many matching pairs of parentheses surround the star. Let $S_i$be the $i$-th character of a string $S$. The pair of $S_l$ and $S_r$ ($l < r$) is called a matching pair of parentheses if $S_l$ is '(', $S_r$ is ')' and the surrounded string by them is balanced when ignoring a star symbol. Input The input consists of a single test case formatted as follows. $S$ $S$ is balanced parentheses with exactly one '*' inserted somewhere. The length of $S$ is between 1 and 100, inclusive. Output Print the answer in one line. Examples Input ((*)()) Output 2 Input (*) Output 1 Input (()())* Output 0 Input ()*() Output 0 Input ((((((((((*)))))))))) Output 10 Input * Output 0
instruction
0
52,150
0
104,300
"Correct Solution: ``` s = input() while '()' in s: s = s.replace('()', '') else: print(s.count('(')) ```
output
1
52,150
0
104,301
Provide a correct Python 3 solution for this coding contest problem. You are given a string $S$, which is balanced parentheses with a star symbol '*' inserted. Any balanced parentheses can be constructed using the following rules: * An empty string is balanced. * Concatenation of two balanced parentheses is balanced. * If $T$ is balanced parentheses, concatenation of '(', $T$, and ')' in this order is balanced. For example, '()()' and '(()())' are balanced parentheses. ')(' and ')()(()' are not balanced parentheses. Your task is to count how many matching pairs of parentheses surround the star. Let $S_i$be the $i$-th character of a string $S$. The pair of $S_l$ and $S_r$ ($l < r$) is called a matching pair of parentheses if $S_l$ is '(', $S_r$ is ')' and the surrounded string by them is balanced when ignoring a star symbol. Input The input consists of a single test case formatted as follows. $S$ $S$ is balanced parentheses with exactly one '*' inserted somewhere. The length of $S$ is between 1 and 100, inclusive. Output Print the answer in one line. Examples Input ((*)()) Output 2 Input (*) Output 1 Input (()())* Output 0 Input ()*() Output 0 Input ((((((((((*)))))))))) Output 10 Input * Output 0
instruction
0
52,151
0
104,302
"Correct Solution: ``` S = input() n = 0 ans = 0 for i in S: if i == "(": n += 1 elif i == ")": n -= 1 else: print (n) break ```
output
1
52,151
0
104,303
Provide a correct Python 3 solution for this coding contest problem. You are given a string $S$, which is balanced parentheses with a star symbol '*' inserted. Any balanced parentheses can be constructed using the following rules: * An empty string is balanced. * Concatenation of two balanced parentheses is balanced. * If $T$ is balanced parentheses, concatenation of '(', $T$, and ')' in this order is balanced. For example, '()()' and '(()())' are balanced parentheses. ')(' and ')()(()' are not balanced parentheses. Your task is to count how many matching pairs of parentheses surround the star. Let $S_i$be the $i$-th character of a string $S$. The pair of $S_l$ and $S_r$ ($l < r$) is called a matching pair of parentheses if $S_l$ is '(', $S_r$ is ')' and the surrounded string by them is balanced when ignoring a star symbol. Input The input consists of a single test case formatted as follows. $S$ $S$ is balanced parentheses with exactly one '*' inserted somewhere. The length of $S$ is between 1 and 100, inclusive. Output Print the answer in one line. Examples Input ((*)()) Output 2 Input (*) Output 1 Input (()())* Output 0 Input ()*() Output 0 Input ((((((((((*)))))))))) Output 10 Input * Output 0
instruction
0
52,153
0
104,306
"Correct Solution: ``` s=input() ans=0 for i in range(len(s)): if s[i]=="*": break elif s[i]=="(": ans+=1 else: ans-=1 print(ans) ```
output
1
52,153
0
104,307
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,822
0
105,644
"Correct Solution: ``` def sa_naive(s): n = len(s) sa = list(range(n)) sa.sort(key=lambda x: s[x:]) return sa 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 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 sa_naive(s) if n < 100: return 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 = 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 def suffix_array(s): n = len(s) s2 = [ord(c) for c in s] return sa_is(s2, 255) def lcp_array(s, sa): n = len(s) #assert n >= 1 s2 = [ord(c) for c in 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 def z_algorithm(s): n = len(s) s2 = [ord(c) for c in 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() sa = suffix_array(S) res = len(S) * (len(S) + 1) // 2 - sum(lcp_array(S, sa)) print(res) ```
output
1
52,822
0
105,645
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,823
0
105,646
"Correct Solution: ``` def sa_naive(s): n = len(s) sa = list(range(n)) sa.sort(key=lambda x: s[x:]) return sa 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 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 < 135: return sa_naive(s) if n < 45: return 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 = 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 def suffix_array(s): n = len(s) s2 = [ord(c) for c in s] return sa_is(s2, 255) def lcp_array(s, sa): n = len(s) #assert n >= 1 s2 = [ord(c) for c in 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 def z_algorithm(s): n = len(s) s2 = [ord(c) for c in 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() sa = suffix_array(S) res = len(S) * (len(S) + 1) // 2 - sum(lcp_array(S, sa)) print(res) ```
output
1
52,823
0
105,647
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,824
0
105,648
"Correct Solution: ``` # # https://github.com/not522/ac-library-python/blob/master/atcoder/string.py 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 s = input() sa = suffix_array(s) answer = len(s) * (len(s) + 1) // 2 for x in lcp_array(s, sa): answer -= x print(answer) ```
output
1
52,824
0
105,649