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.
Background
The kindergarten attached to the University of Aizu is a kindergarten where children who love programming gather. Yu, one of the kindergarten children, loves lowercase letters as much as programming. Yu-kun decided to write a scoring program for a new play that uses paper, circles, lines, and lowercase letters.
Problem
Initially, V circles and E lines are drawn on the paper. The circles are numbered from 0 in ascending order, with one lowercase letter or nothing in each circle. Each line connects two different circles. A circle cannot be connected by more than 26 lines.
The play procedure is as follows.
1. Select one circle with nothing written on it. If such a circle does not exist, this process ends.
2. Write one lowercase letter in the circle. However, if the circle is already connected to a circle with lowercase letters by a line, the same lowercase letters as the lowercase letters cannot be written.
3. Return to 1.
After writing lowercase letters in all the circles according to the above procedure, arrange the lowercase letters in the circles in ascending order of the circle numbers to make a character string. I want to minimize the character strings that can be created in this way in lexicographical order. There are two strings s and t of the same length, and s is smaller than t in lexicographical order in the following cases. si represents the i-th lowercase letter of the string s and ti represents the i-th lowercase letter of the string t. For the smallest i where si differs from ti, si is less than ti.
Since the initial state of the paper is given, output the smallest character string that can be created according to the above procedure in lexicographical order.
Constraints
The input satisfies the following conditions.
* 1 β€ V β€ 100,000
* 0 β€ E β€ 200,000
* ai is either lowercase or'?' (0 β€ i β€ V-1)
* 0 β€ si, ti β€ V-1 (si <ti, 0 β€ i β€ E-1)
* One circle cannot be connected by more than 26 lines
Input
V E
a0 a1 ... a (V-1)
s0 t0
s1 t1
...
s (E-1) t (E-1)
The number of circles V and the number of lines E are given on the first line, separated by blanks.
The initial state of the circle is given on the second line, separated by blanks.
If ai is a lowercase letter, the lowercase letter is written in the i-th circle, and if it is'?', It means that nothing is written in the i-th circle.
The line information is given as si ti on the following E line, which means that the si and ti circles are connected by a line.
Output
Output the smallest character string in the dictionary order on one line among the character strings that can be created according to the procedure in the question sentence.
Examples
Input
3 3
c ? ?
0 1
0 2
1 2
Output
cab
Input
3 2
c ? ?
0 1
0 2
Output
caa
Input
7 6
? a ? ? z a ?
0 1
0 2
3 4
4 5
4 6
5 6
Output
baaazab
Input
5 0
? ? ? ? ?
Output
aaaaa | instruction | 0 | 37,705 | 6 | 75,410 |
"Correct Solution:
```
v, e = map(int, input().split())
a_lst = input().split()
edges = [[] for _ in range(v)]
for _ in range(e):
s, t = map(int, input().split())
edges[s].append(t)
edges[t].append(s)
for i in range(v):
if "a" <= a_lst[i] <= "z": continue
lst = {i for i in range(26)}
for fr in edges[i]:
lst.discard(ord(a_lst[fr]) - ord("a"))
a_lst[i] = chr(min(lst) + ord("a"))
print("".join(a_lst))
``` | output | 1 | 37,705 | 6 | 75,411 |
Provide a correct Python 3 solution for this coding contest problem.
Background
The kindergarten attached to the University of Aizu is a kindergarten where children who love programming gather. Yu, one of the kindergarten children, loves lowercase letters as much as programming. Yu-kun decided to write a scoring program for a new play that uses paper, circles, lines, and lowercase letters.
Problem
Initially, V circles and E lines are drawn on the paper. The circles are numbered from 0 in ascending order, with one lowercase letter or nothing in each circle. Each line connects two different circles. A circle cannot be connected by more than 26 lines.
The play procedure is as follows.
1. Select one circle with nothing written on it. If such a circle does not exist, this process ends.
2. Write one lowercase letter in the circle. However, if the circle is already connected to a circle with lowercase letters by a line, the same lowercase letters as the lowercase letters cannot be written.
3. Return to 1.
After writing lowercase letters in all the circles according to the above procedure, arrange the lowercase letters in the circles in ascending order of the circle numbers to make a character string. I want to minimize the character strings that can be created in this way in lexicographical order. There are two strings s and t of the same length, and s is smaller than t in lexicographical order in the following cases. si represents the i-th lowercase letter of the string s and ti represents the i-th lowercase letter of the string t. For the smallest i where si differs from ti, si is less than ti.
Since the initial state of the paper is given, output the smallest character string that can be created according to the above procedure in lexicographical order.
Constraints
The input satisfies the following conditions.
* 1 β€ V β€ 100,000
* 0 β€ E β€ 200,000
* ai is either lowercase or'?' (0 β€ i β€ V-1)
* 0 β€ si, ti β€ V-1 (si <ti, 0 β€ i β€ E-1)
* One circle cannot be connected by more than 26 lines
Input
V E
a0 a1 ... a (V-1)
s0 t0
s1 t1
...
s (E-1) t (E-1)
The number of circles V and the number of lines E are given on the first line, separated by blanks.
The initial state of the circle is given on the second line, separated by blanks.
If ai is a lowercase letter, the lowercase letter is written in the i-th circle, and if it is'?', It means that nothing is written in the i-th circle.
The line information is given as si ti on the following E line, which means that the si and ti circles are connected by a line.
Output
Output the smallest character string in the dictionary order on one line among the character strings that can be created according to the procedure in the question sentence.
Examples
Input
3 3
c ? ?
0 1
0 2
1 2
Output
cab
Input
3 2
c ? ?
0 1
0 2
Output
caa
Input
7 6
? a ? ? z a ?
0 1
0 2
3 4
4 5
4 6
5 6
Output
baaazab
Input
5 0
? ? ? ? ?
Output
aaaaa | instruction | 0 | 37,706 | 6 | 75,412 |
"Correct Solution:
```
V_, E_ = map(int, input().split())
A = input().split()
E = [[] for _ in range(V_)]
Used = [[False]*26 for _ in range(V_)]
for _ in range(E_):
s, t = map(int, input().split())
As, At = A[s], A[t]
if As != "?":
Used[t][ord(As)-97] = True
if At != "?":
Used[s][ord(At)-97] = True
E[s].append(t)
E[t].append(s)
for i, a in enumerate(A):
if a == "?":
for j in range(26):
if not Used[i][j]:
A[i] = chr(j + 97)
for u in E[i]:
Used[u][j] = True
break
print("".join(A))
``` | output | 1 | 37,706 | 6 | 75,413 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules:
* There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb.
* There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine.
* Masculine adjectives end with -lios, and feminine adjectives end with -liala.
* Masculine nouns end with -etr, and feminime nouns end with -etra.
* Masculine verbs end with -initis, and feminime verbs end with -inites.
* Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language.
* It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language.
* There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications.
* A sentence is either exactly one valid language word or exactly one statement.
Statement is any sequence of the Petya's language, that satisfy both conditions:
* Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs.
* All words in the statement should have the same gender.
After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language.
Input
The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105.
It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language.
Output
If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes).
Examples
Input
petr
Output
YES
Input
etis atis animatis etis atis amatis
Output
NO
Input
nataliala kataliala vetra feinites
Output
YES | instruction | 0 | 37,810 | 6 | 75,620 |
Tags: implementation, strings
Correct Solution:
```
words = [c for c in input().split()]
verdict = True
category = ["" for i in range(len(words))]
gender = ["" for i in range(len(words))]
for i in range(len(words)):
if (not verdict): break
if (len(words[i]) < 3): verdict = False
elif (words[i][-3:] == "etr"):
category[i] = "noun"
gender[i] = "male"
elif (len(words[i]) >= 4 and words[i][-4:] == "etra"):
category[i] = "noun"
gender[i] = "female"
elif ((len(words[i]) >= 4 and words[i][-4:] == "lios")):
category[i] = "adjective"
gender[i] = "male"
elif (len(words[i]) >= 5 and words[i][-5:] == "liala"):
category[i] = "adjective"
gender[i] = "female"
elif (len(words[i]) >= 6):
category[i] = "verb"
if (words[i][-6:] == "initis"): gender[i] = "male"
elif (words[i][-6:] == "inites"): gender[i] = "female"
else: verdict = False
else: verdict = False
first_noun = -1
for i in range(len(category)):
if (not verdict): break
if (category[i] == "noun"):
first_noun = i
break
if (first_noun == -1 and len(words) > 1): verdict = False
elif (first_noun != -1 and verdict):
left, right = first_noun - 1, first_noun + 1
while (left >= 0 and category[left] == "adjective" and gender[left] == gender[first_noun]): left -= 1
while (right < len(category) and category[right] == "verb" and gender[right] == gender[first_noun]): right += 1
if (left >= 0 or right < len(category)): verdict = False
print(("NO" if (not verdict) else "YES"))
``` | output | 1 | 37,810 | 6 | 75,621 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules:
* There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb.
* There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine.
* Masculine adjectives end with -lios, and feminine adjectives end with -liala.
* Masculine nouns end with -etr, and feminime nouns end with -etra.
* Masculine verbs end with -initis, and feminime verbs end with -inites.
* Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language.
* It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language.
* There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications.
* A sentence is either exactly one valid language word or exactly one statement.
Statement is any sequence of the Petya's language, that satisfy both conditions:
* Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs.
* All words in the statement should have the same gender.
After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language.
Input
The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105.
It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language.
Output
If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes).
Examples
Input
petr
Output
YES
Input
etis atis animatis etis atis amatis
Output
NO
Input
nataliala kataliala vetra feinites
Output
YES | instruction | 0 | 37,811 | 6 | 75,622 |
Tags: implementation, strings
Correct Solution:
```
import re
def f(x):
if x.endswith("lios"): return 1
elif x.endswith("liala"): return -1
elif x.endswith("etr"): return 2
elif x.endswith("etra"): return -2
elif x.endswith("initis"):return 3
elif x.endswith("inites"): return -3
else: return 0
a,b=input().strip().split(),[]
for s in a:b.append(f(s))
if len(b)==1:
if b[0]!=0:print("YES")
else:print("NO")
else:
for x in b:
if b[0]*x <= 0:
print("NO")
exit()
c=""
for x in b:c+=str(abs(x))
sbl=re.compile(r'^1*23*$')
if sbl.match(c):
print("YES")
else:
print("NO")
``` | output | 1 | 37,811 | 6 | 75,623 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules:
* There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb.
* There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine.
* Masculine adjectives end with -lios, and feminine adjectives end with -liala.
* Masculine nouns end with -etr, and feminime nouns end with -etra.
* Masculine verbs end with -initis, and feminime verbs end with -inites.
* Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language.
* It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language.
* There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications.
* A sentence is either exactly one valid language word or exactly one statement.
Statement is any sequence of the Petya's language, that satisfy both conditions:
* Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs.
* All words in the statement should have the same gender.
After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language.
Input
The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105.
It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language.
Output
If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes).
Examples
Input
petr
Output
YES
Input
etis atis animatis etis atis amatis
Output
NO
Input
nataliala kataliala vetra feinites
Output
YES | instruction | 0 | 37,812 | 6 | 75,624 |
Tags: implementation, strings
Correct Solution:
```
lista = input().split()
passadj = False
passsub = False
gender = -1
can = True
canF = True
# verificando os generos das palavras
for i in range(0,len(lista)):
if (len(lista[i]) >= 3 and lista[i][len(lista[i])-3::] == "etr") or (len(lista[i]) >= 4 and lista[i][len(lista[i])-4::] == "lios") or (len(lista[i]) >= 6 and lista[i][len(lista[i])-6::] == "initis"):
if gender == -1:
gender = 1
elif gender == 2:
can = False
else:
if gender == -1:
gender = 2
elif gender == 1:
can = False
# print(can)
# verificando os blocos
for i in range(0, len(lista)):
if (len(lista[i]) >= 4 and lista[i][len(lista[i])-4::] == "lios") or (len(lista[i]) >= 5 and lista[i][len(lista[i])-5::] == "liala"):
if(passadj == True):
can = False
elif (len(lista[i]) >= 3 and lista[i][len(lista[i])-3::] == "etr") or (len(lista[i]) >= 4 and lista[i][len(lista[i])-4::] == "etra"):
passadj = True
if passsub == True:
can = False
else:
passsub = True
elif (len(lista[i]) >= 6 and lista[i][len(lista[i])-6::] == "initis") or (len(lista[i]) >= 6 and lista[i][len(lista[i])-6::] == "inites"):
if passadj == False or passsub == False:
can = False
else:
canF = False
# print(can)
if (len(lista)==1 and canF) or (passsub and canF and can):
print("YES\n")
else:
print("NO\n")
``` | output | 1 | 37,812 | 6 | 75,625 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules:
* There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb.
* There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine.
* Masculine adjectives end with -lios, and feminine adjectives end with -liala.
* Masculine nouns end with -etr, and feminime nouns end with -etra.
* Masculine verbs end with -initis, and feminime verbs end with -inites.
* Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language.
* It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language.
* There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications.
* A sentence is either exactly one valid language word or exactly one statement.
Statement is any sequence of the Petya's language, that satisfy both conditions:
* Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs.
* All words in the statement should have the same gender.
After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language.
Input
The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105.
It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language.
Output
If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes).
Examples
Input
petr
Output
YES
Input
etis atis animatis etis atis amatis
Output
NO
Input
nataliala kataliala vetra feinites
Output
YES | instruction | 0 | 37,813 | 6 | 75,626 |
Tags: implementation, strings
Correct Solution:
```
words = input().split()
adj = ['lios', 'liala']
nouns = ['etr', 'etra']
verbs = ['initis', 'inites']
mascul = [adj[0], nouns[0], verbs[0]]
femine = [adj[1], nouns[1], verbs[1]]
good = True
if len(words) > 1:
masc = False
femi = False
if any([x == words[0][-len(x):] for x in mascul]):
masc = True
elif any([x == words[0][-len(x):] for x in femine]):
femi = True
else:
good = False
if masc:
for i in range(len(words)):
if not any([x == words[i][-len(x):] for x in mascul]):
good = False
if femi:
for i in range(len(words)):
if not any([x == words[i][-len(x):] for x in femine]):
good = False
if good and masc:
i = 0
while i < len(words) and words[i][-len(mascul[0]):] == mascul[0]: i += 1
if i == len(words) or words[i][-len(nouns[0]):] != nouns[0]:
good = False
i += 1
while i < len(words):
if words[i][-len(verbs[0]):] != verbs[0]:
good = False
break
i += 1
if good and femi:
i = 0
while i < len(words) and words[i][-len(femine[0]):] == femine[0]: i += 1
if i == len(words) or words[i][-len(nouns[1]):] != nouns[1]:
good = False
i += 1
while i < len(words):
if words[i][-len(verbs[1]):] != verbs[1]:
good = False
break
i += 1
else:
if not any([x == words[0][-len(x):] for x in (mascul + femine)]):
good = False
if good:
print("YES")
else:
print("NO")
``` | output | 1 | 37,813 | 6 | 75,627 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules:
* There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb.
* There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine.
* Masculine adjectives end with -lios, and feminine adjectives end with -liala.
* Masculine nouns end with -etr, and feminime nouns end with -etra.
* Masculine verbs end with -initis, and feminime verbs end with -inites.
* Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language.
* It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language.
* There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications.
* A sentence is either exactly one valid language word or exactly one statement.
Statement is any sequence of the Petya's language, that satisfy both conditions:
* Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs.
* All words in the statement should have the same gender.
After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language.
Input
The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105.
It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language.
Output
If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes).
Examples
Input
petr
Output
YES
Input
etis atis animatis etis atis amatis
Output
NO
Input
nataliala kataliala vetra feinites
Output
YES | instruction | 0 | 37,814 | 6 | 75,628 |
Tags: implementation, strings
Correct Solution:
```
s = input().split(' ');
a = []
b = [0] * 6
for x in s:
if x[-4:] == "lios":
a.append(0)
b[0] += 1
elif x[-5:] == "liala":
a.append(3)
b[3] += 1
elif x[-3:] == "etr":
a.append(1)
b[1] += 1
elif x[-4:] == "etra":
a.append(4)
b[4] += 1
elif x[-6:] == "initis":
a.append(2)
b[2] += 1
elif x[-6:] == "inites":
a.append(5)
b[5] += 1
else :
print("NO")
# print(b,a)
exit(0)
# print(b,a)
if len(s) == 1 and (b[0] > 0 or b[1] > 0 or b[2] > 0 or b[3] > 0 or b[4] > 0 or b[5] > 0):
print("YES")
exit(0)
if (b[0] > 0 or b[1] > 0 or b[2] > 0) and (b[3] > 0 or b[4] > 0 or b[5] > 0) :
print("NO")
exit(0)
if not (b[1] == 1 or b[4] == 1):
print("NO")
exit(0)
n = len(s)
for i in range(1, n):
if(a[i] < a[i - 1]) :
print("NO")
exit(0)
print("YES")
``` | output | 1 | 37,814 | 6 | 75,629 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules:
* There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb.
* There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine.
* Masculine adjectives end with -lios, and feminine adjectives end with -liala.
* Masculine nouns end with -etr, and feminime nouns end with -etra.
* Masculine verbs end with -initis, and feminime verbs end with -inites.
* Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language.
* It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language.
* There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications.
* A sentence is either exactly one valid language word or exactly one statement.
Statement is any sequence of the Petya's language, that satisfy both conditions:
* Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs.
* All words in the statement should have the same gender.
After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language.
Input
The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105.
It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language.
Output
If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes).
Examples
Input
petr
Output
YES
Input
etis atis animatis etis atis amatis
Output
NO
Input
nataliala kataliala vetra feinites
Output
YES | instruction | 0 | 37,815 | 6 | 75,630 |
Tags: implementation, strings
Correct Solution:
```
# from dust i have come dust i will be
#each should be of same gender
#adjective*-noun*1-verb*
a=list(map(str,input().split()))
t=[0]*len(a)
str=["lios","liala","etr","etra","initis","inites"]
if len(a)==1:
for i in range(6):
if a[0].endswith(str[i]):
print("YES")
exit(0)
print("NO")
exit(0)
for i in range(len(a)):
for j in range(6):
if a[i].endswith(str[j]):
t[i]=j+1
break
#not belonging in any language
if t[i]==0:
print("NO")
exit(0)
#all the t[]'s should be either or odd
rem=t[0]%2
for i in range(len(t)):
if t[i]%2!=rem:
print("NO")
exit(0)
x=sorted(t)
cnt=0
for i in range(len(t)):
if t[i]==3 or t[i]==4:
cnt+=1
if t[i]!=x[i]:
print("NO")
exit(0)
if cnt==1:
print("YES")
else:
print("NO")
``` | output | 1 | 37,815 | 6 | 75,631 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules:
* There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb.
* There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine.
* Masculine adjectives end with -lios, and feminine adjectives end with -liala.
* Masculine nouns end with -etr, and feminime nouns end with -etra.
* Masculine verbs end with -initis, and feminime verbs end with -inites.
* Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language.
* It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language.
* There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications.
* A sentence is either exactly one valid language word or exactly one statement.
Statement is any sequence of the Petya's language, that satisfy both conditions:
* Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs.
* All words in the statement should have the same gender.
After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language.
Input
The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105.
It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language.
Output
If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes).
Examples
Input
petr
Output
YES
Input
etis atis animatis etis atis amatis
Output
NO
Input
nataliala kataliala vetra feinites
Output
YES
Submitted Solution:
```
words = [c for c in input().split()]
verdict = True
category = ["" for i in range(len(words))]
for i in range(len(words)):
if (not verdict): break
if (len(words[i]) < 3): verdict = False
elif (words[i][-3:] == "etr" or (len(words[i]) >= 4 and words[i][-4:] == "etra")): category[i] = "noun"
elif ((len(words[i]) >= 4 and words[i][-4:] == "lios") or (len(words[i]) >= 5 and words[i][-5:] == "liala")): category[i] = "adjective"
elif (len(words[i]) >= 6 and (words[i][-6:] == "initis" or words[i][-6:] == "inites")): category[i] = "verb"
else: verdict = False
first_noun = -1
for i in range(len(category)):
if (category[i] == "noun"):
first_noun = i
break
if (first_noun == -1): verdict = False
else:
left, right = first_noun - 1, first_noun + 1
while (left >= 0 and category[left] != "noun"): left -= 1
while (right < len(category) and category[right] != "noun"): right += 1
if (left >= 0 or right < len(category)): verdict = False
print(("NO" if (not verdict) else "YES"))
``` | instruction | 0 | 37,816 | 6 | 75,632 |
No | output | 1 | 37,816 | 6 | 75,633 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules:
* There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb.
* There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine.
* Masculine adjectives end with -lios, and feminine adjectives end with -liala.
* Masculine nouns end with -etr, and feminime nouns end with -etra.
* Masculine verbs end with -initis, and feminime verbs end with -inites.
* Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language.
* It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language.
* There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications.
* A sentence is either exactly one valid language word or exactly one statement.
Statement is any sequence of the Petya's language, that satisfy both conditions:
* Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs.
* All words in the statement should have the same gender.
After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language.
Input
The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105.
It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language.
Output
If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes).
Examples
Input
petr
Output
YES
Input
etis atis animatis etis atis amatis
Output
NO
Input
nataliala kataliala vetra feinites
Output
YES
Submitted Solution:
```
s = input().split(' ');
a = []
b = [0] * 6
for x in s:
if x[-4:] == "lios":
a.append(0)
b[0] += 1
elif x[-5:] == "liala":
a.append(3)
b[3] += 1
elif x[-3:] == "etr":
a.append(1)
b[1] += 1
elif x[-4:] == "etra":
a.append(4)
b[4] += 1
elif x[-6:] == "initis":
a.append(2)
b[2] += 1
elif x[-6:] == "inites":
a.append(5)
b[5] += 1
else :
print("NO")
# print(b,a)
exit(0)
# print(b,a)
if (b[0] > 0 or b[1] > 0 or b[2] > 0) and (b[3] > 0 or b[4] > 0 or b[5] > 0) :
print("NO")
exit(0)
if not (b[1] == 1 or b[4] == 1):
print("NO")
exit(0)
n = len(s)
for i in range(1, n):
if(a[i] < a[i - 1]) :
print("NO")
exit(0)
print("YES")
``` | instruction | 0 | 37,817 | 6 | 75,634 |
No | output | 1 | 37,817 | 6 | 75,635 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules:
* There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb.
* There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine.
* Masculine adjectives end with -lios, and feminine adjectives end with -liala.
* Masculine nouns end with -etr, and feminime nouns end with -etra.
* Masculine verbs end with -initis, and feminime verbs end with -inites.
* Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language.
* It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language.
* There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications.
* A sentence is either exactly one valid language word or exactly one statement.
Statement is any sequence of the Petya's language, that satisfy both conditions:
* Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs.
* All words in the statement should have the same gender.
After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language.
Input
The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105.
It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language.
Output
If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes).
Examples
Input
petr
Output
YES
Input
etis atis animatis etis atis amatis
Output
NO
Input
nataliala kataliala vetra feinites
Output
YES
Submitted Solution:
```
words = [c for c in input().split()]
verdict = True
category = ["" for i in range(len(words))]
for i in range(len(words)):
if (not verdict): break
if (len(words[i]) < 3): verdict = False
elif (words[i][-3:] == "etr" or (len(words[i]) >= 4 and words[i][-4:] == "etra")): category[i] = "noun"
elif ((len(words[i]) >= 4 and words[i][-4:] == "lios") or (len(words[i]) >= 5 and words[i][-5:] == "liala")): category[i] = "adjective"
elif (len(words[i]) >= 6 and (words[i][-6:] == "initis" or words[i][-6:] == "inites")): category[i] = "verb"
else: verdict = False
first_noun = -1
for i in range(len(category)):
if (not verdict): break
if (category[i] == "noun"):
first_noun = i
break
if (first_noun == -1 and len(words) > 1): verdict = False
elif (first_noun != -1 and verdict):
left, right = first_noun - 1, first_noun + 1
while (left >= 0 and category[left] == "adjective"): left -= 1
while (right < len(category) and category[right] == "verb"): right += 1
if (left >= 0 or right < len(category)): verdict = False
print(("NO" if (not verdict) else "YES"))
``` | instruction | 0 | 37,818 | 6 | 75,636 |
No | output | 1 | 37,818 | 6 | 75,637 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules:
* There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb.
* There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine.
* Masculine adjectives end with -lios, and feminine adjectives end with -liala.
* Masculine nouns end with -etr, and feminime nouns end with -etra.
* Masculine verbs end with -initis, and feminime verbs end with -inites.
* Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language.
* It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language.
* There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications.
* A sentence is either exactly one valid language word or exactly one statement.
Statement is any sequence of the Petya's language, that satisfy both conditions:
* Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs.
* All words in the statement should have the same gender.
After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language.
Input
The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105.
It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language.
Output
If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes).
Examples
Input
petr
Output
YES
Input
etis atis animatis etis atis amatis
Output
NO
Input
nataliala kataliala vetra feinites
Output
YES
Submitted Solution:
```
words = [c for c in input().split()]
verdict = True
category = ["" for i in range(len(words))]
for i in range(len(words)):
if (not verdict): break
if (len(words[i]) < 3): verdict = False
elif (words[i][-3:] == "etr" or (len(words[i]) >= 4 and words[i][-4:] == "etra")): category[i] = "noun"
elif ((len(words[i]) >= 4 and words[i][-4:] == "lios") or (len(words[i]) >= 5 and words[i][-5:] == "liala")): category[i] = "adjective"
elif (len(words[i]) >= 6 and (words[i][-6:] == "initis" or words[i][-6:] == "inites")): category[i] = "verb"
else: verdict = False
first_noun = -1
for i in range(len(category)):
if (category[i] == "noun"):
first_noun = i
break
if (first_noun == -1 and len(words) > 1): verdict = False
elif (first_noun != -1):
left, right = first_noun - 1, first_noun + 1
while (left >= 0 and category[left] != "noun"): left -= 1
while (right < len(category) and category[right] != "noun"): right += 1
if (left >= 0 or right < len(category)): verdict = False
print(("NO" if (not verdict) else "YES"))
``` | instruction | 0 | 37,819 | 6 | 75,638 |
No | output | 1 | 37,819 | 6 | 75,639 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Many countries have such a New Year or Christmas tradition as writing a letter to Santa including a wish list for presents. Vasya is an ordinary programmer boy. Like all ordinary boys, he is going to write the letter to Santa on the New Year Eve (we Russians actually expect Santa for the New Year, not for Christmas).
Vasya has come up with an algorithm he will follow while writing a letter. First he chooses two strings, s1 anf s2, consisting of uppercase English letters. Then the boy makes string sk, using a recurrent equation sn = sn - 2 + sn - 1, operation '+' means a concatenation (that is, the sequential record) of strings in the given order. Then Vasya writes down string sk on a piece of paper, puts it in the envelope and sends in to Santa.
Vasya is absolutely sure that Santa will bring him the best present if the resulting string sk has exactly x occurrences of substring AC (the short-cut reminds him ΠΎf accepted problems). Besides, Vasya decided that string s1 should have length n, and string s2 should have length m. Vasya hasn't decided anything else.
At the moment Vasya's got urgent New Year business, so he asks you to choose two strings for him, s1 and s2 in the required manner. Help Vasya.
Input
The first line contains four integers k, x, n, m (3 β€ k β€ 50; 0 β€ x β€ 109; 1 β€ n, m β€ 100).
Output
In the first line print string s1, consisting of n uppercase English letters. In the second line print string s2, consisting of m uppercase English letters. If there are multiple valid strings, print any of them.
If the required pair of strings doesn't exist, print "Happy new year!" without the quotes.
Examples
Input
3 2 2 2
Output
AC
AC
Input
3 3 2 2
Output
Happy new year!
Input
3 0 2 2
Output
AA
AA
Input
4 3 2 1
Output
Happy new year!
Input
4 2 2 1
Output
Happy new year! | instruction | 0 | 38,006 | 6 | 76,012 |
Tags: bitmasks, brute force, dp
Correct Solution:
```
import sys
import itertools
k, x, n, m = map(int, input().split())
def valid(inicio, fim, tamanho, num_ac):
if num_ac == 0:
if tamanho == 1:
return ("" if inicio != fim else inicio)
elif tamanho == 2:
return (inicio + fim if inicio + fim != "AC" else "")
else:
return inicio + "B" * (tamanho - 2) + fim
s = "AC" * num_ac
if (not s) or s[0] != inicio:
s = inicio + s
if len(s) > tamanho or len(s) == tamanho and s[-1] != fim:
return ""
s += fim * (tamanho - len(s))
return s
a = [0] * 51
a[1] = 1
b = [0] * 51
b[2] = 1
for i in range(3, 51):
a[i] = a[i-2] + a[i-1]
b[i] = b[i-2] + b[i-1]
for letters in itertools.product(['A', 'B', 'C'], repeat=4):
first_s1 = letters[0]
last_s1 = letters[1]
first_s2 = letters[2]
last_s2 = letters[3]
c = [0] * 51
meio = last_s1 + first_s2
c[3] = (1 if meio == "AC" else 0)
for i in range(4, 51):
meio = last_s2 + (first_s1 if i % 2 == 0 else first_s2)
c[i] = c[i-2] + c[i-1] + (1 if meio == "AC" else 0)
for occ1 in range(0, 51):
tmp = x - a[k] * occ1 - c[k]
if tmp % b[k] != 0:
continue
tmp = tmp//b[k]
if tmp < 0 or tmp > 50:
continue
s1 = valid(first_s1, last_s1, n, occ1)
s2 = valid(first_s2, last_s2, m, tmp)
if s1 and s2:
print(s1)
print(s2)
sys.exit(0)
print("Happy new year!")
``` | output | 1 | 38,006 | 6 | 76,013 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Many countries have such a New Year or Christmas tradition as writing a letter to Santa including a wish list for presents. Vasya is an ordinary programmer boy. Like all ordinary boys, he is going to write the letter to Santa on the New Year Eve (we Russians actually expect Santa for the New Year, not for Christmas).
Vasya has come up with an algorithm he will follow while writing a letter. First he chooses two strings, s1 anf s2, consisting of uppercase English letters. Then the boy makes string sk, using a recurrent equation sn = sn - 2 + sn - 1, operation '+' means a concatenation (that is, the sequential record) of strings in the given order. Then Vasya writes down string sk on a piece of paper, puts it in the envelope and sends in to Santa.
Vasya is absolutely sure that Santa will bring him the best present if the resulting string sk has exactly x occurrences of substring AC (the short-cut reminds him ΠΎf accepted problems). Besides, Vasya decided that string s1 should have length n, and string s2 should have length m. Vasya hasn't decided anything else.
At the moment Vasya's got urgent New Year business, so he asks you to choose two strings for him, s1 and s2 in the required manner. Help Vasya.
Input
The first line contains four integers k, x, n, m (3 β€ k β€ 50; 0 β€ x β€ 109; 1 β€ n, m β€ 100).
Output
In the first line print string s1, consisting of n uppercase English letters. In the second line print string s2, consisting of m uppercase English letters. If there are multiple valid strings, print any of them.
If the required pair of strings doesn't exist, print "Happy new year!" without the quotes.
Examples
Input
3 2 2 2
Output
AC
AC
Input
3 3 2 2
Output
Happy new year!
Input
3 0 2 2
Output
AA
AA
Input
4 3 2 1
Output
Happy new year!
Input
4 2 2 1
Output
Happy new year! | instruction | 0 | 38,007 | 6 | 76,014 |
Tags: bitmasks, brute force, dp
Correct Solution:
```
# -*- coding: utf-8 -*-
import sys
def make_string(k, k2string, s1, s2):
if k in k2string:
return k2string[k]
if k == 1:
k2string[k] = s1
elif k == 2:
k2string[k] = s2
else:
k2string[k] = make_string(k-2, k2string, s1, s2) + make_string(k-1, k2string, s1, s2)
return k2string[k]
def count_comb(k, k2comb):
if k in k2comb:
return k2comb[k]
if k == 1:
k2comb[k] = ([0, 0, 0, 0, 1, 0], ('1', '1'))
elif k == 2:
k2comb[k] = ([0, 0, 0, 0, 0, 1], ('2', '2'))
else:
r_2 = count_comb(k-2, k2comb)
r_1 = count_comb(k-1, k2comb)
r = ([x+y for (x,y) in zip(r_2[0],r_1[0])], (r_2[1][0], r_1[1][1]))
ss = r_2[1][1] + r_1[1][0]
if ss == '11':
r[0][0] += 1
elif ss == '12':
r[0][1] += 1
elif ss == '21':
r[0][2] += 1
elif ss == '22':
r[0][3] += 1
k2comb[k] = r
return k2comb[k]
def max_independent_ac(l, cStart, aEnd):
if l <= 1:
return 0
elif (cStart and not aEnd) or (not cStart and aEnd):
return (l-1) // 2
elif cStart and aEnd:
return (l-2) // 2
else:
return l // 2
def print_sequence(l, ac, cStart, aEnd):
cStart = 1 if cStart else 0
aEnd = 1 if aEnd else 0
if cStart:
print('C', end='')
for i in range(ac):
print('AC', end='')
for i in range(l - 2*ac - cStart - aEnd):
print('B', end='')
if aEnd:
print('A', end='')
print()
def run_test(k, x, n, m):
comb = count_comb(k, {})[0]
for mask in range(16):
v = [0, 0, 0, 0, 0, 0]
if (mask & 1) and (mask & 2):
v[0] = 1
if (mask & 2) and (mask & 4):
v[1] = 1
if (mask & 1) and (mask & 8):
v[2] = 1
if (mask & 4) and (mask & 8):
v[3] = 1
if (n == 1 and v[0]) or (m == 1 and v[3]):
continue
max1 = max_independent_ac(n, mask & 1, mask & 2)
max2 = max_independent_ac(m, mask & 4, mask & 8)
for p in range(max1+1):
for q in range(max2+1):
v[4] = p
v[5] = q
if sum([x*y for (x,y) in zip(v,comb)]) == x:
print_sequence(n, p, mask&1, mask&2)
print_sequence(m, q, mask&4, mask&8)
return
print('Happy new year!')
k, x, n, m = (int(x) for x in sys.stdin.readline().split(' '))
run_test(k, x, n, m)
``` | output | 1 | 38,007 | 6 | 76,015 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Many countries have such a New Year or Christmas tradition as writing a letter to Santa including a wish list for presents. Vasya is an ordinary programmer boy. Like all ordinary boys, he is going to write the letter to Santa on the New Year Eve (we Russians actually expect Santa for the New Year, not for Christmas).
Vasya has come up with an algorithm he will follow while writing a letter. First he chooses two strings, s1 anf s2, consisting of uppercase English letters. Then the boy makes string sk, using a recurrent equation sn = sn - 2 + sn - 1, operation '+' means a concatenation (that is, the sequential record) of strings in the given order. Then Vasya writes down string sk on a piece of paper, puts it in the envelope and sends in to Santa.
Vasya is absolutely sure that Santa will bring him the best present if the resulting string sk has exactly x occurrences of substring AC (the short-cut reminds him ΠΎf accepted problems). Besides, Vasya decided that string s1 should have length n, and string s2 should have length m. Vasya hasn't decided anything else.
At the moment Vasya's got urgent New Year business, so he asks you to choose two strings for him, s1 and s2 in the required manner. Help Vasya.
Input
The first line contains four integers k, x, n, m (3 β€ k β€ 50; 0 β€ x β€ 109; 1 β€ n, m β€ 100).
Output
In the first line print string s1, consisting of n uppercase English letters. In the second line print string s2, consisting of m uppercase English letters. If there are multiple valid strings, print any of them.
If the required pair of strings doesn't exist, print "Happy new year!" without the quotes.
Examples
Input
3 2 2 2
Output
AC
AC
Input
3 3 2 2
Output
Happy new year!
Input
3 0 2 2
Output
AA
AA
Input
4 3 2 1
Output
Happy new year!
Input
4 2 2 1
Output
Happy new year! | instruction | 0 | 38,008 | 6 | 76,016 |
Tags: bitmasks, brute force, dp
Correct Solution:
```
k,x,n,m=map(int,input().split())
def calc(k,a,b,op1,ed1,op2,ed2):
if k==2:
return b
return calc(k-1,b,a+b+(ed1&op2),op2,ed2,op1,ed2)
def make(len,a,op,ed):
res,i="",0
if op:
res+="C"
i+=1
if ed:
len-=1
while a:
res+="AC"
a-=1
i+=2
while i<len:
res+="P"
i+=1
if ed:
res+="A"
return res
def check(a,b,op1,ed1,op2,ed2):
if (2*a+op1+ed1>n) or (2*b+op2+ed2>m):
return 0
if calc(k,a,b,op1,ed1,op2,ed2) == x:
print(make(n,a,op1,ed1))
print(make(m,b,op2,ed2))
return 1
flag=0
for i in range(0,(n>>1)+1):
for j in range(0,(m>>1)+1):
for l in range(0,16):
if check(i,j,l&1,(l>>1)&1,(l>>2)&1,(l>>3)&1):
flag=1
break
if flag:
break
if flag:
break
if not flag:
print("Happy new year!")
``` | output | 1 | 38,008 | 6 | 76,017 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Many countries have such a New Year or Christmas tradition as writing a letter to Santa including a wish list for presents. Vasya is an ordinary programmer boy. Like all ordinary boys, he is going to write the letter to Santa on the New Year Eve (we Russians actually expect Santa for the New Year, not for Christmas).
Vasya has come up with an algorithm he will follow while writing a letter. First he chooses two strings, s1 anf s2, consisting of uppercase English letters. Then the boy makes string sk, using a recurrent equation sn = sn - 2 + sn - 1, operation '+' means a concatenation (that is, the sequential record) of strings in the given order. Then Vasya writes down string sk on a piece of paper, puts it in the envelope and sends in to Santa.
Vasya is absolutely sure that Santa will bring him the best present if the resulting string sk has exactly x occurrences of substring AC (the short-cut reminds him ΠΎf accepted problems). Besides, Vasya decided that string s1 should have length n, and string s2 should have length m. Vasya hasn't decided anything else.
At the moment Vasya's got urgent New Year business, so he asks you to choose two strings for him, s1 and s2 in the required manner. Help Vasya.
Input
The first line contains four integers k, x, n, m (3 β€ k β€ 50; 0 β€ x β€ 109; 1 β€ n, m β€ 100).
Output
In the first line print string s1, consisting of n uppercase English letters. In the second line print string s2, consisting of m uppercase English letters. If there are multiple valid strings, print any of them.
If the required pair of strings doesn't exist, print "Happy new year!" without the quotes.
Examples
Input
3 2 2 2
Output
AC
AC
Input
3 3 2 2
Output
Happy new year!
Input
3 0 2 2
Output
AA
AA
Input
4 3 2 1
Output
Happy new year!
Input
4 2 2 1
Output
Happy new year! | instruction | 0 | 38,009 | 6 | 76,018 |
Tags: bitmasks, brute force, dp
Correct Solution:
```
def F(a, b, c, d, e, f, k):
for _ in range(k - 2):
a, b, c, d, e, f = d, e, f, a, b + e + (c and d), f
return e
k, x, n, m = map(int, input().split())
for a in [True, False]:
for c in [True, False]:
for b in range((n - a - c) // 2 + 1):
for d in [True, False]:
for f in [True, False]:
for e in range((m - d - f) // 2 + 1):
if F(a, b, c, d, e, f, k) == x:
print(['', 'C'][a] + 'AC' * b + 'Z' * (n - a - b - b - c) + ['', 'A'][c])
print(['', 'C'][d] + 'AC' * e + 'Z' * (m - d - e - e - f) + ['', 'A'][f])
exit()
print('Happy new year!')
``` | output | 1 | 38,009 | 6 | 76,019 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Many countries have such a New Year or Christmas tradition as writing a letter to Santa including a wish list for presents. Vasya is an ordinary programmer boy. Like all ordinary boys, he is going to write the letter to Santa on the New Year Eve (we Russians actually expect Santa for the New Year, not for Christmas).
Vasya has come up with an algorithm he will follow while writing a letter. First he chooses two strings, s1 anf s2, consisting of uppercase English letters. Then the boy makes string sk, using a recurrent equation sn = sn - 2 + sn - 1, operation '+' means a concatenation (that is, the sequential record) of strings in the given order. Then Vasya writes down string sk on a piece of paper, puts it in the envelope and sends in to Santa.
Vasya is absolutely sure that Santa will bring him the best present if the resulting string sk has exactly x occurrences of substring AC (the short-cut reminds him ΠΎf accepted problems). Besides, Vasya decided that string s1 should have length n, and string s2 should have length m. Vasya hasn't decided anything else.
At the moment Vasya's got urgent New Year business, so he asks you to choose two strings for him, s1 and s2 in the required manner. Help Vasya.
Input
The first line contains four integers k, x, n, m (3 β€ k β€ 50; 0 β€ x β€ 109; 1 β€ n, m β€ 100).
Output
In the first line print string s1, consisting of n uppercase English letters. In the second line print string s2, consisting of m uppercase English letters. If there are multiple valid strings, print any of them.
If the required pair of strings doesn't exist, print "Happy new year!" without the quotes.
Examples
Input
3 2 2 2
Output
AC
AC
Input
3 3 2 2
Output
Happy new year!
Input
3 0 2 2
Output
AA
AA
Input
4 3 2 1
Output
Happy new year!
Input
4 2 2 1
Output
Happy new year! | instruction | 0 | 38,010 | 6 | 76,020 |
Tags: bitmasks, brute force, dp
Correct Solution:
```
def main():
k, x, n, m = map(int, input().split())
def f(s, e, n, cnt):
ret = [""] * n
ret[0] = s
ret[-1] = e
sa = 0 if s == 'A' else 1
for i in range(cnt):
ret[sa] = 'A'
ret[sa + 1] = 'C'
sa += 2
for j in range(sa, n - 1):
ret[j] = 'B'
return "".join(ret)
for sa in "ABC":
for ea in "ABC":
if n == 1:
ea = sa
for sb in "ABC":
for eb in "ABC":
if m == 1:
eb = sb
N = max(0, n - (sa != 'A') - (ea != 'C'))
M = max(0, m - (sb != 'A') - (eb != 'C'))
for i in range(1 + N // 2):
for j in range(1 + M // 2):
A = sa + ea
B = sb + eb
a, b = i, j
for c in range(k - 2):
a, b = b, a + b
if A[1] == 'A' and B[0] == 'C':
b += 1
A, B = B, A[0] + B[1]
if b == x:
print(f(sa, ea, n, i))
print(f(sb, eb, m, j))
return 0
print("Happy new year!")
return 0
main()
``` | output | 1 | 38,010 | 6 | 76,021 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Many countries have such a New Year or Christmas tradition as writing a letter to Santa including a wish list for presents. Vasya is an ordinary programmer boy. Like all ordinary boys, he is going to write the letter to Santa on the New Year Eve (we Russians actually expect Santa for the New Year, not for Christmas).
Vasya has come up with an algorithm he will follow while writing a letter. First he chooses two strings, s1 anf s2, consisting of uppercase English letters. Then the boy makes string sk, using a recurrent equation sn = sn - 2 + sn - 1, operation '+' means a concatenation (that is, the sequential record) of strings in the given order. Then Vasya writes down string sk on a piece of paper, puts it in the envelope and sends in to Santa.
Vasya is absolutely sure that Santa will bring him the best present if the resulting string sk has exactly x occurrences of substring AC (the short-cut reminds him ΠΎf accepted problems). Besides, Vasya decided that string s1 should have length n, and string s2 should have length m. Vasya hasn't decided anything else.
At the moment Vasya's got urgent New Year business, so he asks you to choose two strings for him, s1 and s2 in the required manner. Help Vasya.
Input
The first line contains four integers k, x, n, m (3 β€ k β€ 50; 0 β€ x β€ 109; 1 β€ n, m β€ 100).
Output
In the first line print string s1, consisting of n uppercase English letters. In the second line print string s2, consisting of m uppercase English letters. If there are multiple valid strings, print any of them.
If the required pair of strings doesn't exist, print "Happy new year!" without the quotes.
Examples
Input
3 2 2 2
Output
AC
AC
Input
3 3 2 2
Output
Happy new year!
Input
3 0 2 2
Output
AA
AA
Input
4 3 2 1
Output
Happy new year!
Input
4 2 2 1
Output
Happy new year! | instruction | 0 | 38,011 | 6 | 76,022 |
Tags: bitmasks, brute force, dp
Correct Solution:
```
import sys
import itertools
k, x, n, m = map(int, input().split())
def valid(inicio, fim, tamanho, num_ac):
if num_ac == 0:
if tamanho == 1:
return ("" if inicio != fim else inicio)
if tamanho == 2:
return (inicio + fim if inicio + fim != "AC" else "")
return inicio + "B" * (tamanho - 2) + fim
s = "AC" * num_ac
if s[0] != inicio:
s = inicio + s
if len(s) > tamanho:
return ""
s += fim * (tamanho - len(s))
if s[-1] != fim:
return ""
return s
a = [0] * 51
a[1] = 1
b = [0] * 51
b[2] = 1
for i in range(3, 51):
a[i] = a[i-2] + a[i-1]
b[i] = b[i-2] + b[i-1]
for letters in itertools.product(['A', 'B', 'C'], repeat=4):
first_s1 = letters[0]
last_s1 = letters[1]
first_s2 = letters[2]
last_s2 = letters[3]
c = [0] * 51
meio = last_s1 + first_s2
c[3] = (1 if meio == "AC" else 0)
for i in range(4, 51):
meio = last_s2 + (first_s1 if i % 2 == 0 else first_s2)
c[i] = c[i-2] + c[i-1] + (1 if meio == "AC" else 0)
for occ1 in range(0, 51):
tmp = x - a[k] * occ1 - c[k]
if tmp % b[k] != 0:
continue
tmp = tmp//b[k]
if tmp < 0 or tmp > 50:
continue
s1 = valid(first_s1, last_s1, n, occ1)
s2 = valid(first_s2, last_s2, m, tmp)
if s1 and s2:
print(s1)
print(s2)
sys.exit(0)
print("Happy new year!")
``` | output | 1 | 38,011 | 6 | 76,023 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Many countries have such a New Year or Christmas tradition as writing a letter to Santa including a wish list for presents. Vasya is an ordinary programmer boy. Like all ordinary boys, he is going to write the letter to Santa on the New Year Eve (we Russians actually expect Santa for the New Year, not for Christmas).
Vasya has come up with an algorithm he will follow while writing a letter. First he chooses two strings, s1 anf s2, consisting of uppercase English letters. Then the boy makes string sk, using a recurrent equation sn = sn - 2 + sn - 1, operation '+' means a concatenation (that is, the sequential record) of strings in the given order. Then Vasya writes down string sk on a piece of paper, puts it in the envelope and sends in to Santa.
Vasya is absolutely sure that Santa will bring him the best present if the resulting string sk has exactly x occurrences of substring AC (the short-cut reminds him ΠΎf accepted problems). Besides, Vasya decided that string s1 should have length n, and string s2 should have length m. Vasya hasn't decided anything else.
At the moment Vasya's got urgent New Year business, so he asks you to choose two strings for him, s1 and s2 in the required manner. Help Vasya.
Input
The first line contains four integers k, x, n, m (3 β€ k β€ 50; 0 β€ x β€ 109; 1 β€ n, m β€ 100).
Output
In the first line print string s1, consisting of n uppercase English letters. In the second line print string s2, consisting of m uppercase English letters. If there are multiple valid strings, print any of them.
If the required pair of strings doesn't exist, print "Happy new year!" without the quotes.
Examples
Input
3 2 2 2
Output
AC
AC
Input
3 3 2 2
Output
Happy new year!
Input
3 0 2 2
Output
AA
AA
Input
4 3 2 1
Output
Happy new year!
Input
4 2 2 1
Output
Happy new year! | instruction | 0 | 38,012 | 6 | 76,024 |
Tags: bitmasks, brute force, dp
Correct Solution:
```
def f(k):
if k == 1: return (1, 0, 0, 0, 0)
if k == 2: return (0, 1, 0, 0, 0)
if k == 3: return (1, 1, 1, 0, 0)
a, b = 1, 1
for i in range(k - 3): a, b = b, a + b
c = a
d = e = 0
for i in range(k - 3): d, e = e, d + e + int(i % 2 == 0)
return (a, b, c, d, e)
def r(a, i, n):
if n == 1:
if a == 'BB': return 'B'
if a == 'BA': return 'A'
if a == 'CB': return 'C'
return False
if i == 0:
if a == 'BB': return 'B' * n
if a == 'BA': return 'B' * (n - 1) + 'A'
if a == 'CB': return 'C' + 'B' * (n - 1)
x = 'AC' * i
n -= len(x)
if n < 0: return False
if a[0] == 'B':
if a[1] == 'B': return x + 'C' * n
return x + 'A' * n
else:
if a[1] == 'B': return 'C' * n + x
n -= 1
if n < 1: return False
return 'C' + x + 'A' * n
def g(a, b, i, j, n, m):
x, y = r(a, i, n), r(b, j, m)
if x and y:
print(x)
print(y)
return True
return False
def h():
k, x, n, m = map(int, input().split())
t = f(k)
for i in range(n // 2 + 1):
for j in range(m // 2 + 1):
if x == t[0] * i + t[1] * j:
print('AC' * i + 'B' * (n - 2 * i))
print('AC' * j + 'B' * (m - 2 * j))
return
for i in range((n + 1) // 2):
for j in range((m + 1) // 2):
y = x - (t[0] * i + t[1] * j)
if y == t[2] and g('BA', 'CB', i, j, n, m): return
if y == t[3] and g('BB', 'CA', i, j, n, m): return
if y == t[4] and g('CB', 'BA', i, j, n, m): return
if y == t[2] + t[3] and g('BA', 'CA', i, j, n, m): return
if y == t[3] + t[4] and g('CB', 'BA', i, j, n, m): return
if y == t[2] + t[3] + t[4] and g('CA', 'CA', i, j, n, m): return
print('Happy new year!')
h()
``` | output | 1 | 38,012 | 6 | 76,025 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anfisa the monkey learns to type. She is yet unfamiliar with the "space" key and can only type in lower-case Latin letters. Having typed for a fairly long line, Anfisa understood that it would be great to divide what she has written into k lines not shorter than a and not longer than b, for the text to resemble human speech more. Help Anfisa.
Input
The first line contains three integers k, a and b (1 β€ k β€ 200, 1 β€ a β€ b β€ 200). The second line contains a sequence of lowercase Latin letters β the text typed by Anfisa. It is guaranteed that the given line is not empty and its length does not exceed 200 symbols.
Output
Print k lines, each of which contains no less than a and no more than b symbols β Anfisa's text divided into lines. It is not allowed to perform any changes in the text, such as: deleting or adding symbols, changing their order, etc. If the solution is not unique, print any of them. If there is no solution, print "No solution" (without quotes).
Examples
Input
3 2 5
abrakadabra
Output
ab
rakad
abra
Input
4 1 2
abrakadabra
Output
No solution | instruction | 0 | 38,033 | 6 | 76,066 |
Tags: dp
Correct Solution:
```
line = list(map(int, input().split()))
k = line[0]
a = line[1]
b = line[2]
text = input()
textLength = len(text)
if (textLength/k > b or textLength/k < a):
print("No solution")
else:
avg = textLength // k
splitLength = [avg for i in range(k)]
remaining = textLength % k
for i in range(remaining):
splitLength[i%k]+=1
if (splitLength[0] > b):
print("No solution")
else:
start = 0
for i in range(k):
print(text[start:start+splitLength[i]])
start+= splitLength[i]
``` | output | 1 | 38,033 | 6 | 76,067 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anfisa the monkey learns to type. She is yet unfamiliar with the "space" key and can only type in lower-case Latin letters. Having typed for a fairly long line, Anfisa understood that it would be great to divide what she has written into k lines not shorter than a and not longer than b, for the text to resemble human speech more. Help Anfisa.
Input
The first line contains three integers k, a and b (1 β€ k β€ 200, 1 β€ a β€ b β€ 200). The second line contains a sequence of lowercase Latin letters β the text typed by Anfisa. It is guaranteed that the given line is not empty and its length does not exceed 200 symbols.
Output
Print k lines, each of which contains no less than a and no more than b symbols β Anfisa's text divided into lines. It is not allowed to perform any changes in the text, such as: deleting or adding symbols, changing their order, etc. If the solution is not unique, print any of them. If there is no solution, print "No solution" (without quotes).
Examples
Input
3 2 5
abrakadabra
Output
ab
rakad
abra
Input
4 1 2
abrakadabra
Output
No solution | instruction | 0 | 38,034 | 6 | 76,068 |
Tags: dp
Correct Solution:
```
#region Header
#!/usr/bin/env python3
# from typing import *
import sys
import io
import math
import collections
import decimal
import itertools
import bisect
import heapq
def input():
return sys.stdin.readline()[:-1]
# sys.setrecursionlimit(1000000)
#endregion
# _INPUT = """# paste here...
# """
# sys.stdin = io.StringIO(_INPUT)
def main():
k, a, b = map(int, input().split())
S = input()
N = len(S)
if N < a*k or b*k < N:
print('No solution')
else:
L = []
while N > 0:
v = math.floor(N/k)
L.append(v)
N -= v
k -= 1
a = 0
for l in L:
print(S[a:a+l])
a += l
if __name__ == '__main__':
main()
``` | output | 1 | 38,034 | 6 | 76,069 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anfisa the monkey learns to type. She is yet unfamiliar with the "space" key and can only type in lower-case Latin letters. Having typed for a fairly long line, Anfisa understood that it would be great to divide what she has written into k lines not shorter than a and not longer than b, for the text to resemble human speech more. Help Anfisa.
Input
The first line contains three integers k, a and b (1 β€ k β€ 200, 1 β€ a β€ b β€ 200). The second line contains a sequence of lowercase Latin letters β the text typed by Anfisa. It is guaranteed that the given line is not empty and its length does not exceed 200 symbols.
Output
Print k lines, each of which contains no less than a and no more than b symbols β Anfisa's text divided into lines. It is not allowed to perform any changes in the text, such as: deleting or adding symbols, changing their order, etc. If the solution is not unique, print any of them. If there is no solution, print "No solution" (without quotes).
Examples
Input
3 2 5
abrakadabra
Output
ab
rakad
abra
Input
4 1 2
abrakadabra
Output
No solution | instruction | 0 | 38,035 | 6 | 76,070 |
Tags: dp
Correct Solution:
```
(k, a, b) = map(int, input().split())
min_len = k * a
max_len = k * b
line = input()
line_length = len(line)
print_index = 0
if line_length < min_len or line_length > max_len:
print("No solution")
else:
add_length = line_length - min_len
distance = b - a
print_to = 0
for item in range(0, k):
add_length -= distance
if add_length > 0:
print_to = print_index+a+distance
else:
print_to = print_index + a + distance + add_length
add_length = 0
print(line[print_index:print_to])
print_index = print_to
``` | output | 1 | 38,035 | 6 | 76,071 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anfisa the monkey learns to type. She is yet unfamiliar with the "space" key and can only type in lower-case Latin letters. Having typed for a fairly long line, Anfisa understood that it would be great to divide what she has written into k lines not shorter than a and not longer than b, for the text to resemble human speech more. Help Anfisa.
Input
The first line contains three integers k, a and b (1 β€ k β€ 200, 1 β€ a β€ b β€ 200). The second line contains a sequence of lowercase Latin letters β the text typed by Anfisa. It is guaranteed that the given line is not empty and its length does not exceed 200 symbols.
Output
Print k lines, each of which contains no less than a and no more than b symbols β Anfisa's text divided into lines. It is not allowed to perform any changes in the text, such as: deleting or adding symbols, changing their order, etc. If the solution is not unique, print any of them. If there is no solution, print "No solution" (without quotes).
Examples
Input
3 2 5
abrakadabra
Output
ab
rakad
abra
Input
4 1 2
abrakadabra
Output
No solution | instruction | 0 | 38,036 | 6 | 76,072 |
Tags: dp
Correct Solution:
```
k , n , m = map(int,input().split())
s = input()
l = len(s)
if l>k*m or l<n*k:
print("No solution")
exit()
lis=[n]*k
l-=((n)*(k))
c=0
ans=[]
while l!=0:
for j in range(k):
if l==0:
break
if lis[j]<m:
lis[j]+=1
l-=1
# print(lis,l)
if l==0:
break
c=0
#print(lis)
for j in range(k):
ss=s[c:lis[j]+c]
ans.append(ss)
c+=lis[j]
#print(ans)
for i in ans:
print(*i,sep='')
``` | output | 1 | 38,036 | 6 | 76,073 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anfisa the monkey learns to type. She is yet unfamiliar with the "space" key and can only type in lower-case Latin letters. Having typed for a fairly long line, Anfisa understood that it would be great to divide what she has written into k lines not shorter than a and not longer than b, for the text to resemble human speech more. Help Anfisa.
Input
The first line contains three integers k, a and b (1 β€ k β€ 200, 1 β€ a β€ b β€ 200). The second line contains a sequence of lowercase Latin letters β the text typed by Anfisa. It is guaranteed that the given line is not empty and its length does not exceed 200 symbols.
Output
Print k lines, each of which contains no less than a and no more than b symbols β Anfisa's text divided into lines. It is not allowed to perform any changes in the text, such as: deleting or adding symbols, changing their order, etc. If the solution is not unique, print any of them. If there is no solution, print "No solution" (without quotes).
Examples
Input
3 2 5
abrakadabra
Output
ab
rakad
abra
Input
4 1 2
abrakadabra
Output
No solution | instruction | 0 | 38,037 | 6 | 76,074 |
Tags: dp
Correct Solution:
```
k,a,b=map(int,input().split(' '))
s=input()
l=len(s)
if(l<k*a or l>k*b):
print("No solution")
else:
n1=l//k
n2=n1+1
n3=k-(l%k)
n4=l%k
cur=0
for i in range(n3):
print(s[cur:cur+n1])
cur+=n1
for i in range(n4):
print(s[cur:cur+n2])
cur+=n2
``` | output | 1 | 38,037 | 6 | 76,075 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anfisa the monkey learns to type. She is yet unfamiliar with the "space" key and can only type in lower-case Latin letters. Having typed for a fairly long line, Anfisa understood that it would be great to divide what she has written into k lines not shorter than a and not longer than b, for the text to resemble human speech more. Help Anfisa.
Input
The first line contains three integers k, a and b (1 β€ k β€ 200, 1 β€ a β€ b β€ 200). The second line contains a sequence of lowercase Latin letters β the text typed by Anfisa. It is guaranteed that the given line is not empty and its length does not exceed 200 symbols.
Output
Print k lines, each of which contains no less than a and no more than b symbols β Anfisa's text divided into lines. It is not allowed to perform any changes in the text, such as: deleting or adding symbols, changing their order, etc. If the solution is not unique, print any of them. If there is no solution, print "No solution" (without quotes).
Examples
Input
3 2 5
abrakadabra
Output
ab
rakad
abra
Input
4 1 2
abrakadabra
Output
No solution | instruction | 0 | 38,038 | 6 | 76,076 |
Tags: dp
Correct Solution:
```
def chujnia():
k, n, m = tuple(list(map(int, input().split())))
slowo = input()
lower = k*n
higher = k*m
if len(slowo) < lower or len(slowo) > higher:
print("No solution")
exit(0)
ilosc = len(slowo)//k
reszta = len(slowo) % k
cp = reszta
i = 0
for _ in range(k):
if cp != 0:
print(slowo[i:i+ilosc+1])
i+=ilosc+1
cp -= 1
else:
print(slowo[i:i+ilosc])
i+=ilosc
chujnia()
``` | output | 1 | 38,038 | 6 | 76,077 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anfisa the monkey learns to type. She is yet unfamiliar with the "space" key and can only type in lower-case Latin letters. Having typed for a fairly long line, Anfisa understood that it would be great to divide what she has written into k lines not shorter than a and not longer than b, for the text to resemble human speech more. Help Anfisa.
Input
The first line contains three integers k, a and b (1 β€ k β€ 200, 1 β€ a β€ b β€ 200). The second line contains a sequence of lowercase Latin letters β the text typed by Anfisa. It is guaranteed that the given line is not empty and its length does not exceed 200 symbols.
Output
Print k lines, each of which contains no less than a and no more than b symbols β Anfisa's text divided into lines. It is not allowed to perform any changes in the text, such as: deleting or adding symbols, changing their order, etc. If the solution is not unique, print any of them. If there is no solution, print "No solution" (without quotes).
Examples
Input
3 2 5
abrakadabra
Output
ab
rakad
abra
Input
4 1 2
abrakadabra
Output
No solution | instruction | 0 | 38,039 | 6 | 76,078 |
Tags: dp
Correct Solution:
```
n, a, b = map(int, input().split())
s = input()
if n * a <= len(s) <= n * b:
x, y = divmod(len(s), n)
j = 0
for i in range(n):
print(s[j : j + x + (y > i)])
j = j + x + (y > i)
else:
print('No solution')
``` | output | 1 | 38,039 | 6 | 76,079 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anfisa the monkey learns to type. She is yet unfamiliar with the "space" key and can only type in lower-case Latin letters. Having typed for a fairly long line, Anfisa understood that it would be great to divide what she has written into k lines not shorter than a and not longer than b, for the text to resemble human speech more. Help Anfisa.
Input
The first line contains three integers k, a and b (1 β€ k β€ 200, 1 β€ a β€ b β€ 200). The second line contains a sequence of lowercase Latin letters β the text typed by Anfisa. It is guaranteed that the given line is not empty and its length does not exceed 200 symbols.
Output
Print k lines, each of which contains no less than a and no more than b symbols β Anfisa's text divided into lines. It is not allowed to perform any changes in the text, such as: deleting or adding symbols, changing their order, etc. If the solution is not unique, print any of them. If there is no solution, print "No solution" (without quotes).
Examples
Input
3 2 5
abrakadabra
Output
ab
rakad
abra
Input
4 1 2
abrakadabra
Output
No solution | instruction | 0 | 38,040 | 6 | 76,080 |
Tags: dp
Correct Solution:
```
k,a,b=map(int,input().split())
s=input()
bal =len(s)
if bal>k*b or bal<k*a:
print("No solution")
else:
arr=[a]*k
bal-=a*k
inc=bal//k
bal-=inc*k
for i in range(k):
arr[i]+=inc
for i in range(bal):
arr[i]+=1
#print(arr)
for i in range(1,k):
arr[i]+=arr[i-1]
arr2=[s[:arr[0]]]
for i in range(1,k):
arr2.append(s[arr[i-1]:arr[i]])
#print(arr)
for i in arr2:
print(i)
``` | output | 1 | 38,040 | 6 | 76,081 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture:
<image>
After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.
Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
Input
The only line of input contains the name of some exhibit β the non-empty string consisting of no more than 100 characters. It's guaranteed that the string consists of only lowercase English letters.
Output
Print one integer β the minimum number of rotations of the wheel, required to print the name given in the input.
Examples
Input
zeus
Output
18
Input
map
Output
35
Input
ares
Output
34
Note
<image>
To print the string from the first sample it would be optimal to perform the following sequence of rotations:
1. from 'a' to 'z' (1 rotation counterclockwise),
2. from 'z' to 'e' (5 clockwise rotations),
3. from 'e' to 'u' (10 rotations counterclockwise),
4. from 'u' to 's' (2 counterclockwise rotations).
In total, 1 + 5 + 10 + 2 = 18 rotations are required. | instruction | 0 | 38,175 | 6 | 76,350 |
Tags: implementation, strings
Correct Solution:
```
s = input()
ans = 0
prev = 'a'
for c in s:
v = abs(ord(c)-ord(prev))
ans += min(v, 26-v)
prev = c
print(ans)
``` | output | 1 | 38,175 | 6 | 76,351 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture:
<image>
After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.
Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
Input
The only line of input contains the name of some exhibit β the non-empty string consisting of no more than 100 characters. It's guaranteed that the string consists of only lowercase English letters.
Output
Print one integer β the minimum number of rotations of the wheel, required to print the name given in the input.
Examples
Input
zeus
Output
18
Input
map
Output
35
Input
ares
Output
34
Note
<image>
To print the string from the first sample it would be optimal to perform the following sequence of rotations:
1. from 'a' to 'z' (1 rotation counterclockwise),
2. from 'z' to 'e' (5 clockwise rotations),
3. from 'e' to 'u' (10 rotations counterclockwise),
4. from 'u' to 's' (2 counterclockwise rotations).
In total, 1 + 5 + 10 + 2 = 18 rotations are required. | instruction | 0 | 38,176 | 6 | 76,352 |
Tags: implementation, strings
Correct Solution:
```
grigoriye = ['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']
l = len(grigoriye)
staticpointer = grigoriye[0]
def get_least_distance(value):
total = 0
staticpointer_index = 0
for i in value:
value_index = grigoriye.index(i)
min_distance = abs(min(value_index - staticpointer_index , l-(value_index-staticpointer_index)))
if min_distance > 13:
min_distance = 26-min_distance
staticpointer_index = value_index
total += min_distance
return total
if __name__ == "__main__":
value = str(input())
least_distance = get_least_distance(value)
print(least_distance)
``` | output | 1 | 38,176 | 6 | 76,353 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture:
<image>
After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.
Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
Input
The only line of input contains the name of some exhibit β the non-empty string consisting of no more than 100 characters. It's guaranteed that the string consists of only lowercase English letters.
Output
Print one integer β the minimum number of rotations of the wheel, required to print the name given in the input.
Examples
Input
zeus
Output
18
Input
map
Output
35
Input
ares
Output
34
Note
<image>
To print the string from the first sample it would be optimal to perform the following sequence of rotations:
1. from 'a' to 'z' (1 rotation counterclockwise),
2. from 'z' to 'e' (5 clockwise rotations),
3. from 'e' to 'u' (10 rotations counterclockwise),
4. from 'u' to 's' (2 counterclockwise rotations).
In total, 1 + 5 + 10 + 2 = 18 rotations are required. | instruction | 0 | 38,177 | 6 | 76,354 |
Tags: implementation, strings
Correct Solution:
```
import sys
inp = sys.stdin.readlines()
start_position = 'a'
alpha = list(map(chr, range(97, 123)))
word = inp[0].lower().strip()
rounds = 0
for letter in word:
right = 0
while True:
try:
if alpha[alpha.index(start_position)+right] == letter:
break
except IndexError:
if alpha[alpha.index(start_position)+right-len(alpha)] == letter:
break
finally:
right += 1
right -= 1
left = 0
while True:
try:
if alpha[alpha.index(start_position) - left] == letter:
break
except IndexError:
if alpha[alpha.index(start_position)-left+len(alpha)] == letter:
break
finally:
left += 1
left -= 1
rounds += min(right, left)
start_position = letter
print(rounds)
``` | output | 1 | 38,177 | 6 | 76,355 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture:
<image>
After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.
Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
Input
The only line of input contains the name of some exhibit β the non-empty string consisting of no more than 100 characters. It's guaranteed that the string consists of only lowercase English letters.
Output
Print one integer β the minimum number of rotations of the wheel, required to print the name given in the input.
Examples
Input
zeus
Output
18
Input
map
Output
35
Input
ares
Output
34
Note
<image>
To print the string from the first sample it would be optimal to perform the following sequence of rotations:
1. from 'a' to 'z' (1 rotation counterclockwise),
2. from 'z' to 'e' (5 clockwise rotations),
3. from 'e' to 'u' (10 rotations counterclockwise),
4. from 'u' to 's' (2 counterclockwise rotations).
In total, 1 + 5 + 10 + 2 = 18 rotations are required. | instruction | 0 | 38,178 | 6 | 76,356 |
Tags: implementation, strings
Correct Solution:
```
import string
arr = [i for i in string.ascii_lowercase]
current = 'a'
s = str(input())
count = 0
for i in s:
if i != current:
count += min(abs(arr.index(i) - arr.index(current)), 26 - abs(arr.index(i) - arr.index(current)))
current = i
print(count)
``` | output | 1 | 38,178 | 6 | 76,357 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture:
<image>
After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.
Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
Input
The only line of input contains the name of some exhibit β the non-empty string consisting of no more than 100 characters. It's guaranteed that the string consists of only lowercase English letters.
Output
Print one integer β the minimum number of rotations of the wheel, required to print the name given in the input.
Examples
Input
zeus
Output
18
Input
map
Output
35
Input
ares
Output
34
Note
<image>
To print the string from the first sample it would be optimal to perform the following sequence of rotations:
1. from 'a' to 'z' (1 rotation counterclockwise),
2. from 'z' to 'e' (5 clockwise rotations),
3. from 'e' to 'u' (10 rotations counterclockwise),
4. from 'u' to 's' (2 counterclockwise rotations).
In total, 1 + 5 + 10 + 2 = 18 rotations are required. | instruction | 0 | 38,179 | 6 | 76,358 |
Tags: implementation, strings
Correct Solution:
```
word = input()
lc = 'a'
t = 0
for c in word:
x = max(ord(c)-ord('a')+1, ord(lc)-ord('a')+1)
y = min(ord(c)-ord('a')+1, ord(lc)-ord('a')+1)
if x - y <= 13:
t += x-y
else:
t += 26 + y-x
lc = c
print(t)
``` | output | 1 | 38,179 | 6 | 76,359 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture:
<image>
After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.
Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
Input
The only line of input contains the name of some exhibit β the non-empty string consisting of no more than 100 characters. It's guaranteed that the string consists of only lowercase English letters.
Output
Print one integer β the minimum number of rotations of the wheel, required to print the name given in the input.
Examples
Input
zeus
Output
18
Input
map
Output
35
Input
ares
Output
34
Note
<image>
To print the string from the first sample it would be optimal to perform the following sequence of rotations:
1. from 'a' to 'z' (1 rotation counterclockwise),
2. from 'z' to 'e' (5 clockwise rotations),
3. from 'e' to 'u' (10 rotations counterclockwise),
4. from 'u' to 's' (2 counterclockwise rotations).
In total, 1 + 5 + 10 + 2 = 18 rotations are required. | instruction | 0 | 38,180 | 6 | 76,360 |
Tags: implementation, strings
Correct Solution:
```
count = 0
beg = 'a'
st = input()
c = 0
for i in range (len (st)):
c = abs (ord (beg) - ord (st[i]))
count += min (c, 26 - c)
beg = st[i]
print (count)
``` | output | 1 | 38,180 | 6 | 76,361 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture:
<image>
After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.
Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
Input
The only line of input contains the name of some exhibit β the non-empty string consisting of no more than 100 characters. It's guaranteed that the string consists of only lowercase English letters.
Output
Print one integer β the minimum number of rotations of the wheel, required to print the name given in the input.
Examples
Input
zeus
Output
18
Input
map
Output
35
Input
ares
Output
34
Note
<image>
To print the string from the first sample it would be optimal to perform the following sequence of rotations:
1. from 'a' to 'z' (1 rotation counterclockwise),
2. from 'z' to 'e' (5 clockwise rotations),
3. from 'e' to 'u' (10 rotations counterclockwise),
4. from 'u' to 's' (2 counterclockwise rotations).
In total, 1 + 5 + 10 + 2 = 18 rotations are required. | instruction | 0 | 38,181 | 6 | 76,362 |
Tags: implementation, strings
Correct Solution:
```
name = input()
ans = 0
ptr = 1
for i in name:
pos = ord(i) - 96
ans += min(abs(ptr - pos), 26 - abs(ptr - pos))
ptr = pos
print(ans)
``` | output | 1 | 38,181 | 6 | 76,363 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture:
<image>
After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.
Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
Input
The only line of input contains the name of some exhibit β the non-empty string consisting of no more than 100 characters. It's guaranteed that the string consists of only lowercase English letters.
Output
Print one integer β the minimum number of rotations of the wheel, required to print the name given in the input.
Examples
Input
zeus
Output
18
Input
map
Output
35
Input
ares
Output
34
Note
<image>
To print the string from the first sample it would be optimal to perform the following sequence of rotations:
1. from 'a' to 'z' (1 rotation counterclockwise),
2. from 'z' to 'e' (5 clockwise rotations),
3. from 'e' to 'u' (10 rotations counterclockwise),
4. from 'u' to 's' (2 counterclockwise rotations).
In total, 1 + 5 + 10 + 2 = 18 rotations are required. | instruction | 0 | 38,182 | 6 | 76,364 |
Tags: implementation, strings
Correct Solution:
```
# https://codeforces.com/contest/731/problem/A
# zeus
inp = input()
start = 'a'
my_dict = {'a':1}
for i in range(2,27):
start = chr(ord(start) + 1)
my_dict[start] = i
#print(my_dict)
rotation = 0
counter = 'a'
for i in inp:
distance1 = my_dict[counter] - my_dict[i]
distance2 = my_dict[i] - my_dict[counter]
#print('\t i:{}'.format(i))
#print(' d1:{};d2:{};min_steps:{}'
#.format(distance1,distance2,min(distance1, distance2)), end='')
if distance1 < 0:
distance1 += 26
if distance2 < 0:
distance2 += 26
rotation += min(distance1, distance2)
#print(' d1:{};d2:{};min_steps:{}'
#.format(distance1,distance2,min(distance1, distance2)))
counter = i
print(rotation)
``` | output | 1 | 38,182 | 6 | 76,365 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture:
<image>
After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.
Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
Input
The only line of input contains the name of some exhibit β the non-empty string consisting of no more than 100 characters. It's guaranteed that the string consists of only lowercase English letters.
Output
Print one integer β the minimum number of rotations of the wheel, required to print the name given in the input.
Examples
Input
zeus
Output
18
Input
map
Output
35
Input
ares
Output
34
Note
<image>
To print the string from the first sample it would be optimal to perform the following sequence of rotations:
1. from 'a' to 'z' (1 rotation counterclockwise),
2. from 'z' to 'e' (5 clockwise rotations),
3. from 'e' to 'u' (10 rotations counterclockwise),
4. from 'u' to 's' (2 counterclockwise rotations).
In total, 1 + 5 + 10 + 2 = 18 rotations are required.
Submitted Solution:
```
s = input()
t = 'abcdefghijklmnopqrstuvwxyz'
currid = 0
den = 0
for i in s:
temp = abs(currid - t.index(i))
if temp > len(t) - temp :
den += len(t) - temp
else :
den += temp
currid = t.index(i)
print(den)
``` | instruction | 0 | 38,183 | 6 | 76,366 |
Yes | output | 1 | 38,183 | 6 | 76,367 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture:
<image>
After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.
Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
Input
The only line of input contains the name of some exhibit β the non-empty string consisting of no more than 100 characters. It's guaranteed that the string consists of only lowercase English letters.
Output
Print one integer β the minimum number of rotations of the wheel, required to print the name given in the input.
Examples
Input
zeus
Output
18
Input
map
Output
35
Input
ares
Output
34
Note
<image>
To print the string from the first sample it would be optimal to perform the following sequence of rotations:
1. from 'a' to 'z' (1 rotation counterclockwise),
2. from 'z' to 'e' (5 clockwise rotations),
3. from 'e' to 'u' (10 rotations counterclockwise),
4. from 'u' to 's' (2 counterclockwise rotations).
In total, 1 + 5 + 10 + 2 = 18 rotations are required.
Submitted Solution:
```
a=[0,*map(lambda x:ord(x)-97,input())]
print(sum(min(z,26-z) for z in [abs(y-x) for x,y in zip(a,a[1:])]))
``` | instruction | 0 | 38,184 | 6 | 76,368 |
Yes | output | 1 | 38,184 | 6 | 76,369 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture:
<image>
After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.
Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
Input
The only line of input contains the name of some exhibit β the non-empty string consisting of no more than 100 characters. It's guaranteed that the string consists of only lowercase English letters.
Output
Print one integer β the minimum number of rotations of the wheel, required to print the name given in the input.
Examples
Input
zeus
Output
18
Input
map
Output
35
Input
ares
Output
34
Note
<image>
To print the string from the first sample it would be optimal to perform the following sequence of rotations:
1. from 'a' to 'z' (1 rotation counterclockwise),
2. from 'z' to 'e' (5 clockwise rotations),
3. from 'e' to 'u' (10 rotations counterclockwise),
4. from 'u' to 's' (2 counterclockwise rotations).
In total, 1 + 5 + 10 + 2 = 18 rotations are required.
Submitted Solution:
```
from bisect import bisect
s = input()
e = "abcdefghijklmnopqrstuvwxyz"
i = 1
ans = 0
for c in s:
t = bisect(e, c)
ans += min(((t+26)-i) % 26, ((i + 26) - t) % 26)
i = t
print(ans)
``` | instruction | 0 | 38,185 | 6 | 76,370 |
Yes | output | 1 | 38,185 | 6 | 76,371 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture:
<image>
After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.
Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
Input
The only line of input contains the name of some exhibit β the non-empty string consisting of no more than 100 characters. It's guaranteed that the string consists of only lowercase English letters.
Output
Print one integer β the minimum number of rotations of the wheel, required to print the name given in the input.
Examples
Input
zeus
Output
18
Input
map
Output
35
Input
ares
Output
34
Note
<image>
To print the string from the first sample it would be optimal to perform the following sequence of rotations:
1. from 'a' to 'z' (1 rotation counterclockwise),
2. from 'z' to 'e' (5 clockwise rotations),
3. from 'e' to 'u' (10 rotations counterclockwise),
4. from 'u' to 's' (2 counterclockwise rotations).
In total, 1 + 5 + 10 + 2 = 18 rotations are required.
Submitted Solution:
```
str = input()
ch = 'a'
total = 0
for i in str:
dis = abs(ord(ch) - ord(i))
if dis < 13:
total += dis
else:
total = total + (26 - dis)
ch = i
print(total)
``` | instruction | 0 | 38,186 | 6 | 76,372 |
Yes | output | 1 | 38,186 | 6 | 76,373 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture:
<image>
After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.
Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
Input
The only line of input contains the name of some exhibit β the non-empty string consisting of no more than 100 characters. It's guaranteed that the string consists of only lowercase English letters.
Output
Print one integer β the minimum number of rotations of the wheel, required to print the name given in the input.
Examples
Input
zeus
Output
18
Input
map
Output
35
Input
ares
Output
34
Note
<image>
To print the string from the first sample it would be optimal to perform the following sequence of rotations:
1. from 'a' to 'z' (1 rotation counterclockwise),
2. from 'z' to 'e' (5 clockwise rotations),
3. from 'e' to 'u' (10 rotations counterclockwise),
4. from 'u' to 's' (2 counterclockwise rotations).
In total, 1 + 5 + 10 + 2 = 18 rotations are required.
Submitted Solution:
```
#Sereja And Dima
"""n=int(input())
list1=list(map(int,input().split()))
Sereja=0
Dima=0
list2=list1
for i in range(len(list2)):
maximum=max(list1[0],list1[-1])
if i%2==0:
Sereja+=maximum
else:
Dima+=maximum
list1.remove(maximum)
print(Sereja,Dima)"""
#Magnets
"""n=int(input())
list1=[]
count=0
for i in range(n):
s=input()
list1.append(s)
for i in range(len(list1)):
if i<len(list1)-1:
if list1[i]!=list1[i+1]:
count+=1
else:
pass
print(count+1)"""
#Stones on the Table
"""n=int(input())
s=input()
count=0
for i in range(n):
if i<n-1:
if s[i]==s[i+1]:
count+=1
else:
pass
print(count)"""
#Police Recruits
"""n=int(input())
list1=list(map(int,input().split()))
sum1=0
count=0
for i in list1:
sum1+=i
if sum1<0:
count+=1
sum1=0
print(count)"""
#Black Square
"""sum1=0
list1=list(map(int,input().split()))
s=input()
for i in s:
if i==str(1):
sum1+=list1[0]
if i==str(2):
sum1+=list1[1]
if i==str(3):
sum1+=list1[2]
if i==str(4):
sum1+=list1[3]
print(sum1)"""
#Night At The Museum
word=input()
turns=0
for i in word:
if i==word[0]:
turns+=min(abs((26-ord(i)+ord("a"))),abs(ord(i)-ord("a")))
k=word[0]
if i!=word[0]:
turns+=min(abs((26-abs(ord(i)-ord(k)))),abs((ord(i)-ord(k))))
k=i
print(turns)
``` | instruction | 0 | 38,187 | 6 | 76,374 |
No | output | 1 | 38,187 | 6 | 76,375 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture:
<image>
After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.
Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
Input
The only line of input contains the name of some exhibit β the non-empty string consisting of no more than 100 characters. It's guaranteed that the string consists of only lowercase English letters.
Output
Print one integer β the minimum number of rotations of the wheel, required to print the name given in the input.
Examples
Input
zeus
Output
18
Input
map
Output
35
Input
ares
Output
34
Note
<image>
To print the string from the first sample it would be optimal to perform the following sequence of rotations:
1. from 'a' to 'z' (1 rotation counterclockwise),
2. from 'z' to 'e' (5 clockwise rotations),
3. from 'e' to 'u' (10 rotations counterclockwise),
4. from 'u' to 's' (2 counterclockwise rotations).
In total, 1 + 5 + 10 + 2 = 18 rotations are required.
Submitted Solution:
```
def cnt(a,b):
x=abs(ord(a)-ord(b))
return(min(x,26-x))
a=input()
val=0
for i in range(len(a)-1):
if(cnt(a[i],a[i+1])):
val+=1
print(val)
``` | instruction | 0 | 38,188 | 6 | 76,376 |
No | output | 1 | 38,188 | 6 | 76,377 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture:
<image>
After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.
Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
Input
The only line of input contains the name of some exhibit β the non-empty string consisting of no more than 100 characters. It's guaranteed that the string consists of only lowercase English letters.
Output
Print one integer β the minimum number of rotations of the wheel, required to print the name given in the input.
Examples
Input
zeus
Output
18
Input
map
Output
35
Input
ares
Output
34
Note
<image>
To print the string from the first sample it would be optimal to perform the following sequence of rotations:
1. from 'a' to 'z' (1 rotation counterclockwise),
2. from 'z' to 'e' (5 clockwise rotations),
3. from 'e' to 'u' (10 rotations counterclockwise),
4. from 'u' to 's' (2 counterclockwise rotations).
In total, 1 + 5 + 10 + 2 = 18 rotations are required.
Submitted Solution:
```
y=str(input())
y = 'a' + y
j,t=0,0
b = [0]*(len(y))
for i in range(len(y)):
b[j] = (ord(y[i])) - 96
j+=1
print(b)
for k in range(len(y)):
if b[k+1] > b[k]:
f = (26+b[k]) - b[k+1]
e = abs(b[k] - b[k+1])
else:
f = (26+b[k+1]) - b[k]
e = abs(b[k] - b[k+1])
if f > e :
t+=e
else:
t+=f
k+=1
if k+1 >= len(y):
break
print(t)
``` | instruction | 0 | 38,189 | 6 | 76,378 |
No | output | 1 | 38,189 | 6 | 76,379 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture:
<image>
After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.
Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
Input
The only line of input contains the name of some exhibit β the non-empty string consisting of no more than 100 characters. It's guaranteed that the string consists of only lowercase English letters.
Output
Print one integer β the minimum number of rotations of the wheel, required to print the name given in the input.
Examples
Input
zeus
Output
18
Input
map
Output
35
Input
ares
Output
34
Note
<image>
To print the string from the first sample it would be optimal to perform the following sequence of rotations:
1. from 'a' to 'z' (1 rotation counterclockwise),
2. from 'z' to 'e' (5 clockwise rotations),
3. from 'e' to 'u' (10 rotations counterclockwise),
4. from 'u' to 's' (2 counterclockwise rotations).
In total, 1 + 5 + 10 + 2 = 18 rotations are required.
Submitted Solution:
```
s = input()
a = ''.join([chr(i) for i in range(ord('a'), ord('z')+1)])
if s[0] is not 'a':
s = 'a' + s
sum = 0
def distance(len_string, l_1, l_2):
i = (l_1 - l_2) % len_string
j = (l_2 - l_1) % len_string
return min(i, j)
for i, l in enumerate(s):
if l is s[-1]:
break
sum += distance(len(a), a.index(s[i]), a.index(s[i+1]))
print(sum)
``` | instruction | 0 | 38,190 | 6 | 76,380 |
No | output | 1 | 38,190 | 6 | 76,381 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Most C/C++ programmers know about excellent opportunities that preprocessor #define directives give; but many know as well about the problems that can arise because of their careless use.
In this problem we consider the following model of #define constructions (also called macros). Each macro has its name and value. The generic syntax for declaring a macro is the following:
#define macro_name macro_value
After the macro has been declared, "macro_name" is replaced with "macro_value" each time it is met in the program (only the whole tokens can be replaced; i.e. "macro_name" is replaced only when it is surrounded by spaces or other non-alphabetic symbol). A "macro_value" within our model can only be an arithmetic expression consisting of variables, four arithmetic operations, brackets, and also the names of previously declared macros (in this case replacement is performed sequentially). The process of replacing macros with their values is called substitution.
One of the main problems arising while using macros β the situation when as a result of substitution we get an arithmetic expression with the changed order of calculation because of different priorities of the operations.
Let's consider the following example. Say, we declared such a #define construction:
#define sum x + y
and further in the program the expression "2 * sum" is calculated. After macro substitution is performed we get "2 * x + y", instead of intuitively expected "2 * (x + y)".
Let's call the situation "suspicious", if after the macro substitution the order of calculation changes, falling outside the bounds of some macro. Thus, your task is to find out by the given set of #define definitions and the given expression if this expression is suspicious or not.
Let's speak more formally. We should perform an ordinary macros substitution in the given expression. Moreover, we should perform a "safe" macros substitution in the expression, putting in brackets each macro value; after this, guided by arithmetic rules of brackets expansion, we can omit some of the brackets. If there exist a way to get an expression, absolutely coinciding with the expression that is the result of an ordinary substitution (character-by-character, but ignoring spaces), then this expression and the macros system are called correct, otherwise β suspicious.
Note that we consider the "/" operation as the usual mathematical division, not the integer division like in C/C++. That's why, for example, in the expression "a*(b/c)" we can omit brackets to get the expression "a*b/c".
Input
The first line contains the only number n (0 β€ n β€ 100) β the amount of #define constructions in the given program.
Then there follow n lines, each of them contains just one #define construction. Each construction has the following syntax:
#define name expression
where
* name β the macro name,
* expression β the expression with which the given macro will be replaced. An expression is a non-empty string, containing digits,names of variables, names of previously declared macros, round brackets and operational signs +-*/. It is guaranteed that the expression (before and after macros substitution) is a correct arithmetic expression, having no unary operations. The expression contains only non-negative integers, not exceeding 109.
All the names (#define constructions' names and names of their arguments) are strings of case-sensitive Latin characters. It is guaranteed that the name of any variable is different from any #define construction.
Then, the last line contains an expression that you are to check. This expression is non-empty and satisfies the same limitations as the expressions in #define constructions.
The input lines may contain any number of spaces anywhere, providing these spaces do not break the word "define" or the names of constructions and variables. In particular, there can be any number of spaces before and after the "#" symbol.
The length of any line from the input file does not exceed 100 characters.
Output
Output "OK", if the expression is correct according to the above given criterion, otherwise output "Suspicious".
Examples
Input
1
#define sum x + y
1 * sum
Output
Suspicious
Input
1
#define sum (x + y)
sum - sum
Output
OK
Input
4
#define sum x + y
#define mul a * b
#define div a / b
#define expr sum + mul * div * mul
expr
Output
OK
Input
3
#define SumSafe (a+b)
#define DivUnsafe a/b
#define DenominatorUnsafe a*b
((SumSafe) + DivUnsafe/DivUnsafe + x/DenominatorUnsafe)
Output
Suspicious | instruction | 0 | 38,222 | 6 | 76,444 |
Tags: dp, expression parsing, implementation
Correct Solution:
```
#!/usr/bin/env python
"""
CodeForces: 7E. Defining Macros
The key for the solution is the naked operators that are not surrounded by
the parentheses in the macro definition.
Suspicious patterns of the operators in the appearance order are:
o{-} n{+-}
o{*} n{+-}
o{/} n{+-*/}
n{+-} o{*}
n{+-} o{/}
where:
"o{}": an operator before or after the macro might construct
a suspicious expression with the operators in "n{}"
"n{}": a subset of the naked operators in the macro definition
that might construct a suspicious expression with the operator "o"
If the pair of operators in the "o{}" and "n{}" are matched
in the expression, the entire expression would be suspicious.
"""
# Represent the operator as the bit mask:
# Pseudo operator whose priority is lower than "+",
# Add (+), Subtract (-), Multiply (*) and Division (/)
P, A, S, M, D = 1, 2, 4, 8, 16
ADD = A | S
ANY = A | S | M | D
# Map of the operators (+-*/) to the bit mask
OP_BIT = {"+": A, "-": S, "*": M, "/": D, ")": 0}
# unsafe naked operators against the operator before and after the macro
UNSAFE_BEFORE = {P: 0, A: 0, S: ADD, M: ADD, D: ANY}
UNSAFE_AFTER = {P: 0, A: 0, S: 0, M: ADD, D: ADD}
# Macro definitions:
# a map from the macro name to the set of its naked operators
# Note: the set is represented as a bit pattern
macro = dict()
# Parse expression with checking suspicious expression
def expr(chars,
# following arguments are the short cut
pseudo=P,
expand=macro.get,
op_bit=OP_BIT,
unsafe_before=UNSAFE_BEFORE,
unsafe_after=UNSAFE_AFTER):
# stack of the operator before the left parenthesis "("
paren = []
push = paren.append
pop = paren.pop
# list of characters that would be a macro name or a number
name = []
keep = name.append
forget = name.clear
# last_op: last operator before the macro name or the number
# retval: set of the naked operators of this expression
# naked: set of the naked operators of the macro expanded
last_op = retval = naked = pseudo
# expand the macro and check the preceding operator
def safe():
nonlocal naked
naked = expand("".join(name), pseudo)
forget()
# early exit for a suspicious expression and a value
if naked <= pseudo:
return naked
# safety check against the operator before the macro
return not (unsafe_before[last_op] & naked)
# parse the expression
for c in chars:
if c == "(":
push(last_op)
last_op = pseudo
elif c not in op_bit:
keep(c)
elif not safe():
return 0
elif c == ")":
last_op = pop()
else:
# safety check against the operator after the macro
last_op = op_bit[c]
if unsafe_after[last_op] & naked:
return 0
# record operators not surrounded by the parentheses
if not paren:
retval |= last_op
if name and not safe():
return 0
return retval
def main():
global macro
def chars(b, t):
for k in range(b, len(t)):
yield from t[k]
for _ in range(int(input())):
token = input().split()
s = token[0] == "#"
macro[token[1 + s]] = expr(chars(2 + s, token))
print("OK" if expr((c for c in input() if c != " ")) else "Suspicious")
if __name__ == '__main__':
main()
``` | output | 1 | 38,222 | 6 | 76,445 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Most C/C++ programmers know about excellent opportunities that preprocessor #define directives give; but many know as well about the problems that can arise because of their careless use.
In this problem we consider the following model of #define constructions (also called macros). Each macro has its name and value. The generic syntax for declaring a macro is the following:
#define macro_name macro_value
After the macro has been declared, "macro_name" is replaced with "macro_value" each time it is met in the program (only the whole tokens can be replaced; i.e. "macro_name" is replaced only when it is surrounded by spaces or other non-alphabetic symbol). A "macro_value" within our model can only be an arithmetic expression consisting of variables, four arithmetic operations, brackets, and also the names of previously declared macros (in this case replacement is performed sequentially). The process of replacing macros with their values is called substitution.
One of the main problems arising while using macros β the situation when as a result of substitution we get an arithmetic expression with the changed order of calculation because of different priorities of the operations.
Let's consider the following example. Say, we declared such a #define construction:
#define sum x + y
and further in the program the expression "2 * sum" is calculated. After macro substitution is performed we get "2 * x + y", instead of intuitively expected "2 * (x + y)".
Let's call the situation "suspicious", if after the macro substitution the order of calculation changes, falling outside the bounds of some macro. Thus, your task is to find out by the given set of #define definitions and the given expression if this expression is suspicious or not.
Let's speak more formally. We should perform an ordinary macros substitution in the given expression. Moreover, we should perform a "safe" macros substitution in the expression, putting in brackets each macro value; after this, guided by arithmetic rules of brackets expansion, we can omit some of the brackets. If there exist a way to get an expression, absolutely coinciding with the expression that is the result of an ordinary substitution (character-by-character, but ignoring spaces), then this expression and the macros system are called correct, otherwise β suspicious.
Note that we consider the "/" operation as the usual mathematical division, not the integer division like in C/C++. That's why, for example, in the expression "a*(b/c)" we can omit brackets to get the expression "a*b/c".
Input
The first line contains the only number n (0 β€ n β€ 100) β the amount of #define constructions in the given program.
Then there follow n lines, each of them contains just one #define construction. Each construction has the following syntax:
#define name expression
where
* name β the macro name,
* expression β the expression with which the given macro will be replaced. An expression is a non-empty string, containing digits,names of variables, names of previously declared macros, round brackets and operational signs +-*/. It is guaranteed that the expression (before and after macros substitution) is a correct arithmetic expression, having no unary operations. The expression contains only non-negative integers, not exceeding 109.
All the names (#define constructions' names and names of their arguments) are strings of case-sensitive Latin characters. It is guaranteed that the name of any variable is different from any #define construction.
Then, the last line contains an expression that you are to check. This expression is non-empty and satisfies the same limitations as the expressions in #define constructions.
The input lines may contain any number of spaces anywhere, providing these spaces do not break the word "define" or the names of constructions and variables. In particular, there can be any number of spaces before and after the "#" symbol.
The length of any line from the input file does not exceed 100 characters.
Output
Output "OK", if the expression is correct according to the above given criterion, otherwise output "Suspicious".
Examples
Input
1
#define sum x + y
1 * sum
Output
Suspicious
Input
1
#define sum (x + y)
sum - sum
Output
OK
Input
4
#define sum x + y
#define mul a * b
#define div a / b
#define expr sum + mul * div * mul
expr
Output
OK
Input
3
#define SumSafe (a+b)
#define DivUnsafe a/b
#define DenominatorUnsafe a*b
((SumSafe) + DivUnsafe/DivUnsafe + x/DenominatorUnsafe)
Output
Suspicious | instruction | 0 | 38,223 | 6 | 76,446 |
Tags: dp, expression parsing, implementation
Correct Solution:
```
P, A, S, M, D = 1, 2, 4, 8, 16
ADD = A | S
ANY = A | S | M | D
OP_BIT = {"+": A, "-": S, "*": M, "/": D, ")": 0}
UNSAFE_BEFORE = {P: 0, A: 0, S: ADD, M: ADD, D: ANY}
UNSAFE_AFTER = {P: 0, A: 0, S: 0, M: ADD, D: ADD}
macro = dict()
def expr(chars,
pseudo=P,
expand=macro.get,
op_bit=OP_BIT,
unsafe_before=UNSAFE_BEFORE,
unsafe_after=UNSAFE_AFTER):
paren = []
push = paren.append
pop = paren.pop
name = []
keep = name.append
forget = name.clear
last_op = retval = naked = pseudo
def safe():
nonlocal naked
naked = expand("".join(name), pseudo)
forget()
if naked <= pseudo:
return naked
return not (unsafe_before[last_op] & naked)
for c in chars:
if c == "(":
push(last_op)
last_op = pseudo
elif c not in op_bit:
keep(c)
elif not safe():
return 0
elif c == ")":
last_op = pop()
else:
last_op = op_bit[c]
if unsafe_after[last_op] & naked:
return 0
if not paren:
retval |= last_op
if name and not safe():
return 0
return retval
def main():
global macro
def chars(b, t):
for k in range(b, len(t)):
yield from t[k]
for _ in range(int(input())):
token = input().split()
s = token[0] == "#"
macro[token[1 + s]] = expr(chars(2 + s, token))
print("OK" if expr((c for c in input() if c != " ")) else "Suspicious")
if __name__ == '__main__':
main()
``` | output | 1 | 38,223 | 6 | 76,447 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Most C/C++ programmers know about excellent opportunities that preprocessor #define directives give; but many know as well about the problems that can arise because of their careless use.
In this problem we consider the following model of #define constructions (also called macros). Each macro has its name and value. The generic syntax for declaring a macro is the following:
#define macro_name macro_value
After the macro has been declared, "macro_name" is replaced with "macro_value" each time it is met in the program (only the whole tokens can be replaced; i.e. "macro_name" is replaced only when it is surrounded by spaces or other non-alphabetic symbol). A "macro_value" within our model can only be an arithmetic expression consisting of variables, four arithmetic operations, brackets, and also the names of previously declared macros (in this case replacement is performed sequentially). The process of replacing macros with their values is called substitution.
One of the main problems arising while using macros β the situation when as a result of substitution we get an arithmetic expression with the changed order of calculation because of different priorities of the operations.
Let's consider the following example. Say, we declared such a #define construction:
#define sum x + y
and further in the program the expression "2 * sum" is calculated. After macro substitution is performed we get "2 * x + y", instead of intuitively expected "2 * (x + y)".
Let's call the situation "suspicious", if after the macro substitution the order of calculation changes, falling outside the bounds of some macro. Thus, your task is to find out by the given set of #define definitions and the given expression if this expression is suspicious or not.
Let's speak more formally. We should perform an ordinary macros substitution in the given expression. Moreover, we should perform a "safe" macros substitution in the expression, putting in brackets each macro value; after this, guided by arithmetic rules of brackets expansion, we can omit some of the brackets. If there exist a way to get an expression, absolutely coinciding with the expression that is the result of an ordinary substitution (character-by-character, but ignoring spaces), then this expression and the macros system are called correct, otherwise β suspicious.
Note that we consider the "/" operation as the usual mathematical division, not the integer division like in C/C++. That's why, for example, in the expression "a*(b/c)" we can omit brackets to get the expression "a*b/c".
Input
The first line contains the only number n (0 β€ n β€ 100) β the amount of #define constructions in the given program.
Then there follow n lines, each of them contains just one #define construction. Each construction has the following syntax:
#define name expression
where
* name β the macro name,
* expression β the expression with which the given macro will be replaced. An expression is a non-empty string, containing digits,names of variables, names of previously declared macros, round brackets and operational signs +-*/. It is guaranteed that the expression (before and after macros substitution) is a correct arithmetic expression, having no unary operations. The expression contains only non-negative integers, not exceeding 109.
All the names (#define constructions' names and names of their arguments) are strings of case-sensitive Latin characters. It is guaranteed that the name of any variable is different from any #define construction.
Then, the last line contains an expression that you are to check. This expression is non-empty and satisfies the same limitations as the expressions in #define constructions.
The input lines may contain any number of spaces anywhere, providing these spaces do not break the word "define" or the names of constructions and variables. In particular, there can be any number of spaces before and after the "#" symbol.
The length of any line from the input file does not exceed 100 characters.
Output
Output "OK", if the expression is correct according to the above given criterion, otherwise output "Suspicious".
Examples
Input
1
#define sum x + y
1 * sum
Output
Suspicious
Input
1
#define sum (x + y)
sum - sum
Output
OK
Input
4
#define sum x + y
#define mul a * b
#define div a / b
#define expr sum + mul * div * mul
expr
Output
OK
Input
3
#define SumSafe (a+b)
#define DivUnsafe a/b
#define DenominatorUnsafe a*b
((SumSafe) + DivUnsafe/DivUnsafe + x/DenominatorUnsafe)
Output
Suspicious | instruction | 0 | 38,224 | 6 | 76,448 |
Tags: dp, expression parsing, implementation
Correct Solution:
```
#!/usr/bin/env python
'''
' Author: Cheng-Shih Wong
' Email: mob5566@gmail.com
' Date: 2017-08-02
'''
import re
from collections import deque
# compare the priority of operators
def comp(opa, opb):
if opa=='(' or opb=='(':
return False
elif opa==')':
return opb=='('
elif opa in '*/':
return opb in '+-*/)'
else:
return opb in '+-)'
# # print the operator priority table
# print('{:6}'.format(''), end='')
# for a in '+-*/()':
# print('{:>6}'.format(a), end='')
# print()
# for a in '+-*/()':
# print('{:>6}'.format(a), end='')
# for b in '+-*/()':
# print('{:6}'.format(comp(a, b)), end='')
# print()
def arith(stk, stkop):
B = stk.pop()
A = stk.pop()
op = stkop.pop()
ok = True
if op=='-' and B<2:
ok = False
elif op=='*' and (A<2 or B<2):
ok = False
elif op=='/' and (A<2 or B<3):
ok = False
if op in '+-':
stk.append(1)
elif op in '*/':
stk.append(2)
return ok
def solve(pri, exp, defs):
terms = re.findall(r'[a-zA-z0-9]+|[\+\-\*/\(\)]', exp)
safe = True
# arithmetic
stk = deque()
opstk = deque()
for term in terms:
if term in '+-*/()':
while len(opstk) and comp(opstk[-1], term):
safe &= arith(stk, opstk)
if term==')':
opstk.pop()
stk.pop()
stk.append(3)
else:
opstk.append(term)
else:
if term not in pri:
if term in defs:
ok, p = solve(pri, defs[term], defs)
safe &= ok
pri[term] = p
else:
pri[term] = 3
stk.append(pri[term])
while len(opstk):
safe &= arith(stk, opstk)
return safe, stk.pop()
n = int(input())
inputs = [input() for i in range(n)]
expr = input()
defs = {}
for line in inputs:
line = line[re.match(r'.*#.*define', line).end():]
terms = re.findall(r'[^ ]+', line)
defs[terms[0]] = ''.join(terms[1:])
prio = {}
if solve(prio, expr, defs)[0]:
print('OK')
else:
print('Suspicious')
``` | output | 1 | 38,224 | 6 | 76,449 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Most C/C++ programmers know about excellent opportunities that preprocessor #define directives give; but many know as well about the problems that can arise because of their careless use.
In this problem we consider the following model of #define constructions (also called macros). Each macro has its name and value. The generic syntax for declaring a macro is the following:
#define macro_name macro_value
After the macro has been declared, "macro_name" is replaced with "macro_value" each time it is met in the program (only the whole tokens can be replaced; i.e. "macro_name" is replaced only when it is surrounded by spaces or other non-alphabetic symbol). A "macro_value" within our model can only be an arithmetic expression consisting of variables, four arithmetic operations, brackets, and also the names of previously declared macros (in this case replacement is performed sequentially). The process of replacing macros with their values is called substitution.
One of the main problems arising while using macros β the situation when as a result of substitution we get an arithmetic expression with the changed order of calculation because of different priorities of the operations.
Let's consider the following example. Say, we declared such a #define construction:
#define sum x + y
and further in the program the expression "2 * sum" is calculated. After macro substitution is performed we get "2 * x + y", instead of intuitively expected "2 * (x + y)".
Let's call the situation "suspicious", if after the macro substitution the order of calculation changes, falling outside the bounds of some macro. Thus, your task is to find out by the given set of #define definitions and the given expression if this expression is suspicious or not.
Let's speak more formally. We should perform an ordinary macros substitution in the given expression. Moreover, we should perform a "safe" macros substitution in the expression, putting in brackets each macro value; after this, guided by arithmetic rules of brackets expansion, we can omit some of the brackets. If there exist a way to get an expression, absolutely coinciding with the expression that is the result of an ordinary substitution (character-by-character, but ignoring spaces), then this expression and the macros system are called correct, otherwise β suspicious.
Note that we consider the "/" operation as the usual mathematical division, not the integer division like in C/C++. That's why, for example, in the expression "a*(b/c)" we can omit brackets to get the expression "a*b/c".
Input
The first line contains the only number n (0 β€ n β€ 100) β the amount of #define constructions in the given program.
Then there follow n lines, each of them contains just one #define construction. Each construction has the following syntax:
#define name expression
where
* name β the macro name,
* expression β the expression with which the given macro will be replaced. An expression is a non-empty string, containing digits,names of variables, names of previously declared macros, round brackets and operational signs +-*/. It is guaranteed that the expression (before and after macros substitution) is a correct arithmetic expression, having no unary operations. The expression contains only non-negative integers, not exceeding 109.
All the names (#define constructions' names and names of their arguments) are strings of case-sensitive Latin characters. It is guaranteed that the name of any variable is different from any #define construction.
Then, the last line contains an expression that you are to check. This expression is non-empty and satisfies the same limitations as the expressions in #define constructions.
The input lines may contain any number of spaces anywhere, providing these spaces do not break the word "define" or the names of constructions and variables. In particular, there can be any number of spaces before and after the "#" symbol.
The length of any line from the input file does not exceed 100 characters.
Output
Output "OK", if the expression is correct according to the above given criterion, otherwise output "Suspicious".
Examples
Input
1
#define sum x + y
1 * sum
Output
Suspicious
Input
1
#define sum (x + y)
sum - sum
Output
OK
Input
4
#define sum x + y
#define mul a * b
#define div a / b
#define expr sum + mul * div * mul
expr
Output
OK
Input
3
#define SumSafe (a+b)
#define DivUnsafe a/b
#define DenominatorUnsafe a*b
((SumSafe) + DivUnsafe/DivUnsafe + x/DenominatorUnsafe)
Output
Suspicious | instruction | 0 | 38,225 | 6 | 76,450 |
Tags: dp, expression parsing, implementation
Correct Solution:
```
def helper(s, d):
if s in d:
return d[s]
cnt = 0
for idx, c in reversed(list(enumerate(s))):
if c == ')':
cnt += 1
elif c == '(':
cnt -= 1
if cnt == 0 and c in ['+', '-']:
s1 = s[0:idx]
s2 = s[idx+1:]
t1 = helper(s1, d)
t2 = helper(s2, d)
t = 3
if t1 == 2 or t2 == 2:
t = 2
elif t2 == 3 and c == '-':
t = 2
d[s] = t
return t
cnt = 0
for idx, c in reversed(list(enumerate(s))):
if c == ')':
cnt += 1
elif c == '(':
cnt -= 1
if cnt == 0 and c in ['*', '/']:
s1 = s[0:idx]
s2 = s[idx+1:]
t1 = helper(s1, d)
t2 = helper(s2, d)
# print(s)
# print(s1, ' ', s2)
t = 4
if t1 == 2 or t2 == 2:
t = 2
elif t1 == 3 or t2 == 3:
t = 2
elif t2 == 4 and c == '/':
t = 2
d[s] = t
return t
if s[0] == '(' and s[-1] == ')':
if helper(s[1:-1], d) == 2:
return 2
else:
return 1
d[s] = 1
return 1
d = {}
n = int(input())
for i in range(0, n):
temp = input()
j = 0
while temp[j] != '#':
j += 1
while temp[j] != 'd':
j += 1
j += 6
temp = temp[j:].strip()
arr = temp.split(' ', 1)
name, exp = arr[0], ''.join(arr[1].split())
t = helper(exp, d)
d[name] = t
final = ''.join(input().split())
res = helper(final, d)
print(['OK', 'Suspicious'][res == 2])
``` | output | 1 | 38,225 | 6 | 76,451 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Most C/C++ programmers know about excellent opportunities that preprocessor #define directives give; but many know as well about the problems that can arise because of their careless use.
In this problem we consider the following model of #define constructions (also called macros). Each macro has its name and value. The generic syntax for declaring a macro is the following:
#define macro_name macro_value
After the macro has been declared, "macro_name" is replaced with "macro_value" each time it is met in the program (only the whole tokens can be replaced; i.e. "macro_name" is replaced only when it is surrounded by spaces or other non-alphabetic symbol). A "macro_value" within our model can only be an arithmetic expression consisting of variables, four arithmetic operations, brackets, and also the names of previously declared macros (in this case replacement is performed sequentially). The process of replacing macros with their values is called substitution.
One of the main problems arising while using macros β the situation when as a result of substitution we get an arithmetic expression with the changed order of calculation because of different priorities of the operations.
Let's consider the following example. Say, we declared such a #define construction:
#define sum x + y
and further in the program the expression "2 * sum" is calculated. After macro substitution is performed we get "2 * x + y", instead of intuitively expected "2 * (x + y)".
Let's call the situation "suspicious", if after the macro substitution the order of calculation changes, falling outside the bounds of some macro. Thus, your task is to find out by the given set of #define definitions and the given expression if this expression is suspicious or not.
Let's speak more formally. We should perform an ordinary macros substitution in the given expression. Moreover, we should perform a "safe" macros substitution in the expression, putting in brackets each macro value; after this, guided by arithmetic rules of brackets expansion, we can omit some of the brackets. If there exist a way to get an expression, absolutely coinciding with the expression that is the result of an ordinary substitution (character-by-character, but ignoring spaces), then this expression and the macros system are called correct, otherwise β suspicious.
Note that we consider the "/" operation as the usual mathematical division, not the integer division like in C/C++. That's why, for example, in the expression "a*(b/c)" we can omit brackets to get the expression "a*b/c".
Input
The first line contains the only number n (0 β€ n β€ 100) β the amount of #define constructions in the given program.
Then there follow n lines, each of them contains just one #define construction. Each construction has the following syntax:
#define name expression
where
* name β the macro name,
* expression β the expression with which the given macro will be replaced. An expression is a non-empty string, containing digits,names of variables, names of previously declared macros, round brackets and operational signs +-*/. It is guaranteed that the expression (before and after macros substitution) is a correct arithmetic expression, having no unary operations. The expression contains only non-negative integers, not exceeding 109.
All the names (#define constructions' names and names of their arguments) are strings of case-sensitive Latin characters. It is guaranteed that the name of any variable is different from any #define construction.
Then, the last line contains an expression that you are to check. This expression is non-empty and satisfies the same limitations as the expressions in #define constructions.
The input lines may contain any number of spaces anywhere, providing these spaces do not break the word "define" or the names of constructions and variables. In particular, there can be any number of spaces before and after the "#" symbol.
The length of any line from the input file does not exceed 100 characters.
Output
Output "OK", if the expression is correct according to the above given criterion, otherwise output "Suspicious".
Examples
Input
1
#define sum x + y
1 * sum
Output
Suspicious
Input
1
#define sum (x + y)
sum - sum
Output
OK
Input
4
#define sum x + y
#define mul a * b
#define div a / b
#define expr sum + mul * div * mul
expr
Output
OK
Input
3
#define SumSafe (a+b)
#define DivUnsafe a/b
#define DenominatorUnsafe a*b
((SumSafe) + DivUnsafe/DivUnsafe + x/DenominatorUnsafe)
Output
Suspicious | instruction | 0 | 38,226 | 6 | 76,452 |
Tags: dp, expression parsing, implementation
Correct Solution:
```
# 1:correct, 2:incorrect, 3:(a+b), no - at front, no * or / neighbor, 4:(a*b),(a/b) no / at front
def helper(s, d):
# print(s)
if s in d:
return d[s]
cnt = 0
for idx, c in reversed(list(enumerate(s))):
if c == ')':
cnt += 1
elif c == '(':
cnt -= 1
if cnt == 0 and c in ['+', '-']:
s1 = s[0:idx]
s2 = s[idx+1:]
t1 = helper(s1, d)
t2 = helper(s2, d)
t = 3
if t1 == 2 or t2 == 2:
t = 2
elif t2 == 3 and c == '-':
t = 2
d[s] = t
return t
cnt = 0
for idx, c in reversed(list(enumerate(s))):
if c == ')':
cnt += 1
elif c == '(':
cnt -= 1
if cnt == 0 and c in ['*', '/']:
s1 = s[0:idx]
s2 = s[idx+1:]
t1 = helper(s1, d)
t2 = helper(s2, d)
# print(s)
# print(s1, ' ', s2)
t = 4
if t1 == 2 or t2 == 2:
t = 2
elif t1 == 3 or t2 == 3:
t = 2
elif t2 == 4 and c == '/':
t = 2
d[s] = t
return t
if s[0] == '(' and s[-1] == ')':
if helper(s[1:-1], d) == 2:
return 2
else:
return 1
d[s] = 1
return 1
d = {}
n = int(input())
for i in range(0, n):
temp = input()
j = 0
while temp[j] != '#':
j += 1
while temp[j] != 'd':
j += 1
j += 6
temp = temp[j:].strip()
arr = temp.split(' ', 1)
# print(arr)
name, exp = arr[0], ''.join(arr[1].split())
# print(name, exp)
t = helper(exp, d)
d[name] = t
final = ''.join(input().split())
res = helper(final, d)
if res == 2:
print('Suspicious')
else:
print('OK')
# print(arr)
# print(helper('(a-a)*(x/x-1)', d))
``` | output | 1 | 38,226 | 6 | 76,453 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Most C/C++ programmers know about excellent opportunities that preprocessor #define directives give; but many know as well about the problems that can arise because of their careless use.
In this problem we consider the following model of #define constructions (also called macros). Each macro has its name and value. The generic syntax for declaring a macro is the following:
#define macro_name macro_value
After the macro has been declared, "macro_name" is replaced with "macro_value" each time it is met in the program (only the whole tokens can be replaced; i.e. "macro_name" is replaced only when it is surrounded by spaces or other non-alphabetic symbol). A "macro_value" within our model can only be an arithmetic expression consisting of variables, four arithmetic operations, brackets, and also the names of previously declared macros (in this case replacement is performed sequentially). The process of replacing macros with their values is called substitution.
One of the main problems arising while using macros β the situation when as a result of substitution we get an arithmetic expression with the changed order of calculation because of different priorities of the operations.
Let's consider the following example. Say, we declared such a #define construction:
#define sum x + y
and further in the program the expression "2 * sum" is calculated. After macro substitution is performed we get "2 * x + y", instead of intuitively expected "2 * (x + y)".
Let's call the situation "suspicious", if after the macro substitution the order of calculation changes, falling outside the bounds of some macro. Thus, your task is to find out by the given set of #define definitions and the given expression if this expression is suspicious or not.
Let's speak more formally. We should perform an ordinary macros substitution in the given expression. Moreover, we should perform a "safe" macros substitution in the expression, putting in brackets each macro value; after this, guided by arithmetic rules of brackets expansion, we can omit some of the brackets. If there exist a way to get an expression, absolutely coinciding with the expression that is the result of an ordinary substitution (character-by-character, but ignoring spaces), then this expression and the macros system are called correct, otherwise β suspicious.
Note that we consider the "/" operation as the usual mathematical division, not the integer division like in C/C++. That's why, for example, in the expression "a*(b/c)" we can omit brackets to get the expression "a*b/c".
Input
The first line contains the only number n (0 β€ n β€ 100) β the amount of #define constructions in the given program.
Then there follow n lines, each of them contains just one #define construction. Each construction has the following syntax:
#define name expression
where
* name β the macro name,
* expression β the expression with which the given macro will be replaced. An expression is a non-empty string, containing digits,names of variables, names of previously declared macros, round brackets and operational signs +-*/. It is guaranteed that the expression (before and after macros substitution) is a correct arithmetic expression, having no unary operations. The expression contains only non-negative integers, not exceeding 109.
All the names (#define constructions' names and names of their arguments) are strings of case-sensitive Latin characters. It is guaranteed that the name of any variable is different from any #define construction.
Then, the last line contains an expression that you are to check. This expression is non-empty and satisfies the same limitations as the expressions in #define constructions.
The input lines may contain any number of spaces anywhere, providing these spaces do not break the word "define" or the names of constructions and variables. In particular, there can be any number of spaces before and after the "#" symbol.
The length of any line from the input file does not exceed 100 characters.
Output
Output "OK", if the expression is correct according to the above given criterion, otherwise output "Suspicious".
Examples
Input
1
#define sum x + y
1 * sum
Output
Suspicious
Input
1
#define sum (x + y)
sum - sum
Output
OK
Input
4
#define sum x + y
#define mul a * b
#define div a / b
#define expr sum + mul * div * mul
expr
Output
OK
Input
3
#define SumSafe (a+b)
#define DivUnsafe a/b
#define DenominatorUnsafe a*b
((SumSafe) + DivUnsafe/DivUnsafe + x/DenominatorUnsafe)
Output
Suspicious | instruction | 0 | 38,227 | 6 | 76,454 |
Tags: dp, expression parsing, implementation
Correct Solution:
```
# 1:correct, 2:incorrect, 3:(a+b), no - at front, no * or / neighbor, 4:(a*b),(a/b) no / at front
def helper(s, d):
if s in d:
return d[s]
cnt = 0
for idx, c in reversed(list(enumerate(s))):
if c == ')':
cnt += 1
elif c == '(':
cnt -= 1
if cnt == 0 and c in ['+', '-']:
s1 = s[0:idx]
s2 = s[idx+1:]
t1 = helper(s1, d)
t2 = helper(s2, d)
t = 3
if t1 == 2 or t2 == 2:
t = 2
elif t2 == 3 and c == '-':
t = 2
d[s] = t
return t
cnt = 0
for idx, c in reversed(list(enumerate(s))):
if c == ')':
cnt += 1
elif c == '(':
cnt -= 1
if cnt == 0 and c in ['*', '/']:
s1 = s[0:idx]
s2 = s[idx+1:]
t1 = helper(s1, d)
t2 = helper(s2, d)
t = 4
if t1 == 2 or t2 == 2:
t = 2
elif t1 == 3 or t2 == 3:
t = 2
elif t2 == 4 and c == '/':
t = 2
d[s] = t
return t
if s[0] == '(' and s[-1] == ')':
if helper(s[1:-1], d) == 2:
return 2
else:
return 1
d[s] = 1
return 1
d = {}
n = int(input())
for i in range(0, n):
temp = input()
j = 0
while temp[j] != '#':
j += 1
while temp[j] != 'd':
j += 1
j += 6
temp = temp[j:].strip()
arr = temp.split(' ', 1)
name, exp = arr[0], ''.join(arr[1].split())
t = helper(exp, d)
d[name] = t
final = ''.join(input().split())
res = helper(final, d)
if res == 2:
print('Suspicious')
else:
print('OK')
``` | output | 1 | 38,227 | 6 | 76,455 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Most C/C++ programmers know about excellent opportunities that preprocessor #define directives give; but many know as well about the problems that can arise because of their careless use.
In this problem we consider the following model of #define constructions (also called macros). Each macro has its name and value. The generic syntax for declaring a macro is the following:
#define macro_name macro_value
After the macro has been declared, "macro_name" is replaced with "macro_value" each time it is met in the program (only the whole tokens can be replaced; i.e. "macro_name" is replaced only when it is surrounded by spaces or other non-alphabetic symbol). A "macro_value" within our model can only be an arithmetic expression consisting of variables, four arithmetic operations, brackets, and also the names of previously declared macros (in this case replacement is performed sequentially). The process of replacing macros with their values is called substitution.
One of the main problems arising while using macros β the situation when as a result of substitution we get an arithmetic expression with the changed order of calculation because of different priorities of the operations.
Let's consider the following example. Say, we declared such a #define construction:
#define sum x + y
and further in the program the expression "2 * sum" is calculated. After macro substitution is performed we get "2 * x + y", instead of intuitively expected "2 * (x + y)".
Let's call the situation "suspicious", if after the macro substitution the order of calculation changes, falling outside the bounds of some macro. Thus, your task is to find out by the given set of #define definitions and the given expression if this expression is suspicious or not.
Let's speak more formally. We should perform an ordinary macros substitution in the given expression. Moreover, we should perform a "safe" macros substitution in the expression, putting in brackets each macro value; after this, guided by arithmetic rules of brackets expansion, we can omit some of the brackets. If there exist a way to get an expression, absolutely coinciding with the expression that is the result of an ordinary substitution (character-by-character, but ignoring spaces), then this expression and the macros system are called correct, otherwise β suspicious.
Note that we consider the "/" operation as the usual mathematical division, not the integer division like in C/C++. That's why, for example, in the expression "a*(b/c)" we can omit brackets to get the expression "a*b/c".
Input
The first line contains the only number n (0 β€ n β€ 100) β the amount of #define constructions in the given program.
Then there follow n lines, each of them contains just one #define construction. Each construction has the following syntax:
#define name expression
where
* name β the macro name,
* expression β the expression with which the given macro will be replaced. An expression is a non-empty string, containing digits,names of variables, names of previously declared macros, round brackets and operational signs +-*/. It is guaranteed that the expression (before and after macros substitution) is a correct arithmetic expression, having no unary operations. The expression contains only non-negative integers, not exceeding 109.
All the names (#define constructions' names and names of their arguments) are strings of case-sensitive Latin characters. It is guaranteed that the name of any variable is different from any #define construction.
Then, the last line contains an expression that you are to check. This expression is non-empty and satisfies the same limitations as the expressions in #define constructions.
The input lines may contain any number of spaces anywhere, providing these spaces do not break the word "define" or the names of constructions and variables. In particular, there can be any number of spaces before and after the "#" symbol.
The length of any line from the input file does not exceed 100 characters.
Output
Output "OK", if the expression is correct according to the above given criterion, otherwise output "Suspicious".
Examples
Input
1
#define sum x + y
1 * sum
Output
Suspicious
Input
1
#define sum (x + y)
sum - sum
Output
OK
Input
4
#define sum x + y
#define mul a * b
#define div a / b
#define expr sum + mul * div * mul
expr
Output
OK
Input
3
#define SumSafe (a+b)
#define DivUnsafe a/b
#define DenominatorUnsafe a*b
((SumSafe) + DivUnsafe/DivUnsafe + x/DenominatorUnsafe)
Output
Suspicious
Submitted Solution:
```
# 1:correct, 2:incorrect, 3:(a+b), no - at front, no * or / neighbor, 4:(a*b),(a/b) no / at front
def helper(s, d):
if s[0] == '(' and s[-1] == ')':
if helper(s[1:-1], d) == 2:
return 2
else:
return 1
if s in d:
return d[s]
cnt = 0
for idx, c in reversed(list(enumerate(s))):
if c == ')':
cnt += 1
elif c == '(':
cnt -= 1
if cnt == 0 and c in ['+', '-']:
s1 = s[0:idx]
s2 = s[idx+1:]
t1 = helper(s1, d)
t2 = helper(s2, d)
t = 3
if t1 == 2 or t2 == 2:
t = 2
elif t2 == 3 and c == '-':
t = 2
d[s] = t
return t
cnt = 0
for idx, c in reversed(list(enumerate(s))):
if c == ')':
cnt += 1
elif c == '(':
cnt -= 1
if cnt == 0 and c in ['*', '/']:
s1 = s[0:idx]
s2 = s[idx+1:]
t1 = helper(s1, d)
t2 = helper(s2, d)
t = 4
if t1 == 2 or t2 == 2:
t = 2
elif t1 == 3 or t2 == 3:
t = 2
elif t2 == 4 and c == '/':
t = 2
d[s] = t
return t
d[s] = 1
return 1
n = int(input())
d = {}
for i in range(0, n):
temp = input()[8:].split(' ', 1)
name, exp = temp[0], ''.join(temp[1].split())
t = helper(exp, d)
d[name] = t
final = ''.join(input().split())
res = helper(final, d)
if res == 2:
print('Suspicious')
else:
print('OK')
# print(arr)
# print(helper('aa + b - c * (ddd * eee / fff * a / b * c + d - b + c - (a + b)) - d', d))
``` | instruction | 0 | 38,228 | 6 | 76,456 |
No | output | 1 | 38,228 | 6 | 76,457 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.