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 a correct Python 3 solution for this coding contest problem.
Broken crypto generator
JAG (Japanese Alumni Group) is a mysterious organization composed of many programmers, and in order to enter the building where the headquarters of this organization is located, it is necessary to solve the ciphertext generated by a certain machine every time. This ciphertext consists of the symbols'+','-','[',']' and the uppercase alphabet, and is represented by <Cipher> defined by the following BNF.
<Cipher> :: = <String> | <Cipher> <String>
<String> :: = <Letter> |'['<Cipher>']'
<Letter> :: ='+' <Letter> |'-' <Letter> |
'A' |'B' |'C' |'D' |'E' |'F' |'G' |'H' |'I' |'J' |'K' |'L' |'M '|
'N' |'O' |'P' |'Q' |'R' |'S' |'T' |'U' |'V' |'W' |'X' |'Y' |'Z '
Here, each symbol has the following meaning.
* + (Character): Represents the alphabet following that character (provided that the alphabet following'Z'is'A')
*-(Character): Represents the alphabet before that character (provided that the alphabet before'A'is'Z')
* [(Character string)]: Represents a character string that is horizontally inverted.
However, the machine that generates this ciphertext is currently out of order, and some letters of the alphabet in the ciphertext may be broken and unreadable. Unreadable characters are tentatively represented as'?'. As a result of the investigation, it was found that the method of filling the broken characters is such that the decrypted character string is the smallest in the dictionary order among the possible character strings after decoding. Your job is to decrypt this ciphertext correctly.
Input
The input consists of multiple datasets. Each dataset consists of one line containing a string in which some uppercase letters have been replaced with β?β In the ciphertext defined by BNF above. You can assume that the length of each string is less than $ 80 $. You can also assume that the number of'?' In each dataset is greater than or equal to $ 0 $ and less than or equal to $ 3 $.
The end of the input is represented by a line containing only one character,'.'.
Output
For each data set, output the decrypted character string when the ciphertext is decrypted so that the decrypted character string is the smallest in the dictionary order.
Sample Input
A + A ++ A
Z-Z--Z + -Z
[ESREVER]
J ---? --- J
++++++++ A +++ Z ----------- A +++ Z
[[++-+-? [-++-? ++-+++ L]] [-+ ----- + -O]] ++++ --- + L
..
Output for Sample Input
ABC
ZYXZ
REVERSE
JAG
ICPC
JAPAN
Example
Input
A+A++A
Z-Z--Z+-Z
[ESREVER]
J---?---J
++++++++A+++Z-----------A+++Z
[[++-+--?[--++-?++-+++L]][-+-----+-O]]++++---+L
.
Output
ABC
ZYXZ
REVERSE
JAG
ICPC
JAPAN | instruction | 0 | 29,992 | 6 | 59,984 |
"Correct Solution:
```
while True:
s = input()
if s == '.':break
while True:
if s.find('+') == -1 and s.find('-') == -1:
index = s.rfind('[')
if index == -1:break
e = s.find(']', index)
s = s[:index] + s[index + 1:e][::-1] + s[e + 1:]
else:
index = s.find('+')
if index == -1:
index = s.find('-')
if s.find('-') != -1:
index = min(index, s.find('-'))
e = index
f = 0
while s[e] == '+' or s[e] == '-':
f += [-1, 1][s[e] == '+']
e += 1
r = s[e]
if r != '?':
r = chr((ord(r) - ord('A') + f) % 26 + ord('A'))
s = s[:index] + r + s[e + 1:]
print(s.replace('?', 'A'))
``` | output | 1 | 29,992 | 6 | 59,985 |
Provide a correct Python 3 solution for this coding contest problem.
Broken crypto generator
JAG (Japanese Alumni Group) is a mysterious organization composed of many programmers, and in order to enter the building where the headquarters of this organization is located, it is necessary to solve the ciphertext generated by a certain machine every time. This ciphertext consists of the symbols'+','-','[',']' and the uppercase alphabet, and is represented by <Cipher> defined by the following BNF.
<Cipher> :: = <String> | <Cipher> <String>
<String> :: = <Letter> |'['<Cipher>']'
<Letter> :: ='+' <Letter> |'-' <Letter> |
'A' |'B' |'C' |'D' |'E' |'F' |'G' |'H' |'I' |'J' |'K' |'L' |'M '|
'N' |'O' |'P' |'Q' |'R' |'S' |'T' |'U' |'V' |'W' |'X' |'Y' |'Z '
Here, each symbol has the following meaning.
* + (Character): Represents the alphabet following that character (provided that the alphabet following'Z'is'A')
*-(Character): Represents the alphabet before that character (provided that the alphabet before'A'is'Z')
* [(Character string)]: Represents a character string that is horizontally inverted.
However, the machine that generates this ciphertext is currently out of order, and some letters of the alphabet in the ciphertext may be broken and unreadable. Unreadable characters are tentatively represented as'?'. As a result of the investigation, it was found that the method of filling the broken characters is such that the decrypted character string is the smallest in the dictionary order among the possible character strings after decoding. Your job is to decrypt this ciphertext correctly.
Input
The input consists of multiple datasets. Each dataset consists of one line containing a string in which some uppercase letters have been replaced with β?β In the ciphertext defined by BNF above. You can assume that the length of each string is less than $ 80 $. You can also assume that the number of'?' In each dataset is greater than or equal to $ 0 $ and less than or equal to $ 3 $.
The end of the input is represented by a line containing only one character,'.'.
Output
For each data set, output the decrypted character string when the ciphertext is decrypted so that the decrypted character string is the smallest in the dictionary order.
Sample Input
A + A ++ A
Z-Z--Z + -Z
[ESREVER]
J ---? --- J
++++++++ A +++ Z ----------- A +++ Z
[[++-+-? [-++-? ++-+++ L]] [-+ ----- + -O]] ++++ --- + L
..
Output for Sample Input
ABC
ZYXZ
REVERSE
JAG
ICPC
JAPAN
Example
Input
A+A++A
Z-Z--Z+-Z
[ESREVER]
J---?---J
++++++++A+++Z-----------A+++Z
[[++-+--?[--++-?++-+++L]][-+-----+-O]]++++---+L
.
Output
ABC
ZYXZ
REVERSE
JAG
ICPC
JAPAN | instruction | 0 | 29,993 | 6 | 59,986 |
"Correct Solution:
```
import re
while 1:
s=input()
if s==".":break
while "+-" in s or "-+" in s:
s=s.replace("+-","").replace("-+","")
while "+" in s:
pos=s.rfind("+")
cha=s[pos]+s[pos+1]
if ord(s[pos+1])==90:cha_r="A"
elif ord(s[pos+1])==63:cha_r="?"
else:cha_r=chr(ord(s[pos+1])+1)
s=s.replace(cha,cha_r)
while "-" in s:
pos=s.rfind("-")
cha=s[pos]+s[pos+1]
if ord(s[pos+1])==65:cha_r="Z"
elif ord(s[pos+1])==63:cha_r="?"
else:cha_r=chr(ord(s[pos+1])-1)
s=s.replace(cha,cha_r)
while "[" in s:
match = re.search(r'\[[A-Z\?]+\]',s)
cha=match.group(0)
cha_r=cha[::-1][1:-1]
s=s.replace(cha,cha_r)
while "?" in s:
s=s.replace("?","A")
print(s)
``` | output | 1 | 29,993 | 6 | 59,987 |
Provide a correct Python 3 solution for this coding contest problem.
Broken crypto generator
JAG (Japanese Alumni Group) is a mysterious organization composed of many programmers, and in order to enter the building where the headquarters of this organization is located, it is necessary to solve the ciphertext generated by a certain machine every time. This ciphertext consists of the symbols'+','-','[',']' and the uppercase alphabet, and is represented by <Cipher> defined by the following BNF.
<Cipher> :: = <String> | <Cipher> <String>
<String> :: = <Letter> |'['<Cipher>']'
<Letter> :: ='+' <Letter> |'-' <Letter> |
'A' |'B' |'C' |'D' |'E' |'F' |'G' |'H' |'I' |'J' |'K' |'L' |'M '|
'N' |'O' |'P' |'Q' |'R' |'S' |'T' |'U' |'V' |'W' |'X' |'Y' |'Z '
Here, each symbol has the following meaning.
* + (Character): Represents the alphabet following that character (provided that the alphabet following'Z'is'A')
*-(Character): Represents the alphabet before that character (provided that the alphabet before'A'is'Z')
* [(Character string)]: Represents a character string that is horizontally inverted.
However, the machine that generates this ciphertext is currently out of order, and some letters of the alphabet in the ciphertext may be broken and unreadable. Unreadable characters are tentatively represented as'?'. As a result of the investigation, it was found that the method of filling the broken characters is such that the decrypted character string is the smallest in the dictionary order among the possible character strings after decoding. Your job is to decrypt this ciphertext correctly.
Input
The input consists of multiple datasets. Each dataset consists of one line containing a string in which some uppercase letters have been replaced with β?β In the ciphertext defined by BNF above. You can assume that the length of each string is less than $ 80 $. You can also assume that the number of'?' In each dataset is greater than or equal to $ 0 $ and less than or equal to $ 3 $.
The end of the input is represented by a line containing only one character,'.'.
Output
For each data set, output the decrypted character string when the ciphertext is decrypted so that the decrypted character string is the smallest in the dictionary order.
Sample Input
A + A ++ A
Z-Z--Z + -Z
[ESREVER]
J ---? --- J
++++++++ A +++ Z ----------- A +++ Z
[[++-+-? [-++-? ++-+++ L]] [-+ ----- + -O]] ++++ --- + L
..
Output for Sample Input
ABC
ZYXZ
REVERSE
JAG
ICPC
JAPAN
Example
Input
A+A++A
Z-Z--Z+-Z
[ESREVER]
J---?---J
++++++++A+++Z-----------A+++Z
[[++-+--?[--++-?++-+++L]][-+-----+-O]]++++---+L
.
Output
ABC
ZYXZ
REVERSE
JAG
ICPC
JAPAN | instruction | 0 | 29,994 | 6 | 59,988 |
"Correct Solution:
```
import string
dic_str = {}
for i,item in enumerate(string.ascii_uppercase):
dic_str[item] = i
"""
def rev(lis,bl = False):
if not "[" in lis:
return "".join(lis)
else:
start = -1
end = -1
i = 0
while(i < len(lis)):
if (start == -1) and (lis[i] == "["):
start = i
if (start != -1) and (lis[i] == "]"):
end = i
break
i += 1
print(start,end)
return rev(list("".join(lis[0:start])+rev(lis[start+1:end],True)+"".join(lis[end+1:len(lis)+1])))
"""
while(True):
strs = input()
if strs == ".":
break
lis_str = list(strs)
change_alpha = []
count = 0
i = 0
while(i < len(lis_str)):
if lis_str[i] in list(string.ascii_uppercase):
change_alpha.append(string.ascii_uppercase[(dic_str[lis_str[i]]+count)%26])
count = 0
elif lis_str[i] == "?":
change_alpha.append("A")
count = 0
elif lis_str[i] == "+":
count += 1
elif lis_str[i] == "-":
count -= 1
elif (lis_str[i] == "[") or (lis_str[i] == "]"):
change_alpha.append(lis_str[i])
i += 1
i = 0
start = -1
end = -1
while(i < len(change_alpha)):
if change_alpha[i] == "[":
start = i
i += 1
elif change_alpha[i] == "]":
end = i
#print(change_alpha)
#print(change_alpha[start+1:end])
#print(list(reversed(change_alpha[start+1:end])))
change_alpha[start+1:end] = list(reversed(change_alpha[start+1:end]))
#print(change_alpha)
change_alpha.pop(start)
change_alpha.pop(end-1)
start = -1
end = -1
i = 0
else:
i += 1
else:
print("".join(change_alpha))
``` | output | 1 | 29,994 | 6 | 59,989 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
During the study of the Martians Petya clearly understood that the Martians are absolutely lazy. They like to sleep and don't like to wake up.
Imagine a Martian who has exactly n eyes located in a row and numbered from the left to the right from 1 to n. When a Martian sleeps, he puts a patch on each eye (so that the Martian morning doesn't wake him up). The inner side of each patch has an uppercase Latin letter. So, when a Martian wakes up and opens all his eyes he sees a string s consisting of uppercase Latin letters. The string's length is n.
"Ding dong!" β the alarm goes off. A Martian has already woken up but he hasn't opened any of his eyes. He feels that today is going to be a hard day, so he wants to open his eyes and see something good. The Martian considers only m Martian words beautiful. Besides, it is hard for him to open all eyes at once so early in the morning. So he opens two non-overlapping segments of consecutive eyes. More formally, the Martian chooses four numbers a, b, c, d, (1 β€ a β€ b < c β€ d β€ n) and opens all eyes with numbers i such that a β€ i β€ b or c β€ i β€ d. After the Martian opens the eyes he needs, he reads all the visible characters from the left to the right and thus, he sees some word.
Let's consider all different words the Martian can see in the morning. Your task is to find out how many beautiful words are among them.
Input
The first line contains a non-empty string s consisting of uppercase Latin letters. The strings' length is n (2 β€ n β€ 105). The second line contains an integer m (1 β€ m β€ 100) β the number of beautiful words. Next m lines contain the beautiful words pi, consisting of uppercase Latin letters. Their length is from 1 to 1000. All beautiful strings are pairwise different.
Output
Print the single integer β the number of different beautiful strings the Martian can see this morning.
Examples
Input
ABCBABA
2
BAAB
ABBA
Output
1
Note
Let's consider the sample test. There the Martian can get only the second beautiful string if he opens segments of eyes a = 1, b = 2 and c = 4, d = 5 or of he opens segments of eyes a = 1, b = 2 and c = 6, d = 7.
Submitted Solution:
```
def z(p, s):
pref = [len(s)] * len(p)
for i in range(len(p)):
pr = p[:i+1]
for index in range(len(s) - i):
if pr == s[index:index + i + 1]:
pref[i] = index + i
break
return [-1] + pref
def main():
s = input()
m = int(input())
subs = (input() for _ in range(m))
res = 0
for sub in subs:
pref = z(sub, s)
suff = z(sub[::-1], s[::-1])
for x, y in zip(pref, suff[::-1]):
if x + y <= len(s) - 2:
res += 1
break
print(res)
if __name__ == '__main__':
main()
``` | instruction | 0 | 31,229 | 6 | 62,458 |
No | output | 1 | 31,229 | 6 | 62,459 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
During the study of the Martians Petya clearly understood that the Martians are absolutely lazy. They like to sleep and don't like to wake up.
Imagine a Martian who has exactly n eyes located in a row and numbered from the left to the right from 1 to n. When a Martian sleeps, he puts a patch on each eye (so that the Martian morning doesn't wake him up). The inner side of each patch has an uppercase Latin letter. So, when a Martian wakes up and opens all his eyes he sees a string s consisting of uppercase Latin letters. The string's length is n.
"Ding dong!" β the alarm goes off. A Martian has already woken up but he hasn't opened any of his eyes. He feels that today is going to be a hard day, so he wants to open his eyes and see something good. The Martian considers only m Martian words beautiful. Besides, it is hard for him to open all eyes at once so early in the morning. So he opens two non-overlapping segments of consecutive eyes. More formally, the Martian chooses four numbers a, b, c, d, (1 β€ a β€ b < c β€ d β€ n) and opens all eyes with numbers i such that a β€ i β€ b or c β€ i β€ d. After the Martian opens the eyes he needs, he reads all the visible characters from the left to the right and thus, he sees some word.
Let's consider all different words the Martian can see in the morning. Your task is to find out how many beautiful words are among them.
Input
The first line contains a non-empty string s consisting of uppercase Latin letters. The strings' length is n (2 β€ n β€ 105). The second line contains an integer m (1 β€ m β€ 100) β the number of beautiful words. Next m lines contain the beautiful words pi, consisting of uppercase Latin letters. Their length is from 1 to 1000. All beautiful strings are pairwise different.
Output
Print the single integer β the number of different beautiful strings the Martian can see this morning.
Examples
Input
ABCBABA
2
BAAB
ABBA
Output
1
Note
Let's consider the sample test. There the Martian can get only the second beautiful string if he opens segments of eyes a = 1, b = 2 and c = 4, d = 5 or of he opens segments of eyes a = 1, b = 2 and c = 6, d = 7.
Submitted Solution:
```
from sys import stdin
def z(p, s):
pref = [len(s)] * len(p)
for i in range(len(p)):
pr = p[:i+1]
for index in range(len(s) - i):
if pr == s[index:index + i + 1]:
pref[i] = index + i
break
return [-1] + pref
def main():
s = stdin.readline()
m = int(stdin.readline())
subs = (stdin.readline() for _ in range(m))
res = 0
for sub in subs:
if len(sub) > 1:
pref = z(sub, s)
suff = z(sub[::-1], s[::-1])
for x, y in zip(pref, suff[::-1]):
if x + y <= len(s) - 2:
res += 1
break
print(res)
if __name__ == '__main__':
main()
``` | instruction | 0 | 31,230 | 6 | 62,460 |
No | output | 1 | 31,230 | 6 | 62,461 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
During the study of the Martians Petya clearly understood that the Martians are absolutely lazy. They like to sleep and don't like to wake up.
Imagine a Martian who has exactly n eyes located in a row and numbered from the left to the right from 1 to n. When a Martian sleeps, he puts a patch on each eye (so that the Martian morning doesn't wake him up). The inner side of each patch has an uppercase Latin letter. So, when a Martian wakes up and opens all his eyes he sees a string s consisting of uppercase Latin letters. The string's length is n.
"Ding dong!" β the alarm goes off. A Martian has already woken up but he hasn't opened any of his eyes. He feels that today is going to be a hard day, so he wants to open his eyes and see something good. The Martian considers only m Martian words beautiful. Besides, it is hard for him to open all eyes at once so early in the morning. So he opens two non-overlapping segments of consecutive eyes. More formally, the Martian chooses four numbers a, b, c, d, (1 β€ a β€ b < c β€ d β€ n) and opens all eyes with numbers i such that a β€ i β€ b or c β€ i β€ d. After the Martian opens the eyes he needs, he reads all the visible characters from the left to the right and thus, he sees some word.
Let's consider all different words the Martian can see in the morning. Your task is to find out how many beautiful words are among them.
Input
The first line contains a non-empty string s consisting of uppercase Latin letters. The strings' length is n (2 β€ n β€ 105). The second line contains an integer m (1 β€ m β€ 100) β the number of beautiful words. Next m lines contain the beautiful words pi, consisting of uppercase Latin letters. Their length is from 1 to 1000. All beautiful strings are pairwise different.
Output
Print the single integer β the number of different beautiful strings the Martian can see this morning.
Examples
Input
ABCBABA
2
BAAB
ABBA
Output
1
Note
Let's consider the sample test. There the Martian can get only the second beautiful string if he opens segments of eyes a = 1, b = 2 and c = 4, d = 5 or of he opens segments of eyes a = 1, b = 2 and c = 6, d = 7.
Submitted Solution:
```
def z_func(s):
l = 0
r = 0
n = len(s)
z = [0]*n
z[0] = n
for i in range(1, n):
if i <= r:
z[i] = min(r-i+1, z[i-l])
while (i+z[i] < n) and (s[z[i]] == s[i+z[i]]):
z[i] += 1
if i+z[i]-1 > r:
l = i
r = i+z[i]-1
return z
main = input()
n = int(input())
kol = 0
for i in range(n):
s = input()
z = z_func(s+main)[len(s):len(main+s)]
newz = z_func(s[::-1] + main[::-1])[len(s):len(main+s)]
pr = [0 for _ in range(len(main))]
pr[0] =newz[0]
for j in range(1, len(main)):
pr[j] = max(pr[j-1], newz[j])
pr = pr[::-1]
b = False
for j in range(len(main)):
if j+len(s)-1 < len(main):
if z[j]+pr[j+len(s)-1] >= len(s):
b = True
break
if b:
kol += 1
print(kol)
``` | instruction | 0 | 31,231 | 6 | 62,462 |
No | output | 1 | 31,231 | 6 | 62,463 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
During the study of the Martians Petya clearly understood that the Martians are absolutely lazy. They like to sleep and don't like to wake up.
Imagine a Martian who has exactly n eyes located in a row and numbered from the left to the right from 1 to n. When a Martian sleeps, he puts a patch on each eye (so that the Martian morning doesn't wake him up). The inner side of each patch has an uppercase Latin letter. So, when a Martian wakes up and opens all his eyes he sees a string s consisting of uppercase Latin letters. The string's length is n.
"Ding dong!" β the alarm goes off. A Martian has already woken up but he hasn't opened any of his eyes. He feels that today is going to be a hard day, so he wants to open his eyes and see something good. The Martian considers only m Martian words beautiful. Besides, it is hard for him to open all eyes at once so early in the morning. So he opens two non-overlapping segments of consecutive eyes. More formally, the Martian chooses four numbers a, b, c, d, (1 β€ a β€ b < c β€ d β€ n) and opens all eyes with numbers i such that a β€ i β€ b or c β€ i β€ d. After the Martian opens the eyes he needs, he reads all the visible characters from the left to the right and thus, he sees some word.
Let's consider all different words the Martian can see in the morning. Your task is to find out how many beautiful words are among them.
Input
The first line contains a non-empty string s consisting of uppercase Latin letters. The strings' length is n (2 β€ n β€ 105). The second line contains an integer m (1 β€ m β€ 100) β the number of beautiful words. Next m lines contain the beautiful words pi, consisting of uppercase Latin letters. Their length is from 1 to 1000. All beautiful strings are pairwise different.
Output
Print the single integer β the number of different beautiful strings the Martian can see this morning.
Examples
Input
ABCBABA
2
BAAB
ABBA
Output
1
Note
Let's consider the sample test. There the Martian can get only the second beautiful string if he opens segments of eyes a = 1, b = 2 and c = 4, d = 5 or of he opens segments of eyes a = 1, b = 2 and c = 6, d = 7.
Submitted Solution:
```
class Problem:
def __init__(self, S, length, n):
self.s = S
self.length = length
self.n0 = n
self.n = len(S)
self.sa = self.suffix_array()
self.lcp, self.rank = self.calc_lcp()
self.table_lcp, self.table_min, self.table_max, self.logs = self.build_table()
def calc_lcp(self):
rank = [0 for _ in range(len(self.s))]
for i in range(len(self.s)):
rank[self.sa[i]] = i
lcp = [0 for _ in range(len(self.s) - 1)]
h = 0
for i in range(len(self.s)):
if rank[i] < len(self.s) - 1:
while max(i, self.sa[rank[i] + 1]) + h < len(self.s) and self.s[i + h] == self.s[self.sa[rank[i] + 1] + h]:
h += 1
lcp[rank[i]] = h
if h > 0:
h -= 1
return lcp, rank
def suffix_array(self):
s = self.s + '\0'
sa = [0 for _ in range(len(s))]
cnt256 = [0 for _ in range(256)]
for c in s:
cnt256[ord(c)] += 1
for i in range(1, 256):
cnt256[i] += cnt256[i - 1]
for i in range(len(s) - 1, -1, -1):
cnt256[ord(s[i])] -= 1
sa[cnt256[ord(s[i])]] = i
rank = 0
ranks = [0 for _ in range(len(s))]
for i in range(1, len(s)):
if s[sa[i - 1]] != s[sa[i]]:
rank += 1
ranks[sa[i]] = rank
k = 1
while k < len(s):
sa_new = [0 for _ in range(len(s))]
rank_new = [0 for _ in range(len(s))]
for i in range(len(s)):
sa_new[i] = sa[i] - k
if sa_new[i] < 0:
sa_new[i] += len(s)
cnt = [0 for _ in range(len(s))]
for i in range(len(s)):
cnt[ranks[i]] += 1
for i in range(1, len(s)):
cnt[i] += cnt[i - 1]
for i in range(len(s) - 1, -1, -1):
cnt[ranks[sa_new[i]]] -= 1
sa[cnt[ranks[sa_new[i]]]] = sa_new[i]
rank = 0
for i in range(1, len(s)):
if ranks[sa[i - 1]] != ranks[sa[i]] or ranks[sa[i - 1] + k] != ranks[sa[i] + k]:
rank += 1
rank_new[sa[i]] = rank
ranks = rank_new
k *= 2
return sa[1:]
def build_table(self):
size = len(self.lcp)
table_lcp = [[i for i in self.lcp]]
table_min = [[i for i in self.sa]]
table_max = [[i if i < self.n0 else -1 for i in self.sa]]
k = 1
while 2 * k < size:
row = []
for i in range(size):
min_val = table_lcp[-1][i]
if i + k < size:
min_val = min(min_val, table_lcp[-1][i + k])
row.append(min_val)
k *= 2
table_lcp.append(row)
size += 1
k = 1
while 2 * k < size:
row_min = []
row_max = []
for i in range(size):
min_val = table_min[-1][i]
max_val = table_max[-1][i]
if i + k < size:
min_val = min(min_val, table_min[-1][i + k])
max_val = max(max_val, table_max[-1][i + k])
row_min.append(min_val)
row_max.append(max_val)
k *= 2
table_min.append(row_min)
table_max.append(row_max)
logs = []
h = 0
for i in range(size):
if (1 << (h + 1)) < i:
h += 1
logs.append(h)
return table_lcp, table_min, table_max, logs
def query(self, l, r):
if l == r:
return self.n + 1
log = self.logs[r - l]
return min(self.table_lcp[log][l], self.table_lcp[log][r - (1 << log)])
def query_min(self, l, r):
log = self.logs[r - l]
return min(self.table_min[log][l], self.table_min[log][r - (1 << log) + 1])
def query_max(self, l, r):
log = self.logs[r - l]
return max(self.table_max[log][l], self.table_max[log][r - (1 << log) + 1])
def binary_search(self, l, r, pred):
while r - l > 1:
mid = (l + r) >> 1
if pred(mid):
l = mid
else:
r = mid
return l
def solve(self):
ans = 0
index = self.n0 + 1
for i in range(len(self.length)):
for k in range(1, self.length[i]):
pos = self.rank[index]
start = self.binary_search(0, pos, lambda x: self.query(x, pos) < k) + 1
end = self.binary_search(pos, self.n, lambda x: self.query(pos, x) >= k)
pref = self.query_min(start, end)
pos = self.rank[index + k]
start = self.binary_search(0, pos, lambda x: self.query(x, pos) < self.length[i] - k) + 1
end = self.binary_search(pos, self.n, lambda x: self.query(pos, x) >= self.length[i] - k)
suff = self.query_max(start, end)
if pref + k <= suff:
ans += 1
break
index += self.length[i] + 1
return ans
s = input()
n = len(s)
m = int(input())
S = [s]
length = []
for _ in range(m):
s = input()
S.append('*')
S.append(s)
length.append(len(s))
p = Problem(''.join(S), length, n)
print(p.solve())
``` | instruction | 0 | 31,232 | 6 | 62,464 |
No | output | 1 | 31,232 | 6 | 62,465 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today Vasya visited a widely known site and learned that the continuation of his favourite game Codecraft II will appear after exactly k months. He looked at the calendar and learned that at the moment is the month number s. Vasya immediately got interested in what month Codecraft III will appear. Help him understand that.
All the twelve months in Vasya's calendar are named using their usual English names: January, February, March, April, May, June, July, August, September, October, November, December.
Input
The first input line contains the name of the current month. It is guaranteed that it is a proper English name of one of twelve months. The first letter is uppercase, the rest are lowercase. The second line contains integer k (0 β€ k β€ 100) β the number of months left till the appearance of Codecraft III.
Output
Print starting from an uppercase letter the name of the month in which the continuation of Codeforces II will appear. The printed name must be contained in the list January, February, March, April, May, June, July, August, September, October, November, December.
Examples
Input
November
3
Output
February
Input
May
24
Output
May | instruction | 0 | 31,348 | 6 | 62,696 |
Tags: implementation
Correct Solution:
```
import re
import sys
exit=sys.exit
from bisect import bisect_left as bsl,bisect_right as bsr
from collections import Counter,defaultdict as ddict,deque
from functools import lru_cache
cache=lru_cache(None)
from heapq import *
from itertools import *
from math import inf
from pprint import pprint as pp
enum=enumerate
ri=lambda:int(rln())
ris=lambda:list(map(int,rfs()))
rln=sys.stdin.readline
rl=lambda:rln().rstrip('\n')
rfs=lambda:rln().split()
cat=''.join
catn='\n'.join
mod=1000000007
d4=[(0,-1),(1,0),(0,1),(-1,0)]
d8=[(-1,-1),(0,-1),(1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)]
########################################################################
m='January February March April May June July August September October November December'.split()
s=rl()
k=ri()
print(m[(m.index(s)+k)%12])
``` | output | 1 | 31,348 | 6 | 62,697 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.
This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.
Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.
Substring is a continuous subsequence of a string.
Input
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
Output
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
Examples
Input
intellect
tell
Output
1
Input
google
apple
Output
0
Input
sirisiri
sir
Output
2
Note
In the first sample AI's name may be replaced with "int#llect".
In the second sample Gogol can just keep things as they are.
In the third sample one of the new possible names of AI may be "s#ris#ri". | instruction | 0 | 31,384 | 6 | 62,768 |
Tags: constructive algorithms, greedy, strings
Correct Solution:
```
a = str(input())
b = str(input())
c=0
d=0
while(d<len(a)+1):
if(a[d:d+len(b)]==b):
c+=1
d+=len(b)
else:
d+=1
print(c)
``` | output | 1 | 31,384 | 6 | 62,769 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.
This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.
Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.
Substring is a continuous subsequence of a string.
Input
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
Output
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
Examples
Input
intellect
tell
Output
1
Input
google
apple
Output
0
Input
sirisiri
sir
Output
2
Note
In the first sample AI's name may be replaced with "int#llect".
In the second sample Gogol can just keep things as they are.
In the third sample one of the new possible names of AI may be "s#ris#ri". | instruction | 0 | 31,385 | 6 | 62,770 |
Tags: constructive algorithms, greedy, strings
Correct Solution:
```
s1 = input()
s1 = s1.lower()
s2 = input()
s2 = s2.lower()
count = 0
if (len(s1) <= 100000 and len(s2) <= 30) and (len(s1) and len(s2)) >= 1 :
count = s1.count(s2)
print(count)
``` | output | 1 | 31,385 | 6 | 62,771 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.
This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.
Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.
Substring is a continuous subsequence of a string.
Input
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
Output
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
Examples
Input
intellect
tell
Output
1
Input
google
apple
Output
0
Input
sirisiri
sir
Output
2
Note
In the first sample AI's name may be replaced with "int#llect".
In the second sample Gogol can just keep things as they are.
In the third sample one of the new possible names of AI may be "s#ris#ri". | instruction | 0 | 31,386 | 6 | 62,772 |
Tags: constructive algorithms, greedy, strings
Correct Solution:
```
import re
string = str(input())
string1 = str(input())
count = 0
print(len(re.findall(string1, string)))
``` | output | 1 | 31,386 | 6 | 62,773 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.
This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.
Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.
Substring is a continuous subsequence of a string.
Input
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
Output
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
Examples
Input
intellect
tell
Output
1
Input
google
apple
Output
0
Input
sirisiri
sir
Output
2
Note
In the first sample AI's name may be replaced with "int#llect".
In the second sample Gogol can just keep things as they are.
In the third sample one of the new possible names of AI may be "s#ris#ri". | instruction | 0 | 31,387 | 6 | 62,774 |
Tags: constructive algorithms, greedy, strings
Correct Solution:
```
a = input()
b = input()
blen = len(b)
amount = 0
i = 0
while i < len(a) - blen + 1:
if a[i:i+blen] == b:
amount += 1
i += blen
else:
i += 1
print(amount)
``` | output | 1 | 31,387 | 6 | 62,775 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.
This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.
Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.
Substring is a continuous subsequence of a string.
Input
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
Output
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
Examples
Input
intellect
tell
Output
1
Input
google
apple
Output
0
Input
sirisiri
sir
Output
2
Note
In the first sample AI's name may be replaced with "int#llect".
In the second sample Gogol can just keep things as they are.
In the third sample one of the new possible names of AI may be "s#ris#ri". | instruction | 0 | 31,388 | 6 | 62,776 |
Tags: constructive algorithms, greedy, strings
Correct Solution:
```
s=input()
s1=input()
count,i=0,0
while i<((len(s)-len(s1))+1):
if s[i:i+len(s1)]==s1:
count+=1
i+=len(s1)
else:
i+=1
print(count)
``` | output | 1 | 31,388 | 6 | 62,777 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.
This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.
Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.
Substring is a continuous subsequence of a string.
Input
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
Output
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
Examples
Input
intellect
tell
Output
1
Input
google
apple
Output
0
Input
sirisiri
sir
Output
2
Note
In the first sample AI's name may be replaced with "int#llect".
In the second sample Gogol can just keep things as they are.
In the third sample one of the new possible names of AI may be "s#ris#ri". | instruction | 0 | 31,389 | 6 | 62,778 |
Tags: constructive algorithms, greedy, strings
Correct Solution:
```
a = input();
b = input();
i = a.find(b);
ans = 0;
while i >= 0:
i = a.find(b, i + len(b))
ans+=1;
print(ans)
``` | output | 1 | 31,389 | 6 | 62,779 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.
This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.
Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.
Substring is a continuous subsequence of a string.
Input
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
Output
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
Examples
Input
intellect
tell
Output
1
Input
google
apple
Output
0
Input
sirisiri
sir
Output
2
Note
In the first sample AI's name may be replaced with "int#llect".
In the second sample Gogol can just keep things as they are.
In the third sample one of the new possible names of AI may be "s#ris#ri". | instruction | 0 | 31,390 | 6 | 62,780 |
Tags: constructive algorithms, greedy, strings
Correct Solution:
```
s = input()
sub = input()
n1, n2 = len(s), len(sub)
ans = 0
i1, i2 = 0, 0
while i1 < n1:
ist = i1 + 1
while i1 < n1 and i2 < n2 and sub[i2] == s[i1]:
if s[i1] == sub[0] and i1 > ist:
ist = i1
i1 += 1
i2 += 1
if i2 == n2:
ans += 1
else:
i1 = ist
i2 = 0
print(ans)
``` | output | 1 | 31,390 | 6 | 62,781 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.
This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.
Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.
Substring is a continuous subsequence of a string.
Input
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
Output
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
Examples
Input
intellect
tell
Output
1
Input
google
apple
Output
0
Input
sirisiri
sir
Output
2
Note
In the first sample AI's name may be replaced with "int#llect".
In the second sample Gogol can just keep things as they are.
In the third sample one of the new possible names of AI may be "s#ris#ri". | instruction | 0 | 31,391 | 6 | 62,782 |
Tags: constructive algorithms, greedy, strings
Correct Solution:
```
google = input()
apple = input()
answer = 0
if (apple in google):
answer = google.count(apple)
print(answer)
``` | output | 1 | 31,391 | 6 | 62,783 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalizationΒ» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
Input
The first line contains an integer n (1 β€ n β€ 100). Each of the following n lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.
Output
Print n lines. The i-th line should contain the result of replacing of the i-th word from the input data.
Examples
Input
4
word
localization
internationalization
pneumonoultramicroscopicsilicovolcanoconiosis
Output
word
l10n
i18n
p43s | instruction | 0 | 31,416 | 6 | 62,832 |
Tags: strings
Correct Solution:
```
n = int(input())
for i in range(0, n):
aString = input()
aStringLength = len(aString)
outputString = ""
if aStringLength > 10:
outputString += aString[0]
outputString += str(aStringLength-2)
outputString += aString[aStringLength-1]
else:
outputString = aString
print(outputString)
``` | output | 1 | 31,416 | 6 | 62,833 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalizationΒ» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
Input
The first line contains an integer n (1 β€ n β€ 100). Each of the following n lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.
Output
Print n lines. The i-th line should contain the result of replacing of the i-th word from the input data.
Examples
Input
4
word
localization
internationalization
pneumonoultramicroscopicsilicovolcanoconiosis
Output
word
l10n
i18n
p43s | instruction | 0 | 31,417 | 6 | 62,834 |
Tags: strings
Correct Solution:
```
a = int(input())
list2 = []
for i in range(0,a,1):
list2.append(input())
for j in list2:
if len(j)>10:
lis = [c for c in j]
num = str(len(lis) - 2)
print(lis[0] + num + lis[-1])
else:
print(j)
``` | output | 1 | 31,417 | 6 | 62,835 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalizationΒ» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
Input
The first line contains an integer n (1 β€ n β€ 100). Each of the following n lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.
Output
Print n lines. The i-th line should contain the result of replacing of the i-th word from the input data.
Examples
Input
4
word
localization
internationalization
pneumonoultramicroscopicsilicovolcanoconiosis
Output
word
l10n
i18n
p43s | instruction | 0 | 31,418 | 6 | 62,836 |
Tags: strings
Correct Solution:
```
n=int(input())
words =[]
for i in range(n):
words.append(input())
for i in range(n):
if len(words[i])>10:
words[i]=words[i][0]+str(len(words[i])-2)+words[i][len(words[i])-1]
for i in words:
print(i+'\n');
``` | output | 1 | 31,418 | 6 | 62,837 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalizationΒ» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
Input
The first line contains an integer n (1 β€ n β€ 100). Each of the following n lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.
Output
Print n lines. The i-th line should contain the result of replacing of the i-th word from the input data.
Examples
Input
4
word
localization
internationalization
pneumonoultramicroscopicsilicovolcanoconiosis
Output
word
l10n
i18n
p43s | instruction | 0 | 31,419 | 6 | 62,838 |
Tags: strings
Correct Solution:
```
n = int(input())
for i in range(n):
word = input()
if len(word) <= 10:
print(word)
else:
first_letter = word[0]
last_let = word[len(word) - 1]
middle = str(len(word) - 2)
newWord = first_letter + middle + last_let
print(newWord)
``` | output | 1 | 31,419 | 6 | 62,839 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalizationΒ» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
Input
The first line contains an integer n (1 β€ n β€ 100). Each of the following n lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.
Output
Print n lines. The i-th line should contain the result of replacing of the i-th word from the input data.
Examples
Input
4
word
localization
internationalization
pneumonoultramicroscopicsilicovolcanoconiosis
Output
word
l10n
i18n
p43s | instruction | 0 | 31,420 | 6 | 62,840 |
Tags: strings
Correct Solution:
```
n=int(input())
for i in range(n):
s=str(input())
l=len(s)
if(l>10):
s=s[0]+str(l-2)+s[l-1]
print(s)
else:
print(s)
``` | output | 1 | 31,420 | 6 | 62,841 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalizationΒ» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
Input
The first line contains an integer n (1 β€ n β€ 100). Each of the following n lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.
Output
Print n lines. The i-th line should contain the result of replacing of the i-th word from the input data.
Examples
Input
4
word
localization
internationalization
pneumonoultramicroscopicsilicovolcanoconiosis
Output
word
l10n
i18n
p43s | instruction | 0 | 31,421 | 6 | 62,842 |
Tags: strings
Correct Solution:
```
n = int(input())
for i in range(1, n+1):
s = input()
if len(s) > 10:
print(s[0]+str(len(s)-2)+s[len(s)-1])
else:
print(s)
``` | output | 1 | 31,421 | 6 | 62,843 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalizationΒ» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
Input
The first line contains an integer n (1 β€ n β€ 100). Each of the following n lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.
Output
Print n lines. The i-th line should contain the result of replacing of the i-th word from the input data.
Examples
Input
4
word
localization
internationalization
pneumonoultramicroscopicsilicovolcanoconiosis
Output
word
l10n
i18n
p43s | instruction | 0 | 31,422 | 6 | 62,844 |
Tags: strings
Correct Solution:
```
a=int(input())
for i in range(a):
string=input()
if(len(string)>10):
st=""
st+=str(string[0])
st+=str(len(string)-2)
st+=str(string[len(string)-1])
print(st)
else:
print(string)
``` | output | 1 | 31,422 | 6 | 62,845 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalizationΒ» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
Input
The first line contains an integer n (1 β€ n β€ 100). Each of the following n lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.
Output
Print n lines. The i-th line should contain the result of replacing of the i-th word from the input data.
Examples
Input
4
word
localization
internationalization
pneumonoultramicroscopicsilicovolcanoconiosis
Output
word
l10n
i18n
p43s | instruction | 0 | 31,423 | 6 | 62,846 |
Tags: strings
Correct Solution:
```
n=int(input())
for k in range(n):
word=input()
z=len(word)
if z>10:
print(word[0]+str(z-2)+word[-1])
else:
print(word)
``` | output | 1 | 31,423 | 6 | 62,847 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalizationΒ» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
Input
The first line contains an integer n (1 β€ n β€ 100). Each of the following n lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.
Output
Print n lines. The i-th line should contain the result of replacing of the i-th word from the input data.
Examples
Input
4
word
localization
internationalization
pneumonoultramicroscopicsilicovolcanoconiosis
Output
word
l10n
i18n
p43s
Submitted Solution:
```
def main():
n = int(input())
words = []
for i in range(n):
word = input()
if (len(word) <= 10):
words.append(word)
else:
newWord = word[0] + str((len(word) - 2)) + word[len(word)-1]
words.append(newWord)
for word in words:
print(word)
if __name__ == '__main__':
main()
``` | instruction | 0 | 31,424 | 6 | 62,848 |
Yes | output | 1 | 31,424 | 6 | 62,849 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase.
Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed x. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys.
Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than x. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips.
You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand.
Input
The first line contains three integers n, m, x (1 β€ n, m β€ 30, 1 β€ x β€ 50).
Next n lines contain descriptions of all the keyboard keys. Each line contains the descriptions of exactly m keys, without spaces. The letter keys are marked with the corresponding lowercase letters. The "Shift" keys are marked with the "S" symbol.
Then follow the length of the text q (1 β€ q β€ 5Β·105). The last line contains the text T, which consists of q symbols, which are uppercase and lowercase Latin letters.
Output
If Vasya can type the text, then print the minimum number of times he will have to use his other hand. Otherwise, print "-1" (without the quotes).
Examples
Input
2 2 1
ab
cd
1
A
Output
-1
Input
2 2 1
ab
cd
1
e
Output
-1
Input
2 2 1
ab
cS
5
abcBA
Output
1
Input
3 9 4
qwertyuio
asdfghjkl
SzxcvbnmS
35
TheQuIcKbRoWnFOXjummsovertHeLazYDOG
Output
2
Note
In the first sample the symbol "A" is impossible to print as there's no "Shift" key on the keyboard.
In the second sample the symbol "e" is impossible to print as there's no such key on the keyboard.
In the fourth sample the symbols "T", "G" are impossible to print with one hand. The other letters that are on the keyboard can be printed. Those symbols come up in the text twice, thus, the answer is 2. | instruction | 0 | 32,190 | 6 | 64,380 |
Tags: implementation
Correct Solution:
```
from collections import defaultdict
n, m, x = [int(y) for y in input().split()]
a=[]
for _ in range(n):
a.append(input())
l=int(input())
s=input()
d=defaultdict(int)
shift=[]
for i in range(n):
for j in range(m):
if a[i][j]=='S':
shift.append((i,j))
for i in range(n):
for j in range(m):
if a[i][j]!='S':
if d[a[i][j].upper()]==1:continue
if shift:
d[a[i][j]]=1
mn=((shift[0][0]-i)**2+(shift[0][1]-j)**2)**0.5
if mn>x:
for k in shift:
if ((k[0]-i)**2+(k[1]-j)**2)**0.5<mn:
mn=((k[0]-i)**2+(k[1]-j)**2)**0.5
if mn<=x:
d[(a[i][j]).upper()]=1
break
if mn>x:d[(a[i][j]).upper()]=2
else:
d[(a[i][j]).upper()]=1
else:
d[a[i][j]]=1
found=False
cnt=0
for i in s:
if d[i]==0:
print(-1)
found=True
break
elif d[i]==2:
cnt+=1
if not found:print(cnt)
``` | output | 1 | 32,190 | 6 | 64,381 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase.
Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed x. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys.
Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than x. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips.
You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand.
Input
The first line contains three integers n, m, x (1 β€ n, m β€ 30, 1 β€ x β€ 50).
Next n lines contain descriptions of all the keyboard keys. Each line contains the descriptions of exactly m keys, without spaces. The letter keys are marked with the corresponding lowercase letters. The "Shift" keys are marked with the "S" symbol.
Then follow the length of the text q (1 β€ q β€ 5Β·105). The last line contains the text T, which consists of q symbols, which are uppercase and lowercase Latin letters.
Output
If Vasya can type the text, then print the minimum number of times he will have to use his other hand. Otherwise, print "-1" (without the quotes).
Examples
Input
2 2 1
ab
cd
1
A
Output
-1
Input
2 2 1
ab
cd
1
e
Output
-1
Input
2 2 1
ab
cS
5
abcBA
Output
1
Input
3 9 4
qwertyuio
asdfghjkl
SzxcvbnmS
35
TheQuIcKbRoWnFOXjummsovertHeLazYDOG
Output
2
Note
In the first sample the symbol "A" is impossible to print as there's no "Shift" key on the keyboard.
In the second sample the symbol "e" is impossible to print as there's no such key on the keyboard.
In the fourth sample the symbols "T", "G" are impossible to print with one hand. The other letters that are on the keyboard can be printed. Those symbols come up in the text twice, thus, the answer is 2. | instruction | 0 | 32,191 | 6 | 64,382 |
Tags: implementation
Correct Solution:
```
from collections import Counter as cnt
# Function to get the distance between two points
def dis(ls, shifts, z):
x, y = ls[0], ls[1]
ans = []
for shift in shifts:
x1, y1 = shift[0], shift[1]
a = (x - x1) ** 2
b = (y - y1) ** 2
d = (a + b) ** 0.5
if d > z:
ans.append(True)
else:
ans.append(False)
if False in ans:
return False
else:
return True
n, m, z = map(int, input().split())
keys = []
shifts = []
for x in range(n):
row = input()
keys.append(row)
# Getting all the index of shift keys
if 'S' in row:
for y, val in enumerate(row):
if val == 'S':
shifts.append([x+1, y+1])
move = dict()
# Checking out which keys needs double hand and which key doesn't
for x, row in enumerate(keys):
for y, key in enumerate(row):
d = dis([x+1, y+1], shifts, z)
if key in move and move[key] is False: pass
else:
move[key] = d
# Turing the 2D keys list into a 1D list
all_keys = []
all_keys += [key for key in keys]
all_keys = ''.join(all_keys)
all_keys = all_keys.replace('S', '')
q = int(input())
a = input()
count = cnt(a)
uppa = 0
ans = 0
# Checking all the uppercase characters
for key in count:
if key.lower() not in all_keys:
ans = -1
break
if key.isupper():
uppa += 1
if move[key.lower()]:
ans += count[key]
shifts = len(shifts)
if shifts == 0 and uppa > 0:
ans = -1
print(ans)
``` | output | 1 | 32,191 | 6 | 64,383 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase.
Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed x. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys.
Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than x. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips.
You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand.
Input
The first line contains three integers n, m, x (1 β€ n, m β€ 30, 1 β€ x β€ 50).
Next n lines contain descriptions of all the keyboard keys. Each line contains the descriptions of exactly m keys, without spaces. The letter keys are marked with the corresponding lowercase letters. The "Shift" keys are marked with the "S" symbol.
Then follow the length of the text q (1 β€ q β€ 5Β·105). The last line contains the text T, which consists of q symbols, which are uppercase and lowercase Latin letters.
Output
If Vasya can type the text, then print the minimum number of times he will have to use his other hand. Otherwise, print "-1" (without the quotes).
Examples
Input
2 2 1
ab
cd
1
A
Output
-1
Input
2 2 1
ab
cd
1
e
Output
-1
Input
2 2 1
ab
cS
5
abcBA
Output
1
Input
3 9 4
qwertyuio
asdfghjkl
SzxcvbnmS
35
TheQuIcKbRoWnFOXjummsovertHeLazYDOG
Output
2
Note
In the first sample the symbol "A" is impossible to print as there's no "Shift" key on the keyboard.
In the second sample the symbol "e" is impossible to print as there's no such key on the keyboard.
In the fourth sample the symbols "T", "G" are impossible to print with one hand. The other letters that are on the keyboard can be printed. Those symbols come up in the text twice, thus, the answer is 2. | instruction | 0 | 32,192 | 6 | 64,384 |
Tags: implementation
Correct Solution:
```
from collections import defaultdict
import math
def dist(x1, y1, x2, y2):
a1 = (x1 - x2) * (x1 - x2)
b1 = (y1 - y2) * (y1 - y2)
# print(math.sqrt(a1 + b1))
return math.sqrt(a1 + b1)
def dfs(r, c, mat, vis, r_m, c_m, r1, c1, x):
if 0 < dist(r, c, r1, c1) <= x and matrix[r1][c1] != "S":
# print(mat[r1][c1])
Dict[mat[r1][c1].upper()] = 1
vis[(r1, c1)] = 1
if r1 + 1 < r_m and vis[(r1 + 1, c1)] != 1:
dfs(r, c, mat, vis, r_m, c_m, r1 + 1, c1, x)
if r1 - 1 >= 0 and vis[(r1 - 1, c1)] != 1:
dfs(r, c, mat, vis, r_m, c_m, r1 - 1, c1, x)
if c1 + 1 < c_m and vis[(r1, c1 + 1)] != 1:
dfs(r, c, mat, vis, r_m, c_m, r1, c1 + 1, x)
if c1 - 1 >= 0 and vis[(r1, c1 - 1)] != 1:
dfs(r, c, mat, vis, r_m, c_m, r1, c1 - 1, x)
return
n, m, x = [int(i) for i in input().split()]
matrix = []
Dict = defaultdict(int)
for i in range(n):
matrix.append([i for i in input()])
for i in range(n):
for j in range(m):
if matrix[i][j] == "S":
continue
Dict[matrix[i][j]] = 1
flag = 0
for i in range(n):
for j in range(m):
if matrix[i][j] == "S":
flag = 1
visited = defaultdict(int)
dfs(i, j, matrix, visited, n, m, i, j, x)
t = int(input())
s1 = input()
ans = 0
flag1 = 0
for i in range(t):
if Dict[s1[i]] == 0:
if Dict[s1[i].lower()] == 1 and flag == 1:
ans += 1
else:
flag1 = 1
break
if flag1:
print(-1)
else:
# print(Dict)
print(ans)
``` | output | 1 | 32,192 | 6 | 64,385 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase.
Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed x. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys.
Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than x. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips.
You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand.
Input
The first line contains three integers n, m, x (1 β€ n, m β€ 30, 1 β€ x β€ 50).
Next n lines contain descriptions of all the keyboard keys. Each line contains the descriptions of exactly m keys, without spaces. The letter keys are marked with the corresponding lowercase letters. The "Shift" keys are marked with the "S" symbol.
Then follow the length of the text q (1 β€ q β€ 5Β·105). The last line contains the text T, which consists of q symbols, which are uppercase and lowercase Latin letters.
Output
If Vasya can type the text, then print the minimum number of times he will have to use his other hand. Otherwise, print "-1" (without the quotes).
Examples
Input
2 2 1
ab
cd
1
A
Output
-1
Input
2 2 1
ab
cd
1
e
Output
-1
Input
2 2 1
ab
cS
5
abcBA
Output
1
Input
3 9 4
qwertyuio
asdfghjkl
SzxcvbnmS
35
TheQuIcKbRoWnFOXjummsovertHeLazYDOG
Output
2
Note
In the first sample the symbol "A" is impossible to print as there's no "Shift" key on the keyboard.
In the second sample the symbol "e" is impossible to print as there's no such key on the keyboard.
In the fourth sample the symbols "T", "G" are impossible to print with one hand. The other letters that are on the keyboard can be printed. Those symbols come up in the text twice, thus, the answer is 2. | instruction | 0 | 32,193 | 6 | 64,386 |
Tags: implementation
Correct Solution:
```
from math import *
def euclidian(x1, x2, y1, y2):
return sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
dic = dict()
n, m, x = map(int, input().split())
for i in range(n):
a = input()
for j in range(m):
if a[j] not in dic:
dic[a[j]] = []
dic[a[j]].append([i, j])
q, t = int(input()), input()
dic2 = dict()
ans = 0
for i in t:
if i.islower():
if i not in dic:
exit(print(-1))
else:
if i.lower() not in dic or 'S' not in dic:
exit(print(-1))
else:
chr, mi = i.lower(), inf
if chr in dic2:
ans += int(dic2[chr])
else:
for j in dic['S']:
for l in dic[chr]:
mi = min(mi, euclidian(j[0], l[0], j[1], l[1]))
if mi > x:
ans += 1
dic2[chr] = mi > x
print(ans)
``` | output | 1 | 32,193 | 6 | 64,387 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase.
Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed x. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys.
Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than x. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips.
You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand.
Input
The first line contains three integers n, m, x (1 β€ n, m β€ 30, 1 β€ x β€ 50).
Next n lines contain descriptions of all the keyboard keys. Each line contains the descriptions of exactly m keys, without spaces. The letter keys are marked with the corresponding lowercase letters. The "Shift" keys are marked with the "S" symbol.
Then follow the length of the text q (1 β€ q β€ 5Β·105). The last line contains the text T, which consists of q symbols, which are uppercase and lowercase Latin letters.
Output
If Vasya can type the text, then print the minimum number of times he will have to use his other hand. Otherwise, print "-1" (without the quotes).
Examples
Input
2 2 1
ab
cd
1
A
Output
-1
Input
2 2 1
ab
cd
1
e
Output
-1
Input
2 2 1
ab
cS
5
abcBA
Output
1
Input
3 9 4
qwertyuio
asdfghjkl
SzxcvbnmS
35
TheQuIcKbRoWnFOXjummsovertHeLazYDOG
Output
2
Note
In the first sample the symbol "A" is impossible to print as there's no "Shift" key on the keyboard.
In the second sample the symbol "e" is impossible to print as there's no such key on the keyboard.
In the fourth sample the symbols "T", "G" are impossible to print with one hand. The other letters that are on the keyboard can be printed. Those symbols come up in the text twice, thus, the answer is 2. | instruction | 0 | 32,194 | 6 | 64,388 |
Tags: implementation
Correct Solution:
```
#!/usr/bin/env python3
(n,m,x) = map(int, input().split())
keyboard = []
for i in range(n):
keyboard.append(input().strip())
q = int(input())
text = input().strip()
shift_keys = []
cost = dict()
for i in range(n):
for j in range(m):
if (keyboard[i][j] == 'S'):
shift_keys.append((i,j))
else:
cost[keyboard[i][j]] = 0
if (len(shift_keys) > 0):
for i in range(n):
for j in range(m):
if (keyboard[i][j] != 'S'):
distance = min((i-si)**2 + (j-sj)**2 for (si,sj) in shift_keys)
letter = keyboard[i][j].upper()
if (distance <= x**2):
cost[letter] = 0
elif (letter not in cost):
cost[letter] = 1
result = 0
for letter in text:
if letter not in cost:
print(-1)
exit()
else:
result += cost[letter]
print(result)
``` | output | 1 | 32,194 | 6 | 64,389 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase.
Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed x. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys.
Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than x. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips.
You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand.
Input
The first line contains three integers n, m, x (1 β€ n, m β€ 30, 1 β€ x β€ 50).
Next n lines contain descriptions of all the keyboard keys. Each line contains the descriptions of exactly m keys, without spaces. The letter keys are marked with the corresponding lowercase letters. The "Shift" keys are marked with the "S" symbol.
Then follow the length of the text q (1 β€ q β€ 5Β·105). The last line contains the text T, which consists of q symbols, which are uppercase and lowercase Latin letters.
Output
If Vasya can type the text, then print the minimum number of times he will have to use his other hand. Otherwise, print "-1" (without the quotes).
Examples
Input
2 2 1
ab
cd
1
A
Output
-1
Input
2 2 1
ab
cd
1
e
Output
-1
Input
2 2 1
ab
cS
5
abcBA
Output
1
Input
3 9 4
qwertyuio
asdfghjkl
SzxcvbnmS
35
TheQuIcKbRoWnFOXjummsovertHeLazYDOG
Output
2
Note
In the first sample the symbol "A" is impossible to print as there's no "Shift" key on the keyboard.
In the second sample the symbol "e" is impossible to print as there's no such key on the keyboard.
In the fourth sample the symbols "T", "G" are impossible to print with one hand. The other letters that are on the keyboard can be printed. Those symbols come up in the text twice, thus, the answer is 2. | instruction | 0 | 32,195 | 6 | 64,390 |
Tags: implementation
Correct Solution:
```
from collections import Counter as cnt
def dis(ls, shifts, z):
x, y = ls[0], ls[1]
ans = []
for shift in shifts:
x1, y1 = shift[0], shift[1]
a = (x - x1) ** 2
b = (y - y1) ** 2
d = (a + b) ** 0.5
if d > z:
ans.append(True)
else:
ans.append(False)
if False in ans:
return False
else:
return True
n, m, z = map(int, input().split())
keys = []
shifts = []
for x in range(n):
row = input()
keys.append(row)
if 'S' in row:
for y, val in enumerate(row):
if val == 'S':
shifts.append([x+1, y+1])
move = dict()
for x, row in enumerate(keys):
for y, key in enumerate(row):
d = dis([x+1, y+1], shifts, z)
if key in move and move[key] is False: pass
else:
move[key] = d
all_keys = []
all_keys += [key for key in keys]
all_keys = ''.join(all_keys)
all_keys = all_keys.replace('S', '')
q = int(input())
a = input()
count = cnt(a)
uppa = 0
ans = 0
for key in count:
if key.lower() not in all_keys:
ans = -1
break
if key.isupper():
uppa += 1
if move[key.lower()]:
ans += count[key]
shifts = len(shifts)
if shifts == 0 and uppa > 0:
ans = -1
print(ans)
``` | output | 1 | 32,195 | 6 | 64,391 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase.
Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed x. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys.
Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than x. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips.
You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand.
Input
The first line contains three integers n, m, x (1 β€ n, m β€ 30, 1 β€ x β€ 50).
Next n lines contain descriptions of all the keyboard keys. Each line contains the descriptions of exactly m keys, without spaces. The letter keys are marked with the corresponding lowercase letters. The "Shift" keys are marked with the "S" symbol.
Then follow the length of the text q (1 β€ q β€ 5Β·105). The last line contains the text T, which consists of q symbols, which are uppercase and lowercase Latin letters.
Output
If Vasya can type the text, then print the minimum number of times he will have to use his other hand. Otherwise, print "-1" (without the quotes).
Examples
Input
2 2 1
ab
cd
1
A
Output
-1
Input
2 2 1
ab
cd
1
e
Output
-1
Input
2 2 1
ab
cS
5
abcBA
Output
1
Input
3 9 4
qwertyuio
asdfghjkl
SzxcvbnmS
35
TheQuIcKbRoWnFOXjummsovertHeLazYDOG
Output
2
Note
In the first sample the symbol "A" is impossible to print as there's no "Shift" key on the keyboard.
In the second sample the symbol "e" is impossible to print as there's no such key on the keyboard.
In the fourth sample the symbols "T", "G" are impossible to print with one hand. The other letters that are on the keyboard can be printed. Those symbols come up in the text twice, thus, the answer is 2. | instruction | 0 | 32,196 | 6 | 64,392 |
Tags: implementation
Correct Solution:
```
import math
n, m, x = map(int, input().split())
keys = dict()
posKeys = []
a = []
for i in range(n):
a.append(input())
for i in range(n):
for j in range(m):
if a[i][j] == 'S':
posKeys.append((i,j))
else:
keys[a[i][j]] = 0
if len(posKeys)>0:
for i in range(n):
for j in range(m):
if a[i][j] != 'S':
letter = a[i][j].upper()
dis = min((i-si)**2 + (j-sj)**2 for si, sj in posKeys)
if dis <= x**2:
keys[letter] = 0
elif letter not in keys:
keys[letter] = 1
q = int(input())
text = input()
res = 0
for i in range(q):
if text[i] not in keys:
print(-1)
exit()
else:
res += keys[text[i]]
print(res)
``` | output | 1 | 32,196 | 6 | 64,393 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase.
Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed x. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys.
Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than x. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips.
You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand.
Input
The first line contains three integers n, m, x (1 β€ n, m β€ 30, 1 β€ x β€ 50).
Next n lines contain descriptions of all the keyboard keys. Each line contains the descriptions of exactly m keys, without spaces. The letter keys are marked with the corresponding lowercase letters. The "Shift" keys are marked with the "S" symbol.
Then follow the length of the text q (1 β€ q β€ 5Β·105). The last line contains the text T, which consists of q symbols, which are uppercase and lowercase Latin letters.
Output
If Vasya can type the text, then print the minimum number of times he will have to use his other hand. Otherwise, print "-1" (without the quotes).
Examples
Input
2 2 1
ab
cd
1
A
Output
-1
Input
2 2 1
ab
cd
1
e
Output
-1
Input
2 2 1
ab
cS
5
abcBA
Output
1
Input
3 9 4
qwertyuio
asdfghjkl
SzxcvbnmS
35
TheQuIcKbRoWnFOXjummsovertHeLazYDOG
Output
2
Note
In the first sample the symbol "A" is impossible to print as there's no "Shift" key on the keyboard.
In the second sample the symbol "e" is impossible to print as there's no such key on the keyboard.
In the fourth sample the symbols "T", "G" are impossible to print with one hand. The other letters that are on the keyboard can be printed. Those symbols come up in the text twice, thus, the answer is 2. | instruction | 0 | 32,197 | 6 | 64,394 |
Tags: implementation
Correct Solution:
```
from math import sqrt
n, m, x = list(map(int, input().split()))
keyboard = {}
for i in range(n):
line_raw=input()
for j in range(len(line_raw)):
if line_raw[j] in keyboard:
keyboard[line_raw[j]].append((i, j))
else:
keyboard[line_raw[j]] = [(i, j)]
def dist(A, B):
return sqrt((A[0] - B[0])**2 + (A[1] - B[1])**2)
dist_from_shift = {}
for key, pos in keyboard.items():
min_pos = float('inf')
if 'S' in keyboard and key != 'S':
for kp in pos:
for shift_pos in keyboard['S']:
min_pos = min(min_pos, dist(kp, shift_pos))
dist_from_shift[key.upper()] = min_pos
q = int(input())
query = input()
count = 0
found = True
for c in query:
if c.isupper():
if c.lower() in keyboard and 'S' in keyboard:
if dist_from_shift[c] > x:
count = count + 1
else:
found = False
print("-1")
break
else:
if c not in keyboard:
found = False
print("-1")
break
if found:
print(count)
``` | output | 1 | 32,197 | 6 | 64,395 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase.
Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed x. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys.
Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than x. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips.
You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand.
Input
The first line contains three integers n, m, x (1 β€ n, m β€ 30, 1 β€ x β€ 50).
Next n lines contain descriptions of all the keyboard keys. Each line contains the descriptions of exactly m keys, without spaces. The letter keys are marked with the corresponding lowercase letters. The "Shift" keys are marked with the "S" symbol.
Then follow the length of the text q (1 β€ q β€ 5Β·105). The last line contains the text T, which consists of q symbols, which are uppercase and lowercase Latin letters.
Output
If Vasya can type the text, then print the minimum number of times he will have to use his other hand. Otherwise, print "-1" (without the quotes).
Examples
Input
2 2 1
ab
cd
1
A
Output
-1
Input
2 2 1
ab
cd
1
e
Output
-1
Input
2 2 1
ab
cS
5
abcBA
Output
1
Input
3 9 4
qwertyuio
asdfghjkl
SzxcvbnmS
35
TheQuIcKbRoWnFOXjummsovertHeLazYDOG
Output
2
Note
In the first sample the symbol "A" is impossible to print as there's no "Shift" key on the keyboard.
In the second sample the symbol "e" is impossible to print as there's no such key on the keyboard.
In the fourth sample the symbols "T", "G" are impossible to print with one hand. The other letters that are on the keyboard can be printed. Those symbols come up in the text twice, thus, the answer is 2.
Submitted Solution:
```
n,m,e=input().split()
key=[]
shift=[]
dist=[0 for i in range(26)]
for i in range(int(n)):
x=input()
for h in range(len(x)):
if(x[h]=='S'):
shift.append([i,h])
key.append(x)
input()
str=input()
l=len(shift)
for i in range(int(n)):
for j in range(int(m)):
if(key[i][j]=='S'):continue
comp=1000
for x in range(l):
comp=min(comp,(abs(shift[x][0]-i)**2)+(abs(shift[x][1]-j)**2))
if(l!=0):
if(dist[ord(key[i][j])-ord('a')]>0):
dist[ord(key[i][j]) - ord('a')]=min(dist[ord(key[i][j]) - ord('a')],comp)
else:
dist[ord(key[i][j])-ord('a')]=comp
else:
dist[ord(key[i][j])-ord('a')]=1
ans=0
for s in str:
d=ord(s)
if(d>=65 and d<=90):
d+=32
if(l==0):
ans=-1
break
if(dist[d-97]==0):
ans=-1
break
else:
if(ord(s)>=65 and ord(s)<=90):
if(dist[d-97]>int(e)*int(e)):
ans+=1
print(ans)
``` | instruction | 0 | 32,198 | 6 | 64,396 |
Yes | output | 1 | 32,198 | 6 | 64,397 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase.
Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed x. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys.
Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than x. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips.
You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand.
Input
The first line contains three integers n, m, x (1 β€ n, m β€ 30, 1 β€ x β€ 50).
Next n lines contain descriptions of all the keyboard keys. Each line contains the descriptions of exactly m keys, without spaces. The letter keys are marked with the corresponding lowercase letters. The "Shift" keys are marked with the "S" symbol.
Then follow the length of the text q (1 β€ q β€ 5Β·105). The last line contains the text T, which consists of q symbols, which are uppercase and lowercase Latin letters.
Output
If Vasya can type the text, then print the minimum number of times he will have to use his other hand. Otherwise, print "-1" (without the quotes).
Examples
Input
2 2 1
ab
cd
1
A
Output
-1
Input
2 2 1
ab
cd
1
e
Output
-1
Input
2 2 1
ab
cS
5
abcBA
Output
1
Input
3 9 4
qwertyuio
asdfghjkl
SzxcvbnmS
35
TheQuIcKbRoWnFOXjummsovertHeLazYDOG
Output
2
Note
In the first sample the symbol "A" is impossible to print as there's no "Shift" key on the keyboard.
In the second sample the symbol "e" is impossible to print as there's no such key on the keyboard.
In the fourth sample the symbols "T", "G" are impossible to print with one hand. The other letters that are on the keyboard can be printed. Those symbols come up in the text twice, thus, the answer is 2.
Submitted Solution:
```
def sqrt(a):
return a**0.5
n , m , x = map(int,input().split())
keyboard = []
for i in range(n):
keyboard.append(input())
#print(keyboard)
q = int(input())
text = input()
shifts = []
cost = dict()
for i in range(n):
for j in range(m):
if keyboard[i][j] == 'S':
shifts.append((i , j))
else:
cost[keyboard[i][j]] = 0
if (len(shifts) > 0 ):
for i in range(n):
for j in range(m):
if keyboard[i][j] != 'S':
distance= min((i - si)**2 + (j - sj)**2 for si , sj in shifts )
letter = keyboard[i][j].upper()
#print(letter)
if distance <= x ** 2:
cost[letter] = 0
elif letter not in cost:
cost[letter] = 1
#print(cost)
res = 0
for letter in text :
if letter in cost:
res += cost[letter]
else:
res = -1
break
print(res)
``` | instruction | 0 | 32,199 | 6 | 64,398 |
Yes | output | 1 | 32,199 | 6 | 64,399 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase.
Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed x. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys.
Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than x. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips.
You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand.
Input
The first line contains three integers n, m, x (1 β€ n, m β€ 30, 1 β€ x β€ 50).
Next n lines contain descriptions of all the keyboard keys. Each line contains the descriptions of exactly m keys, without spaces. The letter keys are marked with the corresponding lowercase letters. The "Shift" keys are marked with the "S" symbol.
Then follow the length of the text q (1 β€ q β€ 5Β·105). The last line contains the text T, which consists of q symbols, which are uppercase and lowercase Latin letters.
Output
If Vasya can type the text, then print the minimum number of times he will have to use his other hand. Otherwise, print "-1" (without the quotes).
Examples
Input
2 2 1
ab
cd
1
A
Output
-1
Input
2 2 1
ab
cd
1
e
Output
-1
Input
2 2 1
ab
cS
5
abcBA
Output
1
Input
3 9 4
qwertyuio
asdfghjkl
SzxcvbnmS
35
TheQuIcKbRoWnFOXjummsovertHeLazYDOG
Output
2
Note
In the first sample the symbol "A" is impossible to print as there's no "Shift" key on the keyboard.
In the second sample the symbol "e" is impossible to print as there's no such key on the keyboard.
In the fourth sample the symbols "T", "G" are impossible to print with one hand. The other letters that are on the keyboard can be printed. Those symbols come up in the text twice, thus, the answer is 2.
Submitted Solution:
```
n, m, x = list(map(int, input().split()))
x = x ** 2
k = []
contains_shift = False
for i in range(n):
line = input()
if 'S' in line:
contains_shift = True
k.append(line)
q = int(input())
t = input()
def getMinShiftDist(i, j):
min_d = 5000
for x in range(n):
for y in range(m):
if k[x][y] == 'S':
dist = (i - x) ** 2 + (j - y) ** 2
if dist < min_d:
min_d = dist
return min_d
def getCoords(c):
coords = []
for x in range(n):
for y in range(m):
if k[x][y] == c:
coords.append((x, y))
return coords
def containsKey(c):
for x in range(n):
for y in range(m):
if k[x][y] == c:
return True
return False
min_cache = {}
ans = 0
for c in t:
if min_cache.get(c.lower()) == None:
if not containsKey(c.lower()):
ans = -1
break
min_cache[c.lower()] = 0
if c.isupper():
if not contains_shift:
ans = -1
break
else:
min_d = 5000
if min_cache.get(c) != None:
min_d = min_cache.get(c)
else:
coords = getCoords(c.lower())
for coord in coords:
ret = getMinShiftDist(*coord)
if ret < min_d:
min_d = ret
min_cache[c] = min_d
if min_d > x:
ans +=1
print(ans)
``` | instruction | 0 | 32,200 | 6 | 64,400 |
Yes | output | 1 | 32,200 | 6 | 64,401 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase.
Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed x. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys.
Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than x. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips.
You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand.
Input
The first line contains three integers n, m, x (1 β€ n, m β€ 30, 1 β€ x β€ 50).
Next n lines contain descriptions of all the keyboard keys. Each line contains the descriptions of exactly m keys, without spaces. The letter keys are marked with the corresponding lowercase letters. The "Shift" keys are marked with the "S" symbol.
Then follow the length of the text q (1 β€ q β€ 5Β·105). The last line contains the text T, which consists of q symbols, which are uppercase and lowercase Latin letters.
Output
If Vasya can type the text, then print the minimum number of times he will have to use his other hand. Otherwise, print "-1" (without the quotes).
Examples
Input
2 2 1
ab
cd
1
A
Output
-1
Input
2 2 1
ab
cd
1
e
Output
-1
Input
2 2 1
ab
cS
5
abcBA
Output
1
Input
3 9 4
qwertyuio
asdfghjkl
SzxcvbnmS
35
TheQuIcKbRoWnFOXjummsovertHeLazYDOG
Output
2
Note
In the first sample the symbol "A" is impossible to print as there's no "Shift" key on the keyboard.
In the second sample the symbol "e" is impossible to print as there's no such key on the keyboard.
In the fourth sample the symbols "T", "G" are impossible to print with one hand. The other letters that are on the keyboard can be printed. Those symbols come up in the text twice, thus, the answer is 2.
Submitted Solution:
```
import sys
import math, collections
pr = print
def fill(arr, val):
for i in range(len(arr)):
if isinstance(arr[i], list):
fill(arr[i], val)
else:
arr[i] = val
def ls(*dims):
if len(dims) == 0:
return []
a = dims[::-1]
res = [0] * a[0]
for i in a[1:]:
res = [res.copy() for _ in range(i)]
return res
rowin = lambda: list(map(int, input().split()))
numin = lambda: int(input())
keyb = []
n,m,x = rowin()
for i in range(n):
line=input()
keyb.append(line)
canshift = set()
cantype = set()
def eu(i1, j1, i2, j2):
global x
return (i2-i1)**2 + (j2-j1)**2 <=x**2
has_shift = False
for i in range(n):
line = keyb[i]
for j in range(m):
if line[j] == 'S':
has_shift = True
for p_i in range(n):
for p_j in range(m):
if keyb[p_i][p_j] != 'S' and eu(i, j, p_i, p_j):
canshift.add(keyb[p_i][p_j])
cantype.add(keyb[i][j])
# pr(canshift)
c = 0
input()
z = input()
for i in z:
if i.isupper():
if not has_shift:
print(-1)
sys.exit()
# print(i)
if i.lower() in cantype and i.lower() not in canshift:
# print('not')
c += 1
if i.lower() not in cantype:
print(-1)
sys.exit()
print(c)
``` | instruction | 0 | 32,201 | 6 | 64,402 |
Yes | output | 1 | 32,201 | 6 | 64,403 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase.
Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed x. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys.
Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than x. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips.
You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand.
Input
The first line contains three integers n, m, x (1 β€ n, m β€ 30, 1 β€ x β€ 50).
Next n lines contain descriptions of all the keyboard keys. Each line contains the descriptions of exactly m keys, without spaces. The letter keys are marked with the corresponding lowercase letters. The "Shift" keys are marked with the "S" symbol.
Then follow the length of the text q (1 β€ q β€ 5Β·105). The last line contains the text T, which consists of q symbols, which are uppercase and lowercase Latin letters.
Output
If Vasya can type the text, then print the minimum number of times he will have to use his other hand. Otherwise, print "-1" (without the quotes).
Examples
Input
2 2 1
ab
cd
1
A
Output
-1
Input
2 2 1
ab
cd
1
e
Output
-1
Input
2 2 1
ab
cS
5
abcBA
Output
1
Input
3 9 4
qwertyuio
asdfghjkl
SzxcvbnmS
35
TheQuIcKbRoWnFOXjummsovertHeLazYDOG
Output
2
Note
In the first sample the symbol "A" is impossible to print as there's no "Shift" key on the keyboard.
In the second sample the symbol "e" is impossible to print as there's no such key on the keyboard.
In the fourth sample the symbols "T", "G" are impossible to print with one hand. The other letters that are on the keyboard can be printed. Those symbols come up in the text twice, thus, the answer is 2.
Submitted Solution:
```
from collections import defaultdict
from math import dist
if __name__ == '__main__':
n,m,x = map(int,input().split())
k = []
for i in range(n):
k.append(input())
q = int(input())
s = input()
km = defaultdict(tuple)
ks = defaultdict(list)
for i in range(n):
for j in range(m):
if k[i][j] == 'S':
ks[k[i][j]].append((i,j))
else:
km[k[i][j]] = (i,j)
count = 0
for i in s:
if km[i.lower()] == () or (i.isupper() and len(ks['S']) == 0):
print(-1)
exit()
if i.islower():
continue
f = False
for j in ks['S']:
if dist(km[i.lower()],j) <= x:
f = True
if f:
continue
else:
count += 1
print(count)
``` | instruction | 0 | 32,202 | 6 | 64,404 |
No | output | 1 | 32,202 | 6 | 64,405 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase.
Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed x. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys.
Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than x. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips.
You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand.
Input
The first line contains three integers n, m, x (1 β€ n, m β€ 30, 1 β€ x β€ 50).
Next n lines contain descriptions of all the keyboard keys. Each line contains the descriptions of exactly m keys, without spaces. The letter keys are marked with the corresponding lowercase letters. The "Shift" keys are marked with the "S" symbol.
Then follow the length of the text q (1 β€ q β€ 5Β·105). The last line contains the text T, which consists of q symbols, which are uppercase and lowercase Latin letters.
Output
If Vasya can type the text, then print the minimum number of times he will have to use his other hand. Otherwise, print "-1" (without the quotes).
Examples
Input
2 2 1
ab
cd
1
A
Output
-1
Input
2 2 1
ab
cd
1
e
Output
-1
Input
2 2 1
ab
cS
5
abcBA
Output
1
Input
3 9 4
qwertyuio
asdfghjkl
SzxcvbnmS
35
TheQuIcKbRoWnFOXjummsovertHeLazYDOG
Output
2
Note
In the first sample the symbol "A" is impossible to print as there's no "Shift" key on the keyboard.
In the second sample the symbol "e" is impossible to print as there's no such key on the keyboard.
In the fourth sample the symbols "T", "G" are impossible to print with one hand. The other letters that are on the keyboard can be printed. Those symbols come up in the text twice, thus, the answer is 2.
Submitted Solution:
```
n,m,e=input().split()
key=[]
shift=[]
dist=[0 for i in range(26)]
for i in range(int(n)):
x=input()
for h in range(len(x)):
if(x[h]=='S'):
shift.append([i,h])
key.append(x)
input()
str=input()
l=len(shift)
for i in range(int(n)):
for j in range(int(m)):
if(key[i][j]=='S'):continue
comp=1000
for x in range(l):
comp=min(comp,(abs(shift[x][0]-i)**2)+(abs(shift[x][1]-j)**2))
if(l!=0):
if(dist[ord(key[i][j])-ord('a')]>0):
dist[ord(key[i][j]) - ord('a')]=min(dist[ord(key[i][j]) - ord('a')],comp)
else:
dist[ord(key[i][j])-ord('a')]=comp
else:
dist[ord(key[i][j])-ord('a')]=1
ans=0
for s in str:
d=ord(s)
if(d>=65 and d<=90):
d+=32
if(l==0):
ans=-1
break
if(dist[d-97]==0):
print(s)
ans=-1
break
else:
if(ord(s)>=65 and ord(s)<=90):
if(dist[d-97]>int(e)*int(e)):
print(s)
ans+=1
print(ans)
``` | instruction | 0 | 32,203 | 6 | 64,406 |
No | output | 1 | 32,203 | 6 | 64,407 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase.
Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed x. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys.
Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than x. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips.
You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand.
Input
The first line contains three integers n, m, x (1 β€ n, m β€ 30, 1 β€ x β€ 50).
Next n lines contain descriptions of all the keyboard keys. Each line contains the descriptions of exactly m keys, without spaces. The letter keys are marked with the corresponding lowercase letters. The "Shift" keys are marked with the "S" symbol.
Then follow the length of the text q (1 β€ q β€ 5Β·105). The last line contains the text T, which consists of q symbols, which are uppercase and lowercase Latin letters.
Output
If Vasya can type the text, then print the minimum number of times he will have to use his other hand. Otherwise, print "-1" (without the quotes).
Examples
Input
2 2 1
ab
cd
1
A
Output
-1
Input
2 2 1
ab
cd
1
e
Output
-1
Input
2 2 1
ab
cS
5
abcBA
Output
1
Input
3 9 4
qwertyuio
asdfghjkl
SzxcvbnmS
35
TheQuIcKbRoWnFOXjummsovertHeLazYDOG
Output
2
Note
In the first sample the symbol "A" is impossible to print as there's no "Shift" key on the keyboard.
In the second sample the symbol "e" is impossible to print as there's no such key on the keyboard.
In the fourth sample the symbols "T", "G" are impossible to print with one hand. The other letters that are on the keyboard can be printed. Those symbols come up in the text twice, thus, the answer is 2.
Submitted Solution:
```
def dis(a,b,c,d):
d=(a-c)*(a-c)+(b-d)*(b-d)
return d
n,m,x=map(int,input().split())
l=[]
shift=[]
pos=[]
for i in range(n):
a=input()
l.append(a)
for i in range(n):
for j in range(m):
if l[i][j]=='S':
shift.append((i,j))
else:
pos.append((l[i][j],i,j))
q=int(input())
s=input()
ans=0
e=0
p=[]
for k in s:
#print("insidefor1,value of e is",e)
if k.isupper() and k!='S':
#print("Inside if1,k",k)
t=k.lower()
for i in pos:
#print("inside for 2,i",i)
d=0
a=26
if len(shift)==0:
e=0
elif i[0]==t:
#print("inside if 2")
for j in shift:
#print("insidefor 3,j",j)
d=dis(i[1],i[2],j[0],j[1])
#print("values",i[1],i[2],j[0],j[1])
a=min(d,a)
e=1
#print(a)
p.append((abs(a),k))
b=''
for i in p:
if i[1] not in b and i[0]>x*x:
b+=i[1]
e=1
ans=len(b)
if e==0:
print(-1)
else:
print(ans)
``` | instruction | 0 | 32,204 | 6 | 64,408 |
No | output | 1 | 32,204 | 6 | 64,409 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase.
Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed x. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys.
Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than x. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips.
You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand.
Input
The first line contains three integers n, m, x (1 β€ n, m β€ 30, 1 β€ x β€ 50).
Next n lines contain descriptions of all the keyboard keys. Each line contains the descriptions of exactly m keys, without spaces. The letter keys are marked with the corresponding lowercase letters. The "Shift" keys are marked with the "S" symbol.
Then follow the length of the text q (1 β€ q β€ 5Β·105). The last line contains the text T, which consists of q symbols, which are uppercase and lowercase Latin letters.
Output
If Vasya can type the text, then print the minimum number of times he will have to use his other hand. Otherwise, print "-1" (without the quotes).
Examples
Input
2 2 1
ab
cd
1
A
Output
-1
Input
2 2 1
ab
cd
1
e
Output
-1
Input
2 2 1
ab
cS
5
abcBA
Output
1
Input
3 9 4
qwertyuio
asdfghjkl
SzxcvbnmS
35
TheQuIcKbRoWnFOXjummsovertHeLazYDOG
Output
2
Note
In the first sample the symbol "A" is impossible to print as there's no "Shift" key on the keyboard.
In the second sample the symbol "e" is impossible to print as there's no such key on the keyboard.
In the fourth sample the symbols "T", "G" are impossible to print with one hand. The other letters that are on the keyboard can be printed. Those symbols come up in the text twice, thus, the answer is 2.
Submitted Solution:
```
from typing import DefaultDict
n,m,d = list(map(int, input().split(' ')))
keyboard = DefaultDict(list)
memory = {}
for i in range(n):
s = input()
for j in range(m):
keyboard[s[j]] += [(i,j)]
q = int(input())
word = input()
ans = 0
for i in range(q):
if word[i].lower() not in keyboard:
ans = -1
break
else:
if word[i] in memory:
if not memory[word[i]]:
ans+=1
continue
if not word[i].islower():
if 'S' not in keyboard:
ans = -1
continue
min_dis = False
memory[word[i]]=True
for i, j in keyboard[word[i].lower()]:
for x, y in keyboard['S']:
if ((x-i)**2+(y-j)**2) <= d**2:
min_dis=True
if not min_dis:
memory[word[i]] = False
ans+=1
print(ans)
``` | instruction | 0 | 32,205 | 6 | 64,410 |
No | output | 1 | 32,205 | 6 | 64,411 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Unary is a minimalistic Brainfuck dialect in which programs are written using only one token.
Brainfuck programs use 8 commands: "+", "-", "[", "]", "<", ">", "." and "," (their meaning is not important for the purposes of this problem). Unary programs are created from Brainfuck programs using the following algorithm. First, replace each command with a corresponding binary code, using the following conversion table:
* ">" β 1000,
* "<" β 1001,
* "+" β 1010,
* "-" β 1011,
* "." β 1100,
* "," β 1101,
* "[" β 1110,
* "]" β 1111.
Next, concatenate the resulting binary codes into one binary number in the same order as in the program. Finally, write this number using unary numeral system β this is the Unary program equivalent to the original Brainfuck one.
You are given a Brainfuck program. Your task is to calculate the size of the equivalent Unary program, and print it modulo 1000003 (106 + 3).
Input
The input will consist of a single line p which gives a Brainfuck program. String p will contain between 1 and 100 characters, inclusive. Each character of p will be "+", "-", "[", "]", "<", ">", "." or ",".
Output
Output the size of the equivalent Unary program modulo 1000003 (106 + 3).
Examples
Input
,.
Output
220
Input
++++[>,.<-]
Output
61425
Note
To write a number n in unary numeral system, one simply has to write 1 n times. For example, 5 written in unary system will be 11111.
In the first example replacing Brainfuck commands with binary code will give us 1101 1100. After we concatenate the codes, we'll get 11011100 in binary system, or 220 in decimal. That's exactly the number of tokens in the equivalent Unary program. | instruction | 0 | 32,674 | 6 | 65,348 |
Tags: implementation
Correct Solution:
```
def language(string):
dct={
">" :1000,
"<" : 1001,
"+" :1010,
"-" :1011,
"." :1100,
"," :1101,
"[" :1110,
"]" :1111
}
ans=""
for i in string:
ans+=str(dct[i])
return int(ans,2)% 1000003
print(language(input()))
``` | output | 1 | 32,674 | 6 | 65,349 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Unary is a minimalistic Brainfuck dialect in which programs are written using only one token.
Brainfuck programs use 8 commands: "+", "-", "[", "]", "<", ">", "." and "," (their meaning is not important for the purposes of this problem). Unary programs are created from Brainfuck programs using the following algorithm. First, replace each command with a corresponding binary code, using the following conversion table:
* ">" β 1000,
* "<" β 1001,
* "+" β 1010,
* "-" β 1011,
* "." β 1100,
* "," β 1101,
* "[" β 1110,
* "]" β 1111.
Next, concatenate the resulting binary codes into one binary number in the same order as in the program. Finally, write this number using unary numeral system β this is the Unary program equivalent to the original Brainfuck one.
You are given a Brainfuck program. Your task is to calculate the size of the equivalent Unary program, and print it modulo 1000003 (106 + 3).
Input
The input will consist of a single line p which gives a Brainfuck program. String p will contain between 1 and 100 characters, inclusive. Each character of p will be "+", "-", "[", "]", "<", ">", "." or ",".
Output
Output the size of the equivalent Unary program modulo 1000003 (106 + 3).
Examples
Input
,.
Output
220
Input
++++[>,.<-]
Output
61425
Note
To write a number n in unary numeral system, one simply has to write 1 n times. For example, 5 written in unary system will be 11111.
In the first example replacing Brainfuck commands with binary code will give us 1101 1100. After we concatenate the codes, we'll get 11011100 in binary system, or 220 in decimal. That's exactly the number of tokens in the equivalent Unary program. | instruction | 0 | 32,675 | 6 | 65,350 |
Tags: implementation
Correct Solution:
```
# B. Unary
# time limit per test2 seconds
# memory limit per test256 megabytes
# inputstandard input
# outputstandard output
# Unary is a minimalistic Brainfuck dialect in which programs are written using only one token.
#
# Brainfuck programs use 8 commands: "+", "-", "[", "]", "<", ">", "." and "," (their meaning is not important for
# the purposes of this problem). Unary programs are created from Brainfuck programs using the following algorithm.
# First, replace each command with a corresponding binary code, using the following conversion table:
#
# ">" βββ 1000, "<" βββ 1001, "+" βββ 1010, "-" βββ 1011, "." βββ 1100, "," βββ 1101, "[" βββ 1110, "]" βββ 1111.
# Next, concatenate the resulting binary codes into one binary number in the same order as in the program. Finally,
# write this number using unary numeral system β this is the Unary program equivalent to the original Brainfuck one.
#
# You are given a Brainfuck program. Your task is to calculate the size of the equivalent Unary program, and print it
# modulo 1000003 (106β+β3).
#
# Input The input will consist of a single line p which gives a Brainfuck program. String p will contain between 1
# and 100 characters, inclusive. Each character of p will be "+", "-", "[", "]", "<", ">", "." or ",".
#
# Output
# Output the size of the equivalent Unary program modulo 1000003 (106β+β3).
#
# Examples input ,. output 220 input ++++[>,.<-] output 61425 Note To write a number n in unary numeral system,
# one simply has to write 1 n times. For example, 5 written in unary system will be 11111.
#
# In the first example replacing Brainfuck commands with binary code will give us 1101 1100. After we concatenate the
# codes, we'll get 11011100 in binary system, or 220 in decimal. That's exactly the number of tokens in the
# equivalent Unary program.
print(int(''.join({'>': '1000', '<': '1001', '+': '1010', '-': '1011', '.': '1100', ',': '1101', '[': '1110', ']': '1111'}[_] for _ in input()), 2) % 1000003)
``` | output | 1 | 32,675 | 6 | 65,351 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Special Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there.
The content special agent has got an important task: to get the latest research by British scientists on the English Language. These developments are encoded and stored in a large safe. The Beaver's teeth are strong enough, so the authorities assured that upon arriving at the place the beaver won't have any problems with opening the safe.
And he finishes his aspen sprig and leaves for this important task. Of course, the Beaver arrived at the location without any problems, but alas. He can't open the safe with his strong and big teeth. At this point, the Smart Beaver get a call from the headquarters and learns that opening the safe with the teeth is not necessary, as a reliable source has sent the following information: the safe code consists of digits and has no leading zeroes. There also is a special hint, which can be used to open the safe. The hint is string s with the following structure:
* if si = "?", then the digit that goes i-th in the safe code can be anything (between 0 to 9, inclusively);
* if si is a digit (between 0 to 9, inclusively), then it means that there is digit si on position i in code;
* if the string contains letters from "A" to "J", then all positions with the same letters must contain the same digits and the positions with distinct letters must contain distinct digits.
* The length of the safe code coincides with the length of the hint.
For example, hint "?JGJ9" has such matching safe code variants: "51919", "55959", "12329", "93539" and so on, and has wrong variants such as: "56669", "00111", "03539" and "13666".
After receiving such information, the authorities change the plan and ask the special agents to work quietly and gently and not to try to open the safe by mechanical means, and try to find the password using the given hint.
At a special agent school the Smart Beaver was the fastest in his platoon finding codes for such safes, but now he is not in that shape: the years take their toll ... Help him to determine the number of possible variants of the code to the safe, matching the given hint. After receiving this information, and knowing his own speed of entering codes, the Smart Beaver will be able to determine whether he will have time for tonight's show "Beavers are on the trail" on his favorite TV channel, or he should work for a sleepless night...
Input
The first line contains string s β the hint to the safe code. String s consists of the following characters: ?, 0-9, A-J. It is guaranteed that the first character of string s doesn't equal to character 0.
The input limits for scoring 30 points are (subproblem A1):
* 1 β€ |s| β€ 5.
The input limits for scoring 100 points are (subproblems A1+A2):
* 1 β€ |s| β€ 105.
Here |s| means the length of string s.
Output
Print the number of codes that match the given hint.
Examples
Input
AJ
Output
81
Input
1?AA
Output
100 | instruction | 0 | 32,830 | 6 | 65,660 |
Tags: math
Correct Solution:
```
res = 1
started = False
seen = set()
codes = set(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'])
zeroes = 0
for ch in input():
if ch == '?':
if started:
zeroes += 1
else:
res *= 9
elif (ch in codes) and (ch not in seen):
if not started:
res *= len(codes) - len(seen) - 1
else:
res *= len(codes) - len(seen)
seen.add(ch)
started = True
print(res, '0' * zeroes, sep='')
``` | output | 1 | 32,830 | 6 | 65,661 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Special Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there.
The content special agent has got an important task: to get the latest research by British scientists on the English Language. These developments are encoded and stored in a large safe. The Beaver's teeth are strong enough, so the authorities assured that upon arriving at the place the beaver won't have any problems with opening the safe.
And he finishes his aspen sprig and leaves for this important task. Of course, the Beaver arrived at the location without any problems, but alas. He can't open the safe with his strong and big teeth. At this point, the Smart Beaver get a call from the headquarters and learns that opening the safe with the teeth is not necessary, as a reliable source has sent the following information: the safe code consists of digits and has no leading zeroes. There also is a special hint, which can be used to open the safe. The hint is string s with the following structure:
* if si = "?", then the digit that goes i-th in the safe code can be anything (between 0 to 9, inclusively);
* if si is a digit (between 0 to 9, inclusively), then it means that there is digit si on position i in code;
* if the string contains letters from "A" to "J", then all positions with the same letters must contain the same digits and the positions with distinct letters must contain distinct digits.
* The length of the safe code coincides with the length of the hint.
For example, hint "?JGJ9" has such matching safe code variants: "51919", "55959", "12329", "93539" and so on, and has wrong variants such as: "56669", "00111", "03539" and "13666".
After receiving such information, the authorities change the plan and ask the special agents to work quietly and gently and not to try to open the safe by mechanical means, and try to find the password using the given hint.
At a special agent school the Smart Beaver was the fastest in his platoon finding codes for such safes, but now he is not in that shape: the years take their toll ... Help him to determine the number of possible variants of the code to the safe, matching the given hint. After receiving this information, and knowing his own speed of entering codes, the Smart Beaver will be able to determine whether he will have time for tonight's show "Beavers are on the trail" on his favorite TV channel, or he should work for a sleepless night...
Input
The first line contains string s β the hint to the safe code. String s consists of the following characters: ?, 0-9, A-J. It is guaranteed that the first character of string s doesn't equal to character 0.
The input limits for scoring 30 points are (subproblem A1):
* 1 β€ |s| β€ 5.
The input limits for scoring 100 points are (subproblems A1+A2):
* 1 β€ |s| β€ 105.
Here |s| means the length of string s.
Output
Print the number of codes that match the given hint.
Examples
Input
AJ
Output
81
Input
1?AA
Output
100 | instruction | 0 | 32,831 | 6 | 65,662 |
Tags: math
Correct Solution:
```
input_str = input()
q=0
tmp = []
for c in input_str:
if c == '?':
q+=1
if 'A' <= c <= 'J' and tmp.count(c)==0:
tmp.append(c)
k=1
for i in range(len(tmp)):
k*=(10-i)
if input_str[0] == '?':
print(str(9 * k) + '0'*(q-1))
elif 'A' <= input_str[0] <= 'J':
print(str(9 * (k//10)) + '0'*q)
else:
print(str(k) + '0'*q)
``` | output | 1 | 32,831 | 6 | 65,663 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Special Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there.
The content special agent has got an important task: to get the latest research by British scientists on the English Language. These developments are encoded and stored in a large safe. The Beaver's teeth are strong enough, so the authorities assured that upon arriving at the place the beaver won't have any problems with opening the safe.
And he finishes his aspen sprig and leaves for this important task. Of course, the Beaver arrived at the location without any problems, but alas. He can't open the safe with his strong and big teeth. At this point, the Smart Beaver get a call from the headquarters and learns that opening the safe with the teeth is not necessary, as a reliable source has sent the following information: the safe code consists of digits and has no leading zeroes. There also is a special hint, which can be used to open the safe. The hint is string s with the following structure:
* if si = "?", then the digit that goes i-th in the safe code can be anything (between 0 to 9, inclusively);
* if si is a digit (between 0 to 9, inclusively), then it means that there is digit si on position i in code;
* if the string contains letters from "A" to "J", then all positions with the same letters must contain the same digits and the positions with distinct letters must contain distinct digits.
* The length of the safe code coincides with the length of the hint.
For example, hint "?JGJ9" has such matching safe code variants: "51919", "55959", "12329", "93539" and so on, and has wrong variants such as: "56669", "00111", "03539" and "13666".
After receiving such information, the authorities change the plan and ask the special agents to work quietly and gently and not to try to open the safe by mechanical means, and try to find the password using the given hint.
At a special agent school the Smart Beaver was the fastest in his platoon finding codes for such safes, but now he is not in that shape: the years take their toll ... Help him to determine the number of possible variants of the code to the safe, matching the given hint. After receiving this information, and knowing his own speed of entering codes, the Smart Beaver will be able to determine whether he will have time for tonight's show "Beavers are on the trail" on his favorite TV channel, or he should work for a sleepless night...
Input
The first line contains string s β the hint to the safe code. String s consists of the following characters: ?, 0-9, A-J. It is guaranteed that the first character of string s doesn't equal to character 0.
The input limits for scoring 30 points are (subproblem A1):
* 1 β€ |s| β€ 5.
The input limits for scoring 100 points are (subproblems A1+A2):
* 1 β€ |s| β€ 105.
Here |s| means the length of string s.
Output
Print the number of codes that match the given hint.
Examples
Input
AJ
Output
81
Input
1?AA
Output
100 | instruction | 0 | 32,832 | 6 | 65,664 |
Tags: math
Correct Solution:
```
#!/usr/bin/env python3
def solve():
s = input()
x = set()
f = False
r = 1
rc = 0
letter = set([c for c in 'ABCDEFGHIJ'])
if s[0] == '?':
r *= 9
if s[0] in letter:
x.add(s[0])
f = True
for c in s[1:]:
if c == '?':
rc += 1
if c in letter:
x.add(c)
for t in range(len(x)):
if t == 0 and f:
r *= 9
else:
r *= 10 - t;
r = str(r) + '0' * rc;
print(r)
solve()
``` | output | 1 | 32,832 | 6 | 65,665 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Special Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there.
The content special agent has got an important task: to get the latest research by British scientists on the English Language. These developments are encoded and stored in a large safe. The Beaver's teeth are strong enough, so the authorities assured that upon arriving at the place the beaver won't have any problems with opening the safe.
And he finishes his aspen sprig and leaves for this important task. Of course, the Beaver arrived at the location without any problems, but alas. He can't open the safe with his strong and big teeth. At this point, the Smart Beaver get a call from the headquarters and learns that opening the safe with the teeth is not necessary, as a reliable source has sent the following information: the safe code consists of digits and has no leading zeroes. There also is a special hint, which can be used to open the safe. The hint is string s with the following structure:
* if si = "?", then the digit that goes i-th in the safe code can be anything (between 0 to 9, inclusively);
* if si is a digit (between 0 to 9, inclusively), then it means that there is digit si on position i in code;
* if the string contains letters from "A" to "J", then all positions with the same letters must contain the same digits and the positions with distinct letters must contain distinct digits.
* The length of the safe code coincides with the length of the hint.
For example, hint "?JGJ9" has such matching safe code variants: "51919", "55959", "12329", "93539" and so on, and has wrong variants such as: "56669", "00111", "03539" and "13666".
After receiving such information, the authorities change the plan and ask the special agents to work quietly and gently and not to try to open the safe by mechanical means, and try to find the password using the given hint.
At a special agent school the Smart Beaver was the fastest in his platoon finding codes for such safes, but now he is not in that shape: the years take their toll ... Help him to determine the number of possible variants of the code to the safe, matching the given hint. After receiving this information, and knowing his own speed of entering codes, the Smart Beaver will be able to determine whether he will have time for tonight's show "Beavers are on the trail" on his favorite TV channel, or he should work for a sleepless night...
Input
The first line contains string s β the hint to the safe code. String s consists of the following characters: ?, 0-9, A-J. It is guaranteed that the first character of string s doesn't equal to character 0.
The input limits for scoring 30 points are (subproblem A1):
* 1 β€ |s| β€ 5.
The input limits for scoring 100 points are (subproblems A1+A2):
* 1 β€ |s| β€ 105.
Here |s| means the length of string s.
Output
Print the number of codes that match the given hint.
Examples
Input
AJ
Output
81
Input
1?AA
Output
100 | instruction | 0 | 32,833 | 6 | 65,666 |
Tags: math
Correct Solution:
```
s = input()
si = len(s)
res = 1
seen = {}
Len = 0
if '0'<= s[0] <='9':
pass
else:
if s[0] == '?':
res *= 9
else:
res*= 9
seen[s[0]] = 1
Len+= 1
tmp = ""
for i in range(1, si):
if '0'<=s[i] <='9':
pass
else:
if s[i] != '?':
if seen.get(s[i], 0) == 0:
res*= (10 - Len)
seen[s[i]] = 1
Len+= 1
else:
pass
else:
tmp+= '0'
print(res, tmp, sep = "")
``` | output | 1 | 32,833 | 6 | 65,667 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Special Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there.
The content special agent has got an important task: to get the latest research by British scientists on the English Language. These developments are encoded and stored in a large safe. The Beaver's teeth are strong enough, so the authorities assured that upon arriving at the place the beaver won't have any problems with opening the safe.
And he finishes his aspen sprig and leaves for this important task. Of course, the Beaver arrived at the location without any problems, but alas. He can't open the safe with his strong and big teeth. At this point, the Smart Beaver get a call from the headquarters and learns that opening the safe with the teeth is not necessary, as a reliable source has sent the following information: the safe code consists of digits and has no leading zeroes. There also is a special hint, which can be used to open the safe. The hint is string s with the following structure:
* if si = "?", then the digit that goes i-th in the safe code can be anything (between 0 to 9, inclusively);
* if si is a digit (between 0 to 9, inclusively), then it means that there is digit si on position i in code;
* if the string contains letters from "A" to "J", then all positions with the same letters must contain the same digits and the positions with distinct letters must contain distinct digits.
* The length of the safe code coincides with the length of the hint.
For example, hint "?JGJ9" has such matching safe code variants: "51919", "55959", "12329", "93539" and so on, and has wrong variants such as: "56669", "00111", "03539" and "13666".
After receiving such information, the authorities change the plan and ask the special agents to work quietly and gently and not to try to open the safe by mechanical means, and try to find the password using the given hint.
At a special agent school the Smart Beaver was the fastest in his platoon finding codes for such safes, but now he is not in that shape: the years take their toll ... Help him to determine the number of possible variants of the code to the safe, matching the given hint. After receiving this information, and knowing his own speed of entering codes, the Smart Beaver will be able to determine whether he will have time for tonight's show "Beavers are on the trail" on his favorite TV channel, or he should work for a sleepless night...
Input
The first line contains string s β the hint to the safe code. String s consists of the following characters: ?, 0-9, A-J. It is guaranteed that the first character of string s doesn't equal to character 0.
The input limits for scoring 30 points are (subproblem A1):
* 1 β€ |s| β€ 5.
The input limits for scoring 100 points are (subproblems A1+A2):
* 1 β€ |s| β€ 105.
Here |s| means the length of string s.
Output
Print the number of codes that match the given hint.
Examples
Input
AJ
Output
81
Input
1?AA
Output
100 | instruction | 0 | 32,834 | 6 | 65,668 |
Tags: math
Correct Solution:
```
s = str(input())
result = 1
n = len(s)
rozne = set()
pytajniki = 0
mnoznik_z_pierwszego = 1
for i in range(0,n):
if ord(s[i]) >= ord('0') and ord(s[i]) <= ord('9'):
continue;
elif ord(s[i]) >= ord('A') and ord(s[i]) <= ord('Z'):
rozne.add(ord(s[i]))
continue
else:
if i == 0:
mnoznik_z_pierwszego = 9
else:
pytajniki = pytajniki + 1
for i in range(0, len(rozne)):
result = result * (10 - i)
result = result * mnoznik_z_pierwszego
if ord(s[0]) >= ord('A') and ord(s[0]) <= ord('Z'):
result = result / 10 * 9
print(int(result), end="")
for i in range(pytajniki):
print("0", end="")
print()
``` | output | 1 | 32,834 | 6 | 65,669 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Special Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there.
The content special agent has got an important task: to get the latest research by British scientists on the English Language. These developments are encoded and stored in a large safe. The Beaver's teeth are strong enough, so the authorities assured that upon arriving at the place the beaver won't have any problems with opening the safe.
And he finishes his aspen sprig and leaves for this important task. Of course, the Beaver arrived at the location without any problems, but alas. He can't open the safe with his strong and big teeth. At this point, the Smart Beaver get a call from the headquarters and learns that opening the safe with the teeth is not necessary, as a reliable source has sent the following information: the safe code consists of digits and has no leading zeroes. There also is a special hint, which can be used to open the safe. The hint is string s with the following structure:
* if si = "?", then the digit that goes i-th in the safe code can be anything (between 0 to 9, inclusively);
* if si is a digit (between 0 to 9, inclusively), then it means that there is digit si on position i in code;
* if the string contains letters from "A" to "J", then all positions with the same letters must contain the same digits and the positions with distinct letters must contain distinct digits.
* The length of the safe code coincides with the length of the hint.
For example, hint "?JGJ9" has such matching safe code variants: "51919", "55959", "12329", "93539" and so on, and has wrong variants such as: "56669", "00111", "03539" and "13666".
After receiving such information, the authorities change the plan and ask the special agents to work quietly and gently and not to try to open the safe by mechanical means, and try to find the password using the given hint.
At a special agent school the Smart Beaver was the fastest in his platoon finding codes for such safes, but now he is not in that shape: the years take their toll ... Help him to determine the number of possible variants of the code to the safe, matching the given hint. After receiving this information, and knowing his own speed of entering codes, the Smart Beaver will be able to determine whether he will have time for tonight's show "Beavers are on the trail" on his favorite TV channel, or he should work for a sleepless night...
Input
The first line contains string s β the hint to the safe code. String s consists of the following characters: ?, 0-9, A-J. It is guaranteed that the first character of string s doesn't equal to character 0.
The input limits for scoring 30 points are (subproblem A1):
* 1 β€ |s| β€ 5.
The input limits for scoring 100 points are (subproblems A1+A2):
* 1 β€ |s| β€ 105.
Here |s| means the length of string s.
Output
Print the number of codes that match the given hint.
Examples
Input
AJ
Output
81
Input
1?AA
Output
100 | instruction | 0 | 32,835 | 6 | 65,670 |
Tags: math
Correct Solution:
```
#316A2
hint = input()
possibilities = 1
zeroes = 0
letters = "ABCDEFGHIJ"
if hint[0] in letters:
possibilities *= 9
i = letters.index(hint[0])
letters = letters[:i] + letters[i+1:]
if hint[0] == "?":
possibilities *= 9
hint = hint[1:]
for char in hint:
if char == "?":
zeroes += 1
elif char in letters:
possibilities *= len(letters)
i = letters.index(char)
letters = letters[:i] + letters[i+1:]
print(str(possibilities)+"0"*zeroes)
``` | output | 1 | 32,835 | 6 | 65,671 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Special Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there.
The content special agent has got an important task: to get the latest research by British scientists on the English Language. These developments are encoded and stored in a large safe. The Beaver's teeth are strong enough, so the authorities assured that upon arriving at the place the beaver won't have any problems with opening the safe.
And he finishes his aspen sprig and leaves for this important task. Of course, the Beaver arrived at the location without any problems, but alas. He can't open the safe with his strong and big teeth. At this point, the Smart Beaver get a call from the headquarters and learns that opening the safe with the teeth is not necessary, as a reliable source has sent the following information: the safe code consists of digits and has no leading zeroes. There also is a special hint, which can be used to open the safe. The hint is string s with the following structure:
* if si = "?", then the digit that goes i-th in the safe code can be anything (between 0 to 9, inclusively);
* if si is a digit (between 0 to 9, inclusively), then it means that there is digit si on position i in code;
* if the string contains letters from "A" to "J", then all positions with the same letters must contain the same digits and the positions with distinct letters must contain distinct digits.
* The length of the safe code coincides with the length of the hint.
For example, hint "?JGJ9" has such matching safe code variants: "51919", "55959", "12329", "93539" and so on, and has wrong variants such as: "56669", "00111", "03539" and "13666".
After receiving such information, the authorities change the plan and ask the special agents to work quietly and gently and not to try to open the safe by mechanical means, and try to find the password using the given hint.
At a special agent school the Smart Beaver was the fastest in his platoon finding codes for such safes, but now he is not in that shape: the years take their toll ... Help him to determine the number of possible variants of the code to the safe, matching the given hint. After receiving this information, and knowing his own speed of entering codes, the Smart Beaver will be able to determine whether he will have time for tonight's show "Beavers are on the trail" on his favorite TV channel, or he should work for a sleepless night...
Input
The first line contains string s β the hint to the safe code. String s consists of the following characters: ?, 0-9, A-J. It is guaranteed that the first character of string s doesn't equal to character 0.
The input limits for scoring 30 points are (subproblem A1):
* 1 β€ |s| β€ 5.
The input limits for scoring 100 points are (subproblems A1+A2):
* 1 β€ |s| β€ 105.
Here |s| means the length of string s.
Output
Print the number of codes that match the given hint.
Examples
Input
AJ
Output
81
Input
1?AA
Output
100 | instruction | 0 | 32,836 | 6 | 65,672 |
Tags: math
Correct Solution:
```
from sys import *
from math import *
s = stdin.readline().strip()
ans = 1
now = 10
was = {}
was['A'] = False
was['B'] = False
was['C'] = False
was['D'] = False
was['E'] = False
was['F'] = False
was['G'] = False
was['H'] = False
was['I'] = False
was['J'] = False
if s[0] == '?':
ans *= 9
if (ord(s[0]) >= ord('A')) and (ord(s[0]) <= ord('J')):
ans *= 9
was[s[0]] = True
now = 9
cnt = 0
for i in range(1, len(s)):
if s[i] == '?':
cnt += 1
if (ord(s[i]) >= ord('A')) and (ord(s[i]) <= ord('J')):
if was[s[i]] == False:
ans *= now
now -= 1
was[s[i]] = True
print(ans, end = "")
for i in range(cnt):
print('0', end = "")
print()
``` | output | 1 | 32,836 | 6 | 65,673 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.