message stringlengths 2 23.4k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 129 108k | cluster float64 6 6 | __index_level_0__ int64 258 216k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Nam is playing with a string on his computer. The string consists of n lowercase English letters. It is meaningless, so Nam decided to make the string more beautiful, that is to make it be a palindrome by using 4 arrow keys: left, right, up, down.
There is a cursor pointing at some symbol of the string. Suppose that cursor is at position i (1 β€ i β€ n, the string uses 1-based indexing) now. Left and right arrow keys are used to move cursor around the string. The string is cyclic, that means that when Nam presses left arrow key, the cursor will move to position i - 1 if i > 1 or to the end of the string (i. e. position n) otherwise. The same holds when he presses the right arrow key (if i = n, the cursor appears at the beginning of the string).
When Nam presses up arrow key, the letter which the text cursor is pointing to will change to the next letter in English alphabet (assuming that alphabet is also cyclic, i. e. after 'z' follows 'a'). The same holds when he presses the down arrow key.
Initially, the text cursor is at position p.
Because Nam has a lot homework to do, he wants to complete this as fast as possible. Can you help him by calculating the minimum number of arrow keys presses to make the string to be a palindrome?
Input
The first line contains two space-separated integers n (1 β€ n β€ 105) and p (1 β€ p β€ n), the length of Nam's string and the initial position of the text cursor.
The next line contains n lowercase characters of Nam's string.
Output
Print the minimum number of presses needed to change string into a palindrome.
Examples
Input
8 3
aeabcaez
Output
6
Note
A string is a palindrome if it reads the same forward or reversed.
In the sample test, initial Nam's string is: <image> (cursor position is shown bold).
In optimal solution, Nam may do 6 following steps:
<image>
The result, <image>, is now a palindrome. | instruction | 0 | 70,201 | 6 | 140,402 |
Tags: brute force, greedy, implementation
Correct Solution:
```
n , p = map(int,input().split())
string = input()
def palindrome_transformer(string,n,p):#1 base indexing is p
if n % 2 == 0:
s_1 = string[0:int(n/2)]
s_2 = string[int(n/2):len(string)]
s_1_reversed = ""
for numbers in range(int(len(string)/2)-1,-1,-1):
s_1_reversed += s_1[numbers]
score = 0
different_elements = [] #0 means no and 1 means yes
for i in range(len(s_1)):
if abs(ord(s_1_reversed[i]) - ord(s_2[i])) > 12:
score += 26 - abs(ord(s_1_reversed[i]) - ord(s_2[i]))
different_elements.append(1)
else:
if abs(ord(s_1_reversed[i]) - ord(s_2[i])) == 0:
different_elements.append(0)
else:
different_elements.append(1)
score += abs(ord(s_1_reversed[i]) - ord(s_2[i]))
if p <= int(len(string)/2):
different_elements.reverse()
start = 1
for elements in different_elements:
if elements ==1:
break
else:
start +=1
different_elements.reverse()
end = int(len(string)/2)
for elements in different_elements:
if elements ==1:
break
else:
end -=1
if start == int(len(string)/2) +1 and end ==0 :
return 0
score += max(p,end) - min(start,p) + min(max(end - p,0),max(p-start,0))
else:
p -= int(len(string)/2)
start = 1
for elements in different_elements:
if elements == 1:
break
else:
start += 1
different_elements.reverse()
end = int(len(string) / 2)
for elements in different_elements:
if elements == 1:
break
else:
end -= 1
if start == int(len(string) / 2) + 1 and end == 0:
return 0
score += max(p, end) - min(start, p) + min(max(end - p, 0), max(p - start, 0))
return score
if n % 2 == 1 :
string_new = ""
for i in range(len(string)):
if i == int(len(string) /2 ):
continue
else:
string_new += string[i]
if p > int(n/2):
p-=1
return palindrome_transformer(string_new,n-1,p)
elif p == int(n/2):
return palindrome_transformer(string_new,n-1,p)
else:
return palindrome_transformer(string_new, n - 1, p)
print(palindrome_transformer(string,n,p))
``` | output | 1 | 70,201 | 6 | 140,403 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nam is playing with a string on his computer. The string consists of n lowercase English letters. It is meaningless, so Nam decided to make the string more beautiful, that is to make it be a palindrome by using 4 arrow keys: left, right, up, down.
There is a cursor pointing at some symbol of the string. Suppose that cursor is at position i (1 β€ i β€ n, the string uses 1-based indexing) now. Left and right arrow keys are used to move cursor around the string. The string is cyclic, that means that when Nam presses left arrow key, the cursor will move to position i - 1 if i > 1 or to the end of the string (i. e. position n) otherwise. The same holds when he presses the right arrow key (if i = n, the cursor appears at the beginning of the string).
When Nam presses up arrow key, the letter which the text cursor is pointing to will change to the next letter in English alphabet (assuming that alphabet is also cyclic, i. e. after 'z' follows 'a'). The same holds when he presses the down arrow key.
Initially, the text cursor is at position p.
Because Nam has a lot homework to do, he wants to complete this as fast as possible. Can you help him by calculating the minimum number of arrow keys presses to make the string to be a palindrome?
Input
The first line contains two space-separated integers n (1 β€ n β€ 105) and p (1 β€ p β€ n), the length of Nam's string and the initial position of the text cursor.
The next line contains n lowercase characters of Nam's string.
Output
Print the minimum number of presses needed to change string into a palindrome.
Examples
Input
8 3
aeabcaez
Output
6
Note
A string is a palindrome if it reads the same forward or reversed.
In the sample test, initial Nam's string is: <image> (cursor position is shown bold).
In optimal solution, Nam may do 6 following steps:
<image>
The result, <image>, is now a palindrome. | instruction | 0 | 70,202 | 6 | 140,404 |
Tags: brute force, greedy, implementation
Correct Solution:
```
n, p = map(int, input().split())
s = list(map(ord, input()))
if p > n//2:
p = n - p
else:
p -= 1
l = n // 2
r = -1
ans = 0
for i in range(n//2):
d = abs(s[i]-s[n-i-1])
d = min(d, 26 - d)
if d:
l = min(l, i)
r = max(r, i)
ans += d
print(ans + r - l + min(abs(r-p), abs(l-p)) if ans else 0)
``` | output | 1 | 70,202 | 6 | 140,405 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Genos recently installed the game Zuma on his phone. In Zuma there exists a line of n gemstones, the i-th of which has color ci. The goal of the game is to destroy all the gemstones in the line as quickly as possible.
In one second, Genos is able to choose exactly one continuous substring of colored gemstones that is a palindrome and remove it from the line. After the substring is removed, the remaining gemstones shift to form a solid line again. What is the minimum number of seconds needed to destroy the entire line?
Let us remind, that the string (or substring) is called palindrome, if it reads same backwards or forward. In our case this means the color of the first gemstone is equal to the color of the last one, the color of the second gemstone is equal to the color of the next to last and so on.
Input
The first line of input contains a single integer n (1 β€ n β€ 500) β the number of gemstones.
The second line contains n space-separated integers, the i-th of which is ci (1 β€ ci β€ n) β the color of the i-th gemstone in a line.
Output
Print a single integer β the minimum number of seconds needed to destroy the entire line.
Examples
Input
3
1 2 1
Output
1
Input
3
1 2 3
Output
3
Input
7
1 4 4 2 3 2 1
Output
2
Note
In the first sample, Genos can destroy the entire line in one second.
In the second sample, Genos can only destroy one gemstone at a time, so destroying three gemstones takes three seconds.
In the third sample, to achieve the optimal time of two seconds, destroy palindrome 4 4 first and then destroy palindrome 1 2 3 2 1. | instruction | 0 | 70,260 | 6 | 140,520 |
Tags: dp
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
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")
# ------------------------------
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
# ------------------------------
def main():
n = N()
arr = RLL()
dp = [[n]*n for _ in range(n)]
for i in range(n): dp[i][i] = 1
for le in range(2, n+1):
for l in range(n):
r = l+le-1
if r>=n: break
if le==2:
if arr[l]==arr[r]: dp[l][r] = 1
else: dp[l][r] = 2
else:
for m in range(l, r):
dp[l][r] = min(dp[l][r], dp[l][m]+dp[m+1][r])
if arr[l]==arr[r]:
dp[l][r] = min(dp[l+1][r-1], dp[l][r])
print(dp[0][-1])
if __name__ == "__main__":
main()
``` | output | 1 | 70,260 | 6 | 140,521 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Limak is a little polar bear. Polar bears hate long strings and thus they like to compress them. You should also know that Limak is so young that he knows only first six letters of the English alphabet: 'a', 'b', 'c', 'd', 'e' and 'f'.
You are given a set of q possible operations. Limak can perform them in any order, any operation may be applied any number of times. The i-th operation is described by a string ai of length two and a string bi of length one. No two of q possible operations have the same string ai.
When Limak has a string s he can perform the i-th operation on s if the first two letters of s match a two-letter string ai. Performing the i-th operation removes first two letters of s and inserts there a string bi. See the notes section for further clarification.
You may note that performing an operation decreases the length of a string s exactly by 1. Also, for some sets of operations there may be a string that cannot be compressed any further, because the first two letters don't match any ai.
Limak wants to start with a string of length n and perform n - 1 operations to finally get a one-letter string "a". In how many ways can he choose the starting string to be able to get "a"? Remember that Limak can use only letters he knows.
Input
The first line contains two integers n and q (2 β€ n β€ 6, 1 β€ q β€ 36) β the length of the initial string and the number of available operations.
The next q lines describe the possible operations. The i-th of them contains two strings ai and bi (|ai| = 2, |bi| = 1). It's guaranteed that ai β aj for i β j and that all ai and bi consist of only first six lowercase English letters.
Output
Print the number of strings of length n that Limak will be able to transform to string "a" by applying only operations given in the input.
Examples
Input
3 5
ab a
cc c
ca a
ee c
ff d
Output
4
Input
2 8
af e
dc d
cc f
bc b
da b
eb a
bb b
ff c
Output
1
Input
6 2
bb a
ba a
Output
0
Note
In the first sample, we count initial strings of length 3 from which Limak can get a required string "a". There are 4 such strings: "abb", "cab", "cca", "eea". The first one Limak can compress using operation 1 two times (changing "ab" to a single "a"). The first operation would change "abb" to "ab" and the second operation would change "ab" to "a".
Other three strings may be compressed as follows:
* "cab" <image> "ab" <image> "a"
* "cca" <image> "ca" <image> "a"
* "eea" <image> "ca" <image> "a"
In the second sample, the only correct initial string is "eb" because it can be immediately compressed to "a". | instruction | 0 | 70,292 | 6 | 140,584 |
Tags: brute force, dfs and similar, dp, strings
Correct Solution:
```
from itertools import product
#n = int(input().strip())
n, q = map(int, input().strip().split())
dic = {}
for i in range(q):
a, b = input().strip().split()
dic[a] = b
count = 0
for i in product('abcdef', repeat = n):
s = ''.join(i)
for j in range(n-1):
if s[:1] == 'g':
break
s = dic.get(s[:2], 'g') + s[2:]
if s == 'a':
count += 1
print(count)
``` | output | 1 | 70,292 | 6 | 140,585 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Limak is a little polar bear. Polar bears hate long strings and thus they like to compress them. You should also know that Limak is so young that he knows only first six letters of the English alphabet: 'a', 'b', 'c', 'd', 'e' and 'f'.
You are given a set of q possible operations. Limak can perform them in any order, any operation may be applied any number of times. The i-th operation is described by a string ai of length two and a string bi of length one. No two of q possible operations have the same string ai.
When Limak has a string s he can perform the i-th operation on s if the first two letters of s match a two-letter string ai. Performing the i-th operation removes first two letters of s and inserts there a string bi. See the notes section for further clarification.
You may note that performing an operation decreases the length of a string s exactly by 1. Also, for some sets of operations there may be a string that cannot be compressed any further, because the first two letters don't match any ai.
Limak wants to start with a string of length n and perform n - 1 operations to finally get a one-letter string "a". In how many ways can he choose the starting string to be able to get "a"? Remember that Limak can use only letters he knows.
Input
The first line contains two integers n and q (2 β€ n β€ 6, 1 β€ q β€ 36) β the length of the initial string and the number of available operations.
The next q lines describe the possible operations. The i-th of them contains two strings ai and bi (|ai| = 2, |bi| = 1). It's guaranteed that ai β aj for i β j and that all ai and bi consist of only first six lowercase English letters.
Output
Print the number of strings of length n that Limak will be able to transform to string "a" by applying only operations given in the input.
Examples
Input
3 5
ab a
cc c
ca a
ee c
ff d
Output
4
Input
2 8
af e
dc d
cc f
bc b
da b
eb a
bb b
ff c
Output
1
Input
6 2
bb a
ba a
Output
0
Note
In the first sample, we count initial strings of length 3 from which Limak can get a required string "a". There are 4 such strings: "abb", "cab", "cca", "eea". The first one Limak can compress using operation 1 two times (changing "ab" to a single "a"). The first operation would change "abb" to "ab" and the second operation would change "ab" to "a".
Other three strings may be compressed as follows:
* "cab" <image> "ab" <image> "a"
* "cca" <image> "ca" <image> "a"
* "eea" <image> "ca" <image> "a"
In the second sample, the only correct initial string is "eb" because it can be immediately compressed to "a". | instruction | 0 | 70,293 | 6 | 140,586 |
Tags: brute force, dfs and similar, dp, strings
Correct Solution:
```
n, q = map(int, input().split())
fr = dict()
for i in range(q):
a, b = input().split()
if b in fr:
fr[b].append(a)
else:
fr[b] = [a]
def dfs(c, cnt):
global n
if cnt == n:
return 1
if cnt > n:
return 0
global fr
if c not in fr:
return 0
ans = 0
for i in fr[c]:
ans += dfs(i[0], cnt+1)
return ans
print(dfs('a', 1))
``` | output | 1 | 70,293 | 6 | 140,587 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Limak is a little polar bear. Polar bears hate long strings and thus they like to compress them. You should also know that Limak is so young that he knows only first six letters of the English alphabet: 'a', 'b', 'c', 'd', 'e' and 'f'.
You are given a set of q possible operations. Limak can perform them in any order, any operation may be applied any number of times. The i-th operation is described by a string ai of length two and a string bi of length one. No two of q possible operations have the same string ai.
When Limak has a string s he can perform the i-th operation on s if the first two letters of s match a two-letter string ai. Performing the i-th operation removes first two letters of s and inserts there a string bi. See the notes section for further clarification.
You may note that performing an operation decreases the length of a string s exactly by 1. Also, for some sets of operations there may be a string that cannot be compressed any further, because the first two letters don't match any ai.
Limak wants to start with a string of length n and perform n - 1 operations to finally get a one-letter string "a". In how many ways can he choose the starting string to be able to get "a"? Remember that Limak can use only letters he knows.
Input
The first line contains two integers n and q (2 β€ n β€ 6, 1 β€ q β€ 36) β the length of the initial string and the number of available operations.
The next q lines describe the possible operations. The i-th of them contains two strings ai and bi (|ai| = 2, |bi| = 1). It's guaranteed that ai β aj for i β j and that all ai and bi consist of only first six lowercase English letters.
Output
Print the number of strings of length n that Limak will be able to transform to string "a" by applying only operations given in the input.
Examples
Input
3 5
ab a
cc c
ca a
ee c
ff d
Output
4
Input
2 8
af e
dc d
cc f
bc b
da b
eb a
bb b
ff c
Output
1
Input
6 2
bb a
ba a
Output
0
Note
In the first sample, we count initial strings of length 3 from which Limak can get a required string "a". There are 4 such strings: "abb", "cab", "cca", "eea". The first one Limak can compress using operation 1 two times (changing "ab" to a single "a"). The first operation would change "abb" to "ab" and the second operation would change "ab" to "a".
Other three strings may be compressed as follows:
* "cab" <image> "ab" <image> "a"
* "cca" <image> "ca" <image> "a"
* "eea" <image> "ca" <image> "a"
In the second sample, the only correct initial string is "eb" because it can be immediately compressed to "a". | instruction | 0 | 70,294 | 6 | 140,588 |
Tags: brute force, dfs and similar, dp, strings
Correct Solution:
```
n, m = map(int, input().split())
d = {}
for i in range(m):
t, o = input().split()
if o in d:
d[o].append(t)
else:
d[o] = [t]
q = [('a', 0)]
cnt = 0
while q and q[0][1] < n :
st = q[0]
q.pop(0)
if st[1] == n - 1:
cnt += 1
if st[0][0] in d:
for j in d[st[0][0]]:
q.append((j + st[0][1:], st[1] + 1))
print(cnt)
``` | output | 1 | 70,294 | 6 | 140,589 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Limak is a little polar bear. Polar bears hate long strings and thus they like to compress them. You should also know that Limak is so young that he knows only first six letters of the English alphabet: 'a', 'b', 'c', 'd', 'e' and 'f'.
You are given a set of q possible operations. Limak can perform them in any order, any operation may be applied any number of times. The i-th operation is described by a string ai of length two and a string bi of length one. No two of q possible operations have the same string ai.
When Limak has a string s he can perform the i-th operation on s if the first two letters of s match a two-letter string ai. Performing the i-th operation removes first two letters of s and inserts there a string bi. See the notes section for further clarification.
You may note that performing an operation decreases the length of a string s exactly by 1. Also, for some sets of operations there may be a string that cannot be compressed any further, because the first two letters don't match any ai.
Limak wants to start with a string of length n and perform n - 1 operations to finally get a one-letter string "a". In how many ways can he choose the starting string to be able to get "a"? Remember that Limak can use only letters he knows.
Input
The first line contains two integers n and q (2 β€ n β€ 6, 1 β€ q β€ 36) β the length of the initial string and the number of available operations.
The next q lines describe the possible operations. The i-th of them contains two strings ai and bi (|ai| = 2, |bi| = 1). It's guaranteed that ai β aj for i β j and that all ai and bi consist of only first six lowercase English letters.
Output
Print the number of strings of length n that Limak will be able to transform to string "a" by applying only operations given in the input.
Examples
Input
3 5
ab a
cc c
ca a
ee c
ff d
Output
4
Input
2 8
af e
dc d
cc f
bc b
da b
eb a
bb b
ff c
Output
1
Input
6 2
bb a
ba a
Output
0
Note
In the first sample, we count initial strings of length 3 from which Limak can get a required string "a". There are 4 such strings: "abb", "cab", "cca", "eea". The first one Limak can compress using operation 1 two times (changing "ab" to a single "a"). The first operation would change "abb" to "ab" and the second operation would change "ab" to "a".
Other three strings may be compressed as follows:
* "cab" <image> "ab" <image> "a"
* "cca" <image> "ca" <image> "a"
* "eea" <image> "ca" <image> "a"
In the second sample, the only correct initial string is "eb" because it can be immediately compressed to "a". | instruction | 0 | 70,295 | 6 | 140,590 |
Tags: brute force, dfs and similar, dp, strings
Correct Solution:
```
n,q=map(int,input().split())
d={i:""for i in "abcdef"}
for i in range(q):
a,b=input().split()
d[b]+=a[0]
cur=d['a']
for i in range(n-2):
nwcur=""
for j in cur:nwcur+=d[j]
cur=nwcur
print(len(cur))
``` | output | 1 | 70,295 | 6 | 140,591 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Limak is a little polar bear. Polar bears hate long strings and thus they like to compress them. You should also know that Limak is so young that he knows only first six letters of the English alphabet: 'a', 'b', 'c', 'd', 'e' and 'f'.
You are given a set of q possible operations. Limak can perform them in any order, any operation may be applied any number of times. The i-th operation is described by a string ai of length two and a string bi of length one. No two of q possible operations have the same string ai.
When Limak has a string s he can perform the i-th operation on s if the first two letters of s match a two-letter string ai. Performing the i-th operation removes first two letters of s and inserts there a string bi. See the notes section for further clarification.
You may note that performing an operation decreases the length of a string s exactly by 1. Also, for some sets of operations there may be a string that cannot be compressed any further, because the first two letters don't match any ai.
Limak wants to start with a string of length n and perform n - 1 operations to finally get a one-letter string "a". In how many ways can he choose the starting string to be able to get "a"? Remember that Limak can use only letters he knows.
Input
The first line contains two integers n and q (2 β€ n β€ 6, 1 β€ q β€ 36) β the length of the initial string and the number of available operations.
The next q lines describe the possible operations. The i-th of them contains two strings ai and bi (|ai| = 2, |bi| = 1). It's guaranteed that ai β aj for i β j and that all ai and bi consist of only first six lowercase English letters.
Output
Print the number of strings of length n that Limak will be able to transform to string "a" by applying only operations given in the input.
Examples
Input
3 5
ab a
cc c
ca a
ee c
ff d
Output
4
Input
2 8
af e
dc d
cc f
bc b
da b
eb a
bb b
ff c
Output
1
Input
6 2
bb a
ba a
Output
0
Note
In the first sample, we count initial strings of length 3 from which Limak can get a required string "a". There are 4 such strings: "abb", "cab", "cca", "eea". The first one Limak can compress using operation 1 two times (changing "ab" to a single "a"). The first operation would change "abb" to "ab" and the second operation would change "ab" to "a".
Other three strings may be compressed as follows:
* "cab" <image> "ab" <image> "a"
* "cca" <image> "ca" <image> "a"
* "eea" <image> "ca" <image> "a"
In the second sample, the only correct initial string is "eb" because it can be immediately compressed to "a". | instruction | 0 | 70,296 | 6 | 140,592 |
Tags: brute force, dfs and similar, dp, strings
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
from itertools import combinations_with_replacement,permutations
# region fastio
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 = 'abcdef'
letters = list(s)
n,m = list(map(int,input().split()))
mp = {}
for i in range(m):
x,red = list(map(str,input().split()))
mp[x] = red
combo = list(combinations_with_replacement(letters,n))
perm = []
for i in combo:
perm+=list(permutations(list(i)))
all_words = []
for i in perm:
x = ''.join(str(x) for x in i)
all_words.append(x)
unique = set()
for i in all_words:
flag = 0
cur = i[0]
for j in range(1,len(i)):
two = cur+i[j]
if two in mp:
cur = mp[two]
else:
flag = 1
break
if flag==0 and cur=='a':
unique.add(i)
print(len(unique))
``` | output | 1 | 70,296 | 6 | 140,593 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Limak is a little polar bear. Polar bears hate long strings and thus they like to compress them. You should also know that Limak is so young that he knows only first six letters of the English alphabet: 'a', 'b', 'c', 'd', 'e' and 'f'.
You are given a set of q possible operations. Limak can perform them in any order, any operation may be applied any number of times. The i-th operation is described by a string ai of length two and a string bi of length one. No two of q possible operations have the same string ai.
When Limak has a string s he can perform the i-th operation on s if the first two letters of s match a two-letter string ai. Performing the i-th operation removes first two letters of s and inserts there a string bi. See the notes section for further clarification.
You may note that performing an operation decreases the length of a string s exactly by 1. Also, for some sets of operations there may be a string that cannot be compressed any further, because the first two letters don't match any ai.
Limak wants to start with a string of length n and perform n - 1 operations to finally get a one-letter string "a". In how many ways can he choose the starting string to be able to get "a"? Remember that Limak can use only letters he knows.
Input
The first line contains two integers n and q (2 β€ n β€ 6, 1 β€ q β€ 36) β the length of the initial string and the number of available operations.
The next q lines describe the possible operations. The i-th of them contains two strings ai and bi (|ai| = 2, |bi| = 1). It's guaranteed that ai β aj for i β j and that all ai and bi consist of only first six lowercase English letters.
Output
Print the number of strings of length n that Limak will be able to transform to string "a" by applying only operations given in the input.
Examples
Input
3 5
ab a
cc c
ca a
ee c
ff d
Output
4
Input
2 8
af e
dc d
cc f
bc b
da b
eb a
bb b
ff c
Output
1
Input
6 2
bb a
ba a
Output
0
Note
In the first sample, we count initial strings of length 3 from which Limak can get a required string "a". There are 4 such strings: "abb", "cab", "cca", "eea". The first one Limak can compress using operation 1 two times (changing "ab" to a single "a"). The first operation would change "abb" to "ab" and the second operation would change "ab" to "a".
Other three strings may be compressed as follows:
* "cab" <image> "ab" <image> "a"
* "cca" <image> "ca" <image> "a"
* "eea" <image> "ca" <image> "a"
In the second sample, the only correct initial string is "eb" because it can be immediately compressed to "a". | instruction | 0 | 70,297 | 6 | 140,594 |
Tags: brute force, dfs and similar, dp, strings
Correct Solution:
```
n,k = map(int,input().split())
l = {}
cnt = 0
for i in range(k):
a,b = input().split()
l[a] = b;
if n==2:
print(list(l.values()).count('a'))
exit(0)
def allcombs(s,prefix,l):
global cnt
if l==0:
if (check(prefix)):
cnt+=1
return
for i in s:
allcombs(s,prefix+i,l-1)
def check(s):
while len(s)>1:
yes = False
if s[:2] in l:
s = l[s[:2]] + s[2:]
yes = True
if not yes:
return False
if s=='a':
return True
else:
return False
allcombs(['a','b','c','d','e','f'],"",n)
print(cnt)
``` | output | 1 | 70,297 | 6 | 140,595 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Limak is a little polar bear. Polar bears hate long strings and thus they like to compress them. You should also know that Limak is so young that he knows only first six letters of the English alphabet: 'a', 'b', 'c', 'd', 'e' and 'f'.
You are given a set of q possible operations. Limak can perform them in any order, any operation may be applied any number of times. The i-th operation is described by a string ai of length two and a string bi of length one. No two of q possible operations have the same string ai.
When Limak has a string s he can perform the i-th operation on s if the first two letters of s match a two-letter string ai. Performing the i-th operation removes first two letters of s and inserts there a string bi. See the notes section for further clarification.
You may note that performing an operation decreases the length of a string s exactly by 1. Also, for some sets of operations there may be a string that cannot be compressed any further, because the first two letters don't match any ai.
Limak wants to start with a string of length n and perform n - 1 operations to finally get a one-letter string "a". In how many ways can he choose the starting string to be able to get "a"? Remember that Limak can use only letters he knows.
Input
The first line contains two integers n and q (2 β€ n β€ 6, 1 β€ q β€ 36) β the length of the initial string and the number of available operations.
The next q lines describe the possible operations. The i-th of them contains two strings ai and bi (|ai| = 2, |bi| = 1). It's guaranteed that ai β aj for i β j and that all ai and bi consist of only first six lowercase English letters.
Output
Print the number of strings of length n that Limak will be able to transform to string "a" by applying only operations given in the input.
Examples
Input
3 5
ab a
cc c
ca a
ee c
ff d
Output
4
Input
2 8
af e
dc d
cc f
bc b
da b
eb a
bb b
ff c
Output
1
Input
6 2
bb a
ba a
Output
0
Note
In the first sample, we count initial strings of length 3 from which Limak can get a required string "a". There are 4 such strings: "abb", "cab", "cca", "eea". The first one Limak can compress using operation 1 two times (changing "ab" to a single "a"). The first operation would change "abb" to "ab" and the second operation would change "ab" to "a".
Other three strings may be compressed as follows:
* "cab" <image> "ab" <image> "a"
* "cca" <image> "ca" <image> "a"
* "eea" <image> "ca" <image> "a"
In the second sample, the only correct initial string is "eb" because it can be immediately compressed to "a". | instruction | 0 | 70,298 | 6 | 140,596 |
Tags: brute force, dfs and similar, dp, strings
Correct Solution:
```
n,q=map(int,input().split())
d={}
ch=set()
ans=set()
for i in range(q):
a,b=input().split()
d.setdefault(b,set()).add(a)
ch={"a"}
while ch!=set():
b=ch.pop()
if len(b)==n: ans.add(b); continue
for a in d.setdefault(b[0],set()):
ch.add(''.join((a,b[1:])))
print(len(ans))
``` | output | 1 | 70,298 | 6 | 140,597 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Limak is a little polar bear. Polar bears hate long strings and thus they like to compress them. You should also know that Limak is so young that he knows only first six letters of the English alphabet: 'a', 'b', 'c', 'd', 'e' and 'f'.
You are given a set of q possible operations. Limak can perform them in any order, any operation may be applied any number of times. The i-th operation is described by a string ai of length two and a string bi of length one. No two of q possible operations have the same string ai.
When Limak has a string s he can perform the i-th operation on s if the first two letters of s match a two-letter string ai. Performing the i-th operation removes first two letters of s and inserts there a string bi. See the notes section for further clarification.
You may note that performing an operation decreases the length of a string s exactly by 1. Also, for some sets of operations there may be a string that cannot be compressed any further, because the first two letters don't match any ai.
Limak wants to start with a string of length n and perform n - 1 operations to finally get a one-letter string "a". In how many ways can he choose the starting string to be able to get "a"? Remember that Limak can use only letters he knows.
Input
The first line contains two integers n and q (2 β€ n β€ 6, 1 β€ q β€ 36) β the length of the initial string and the number of available operations.
The next q lines describe the possible operations. The i-th of them contains two strings ai and bi (|ai| = 2, |bi| = 1). It's guaranteed that ai β aj for i β j and that all ai and bi consist of only first six lowercase English letters.
Output
Print the number of strings of length n that Limak will be able to transform to string "a" by applying only operations given in the input.
Examples
Input
3 5
ab a
cc c
ca a
ee c
ff d
Output
4
Input
2 8
af e
dc d
cc f
bc b
da b
eb a
bb b
ff c
Output
1
Input
6 2
bb a
ba a
Output
0
Note
In the first sample, we count initial strings of length 3 from which Limak can get a required string "a". There are 4 such strings: "abb", "cab", "cca", "eea". The first one Limak can compress using operation 1 two times (changing "ab" to a single "a"). The first operation would change "abb" to "ab" and the second operation would change "ab" to "a".
Other three strings may be compressed as follows:
* "cab" <image> "ab" <image> "a"
* "cca" <image> "ca" <image> "a"
* "eea" <image> "ca" <image> "a"
In the second sample, the only correct initial string is "eb" because it can be immediately compressed to "a". | instruction | 0 | 70,299 | 6 | 140,598 |
Tags: brute force, dfs and similar, dp, strings
Correct Solution:
```
n, m = map(int, input().split())
mp = dict()
for _ in range(m):
a, b = input().split()
mp[a] = b;
from itertools import product
count = 0
for t in product('abcdef', repeat=n) :
s = ''.join(t)
for _ in range(n - 1):
s = mp.get(s[:2], 'g') + s[2:];
if (s=='a'):
count += 1
print(count)
``` | output | 1 | 70,299 | 6 | 140,599 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Modern text editors usually show some information regarding the document being edited. For example, the number of words, the number of pages, or the number of characters.
In this problem you should implement the similar functionality.
You are given a string which only consists of:
* uppercase and lowercase English letters,
* underscore symbols (they are used as separators),
* parentheses (both opening and closing).
It is guaranteed that each opening parenthesis has a succeeding closing parenthesis. Similarly, each closing parentheses has a preceding opening parentheses matching it. For each pair of matching parentheses there are no other parenthesis between them. In other words, each parenthesis in the string belongs to a matching "opening-closing" pair, and such pairs can't be nested.
For example, the following string is valid: "_Hello_Vasya(and_Petya)__bye_(and_OK)".
Word is a maximal sequence of consecutive letters, i.e. such sequence that the first character to the left and the first character to the right of it is an underscore, a parenthesis, or it just does not exist. For example, the string above consists of seven words: "Hello", "Vasya", "and", "Petya", "bye", "and" and "OK". Write a program that finds:
* the length of the longest word outside the parentheses (print 0, if there is no word outside the parentheses),
* the number of words inside the parentheses (print 0, if there is no word inside the parentheses).
Input
The first line of the input contains a single integer n (1 β€ n β€ 255) β the length of the given string. The second line contains the string consisting of only lowercase and uppercase English letters, parentheses and underscore symbols.
Output
Print two space-separated integers:
* the length of the longest word outside the parentheses (print 0, if there is no word outside the parentheses),
* the number of words inside the parentheses (print 0, if there is no word inside the parentheses).
Examples
Input
37
_Hello_Vasya(and_Petya)__bye_(and_OK)
Output
5 4
Input
37
_a_(_b___c)__de_f(g_)__h__i(j_k_l)m__
Output
2 6
Input
27
(LoooonG)__shOrt__(LoooonG)
Output
5 2
Input
5
(___)
Output
0 0
Note
In the first sample, the words "Hello", "Vasya" and "bye" are outside any of the parentheses, and the words "and", "Petya", "and" and "OK" are inside. Note, that the word "and" is given twice and you should count it twice in the answer. | instruction | 0 | 70,328 | 6 | 140,656 |
Tags: expression parsing, implementation, strings
Correct Solution:
```
n = int(input())
s = input()
ib = 0; mx = 0; foo = 0
for i in range(n):
if s[i]=='(':
k = i
while s[k]!=')':
if (s[k]=='(' or s[k]=='_') and (s[k+1]!=')' and s[k+1]!='_'): ib += 1
k += 1
for i in range(n):
if s[i]=='(':
k=i+1
while s[k]!=')':
k += 1
s = s.replace(s[i:k+1], len(s[i:k+1])*'_')
s += '_'
for i in range(n+1):
if s[i] != '_': mx += 1
else:
foo = max(mx, foo)
mx = 0
print(foo, ib)
``` | output | 1 | 70,328 | 6 | 140,657 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Modern text editors usually show some information regarding the document being edited. For example, the number of words, the number of pages, or the number of characters.
In this problem you should implement the similar functionality.
You are given a string which only consists of:
* uppercase and lowercase English letters,
* underscore symbols (they are used as separators),
* parentheses (both opening and closing).
It is guaranteed that each opening parenthesis has a succeeding closing parenthesis. Similarly, each closing parentheses has a preceding opening parentheses matching it. For each pair of matching parentheses there are no other parenthesis between them. In other words, each parenthesis in the string belongs to a matching "opening-closing" pair, and such pairs can't be nested.
For example, the following string is valid: "_Hello_Vasya(and_Petya)__bye_(and_OK)".
Word is a maximal sequence of consecutive letters, i.e. such sequence that the first character to the left and the first character to the right of it is an underscore, a parenthesis, or it just does not exist. For example, the string above consists of seven words: "Hello", "Vasya", "and", "Petya", "bye", "and" and "OK". Write a program that finds:
* the length of the longest word outside the parentheses (print 0, if there is no word outside the parentheses),
* the number of words inside the parentheses (print 0, if there is no word inside the parentheses).
Input
The first line of the input contains a single integer n (1 β€ n β€ 255) β the length of the given string. The second line contains the string consisting of only lowercase and uppercase English letters, parentheses and underscore symbols.
Output
Print two space-separated integers:
* the length of the longest word outside the parentheses (print 0, if there is no word outside the parentheses),
* the number of words inside the parentheses (print 0, if there is no word inside the parentheses).
Examples
Input
37
_Hello_Vasya(and_Petya)__bye_(and_OK)
Output
5 4
Input
37
_a_(_b___c)__de_f(g_)__h__i(j_k_l)m__
Output
2 6
Input
27
(LoooonG)__shOrt__(LoooonG)
Output
5 2
Input
5
(___)
Output
0 0
Note
In the first sample, the words "Hello", "Vasya" and "bye" are outside any of the parentheses, and the words "and", "Petya", "and" and "OK" are inside. Note, that the word "and" is given twice and you should count it twice in the answer. | instruction | 0 | 70,329 | 6 | 140,658 |
Tags: expression parsing, implementation, strings
Correct Solution:
```
n = int(input())
len_out, count_in = 0, 0
balance, cur = 0, 0
for c in input():
if not (('a' <= c <= 'z') or ('A' <= c <= 'Z')) and cur:
if balance:
count_in += 1
else:
len_out = max(len_out, cur)
cur = 0
if c == '(':
balance += 1
elif c == ')':
balance -= 1
elif ('a' <= c <= 'z') or ('A' <= c <= 'Z'):
cur += 1
if cur:
len_out = max(len_out, cur)
print(len_out, count_in)
``` | output | 1 | 70,329 | 6 | 140,659 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Modern text editors usually show some information regarding the document being edited. For example, the number of words, the number of pages, or the number of characters.
In this problem you should implement the similar functionality.
You are given a string which only consists of:
* uppercase and lowercase English letters,
* underscore symbols (they are used as separators),
* parentheses (both opening and closing).
It is guaranteed that each opening parenthesis has a succeeding closing parenthesis. Similarly, each closing parentheses has a preceding opening parentheses matching it. For each pair of matching parentheses there are no other parenthesis between them. In other words, each parenthesis in the string belongs to a matching "opening-closing" pair, and such pairs can't be nested.
For example, the following string is valid: "_Hello_Vasya(and_Petya)__bye_(and_OK)".
Word is a maximal sequence of consecutive letters, i.e. such sequence that the first character to the left and the first character to the right of it is an underscore, a parenthesis, or it just does not exist. For example, the string above consists of seven words: "Hello", "Vasya", "and", "Petya", "bye", "and" and "OK". Write a program that finds:
* the length of the longest word outside the parentheses (print 0, if there is no word outside the parentheses),
* the number of words inside the parentheses (print 0, if there is no word inside the parentheses).
Input
The first line of the input contains a single integer n (1 β€ n β€ 255) β the length of the given string. The second line contains the string consisting of only lowercase and uppercase English letters, parentheses and underscore symbols.
Output
Print two space-separated integers:
* the length of the longest word outside the parentheses (print 0, if there is no word outside the parentheses),
* the number of words inside the parentheses (print 0, if there is no word inside the parentheses).
Examples
Input
37
_Hello_Vasya(and_Petya)__bye_(and_OK)
Output
5 4
Input
37
_a_(_b___c)__de_f(g_)__h__i(j_k_l)m__
Output
2 6
Input
27
(LoooonG)__shOrt__(LoooonG)
Output
5 2
Input
5
(___)
Output
0 0
Note
In the first sample, the words "Hello", "Vasya" and "bye" are outside any of the parentheses, and the words "and", "Petya", "and" and "OK" are inside. Note, that the word "and" is given twice and you should count it twice in the answer. | instruction | 0 | 70,330 | 6 | 140,660 |
Tags: expression parsing, implementation, strings
Correct Solution:
```
n=int(input())
text= input()[:n]
# words_with_paren=input().split('_')
len_long_word_out=0
numb_words_in_paren=0
if '(' in text:
open_ind = [i for i, x in enumerate(text) if x == "("]
close_ind= [i for i, x in enumerate(text) if x == ")"]
for (i,offset) in enumerate(open_ind):
tmp=text[offset+1:close_ind[i]]
numb_words_in_paren+=len(list(filter(None,tmp.split('_'))))
begin=0
for (i, offset) in enumerate(open_ind):
substr=text[begin:offset].split('_')
for word in filter(None,substr):
if len(word)>len_long_word_out:
len_long_word_out=len(word)
begin=close_ind[i]+1
if begin < len(text):
for word in text[begin:].split('_'):
if len(word)>len_long_word_out:
len_long_word_out=len(word)
else:
words=text.split('_')
for word in filter(None,words):
if len(word) > len_long_word_out:
len_long_word_out=len(word)
print("%d %d" %(len_long_word_out,numb_words_in_paren))
``` | output | 1 | 70,330 | 6 | 140,661 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Modern text editors usually show some information regarding the document being edited. For example, the number of words, the number of pages, or the number of characters.
In this problem you should implement the similar functionality.
You are given a string which only consists of:
* uppercase and lowercase English letters,
* underscore symbols (they are used as separators),
* parentheses (both opening and closing).
It is guaranteed that each opening parenthesis has a succeeding closing parenthesis. Similarly, each closing parentheses has a preceding opening parentheses matching it. For each pair of matching parentheses there are no other parenthesis between them. In other words, each parenthesis in the string belongs to a matching "opening-closing" pair, and such pairs can't be nested.
For example, the following string is valid: "_Hello_Vasya(and_Petya)__bye_(and_OK)".
Word is a maximal sequence of consecutive letters, i.e. such sequence that the first character to the left and the first character to the right of it is an underscore, a parenthesis, or it just does not exist. For example, the string above consists of seven words: "Hello", "Vasya", "and", "Petya", "bye", "and" and "OK". Write a program that finds:
* the length of the longest word outside the parentheses (print 0, if there is no word outside the parentheses),
* the number of words inside the parentheses (print 0, if there is no word inside the parentheses).
Input
The first line of the input contains a single integer n (1 β€ n β€ 255) β the length of the given string. The second line contains the string consisting of only lowercase and uppercase English letters, parentheses and underscore symbols.
Output
Print two space-separated integers:
* the length of the longest word outside the parentheses (print 0, if there is no word outside the parentheses),
* the number of words inside the parentheses (print 0, if there is no word inside the parentheses).
Examples
Input
37
_Hello_Vasya(and_Petya)__bye_(and_OK)
Output
5 4
Input
37
_a_(_b___c)__de_f(g_)__h__i(j_k_l)m__
Output
2 6
Input
27
(LoooonG)__shOrt__(LoooonG)
Output
5 2
Input
5
(___)
Output
0 0
Note
In the first sample, the words "Hello", "Vasya" and "bye" are outside any of the parentheses, and the words "and", "Petya", "and" and "OK" are inside. Note, that the word "and" is given twice and you should count it twice in the answer. | instruction | 0 | 70,331 | 6 | 140,662 |
Tags: expression parsing, implementation, strings
Correct Solution:
```
from string import ascii_lowercase
n = int(input())
s = input()
wordsLen = 0
wordsInside = 0
flagInside = False
currWord = ""
for i in range(n):
if(s[i]=='_'):
currWord = ""
continue
elif(s[i]=='('):
currWord = ""
flagInside = True
elif(s[i]==')'):
currWord = ""
flagInside = False
elif s[i].lower() in ascii_lowercase:
currWord+=s[i]
if i+1<n:
if s[i+1]=='_' or s[i+1]==')' or s[i+1]=='(':
if flagInside:
wordsInside+=1
else:
wordsLen = max(wordsLen, len(currWord))
if s[n-1].lower() in ascii_lowercase:
wordsLen = max(wordsLen, len(currWord))
print(wordsLen, wordsInside)
``` | output | 1 | 70,331 | 6 | 140,663 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Modern text editors usually show some information regarding the document being edited. For example, the number of words, the number of pages, or the number of characters.
In this problem you should implement the similar functionality.
You are given a string which only consists of:
* uppercase and lowercase English letters,
* underscore symbols (they are used as separators),
* parentheses (both opening and closing).
It is guaranteed that each opening parenthesis has a succeeding closing parenthesis. Similarly, each closing parentheses has a preceding opening parentheses matching it. For each pair of matching parentheses there are no other parenthesis between them. In other words, each parenthesis in the string belongs to a matching "opening-closing" pair, and such pairs can't be nested.
For example, the following string is valid: "_Hello_Vasya(and_Petya)__bye_(and_OK)".
Word is a maximal sequence of consecutive letters, i.e. such sequence that the first character to the left and the first character to the right of it is an underscore, a parenthesis, or it just does not exist. For example, the string above consists of seven words: "Hello", "Vasya", "and", "Petya", "bye", "and" and "OK". Write a program that finds:
* the length of the longest word outside the parentheses (print 0, if there is no word outside the parentheses),
* the number of words inside the parentheses (print 0, if there is no word inside the parentheses).
Input
The first line of the input contains a single integer n (1 β€ n β€ 255) β the length of the given string. The second line contains the string consisting of only lowercase and uppercase English letters, parentheses and underscore symbols.
Output
Print two space-separated integers:
* the length of the longest word outside the parentheses (print 0, if there is no word outside the parentheses),
* the number of words inside the parentheses (print 0, if there is no word inside the parentheses).
Examples
Input
37
_Hello_Vasya(and_Petya)__bye_(and_OK)
Output
5 4
Input
37
_a_(_b___c)__de_f(g_)__h__i(j_k_l)m__
Output
2 6
Input
27
(LoooonG)__shOrt__(LoooonG)
Output
5 2
Input
5
(___)
Output
0 0
Note
In the first sample, the words "Hello", "Vasya" and "bye" are outside any of the parentheses, and the words "and", "Petya", "and" and "OK" are inside. Note, that the word "and" is given twice and you should count it twice in the answer. | instruction | 0 | 70,332 | 6 | 140,664 |
Tags: expression parsing, implementation, strings
Correct Solution:
```
import math,sys,re,itertools,pprint
ri,rai=lambda:int(input()),lambda:list(map(int, input().split()))
n = ri()
s = input()
out = True
w = 0
r1, r2 = 0, 0
for c in s:
if c in '_()':
if w > 0 and not out:
r2 += 1
w = 0
else:
w += 1
if out:
r1 = max(r1, w)
if c == '(':
out = False
if c == ')':
out = True
print(r1, r2)
``` | output | 1 | 70,332 | 6 | 140,665 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Modern text editors usually show some information regarding the document being edited. For example, the number of words, the number of pages, or the number of characters.
In this problem you should implement the similar functionality.
You are given a string which only consists of:
* uppercase and lowercase English letters,
* underscore symbols (they are used as separators),
* parentheses (both opening and closing).
It is guaranteed that each opening parenthesis has a succeeding closing parenthesis. Similarly, each closing parentheses has a preceding opening parentheses matching it. For each pair of matching parentheses there are no other parenthesis between them. In other words, each parenthesis in the string belongs to a matching "opening-closing" pair, and such pairs can't be nested.
For example, the following string is valid: "_Hello_Vasya(and_Petya)__bye_(and_OK)".
Word is a maximal sequence of consecutive letters, i.e. such sequence that the first character to the left and the first character to the right of it is an underscore, a parenthesis, or it just does not exist. For example, the string above consists of seven words: "Hello", "Vasya", "and", "Petya", "bye", "and" and "OK". Write a program that finds:
* the length of the longest word outside the parentheses (print 0, if there is no word outside the parentheses),
* the number of words inside the parentheses (print 0, if there is no word inside the parentheses).
Input
The first line of the input contains a single integer n (1 β€ n β€ 255) β the length of the given string. The second line contains the string consisting of only lowercase and uppercase English letters, parentheses and underscore symbols.
Output
Print two space-separated integers:
* the length of the longest word outside the parentheses (print 0, if there is no word outside the parentheses),
* the number of words inside the parentheses (print 0, if there is no word inside the parentheses).
Examples
Input
37
_Hello_Vasya(and_Petya)__bye_(and_OK)
Output
5 4
Input
37
_a_(_b___c)__de_f(g_)__h__i(j_k_l)m__
Output
2 6
Input
27
(LoooonG)__shOrt__(LoooonG)
Output
5 2
Input
5
(___)
Output
0 0
Note
In the first sample, the words "Hello", "Vasya" and "bye" are outside any of the parentheses, and the words "and", "Petya", "and" and "OK" are inside. Note, that the word "and" is given twice and you should count it twice in the answer. | instruction | 0 | 70,333 | 6 | 140,666 |
Tags: expression parsing, implementation, strings
Correct Solution:
```
n = int(input())
s = input()
s += '_'
skob = 0
cnt = 0
maxL = 0
word = ''
for i in range(len(s)):
cur = s[i]
if cur == '_':
if skob > 0 and len(word) != 0:
cnt += 1
else:
if len(word) != 0:
if len(word) > maxL:
maxL = len(word)
word = ''
elif cur == '(':
if skob == 0:
if len(word) > maxL:
maxL = len(word)
else:
cnt += 1
skob += 1
word = ''
elif cur == ')':
if s[i - 1] != '_' and s[i - 1] != '(':
cnt += 1
word = ''
skob -= 1
else:
word += cur
print(maxL, cnt)
``` | output | 1 | 70,333 | 6 | 140,667 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Modern text editors usually show some information regarding the document being edited. For example, the number of words, the number of pages, or the number of characters.
In this problem you should implement the similar functionality.
You are given a string which only consists of:
* uppercase and lowercase English letters,
* underscore symbols (they are used as separators),
* parentheses (both opening and closing).
It is guaranteed that each opening parenthesis has a succeeding closing parenthesis. Similarly, each closing parentheses has a preceding opening parentheses matching it. For each pair of matching parentheses there are no other parenthesis between them. In other words, each parenthesis in the string belongs to a matching "opening-closing" pair, and such pairs can't be nested.
For example, the following string is valid: "_Hello_Vasya(and_Petya)__bye_(and_OK)".
Word is a maximal sequence of consecutive letters, i.e. such sequence that the first character to the left and the first character to the right of it is an underscore, a parenthesis, or it just does not exist. For example, the string above consists of seven words: "Hello", "Vasya", "and", "Petya", "bye", "and" and "OK". Write a program that finds:
* the length of the longest word outside the parentheses (print 0, if there is no word outside the parentheses),
* the number of words inside the parentheses (print 0, if there is no word inside the parentheses).
Input
The first line of the input contains a single integer n (1 β€ n β€ 255) β the length of the given string. The second line contains the string consisting of only lowercase and uppercase English letters, parentheses and underscore symbols.
Output
Print two space-separated integers:
* the length of the longest word outside the parentheses (print 0, if there is no word outside the parentheses),
* the number of words inside the parentheses (print 0, if there is no word inside the parentheses).
Examples
Input
37
_Hello_Vasya(and_Petya)__bye_(and_OK)
Output
5 4
Input
37
_a_(_b___c)__de_f(g_)__h__i(j_k_l)m__
Output
2 6
Input
27
(LoooonG)__shOrt__(LoooonG)
Output
5 2
Input
5
(___)
Output
0 0
Note
In the first sample, the words "Hello", "Vasya" and "bye" are outside any of the parentheses, and the words "and", "Petya", "and" and "OK" are inside. Note, that the word "and" is given twice and you should count it twice in the answer. | instruction | 0 | 70,334 | 6 | 140,668 |
Tags: expression parsing, implementation, strings
Correct Solution:
```
n = int(input())
s = str(input())
s = s.replace("(", " ( ")
s = s.replace(")", " ) ")
s = s.replace("_", " ")
answer = s.split()
a = 0
b = 0
op = False
for element in answer:
if element == "(":
op = True
elif element == ")":
op = False
else:
if op:
b += 1
else:
a = max(len(element), a)
print(a, b)
``` | output | 1 | 70,334 | 6 | 140,669 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Modern text editors usually show some information regarding the document being edited. For example, the number of words, the number of pages, or the number of characters.
In this problem you should implement the similar functionality.
You are given a string which only consists of:
* uppercase and lowercase English letters,
* underscore symbols (they are used as separators),
* parentheses (both opening and closing).
It is guaranteed that each opening parenthesis has a succeeding closing parenthesis. Similarly, each closing parentheses has a preceding opening parentheses matching it. For each pair of matching parentheses there are no other parenthesis between them. In other words, each parenthesis in the string belongs to a matching "opening-closing" pair, and such pairs can't be nested.
For example, the following string is valid: "_Hello_Vasya(and_Petya)__bye_(and_OK)".
Word is a maximal sequence of consecutive letters, i.e. such sequence that the first character to the left and the first character to the right of it is an underscore, a parenthesis, or it just does not exist. For example, the string above consists of seven words: "Hello", "Vasya", "and", "Petya", "bye", "and" and "OK". Write a program that finds:
* the length of the longest word outside the parentheses (print 0, if there is no word outside the parentheses),
* the number of words inside the parentheses (print 0, if there is no word inside the parentheses).
Input
The first line of the input contains a single integer n (1 β€ n β€ 255) β the length of the given string. The second line contains the string consisting of only lowercase and uppercase English letters, parentheses and underscore symbols.
Output
Print two space-separated integers:
* the length of the longest word outside the parentheses (print 0, if there is no word outside the parentheses),
* the number of words inside the parentheses (print 0, if there is no word inside the parentheses).
Examples
Input
37
_Hello_Vasya(and_Petya)__bye_(and_OK)
Output
5 4
Input
37
_a_(_b___c)__de_f(g_)__h__i(j_k_l)m__
Output
2 6
Input
27
(LoooonG)__shOrt__(LoooonG)
Output
5 2
Input
5
(___)
Output
0 0
Note
In the first sample, the words "Hello", "Vasya" and "bye" are outside any of the parentheses, and the words "and", "Petya", "and" and "OK" are inside. Note, that the word "and" is given twice and you should count it twice in the answer. | instruction | 0 | 70,335 | 6 | 140,670 |
Tags: expression parsing, implementation, strings
Correct Solution:
```
litter=input();inside=outside=0
s=input()
i=s.find('(')
while i != -1 :
last = s.find(')')
for j in s[i+1 : last].split('_') :
if j != '':
inside+=1
if i==0:
s=s[last+1:]
else:
s = s[:i]+'_'+s[last+1:]
i=s.find('(')
for i in s.split('_'):
if i!='':
if len(i)> outside :
outside = len(i)
print(outside , inside)
``` | output | 1 | 70,335 | 6 | 140,671 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on.
Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.
Input
The first line of input will be a single string s (1 β€ |s| β€ 50), the word Hongcow initially learns how to spell. The string s consists only of lowercase English letters ('a'β'z').
Output
Output a single integer equal to the number of distinct strings that Hongcow can obtain by applying the cyclic shift arbitrarily many times to the given string.
Examples
Input
abcd
Output
4
Input
bbb
Output
1
Input
yzyz
Output
2
Note
For the first sample, the strings Hongcow can generate are "abcd", "dabc", "cdab", and "bcda".
For the second sample, no matter how many times Hongcow does the cyclic shift, Hongcow can only generate "bbb".
For the third sample, the two strings Hongcow can generate are "yzyz" and "zyzy". | instruction | 0 | 70,344 | 6 | 140,688 |
Tags: implementation, strings
Correct Solution:
```
count={}
str=input()
count[str]=1
l=(len(str))
for i in range(l):
str=str[-1]+str[0:l-1]
count[str]=(count.get(str,0))
print(len(count))
``` | output | 1 | 70,344 | 6 | 140,689 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on.
Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.
Input
The first line of input will be a single string s (1 β€ |s| β€ 50), the word Hongcow initially learns how to spell. The string s consists only of lowercase English letters ('a'β'z').
Output
Output a single integer equal to the number of distinct strings that Hongcow can obtain by applying the cyclic shift arbitrarily many times to the given string.
Examples
Input
abcd
Output
4
Input
bbb
Output
1
Input
yzyz
Output
2
Note
For the first sample, the strings Hongcow can generate are "abcd", "dabc", "cdab", and "bcda".
For the second sample, no matter how many times Hongcow does the cyclic shift, Hongcow can only generate "bbb".
For the third sample, the two strings Hongcow can generate are "yzyz" and "zyzy". | instruction | 0 | 70,345 | 6 | 140,690 |
Tags: implementation, strings
Correct Solution:
```
st = input()
arr = []
for i in range(len(st)):
arr.append(st[i:] + st[:i])
arr = sorted(arr)
cnt = 1
for i in range(1,len(st)):
if(arr[i] != arr[i-1]):
cnt = cnt + 1
print(cnt)
``` | output | 1 | 70,345 | 6 | 140,691 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on.
Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.
Input
The first line of input will be a single string s (1 β€ |s| β€ 50), the word Hongcow initially learns how to spell. The string s consists only of lowercase English letters ('a'β'z').
Output
Output a single integer equal to the number of distinct strings that Hongcow can obtain by applying the cyclic shift arbitrarily many times to the given string.
Examples
Input
abcd
Output
4
Input
bbb
Output
1
Input
yzyz
Output
2
Note
For the first sample, the strings Hongcow can generate are "abcd", "dabc", "cdab", and "bcda".
For the second sample, no matter how many times Hongcow does the cyclic shift, Hongcow can only generate "bbb".
For the third sample, the two strings Hongcow can generate are "yzyz" and "zyzy". | instruction | 0 | 70,346 | 6 | 140,692 |
Tags: implementation, strings
Correct Solution:
```
lis = []
s = input()
for i in range(len(s)):
lis.append(s[i:] + s[:i])
print(len(set(lis)))
``` | output | 1 | 70,346 | 6 | 140,693 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on.
Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.
Input
The first line of input will be a single string s (1 β€ |s| β€ 50), the word Hongcow initially learns how to spell. The string s consists only of lowercase English letters ('a'β'z').
Output
Output a single integer equal to the number of distinct strings that Hongcow can obtain by applying the cyclic shift arbitrarily many times to the given string.
Examples
Input
abcd
Output
4
Input
bbb
Output
1
Input
yzyz
Output
2
Note
For the first sample, the strings Hongcow can generate are "abcd", "dabc", "cdab", and "bcda".
For the second sample, no matter how many times Hongcow does the cyclic shift, Hongcow can only generate "bbb".
For the third sample, the two strings Hongcow can generate are "yzyz" and "zyzy". | instruction | 0 | 70,347 | 6 | 140,694 |
Tags: implementation, strings
Correct Solution:
```
n = input()
l = []
for i in range(len(n)):
l.append(n[i:]+n[:i])
print(len(list(dict.fromkeys(l))))
``` | output | 1 | 70,347 | 6 | 140,695 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on.
Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.
Input
The first line of input will be a single string s (1 β€ |s| β€ 50), the word Hongcow initially learns how to spell. The string s consists only of lowercase English letters ('a'β'z').
Output
Output a single integer equal to the number of distinct strings that Hongcow can obtain by applying the cyclic shift arbitrarily many times to the given string.
Examples
Input
abcd
Output
4
Input
bbb
Output
1
Input
yzyz
Output
2
Note
For the first sample, the strings Hongcow can generate are "abcd", "dabc", "cdab", and "bcda".
For the second sample, no matter how many times Hongcow does the cyclic shift, Hongcow can only generate "bbb".
For the third sample, the two strings Hongcow can generate are "yzyz" and "zyzy". | instruction | 0 | 70,348 | 6 | 140,696 |
Tags: implementation, strings
Correct Solution:
```
s = input()
known = set()
for i in range(len(s)):
p = s[i:]+ s[:i]
known.add(p)
print(len(known))
``` | output | 1 | 70,348 | 6 | 140,697 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on.
Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.
Input
The first line of input will be a single string s (1 β€ |s| β€ 50), the word Hongcow initially learns how to spell. The string s consists only of lowercase English letters ('a'β'z').
Output
Output a single integer equal to the number of distinct strings that Hongcow can obtain by applying the cyclic shift arbitrarily many times to the given string.
Examples
Input
abcd
Output
4
Input
bbb
Output
1
Input
yzyz
Output
2
Note
For the first sample, the strings Hongcow can generate are "abcd", "dabc", "cdab", and "bcda".
For the second sample, no matter how many times Hongcow does the cyclic shift, Hongcow can only generate "bbb".
For the third sample, the two strings Hongcow can generate are "yzyz" and "zyzy". | instruction | 0 | 70,349 | 6 | 140,698 |
Tags: implementation, strings
Correct Solution:
```
s = input()
ss = set()
for i in range(len(s)):
a = s[-1]+s[0:-1]
ss.add(a)
s = a
print(len(ss))
``` | output | 1 | 70,349 | 6 | 140,699 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on.
Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.
Input
The first line of input will be a single string s (1 β€ |s| β€ 50), the word Hongcow initially learns how to spell. The string s consists only of lowercase English letters ('a'β'z').
Output
Output a single integer equal to the number of distinct strings that Hongcow can obtain by applying the cyclic shift arbitrarily many times to the given string.
Examples
Input
abcd
Output
4
Input
bbb
Output
1
Input
yzyz
Output
2
Note
For the first sample, the strings Hongcow can generate are "abcd", "dabc", "cdab", and "bcda".
For the second sample, no matter how many times Hongcow does the cyclic shift, Hongcow can only generate "bbb".
For the third sample, the two strings Hongcow can generate are "yzyz" and "zyzy". | instruction | 0 | 70,350 | 6 | 140,700 |
Tags: implementation, strings
Correct Solution:
```
a=input()
r=['']
for i in range(len(a)):
s=a[len(a)-1]+a[:len(a)-1]
a=s
if a not in r:
r.append(a)
print(len(r)-1)
``` | output | 1 | 70,350 | 6 | 140,701 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on.
Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.
Input
The first line of input will be a single string s (1 β€ |s| β€ 50), the word Hongcow initially learns how to spell. The string s consists only of lowercase English letters ('a'β'z').
Output
Output a single integer equal to the number of distinct strings that Hongcow can obtain by applying the cyclic shift arbitrarily many times to the given string.
Examples
Input
abcd
Output
4
Input
bbb
Output
1
Input
yzyz
Output
2
Note
For the first sample, the strings Hongcow can generate are "abcd", "dabc", "cdab", and "bcda".
For the second sample, no matter how many times Hongcow does the cyclic shift, Hongcow can only generate "bbb".
For the third sample, the two strings Hongcow can generate are "yzyz" and "zyzy". | instruction | 0 | 70,351 | 6 | 140,702 |
Tags: implementation, strings
Correct Solution:
```
a=input()
n=len(a)
lis=[]
lis.append(a)
for i in range(1,n):
newstr=a[i:n]+a[:i]
lis.append(newstr)
set_lis=set(lis)
print(len(set_lis))
``` | output | 1 | 70,351 | 6 | 140,703 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on.
Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.
Input
The first line of input will be a single string s (1 β€ |s| β€ 50), the word Hongcow initially learns how to spell. The string s consists only of lowercase English letters ('a'β'z').
Output
Output a single integer equal to the number of distinct strings that Hongcow can obtain by applying the cyclic shift arbitrarily many times to the given string.
Examples
Input
abcd
Output
4
Input
bbb
Output
1
Input
yzyz
Output
2
Note
For the first sample, the strings Hongcow can generate are "abcd", "dabc", "cdab", and "bcda".
For the second sample, no matter how many times Hongcow does the cyclic shift, Hongcow can only generate "bbb".
For the third sample, the two strings Hongcow can generate are "yzyz" and "zyzy".
Submitted Solution:
```
str=input();
l=len(str);
m={};
for i in range(1,l+1):
ch=str[l-1:l];
st=str[0:l-1];
ch+=st;
if (not(ch in m)):
m[ch]=1;
#print(ch)
str=ch;
print(len(m));
``` | instruction | 0 | 70,352 | 6 | 140,704 |
Yes | output | 1 | 70,352 | 6 | 140,705 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on.
Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.
Input
The first line of input will be a single string s (1 β€ |s| β€ 50), the word Hongcow initially learns how to spell. The string s consists only of lowercase English letters ('a'β'z').
Output
Output a single integer equal to the number of distinct strings that Hongcow can obtain by applying the cyclic shift arbitrarily many times to the given string.
Examples
Input
abcd
Output
4
Input
bbb
Output
1
Input
yzyz
Output
2
Note
For the first sample, the strings Hongcow can generate are "abcd", "dabc", "cdab", and "bcda".
For the second sample, no matter how many times Hongcow does the cyclic shift, Hongcow can only generate "bbb".
For the third sample, the two strings Hongcow can generate are "yzyz" and "zyzy".
Submitted Solution:
```
def rotate(l, n):
return ' '.join(l[n:] + l[:n])
word = list(input())
set_of_words = set()
for i in range(len(word)):
set_of_words.add(rotate(word, i))
print(len(set_of_words))
``` | instruction | 0 | 70,353 | 6 | 140,706 |
Yes | output | 1 | 70,353 | 6 | 140,707 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on.
Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.
Input
The first line of input will be a single string s (1 β€ |s| β€ 50), the word Hongcow initially learns how to spell. The string s consists only of lowercase English letters ('a'β'z').
Output
Output a single integer equal to the number of distinct strings that Hongcow can obtain by applying the cyclic shift arbitrarily many times to the given string.
Examples
Input
abcd
Output
4
Input
bbb
Output
1
Input
yzyz
Output
2
Note
For the first sample, the strings Hongcow can generate are "abcd", "dabc", "cdab", and "bcda".
For the second sample, no matter how many times Hongcow does the cyclic shift, Hongcow can only generate "bbb".
For the third sample, the two strings Hongcow can generate are "yzyz" and "zyzy".
Submitted Solution:
```
s=input()
l=[s]
for i in range(len(s)-1):
s=s[-1]+s[:len(s)-1]
l.append(s)
print(len(set(l)))
``` | instruction | 0 | 70,354 | 6 | 140,708 |
Yes | output | 1 | 70,354 | 6 | 140,709 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on.
Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.
Input
The first line of input will be a single string s (1 β€ |s| β€ 50), the word Hongcow initially learns how to spell. The string s consists only of lowercase English letters ('a'β'z').
Output
Output a single integer equal to the number of distinct strings that Hongcow can obtain by applying the cyclic shift arbitrarily many times to the given string.
Examples
Input
abcd
Output
4
Input
bbb
Output
1
Input
yzyz
Output
2
Note
For the first sample, the strings Hongcow can generate are "abcd", "dabc", "cdab", and "bcda".
For the second sample, no matter how many times Hongcow does the cyclic shift, Hongcow can only generate "bbb".
For the third sample, the two strings Hongcow can generate are "yzyz" and "zyzy".
Submitted Solution:
```
I = lambda: list(map(int, input().split()))
s = input()
for i in range(1, len(s)):
if s[:i]*(len(s)//i)==s:
print(i)
quit()
print(len(s))
``` | instruction | 0 | 70,355 | 6 | 140,710 |
Yes | output | 1 | 70,355 | 6 | 140,711 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on.
Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.
Input
The first line of input will be a single string s (1 β€ |s| β€ 50), the word Hongcow initially learns how to spell. The string s consists only of lowercase English letters ('a'β'z').
Output
Output a single integer equal to the number of distinct strings that Hongcow can obtain by applying the cyclic shift arbitrarily many times to the given string.
Examples
Input
abcd
Output
4
Input
bbb
Output
1
Input
yzyz
Output
2
Note
For the first sample, the strings Hongcow can generate are "abcd", "dabc", "cdab", and "bcda".
For the second sample, no matter how many times Hongcow does the cyclic shift, Hongcow can only generate "bbb".
For the third sample, the two strings Hongcow can generate are "yzyz" and "zyzy".
Submitted Solution:
```
import math
from collections import Counter
from functools import reduce
s = input()
c = Counter(s).most_common()
s1 = [v for k, v in c]
c1 = Counter(s1).most_common()
x = [k for k, v in c1]
gcd = reduce(math.gcd, x)
if gcd < sorted(x)[0] and gcd != 1:
gcd = 1
n = 0
for k, v in c1:
n += (k//gcd)*v
print(n)
``` | instruction | 0 | 70,356 | 6 | 140,712 |
No | output | 1 | 70,356 | 6 | 140,713 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on.
Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.
Input
The first line of input will be a single string s (1 β€ |s| β€ 50), the word Hongcow initially learns how to spell. The string s consists only of lowercase English letters ('a'β'z').
Output
Output a single integer equal to the number of distinct strings that Hongcow can obtain by applying the cyclic shift arbitrarily many times to the given string.
Examples
Input
abcd
Output
4
Input
bbb
Output
1
Input
yzyz
Output
2
Note
For the first sample, the strings Hongcow can generate are "abcd", "dabc", "cdab", and "bcda".
For the second sample, no matter how many times Hongcow does the cyclic shift, Hongcow can only generate "bbb".
For the third sample, the two strings Hongcow can generate are "yzyz" and "zyzy".
Submitted Solution:
```
I = lambda: list(map(int, input().split()))
s = input()
for i in range(1, len(s)):
if s[:i]*(len(s)//i)==s:
print(len(s)//i)
quit()
print(len(s))
``` | instruction | 0 | 70,357 | 6 | 140,714 |
No | output | 1 | 70,357 | 6 | 140,715 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on.
Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.
Input
The first line of input will be a single string s (1 β€ |s| β€ 50), the word Hongcow initially learns how to spell. The string s consists only of lowercase English letters ('a'β'z').
Output
Output a single integer equal to the number of distinct strings that Hongcow can obtain by applying the cyclic shift arbitrarily many times to the given string.
Examples
Input
abcd
Output
4
Input
bbb
Output
1
Input
yzyz
Output
2
Note
For the first sample, the strings Hongcow can generate are "abcd", "dabc", "cdab", and "bcda".
For the second sample, no matter how many times Hongcow does the cyclic shift, Hongcow can only generate "bbb".
For the third sample, the two strings Hongcow can generate are "yzyz" and "zyzy".
Submitted Solution:
```
def distinct(mystr):
if mystr is None:
return 0
st = set(mystr)
return len(st)
print(distinct(str(input())))
``` | instruction | 0 | 70,358 | 6 | 140,716 |
No | output | 1 | 70,358 | 6 | 140,717 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on.
Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.
Input
The first line of input will be a single string s (1 β€ |s| β€ 50), the word Hongcow initially learns how to spell. The string s consists only of lowercase English letters ('a'β'z').
Output
Output a single integer equal to the number of distinct strings that Hongcow can obtain by applying the cyclic shift arbitrarily many times to the given string.
Examples
Input
abcd
Output
4
Input
bbb
Output
1
Input
yzyz
Output
2
Note
For the first sample, the strings Hongcow can generate are "abcd", "dabc", "cdab", and "bcda".
For the second sample, no matter how many times Hongcow does the cyclic shift, Hongcow can only generate "bbb".
For the third sample, the two strings Hongcow can generate are "yzyz" and "zyzy".
Submitted Solution:
```
def main():
# strin = input()
strin = "ysysysysyys"
new = strin
if len(set(list(strin))) == 1:
print(1)
else:
lis = [strin]
for i in range(0,len(strin)-1):
# print(new)
last = new[len(strin)-1]
new = last+new;
new = new[0:len(new)-1]
# new.replace(new[len(new)-1],'')
lis.append(new)
# print("for loop ended",i)
set_s = set(lis)
print(len(set_s))
main()
``` | instruction | 0 | 70,359 | 6 | 140,718 |
No | output | 1 | 70,359 | 6 | 140,719 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.
Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.
Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
Input
The first line contains a non-empty string s, consisting of lowercase Latin letters β that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105.
The next line contains integer k (0 β€ k β€ 13) β the number of forbidden pairs of letters.
Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
Output
Print the single number β the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
Examples
Input
ababa
1
ab
Output
2
Input
codeforces
2
do
cs
Output
1
Note
In the first sample you should remove two letters b.
In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution. | instruction | 0 | 70,993 | 6 | 141,986 |
Tags: greedy
Correct Solution:
```
######################################################
############Created by Devesh Kumar###################
#############devesh1102@gmail.com####################
##########For CodeForces(Devesh1102)#################
#####################2020#############################
######################################################
import sys
input = sys.stdin.readline
# import sys
import heapq
import copy
import math
import decimal
# import sys.stdout.flush as flush
# from decimal import *
#heapq.heapify(li)
#
#heapq.heappush(li,4)
#
#heapq.heappop(li)
#
# & Bitwise AND Operator 10 & 7 = 2
# | Bitwise OR Operator 10 | 7 = 15
# ^ Bitwise XOR Operator 10 ^ 7 = 13
# << Bitwise Left Shift operator 10<<2 = 40
# >> Bitwise Right Shift Operator
# '''############ ---- Input Functions ---- #######Start#####'''
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def insr2():
s = input()
return((s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
############ ---- Input Functions ---- #######End
# #####
def pr_list(a):
print(*a, sep=" ")
def main():
# tests = inp()
tests = 1
mod = 998244353
limit = 10**18
ans = 0
for test in range(tests):
s = insr()
n = len(s)
k = inp()
forbid = [[0 for i in range(26)] for j in range(26)]
for i in range(k):
a = insr()
forbid[ord(a[0]) - ord('a')][ord(a[1]) - ord('a')] = 1
forbid[ord(a[1]) - ord('a')][ord(a[0]) - ord('a')] = 1
dp = [sys.maxsize for i in range(26)]
dp[ord(s[0]) - ord('a')] = 0
for i in range(1,n):
# print(dp)
mini = sys.maxsize
for j in range(26):
if dp[j] != sys.maxsize and forbid[j][ord(s[i]) - ord('a')]!=1:
mini = min(mini,dp[j])
for j in range(26):
if dp[j]!= sys.maxsize:
dp[j] = dp[j] +1
dp[ord(s[i]) - ord('a')] = min(mini,i)
# print(dp)
print(min(dp))
if __name__== "__main__":
main()
``` | output | 1 | 70,993 | 6 | 141,987 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.
Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.
Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
Input
The first line contains a non-empty string s, consisting of lowercase Latin letters β that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105.
The next line contains integer k (0 β€ k β€ 13) β the number of forbidden pairs of letters.
Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
Output
Print the single number β the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
Examples
Input
ababa
1
ab
Output
2
Input
codeforces
2
do
cs
Output
1
Note
In the first sample you should remove two letters b.
In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution. | instruction | 0 | 70,994 | 6 | 141,988 |
Tags: greedy
Correct Solution:
```
import sys
from math import gcd,sqrt,ceil,log2
from collections import defaultdict,Counter,deque
from bisect import bisect_left,bisect_right
import math
import heapq
from itertools import permutations
# input=sys.stdin.readline
# def print(x):
# sys.stdout.write(str(x)+"\n")
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
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")
# import sys
# import io, os
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def get_sum(bit,i):
s = 0
i+=1
while i>0:
s+=bit[i]
i-=i&(-i)
return s
def update(bit,n,i,v):
i+=1
while i<=n:
bit[i]+=v
i+=i&(-i)
def modInverse(b,m):
g = math.gcd(b, m)
if (g != 1):
return -1
else:
return pow(b, m - 2, m)
def primeFactors(n):
sa = set()
sa.add(n)
while n % 2 == 0:
sa.add(2)
n = n // 2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
sa.add(i)
n = n // i
# sa.add(n)
return sa
def seive(n):
pri = [True]*(n+1)
p = 2
while p*p<=n:
if pri[p] == True:
for i in range(p*p,n+1,p):
pri[i] = False
p+=1
return pri
def check_prim(n):
if n<0:
return False
for i in range(2,int(sqrt(n))+1):
if n%i == 0:
return False
return True
def getZarr(string, z):
n = len(string)
# [L,R] make a window which matches
# with prefix of s
l, r, k = 0, 0, 0
for i in range(1, n):
# if i>R nothing matches so we will calculate.
# Z[i] using naive way.
if i > r:
l, r = i, i
# R-L = 0 in starting, so it will start
# checking from 0'th index. For example,
# for "ababab" and i = 1, the value of R
# remains 0 and Z[i] becomes 0. For string
# "aaaaaa" and i = 1, Z[i] and R become 5
while r < n and string[r - l] == string[r]:
r += 1
z[i] = r - l
r -= 1
else:
# k = i-L so k corresponds to number which
# matches in [L,R] interval.
k = i - l
# if Z[k] is less than remaining interval
# then Z[i] will be equal to Z[k].
# For example, str = "ababab", i = 3, R = 5
# and L = 2
if z[k] < r - i + 1:
z[i] = z[k]
# For example str = "aaaaaa" and i = 2,
# R is 5, L is 0
else:
# else start from R and check manually
l = i
while r < n and string[r - l] == string[r]:
r += 1
z[i] = r - l
r -= 1
def search(text, pattern):
# Create concatenated string "P$T"
concat = pattern + "$" + text
l = len(concat)
z = [0] * l
getZarr(concat, z)
ha = []
for i in range(l):
if z[i] == len(pattern):
ha.append(i - len(pattern) - 1)
return ha
# n,k = map(int,input().split())
# l = list(map(int,input().split()))
#
# n = int(input())
# l = list(map(int,input().split()))
#
# hash = defaultdict(list)
# la = []
#
# for i in range(n):
# la.append([l[i],i+1])
#
# la.sort(key = lambda x: (x[0],-x[1]))
# ans = []
# r = n
# flag = 0
# lo = []
# ha = [i for i in range(n,0,-1)]
# yo = []
# for a,b in la:
#
# if a == 1:
# ans.append([r,b])
# # hash[(1,1)].append([b,r])
# lo.append((r,b))
# ha.pop(0)
# yo.append([r,b])
# r-=1
#
# elif a == 2:
# # print(yo,lo)
# # print(hash[1,1])
# if lo == []:
# flag = 1
# break
# c,d = lo.pop(0)
# yo.pop(0)
# if b>=d:
# flag = 1
# break
# ans.append([c,b])
# yo.append([c,b])
#
#
#
# elif a == 3:
#
# if yo == []:
# flag = 1
# break
# c,d = yo.pop(0)
# if b>=d:
# flag = 1
# break
# if ha == []:
# flag = 1
# break
#
# ka = ha.pop(0)
#
# ans.append([ka,b])
# ans.append([ka,d])
# yo.append([ka,b])
#
# if flag:
# print(-1)
# else:
# print(len(ans))
# for a,b in ans:
# print(a,b)
s = input()
n = len(s)
k = int(input())
l = []
for i in range(k):
z = input()
l.append(z)
l.append(z[::-1])
la = []
i = 0
while i<n:
cnt = 0
z = s[i]
while i<n and s[i] == z:
cnt+=1
i+=1
la.append([z,cnt])
ans = 0
if len(la) == 1:
print(0)
exit()
x,y = la[0][0],la[1][0]
cnt1,cnt2 = la[0][1],0
i = 1
while i<len(la):
if la[i][0]!=x and la[i][0]!=y:
if x+y in l:
ans += min(cnt1,cnt2)
i-=1
x,y = la[i][0],la[i+1][0]
cnt1,cnt2 = la[i][1],0
i+=1
else:
if la[i][0]==x:
# print(x,cnt1)
cnt1+=la[i][1]
else:
cnt2+=la[i][1]
i+=1
if x+y in l:
ans += min(cnt1,cnt2)
print(ans)
``` | output | 1 | 70,994 | 6 | 141,989 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.
Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.
Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
Input
The first line contains a non-empty string s, consisting of lowercase Latin letters β that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105.
The next line contains integer k (0 β€ k β€ 13) β the number of forbidden pairs of letters.
Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
Output
Print the single number β the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
Examples
Input
ababa
1
ab
Output
2
Input
codeforces
2
do
cs
Output
1
Note
In the first sample you should remove two letters b.
In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution. | instruction | 0 | 70,995 | 6 | 141,990 |
Tags: greedy
Correct Solution:
```
S = input()
M = int( input() )
banned = set( input() for i in range( M ) )
buff = set()
for s in banned:
if not ( s[ : : -1 ] in banned ):
buff.add( s[ : : -1 ] )
banned.update( buff )
dp = [ [ 1e9 for i in range( 26 ) ] for j in range( len( S ) + 1 ) ]
for i in range( 26 ):
dp[ 0 ][ i ] = 0
for i in range( len( S ) ):
for j in range( 26 ):
if dp[ i ][ j ] == 1e9: continue
if not ( chr( ord( 'a' ) + j ) + S[ i ] in banned ):
dp[ i + 1 ][ ord( S[ i ] ) - ord( 'a' ) ] = min( dp[ i + 1 ][ ord( S[ i ] ) - ord( 'a' ) ], dp[ i ][ j ] )
dp[ i + 1 ][ j ] = min( dp[ i + 1 ][ j ], dp[ i ][ j ] + 1 )
print( min( dp[ len( S ) ] ) )
``` | output | 1 | 70,995 | 6 | 141,991 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.
Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.
Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
Input
The first line contains a non-empty string s, consisting of lowercase Latin letters β that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105.
The next line contains integer k (0 β€ k β€ 13) β the number of forbidden pairs of letters.
Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
Output
Print the single number β the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
Examples
Input
ababa
1
ab
Output
2
Input
codeforces
2
do
cs
Output
1
Note
In the first sample you should remove two letters b.
In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution. | instruction | 0 | 70,996 | 6 | 141,992 |
Tags: greedy
Correct Solution:
```
s = input()
k = int(input())
h = 1
d = {}
for i in range(k):
a, b = input()
d[a] = d[b] = h
h += 1
for c in s:
if c not in d:
d[c] = h
h += 1
count = 0
i = 0
ch = ''
c_ch, c_e = 0, 0
val = 0
while True:
if d[s[i]] != val:
count += min(c_ch, c_e)
c_ch, c_e = 0, 0
val = d[s[i]]
ch = s[i]
if s[i] == ch:
c_ch += 1
else:
c_e += 1
i += 1
if i == len(s):
count += min(c_ch, c_e)
break
print(count)
``` | output | 1 | 70,996 | 6 | 141,993 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.
Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.
Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
Input
The first line contains a non-empty string s, consisting of lowercase Latin letters β that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105.
The next line contains integer k (0 β€ k β€ 13) β the number of forbidden pairs of letters.
Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
Output
Print the single number β the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
Examples
Input
ababa
1
ab
Output
2
Input
codeforces
2
do
cs
Output
1
Note
In the first sample you should remove two letters b.
In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution. | instruction | 0 | 70,997 | 6 | 141,994 |
Tags: greedy
Correct Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
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")
ALPHA='abcdefghijklmnopqrstuvwxyz'
MOD=1000000007
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
s=input()
m=Int()
n=len(s)
ans=0
for _ in range(m):
a,b=list(input())
Ca=0
Cb=0
for i in s+'/':
if(i==a): Ca+=1
elif(i==b): Cb+=1
else:
ans+=min(Ca,Cb)
Ca=0
Cb=0
print(ans)
``` | output | 1 | 70,997 | 6 | 141,995 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.
Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.
Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
Input
The first line contains a non-empty string s, consisting of lowercase Latin letters β that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105.
The next line contains integer k (0 β€ k β€ 13) β the number of forbidden pairs of letters.
Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
Output
Print the single number β the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
Examples
Input
ababa
1
ab
Output
2
Input
codeforces
2
do
cs
Output
1
Note
In the first sample you should remove two letters b.
In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution. | instruction | 0 | 70,998 | 6 | 141,996 |
Tags: greedy
Correct Solution:
```
s=input()
ans=[]
count=1
for i in range(1,len(s)):
if(s[i]==s[i-1]):
count+=1
else:
ans.append([count,s[i-1]])
count=1
ans.append([count,s[-1]])
total=0
t=int(input())
for m in range(t):
r=input()
i=0
while(i<len(ans)):
if(ans[i][1] in r):
t1=ans[i][0]
t2=0
flag=0
j=i+1
for j in range(i+1,len(ans)):
if(flag==0):
if(ans[j][1]!=ans[i][1] and ans[j][1] in r):
t2+=ans[j][0]
flag=1
continue;
else:
break;
else:
if(ans[i][1]==ans[j][1]):
t1+=ans[j][0]
flag=0
continue;
else:
break;
total+=min(t1,t2)
i=j+1
else:
i+=1
print(total)
``` | output | 1 | 70,998 | 6 | 141,997 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.
Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.
Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
Input
The first line contains a non-empty string s, consisting of lowercase Latin letters β that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105.
The next line contains integer k (0 β€ k β€ 13) β the number of forbidden pairs of letters.
Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
Output
Print the single number β the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
Examples
Input
ababa
1
ab
Output
2
Input
codeforces
2
do
cs
Output
1
Note
In the first sample you should remove two letters b.
In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution. | instruction | 0 | 70,999 | 6 | 141,998 |
Tags: greedy
Correct Solution:
```
import sys
input=sys.stdin.readline
s=input().rstrip()
k=int(input())
cannot=[input().rstrip() for i in range(k)]
ans=0
for t in cannot:
a,b=0,0
for i in range(len(s)):
if s[i]==t[0]:
a+=1
elif s[i]==t[1]:
b+=1
else:
ans+=min(a,b)
a=b=0
ans+=min(a,b)
print(ans)
``` | output | 1 | 70,999 | 6 | 141,999 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.
Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.
Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
Input
The first line contains a non-empty string s, consisting of lowercase Latin letters β that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105.
The next line contains integer k (0 β€ k β€ 13) β the number of forbidden pairs of letters.
Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
Output
Print the single number β the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
Examples
Input
ababa
1
ab
Output
2
Input
codeforces
2
do
cs
Output
1
Note
In the first sample you should remove two letters b.
In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution. | instruction | 0 | 71,000 | 6 | 142,000 |
Tags: greedy
Correct Solution:
```
p, t = {}, input()
a, n = False, len(t)
x = y = s = 0
q = [input() for i in range(int(input()))]
for a, b in q: p[a], p[b] = b, a
for i in t:
if a:
if i == a: x += 1
elif i == b: y += 1
else:
s += min(x, y)
if i in p:
a, b = i, p[i]
x, y = 1, 0
else: a = False
elif i in p:
a, b = i, p[i]
x, y = 1, 0
if a: s += min(x, y)
print(s)
``` | output | 1 | 71,000 | 6 | 142,001 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.
Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.
Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
Input
The first line contains a non-empty string s, consisting of lowercase Latin letters β that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105.
The next line contains integer k (0 β€ k β€ 13) β the number of forbidden pairs of letters.
Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
Output
Print the single number β the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
Examples
Input
ababa
1
ab
Output
2
Input
codeforces
2
do
cs
Output
1
Note
In the first sample you should remove two letters b.
In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Submitted Solution:
```
#!/usr/bin/env python
from __future__ import division, print_function
import math
import os
import sys
from fractions import *
from sys import *
from decimal import *
from io import BytesIO, IOBase
from itertools import *
from collections import *
# sys.setrecursionlimit(10**5)
M = 10 ** 9 + 7
# print(math.factorial(5))
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
# sys.setrecursionlimit(10**6)
# region fastio
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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def inp(): return sys.stdin.readline().rstrip("\r\n") # for fast input
def out(var): sys.stdout.write(str(var)) # for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
def fsep(): return map(float, inp().split())
def inpu(): return int(inp())
# -----------------------------------------------------------------
def regularbracket(t):
p = 0
for i in t:
if i == "(":
p += 1
else:
p -= 1
if p < 0:
return False
else:
if p > 0:
return False
else:
return True
# -------------------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] <= key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# ------------------------------reverse string(pallindrome)
def reverse1(string):
pp = ""
for i in string[::-1]:
pp += i
if pp == string:
return True
return False
# --------------------------------reverse list(paindrome)
def reverse2(list1):
l = []
for i in list1[::-1]:
l.append(i)
if l == list1:
return True
return False
def mex(list1):
# list1 = sorted(list1)
p = max(list1) + 1
for i in range(len(list1)):
if list1[i] != i:
p = i
break
return p
def sumofdigits(n):
n = str(n)
s1 = 0
for i in n:
s1 += int(i)
return s1
def perfect_square(n):
s = math.sqrt(n)
if s == int(s):
return True
return False
# -----------------------------roman
def roman_number(x):
if x > 15999:
return
value = [5000, 4000, 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
symbol = ["F", "MF", "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
roman = ""
i = 0
while x > 0:
div = x // value[i]
x = x % value[i]
while div:
roman += symbol[i]
div -= 1
i += 1
return roman
def soretd(s):
for i in range(1, len(s)):
if s[i - 1] > s[i]:
return False
return True
# print(soretd("1"))
# ---------------------------
def countRhombi(h, w):
ct = 0
for i in range(2, h + 1, 2):
for j in range(2, w + 1, 2):
ct += (h - i + 1) * (w - j + 1)
return ct
def countrhombi2(h, w):
return ((h * h) // 4) * ((w * w) // 4)
# ---------------------------------
def binpow(a, b):
if b == 0:
return 1
else:
res = binpow(a, b // 2)
if b % 2 != 0:
return res * res * a
else:
return res * res
# -------------------------------------------------------
def binpowmodulus(a, b, m):
a %= m
res = 1
while (b > 0):
if (b & 1):
res = res * a % m
a = a * a % m
b >>= 1
return res
# -------------------------------------------------------------
def coprime_to_n(n):
result = n
i = 2
while (i * i <= n):
if (n % i == 0):
while (n % i == 0):
n //= i
result -= result // i
i += 1
if (n > 1):
result -= result // n
return result
# -------------------prime
def prime(x):
if x == 1:
return False
else:
for i in range(2, int(math.sqrt(x)) + 1):
# print(x)
if (x % i == 0):
return False
else:
return True
def luckynumwithequalnumberoffourandseven(x,n,a):
if x >= n and str(x).count("4") == str(x).count("7"):
a.append(x)
else:
if x < 1e12:
luckynumwithequalnumberoffourandseven(x * 10 + 4,n,a)
luckynumwithequalnumberoffourandseven(x * 10 + 7,n,a)
return a
#----------------------
def luckynum(x,l,r,a):
if x>=l and x<=r:
a.append(x)
if x>r:
a.append(x)
return a
if x < 1e10:
luckynum(x * 10 + 4, l,r,a)
luckynum(x * 10 + 7, l,r,a)
return a
def luckynuber(x, n, a):
p = set(str(x))
if len(p) <= 2:
a.append(x)
if x < n:
luckynuber(x + 1, n, a)
return a
# ------------------------------------------------------interactive problems
def interact(type, x):
if type == "r":
inp = input()
return inp.strip()
else:
print(x, flush=True)
# ------------------------------------------------------------------zero at end of factorial of a number
def findTrailingZeros(n):
# Initialize result
count = 0
# Keep dividing n by
# 5 & update Count
while (n >= 5):
n //= 5
count += n
return count
# -----------------------------------------------merge sort
# Python program for implementation of MergeSort
def mergeSort(arr):
if len(arr) > 1:
# Finding the mid of the array
mid = len(arr) // 2
# Dividing the array elements
L = arr[:mid]
# into 2 halves
R = arr[mid:]
# Sorting the first half
mergeSort(L)
# Sorting the second half
mergeSort(R)
i = j = k = 0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
# -----------------------------------------------lucky number with two lucky any digits
res = set()
def solven(p, l, a, b, n): # given number
if p > n or l > 10:
return
if p > 0:
res.add(p)
solven(p * 10 + a, l + 1, a, b, n)
solven(p * 10 + b, l + 1, a, b, n)
# problem
"""
n = int(input())
for a in range(0, 10):
for b in range(0, a):
solve(0, 0)
print(len(res))
"""
# Python3 program to find all subsets
# by backtracking.
# In the array A at every step we have two
# choices for each element either we can
# ignore the element or we can include the
# element in our subset
def subsetsUtil(A, subset, index, d):
print(*subset)
s = sum(subset)
d.append(s)
for i in range(index, len(A)):
# include the A[i] in subset.
subset.append(A[i])
# move onto the next element.
subsetsUtil(A, subset, i + 1, d)
# exclude the A[i] from subset and
# triggers backtracking.
subset.pop(-1)
return d
def subsetSums(arr, l, r, d, sum=0):
if l > r:
d.append(sum)
return
subsetSums(arr, l + 1, r, d, sum + arr[l])
# Subset excluding arr[l]
subsetSums(arr, l + 1, r, d, sum)
return d
def print_factors(x):
factors = []
for i in range(1, x + 1):
if x % i == 0:
factors.append(i)
return (factors)
# -----------------------------------------------
def calc(X, d, ans, D):
# print(X,d)
if len(X) == 0:
return
i = X.index(max(X))
ans[D[max(X)]] = d
Y = X[:i]
Z = X[i + 1:]
calc(Y, d + 1, ans, D)
calc(Z, d + 1, ans, D)
# ---------------------------------------
def factorization(n, l):
c = n
if prime(n) == True:
l.append(n)
return l
for i in range(2, c):
if n == 1:
break
while n % i == 0:
l.append(i)
n = n // i
return l
# endregion------------------------------
def good(b):
l = []
i = 0
while (len(b) != 0):
if b[i] < b[len(b) - 1 - i]:
l.append(b[i])
b.remove(b[i])
else:
l.append(b[len(b) - 1 - i])
b.remove(b[len(b) - 1 - i])
if l == sorted(l):
# print(l)
return True
return False
# arr=[]
# print(good(arr))
def generate(st, s):
if len(s) == 0:
return
# If current string is not already present.
if s not in st:
st.add(s)
# Traverse current string, one by one
# remove every character and recur.
for i in range(len(s)):
t = list(s).copy()
t.remove(s[i])
t = ''.join(t)
generate(st, t)
return
#=--------------------------------------------longest increasing subsequence
def largestincreasingsubsequence(A):
l = [1]*len(A)
sub=[]
for i in range(1,len(l)):
for k in range(i):
if A[k]<A[i]:
sub.append(l[k])
l[i]=1+max(sub,default=0)
return max(l,default=0)
#----------------------------------longest palindromic substring
# Python3 program for the
# above approach
# Function to calculate
# Bitwise OR of sums of
# all subsequences
def findOR(nums, N):
# Stores the prefix
# sum of nums[]
prefix_sum = 0
# Stores the bitwise OR of
# sum of each subsequence
result = 0
# Iterate through array nums[]
for i in range(N):
# Bits set in nums[i] are
# also set in result
result |= nums[i]
# Calculate prefix_sum
prefix_sum += nums[i]
# Bits set in prefix_sum
# are also set in result
result |= prefix_sum
# Return the result
return result
#l=[]
def OR(a, n):
ans = a[0]
for i in range(1, n):
ans |= a[i]
#l.append(ans)
return ans
#print(prime(12345678987766))
"""
def main():
q=inpu()
x = q
v1 = 0
v2 = 0
i = 2
while i * i <= q:
while q % i == 0:
if v1!=0:
v2 = i
else:
v1 = i
q //= i
i += 1
if q - 1!=0:
v2 = q
if v1 * v2 - x!=0:
print(1)
print(v1 * v2)
else:
print(2)
if __name__ == '__main__':
main()
"""
"""
def main():
l,r = sep()
a=[]
luckynum(0,l,r,a)
a.sort()
#print(a)
i=0
ans=0
l-=1
#print(a)
while(True):
if r>a[i]:
ans+=(a[i]*(a[i]-l))
l=a[i]
else:
ans+=(a[i]*(r-l))
break
i+=1
print(ans)
if __name__ == '__main__':
main()
"""
"""
def main():
sqrt = {i * i: i for i in range(1, 1000)}
#print(sqrt)
a, b = sep()
for y in range(1, a):
x2 = a * a - y * y
if x2 in sqrt:
x = sqrt[x2]
if b * y % a == 0 and b * x % a == 0 and b * x // a != y:
print('YES')
print(-x, y)
print(0, 0)
print(b * y // a, b * x // a)
exit()
print('NO')
if __name__ == '__main__':
main()
"""
"""
def main():
m=inpu()
q=lis()
n=inpu()
arr=lis()
q=min(q)
arr.sort(reverse=True)
s=0
cnt=0
i=0
while(i<n):
cnt+=1
s+=arr[i]
#print(cnt,q)
if cnt==q:
i+=2
cnt=0
i+=1
print(s)
if __name__ == '__main__':
main()
"""
"""
def main():
n,k = sep()
if k * 2 >= (n - 1) * n:
print('no solution')
else:
for i in range(n):
print(0,i)
if __name__ == '__main__':
main()
"""
"""
def main():
t = inpu()
for _ in range(t):
n,k = sep()
arr = lis()
i=0
j=0
while(k!=0):
if i==n-1:
break
if arr[i]!=0:
arr[i]-=1
arr[n-1]+=1
k-=1
else:
i+=1
print(*arr)
if __name__ == '__main__':
main()
"""
"""
def main():
t = int(input())
for _ in range(t):
n=int(input())
arr = lis()
s = 0
for x in arr:
s ^= x
if s == 0:
print('YES')
else:
c = 0
y=0
for i in range(n):
y ^= arr[i]
if y == s:
c += 1
y=0
if c >= 2:
print("YES")
else:
print("NO")
if __name__ == '__main__':
main()
"""
def main():
s = inp()
ans = 0
k= inpu()
for _ in range(k):
a, b = 0, 0
p = input()
for x in s:
if (x == p[0]):
a += 1
elif (x == p[1]):
b += 1
else:
ans += min(a, b)
a, b = 0, 0
ans += min(a, b)
print(ans)
if __name__ == '__main__':
main()
``` | instruction | 0 | 71,001 | 6 | 142,002 |
Yes | output | 1 | 71,001 | 6 | 142,003 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.
Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.
Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
Input
The first line contains a non-empty string s, consisting of lowercase Latin letters β that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105.
The next line contains integer k (0 β€ k β€ 13) β the number of forbidden pairs of letters.
Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
Output
Print the single number β the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
Examples
Input
ababa
1
ab
Output
2
Input
codeforces
2
do
cs
Output
1
Note
In the first sample you should remove two letters b.
In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Submitted Solution:
```
s = input()
ans = 0
for i in range(int(input())):
x = input()
a, b = 0, 0
for j in s:
if j == x[0]:
a += 1
elif j == x[1]:
b += 1
else:
ans += min(a, b)
a, b = 0, 0
ans += min(a, b)
print(ans)
``` | instruction | 0 | 71,002 | 6 | 142,004 |
Yes | output | 1 | 71,002 | 6 | 142,005 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.
Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.
Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
Input
The first line contains a non-empty string s, consisting of lowercase Latin letters β that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105.
The next line contains integer k (0 β€ k β€ 13) β the number of forbidden pairs of letters.
Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
Output
Print the single number β the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
Examples
Input
ababa
1
ab
Output
2
Input
codeforces
2
do
cs
Output
1
Note
In the first sample you should remove two letters b.
In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Submitted Solution:
```
ans = 0
t = []
x = input()
y = int(input())
for i in range(y):
z = input()
t.append(z)
#x = codeforces
#y = 2
#t = [do, cs]
pt = -1
ln = len(x)
for i in t:
a = i[0]
b = i[1]
pt = 0
for j in range(ln):
ded1=0
ded2=0
if j >= pt:
if x[j] in [a,b]:
pt = j
while pt < ln and x[pt] in [a,b]:
if x[pt] == a:
ded1+=1
else:
ded2+=1
pt += 1
ans += min(ded1, ded2)
print(ans)
``` | instruction | 0 | 71,003 | 6 | 142,006 |
Yes | output | 1 | 71,003 | 6 | 142,007 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.
Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.
Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
Input
The first line contains a non-empty string s, consisting of lowercase Latin letters β that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105.
The next line contains integer k (0 β€ k β€ 13) β the number of forbidden pairs of letters.
Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
Output
Print the single number β the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
Examples
Input
ababa
1
ab
Output
2
Input
codeforces
2
do
cs
Output
1
Note
In the first sample you should remove two letters b.
In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Submitted Solution:
```
a=input()
b=[input() for i in range(int(input()))]
e=0
for i in b:
x=y=0
for j in a:
if j==i[0]:
x+=1
elif j==i[1]:
y+=1
else:
e+=min(x,y)
x=y=0
e+=min(x,y)
print(e)
``` | instruction | 0 | 71,004 | 6 | 142,008 |
Yes | output | 1 | 71,004 | 6 | 142,009 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.
Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.
Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
Input
The first line contains a non-empty string s, consisting of lowercase Latin letters β that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105.
The next line contains integer k (0 β€ k β€ 13) β the number of forbidden pairs of letters.
Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
Output
Print the single number β the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
Examples
Input
ababa
1
ab
Output
2
Input
codeforces
2
do
cs
Output
1
Note
In the first sample you should remove two letters b.
In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Submitted Solution:
```
ans = 0
t = []
x = input()
y = int(input())
for i in range(y):
z = input()
t.append(z)
#x = codeforces
#y = 2
#t = [do, cs]
pt = -1
ln = len(x)
for i in t:
a = i[0]
b = i[1]
for j in range(ln):
ded1=0
ded2=0
if j >= pt:
if x[j] in [a,b]:
pt = j
while pt < ln and x[pt] in [a,b]:
if x[pt] == a:
ded1+=1
else:
ded2+=1
pt += 1
ans += min(ded1, ded2)
print(ans)
``` | instruction | 0 | 71,005 | 6 | 142,010 |
No | output | 1 | 71,005 | 6 | 142,011 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.
Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.
Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
Input
The first line contains a non-empty string s, consisting of lowercase Latin letters β that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105.
The next line contains integer k (0 β€ k β€ 13) β the number of forbidden pairs of letters.
Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
Output
Print the single number β the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
Examples
Input
ababa
1
ab
Output
2
Input
codeforces
2
do
cs
Output
1
Note
In the first sample you should remove two letters b.
In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Submitted Solution:
```
s=input()
n=len(s)
k=int(input())
l=[]
for i in range(k):
l.append(input())
ans=0
i=1
j=0
while i<n:
if i+1<n:
f=0
for x in range(k):
if s[j]+s[i]==l[x][0]+l[x][1] or s[j]+s[i]==l[x][1]+l[x][0]:
if i+1<n:
if s[i+1]==s[i] or s[i+1]==s[j]:
if s[i+1]==s[i]:
ans=ans+1
j=j-1
elif s[i+1]==s[j]:
ans=ans+1
i=i+2
j=i-1
else:
ans=ans+1
i=i+1
j=i-1
else:
ans=ans+1
i=i+1
j=i-1
f=1
break
if f==0:
i=i+1
j=i-1
else:
i=i+1
j=i-1
print(ans)
``` | instruction | 0 | 71,006 | 6 | 142,012 |
No | output | 1 | 71,006 | 6 | 142,013 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.
Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.
Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
Input
The first line contains a non-empty string s, consisting of lowercase Latin letters β that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105.
The next line contains integer k (0 β€ k β€ 13) β the number of forbidden pairs of letters.
Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
Output
Print the single number β the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
Examples
Input
ababa
1
ab
Output
2
Input
codeforces
2
do
cs
Output
1
Note
In the first sample you should remove two letters b.
In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Submitted Solution:
```
#------------------------------warmup----------------------------
import os
import sys
import math
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")
#-------------------game starts now----------------------------------------------------
s=input()
j=len(s)
n=int(input())
l=list()
for i in range (n):
t=input()
l.append(t)
l.append(t[::-1])
#print(*l)
c=0
i=1
while i<j:
sub=s[i-1:i+1]
if sub in l:
c+=1
i+=2
else:
i+=1
#print(sub,c,i)
print(c)
``` | instruction | 0 | 71,007 | 6 | 142,014 |
No | output | 1 | 71,007 | 6 | 142,015 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.