message stringlengths 2 23.4k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 129 108k | cluster float64 6 6 | __index_level_0__ int64 258 216k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
There are some ambiguities when one writes Berland names with the letters of the Latin alphabet.
For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name.
The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name.
There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account?
Formally, we assume that two words denote the same name, if using the replacements "u" <image> "oo" and "h" <image> "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements.
For example, the following pairs of words denote the same name:
* "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper" <image> "kuuper" and "kuooper" <image> "kuuper".
* "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun" <image> "khoon" and "kkkhoon" <image> "kkhoon" <image> "khoon".
For a given list of words, find the minimal number of groups where the words in each group denote the same name.
Input
The first line contains integer number n (2 β€ n β€ 400) β number of the words in the list.
The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive.
Output
Print the minimal number of groups where the words in each group denote the same name.
Examples
Input
10
mihail
oolyana
kooooper
hoon
ulyana
koouper
mikhail
khun
kuooper
kkkhoon
Output
4
Input
9
hariton
hkariton
buoi
kkkhariton
boooi
bui
khariton
boui
boi
Output
5
Input
2
alex
alex
Output
1
Note
There are four groups of words in the first example. Words in each group denote same name:
1. "mihail", "mikhail"
2. "oolyana", "ulyana"
3. "kooooper", "koouper"
4. "hoon", "khun", "kkkhoon"
There are five groups of words in the second example. Words in each group denote same name:
1. "hariton", "kkkhariton", "khariton"
2. "hkariton"
3. "buoi", "boooi", "boui"
4. "bui"
5. "boi"
In the third example the words are equal, so they denote the same name. | instruction | 0 | 78,818 | 6 | 157,636 |
Tags: implementation
Correct Solution:
```
from collections import defaultdict
n = int(input())
w = []
for i in range(n):
w.append([j for j in input()])
g = defaultdict(int)
for i in range(n):
moved = True
w1 = w[i].copy()
while moved:
moved = False
for j in range(len(w1)-1, 0, -1):
if w1[j] == "h" and w1[j-1] == "k":
w1.pop(j)
w1 = w1[:j] + ["h"] + w1[j:]
w1.pop(j-1)
moved = True
for j in range(len(w1)-1, -1, -1):
if w1[j] == "u":
w1.pop(j)
w1 = w1[:j] + ["o"] + ["o"] + w1[j:]
moved = True
w1 = "".join(w1)
g[w1] += 1
print(len(g))
``` | output | 1 | 78,818 | 6 | 157,637 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are some ambiguities when one writes Berland names with the letters of the Latin alphabet.
For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name.
The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name.
There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account?
Formally, we assume that two words denote the same name, if using the replacements "u" <image> "oo" and "h" <image> "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements.
For example, the following pairs of words denote the same name:
* "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper" <image> "kuuper" and "kuooper" <image> "kuuper".
* "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun" <image> "khoon" and "kkkhoon" <image> "kkhoon" <image> "khoon".
For a given list of words, find the minimal number of groups where the words in each group denote the same name.
Input
The first line contains integer number n (2 β€ n β€ 400) β number of the words in the list.
The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive.
Output
Print the minimal number of groups where the words in each group denote the same name.
Examples
Input
10
mihail
oolyana
kooooper
hoon
ulyana
koouper
mikhail
khun
kuooper
kkkhoon
Output
4
Input
9
hariton
hkariton
buoi
kkkhariton
boooi
bui
khariton
boui
boi
Output
5
Input
2
alex
alex
Output
1
Note
There are four groups of words in the first example. Words in each group denote same name:
1. "mihail", "mikhail"
2. "oolyana", "ulyana"
3. "kooooper", "koouper"
4. "hoon", "khun", "kkkhoon"
There are five groups of words in the second example. Words in each group denote same name:
1. "hariton", "kkkhariton", "khariton"
2. "hkariton"
3. "buoi", "boooi", "boui"
4. "bui"
5. "boi"
In the third example the words are equal, so they denote the same name. | instruction | 0 | 78,819 | 6 | 157,638 |
Tags: implementation
Correct Solution:
```
from sys import stdin
words = set()
def ko(w):
while 'kh' in w:
w = w.replace('kh', 'h', 1)
return w.replace('u', 'oo')
def solve():
inp = stdin.read().strip().split()[1:]
for w in inp:
words.add(ko(w))
print(len(words))
solve()
``` | output | 1 | 78,819 | 6 | 157,639 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are some ambiguities when one writes Berland names with the letters of the Latin alphabet.
For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name.
The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name.
There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account?
Formally, we assume that two words denote the same name, if using the replacements "u" <image> "oo" and "h" <image> "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements.
For example, the following pairs of words denote the same name:
* "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper" <image> "kuuper" and "kuooper" <image> "kuuper".
* "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun" <image> "khoon" and "kkkhoon" <image> "kkhoon" <image> "khoon".
For a given list of words, find the minimal number of groups where the words in each group denote the same name.
Input
The first line contains integer number n (2 β€ n β€ 400) β number of the words in the list.
The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive.
Output
Print the minimal number of groups where the words in each group denote the same name.
Examples
Input
10
mihail
oolyana
kooooper
hoon
ulyana
koouper
mikhail
khun
kuooper
kkkhoon
Output
4
Input
9
hariton
hkariton
buoi
kkkhariton
boooi
bui
khariton
boui
boi
Output
5
Input
2
alex
alex
Output
1
Note
There are four groups of words in the first example. Words in each group denote same name:
1. "mihail", "mikhail"
2. "oolyana", "ulyana"
3. "kooooper", "koouper"
4. "hoon", "khun", "kkkhoon"
There are five groups of words in the second example. Words in each group denote same name:
1. "hariton", "kkkhariton", "khariton"
2. "hkariton"
3. "buoi", "boooi", "boui"
4. "bui"
5. "boi"
In the third example the words are equal, so they denote the same name. | instruction | 0 | 78,820 | 6 | 157,640 |
Tags: implementation
Correct Solution:
```
def k(s):
a = ''
temp = 0
for i in range(len(s)):
if s[i] == 'k' and s[i-1] != 'k' and i != len(s)-1:
temp = i
elif s[i] == 'k' and s[i-1] != 'k' and i == len(s)-1:
a += 'k'
elif s[i] == 'k' and s[i-1] == 'k' and i != len(s)-1:
continue
elif s[i] == 'h' and s[i-1] == 'k':
a += s[i]
elif s[i] != 'h' and s[i-1] == 'k':
a += s[temp:i+1]
elif s[i] == 'k' and s[i-1] == 'k' and i == len(s)-1:
a += s[temp:i+1]
else:
a += s[i]
return a
def u(s):
a = ''
for i in s:
if i == 'u':
a += 'oo'
else:
a += i
return a
n = int(input())
s = set()
for i in range(n):
temp = input()
t2 = u(k(temp))
s.add(t2)
print(len(s))
``` | output | 1 | 78,820 | 6 | 157,641 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are some ambiguities when one writes Berland names with the letters of the Latin alphabet.
For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name.
The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name.
There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account?
Formally, we assume that two words denote the same name, if using the replacements "u" <image> "oo" and "h" <image> "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements.
For example, the following pairs of words denote the same name:
* "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper" <image> "kuuper" and "kuooper" <image> "kuuper".
* "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun" <image> "khoon" and "kkkhoon" <image> "kkhoon" <image> "khoon".
For a given list of words, find the minimal number of groups where the words in each group denote the same name.
Input
The first line contains integer number n (2 β€ n β€ 400) β number of the words in the list.
The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive.
Output
Print the minimal number of groups where the words in each group denote the same name.
Examples
Input
10
mihail
oolyana
kooooper
hoon
ulyana
koouper
mikhail
khun
kuooper
kkkhoon
Output
4
Input
9
hariton
hkariton
buoi
kkkhariton
boooi
bui
khariton
boui
boi
Output
5
Input
2
alex
alex
Output
1
Note
There are four groups of words in the first example. Words in each group denote same name:
1. "mihail", "mikhail"
2. "oolyana", "ulyana"
3. "kooooper", "koouper"
4. "hoon", "khun", "kkkhoon"
There are five groups of words in the second example. Words in each group denote same name:
1. "hariton", "kkkhariton", "khariton"
2. "hkariton"
3. "buoi", "boooi", "boui"
4. "bui"
5. "boi"
In the third example the words are equal, so they denote the same name. | instruction | 0 | 78,821 | 6 | 157,642 |
Tags: implementation
Correct Solution:
```
n = int(input())
m = set()
for i in range(n):
s = input()
while s.count('u') > 0:
s = s.replace('u', 'oo')
while s.count('kh') > 0:
s = s.replace('kh', 'h')
m.add(s)
print(len(m))
``` | output | 1 | 78,821 | 6 | 157,643 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are some ambiguities when one writes Berland names with the letters of the Latin alphabet.
For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name.
The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name.
There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account?
Formally, we assume that two words denote the same name, if using the replacements "u" <image> "oo" and "h" <image> "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements.
For example, the following pairs of words denote the same name:
* "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper" <image> "kuuper" and "kuooper" <image> "kuuper".
* "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun" <image> "khoon" and "kkkhoon" <image> "kkhoon" <image> "khoon".
For a given list of words, find the minimal number of groups where the words in each group denote the same name.
Input
The first line contains integer number n (2 β€ n β€ 400) β number of the words in the list.
The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive.
Output
Print the minimal number of groups where the words in each group denote the same name.
Examples
Input
10
mihail
oolyana
kooooper
hoon
ulyana
koouper
mikhail
khun
kuooper
kkkhoon
Output
4
Input
9
hariton
hkariton
buoi
kkkhariton
boooi
bui
khariton
boui
boi
Output
5
Input
2
alex
alex
Output
1
Note
There are four groups of words in the first example. Words in each group denote same name:
1. "mihail", "mikhail"
2. "oolyana", "ulyana"
3. "kooooper", "koouper"
4. "hoon", "khun", "kkkhoon"
There are five groups of words in the second example. Words in each group denote same name:
1. "hariton", "kkkhariton", "khariton"
2. "hkariton"
3. "buoi", "boooi", "boui"
4. "bui"
5. "boi"
In the third example the words are equal, so they denote the same name.
Submitted Solution:
```
n = input()
#print(n)
names = set()
for i in range(0, int(n)):
s = input()
while "kh" in s:
s = s.replace("kh", "h")
while "u" in s:
s = s.replace("u", "oo")
#print("->", s)
#print(i)
names.add(s)
print(len(names))
``` | instruction | 0 | 78,822 | 6 | 157,644 |
Yes | output | 1 | 78,822 | 6 | 157,645 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are some ambiguities when one writes Berland names with the letters of the Latin alphabet.
For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name.
The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name.
There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account?
Formally, we assume that two words denote the same name, if using the replacements "u" <image> "oo" and "h" <image> "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements.
For example, the following pairs of words denote the same name:
* "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper" <image> "kuuper" and "kuooper" <image> "kuuper".
* "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun" <image> "khoon" and "kkkhoon" <image> "kkhoon" <image> "khoon".
For a given list of words, find the minimal number of groups where the words in each group denote the same name.
Input
The first line contains integer number n (2 β€ n β€ 400) β number of the words in the list.
The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive.
Output
Print the minimal number of groups where the words in each group denote the same name.
Examples
Input
10
mihail
oolyana
kooooper
hoon
ulyana
koouper
mikhail
khun
kuooper
kkkhoon
Output
4
Input
9
hariton
hkariton
buoi
kkkhariton
boooi
bui
khariton
boui
boi
Output
5
Input
2
alex
alex
Output
1
Note
There are four groups of words in the first example. Words in each group denote same name:
1. "mihail", "mikhail"
2. "oolyana", "ulyana"
3. "kooooper", "koouper"
4. "hoon", "khun", "kkkhoon"
There are five groups of words in the second example. Words in each group denote same name:
1. "hariton", "kkkhariton", "khariton"
2. "hkariton"
3. "buoi", "boooi", "boui"
4. "bui"
5. "boi"
In the third example the words are equal, so they denote the same name.
Submitted Solution:
```
n=int(input())
use=set()
for i in range(n):
s=''
fl=False
for j in input()[::-1]:
if fl and j=='k':
continue
elif j=='u':
s+='oo'
fl=False
elif (j=='h'):
fl=True
s+='h'
else:
s+=j
fl=False
#print(s[::-1])
use.add(s[::-1])
print(len(use))
``` | instruction | 0 | 78,823 | 6 | 157,646 |
Yes | output | 1 | 78,823 | 6 | 157,647 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are some ambiguities when one writes Berland names with the letters of the Latin alphabet.
For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name.
The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name.
There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account?
Formally, we assume that two words denote the same name, if using the replacements "u" <image> "oo" and "h" <image> "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements.
For example, the following pairs of words denote the same name:
* "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper" <image> "kuuper" and "kuooper" <image> "kuuper".
* "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun" <image> "khoon" and "kkkhoon" <image> "kkhoon" <image> "khoon".
For a given list of words, find the minimal number of groups where the words in each group denote the same name.
Input
The first line contains integer number n (2 β€ n β€ 400) β number of the words in the list.
The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive.
Output
Print the minimal number of groups where the words in each group denote the same name.
Examples
Input
10
mihail
oolyana
kooooper
hoon
ulyana
koouper
mikhail
khun
kuooper
kkkhoon
Output
4
Input
9
hariton
hkariton
buoi
kkkhariton
boooi
bui
khariton
boui
boi
Output
5
Input
2
alex
alex
Output
1
Note
There are four groups of words in the first example. Words in each group denote same name:
1. "mihail", "mikhail"
2. "oolyana", "ulyana"
3. "kooooper", "koouper"
4. "hoon", "khun", "kkkhoon"
There are five groups of words in the second example. Words in each group denote same name:
1. "hariton", "kkkhariton", "khariton"
2. "hkariton"
3. "buoi", "boooi", "boui"
4. "bui"
5. "boi"
In the third example the words are equal, so they denote the same name.
Submitted Solution:
```
def uoo(x):
newuser=[]
for i in x:
if i=="u":
newuser.append("oo")
else:
newuser.append(i)
return("".join(newuser))
def khh(x):
newuser=[]
kcount=0
kflag=False
for i in x:
if i=="k":
kflag=True
kcount+=1
else:
if kflag:
if i=="h":
newuser.append(i)
else:
for j in range(kcount):
newuser.append("k")
newuser.append(i)
else:
newuser.append(i)
kcount=0
kflag=False
if(kflag):
for j in range(kcount):
newuser.append("k")
# print(newuser)
return("".join(newuser))
n=int(input())
usernames=set()
duplicates=0
for _ in range(n):
user=input()
user=uoo(user)
user=khh(user)
# print(user)
if(user in usernames):
duplicates+=1
else:
usernames.add(user)
# print(usernames)
print(len(usernames))
``` | instruction | 0 | 78,824 | 6 | 157,648 |
Yes | output | 1 | 78,824 | 6 | 157,649 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are some ambiguities when one writes Berland names with the letters of the Latin alphabet.
For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name.
The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name.
There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account?
Formally, we assume that two words denote the same name, if using the replacements "u" <image> "oo" and "h" <image> "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements.
For example, the following pairs of words denote the same name:
* "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper" <image> "kuuper" and "kuooper" <image> "kuuper".
* "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun" <image> "khoon" and "kkkhoon" <image> "kkhoon" <image> "khoon".
For a given list of words, find the minimal number of groups where the words in each group denote the same name.
Input
The first line contains integer number n (2 β€ n β€ 400) β number of the words in the list.
The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive.
Output
Print the minimal number of groups where the words in each group denote the same name.
Examples
Input
10
mihail
oolyana
kooooper
hoon
ulyana
koouper
mikhail
khun
kuooper
kkkhoon
Output
4
Input
9
hariton
hkariton
buoi
kkkhariton
boooi
bui
khariton
boui
boi
Output
5
Input
2
alex
alex
Output
1
Note
There are four groups of words in the first example. Words in each group denote same name:
1. "mihail", "mikhail"
2. "oolyana", "ulyana"
3. "kooooper", "koouper"
4. "hoon", "khun", "kkkhoon"
There are five groups of words in the second example. Words in each group denote same name:
1. "hariton", "kkkhariton", "khariton"
2. "hkariton"
3. "buoi", "boooi", "boui"
4. "bui"
5. "boi"
In the third example the words are equal, so they denote the same name.
Submitted Solution:
```
n = int(input().strip())
A = []
for i in range(n):
A.append(input().strip())
A = list(map(lambda x: x.replace('u','oo'), A))
for i in range(n):
tem = A[i]
toRem = []
for j in range(len(tem)):
if tem[j] == 'h':
lo = None
for k in range(j-1,-1,-1):
if tem[k] == 'k':
lo = k
else:
break
if not lo is None:
toRem.append([lo,j])
# print(tem,toRem)
if toRem:
for j in range(len(toRem)-1,-1,-1):
tem = tem[:toRem[j][0]]+tem[toRem[j][1]:]
A[i] = tem
A.sort()
if A:
out = 1
for i in range(1,len(A)):
if A[i] != A[i-1]:
out+=1
print(out)
``` | instruction | 0 | 78,825 | 6 | 157,650 |
Yes | output | 1 | 78,825 | 6 | 157,651 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are some ambiguities when one writes Berland names with the letters of the Latin alphabet.
For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name.
The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name.
There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account?
Formally, we assume that two words denote the same name, if using the replacements "u" <image> "oo" and "h" <image> "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements.
For example, the following pairs of words denote the same name:
* "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper" <image> "kuuper" and "kuooper" <image> "kuuper".
* "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun" <image> "khoon" and "kkkhoon" <image> "kkhoon" <image> "khoon".
For a given list of words, find the minimal number of groups where the words in each group denote the same name.
Input
The first line contains integer number n (2 β€ n β€ 400) β number of the words in the list.
The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive.
Output
Print the minimal number of groups where the words in each group denote the same name.
Examples
Input
10
mihail
oolyana
kooooper
hoon
ulyana
koouper
mikhail
khun
kuooper
kkkhoon
Output
4
Input
9
hariton
hkariton
buoi
kkkhariton
boooi
bui
khariton
boui
boi
Output
5
Input
2
alex
alex
Output
1
Note
There are four groups of words in the first example. Words in each group denote same name:
1. "mihail", "mikhail"
2. "oolyana", "ulyana"
3. "kooooper", "koouper"
4. "hoon", "khun", "kkkhoon"
There are five groups of words in the second example. Words in each group denote same name:
1. "hariton", "kkkhariton", "khariton"
2. "hkariton"
3. "buoi", "boooi", "boui"
4. "bui"
5. "boi"
In the third example the words are equal, so they denote the same name.
Submitted Solution:
```
n = int(input())
s = set()
for i in range(n):
t = input()
tmp = ""
j = 0
while j < len(t):
if j < len(t) - 1 and t[j] == "o" and t[j + 1] == "o":
tmp += "u"
j += 2
else:
tmp += t[j]
j += 1
t = list(tmp)
j = 0
while j < len(t):
if j < len(t) - 1 and t[j] == "u" and t[j + 1] == "o":
t[j], t[j + 1] = t[j + 1], t[j]
j += 1
else:
j += 1
t = "".join(map(str, t))
tmp = ""
j = len(t) - 1
while j >= 0:
if j >= 0 and t[j] == "h" and t[j - 1] == "k":
j -= 1
k = j
tmp += "h"
while k >= 0 and t[k] == "k":
k -= 1
j -= 1
else:
tmp += t[j]
j -= 1
s.add("".join(tmp[::-1]))
print(len(s))
``` | instruction | 0 | 78,826 | 6 | 157,652 |
No | output | 1 | 78,826 | 6 | 157,653 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are some ambiguities when one writes Berland names with the letters of the Latin alphabet.
For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name.
The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name.
There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account?
Formally, we assume that two words denote the same name, if using the replacements "u" <image> "oo" and "h" <image> "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements.
For example, the following pairs of words denote the same name:
* "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper" <image> "kuuper" and "kuooper" <image> "kuuper".
* "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun" <image> "khoon" and "kkkhoon" <image> "kkhoon" <image> "khoon".
For a given list of words, find the minimal number of groups where the words in each group denote the same name.
Input
The first line contains integer number n (2 β€ n β€ 400) β number of the words in the list.
The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive.
Output
Print the minimal number of groups where the words in each group denote the same name.
Examples
Input
10
mihail
oolyana
kooooper
hoon
ulyana
koouper
mikhail
khun
kuooper
kkkhoon
Output
4
Input
9
hariton
hkariton
buoi
kkkhariton
boooi
bui
khariton
boui
boi
Output
5
Input
2
alex
alex
Output
1
Note
There are four groups of words in the first example. Words in each group denote same name:
1. "mihail", "mikhail"
2. "oolyana", "ulyana"
3. "kooooper", "koouper"
4. "hoon", "khun", "kkkhoon"
There are five groups of words in the second example. Words in each group denote same name:
1. "hariton", "kkkhariton", "khariton"
2. "hkariton"
3. "buoi", "boooi", "boui"
4. "bui"
5. "boi"
In the third example the words are equal, so they denote the same name.
Submitted Solution:
```
def rev(s):
s = s[::-1]
news = []
for i in range(len(s)):
letter = s[i]
if(i == 0):
news.append(letter)
continue
if(letter == 'k'):
if(news[-1] == 'h'):
continue
news.append(letter)
continue
if(letter == 'o'):
if(news[-1] == 'o'):
news.pop()
news.append('u')
continue
news.append(letter)
continue
news.append(letter)
return ''.join(news[::-1])
def transform(s):
news = []
for item in s:
news.append(item)
f = 0
while(f < len(s)):
index = s[f:].find('o')
if(index == -1):break
index += f
if(index == 0):
f += 1
continue
if(news[index - 1] != 'u'):
f += 1
continue
changeindex = index - 1
while(news[changeindex] == 'u' and changeindex >= 0):
changeindex -= 1
changeindex += 1
news[index], news[changeindex] = news[changeindex], news[index]
f += 1
return ''.join(news)
n = int(input())
g = set()
for i in range(n):
s = input()
s = rev(s)
#print("rev", s)
s = transform(s)
#print("trans", s)
g.add(s)
print(len(g))
``` | instruction | 0 | 78,827 | 6 | 157,654 |
No | output | 1 | 78,827 | 6 | 157,655 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are some ambiguities when one writes Berland names with the letters of the Latin alphabet.
For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name.
The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name.
There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account?
Formally, we assume that two words denote the same name, if using the replacements "u" <image> "oo" and "h" <image> "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements.
For example, the following pairs of words denote the same name:
* "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper" <image> "kuuper" and "kuooper" <image> "kuuper".
* "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun" <image> "khoon" and "kkkhoon" <image> "kkhoon" <image> "khoon".
For a given list of words, find the minimal number of groups where the words in each group denote the same name.
Input
The first line contains integer number n (2 β€ n β€ 400) β number of the words in the list.
The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive.
Output
Print the minimal number of groups where the words in each group denote the same name.
Examples
Input
10
mihail
oolyana
kooooper
hoon
ulyana
koouper
mikhail
khun
kuooper
kkkhoon
Output
4
Input
9
hariton
hkariton
buoi
kkkhariton
boooi
bui
khariton
boui
boi
Output
5
Input
2
alex
alex
Output
1
Note
There are four groups of words in the first example. Words in each group denote same name:
1. "mihail", "mikhail"
2. "oolyana", "ulyana"
3. "kooooper", "koouper"
4. "hoon", "khun", "kkkhoon"
There are five groups of words in the second example. Words in each group denote same name:
1. "hariton", "kkkhariton", "khariton"
2. "hkariton"
3. "buoi", "boooi", "boui"
4. "bui"
5. "boi"
In the third example the words are equal, so they denote the same name.
Submitted Solution:
```
n=int(input())
a=[]
for _ in range(n):
s=input()
l=list(s)
d=""
l.reverse()
i=0
while i<len(l)-1:
if i<n-1:
if l[i]=='h' and l[i+1]=='k':
d+='h'
i+=1
while(i<len(l) and l[i]=='k'):
i+=1
i-=1
elif l[i]=="u":
d+="oo"
else:
d+=l[i]
i+=1
if len(d)>1:
if d[-1]=="h" and l[-1]=="k":
continue
if l[-1]=="u":
d+="oo"
else:
d+=l[-1]
else:
if l[-1]=="u":
d+="oo"
else:
d+=l[-1]
#print(d)
a.append(d)
for i in range(len(a)):
if len(a[i])==a[i].count('o') and len(a[i])%2==0:
a[i]='00'
print(len(set(a)))
``` | instruction | 0 | 78,828 | 6 | 157,656 |
No | output | 1 | 78,828 | 6 | 157,657 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are some ambiguities when one writes Berland names with the letters of the Latin alphabet.
For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name.
The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name.
There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account?
Formally, we assume that two words denote the same name, if using the replacements "u" <image> "oo" and "h" <image> "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements.
For example, the following pairs of words denote the same name:
* "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper" <image> "kuuper" and "kuooper" <image> "kuuper".
* "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun" <image> "khoon" and "kkkhoon" <image> "kkhoon" <image> "khoon".
For a given list of words, find the minimal number of groups where the words in each group denote the same name.
Input
The first line contains integer number n (2 β€ n β€ 400) β number of the words in the list.
The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive.
Output
Print the minimal number of groups where the words in each group denote the same name.
Examples
Input
10
mihail
oolyana
kooooper
hoon
ulyana
koouper
mikhail
khun
kuooper
kkkhoon
Output
4
Input
9
hariton
hkariton
buoi
kkkhariton
boooi
bui
khariton
boui
boi
Output
5
Input
2
alex
alex
Output
1
Note
There are four groups of words in the first example. Words in each group denote same name:
1. "mihail", "mikhail"
2. "oolyana", "ulyana"
3. "kooooper", "koouper"
4. "hoon", "khun", "kkkhoon"
There are five groups of words in the second example. Words in each group denote same name:
1. "hariton", "kkkhariton", "khariton"
2. "hkariton"
3. "buoi", "boooi", "boui"
4. "bui"
5. "boi"
In the third example the words are equal, so they denote the same name.
Submitted Solution:
```
n=int(input())
b=[]
for i in range(n):
t=input()
b.append(t)
ans=0
for i in range(n):
for j in range(i+1,n):
te=b[j].replace('oo','u')
te1=b[j].replace('u','oo')
if(b[i]==te or b[i]==te1):
ans=ans+1
else:
te=b[j].replace('kh','h')
te1=b[j].replace('h','kh')
if(b[i]==te or b[i]==te1):
ans=ans+1
print(ans)
``` | instruction | 0 | 78,829 | 6 | 157,658 |
No | output | 1 | 78,829 | 6 | 157,659 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a matrix of size n Γ n filled with lowercase English letters. You can change no more than k letters in this matrix.
Consider all paths from the upper left corner to the lower right corner that move from a cell to its neighboring cell to the right or down. Each path is associated with the string that is formed by all the letters in the cells the path visits. Thus, the length of each string is 2n - 1.
Find the lexicographically smallest string that can be associated with a path after changing letters in at most k cells of the matrix.
A string a is lexicographically smaller than a string b, if the first different letter in a and b is smaller in a.
Input
The first line contains two integers n and k (1 β€ n β€ 2000, 0 β€ k β€ n^2) β the size of the matrix and the number of letters you can change.
Each of the next n lines contains a string of n lowercase English letters denoting one row of the matrix.
Output
Output the lexicographically smallest string that can be associated with some valid path after changing no more than k letters in the matrix.
Examples
Input
4 2
abcd
bcde
bcad
bcde
Output
aaabcde
Input
5 3
bwwwz
hrhdh
sepsp
sqfaf
ajbvw
Output
aaaepfafw
Input
7 6
ypnxnnp
pnxonpm
nxanpou
xnnpmud
nhtdudu
npmuduh
pmutsnz
Output
aaaaaaadudsnz
Note
In the first sample test case it is possible to change letters 'b' in cells (2, 1) and (3, 1) to 'a', then the minimum path contains cells (1, 1), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3), (4, 4). The first coordinate corresponds to the row and the second coordinate corresponds to the column. | instruction | 0 | 79,126 | 6 | 158,252 |
Tags: greedy
Correct Solution:
```
from array import array
inf = (1 << 30)
def main():
(n,k) = [int(x) for x in input().split(' ')]
Matrix = []
for i in range(n):
Matrix.append(array('b',[ord(x) for x in input()]))
dp = [array('l', [inf for j in range(n)]) for i in range(n)]
direct = [[ord('d') for j in range(n)] for i in range(n)]
opt = ""
for s in range (2 * n - 1):
opchar = chr(ord('z') + 1)
positions = []
for i in range(0, s+1):
j = s - i;
if j < n and i < n:
if(i > 0 and j > 0):
if(dp[i-1][j] < dp[i][j-1]):
dp[i][j] = dp[i-1][j]
direct[i][j] = 'l'
else:
dp[i][j] = dp[i][j-1]
direct[i][j] = 'd'
elif i > 0:
dp[i][j] = dp[i-1][j]
direct[i][j] = 'l'
elif j > 0:
dp[i][j] = dp[i][j-1]
direct[i][j] = 'd'
else:
dp[i][j] = 0
direct[i][j] = 'e'
if(dp[i][j] < k and Matrix[i][j] is not ord('a')):
dp[i][j]+=1
Matrix[i][j] = ord('a')
if(Matrix[i][j] < ord(opchar) and dp[i][j] <= k):
opchar = chr(Matrix[i][j])
for i in range(0, s+1):
j = s - i;
if j < n and i < n:
if(Matrix[i][j] is not ord(opchar)):
dp[i][j] = inf
ans = ""
a,b = (n-1,n-1)
while(direct[a][b] is not 'e'):
ans += chr(Matrix[a][b])
if(direct[a][b] is 'l'):
a-=1
else:
b-=1
ans += chr(Matrix[0][0])
print(ans[::-1])
main()
``` | output | 1 | 79,126 | 6 | 158,253 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a matrix of size n Γ n filled with lowercase English letters. You can change no more than k letters in this matrix.
Consider all paths from the upper left corner to the lower right corner that move from a cell to its neighboring cell to the right or down. Each path is associated with the string that is formed by all the letters in the cells the path visits. Thus, the length of each string is 2n - 1.
Find the lexicographically smallest string that can be associated with a path after changing letters in at most k cells of the matrix.
A string a is lexicographically smaller than a string b, if the first different letter in a and b is smaller in a.
Input
The first line contains two integers n and k (1 β€ n β€ 2000, 0 β€ k β€ n^2) β the size of the matrix and the number of letters you can change.
Each of the next n lines contains a string of n lowercase English letters denoting one row of the matrix.
Output
Output the lexicographically smallest string that can be associated with some valid path after changing no more than k letters in the matrix.
Examples
Input
4 2
abcd
bcde
bcad
bcde
Output
aaabcde
Input
5 3
bwwwz
hrhdh
sepsp
sqfaf
ajbvw
Output
aaaepfafw
Input
7 6
ypnxnnp
pnxonpm
nxanpou
xnnpmud
nhtdudu
npmuduh
pmutsnz
Output
aaaaaaadudsnz
Note
In the first sample test case it is possible to change letters 'b' in cells (2, 1) and (3, 1) to 'a', then the minimum path contains cells (1, 1), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3), (4, 4). The first coordinate corresponds to the row and the second coordinate corresponds to the column. | instruction | 0 | 79,127 | 6 | 158,254 |
Tags: greedy
Correct Solution:
```
def main():
n,k=readIntArr()
arr=[]
for _ in range(n):
arr.append(input())
#use all ks to change characters to a
maxAinPath=[[0 for _ in range(n)] for __ in range(n)]
for i in range(n):
for j in range(n):
if i>0:
maxAinPath[i][j]=max(maxAinPath[i][j],maxAinPath[i-1][j])
if j>0:
maxAinPath[i][j]=max(maxAinPath[i][j],maxAinPath[i][j-1])
if arr[i][j]=='a':
maxAinPath[i][j]+=1
if maxAinPath[n-1][n-1]+k>=2*n-1: #all 'a's
print('a'*(2*n-1))
else:
#find all (i,j) where 1+i+j==maxAinPath[i][j]+k meaning everything in path is 'a's
#of these, only consider the paths with largest i+j
potential=[] #[i,j]
for i in range(n):
for j in range(n):
if 1+i+j==maxAinPath[i][j]+k:
potential.append([i,j])
#potential might be empty
maxLen=-inf
for i,j in potential:
maxLen=max(maxLen,i+j)
if maxLen==-inf:
ans=[]
else:
ans=['a']*(maxLen+1)
bfs=[] #(i,j)
for i,j in potential:
if i+j==maxLen:
bfs.append((i,j))
if len(bfs)==0: #because potential was empty
bfs.append((0,0))
ans.append(arr[0][0])
while len(ans)<2*n-1:
bfs2=set() #(i,j)
for i,j in bfs:
if i+1<n:
bfs2.add((i+1,j))
if j+1<n:
bfs2.add((i,j+1))
# print('ans:{} bfs:{} bfs2{}'.format(ans,bfs,bfs2))###
minLetter='z'
for i,j in bfs2:
letter=arr[i][j]
minLetter=min(minLetter,letter)
ans.append(minLetter)
bfs=[]
for i,j in bfs2:
if arr[i][j]==minLetter:
bfs.append((i,j))
assert len(bfs)>0
print(''.join(ans))
return
#import sys
#input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
import sys
input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
inf=float('inf')
MOD=10**9+7
main()
``` | output | 1 | 79,127 | 6 | 158,255 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a matrix of size n Γ n filled with lowercase English letters. You can change no more than k letters in this matrix.
Consider all paths from the upper left corner to the lower right corner that move from a cell to its neighboring cell to the right or down. Each path is associated with the string that is formed by all the letters in the cells the path visits. Thus, the length of each string is 2n - 1.
Find the lexicographically smallest string that can be associated with a path after changing letters in at most k cells of the matrix.
A string a is lexicographically smaller than a string b, if the first different letter in a and b is smaller in a.
Input
The first line contains two integers n and k (1 β€ n β€ 2000, 0 β€ k β€ n^2) β the size of the matrix and the number of letters you can change.
Each of the next n lines contains a string of n lowercase English letters denoting one row of the matrix.
Output
Output the lexicographically smallest string that can be associated with some valid path after changing no more than k letters in the matrix.
Examples
Input
4 2
abcd
bcde
bcad
bcde
Output
aaabcde
Input
5 3
bwwwz
hrhdh
sepsp
sqfaf
ajbvw
Output
aaaepfafw
Input
7 6
ypnxnnp
pnxonpm
nxanpou
xnnpmud
nhtdudu
npmuduh
pmutsnz
Output
aaaaaaadudsnz
Note
In the first sample test case it is possible to change letters 'b' in cells (2, 1) and (3, 1) to 'a', then the minimum path contains cells (1, 1), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3), (4, 4). The first coordinate corresponds to the row and the second coordinate corresponds to the column. | instruction | 0 | 79,128 | 6 | 158,256 |
Tags: greedy
Correct Solution:
```
def solve(m, matrix, good, n):
c = 'z'
for x in range(n):
y = m - x
if y < 0 or y >= n: continue
if not good[x][y]: continue
if x < n - 1: c = min(c, matrix[x + 1][y])
if y < n - 1: c = min(c, matrix[x][y + 1])
for x in range(n):
y = m - x
if y < 0 or y >= n: continue
if not good[x][y]: continue
if x < n - 1 and matrix[x + 1][y] == c: good[x+1][y] = 1
if y < n - 1 and matrix[x][y + 1] == c: good[x][y + 1] = 1
return c
def main():
n, k = map(int, input().split())
matrix = []
for i in range(n):
s = list(input())
matrix.append(s)
dp = [[0 for i in range(n)] for j in range(n)]
good = [[0 for i in range(n)] for j in range(n)]
dp[0][0] = 0 if matrix[0][0] == 'a' else 1
for i in range(1, n):
dp[0][i] = dp[0][i - 1]
if matrix[0][i] != 'a':
dp[0][i] += 1
dp[i][0] = dp[i - 1][0]
if matrix[i][0] != 'a':
dp[i][0] += 1
for i in range(1, n):
for j in range(1, n):
dp[i][j] = min(dp[i-1][j], dp[i][j-1])
if matrix[i][j] != 'a':
dp[i][j] += 1
m = -1
for i in range(n):
for j in range(n):
if dp[i][j] <= k:
m = max(m, i + j)
if m == -1:
print(matrix[0][0], end = '')
m = 0
good[0][0] = 1
else:
for i in range(m + 1):
print('a', end = '')
for i in range(n):
y = m - i
if y < 0 or y >= n:
continue
if dp[i][y] <= k:
good[i][y] = 1
while m < 2*n - 2:
res = solve(m, matrix, good, n)
print(res, end = '')
m += 1
if __name__=="__main__":
main()
``` | output | 1 | 79,128 | 6 | 158,257 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a matrix of size n Γ n filled with lowercase English letters. You can change no more than k letters in this matrix.
Consider all paths from the upper left corner to the lower right corner that move from a cell to its neighboring cell to the right or down. Each path is associated with the string that is formed by all the letters in the cells the path visits. Thus, the length of each string is 2n - 1.
Find the lexicographically smallest string that can be associated with a path after changing letters in at most k cells of the matrix.
A string a is lexicographically smaller than a string b, if the first different letter in a and b is smaller in a.
Input
The first line contains two integers n and k (1 β€ n β€ 2000, 0 β€ k β€ n^2) β the size of the matrix and the number of letters you can change.
Each of the next n lines contains a string of n lowercase English letters denoting one row of the matrix.
Output
Output the lexicographically smallest string that can be associated with some valid path after changing no more than k letters in the matrix.
Examples
Input
4 2
abcd
bcde
bcad
bcde
Output
aaabcde
Input
5 3
bwwwz
hrhdh
sepsp
sqfaf
ajbvw
Output
aaaepfafw
Input
7 6
ypnxnnp
pnxonpm
nxanpou
xnnpmud
nhtdudu
npmuduh
pmutsnz
Output
aaaaaaadudsnz
Note
In the first sample test case it is possible to change letters 'b' in cells (2, 1) and (3, 1) to 'a', then the minimum path contains cells (1, 1), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3), (4, 4). The first coordinate corresponds to the row and the second coordinate corresponds to the column. | instruction | 0 | 79,129 | 6 | 158,258 |
Tags: greedy
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
# ------------------------------
# f = open('./input.txt')
# sys.stdin = f
def main():
n, k = RL()
arr = [input() for _ in range(n)]
dp = [[INF]*(n) for _ in range(n)]
q = deque()
pre = 0
for i in range(n):
for j in range(n):
if i==0 and j==0:
dp[0][0] = 1 if arr[0][0] != 'a' else 0
elif i==0: dp[0][j] = dp[0][j-1] + (1 if arr[0][j]!='a' else 0 )
elif j==0: dp[i][0] = dp[i-1][0] + (1 if arr[i][0]!='a' else 0)
else: dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + (1 if arr[i][j]!='a' else 0)
if dp[i][j]<=k:
pre = max(pre, i+j+1)
suf = 2*n-1-pre
res = ['a']*pre + ['z']*suf
vis = [[0]*n for _ in range(n)]
q = []
for i in range(n):
for j in range(n):
if dp[i][j]==k and i+j+1==pre:
if i+1<n and vis[i+1][j]==0: q.append((i+1, j)); vis[i+1][j] = 1
if j+1<n and vis[i][j+1]==0: q.append((i, j+1)); vis[i][j+1] = 1
q.sort(key=lambda a: arr[a[0]][a[1]])
if not q: q.append((0, 0))
for i in range(pre, len(res)):
newq = []
res[i] = arr[q[0][0]][q[0][1]]
for j in range(len(q)):
now = arr[q[j][0]][q[j][1]]
if now!=res[i]: break
for nx, ny in [[1, 0], [0, 1]]:
xx, yy = nx+q[j][0], ny+q[j][1]
if xx<n and yy<n and vis[xx][yy]==0:
vis[xx][yy] = 1
while newq and arr[xx][yy]<arr[newq[-1][0]][newq[-1][1]]: newq.pop()
if not newq or arr[xx][yy]==arr[newq[-1][0]][newq[-1][1]]:
newq.append((xx, yy))
q = newq
print("".join(res))
if __name__ == "__main__":
main()
``` | output | 1 | 79,129 | 6 | 158,259 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a matrix of size n Γ n filled with lowercase English letters. You can change no more than k letters in this matrix.
Consider all paths from the upper left corner to the lower right corner that move from a cell to its neighboring cell to the right or down. Each path is associated with the string that is formed by all the letters in the cells the path visits. Thus, the length of each string is 2n - 1.
Find the lexicographically smallest string that can be associated with a path after changing letters in at most k cells of the matrix.
A string a is lexicographically smaller than a string b, if the first different letter in a and b is smaller in a.
Input
The first line contains two integers n and k (1 β€ n β€ 2000, 0 β€ k β€ n^2) β the size of the matrix and the number of letters you can change.
Each of the next n lines contains a string of n lowercase English letters denoting one row of the matrix.
Output
Output the lexicographically smallest string that can be associated with some valid path after changing no more than k letters in the matrix.
Examples
Input
4 2
abcd
bcde
bcad
bcde
Output
aaabcde
Input
5 3
bwwwz
hrhdh
sepsp
sqfaf
ajbvw
Output
aaaepfafw
Input
7 6
ypnxnnp
pnxonpm
nxanpou
xnnpmud
nhtdudu
npmuduh
pmutsnz
Output
aaaaaaadudsnz
Note
In the first sample test case it is possible to change letters 'b' in cells (2, 1) and (3, 1) to 'a', then the minimum path contains cells (1, 1), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3), (4, 4). The first coordinate corresponds to the row and the second coordinate corresponds to the column. | instruction | 0 | 79,130 | 6 | 158,260 |
Tags: greedy
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
# ------------------------------
# f = open('./input.txt')
# sys.stdin = f
def main():
n, k = RL()
arr = [input() for _ in range(n)]
dp = [[INF]*(n) for _ in range(n)]
q = deque()
pre = 0
for i in range(n):
for j in range(n):
if i==0 and j==0:
dp[0][0] = 1 if arr[0][0] != 'a' else 0
elif i==0: dp[0][j] = dp[0][j-1] + (1 if arr[0][j]!='a' else 0 )
elif j==0: dp[i][0] = dp[i-1][0] + (1 if arr[i][0]!='a' else 0)
else: dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + (1 if arr[i][j]!='a' else 0)
if dp[i][j]<=k:
pre = max(pre, i+j+1)
suf = 2*n-1-pre
res = ['a']*pre + ['z']*suf
vis = [[0]*n for _ in range(n)]
q = []
for i in range(n):
for j in range(n):
if dp[i][j]==k and i+j+1==pre:
if i+1<n and vis[i+1][j]==0: q.append((i+1, j)); vis[i+1][j] = 1
if j+1<n and vis[i][j+1]==0: q.append((i, j+1)); vis[i][j+1] = 1
q.sort(key=lambda a: arr[a[0]][a[1]])
if not q: q.append((0, 0))
for i in range(pre, len(res)):
newq = []
res[i] = arr[q[0][0]][q[0][1]]
for j in range(len(q)):
now = arr[q[j][0]][q[j][1]]
if now!=res[i]: break
for nx, ny in [[1, 0], [0, 1]]:
xx, yy = nx+q[j][0], ny+q[j][1]
if xx<n and yy<n and vis[xx][yy]==0:
vis[xx][yy] = 1
if newq:
if arr[xx][yy] > arr[newq[-1][0]][newq[-1][1]]: continue
elif arr[xx][yy] < arr[newq[-1][0]][newq[-1][1]]: newq = []
newq.append((xx, yy))
q = newq
print("".join(res))
if __name__ == "__main__":
main()
``` | output | 1 | 79,130 | 6 | 158,261 |
Provide tags and a correct Python 3 solution for this coding contest problem.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b. | instruction | 0 | 79,294 | 6 | 158,588 |
Tags: implementation
Correct Solution:
```
s = input()
A = []
A.append(0)
for i in s:
codigo = ord(i)
sCodigo = bin(codigo).lstrip("0b")
sCodigo = sCodigo.rjust(8, '0')
sCodigo = sCodigo[::-1]
x = int(sCodigo, 2)
A.append(x)
size = len(s)
for i in range(0, size):
print((A[i] - A[i + 1]) % 256)
``` | output | 1 | 79,294 | 6 | 158,589 |
Provide tags and a correct Python 3 solution for this coding contest problem.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b. | instruction | 0 | 79,295 | 6 | 158,590 |
Tags: implementation
Correct Solution:
```
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now----------------------------------------------------
def decimalToBinary(n):
return bin(n).replace("0b", "")
s=input()
n=len(s)
p=0
for i in range (n):
c=ord(s[i])
b=decimalToBinary(c)
#print(b)
l=len(b)
x=max(0,8-l)
b="0"*x+b
b=b[::-1]
#print(b)
s1=int(b,2)
r=(p-s1)%256
print(r)
p=s1
``` | output | 1 | 79,295 | 6 | 158,591 |
Provide tags and a correct Python 3 solution for this coding contest problem.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b. | instruction | 0 | 79,296 | 6 | 158,592 |
Tags: implementation
Correct Solution:
```
t = input()
f=[0]
for j in range(len(t)):
a=bin(ord(t[j]))[2:]
if len(a)<8:
a = '0'*(8-len(a))+a
b=int(a[::-1],2)
x=(f[-1]-b)%256
print(x)
f.append(b)
``` | output | 1 | 79,296 | 6 | 158,593 |
Provide tags and a correct Python 3 solution for this coding contest problem.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b. | instruction | 0 | 79,297 | 6 | 158,594 |
Tags: implementation
Correct Solution:
```
old=0
for c in input():
s=bin(ord(c))[2:][::-1]
now=int(s+"0"*(8-len(s)),2)
print((old-now)%256)
old=now
``` | output | 1 | 79,297 | 6 | 158,595 |
Provide tags and a correct Python 3 solution for this coding contest problem.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b. | instruction | 0 | 79,298 | 6 | 158,596 |
Tags: implementation
Correct Solution:
```
def reverse(b):
c = ""
for i in range(1,len(b)+1):
c += b[-i]
return c
p = input()
c = 0
for i in p:
pp = str(bin(ord(i))[2:])
for i in range(8-len(pp)):
pp = "0" + pp
k = int(reverse(pp),2)
print((c-k)%256)
c = k
``` | output | 1 | 79,298 | 6 | 158,597 |
Provide tags and a correct Python 3 solution for this coding contest problem.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b. | instruction | 0 | 79,299 | 6 | 158,598 |
Tags: implementation
Correct Solution:
```
text = str(input())
ans = list()
for j in range(len(text)):
ch_code_b = bin(ord(text[j]))
l_ch_code_b = list(ch_code_b)
second_step = int(0)
while len(l_ch_code_b) < 10:
l_ch_code_b.insert(2, 0)
for i in range(2, len(l_ch_code_b)):
second_step += int(l_ch_code_b[i]) * pow(2, i - 2)
if j == 0:
first_step = 0
else:
ch_code_b = bin(ord(text[j - 1]))
l_ch_code_b = list(ch_code_b)
first_step = int(0)
while len(l_ch_code_b) < 10:
l_ch_code_b.insert(2, 0)
for i in range(2, len(l_ch_code_b)):
first_step += int(l_ch_code_b[i]) * pow(2, i - 2)
ans.append((first_step - second_step) % 256)
for i in ans:
print(i)
``` | output | 1 | 79,299 | 6 | 158,599 |
Provide tags and a correct Python 3 solution for this coding contest problem.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b. | instruction | 0 | 79,300 | 6 | 158,600 |
Tags: implementation
Correct Solution:
```
def r(n):
v = 0
for i in range(8):
n, v = n >> 1, (v << 1) + (n & 1)
return v
s = input()
for i in range(len(s)):
print((r(ord(s[i - 1]) if i > 0 else 0) - r(ord(s[i]))) % 256)
``` | output | 1 | 79,300 | 6 | 158,601 |
Provide tags and a correct Python 3 solution for this coding contest problem.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b. | instruction | 0 | 79,301 | 6 | 158,602 |
Tags: implementation
Correct Solution:
```
def obin(a):
a = ord(a)
text = bin(a)[bin(a).find('1'):]
ntext = '0'*(8-len(text))+text
return ntext
def rev(a):
return a[-1::-1]
def revascii(char):
return int(rev(obin(char)),base=2)
text = input()
for i in range(len(text)):
if i == 0:
lastele = 0
else:
lastele = revascii(text[i-1])
print((lastele-revascii(text[i]))%256)
``` | output | 1 | 79,301 | 6 | 158,603 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b.
Submitted Solution:
```
'''''''''''
Author : code_marshal
Method : strings
'''''''''''
x, f = input(), 0
for i in x:
h = bin(ord(i))[2:]; h = ('0' * (8 - len(h)) + h)[::-1]
print ((f - int(h, 2)) % 256)
f = int(h, 2)
``` | instruction | 0 | 79,302 | 6 | 158,604 |
Yes | output | 1 | 79,302 | 6 | 158,605 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b.
Submitted Solution:
```
#codeforces_132A
line = input()
last = '0'*8
ci = '' #ith char bin representation
for e in line:
ci = bin(ord(e))[2:]
ci = '0'*(8-len(ci)) + ci
print((int(last[::-1],2)-int(ci[::-1],2))%256)
last = bin(ord(e))[2:]
last = '0'*(8-len(last))+ last
``` | instruction | 0 | 79,303 | 6 | 158,606 |
Yes | output | 1 | 79,303 | 6 | 158,607 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b.
Submitted Solution:
```
def btd(n):
y=1
r=0
while(n):
s=n%10
r=r+s*y
n=n//10
y=y*2
return r
n=input()
p=list(n)
v=0
for i in p:
s=ord(i)
q=bin(s)
q=q.replace("0b","")
q=q[::-1]
t=len(q)
q=str(q)
q=int(q)
if t<8:
t=8-t
q=q*(10**t)
w=btd(q)
print((v-w)%256)
v=w
``` | instruction | 0 | 79,304 | 6 | 158,608 |
Yes | output | 1 | 79,304 | 6 | 158,609 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b.
Submitted Solution:
```
n = input()
prev = 0
for i in n:
asci = ord(i)
binary = format(asci, '#010b')[2:][::-1]
num = int(binary, 2)
print((prev-num) % 256)
prev = num
``` | instruction | 0 | 79,305 | 6 | 158,610 |
Yes | output | 1 | 79,305 | 6 | 158,611 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b.
Submitted Solution:
```
s = list(input())
prev = 0
for i in s:
n = '0' + bin(ord(i))[2:]
n = n[::-1]
d = int(n, 2)
print((prev - d) % 256)
prev = d
``` | instruction | 0 | 79,306 | 6 | 158,612 |
No | output | 1 | 79,306 | 6 | 158,613 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b.
Submitted Solution:
```
st = str(input()).replace("\n","")
n = 0
s = []
for i in st:
t = int(bin(ord(i)).replace("b","")[::-1],2)
s.append(t)
for i in range(len(s)):
if i==0: print((0-s[i]+256)%256)
else: print((s[i-1]-s[i]+256)%256)
``` | instruction | 0 | 79,307 | 6 | 158,614 |
No | output | 1 | 79,307 | 6 | 158,615 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.
The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:
1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.
2. The i-th element of the array is subtracted from the result of the previous step modulo 256.
3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.
You are given the text printed using this method. Restore the array used to produce this text.
Input
The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.
Output
Output the initial array, which was used to produce text, one integer per line.
Examples
Input
Hello, World!
Output
238
108
112
0
64
194
48
26
244
168
24
16
162
Note
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b.
Submitted Solution:
```
a = input()
b = 0
for i in a:
res = 0
h = ord(i)
j = ''
while h > 0:
j = str(h%2) + j
h = h//2
j = '0'+j
j = j[::-1]
l = len(j)-1
for k in range(l+1):
res += (2**l)*int(j[k])
l -= 1
print((b - res) % 256)
b = res
``` | instruction | 0 | 79,308 | 6 | 158,616 |
No | output | 1 | 79,308 | 6 | 158,617 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's consider one interesting word game. In this game you should transform one word into another through special operations.
Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword".
You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start.
Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 β€ i β€ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β a holds.
Input
The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters.
The third line contains integer k (0 β€ k β€ 105) β the required number of operations.
Output
Print a single number β the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7).
Examples
Input
ab
ab
2
Output
1
Input
ababab
ababab
1
Output
2
Input
ab
ba
2
Output
0
Note
The sought way in the first sample is:
ab β a|b β ba β b|a β ab
In the second sample the two sought ways are:
* ababab β abab|ab β ababab
* ababab β ab|abab β ababab | instruction | 0 | 79,383 | 6 | 158,766 |
Tags: dp
Correct Solution:
```
class Solution():
def number_or_ways(start, end, moves):
p = 10**9+7
num_rots = 0
for i in range(len(start)):
rot = start[i:]+start[0:i]
if rot == end:
num_rots += 1
dp = [[0 for i in range(2)] for j in range(moves+1)]
dp[0][0], dp[0][1] = 1, 0
for i in range(1, moves+1):
dp[i][0] = (((num_rots-1)*dp[i-1][0])%p + ((len(start)-num_rots)*dp[i-1][1])%p)%p
dp[i][1] = ((num_rots*dp[i-1][0])%p + ((len(start)-1-num_rots)*dp[i-1][1])%p)%p
if start == end:
return dp[moves][0]
else:
return dp[moves][1]
start = input().strip()
end = input().strip()
moves = int(input())
print(Solution.number_or_ways(start, end, moves))
``` | output | 1 | 79,383 | 6 | 158,767 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's consider one interesting word game. In this game you should transform one word into another through special operations.
Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword".
You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start.
Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 β€ i β€ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β a holds.
Input
The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters.
The third line contains integer k (0 β€ k β€ 105) β the required number of operations.
Output
Print a single number β the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7).
Examples
Input
ab
ab
2
Output
1
Input
ababab
ababab
1
Output
2
Input
ab
ba
2
Output
0
Note
The sought way in the first sample is:
ab β a|b β ba β b|a β ab
In the second sample the two sought ways are:
* ababab β abab|ab β ababab
* ababab β ab|abab β ababab | instruction | 0 | 79,384 | 6 | 158,768 |
Tags: dp
Correct Solution:
```
MOD = int(1e9) + 7
if __name__ == "__main__":
a, b, k = input(), input(), int(input())
x, y = (1, 0) if a == b else (0, 1)
n = len(b)
b += b
same = sum(a == b[i: i + n] for i in range(n))
diff = n - same
for _ in range(k):
x, y = ((x * (same - 1)) % MOD + (y * same) % MOD) % MOD, ((x * (diff)) % MOD + (y * (diff - 1)) % MOD) % MOD
print(x)
``` | output | 1 | 79,384 | 6 | 158,769 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's consider one interesting word game. In this game you should transform one word into another through special operations.
Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword".
You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start.
Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 β€ i β€ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β a holds.
Input
The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters.
The third line contains integer k (0 β€ k β€ 105) β the required number of operations.
Output
Print a single number β the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7).
Examples
Input
ab
ab
2
Output
1
Input
ababab
ababab
1
Output
2
Input
ab
ba
2
Output
0
Note
The sought way in the first sample is:
ab β a|b β ba β b|a β ab
In the second sample the two sought ways are:
* ababab β abab|ab β ababab
* ababab β ab|abab β ababab | instruction | 0 | 79,385 | 6 | 158,770 |
Tags: dp
Correct Solution:
```
def WordCut():
start = input()
end = input()
k = int(input())
n=len(start)
dpA,dpB = (start==end),(start!=end)
end+=end
A=sum(start==end[i:i+n] for i in range(n))
B = n- A
M = 10**9+7
for _ in range(k):
dpA,dpB=(dpA*(A-1)+dpB*A)%M,(dpA*B+dpB*(B-1))%M
return int(dpA)
print(WordCut())
``` | output | 1 | 79,385 | 6 | 158,771 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's consider one interesting word game. In this game you should transform one word into another through special operations.
Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword".
You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start.
Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 β€ i β€ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β a holds.
Input
The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters.
The third line contains integer k (0 β€ k β€ 105) β the required number of operations.
Output
Print a single number β the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7).
Examples
Input
ab
ab
2
Output
1
Input
ababab
ababab
1
Output
2
Input
ab
ba
2
Output
0
Note
The sought way in the first sample is:
ab β a|b β ba β b|a β ab
In the second sample the two sought ways are:
* ababab β abab|ab β ababab
* ababab β ab|abab β ababab | instruction | 0 | 79,386 | 6 | 158,772 |
Tags: dp
Correct Solution:
```
start, end, k = input(), input(), int(input())
dp = [[start == end for _ in range(k + 1)], [start != end for _ in range(k + 1)]]
mod = int(1e9 + 7)
same = sum(end == (start[i: len(start)] + start[0: i]) for i in range(len(start)))
diff = len(start) - same
for i in range(1, k + 1):
dp[0][i] = (dp[0][i - 1] * (same - 1) + dp[1][i - 1] * same) % mod
dp[1][i] = (dp[0][i - 1] * diff + dp[1][i - 1] * (diff - 1)) % mod
print(int(dp[0][k]))
``` | output | 1 | 79,386 | 6 | 158,773 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's consider one interesting word game. In this game you should transform one word into another through special operations.
Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword".
You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start.
Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 β€ i β€ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β a holds.
Input
The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters.
The third line contains integer k (0 β€ k β€ 105) β the required number of operations.
Output
Print a single number β the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7).
Examples
Input
ab
ab
2
Output
1
Input
ababab
ababab
1
Output
2
Input
ab
ba
2
Output
0
Note
The sought way in the first sample is:
ab β a|b β ba β b|a β ab
In the second sample the two sought ways are:
* ababab β abab|ab β ababab
* ababab β ab|abab β ababab | instruction | 0 | 79,387 | 6 | 158,774 |
Tags: dp
Correct Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import gcd, ceil
def prod(a, mod=10**9+7):
ans = 1
for each in a:
ans = (ans * each) % mod
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
from collections import deque
for _ in range(int(input()) if not True else 1):
#n = int(input())
#n, k = map(int, input().split())
#a, b = map(int, input().split())
#c, d = map(int, input().split())
#a = list(map(int, input().split()))
#b = list(map(int, input().split()))
s1 = deque(k for k in input())
s2 = deque(k for k in input())
n = len(s1)
k = int(input())
if k == 0:
print(int(s1==s2))
quit()
mod = 10**9 + 7
n1pow = [1]
for i in range(696969):
n1pow += [(n1pow[-1]*(n-1)) % mod]
ans0 = 0
for i in range(1, k):
ans0 = (n1pow[i] - ans0) % mod
ans1 = 1
for i in range(1, k):
ans1 = (n1pow[i] - ans1) % mod
#print(ans0, ans1)
total = 0
for t in range(n):
if s1 == s2:
total += ans1 if t else ans0
s1.appendleft(s1.pop())
print(total % mod)
``` | output | 1 | 79,387 | 6 | 158,775 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's consider one interesting word game. In this game you should transform one word into another through special operations.
Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword".
You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start.
Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 β€ i β€ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β a holds.
Input
The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters.
The third line contains integer k (0 β€ k β€ 105) β the required number of operations.
Output
Print a single number β the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7).
Examples
Input
ab
ab
2
Output
1
Input
ababab
ababab
1
Output
2
Input
ab
ba
2
Output
0
Note
The sought way in the first sample is:
ab β a|b β ba β b|a β ab
In the second sample the two sought ways are:
* ababab β abab|ab β ababab
* ababab β ab|abab β ababab | instruction | 0 | 79,388 | 6 | 158,776 |
Tags: dp
Correct Solution:
```
start,end,k=input(),input(),int(input())
n,mod=len(end),10**9+7
dp=[1,0]
psum=1
for i in range(k):
dp[0]=psum-dp[0]
dp[1]=psum-dp[1]
psum=(dp[0]+((n-1)*dp[1])%mod)%mod
ans=0
for i in range(n):
if start[i:]+start[:i]==end:
if i==0:ans+=dp[0]
else:ans+=dp[1]
print(ans%mod)
``` | output | 1 | 79,388 | 6 | 158,777 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's consider one interesting word game. In this game you should transform one word into another through special operations.
Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword".
You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start.
Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 β€ i β€ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β a holds.
Input
The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters.
The third line contains integer k (0 β€ k β€ 105) β the required number of operations.
Output
Print a single number β the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7).
Examples
Input
ab
ab
2
Output
1
Input
ababab
ababab
1
Output
2
Input
ab
ba
2
Output
0
Note
The sought way in the first sample is:
ab β a|b β ba β b|a β ab
In the second sample the two sought ways are:
* ababab β abab|ab β ababab
* ababab β ab|abab β ababab | instruction | 0 | 79,389 | 6 | 158,778 |
Tags: dp
Correct Solution:
```
MOD = int(1e9) + 7
if __name__ == "__main__":
a = input()
b = input()
k = int(input())
if(len(a) != len(b)):
print(0)
exit()
a = a + a
x = 0
y = 0
for i in range(len(a) // 2):
flag = 1
for j in range(len(b)):
if(a[j + i] != b[j]):
flag = 0
break
if(flag == 1):
x += 1
else:
y += 1
flag = 0
for i in range(len(b)):
if(a[i] != b[i]):
flag = 1
u = 1
v = 0
if(flag == 1):
v = 1
u = 0
for i in range(k):
uu = (u * (x - 1)) % MOD + (v * (x)) % MOD
vv = (u * (y)) % MOD + (v * (y - 1)) % MOD
u = uu % MOD
v = vv % MOD
print(u)
``` | output | 1 | 79,389 | 6 | 158,779 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's consider one interesting word game. In this game you should transform one word into another through special operations.
Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword".
You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start.
Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 β€ i β€ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β a holds.
Input
The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters.
The third line contains integer k (0 β€ k β€ 105) β the required number of operations.
Output
Print a single number β the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7).
Examples
Input
ab
ab
2
Output
1
Input
ababab
ababab
1
Output
2
Input
ab
ba
2
Output
0
Note
The sought way in the first sample is:
ab β a|b β ba β b|a β ab
In the second sample the two sought ways are:
* ababab β abab|ab β ababab
* ababab β ab|abab β ababab | instruction | 0 | 79,390 | 6 | 158,780 |
Tags: dp
Correct Solution:
```
# ========= /\ /| |====/|
# | / \ | | / |
# | /____\ | | / |
# | / \ | | / |
# ========= / \ ===== |/====|
# code
def main():
MOD = int(1e9 + 7)
a = input()
b = input()
n = int(input())
ca, cb = 0,0
for i in range(len(a)):
s = a[i:] + a[:i]
if s == b:
ca += 1
else:
cb += 1
if ca == 0:
print(0)
return
da = [0] * (n + 1)
db = da[:]
da[0] = 1 if a == b else 0
db[0] = 1 - da[0]
for i in range(1, n + 1):
da[i] = da[i - 1] * (ca - 1) + db[i - 1] * ca
db[i] = da[i - 1] * cb + db[i - 1] * (cb - 1)
da[i] %= MOD
db[i] %= MOD
# print(da[i], db[i], ca, cb)
print(da[n])
return
if __name__ == "__main__":
main()
``` | output | 1 | 79,390 | 6 | 158,781 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's consider one interesting word game. In this game you should transform one word into another through special operations.
Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword".
You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start.
Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 β€ i β€ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β a holds.
Input
The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters.
The third line contains integer k (0 β€ k β€ 105) β the required number of operations.
Output
Print a single number β the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7).
Examples
Input
ab
ab
2
Output
1
Input
ababab
ababab
1
Output
2
Input
ab
ba
2
Output
0
Note
The sought way in the first sample is:
ab β a|b β ba β b|a β ab
In the second sample the two sought ways are:
* ababab β abab|ab β ababab
* ababab β ab|abab β ababab
Submitted Solution:
```
from collections import deque
start = deque(input())
end = deque(input())
k = int(input())
n = len(start)
deu = 0
naoDeu = 0
for i in range(0, n):
if (start == end):
deu += 1
else:
naoDeu += 1
start.rotate(1)
dpDeu = [0] * (k + 1)
dpNaoDeu = [0] * (k + 1)
if (start == end):
dpDeu[0] = 1
dpNaoDeu[0] = 0
else:
dpDeu[0] = 0
dpNaoDeu[0] = 1
for i in range(1, k + 1):
dpDeu[i] = (dpDeu[i - 1] * (deu - 1) + dpNaoDeu[i - 1] * deu) % 1000000007
dpNaoDeu[i] = (dpDeu[i - 1] * naoDeu + dpNaoDeu[i - 1] * (naoDeu - 1)) % 1000000007
print(dpDeu[k])
``` | instruction | 0 | 79,391 | 6 | 158,782 |
Yes | output | 1 | 79,391 | 6 | 158,783 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's consider one interesting word game. In this game you should transform one word into another through special operations.
Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword".
You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start.
Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 β€ i β€ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β a holds.
Input
The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters.
The third line contains integer k (0 β€ k β€ 105) β the required number of operations.
Output
Print a single number β the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7).
Examples
Input
ab
ab
2
Output
1
Input
ababab
ababab
1
Output
2
Input
ab
ba
2
Output
0
Note
The sought way in the first sample is:
ab β a|b β ba β b|a β ab
In the second sample the two sought ways are:
* ababab β abab|ab β ababab
* ababab β ab|abab β ababab
Submitted Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import gcd, ceil
def prod(a, mod=10**9+7):
ans = 1
for each in a:
ans = (ans * each) % mod
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
from collections import deque
for _ in range(int(input()) if not True else 1):
#n = int(input())
#n, k = map(int, input().split())
#a, b = map(int, input().split())
#c, d = map(int, input().split())
#a = list(map(int, input().split()))
#b = list(map(int, input().split()))
s1 = deque(k for k in input())
s2 = deque(k for k in input())
n = len(s1)
k = int(input())
mod = 10**9 + 7
n1pow = [1]
for i in range(6969):
n1pow += [(n1pow[-1]*(n-1)) % mod]
ans0 = 0
for i in range(1, k):
ans0 = (n1pow[i] - ans0) % mod
ans1 = 1
for i in range(1, k):
ans1 = (n1pow[i] - ans1) % mod
#print(ans0, ans1)
total = 0
for t in range(n):
if s1 == s2:
total += ans1 if t else ans0
s1.appendleft(s1.pop())
print(total % mod)
``` | instruction | 0 | 79,392 | 6 | 158,784 |
No | output | 1 | 79,392 | 6 | 158,785 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's consider one interesting word game. In this game you should transform one word into another through special operations.
Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword".
You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start.
Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 β€ i β€ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β a holds.
Input
The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters.
The third line contains integer k (0 β€ k β€ 105) β the required number of operations.
Output
Print a single number β the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7).
Examples
Input
ab
ab
2
Output
1
Input
ababab
ababab
1
Output
2
Input
ab
ba
2
Output
0
Note
The sought way in the first sample is:
ab β a|b β ba β b|a β ab
In the second sample the two sought ways are:
* ababab β abab|ab β ababab
* ababab β ab|abab β ababab
Submitted Solution:
```
# ========= /\ /| |====/|
# | / \ | | / |
# | /____\ | | / |
# | / \ | | / |
# ========= / \ ===== |/====|
# code
def main():
MOD = int(1e9 + 7)
a = input()
b = input()
n = int(input())
ca, cb = 0,0
for i in range(len(a)):
s = a[i:] + a[:i]
if s == b:
ca += 1
else:
cb += 1
da = [0] * (n + 1)
db = da[:]
da[0] = 1 if a == b else 0
db[0] = 1 - da[0]
for i in range(1, n + 1):
da[i] = da[i - 1] * (ca - 1) + db[i - 1] * cb
db[i] = da[i - 1] * ca + db[i - 1] * (cb - 1)
print(da[n])
return
if __name__ == "__main__":
main()
``` | instruction | 0 | 79,393 | 6 | 158,786 |
No | output | 1 | 79,393 | 6 | 158,787 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's consider one interesting word game. In this game you should transform one word into another through special operations.
Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword".
You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start.
Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 β€ i β€ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β a holds.
Input
The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters.
The third line contains integer k (0 β€ k β€ 105) β the required number of operations.
Output
Print a single number β the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7).
Examples
Input
ab
ab
2
Output
1
Input
ababab
ababab
1
Output
2
Input
ab
ba
2
Output
0
Note
The sought way in the first sample is:
ab β a|b β ba β b|a β ab
In the second sample the two sought ways are:
* ababab β abab|ab β ababab
* ababab β ab|abab β ababab
Submitted Solution:
```
# ========= /\ /| |====/|
# | / \ | | / |
# | /____\ | | / |
# | / \ | | / |
# ========= / \ ===== |/====|
# code
def main():
MOD = int(1e9 + 7)
a = input()
b = input()
n = int(input())
ca, cb = 0,0
for i in range(len(a)):
s = a[i:] + a[:i]
if s == b:
ca += 1
else:
cb += 1
if ca == 0:
print(0)
return
da = [0] * (n + 1)
db = da[:]
da[0] = 1 if a == b else 0
db[0] = 1 - da[0]
for i in range(1, n + 1):
da[i] = da[i - 1] * (ca - 1) + db[i - 1] * ca
db[i] = da[i - 1] * cb + db[i - 1] * (cb - 1)
da[i] %= MOD
db[i] %= MOD
print(da[i], db[i], ca, cb)
print(da[n])
return
if __name__ == "__main__":
main()
``` | instruction | 0 | 79,394 | 6 | 158,788 |
No | output | 1 | 79,394 | 6 | 158,789 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's consider one interesting word game. In this game you should transform one word into another through special operations.
Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword".
You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start.
Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 β€ i β€ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β a holds.
Input
The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters.
The third line contains integer k (0 β€ k β€ 105) β the required number of operations.
Output
Print a single number β the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7).
Examples
Input
ab
ab
2
Output
1
Input
ababab
ababab
1
Output
2
Input
ab
ba
2
Output
0
Note
The sought way in the first sample is:
ab β a|b β ba β b|a β ab
In the second sample the two sought ways are:
* ababab β abab|ab β ababab
* ababab β ab|abab β ababab
Submitted Solution:
```
# ========= /\ /| |====/|
# | / \ | | / |
# | /____\ | | / |
# | / \ | | / |
# ========= / \ ===== |/====|
# code
def main():
MOD = int(1e9 + 7)
a = input()
b = input()
n = int(input())
ca, cb = 0,0
for i in range(len(a)):
s = a[i:] + a[:i]
if s == b:
ca += 1
else:
cb += 1
if ca == 0:
print(0)
return
da = [0] * (n + 1)
db = da[:]
da[0] = 1 if a == b else 0
db[0] = 1 - da[0]
for i in range(1, n + 1):
da[i] = da[i - 1] * (ca - 1)
da[i] += db[i - 1] * cb
db[i] = da[i - 1] * ca
if cb:
db[i - 1] * (cb - 1)
da[i] %= MOD
db[i] %= MOD
print(da[n])
return
if __name__ == "__main__":
main()
``` | instruction | 0 | 79,395 | 6 | 158,790 |
No | output | 1 | 79,395 | 6 | 158,791 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, but none β in writing a composition.
As Vasya was fishing for a sentence in the dark pond of his imagination, he suddenly wondered: what is the least number of times he should push a key to shift the cursor from one position to another one?
Let's describe his question more formally: to type a text, Vasya is using the text editor. He has already written n lines, the i-th line contains ai characters (including spaces). If some line contains k characters, then this line overall contains (k + 1) positions where the cursor can stand: before some character or after all characters (at the end of the line). Thus, the cursor's position is determined by a pair of integers (r, c), where r is the number of the line and c is the cursor's position in the line (the positions are indexed starting from one from the beginning of the line).
Vasya doesn't use the mouse to move the cursor. He uses keys "Up", "Down", "Right" and "Left". When he pushes each of these keys, the cursor shifts in the needed direction. Let's assume that before the corresponding key is pressed, the cursor was located in the position (r, c), then Vasya pushed key:
* "Up": if the cursor was located in the first line (r = 1), then it does not move. Otherwise, it moves to the previous line (with number r - 1), to the same position. At that, if the previous line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r - 1;
* "Down": if the cursor was located in the last line (r = n), then it does not move. Otherwise, it moves to the next line (with number r + 1), to the same position. At that, if the next line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r + 1;
* "Right": if the cursor can move to the right in this line (c < ar + 1), then it moves to the right (to position c + 1). Otherwise, it is located at the end of the line and doesn't move anywhere when Vasya presses the "Right" key;
* "Left": if the cursor can move to the left in this line (c > 1), then it moves to the left (to position c - 1). Otherwise, it is located at the beginning of the line and doesn't move anywhere when Vasya presses the "Left" key.
You've got the number of lines in the text file and the number of characters, written in each line of this file. Find the least number of times Vasya should push the keys, described above, to shift the cursor from position (r1, c1) to position (r2, c2).
Input
The first line of the input contains an integer n (1 β€ n β€ 100) β the number of lines in the file. The second line contains n integers a1, a2, ..., an (0 β€ ai β€ 105), separated by single spaces. The third line contains four integers r1, c1, r2, c2 (1 β€ r1, r2 β€ n, 1 β€ c1 β€ ar1 + 1, 1 β€ c2 β€ ar2 + 1).
Output
Print a single integer β the minimum number of times Vasya should push a key to move the cursor from position (r1, c1) to position (r2, c2).
Examples
Input
4
2 1 6 4
3 4 4 2
Output
3
Input
4
10 5 6 4
1 11 4 2
Output
6
Input
3
10 1 10
1 10 1 1
Output
3
Note
In the first sample the editor contains four lines. Let's represent the cursor's possible positions in the line as numbers. Letter s represents the cursor's initial position, letter t represents the last one. Then all possible positions of the cursor in the text editor are described by the following table.
123
12
123s567
1t345
One of the possible answers in the given sample is: "Left", "Down", "Left".
Submitted Solution:
```
'''input
4
10 5 6 4
1 11 4 2
'''
from sys import stdin, stdout, setrecursionlimit
from collections import deque, defaultdict
from bisect import bisect_left
stdin = open('input.txt', 'r')
stdout = open('output.txt', 'w')
def make(first, second):
return str(first) + ' ' + str(second)
def create_graph(arr):
graph = defaultdict(list)
for i in range(1, n + 1):
for j in range(1, arr[i] + 1):
if j > 1:
# left right
graph[make(i, j)].append(make(i, j - 1))
graph[make(i, j - 1)].append(make(i, j))
if i > 1 :
jj = min(j,arr[i - 1])
graph[make(i, j)].append(make(i - 1, jj))
graph[make(i -1 , jj)].append(make(i, j))
if i > 1:
if arr[i] < arr[i - 1]:
for j in range(arr[i] + 1, arr[i - 1] + 1):
graph[make(i, arr[i])].append(make(i - 1, j))
graph[make(i - 1, j)].append(make(i, arr[i]))
return graph
def bfs(graph, start, end):
if start == end:
return 0
myq = deque([])
steps = 1
myq.append(start)
visited = dict()
visited[start] = True
dum = deque([])
while len(myq) > 0:
# print(myq)
node = myq.popleft()
visited[node] = True
for i in graph[node]:
if i == end:
return steps
if i not in visited:
dum.append(i)
if len(myq) == 0:
steps += 1
myq = dum
dum = deque([])
# main starts
n = int(stdin.readline().strip())
arr = list(map(int, stdin.readline().split()))
for i in range(n):
arr[i] += 1
arr.insert(0, "$")
r1, c1, r2, c2 = list(map(int, stdin.readline().split()))
graph = create_graph(arr)
node1 = make(r1, c1)
node2 = make(r2, c2)
# print(graph)
stdout.write(str(bfs(graph, node1, node2)))
``` | instruction | 0 | 79,412 | 6 | 158,824 |
No | output | 1 | 79,412 | 6 | 158,825 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, but none β in writing a composition.
As Vasya was fishing for a sentence in the dark pond of his imagination, he suddenly wondered: what is the least number of times he should push a key to shift the cursor from one position to another one?
Let's describe his question more formally: to type a text, Vasya is using the text editor. He has already written n lines, the i-th line contains ai characters (including spaces). If some line contains k characters, then this line overall contains (k + 1) positions where the cursor can stand: before some character or after all characters (at the end of the line). Thus, the cursor's position is determined by a pair of integers (r, c), where r is the number of the line and c is the cursor's position in the line (the positions are indexed starting from one from the beginning of the line).
Vasya doesn't use the mouse to move the cursor. He uses keys "Up", "Down", "Right" and "Left". When he pushes each of these keys, the cursor shifts in the needed direction. Let's assume that before the corresponding key is pressed, the cursor was located in the position (r, c), then Vasya pushed key:
* "Up": if the cursor was located in the first line (r = 1), then it does not move. Otherwise, it moves to the previous line (with number r - 1), to the same position. At that, if the previous line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r - 1;
* "Down": if the cursor was located in the last line (r = n), then it does not move. Otherwise, it moves to the next line (with number r + 1), to the same position. At that, if the next line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r + 1;
* "Right": if the cursor can move to the right in this line (c < ar + 1), then it moves to the right (to position c + 1). Otherwise, it is located at the end of the line and doesn't move anywhere when Vasya presses the "Right" key;
* "Left": if the cursor can move to the left in this line (c > 1), then it moves to the left (to position c - 1). Otherwise, it is located at the beginning of the line and doesn't move anywhere when Vasya presses the "Left" key.
You've got the number of lines in the text file and the number of characters, written in each line of this file. Find the least number of times Vasya should push the keys, described above, to shift the cursor from position (r1, c1) to position (r2, c2).
Input
The first line of the input contains an integer n (1 β€ n β€ 100) β the number of lines in the file. The second line contains n integers a1, a2, ..., an (0 β€ ai β€ 105), separated by single spaces. The third line contains four integers r1, c1, r2, c2 (1 β€ r1, r2 β€ n, 1 β€ c1 β€ ar1 + 1, 1 β€ c2 β€ ar2 + 1).
Output
Print a single integer β the minimum number of times Vasya should push a key to move the cursor from position (r1, c1) to position (r2, c2).
Examples
Input
4
2 1 6 4
3 4 4 2
Output
3
Input
4
10 5 6 4
1 11 4 2
Output
6
Input
3
10 1 10
1 10 1 1
Output
3
Note
In the first sample the editor contains four lines. Let's represent the cursor's possible positions in the line as numbers. Letter s represents the cursor's initial position, letter t represents the last one. Then all possible positions of the cursor in the text editor are described by the following table.
123
12
123s567
1t345
One of the possible answers in the given sample is: "Left", "Down", "Left".
Submitted Solution:
```
from collections import deque
def read(line):
return [int(c) for c in line.split()]
def solve(n, lines, r1, c1, r2, c2):
queue = deque([(r1, c1, 0)])
visited = {}
while queue:
r, c, cost = queue.pop()
if (r, c) not in visited:
visited[(r, c)] = cost
else:
if cost < visited[(r, c)]:
visited[(r, c)] = cost
else:
continue
# left or right to the target column
if c2 <= lines[r - 1] + 1:
queue.appendleft((r, c2, cost + abs(c - c2)))
# right to last column
last_pos = lines[r - 1] + 1
if c < last_pos:
queue.appendleft((r, last_pos, cost + abs(c - last_pos)))
# up
if r - 1 >= 1:
last_pos_prev = lines[r - 2] + 1
if last_pos_prev >= c:
queue.appendleft((r - 1, c, cost + 1))
else:
queue.appendleft((r - 1, last_pos_prev, cost + 1))
# down
if r + 1 <= n:
last_pos_next = lines[r] + 1
if last_pos_next >= c:
queue.appendleft((r + 1, c, cost + 1))
else:
queue.appendleft((r + 1, last_pos_next, cost + 1))
return visited[(r2, c2)]
def main():
with open('input.txt') as f:
test = f.readlines()
n, = read(test[0])
lines = read(test[1])
r1, c1, r2, c2 = read(test[2])
ans = solve(n, lines, r1, c1, r2, c2)
print(ans)
#with open('output.txt', 'w') as f:
# f.write(str(ans))
if __name__ == "__main__":
main()
``` | instruction | 0 | 79,413 | 6 | 158,826 |
No | output | 1 | 79,413 | 6 | 158,827 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, but none β in writing a composition.
As Vasya was fishing for a sentence in the dark pond of his imagination, he suddenly wondered: what is the least number of times he should push a key to shift the cursor from one position to another one?
Let's describe his question more formally: to type a text, Vasya is using the text editor. He has already written n lines, the i-th line contains ai characters (including spaces). If some line contains k characters, then this line overall contains (k + 1) positions where the cursor can stand: before some character or after all characters (at the end of the line). Thus, the cursor's position is determined by a pair of integers (r, c), where r is the number of the line and c is the cursor's position in the line (the positions are indexed starting from one from the beginning of the line).
Vasya doesn't use the mouse to move the cursor. He uses keys "Up", "Down", "Right" and "Left". When he pushes each of these keys, the cursor shifts in the needed direction. Let's assume that before the corresponding key is pressed, the cursor was located in the position (r, c), then Vasya pushed key:
* "Up": if the cursor was located in the first line (r = 1), then it does not move. Otherwise, it moves to the previous line (with number r - 1), to the same position. At that, if the previous line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r - 1;
* "Down": if the cursor was located in the last line (r = n), then it does not move. Otherwise, it moves to the next line (with number r + 1), to the same position. At that, if the next line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r + 1;
* "Right": if the cursor can move to the right in this line (c < ar + 1), then it moves to the right (to position c + 1). Otherwise, it is located at the end of the line and doesn't move anywhere when Vasya presses the "Right" key;
* "Left": if the cursor can move to the left in this line (c > 1), then it moves to the left (to position c - 1). Otherwise, it is located at the beginning of the line and doesn't move anywhere when Vasya presses the "Left" key.
You've got the number of lines in the text file and the number of characters, written in each line of this file. Find the least number of times Vasya should push the keys, described above, to shift the cursor from position (r1, c1) to position (r2, c2).
Input
The first line of the input contains an integer n (1 β€ n β€ 100) β the number of lines in the file. The second line contains n integers a1, a2, ..., an (0 β€ ai β€ 105), separated by single spaces. The third line contains four integers r1, c1, r2, c2 (1 β€ r1, r2 β€ n, 1 β€ c1 β€ ar1 + 1, 1 β€ c2 β€ ar2 + 1).
Output
Print a single integer β the minimum number of times Vasya should push a key to move the cursor from position (r1, c1) to position (r2, c2).
Examples
Input
4
2 1 6 4
3 4 4 2
Output
3
Input
4
10 5 6 4
1 11 4 2
Output
6
Input
3
10 1 10
1 10 1 1
Output
3
Note
In the first sample the editor contains four lines. Let's represent the cursor's possible positions in the line as numbers. Letter s represents the cursor's initial position, letter t represents the last one. Then all possible positions of the cursor in the text editor are described by the following table.
123
12
123s567
1t345
One of the possible answers in the given sample is: "Left", "Down", "Left".
Submitted Solution:
```
# 253C
__author__ = 'artyom'
f = open('input.txt', 'r')
n = int(f.readline())
a = list(map(int, f.readline().split()))
r1, c1, r2, c2 = map(lambda x: int(x) - 1, f.readline().split())
def neighbours(x, y):
res = set()
if x > 0:
res.add((x - 1, min(y, a[x - 1])))
if x == r2 and y > c1:
res.add((x, y - 1))
if x < n - 1:
res.add((x + 1, min(y, a[x + 1])))
if x == r2 and y < c2:
res.add((x, y + 1))
return res
def bfs():
visited = set()
frontier = set()
frontier.add((r1, c1))
level = 0
while frontier:
next_frontier = set()
for x, y in frontier:
if x == r2 and y == c2:
return level
visited.add((x, y))
next_frontier |= neighbours(x, y) - visited
frontier = next_frontier
level += 1
open('output.txt', 'w').write(str(bfs()))
``` | instruction | 0 | 79,414 | 6 | 158,828 |
No | output | 1 | 79,414 | 6 | 158,829 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, but none β in writing a composition.
As Vasya was fishing for a sentence in the dark pond of his imagination, he suddenly wondered: what is the least number of times he should push a key to shift the cursor from one position to another one?
Let's describe his question more formally: to type a text, Vasya is using the text editor. He has already written n lines, the i-th line contains ai characters (including spaces). If some line contains k characters, then this line overall contains (k + 1) positions where the cursor can stand: before some character or after all characters (at the end of the line). Thus, the cursor's position is determined by a pair of integers (r, c), where r is the number of the line and c is the cursor's position in the line (the positions are indexed starting from one from the beginning of the line).
Vasya doesn't use the mouse to move the cursor. He uses keys "Up", "Down", "Right" and "Left". When he pushes each of these keys, the cursor shifts in the needed direction. Let's assume that before the corresponding key is pressed, the cursor was located in the position (r, c), then Vasya pushed key:
* "Up": if the cursor was located in the first line (r = 1), then it does not move. Otherwise, it moves to the previous line (with number r - 1), to the same position. At that, if the previous line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r - 1;
* "Down": if the cursor was located in the last line (r = n), then it does not move. Otherwise, it moves to the next line (with number r + 1), to the same position. At that, if the next line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r + 1;
* "Right": if the cursor can move to the right in this line (c < ar + 1), then it moves to the right (to position c + 1). Otherwise, it is located at the end of the line and doesn't move anywhere when Vasya presses the "Right" key;
* "Left": if the cursor can move to the left in this line (c > 1), then it moves to the left (to position c - 1). Otherwise, it is located at the beginning of the line and doesn't move anywhere when Vasya presses the "Left" key.
You've got the number of lines in the text file and the number of characters, written in each line of this file. Find the least number of times Vasya should push the keys, described above, to shift the cursor from position (r1, c1) to position (r2, c2).
Input
The first line of the input contains an integer n (1 β€ n β€ 100) β the number of lines in the file. The second line contains n integers a1, a2, ..., an (0 β€ ai β€ 105), separated by single spaces. The third line contains four integers r1, c1, r2, c2 (1 β€ r1, r2 β€ n, 1 β€ c1 β€ ar1 + 1, 1 β€ c2 β€ ar2 + 1).
Output
Print a single integer β the minimum number of times Vasya should push a key to move the cursor from position (r1, c1) to position (r2, c2).
Examples
Input
4
2 1 6 4
3 4 4 2
Output
3
Input
4
10 5 6 4
1 11 4 2
Output
6
Input
3
10 1 10
1 10 1 1
Output
3
Note
In the first sample the editor contains four lines. Let's represent the cursor's possible positions in the line as numbers. Letter s represents the cursor's initial position, letter t represents the last one. Then all possible positions of the cursor in the text editor are described by the following table.
123
12
123s567
1t345
One of the possible answers in the given sample is: "Left", "Down", "Left".
Submitted Solution:
```
import sys
sys.stdin = open('input.txt')
sys.stdout = open('output.txt', 'w')
n = int(input())
a = [int(x) for x in input().split()]
[r1, c1, r2, c2] = [int(x) for x in input().split()]
r1 -= 1
r2 -= 1
c1 -= 1
c2 -= 1
dr = r2 - r1
ddr = dr // abs(dr) if dr != 0 else 1
c = c1
for i in range(abs(dr)+1):
r = r1 + ddr*i
c = min(c, a[r])
pen1 = 0
for i in range(min(r1, r2)):
pen = (min(r1, r2) - i) * 2
if c > c2 and a[i] < c:
pen -= c - c2 - abs(a[i] - c2)
pen1 = min(pen1, pen)
pen2 = 0
for i in range(max(r1, r2)+1, n):
pen = (i - max(r1, r2)) * 2
if c > c2 and a[i] < c:
pen -= c - c2 - abs(a[i] - c2)
pen2 = min(pen2, pen)
pen = abs(dr) + abs(c - c2)
# print(dr, c, c2)
# print(pen, pen1, pen2)
print(min(pen + pen1, pen+ pen2))
``` | instruction | 0 | 79,415 | 6 | 158,830 |
No | output | 1 | 79,415 | 6 | 158,831 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.
Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?
The cost of sending the message is the sum of the costs of sending every word in it.
Input
The first line of input contains integers n, k and m (1 β€ k β€ n β€ 105, 1 β€ m β€ 105) β the number of words in their language, the number of groups of words, and the number of words in Mahmoud's message respectively.
The second line contains n strings consisting of lowercase English letters of length not exceeding 20 which represent the words. It's guaranteed that the words are distinct.
The third line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) where ai is the cost of sending the i-th word.
The next k lines describe the groups of words of same meaning. The next k lines each start with an integer x (1 β€ x β€ n) which means that there are x words in this group, followed by x integers which represent the indices of words in this group. It's guaranteed that each word appears in exactly one group.
The next line contains m space-separated words which represent Mahmoud's message. Each of these words appears in the list of language's words.
Output
The only line should contain the minimum cost to send the message after replacing some words (maybe none) with some words of the same meaning.
Examples
Input
5 4 4
i loser am the second
100 1 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
107
Input
5 4 4
i loser am the second
100 20 1 5 10
1 1
1 3
2 2 5
1 4
i am the second
Output
116
Note
In the first sample, Mahmoud should replace the word "second" with the word "loser" because it has less cost so the cost will be 100+1+5+1=107.
In the second sample, Mahmoud shouldn't do any replacement so the cost will be 100+1+5+10=116. | instruction | 0 | 79,665 | 6 | 159,330 |
Tags: dsu, greedy, implementation
Correct Solution:
```
n, k, m = map(int, input().split())
words = list(input().split())
costs = list(map(int, input().split()))
dic, dic1 = {}, {}
for i in range(k):
a = list(map(int, input().split()))
p, q = a[0], a[1:]
minc = float("inf")
for j in a[1:]:
dic[j] = i
minc = min(minc, costs[j - 1])
for j in a[1:]:
dic1[words[j - 1]] = minc
message = list(input().split())
cost = 0
for j in message:
cost += dic1[j]
print(cost)
``` | output | 1 | 79,665 | 6 | 159,331 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.