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.
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes.
Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels.
Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β ermit).
Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines):
* Clerihew (aabb);
* Alternating (abab);
* Enclosed (abba).
If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa).
If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme.
Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task.
Input
The first line contains two integers n and k (1 β€ n β€ 2500, 1 β€ k β€ 5) β the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104.
If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on.
Output
Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes.
Examples
Input
1 1
day
may
sun
fun
Output
aabb
Input
1 1
day
may
gray
way
Output
aaaa
Input
2 1
a
a
a
a
a
a
e
e
Output
aabb
Input
2 1
day
may
sun
fun
test
hill
fest
thrill
Output
NO
Note
In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
|
instruction
| 0
| 9,272
| 6
| 18,544
|
Tags: implementation
Correct Solution:
```
import math
#------------------------------warmup----------------------------
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")
#-------------------game starts now----------------------------------------------------
def find(s,k):
ek=0
sw=""
vow=set()
vow.add('a')
vow.add('e')
vow.add('i')
vow.add('o')
vow.add('u')
for i in range(len(s)-1,-1,-1):
if s[i] in vow:
ek+=1
sw+=s[i]
if ek==k:
return sw
return "-1"
n,k=map(int,input().split())
l=[]
tot=[]
res=[]
f=0
for i in range(4*n):
u=input()
l.append(find(u,k))
for i in range(n):
a=[]
for j in range(4):
a.append(l[i*4+j])
#print(a)
if "-1" in a or len(set(a))>2:
f=1
break
s=set(a)
sw=""
e=0
e1=0
for j in s:
for i in range(len(a)):
if a[i]==j:
e+=1
sw+="a"
else:
e1+=1
sw+="b"
break
if e==4 or e1==4:
res.append(sw)
continue
elif e==2 and e1==2:
tot.append(sw)
else:
f=1
break
if f==1:
print("NO")
else:
f=0
for i in range(len(tot)):
if tot[i]!=tot[i-1]:
f=1
break
if f==1:
print("NO")
elif len(tot)==0 and len(res)>0:
print("aaaa")
else:
if tot[0][0]=='b':
tot[0]=tot[0][::-1]
print(tot[0])
```
|
output
| 1
| 9,272
| 6
| 18,545
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes.
Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels.
Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β ermit).
Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines):
* Clerihew (aabb);
* Alternating (abab);
* Enclosed (abba).
If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa).
If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme.
Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task.
Input
The first line contains two integers n and k (1 β€ n β€ 2500, 1 β€ k β€ 5) β the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104.
If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on.
Output
Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes.
Examples
Input
1 1
day
may
sun
fun
Output
aabb
Input
1 1
day
may
gray
way
Output
aaaa
Input
2 1
a
a
a
a
a
a
e
e
Output
aabb
Input
2 1
day
may
sun
fun
test
hill
fest
thrill
Output
NO
Note
In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
Submitted Solution:
```
def s(l, k):
v = 0
for i in range(len(l) - 1, -1, -1):
if l[i] in 'aeiou':
v += 1
if v == k:
return l[i:]
return ''
def f(q):
if '' in q:
return 'NO'
elif q[0] == q[1]:
if q[2] == q[3]:
return 'aaaa' if q[1] == q[2] else 'aabb'
else:
return 'NO'
elif q[0] == q[2] and q[1] == q[3]:
return 'abab'
elif q[0] == q[3] and q[1] == q[2]:
return 'abba'
else:
return 'NO'
n, k = map(int, input().split())
v = ''
for i in range(n):
c = f([s(input(), k) for i in range(4)])
if c == 'NO':
v = c
break
elif v and c in (v, 'aaaa'):
pass
elif v in ('', 'aaaa'):
v = c
else:
v = 'NO'
break
print(v)
```
|
instruction
| 0
| 9,273
| 6
| 18,546
|
Yes
|
output
| 1
| 9,273
| 6
| 18,547
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes.
Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels.
Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β ermit).
Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines):
* Clerihew (aabb);
* Alternating (abab);
* Enclosed (abba).
If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa).
If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme.
Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task.
Input
The first line contains two integers n and k (1 β€ n β€ 2500, 1 β€ k β€ 5) β the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104.
If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on.
Output
Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes.
Examples
Input
1 1
day
may
sun
fun
Output
aabb
Input
1 1
day
may
gray
way
Output
aaaa
Input
2 1
a
a
a
a
a
a
e
e
Output
aabb
Input
2 1
day
may
sun
fun
test
hill
fest
thrill
Output
NO
Note
In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
Submitted Solution:
```
#from bisect import bisect_left as bl #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br #c++ upperbound br(array,element)
#from __future__ import print_function, division #while using python2
# from itertools import accumulate
# from collections import defaultdict, Counter
def modinv(n,p):
return pow(n,p-2,p)
def get_suffix(s, k):
vovels = "aeiou"
for i in range(len(s)-1, -1, -1):
if s[i] in vovels:
k -= 1
if k == 0:
return s[i:]
return -1
# aaaa = 1
# aabb = 2
# abab = 3
# abba = 4
# none = -1
def get_scheme(s1, s2, s3, s4):
if s1 == s2 == s3 == s4:
return 1
if s1 == s2 and s3 == s4:
return 2
if s1 == s3 and s2 == s4:
return 3
if s1 == s4 and s2 == s3:
return 4
return -1
def get_scheme2(x):
if x == 1:
return "aaaa"
if x == 2:
return "aabb"
if x == 3:
return "abab"
if x == 4:
return "abba"
def main():
#sys.stdin = open('input.txt', 'r')
#sys.stdout = open('output.txt', 'w')
# print(get_suffix("commit", 3))
n, k = [int(x) for x in input().split()]
rhymes = []
no_scheme = False
for i in range(n):
s1 = get_suffix(input(), k)
s2 = get_suffix(input(), k)
s3 = get_suffix(input(), k)
s4 = get_suffix(input(), k)
if s1 == -1 or s2 == -1 or s3 == -1 or s4 == -1:
rhymes.append(-1)
else:
rhymes.append(get_scheme(s1, s2, s3, s4))
# print(*rhymes)
rhymes = set(rhymes)
scheme = ""
if -1 in rhymes:
scheme = "NO"
elif len(rhymes) == 1:
scheme = get_scheme2(rhymes.pop())
elif len(rhymes) == 2 and 1 in rhymes:
rhymes.remove(1)
scheme = get_scheme2(rhymes.pop())
else:
scheme = "NO"
print(scheme)
#------------------ Python 2 and 3 footer by Pajenegod and c1729-----------------------------------------
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192
class FastIO(BytesIO):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.writable = "x" in file.mode or "w" in file.mode
self.write = super(FastIO, self).write if self.writable else None
def _fill(self):
s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
return s
def read(self):
while self._fill(): pass
return super(FastIO,self).read()
def readline(self):
while self.newlines == 0:
s = self._fill(); self.newlines = s.count(b"\n") + (not s)
self.newlines -= 1
return super(FastIO, self).readline()
def flush(self):
if self.writable:
os.write(self._fd, self.getvalue())
self.truncate(0), self.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
if py2:
self.write = self.buffer.write
self.read = self.buffer.read
self.readline = self.buffer.readline
else:
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')
if __name__ == '__main__':
main()
```
|
instruction
| 0
| 9,274
| 6
| 18,548
|
Yes
|
output
| 1
| 9,274
| 6
| 18,549
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes.
Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels.
Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β ermit).
Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines):
* Clerihew (aabb);
* Alternating (abab);
* Enclosed (abba).
If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa).
If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme.
Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task.
Input
The first line contains two integers n and k (1 β€ n β€ 2500, 1 β€ k β€ 5) β the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104.
If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on.
Output
Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes.
Examples
Input
1 1
day
may
sun
fun
Output
aabb
Input
1 1
day
may
gray
way
Output
aaaa
Input
2 1
a
a
a
a
a
a
e
e
Output
aabb
Input
2 1
day
may
sun
fun
test
hill
fest
thrill
Output
NO
Note
In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
Submitted Solution:
```
n, k = map(int, input().split())
vowels = ['a', 'e', 'i', 'o', 'u']
def find_nth(tab, S, n):
amount, pos = (1 if tab[0] in S else 0), 0
while pos < len(tab) and amount < n:
pos += 1
if tab[pos] in S:
amount += 1
return pos
def rhyme_type(lines, k):
suffixes = []
for line in lines:
amount = 0
for i in line:
if i in vowels:
amount += 1
if amount < k:
return 'TRASH'
rev = list(reversed(list(line)))
ind_from_front = find_nth(rev, vowels, k)
suffixes.append(line[-ind_from_front - 1:])
if all([suffixes[0] == x for x in suffixes]):
return 'aaaa'
if suffixes[0] == suffixes[1] and suffixes[2] == suffixes[3]:
return 'aabb'
if suffixes[0] == suffixes[2] and suffixes[1] == suffixes[3]:
return 'abab'
if suffixes[0] == suffixes[3] and suffixes[1] == suffixes[2]:
return 'abba'
return 'TRASH'
all_rhymes = set()
for _ in range(n):
lines = [input(), input(), input(), input()]
all_rhymes.add(rhyme_type(lines, k))
if 'TRASH' not in all_rhymes and len(all_rhymes) == 2 and 'aaaa' in all_rhymes:
all_rhymes.remove('aaaa')
print(list(all_rhymes)[0])
elif len(all_rhymes) > 1 or 'TRASH' in all_rhymes:
print('NO')
else:
print(list(all_rhymes)[0])
```
|
instruction
| 0
| 9,275
| 6
| 18,550
|
Yes
|
output
| 1
| 9,275
| 6
| 18,551
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes.
Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels.
Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β ermit).
Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines):
* Clerihew (aabb);
* Alternating (abab);
* Enclosed (abba).
If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa).
If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme.
Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task.
Input
The first line contains two integers n and k (1 β€ n β€ 2500, 1 β€ k β€ 5) β the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104.
If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on.
Output
Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes.
Examples
Input
1 1
day
may
sun
fun
Output
aabb
Input
1 1
day
may
gray
way
Output
aaaa
Input
2 1
a
a
a
a
a
a
e
e
Output
aabb
Input
2 1
day
may
sun
fun
test
hill
fest
thrill
Output
NO
Note
In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
Submitted Solution:
```
# import itertools
import bisect
# import math
from collections import defaultdict, Counter
import os
import sys
from io import BytesIO, IOBase
# sys.setrecursionlimit(10 ** 5)
ii = lambda: int(input())
lmii = lambda: list(map(int, input().split()))
slmii = lambda: sorted(map(int, input().split()))
li = lambda: list(input())
mii = lambda: map(int, input().split())
msi = lambda: map(str, input().split())
def gcd(a, b):
if b == 0: return a
return gcd(b, a % b)
def lcm(a, b): return (a * b) // gcd(a, b)
def main():
# for _ in " " * int(input()):
n, k = mii()
lst = []
ans = ""
for i in range(n):
lst.append([li()[::-1], li()[::-1], li()[::-1], li()[::-1]])
first = 0
for i in lst:
f = i[0]
s = i[1]
t = i[2]
ff = i[3]
cnt = 0
indf = -1
for j in range(len(f)):
if f[j] in "aeiou":
cnt += 1
if cnt == k:
indf = j
break
if cnt != k:
print("NO")
exit()
cnt = 0
inds = -1
for j in range(len(s)):
if s[j] in "aeiou":
cnt += 1
if cnt == k:
inds = j
break
if cnt != k:
print("NO")
exit()
cnt = 0
indt = -1
for j in range(len(t)):
if t[j] in "aeiou":
cnt += 1
if cnt == k:
indt = j
break
if cnt != k:
print("NO")
exit()
cnt = 0
indff = -1
for j in range(len(ff)):
if ff[j] in "aeiou":
cnt += 1
if cnt == k:
indff = j
break
if cnt != k:
print("NO")
exit()
if indf == inds == indff == indt and f[:indf + 1] == ff[:indff + 1] == s[:inds + 1] == t[:indt + 1]:
pp = "aaaa"
if first == 0:
first = 1
ans = "aaaa"
elif inds == indf and f[:indf + 1] == s[:inds + 1]:
if indt == indff and t[:indt + 1] == ff[:indff + 1]:
pp = "aabb"
if first == 0 or ans == "aaaa":
ans = "aabb"
first = 1
else:
if ans != pp:
print("NO")
exit(0)
else:
print("NO")
exit(0)
else:
if indf == indt and f[:indf + 1] == t[:indt + 1] and inds == indff and s[:inds + 1] == ff[:indff + 1]:
pp = "abab"
if first == 0 or ans == "aaaa":
ans = "abab"
first = 1
else:
if ans != pp:
print("NO")
exit(0)
elif indf == indff and f[:indf + 1] == ff[:indff + 1] and inds == indt and s[:inds + 1] == t[:indt + 1]:
pp = "abba"
if first == 0 or ans == "aaaa":
ans = "abba"
first = 1
else:
if ans != pp:
print("NO")
exit(0)
else:
print("NO")
exit(0)
print(ans)
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")
if __name__ == "__main__":
main()
```
|
instruction
| 0
| 9,276
| 6
| 18,552
|
Yes
|
output
| 1
| 9,276
| 6
| 18,553
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes.
Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels.
Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β ermit).
Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines):
* Clerihew (aabb);
* Alternating (abab);
* Enclosed (abba).
If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa).
If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme.
Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task.
Input
The first line contains two integers n and k (1 β€ n β€ 2500, 1 β€ k β€ 5) β the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104.
If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on.
Output
Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes.
Examples
Input
1 1
day
may
sun
fun
Output
aabb
Input
1 1
day
may
gray
way
Output
aaaa
Input
2 1
a
a
a
a
a
a
e
e
Output
aabb
Input
2 1
day
may
sun
fun
test
hill
fest
thrill
Output
NO
Note
In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
Submitted Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M=10**9+7
EPS=1e-6
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
vowels='aeiou'
nul='abcd'
nu=0
def operate(s):
global nu
c=0
for i in range(len(s)-1,-1,-1):
if(s[i] in vowels):
c+=1
if(c==k):
return s[i:]
nu=(nu+1)%4
return nul[nu]
def rhymes(a):
a=[operate(i) for i in a]
ID={}
id=0
ans=''
for i in a:
if(i not in ID):
ID[i]=nul[id]
id+=1
ans+=ID[i]
return ans
n,k=value()
scheme=set()
for i in range(n):
a=[]
for j in range(4):
a.append(input())
scheme.add(rhymes(a))
# print(scheme)
for i in scheme:
if(len(set(i))>2):
print("NO")
exit()
if(len(scheme)>2):
print("NO")
elif(len(scheme)==2):
if('aaaa' not in scheme):
print("NO")
else:
for i in scheme:
if(i!='aaaa'):
print(i)
else:
print(*scheme)
```
|
instruction
| 0
| 9,277
| 6
| 18,554
|
No
|
output
| 1
| 9,277
| 6
| 18,555
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes.
Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels.
Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β ermit).
Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines):
* Clerihew (aabb);
* Alternating (abab);
* Enclosed (abba).
If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa).
If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme.
Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task.
Input
The first line contains two integers n and k (1 β€ n β€ 2500, 1 β€ k β€ 5) β the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104.
If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on.
Output
Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes.
Examples
Input
1 1
day
may
sun
fun
Output
aabb
Input
1 1
day
may
gray
way
Output
aaaa
Input
2 1
a
a
a
a
a
a
e
e
Output
aabb
Input
2 1
day
may
sun
fun
test
hill
fest
thrill
Output
NO
Note
In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
Submitted Solution:
```
n,k = map(int,input().split())
lis=[]
vov=['a','e','i','o','u']
d={}
d['aabb']=d['abab']=d['abba']=d['aaaa']=0
for i in range(n*4):
s = input()
lis.append(s)
if i%4==3:
tmp=['']*4
for j in range(4):
s=lis[j]
c=0
cou=0
for ll in s[::-1]:
cou+=1
if ll in vov:
c+=1
if c==k:
tmp[j]=s[-cou:]
break
if tmp[0]==tmp[1]==tmp[2]==tmp[3] and tmp[0]!='':
d['aaaa']+=1
if tmp[0]==tmp[1] and tmp[2]==tmp[3] and tmp[1]!=tmp[3] and tmp[1]!='' and tmp[3]!='':
d['aabb']+=1
elif tmp[0]==tmp[2] and tmp[1]==tmp[3] and tmp[1]!=tmp[0] and tmp[1]!='' and tmp[0]!='':
d['abab']+=1
elif tmp[0]==tmp[3] and tmp[1]==tmp[2] and tmp[2]!=tmp[0] and tmp[1]!='' and tmp[3]!='':
d['abba']+=1
lis=[]
c=0
for i in d:
if d[i]>0:
c+=1
if c==1:
for i in d:
if d[i]>0:
print(i)
exit()
elif c==2 and d['aaaa']>0:
for i in d:
if d[i]>0:
print(i)
exit()
else:
print(-1)
```
|
instruction
| 0
| 9,278
| 6
| 18,556
|
No
|
output
| 1
| 9,278
| 6
| 18,557
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes.
Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels.
Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β ermit).
Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines):
* Clerihew (aabb);
* Alternating (abab);
* Enclosed (abba).
If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa).
If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme.
Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task.
Input
The first line contains two integers n and k (1 β€ n β€ 2500, 1 β€ k β€ 5) β the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104.
If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on.
Output
Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes.
Examples
Input
1 1
day
may
sun
fun
Output
aabb
Input
1 1
day
may
gray
way
Output
aaaa
Input
2 1
a
a
a
a
a
a
e
e
Output
aabb
Input
2 1
day
may
sun
fun
test
hill
fest
thrill
Output
NO
Note
In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
Submitted Solution:
```
n,k=map(int,input().split())
vowel=["a","e","i","o","u"]
w="";t=0;change=0;
for i in range (4*n) :
x=input()
#print(x,change)
j=x[::-1]
#l.append(x)
count=0;t=0;
for i in j:
t=t+1
if i in vowel :
count=count+1
if (count==k) :
break
#print(x,count)
if (count!=k) :
exit(print("NO"))
if j[:t]==w :
w=j[:t]
else :
change=change+1
w=j[:t]
if (change>4) :
exit(print("NO"))
if (change==1 ) :
print("aaaa")
elif (change==2 ) :
print("aabb")
elif (change==3) :
print("abba")
else :
print("abab")
```
|
instruction
| 0
| 9,279
| 6
| 18,558
|
No
|
output
| 1
| 9,279
| 6
| 18,559
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes.
Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels.
Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit β ermit).
Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines):
* Clerihew (aabb);
* Alternating (abab);
* Enclosed (abba).
If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa).
If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme.
Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task.
Input
The first line contains two integers n and k (1 β€ n β€ 2500, 1 β€ k β€ 5) β the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104.
If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on.
Output
Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes.
Examples
Input
1 1
day
may
sun
fun
Output
aabb
Input
1 1
day
may
gray
way
Output
aaaa
Input
2 1
a
a
a
a
a
a
e
e
Output
aabb
Input
2 1
day
may
sun
fun
test
hill
fest
thrill
Output
NO
Note
In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
Submitted Solution:
```
if __name__ == '__main__':
print('', end='')
def get_kth_end(line, k: int):
output = ''
vowels = 'aeiou'
vowel_count = 0
idx = len(line) - 1
while idx >= 0:
output = line[idx] + output
if line[idx] in vowels:
vowel_count += 1
if vowel_count >= k:
break
idx -= 1
return output
def get_scheme(quatrain, k: int):
for q in quatrain:
if len(q) < k:
return 'NO'
if get_kth_end(quatrain[0], k) == get_kth_end(quatrain[1], k) \
== get_kth_end(quatrain[2], k) == get_kth_end(quatrain[3], k):
return 'aaaa'
if get_kth_end(quatrain[0], k) == get_kth_end(quatrain[1], k):
return 'aabb'
elif get_kth_end(quatrain[1], k) == get_kth_end(quatrain[2], k):
return 'abba'
elif get_kth_end(quatrain[0], k) == get_kth_end(quatrain[3], k):
return 'abab'
else:
return 'NO'
in_line_1 = input().split()
k = int(in_line_1[1])
num_quats = int(in_line_1[0])
quats = []
for i in range(num_quats):
quat = []
for i in range(4):
quat.append(input())
quats.append((quat, get_scheme(quat, k)))
scheme = quats[0][1]
for q in quats:
if not q[1] == scheme:
if (scheme == 'aaaa') and (q[1] == 'aabb'):
scheme = 'aabb'
continue
print('NO')
quit(0)
print(scheme)
```
|
instruction
| 0
| 9,280
| 6
| 18,560
|
No
|
output
| 1
| 9,280
| 6
| 18,561
|
Provide a correct Python 3 solution for this coding contest problem.
Stylish is a programming language whose syntax comprises names, that are sequences of Latin alphabet letters, three types of grouping symbols, periods ('.'), and newlines. Grouping symbols, namely round brackets ('(' and ')'), curly brackets ('{' and '}'), and square brackets ('[' and ']'), must match and be nested properly. Unlike most other programming languages, Stylish uses periods instead of whitespaces for the purpose of term separation. The following is an example of a Stylish program.
1 ( Welcome .to
2 ......... Stylish )
3 { Stylish .is
4 .....[.( a. programming . language .fun .to. learn )
5 .......]
6 ..... Maybe .[
7 ....... It. will .be.an. official . ICPC . language
8 .......]
9 .....}
As you see in the example, a Stylish program is indented by periods. The amount of indentation of a line is the number of leading periods of it.
Your mission is to visit Stylish masters, learn their indentation styles, and become the youngest Stylish master. An indentation style for well-indented Stylish programs is defined by a triple of integers, (R, C, S), satisfying 1 β€ R, C, S β€ 20. R, C and S are amounts of indentation introduced by an open round bracket, an open curly bracket, and an open square bracket, respectively.
In a well-indented program, the amount of indentation of a line is given by R(ro β rc) + C(co β cc) + S(so β sc), where ro, co, and so are the numbers of occurrences of open round, curly, and square brackets in all preceding lines, respectively, and rc, cc, and sc are those of close brackets. The first line has no indentation in any well-indented program.
The above example is formatted in the indentation style (R, C, S) = (9, 5, 2). The only grouping symbol occurring in the first line of the above program is an open round bracket. Therefore the amount of indentation for the second line is 9 * (1 β 0) + 5 * (0 β 0) + 2 *(0 β 0) = 9. The first four lines contain two open round brackets, one open curly bracket, one open square bracket, two close round brackets, but no close curly nor square bracket. Therefore the amount of indentation for the fifth line is 9 * (2 β 2) + 5 * (1 β 0) + 2 * (1 β 0) = 7.
Stylish masters write only well-indented Stylish programs. Every master has his/her own indentation style.
Write a program that imitates indentation styles of Stylish masters.
Input
The input consists of multiple datasets. The first line of a dataset contains two integers p (1 β€ p β€ 10) and q (1 β€ q β€ 10). The next p lines form a well-indented program P written by a Stylish master and the following q lines form another program Q. You may assume that every line of both programs has at least one character and at most 80 characters. Also, you may assume that no line of Q starts with a period.
The last dataset is followed by a line containing two zeros.
Output
Apply the indentation style of P to Q and output the appropriate amount of indentation for each line of Q. The amounts must be output in a line in the order of corresponding lines of Q and they must be separated by a single space. The last one should not be followed by trailing spaces. If the appropriate amount of indentation of a line of Q cannot be determined uniquely through analysis of P, then output -1 for that line.
Example
Input
5 4
(Follow.my.style
.........starting.from.round.brackets)
{then.curly.brackets
.....[.and.finally
.......square.brackets.]}
(Thank.you
{for.showing.me
[all
the.secrets]})
4 2
(This.time.I.will.show.you
.........(how.to.use.round.brackets)
.........[but.not.about.square.brackets]
.........{nor.curly.brackets})
(I.learned
how.to.use.round.brackets)
4 2
(This.time.I.will.show.you
.........(how.to.use.round.brackets)
.........[but.not.about.square.brackets]
.........{nor.curly.brackets})
[I.have.not.learned
how.to.use.square.brackets]
2 2
(Be.smart.and.let.fear.of
..(closed.brackets).go)
(A.pair.of.round.brackets.enclosing
[A.line.enclosed.in.square.brackets])
1 2
Telling.you.nothing.but.you.can.make.it
[One.liner.(is).(never.indented)]
[One.liner.(is).(never.indented)]
2 4
([{Learn.from.my.KungFu
...}])
((
{{
[[
]]}}))
1 2
Do.not.waste.your.time.trying.to.read.from.emptiness
(
)
2 3
({Quite.interesting.art.of.ambiguity
....})
{
(
)}
2 4
({[
............................................................]})
(
{
[
]})
0 0
Output
0 9 14 16
0 9
0 -1
0 2
0 0
0 2 4 6
0 -1
0 -1 4
0 20 40 60
|
instruction
| 0
| 9,861
| 6
| 19,722
|
"Correct Solution:
```
import re
while 1:
R=[]
C=[]
S=[]
p,q=map(int,input().split())
if p==q==0:break
#P=[input()for _ in range(p)]
G=[]
R_c=[0]
C_c=[0]
S_c=[0]
for _ in range(p):
s=input()
cnt=s.count
G.append(re.match('[.]*',s).span()[1])
R_c.append(R_c[-1]+cnt('(')-cnt(')'))
C_c.append(C_c[-1]+cnt('{')-cnt('}'))
S_c.append(S_c[-1]+cnt('[')-cnt(']'))
for x in range(1,21):
for y in range(1,21):
for z in range(1,21):
for g,i,j,k, in zip(G,R_c,C_c,S_c):
if i*x+j*y+k*z!=g:
break
else:
R.append(x)
C.append(y)
S.append(z)
#print(R,C,S)
R_c=[0]
C_c=[0]
S_c=[0]
for _ in range(q):
s=input()
cnt=s.count
R_c.append(R_c[-1]+cnt('(')-cnt(')'))
C_c.append(C_c[-1]+cnt('{')-cnt('}'))
S_c.append(S_c[-1]+cnt('[')-cnt(']'))
R_c=R_c[:-1]
C_c=C_c[:-1]
S_c=S_c[:-1]
a=[set()for _ in range(q)]
for x,y,z in zip(R,C,S):
for idx,(i,j,k)in enumerate(zip(R_c,C_c,S_c)):
a[idx].add(i*x+j*y+k*z)
print(*[list(t)[0]if len(t)==1else-1for t in a])
```
|
output
| 1
| 9,861
| 6
| 19,723
|
Provide a correct Python 3 solution for this coding contest problem.
Stylish is a programming language whose syntax comprises names, that are sequences of Latin alphabet letters, three types of grouping symbols, periods ('.'), and newlines. Grouping symbols, namely round brackets ('(' and ')'), curly brackets ('{' and '}'), and square brackets ('[' and ']'), must match and be nested properly. Unlike most other programming languages, Stylish uses periods instead of whitespaces for the purpose of term separation. The following is an example of a Stylish program.
1 ( Welcome .to
2 ......... Stylish )
3 { Stylish .is
4 .....[.( a. programming . language .fun .to. learn )
5 .......]
6 ..... Maybe .[
7 ....... It. will .be.an. official . ICPC . language
8 .......]
9 .....}
As you see in the example, a Stylish program is indented by periods. The amount of indentation of a line is the number of leading periods of it.
Your mission is to visit Stylish masters, learn their indentation styles, and become the youngest Stylish master. An indentation style for well-indented Stylish programs is defined by a triple of integers, (R, C, S), satisfying 1 β€ R, C, S β€ 20. R, C and S are amounts of indentation introduced by an open round bracket, an open curly bracket, and an open square bracket, respectively.
In a well-indented program, the amount of indentation of a line is given by R(ro β rc) + C(co β cc) + S(so β sc), where ro, co, and so are the numbers of occurrences of open round, curly, and square brackets in all preceding lines, respectively, and rc, cc, and sc are those of close brackets. The first line has no indentation in any well-indented program.
The above example is formatted in the indentation style (R, C, S) = (9, 5, 2). The only grouping symbol occurring in the first line of the above program is an open round bracket. Therefore the amount of indentation for the second line is 9 * (1 β 0) + 5 * (0 β 0) + 2 *(0 β 0) = 9. The first four lines contain two open round brackets, one open curly bracket, one open square bracket, two close round brackets, but no close curly nor square bracket. Therefore the amount of indentation for the fifth line is 9 * (2 β 2) + 5 * (1 β 0) + 2 * (1 β 0) = 7.
Stylish masters write only well-indented Stylish programs. Every master has his/her own indentation style.
Write a program that imitates indentation styles of Stylish masters.
Input
The input consists of multiple datasets. The first line of a dataset contains two integers p (1 β€ p β€ 10) and q (1 β€ q β€ 10). The next p lines form a well-indented program P written by a Stylish master and the following q lines form another program Q. You may assume that every line of both programs has at least one character and at most 80 characters. Also, you may assume that no line of Q starts with a period.
The last dataset is followed by a line containing two zeros.
Output
Apply the indentation style of P to Q and output the appropriate amount of indentation for each line of Q. The amounts must be output in a line in the order of corresponding lines of Q and they must be separated by a single space. The last one should not be followed by trailing spaces. If the appropriate amount of indentation of a line of Q cannot be determined uniquely through analysis of P, then output -1 for that line.
Example
Input
5 4
(Follow.my.style
.........starting.from.round.brackets)
{then.curly.brackets
.....[.and.finally
.......square.brackets.]}
(Thank.you
{for.showing.me
[all
the.secrets]})
4 2
(This.time.I.will.show.you
.........(how.to.use.round.brackets)
.........[but.not.about.square.brackets]
.........{nor.curly.brackets})
(I.learned
how.to.use.round.brackets)
4 2
(This.time.I.will.show.you
.........(how.to.use.round.brackets)
.........[but.not.about.square.brackets]
.........{nor.curly.brackets})
[I.have.not.learned
how.to.use.square.brackets]
2 2
(Be.smart.and.let.fear.of
..(closed.brackets).go)
(A.pair.of.round.brackets.enclosing
[A.line.enclosed.in.square.brackets])
1 2
Telling.you.nothing.but.you.can.make.it
[One.liner.(is).(never.indented)]
[One.liner.(is).(never.indented)]
2 4
([{Learn.from.my.KungFu
...}])
((
{{
[[
]]}}))
1 2
Do.not.waste.your.time.trying.to.read.from.emptiness
(
)
2 3
({Quite.interesting.art.of.ambiguity
....})
{
(
)}
2 4
({[
............................................................]})
(
{
[
]})
0 0
Output
0 9 14 16
0 9
0 -1
0 2
0 0
0 2 4 6
0 -1
0 -1 4
0 20 40 60
|
instruction
| 0
| 9,862
| 6
| 19,724
|
"Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(0,-1),(1,0),(0,1),(-1,0)]
ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
rr = []
while True:
p,q = LI()
if p == 0:
break
a = [S() for _ in range(p)]
b = [S() for _ in range(q)]
aa = [[0,0,0,0]]
mc = 0
for c in a:
d = collections.Counter(c)
t = aa[-1][:]
t[0] += d['(']
t[0] -= d[')']
t[1] += d['{']
t[1] -= d['}']
t[2] += d['[']
t[2] -= d[']']
t[3] = 0
for ct in c:
if ct != '.':
break
t[3] += 1
if mc < t[3]:
mc = t[3]
aa.append(t)
k = []
for c1,c2,c3 in itertools.product(range(1,min(mc+1,21)), repeat=3):
f = True
for ci in range(p):
c = aa[ci]
if c[0] * c1 + c[1] * c2 + c[2] * c3 != aa[ci+1][3]:
f = False
break
if f:
k.append((c1,c2,c3))
bb = [[0,0,0]]
for c in b:
d = collections.Counter(c)
t = bb[-1][:]
t[0] += d['(']
t[0] -= d[')']
t[1] += d['{']
t[1] -= d['}']
t[2] += d['[']
t[2] -= d[']']
bb.append(t)
r = [0]
for c in bb[1:-1]:
s = set()
for c1,c2,c3 in k:
s.add(c[0]*c1+c[1]*c2+c[2]*c3)
if len(s) == 1:
r.append(list(s)[0])
elif sum(c) == 0:
r.append(0)
else:
r.append(-1)
rr.append(' '.join(map(str,r)))
return '\n'.join(map(str,rr))
print(main())
```
|
output
| 1
| 9,862
| 6
| 19,725
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Stylish is a programming language whose syntax comprises names, that are sequences of Latin alphabet letters, three types of grouping symbols, periods ('.'), and newlines. Grouping symbols, namely round brackets ('(' and ')'), curly brackets ('{' and '}'), and square brackets ('[' and ']'), must match and be nested properly. Unlike most other programming languages, Stylish uses periods instead of whitespaces for the purpose of term separation. The following is an example of a Stylish program.
1 ( Welcome .to
2 ......... Stylish )
3 { Stylish .is
4 .....[.( a. programming . language .fun .to. learn )
5 .......]
6 ..... Maybe .[
7 ....... It. will .be.an. official . ICPC . language
8 .......]
9 .....}
As you see in the example, a Stylish program is indented by periods. The amount of indentation of a line is the number of leading periods of it.
Your mission is to visit Stylish masters, learn their indentation styles, and become the youngest Stylish master. An indentation style for well-indented Stylish programs is defined by a triple of integers, (R, C, S), satisfying 1 β€ R, C, S β€ 20. R, C and S are amounts of indentation introduced by an open round bracket, an open curly bracket, and an open square bracket, respectively.
In a well-indented program, the amount of indentation of a line is given by R(ro β rc) + C(co β cc) + S(so β sc), where ro, co, and so are the numbers of occurrences of open round, curly, and square brackets in all preceding lines, respectively, and rc, cc, and sc are those of close brackets. The first line has no indentation in any well-indented program.
The above example is formatted in the indentation style (R, C, S) = (9, 5, 2). The only grouping symbol occurring in the first line of the above program is an open round bracket. Therefore the amount of indentation for the second line is 9 * (1 β 0) + 5 * (0 β 0) + 2 *(0 β 0) = 9. The first four lines contain two open round brackets, one open curly bracket, one open square bracket, two close round brackets, but no close curly nor square bracket. Therefore the amount of indentation for the fifth line is 9 * (2 β 2) + 5 * (1 β 0) + 2 * (1 β 0) = 7.
Stylish masters write only well-indented Stylish programs. Every master has his/her own indentation style.
Write a program that imitates indentation styles of Stylish masters.
Input
The input consists of multiple datasets. The first line of a dataset contains two integers p (1 β€ p β€ 10) and q (1 β€ q β€ 10). The next p lines form a well-indented program P written by a Stylish master and the following q lines form another program Q. You may assume that every line of both programs has at least one character and at most 80 characters. Also, you may assume that no line of Q starts with a period.
The last dataset is followed by a line containing two zeros.
Output
Apply the indentation style of P to Q and output the appropriate amount of indentation for each line of Q. The amounts must be output in a line in the order of corresponding lines of Q and they must be separated by a single space. The last one should not be followed by trailing spaces. If the appropriate amount of indentation of a line of Q cannot be determined uniquely through analysis of P, then output -1 for that line.
Example
Input
5 4
(Follow.my.style
.........starting.from.round.brackets)
{then.curly.brackets
.....[.and.finally
.......square.brackets.]}
(Thank.you
{for.showing.me
[all
the.secrets]})
4 2
(This.time.I.will.show.you
.........(how.to.use.round.brackets)
.........[but.not.about.square.brackets]
.........{nor.curly.brackets})
(I.learned
how.to.use.round.brackets)
4 2
(This.time.I.will.show.you
.........(how.to.use.round.brackets)
.........[but.not.about.square.brackets]
.........{nor.curly.brackets})
[I.have.not.learned
how.to.use.square.brackets]
2 2
(Be.smart.and.let.fear.of
..(closed.brackets).go)
(A.pair.of.round.brackets.enclosing
[A.line.enclosed.in.square.brackets])
1 2
Telling.you.nothing.but.you.can.make.it
[One.liner.(is).(never.indented)]
[One.liner.(is).(never.indented)]
2 4
([{Learn.from.my.KungFu
...}])
((
{{
[[
]]}}))
1 2
Do.not.waste.your.time.trying.to.read.from.emptiness
(
)
2 3
({Quite.interesting.art.of.ambiguity
....})
{
(
)}
2 4
({[
............................................................]})
(
{
[
]})
0 0
Output
0 9 14 16
0 9
0 -1
0 2
0 0
0 2 4 6
0 -1
0 -1 4
0 20 40 60
Submitted Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(0,-1),(1,0),(0,1),(-1,0)]
ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
rr = []
while True:
p,q = LI()
if p == 0:
break
a = [S() for _ in range(p)]
b = [S() for _ in range(q)]
aa = [[0,0,0,0]]
mc = 0
for c in a:
d = collections.Counter(c)
t = aa[-1][:]
t[0] += d['(']
t[0] -= d[')']
t[1] += d['{']
t[1] -= d['}']
t[2] += d['[']
t[2] -= d[']']
t[3] = 0
for ct in c:
if ct != '.':
break
t[3] += 1
if mc < t[3]:
mc = t[3]
aa.append(t)
k = []
for c1,c2,c3 in itertools.product(range(1,min(mc+1,21)), repeat=3):
f = True
for ci in range(p):
c = aa[ci]
if c[0] * c1 + c[1] * c2 + c[2] * c3 != aa[ci+1][3]:
f = False
break
if f:
k.append((c1,c2,c3))
bb = [[0,0,0]]
for c in b:
d = collections.Counter(c)
t = bb[-1][:]
t[0] += d['(']
t[0] -= d[')']
t[1] += d['{']
t[1] -= d['}']
t[2] += d['[']
t[2] -= d[']']
bb.append(t)
r = [0]
for c in bb[1:-1]:
s = set()
for c1,c2,c3 in k:
s.add(c[0]*c1+c[1]*c2+c[2]*c3)
if len(s) == 1:
r.append(list(s)[0])
else:
r.append(-1)
rr.append(' '.join(map(str,r)))
return '\n'.join(map(str,rr))
print(main())
```
|
instruction
| 0
| 9,863
| 6
| 19,726
|
No
|
output
| 1
| 9,863
| 6
| 19,727
|
Provide tags and a correct Python 3 solution for this coding contest problem.
R3D3 spent some time on an internship in MDCS. After earning enough money, he decided to go on a holiday somewhere far, far away. He enjoyed suntanning, drinking alcohol-free cocktails and going to concerts of popular local bands. While listening to "The White Buttons" and their hit song "Dacan the Baker", he met another robot for whom he was sure is the love of his life. Well, his summer, at least. Anyway, R3D3 was too shy to approach his potential soulmate, so he decided to write her a love letter. However, he stumbled upon a problem. Due to a terrorist threat, the Intergalactic Space Police was monitoring all letters sent in the area. Thus, R3D3 decided to invent his own alphabet, for which he was sure his love would be able to decipher.
There are n letters in R3D3βs alphabet, and he wants to represent each letter as a sequence of '0' and '1', so that no letterβs sequence is a prefix of another letter's sequence. Since the Intergalactic Space Communications Service has lately introduced a tax for invented alphabets, R3D3 must pay a certain amount of money for each bit in his alphabetβs code (check the sample test for clarifications). He is too lovestruck to think clearly, so he asked you for help.
Given the costs c0 and c1 for each '0' and '1' in R3D3βs alphabet, respectively, you should come up with a coding for the alphabet (with properties as above) with minimum total cost.
Input
The first line of input contains three integers n (2 β€ n β€ 108), c0 and c1 (0 β€ c0, c1 β€ 108) β the number of letters in the alphabet, and costs of '0' and '1', respectively.
Output
Output a single integer β minimum possible total a cost of the whole alphabet.
Example
Input
4 1 2
Output
12
Note
There are 4 letters in the alphabet. The optimal encoding is "00", "01", "10", "11". There are 4 zeroes and 4 ones used, so the total cost is 4Β·1 + 4Β·2 = 12.
|
instruction
| 0
| 10,417
| 6
| 20,834
|
Tags: dp, greedy
Correct Solution:
```
import sys,heapq
#sys.stdin=open("data.txt")
input=sys.stdin.readline
n,a,b=map(int,input().split())
if a<b: a,b=b,a
if b==0:
# 1 01 001 0001 ... is optimal, plus a long series of 0's
print((n-1)*a)
else:
# pascal's triangle thing
pascal=[[1]*20005]
for i in range(20004):
newrow=[1]
for j in range(1,20005):
newrow.append(newrow[-1]+pascal[-1][j])
if newrow[-1]>n: break
pascal.append(newrow)
def getcom(a,b):
# return a+b choose b
# if larger than n, return infinite
if len(pascal[a])>b: return pascal[a][b]
if b==0: return 1
if b==1: return a
return 100000005
# start with the null node (prefix cost 0)
# can split a node into two other nodes with added cost c+a+b
# new nodes have prefix costs c+a, c+b
# want n-1 splits in total
remain=n-1
ans=0
possible=[[a+b,1]] # [c,count]
while 1:
# cost u, v leaves
u,v=heapq.heappop(possible)
while possible and possible[0][0]==u:
v+=possible[0][1]
heapq.heappop(possible)
if remain<=v:
ans+=u*remain
break
ans+=u*v
remain-=v
heapq.heappush(possible,[u+a,v])
heapq.heappush(possible,[u+b,v])
print(ans)
# Made By Mostafa_Khaled
```
|
output
| 1
| 10,417
| 6
| 20,835
|
Provide tags and a correct Python 3 solution for this coding contest problem.
R3D3 spent some time on an internship in MDCS. After earning enough money, he decided to go on a holiday somewhere far, far away. He enjoyed suntanning, drinking alcohol-free cocktails and going to concerts of popular local bands. While listening to "The White Buttons" and their hit song "Dacan the Baker", he met another robot for whom he was sure is the love of his life. Well, his summer, at least. Anyway, R3D3 was too shy to approach his potential soulmate, so he decided to write her a love letter. However, he stumbled upon a problem. Due to a terrorist threat, the Intergalactic Space Police was monitoring all letters sent in the area. Thus, R3D3 decided to invent his own alphabet, for which he was sure his love would be able to decipher.
There are n letters in R3D3βs alphabet, and he wants to represent each letter as a sequence of '0' and '1', so that no letterβs sequence is a prefix of another letter's sequence. Since the Intergalactic Space Communications Service has lately introduced a tax for invented alphabets, R3D3 must pay a certain amount of money for each bit in his alphabetβs code (check the sample test for clarifications). He is too lovestruck to think clearly, so he asked you for help.
Given the costs c0 and c1 for each '0' and '1' in R3D3βs alphabet, respectively, you should come up with a coding for the alphabet (with properties as above) with minimum total cost.
Input
The first line of input contains three integers n (2 β€ n β€ 108), c0 and c1 (0 β€ c0, c1 β€ 108) β the number of letters in the alphabet, and costs of '0' and '1', respectively.
Output
Output a single integer β minimum possible total a cost of the whole alphabet.
Example
Input
4 1 2
Output
12
Note
There are 4 letters in the alphabet. The optimal encoding is "00", "01", "10", "11". There are 4 zeroes and 4 ones used, so the total cost is 4Β·1 + 4Β·2 = 12.
|
instruction
| 0
| 10,418
| 6
| 20,836
|
Tags: dp, greedy
Correct Solution:
```
import sys
#sys.stdin=open("data.txt")
input=sys.stdin.readline
n,a,b=map(int,input().split())
if a<b: a,b=b,a
if b==0:
# 1 01 001 0001 ... is optimal, plus a long series of 0's
print((n-1)*a)
else:
# pascal's triangle thing
pascal=[[1]*20005]
for i in range(20004):
newrow=[1]
for j in range(1,20005):
newrow.append(newrow[-1]+pascal[-1][j])
if newrow[-1]>n: break
pascal.append(newrow)
def getcom(a,b):
# return a+b choose b
# if larger than n, return infinite
if len(pascal[a])>b: return pascal[a][b]
if b==0: return 1
if b==1: return a
return 100000005
# start with the null node (prefix cost 0)
# can split a node into two other nodes with added cost c+a+b
# new nodes have prefix costs c+a, c+b
# want n-1 splits in total
n-=1 # now represents number of splits needed
# binary search the last cost added
lo=0
hi=a*int((n**0.5)*2+5)
while 1:
mid=(lo+hi)//2
# count stuff
c0=0 # < mid
c1=0 # = mid
for i in range(mid//a+1):
j=(mid-i*a)//b
if (mid-i*a)%b!=0:
# c0 += iC0 + (i+1)C1 + (i+2)C2 + ... + (i+j)Cj
for k in range(j+1):
#print(mid,i,k)
c0+=getcom(i,k)
if c0>n: break
else:
for k in range(j):
#print(mid,i,k)
c0+=getcom(i,k)
if c0>n: break
#print(mid,i,j,"c1")
c1+=getcom(i,j)
#print(mid,"is",c0,c1)
if n<c0:
hi=mid-1
elif c0+c1<n:
lo=mid+1
else:
# mid is correct cutoff
lowcost=0 # sum of all cost, where cost < mid
for i in range(mid//a+1):
j=(mid-i*a)//b
if (mid-i*a)%b!=0:
for k in range(j+1):
lowcost+=getcom(i,k)*(i*a+k*b)
else:
for k in range(j):
lowcost+=getcom(i,k)*(i*a+k*b)
temp=lowcost+(n-c0)*mid
print(temp+n*(a+b))
break
```
|
output
| 1
| 10,418
| 6
| 20,837
|
Provide tags and a correct Python 3 solution for this coding contest problem.
R3D3 spent some time on an internship in MDCS. After earning enough money, he decided to go on a holiday somewhere far, far away. He enjoyed suntanning, drinking alcohol-free cocktails and going to concerts of popular local bands. While listening to "The White Buttons" and their hit song "Dacan the Baker", he met another robot for whom he was sure is the love of his life. Well, his summer, at least. Anyway, R3D3 was too shy to approach his potential soulmate, so he decided to write her a love letter. However, he stumbled upon a problem. Due to a terrorist threat, the Intergalactic Space Police was monitoring all letters sent in the area. Thus, R3D3 decided to invent his own alphabet, for which he was sure his love would be able to decipher.
There are n letters in R3D3βs alphabet, and he wants to represent each letter as a sequence of '0' and '1', so that no letterβs sequence is a prefix of another letter's sequence. Since the Intergalactic Space Communications Service has lately introduced a tax for invented alphabets, R3D3 must pay a certain amount of money for each bit in his alphabetβs code (check the sample test for clarifications). He is too lovestruck to think clearly, so he asked you for help.
Given the costs c0 and c1 for each '0' and '1' in R3D3βs alphabet, respectively, you should come up with a coding for the alphabet (with properties as above) with minimum total cost.
Input
The first line of input contains three integers n (2 β€ n β€ 108), c0 and c1 (0 β€ c0, c1 β€ 108) β the number of letters in the alphabet, and costs of '0' and '1', respectively.
Output
Output a single integer β minimum possible total a cost of the whole alphabet.
Example
Input
4 1 2
Output
12
Note
There are 4 letters in the alphabet. The optimal encoding is "00", "01", "10", "11". There are 4 zeroes and 4 ones used, so the total cost is 4Β·1 + 4Β·2 = 12.
|
instruction
| 0
| 10,419
| 6
| 20,838
|
Tags: dp, greedy
Correct Solution:
```
import sys,heapq
#sys.stdin=open("data.txt")
input=sys.stdin.readline
n,a,b=map(int,input().split())
if a<b: a,b=b,a
if b==0:
# 1 01 001 0001 ... is optimal, plus a long series of 0's
print((n-1)*a)
else:
# pascal's triangle thing
pascal=[[1]*20005]
for i in range(20004):
newrow=[1]
for j in range(1,20005):
newrow.append(newrow[-1]+pascal[-1][j])
if newrow[-1]>n: break
pascal.append(newrow)
def getcom(a,b):
# return a+b choose b
# if larger than n, return infinite
if len(pascal[a])>b: return pascal[a][b]
if b==0: return 1
if b==1: return a
return 100000005
# start with the null node (prefix cost 0)
# can split a node into two other nodes with added cost c+a+b
# new nodes have prefix costs c+a, c+b
# want n-1 splits in total
remain=n-1
ans=0
possible=[[a+b,1]] # [c,count]
while 1:
# cost u, v leaves
u,v=heapq.heappop(possible)
while possible and possible[0][0]==u:
v+=possible[0][1]
heapq.heappop(possible)
if remain<=v:
ans+=u*remain
break
ans+=u*v
remain-=v
heapq.heappush(possible,[u+a,v])
heapq.heappush(possible,[u+b,v])
print(ans)
```
|
output
| 1
| 10,419
| 6
| 20,839
|
Provide tags and a correct Python 3 solution for this coding contest problem.
R3D3 spent some time on an internship in MDCS. After earning enough money, he decided to go on a holiday somewhere far, far away. He enjoyed suntanning, drinking alcohol-free cocktails and going to concerts of popular local bands. While listening to "The White Buttons" and their hit song "Dacan the Baker", he met another robot for whom he was sure is the love of his life. Well, his summer, at least. Anyway, R3D3 was too shy to approach his potential soulmate, so he decided to write her a love letter. However, he stumbled upon a problem. Due to a terrorist threat, the Intergalactic Space Police was monitoring all letters sent in the area. Thus, R3D3 decided to invent his own alphabet, for which he was sure his love would be able to decipher.
There are n letters in R3D3βs alphabet, and he wants to represent each letter as a sequence of '0' and '1', so that no letterβs sequence is a prefix of another letter's sequence. Since the Intergalactic Space Communications Service has lately introduced a tax for invented alphabets, R3D3 must pay a certain amount of money for each bit in his alphabetβs code (check the sample test for clarifications). He is too lovestruck to think clearly, so he asked you for help.
Given the costs c0 and c1 for each '0' and '1' in R3D3βs alphabet, respectively, you should come up with a coding for the alphabet (with properties as above) with minimum total cost.
Input
The first line of input contains three integers n (2 β€ n β€ 108), c0 and c1 (0 β€ c0, c1 β€ 108) β the number of letters in the alphabet, and costs of '0' and '1', respectively.
Output
Output a single integer β minimum possible total a cost of the whole alphabet.
Example
Input
4 1 2
Output
12
Note
There are 4 letters in the alphabet. The optimal encoding is "00", "01", "10", "11". There are 4 zeroes and 4 ones used, so the total cost is 4Β·1 + 4Β·2 = 12.
|
instruction
| 0
| 10,420
| 6
| 20,840
|
Tags: dp, greedy
Correct Solution:
```
import sys,heapq
#sys.stdin=open("data.txt")
input=sys.stdin.readline
n,a,b=map(int,input().split())
if a<b: a,b=b,a
if b==0:
# 1 01 001 0001 ... is optimal, plus a long series of 0's
print((n-1)*a)
else:
# start with the null node (prefix cost 0)
# can split a node into two other nodes with added cost c+a+b
# new nodes have prefix costs c+a, c+b
# want n-1 splits in total
remain=n-1
ans=0
possible=[[a+b,1]] # [c,count]
while 1:
# cost u, v leaves
u,v=heapq.heappop(possible)
while possible and possible[0][0]==u:
v+=possible[0][1]
heapq.heappop(possible)
if remain<=v:
ans+=u*remain
break
ans+=u*v
remain-=v
heapq.heappush(possible,[u+a,v])
heapq.heappush(possible,[u+b,v])
print(ans)
```
|
output
| 1
| 10,420
| 6
| 20,841
|
Provide tags and a correct Python 3 solution for this coding contest problem.
After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements:
* There is at least one digit in the string,
* There is at least one lowercase (small) letter of the Latin alphabet in the string,
* There is at least one of three listed symbols in the string: '#', '*', '&'.
<image>
Considering that these are programming classes it is not easy to write the password.
For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one).
During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1.
You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password.
Input
The first line contains two integers n, m (3 β€ n β€ 50, 1 β€ m β€ 50) β the length of the password and the length of strings which are assigned to password symbols.
Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'.
You have such input data that you can always get a valid password.
Output
Print one integer β the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password.
Examples
Input
3 4
1**2
a3*0
c4**
Output
1
Input
5 5
#*&#*
*a1c&
&q2w*
#a3c#
*&#*&
Output
3
Note
In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer.
<image>
In the second test one of possible algorithms will be:
* to move the pointer of the second symbol once to the right.
* to move the pointer of the third symbol twice to the right.
<image>
|
instruction
| 0
| 10,429
| 6
| 20,858
|
Tags: brute force, dp, implementation
Correct Solution:
```
import sys
from itertools import permutations
from operator import itemgetter
def debug(x, table):
for name, val in table.items():
if x is val:
print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
return None
INF = 1000
def solve():
n, m = map(int, input().split())
str_l = []
for i in range(n):
moji = []
line = input()
for c in line:
if c == '*' or c == '#' or c == '&':
moji.append('*')
elif ord('0') <= ord(c) <= ord('9'):
moji.append('1')
else:
moji.append('a')
str_l.append(moji)
# debug(str_l, locals())
row_nums = []
for i in range(n):
kyori = [get_kyori(str_l[i], '1'),
get_kyori(str_l[i], 'a'),
get_kyori(str_l[i], '*')]
row_nums.append(kyori)
ans = INF
debug(row_nums, locals())
for i, j, k in permutations((0,1,2)):
tmp = 0
kyori_c = row_nums.copy()
kyori_c.sort(key=itemgetter(i))
tmp += kyori_c[0][i]
kyori_c = kyori_c[1:]
kyori_c.sort(key=itemgetter(j))
tmp += kyori_c[0][j]
kyori_c = kyori_c[1:]
kyori_c.sort(key=itemgetter(k))
tmp += kyori_c[0][k]
ans = min(tmp, ans)
print(ans)
def get_kyori(str1, c):
res = INF
if c in str1:
i1 = str1.index(c)
if i1 > len(str1) // 2:
i1 = len(str1) - i1
i2 = len(str1) - str1[::-1].index(c)
if i2 > len(str1) // 2:
i2 = len(str1) - i2 + 1
res = min(i1, i2)
return res
if __name__ == '__main__':
solve()
```
|
output
| 1
| 10,429
| 6
| 20,859
|
Provide tags and a correct Python 3 solution for this coding contest problem.
After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements:
* There is at least one digit in the string,
* There is at least one lowercase (small) letter of the Latin alphabet in the string,
* There is at least one of three listed symbols in the string: '#', '*', '&'.
<image>
Considering that these are programming classes it is not easy to write the password.
For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one).
During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1.
You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password.
Input
The first line contains two integers n, m (3 β€ n β€ 50, 1 β€ m β€ 50) β the length of the password and the length of strings which are assigned to password symbols.
Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'.
You have such input data that you can always get a valid password.
Output
Print one integer β the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password.
Examples
Input
3 4
1**2
a3*0
c4**
Output
1
Input
5 5
#*&#*
*a1c&
&q2w*
#a3c#
*&#*&
Output
3
Note
In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer.
<image>
In the second test one of possible algorithms will be:
* to move the pointer of the second symbol once to the right.
* to move the pointer of the third symbol twice to the right.
<image>
|
instruction
| 0
| 10,430
| 6
| 20,860
|
Tags: brute force, dp, implementation
Correct Solution:
```
import itertools
def transform_char(char):
if char in ('#', '&', '*'):
return '*'
elif char.isdigit():
return '0'
else:
return 'a'
def transform(string):
ans = ''.join(transform_char(char) for char in string)
return ans
#input
n, m = (int(x) for x in input().split())
symbols = []
for i in range(n):
symbols.append(list(transform(input())))
sym1 = [ '#', '*', '&']
# sym2 = set(list('1234567890'))
# sym3 = set(list(string.ascii_lowercase))
# print(len(sym3))
min_shifts = 10000
for permutation in itertools.permutations(symbols, 3):
s1, s2, s3 = permutation
sh1, sh2, sh3 = (100, 100, 100)
for i in range((m + 2) // 2):
if (s1[i] == '*' or s1[-i] == '*'):
sh1 = min(sh1, i)
if (s2[i] == '0' or s2[-i] == '0'):
sh2 = min(sh2, i)
if (s3[i] == 'a' or s3[-i] == 'a'):
sh3 = min(sh3, i)
min_shifts = min(min_shifts, (sh1 + sh2 + sh3))
print(min_shifts)
```
|
output
| 1
| 10,430
| 6
| 20,861
|
Provide tags and a correct Python 3 solution for this coding contest problem.
After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements:
* There is at least one digit in the string,
* There is at least one lowercase (small) letter of the Latin alphabet in the string,
* There is at least one of three listed symbols in the string: '#', '*', '&'.
<image>
Considering that these are programming classes it is not easy to write the password.
For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one).
During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1.
You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password.
Input
The first line contains two integers n, m (3 β€ n β€ 50, 1 β€ m β€ 50) β the length of the password and the length of strings which are assigned to password symbols.
Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'.
You have such input data that you can always get a valid password.
Output
Print one integer β the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password.
Examples
Input
3 4
1**2
a3*0
c4**
Output
1
Input
5 5
#*&#*
*a1c&
&q2w*
#a3c#
*&#*&
Output
3
Note
In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer.
<image>
In the second test one of possible algorithms will be:
* to move the pointer of the second symbol once to the right.
* to move the pointer of the third symbol twice to the right.
<image>
|
instruction
| 0
| 10,431
| 6
| 20,862
|
Tags: brute force, dp, implementation
Correct Solution:
```
import itertools
#input
n, m = (int(x) for x in input().split())
symbols = []
for i in range(n):
symbols.append(input())
sym1 = set([ '#', '*', '&'])
sym2 = set(list('1234567890'))
sym3 = set(list('qwertyuiopasdfghjklzxcvbnm'))
# print(len(sym3))
min_shifts = 10000
for permutation in itertools.permutations(symbols, 3):
s1, s2, s3 = permutation
sh1, sh2, sh3 = (100, 100, 100)
for i in range(m):
if (s1[i] in sym1 or s1[-i] in sym1):
sh1 = min(sh1, i)
if (s2[i] in sym2 or s2[-i] in sym2):
sh2 = min(sh2, i)
if (s3[i] in sym3 or s3[-i] in sym3):
sh3 = min(sh3, i)
min_shifts = min(min_shifts, (sh1 + sh2 + sh3))
print(min_shifts)
```
|
output
| 1
| 10,431
| 6
| 20,863
|
Provide tags and a correct Python 3 solution for this coding contest problem.
After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements:
* There is at least one digit in the string,
* There is at least one lowercase (small) letter of the Latin alphabet in the string,
* There is at least one of three listed symbols in the string: '#', '*', '&'.
<image>
Considering that these are programming classes it is not easy to write the password.
For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one).
During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1.
You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password.
Input
The first line contains two integers n, m (3 β€ n β€ 50, 1 β€ m β€ 50) β the length of the password and the length of strings which are assigned to password symbols.
Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'.
You have such input data that you can always get a valid password.
Output
Print one integer β the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password.
Examples
Input
3 4
1**2
a3*0
c4**
Output
1
Input
5 5
#*&#*
*a1c&
&q2w*
#a3c#
*&#*&
Output
3
Note
In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer.
<image>
In the second test one of possible algorithms will be:
* to move the pointer of the second symbol once to the right.
* to move the pointer of the third symbol twice to the right.
<image>
|
instruction
| 0
| 10,432
| 6
| 20,864
|
Tags: brute force, dp, implementation
Correct Solution:
```
n,m=map(int,input().split())
c=[list([])for i in range(3)]
for i in range(n):
t=input()
s=''
for i in range(m):
if ord(t[i])<43:s+='1'
elif ord(t[i])<59:s+='2'
else: s+='3'
x1=s.find('1') if s.find('1') != -1 else 60
x2=s[::-1].find('1')+1 if s.find('1') != -1 else 60
y1=s.find('2') if s.find('2') != -1 else 60
y2=s[::-1].find('2')+1 if s.find('2') != -1 else 60
z1=s.find('3') if s.find('3') != -1 else 60
z2=s[::-1].find('3')+1 if s.find('3') != -1 else 60
x,y,z=min(x1,x2),min(y1,y2),min(z1,z2)
c[0].append(x)
c[1].append(y)
c[2].append(z)
a=[list([])for i in range(3)]
j=0
for i in c:
for _ in range(3):
t=min(i)
s=i.index(t)
c[j][s]=60
a[j].append([s,t])
j+=1
ans=10**10
for i in range(3):
for j in range(3):
for k in range(3):
x,y,z=a[0][i],a[1][j],a[2][k]
if len(set([x[0],y[0],z[0]]))!=3:continue
ans=min(ans,x[1]+y[1]+z[1])
print(ans)
```
|
output
| 1
| 10,432
| 6
| 20,865
|
Provide tags and a correct Python 3 solution for this coding contest problem.
After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements:
* There is at least one digit in the string,
* There is at least one lowercase (small) letter of the Latin alphabet in the string,
* There is at least one of three listed symbols in the string: '#', '*', '&'.
<image>
Considering that these are programming classes it is not easy to write the password.
For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one).
During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1.
You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password.
Input
The first line contains two integers n, m (3 β€ n β€ 50, 1 β€ m β€ 50) β the length of the password and the length of strings which are assigned to password symbols.
Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'.
You have such input data that you can always get a valid password.
Output
Print one integer β the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password.
Examples
Input
3 4
1**2
a3*0
c4**
Output
1
Input
5 5
#*&#*
*a1c&
&q2w*
#a3c#
*&#*&
Output
3
Note
In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer.
<image>
In the second test one of possible algorithms will be:
* to move the pointer of the second symbol once to the right.
* to move the pointer of the third symbol twice to the right.
<image>
|
instruction
| 0
| 10,433
| 6
| 20,866
|
Tags: brute force, dp, implementation
Correct Solution:
```
n, m = map(int, input().split())
a = [0] * n
for i in range(n):
a[i] = list(input())
g1 = '*#&'
g2 = 'qwertyuiopasdfghjklzxcvbnm'
g3 = '1234567890'
b = [[-1] * 3 for i in range(n)]
for i in range(n):
f1, f2, f3 = 0, 0, 0
for j in range(m):
if a[i][j] in g1 and f1 == 0:
f1 = 1
b[i][0] = j
elif a[i][j] in g2 and f2 == 0:
f2 = 1
b[i][1] = j
elif a[i][j] in g3 and f3 == 0:
f3 = 1
b[i][2] = j
f1, f2, f3 = 0, 0, 0
for j in range(-1, -1 * m, -1):
if a[i][j] in g1 and f1 == 0:
f1 = 1
b[i][0] = min(b[i][0], -1 * j )
elif a[i][j] in g2 and f2 == 0:
f2 = 1
b[i][1] = min(b[i][1], -1 * j )
elif a[i][j] in g3 and f3 == 0:
f3 = 1
b[i][2] = min(b[i][2], -1 * j)
ans = int(1e9)
for i in range(n):
for j in range(n):
for k in range(n):
if i == j or j == k or i == k:
continue
#print(i, j, k)
for l in range(3):
for g in range(3):
for q in range(3):
if q != l and l != g and q != g and b[i][l] + b[j][g] + b[k][q] < ans and b[i][l] != -1 and b[j][g] != -1 and b[k][q] != -1:
ans = b[i][l] + b[j][g] + b[k][q]
#print(ans, i, j, k, l, g, q)
print(ans)
```
|
output
| 1
| 10,433
| 6
| 20,867
|
Provide tags and a correct Python 3 solution for this coding contest problem.
After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements:
* There is at least one digit in the string,
* There is at least one lowercase (small) letter of the Latin alphabet in the string,
* There is at least one of three listed symbols in the string: '#', '*', '&'.
<image>
Considering that these are programming classes it is not easy to write the password.
For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one).
During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1.
You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password.
Input
The first line contains two integers n, m (3 β€ n β€ 50, 1 β€ m β€ 50) β the length of the password and the length of strings which are assigned to password symbols.
Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'.
You have such input data that you can always get a valid password.
Output
Print one integer β the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password.
Examples
Input
3 4
1**2
a3*0
c4**
Output
1
Input
5 5
#*&#*
*a1c&
&q2w*
#a3c#
*&#*&
Output
3
Note
In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer.
<image>
In the second test one of possible algorithms will be:
* to move the pointer of the second symbol once to the right.
* to move the pointer of the third symbol twice to the right.
<image>
|
instruction
| 0
| 10,434
| 6
| 20,868
|
Tags: brute force, dp, implementation
Correct Solution:
```
n, m = [int(i) for i in input().split()]
inf = 10 ** 18
fl = [inf] * n
fn = [inf] * n
fs = [inf] * n
for i in range(n):
s = input()
for q in range(m):
if s[q] >= '0' and s[q] <= '9' and fn[i] == inf:
fn[i] = q
if s[q] >= 'a' and s[q] <= 'z' and fl[i] == inf:
fl[i] = q
if s[q] in ['#', '*', '&'] and fs[i] == inf:
fs[i] = q
for q in range(m - 1, -1, -1):
if s[q] >= '0' and s[q] <= '9':
fn[i] = min(fn[i], m - q)
if s[q] >= 'a' and s[q] <= 'z':
fl[i] = min(fl[i], m - q)
if s[q] in ['#', '*', '&']:
fs[i] = min(fs[i], m - q)
ans = inf
for i in range(n):
for q in range(n):
if i == q:
continue
for j in range(n):
if i == j or q == j:
continue
ans = min(ans, fn[i] + fl[q] + fs[j])
print(ans)
```
|
output
| 1
| 10,434
| 6
| 20,869
|
Provide tags and a correct Python 3 solution for this coding contest problem.
After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements:
* There is at least one digit in the string,
* There is at least one lowercase (small) letter of the Latin alphabet in the string,
* There is at least one of three listed symbols in the string: '#', '*', '&'.
<image>
Considering that these are programming classes it is not easy to write the password.
For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one).
During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1.
You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password.
Input
The first line contains two integers n, m (3 β€ n β€ 50, 1 β€ m β€ 50) β the length of the password and the length of strings which are assigned to password symbols.
Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'.
You have such input data that you can always get a valid password.
Output
Print one integer β the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password.
Examples
Input
3 4
1**2
a3*0
c4**
Output
1
Input
5 5
#*&#*
*a1c&
&q2w*
#a3c#
*&#*&
Output
3
Note
In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer.
<image>
In the second test one of possible algorithms will be:
* to move the pointer of the second symbol once to the right.
* to move the pointer of the third symbol twice to the right.
<image>
|
instruction
| 0
| 10,435
| 6
| 20,870
|
Tags: brute force, dp, implementation
Correct Solution:
```
read = lambda: map(int, input().split())
n, m = read()
a = [input() for i in range(n)]
c1 = '1234567890'
c2 = 'qwertyuiopasdfghjklzxcvbnm'
c3 = '#&*'
inf = 10 ** 20
l1 = [inf] * n
l2 = [inf] * n
l3 = [inf] * n
for i in range(n):
for j in range(m):
if a[i][j] in c1: l1[i] = min(l1[i], j, m - j)
if a[i][j] in c2: l2[i] = min(l2[i], j, m - j)
if a[i][j] in c3: l3[i] = min(l3[i], j, m - j)
ans = inf
for i in range(n):
for j in range(n):
for k in range(n):
if len({i, j, k}) < 3: continue
cur = l1[i] + l2[j] + l3[k]
ans = min(ans, cur)
print(ans)
```
|
output
| 1
| 10,435
| 6
| 20,871
|
Provide tags and a correct Python 3 solution for this coding contest problem.
After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements:
* There is at least one digit in the string,
* There is at least one lowercase (small) letter of the Latin alphabet in the string,
* There is at least one of three listed symbols in the string: '#', '*', '&'.
<image>
Considering that these are programming classes it is not easy to write the password.
For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one).
During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1.
You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password.
Input
The first line contains two integers n, m (3 β€ n β€ 50, 1 β€ m β€ 50) β the length of the password and the length of strings which are assigned to password symbols.
Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'.
You have such input data that you can always get a valid password.
Output
Print one integer β the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password.
Examples
Input
3 4
1**2
a3*0
c4**
Output
1
Input
5 5
#*&#*
*a1c&
&q2w*
#a3c#
*&#*&
Output
3
Note
In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer.
<image>
In the second test one of possible algorithms will be:
* to move the pointer of the second symbol once to the right.
* to move the pointer of the third symbol twice to the right.
<image>
|
instruction
| 0
| 10,436
| 6
| 20,872
|
Tags: brute force, dp, implementation
Correct Solution:
```
n,m=map(int,input().split())
a=[]
for i in range(65,91):
a.append(chr(i+32))
b=[]
f1=0
f2=0
f3=0
for i in range(0,10):
b.append(str(i))
c=['*','#','&']
l=[]
s=[]
l1=[1000000000 for i in range(n)]
l2=[1000000000 for i in range(n)]
l3=[1000000000 for i in range(n)]
f=[1 for i in range(n)]
ff1=0
ff2=0
ff3=0
for i in range(n):
l.append(list(str(input())))
s+=l[i][0]
if s[i] in a:
ff1+=1
elif s[i] in b:
ff2+=1
else:
ff3+=1
for i in range(n):
if ff1==1:
if l[i][0] in a:
f[i]=0
elif ff2==1:
if l[i][0] in b:
f[i]=0
elif ff3==1:
if l[i][0] in c:
f[i]=0
for i in range(n):
for j in range(m):
if l[i][j] in a and f[i]:
l1[i]=min(l1[i],j,m-j)
for j in range(m):
if l[i][j] in b and f[i]:
l2[i]=min(l2[i],j,m-j)
for j in range(m):
if l[i][j] in c and f[i]:
l3[i]=min(l3[i],j,m-j)
for i in range(26):
if chr(i+97) in s:
f1=1
for i in range(10):
if b[i] in s:
f2=1
for i in range(3):
if c[i] in s:
f3=1
#print(l1,l2,l3)
#print(f1,f2,f3)
if f1+f2+f3==3:
print(0)
exit()
elif f1+f2+f3==2:
if f1==0:
print(min(l1))
elif f2==0:
print(min(l2))
else:
print(min(l3))
else:
if f1==1:
ans=20*m
for i in range(n):
for j in range(n):
if i!=j and l2[i]<=1000 and l3[j]<=1000:
ans=min(ans,l2[i]+l3[j])
elif f2==1:
ans=20*m
for i in range(n):
for j in range(n):
if i!=j and l1[i]<=1000 and l3[j]<=1000:
ans=min(ans,l1[i]+l3[j])
elif f3==1:
ans=20*m
for i in range(n):
for j in range(n):
if i!=j and l1[i]<=1000 and l2[j]<=1000:
ans=min(ans,l1[i]+l2[j])
print(ans)
```
|
output
| 1
| 10,436
| 6
| 20,873
|
Provide tags and a correct Python 3 solution for this coding contest problem.
During a normal walk in the forest, Katie has stumbled upon a mysterious code! However, the mysterious code had some characters unreadable. She has written down this code as a string c consisting of lowercase English characters and asterisks ("*"), where each of the asterisks denotes an unreadable character. Excited with her discovery, Katie has decided to recover the unreadable characters by replacing each asterisk with arbitrary lowercase English letter (different asterisks might be replaced with different letters).
Katie has a favorite string s and a not-so-favorite string t and she would love to recover the mysterious code so that it has as many occurrences of s as possible and as little occurrences of t as possible. Formally, let's denote f(x, y) as the number of occurrences of y in x (for example, f(aababa, ab) = 2). Katie wants to recover the code c' conforming to the original c, such that f(c', s) - f(c', t) is largest possible. However, Katie is not very good at recovering codes in general, so she would like you to help her out.
Input
The first line contains string c (1 β€ |c| β€ 1000) β the mysterious code . It is guaranteed that c consists of lowercase English characters and asterisks "*" only.
The second and third line contain strings s and t respectively (1 β€ |s|, |t| β€ 50, s β t). It is guaranteed that s and t consist of lowercase English characters only.
Output
Print a single integer β the largest possible value of f(c', s) - f(c', t) of the recovered code.
Examples
Input
*****
katie
shiro
Output
1
Input
caat
caat
a
Output
-1
Input
*a*
bba
b
Output
0
Input
***
cc
z
Output
2
Note
In the first example, for c' equal to "katie" f(c', s) = 1 and f(c', t) = 0, which makes f(c', s) - f(c', t) = 1 which is the largest possible.
In the second example, the only c' conforming to the given c is "caat". The corresponding f(c', s) - f(c', t) = 1 - 2 = -1.
In the third example, there are multiple ways to recover the code such that f(c', s) - f(c', t) is largest possible, for example "aaa", "aac", or even "zaz". The value of f(c', s) - f(c', t) = 0 for all of these recovered codes.
In the fourth example, the optimal recovered code c' would be "ccc". The corresponding f(c', s) - f(c', t) = 2.
|
instruction
| 0
| 10,866
| 6
| 21,732
|
Tags: dp, strings
Correct Solution:
```
import sys
from array import array # noqa: F401
from typing import List, Tuple, TypeVar, Generic, Sequence, Union # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
def build_next_table(s):
s = '*' + s + '*'
n = len(s) - 1
kmp = [0] * (n + 1)
next_table = [[0] * 26 for _ in range(n + 1)]
for i in range(2, n + 1):
cur = kmp[i - 1]
while cur > 0 and s[cur + 1] != s[i]:
cur = kmp[cur]
if s[cur + 1] == s[i]:
cur += 1
kmp[i] = cur
alphabet = [chr(cc) for cc in range(97, 123)]
for i in range(n):
for j, c in enumerate(alphabet):
cur = i
while 0 < cur and s[cur + 1] != c:
cur = kmp[cur]
if s[cur + 1] == c:
cur += 1
next_table[i][j] = cur
return next_table
def main():
code = input().rstrip()
s, t = input().rstrip(), input().rstrip()
table_s = build_next_table(s)
table_t = build_next_table(t)
n, m, l = len(code), len(s), len(t)
minf = -10**9
dp = [[array('i', [minf]) * (l + 1) for _ in range(m + 1)] for _ in range(n + 1)]
dp[0][0][0] = 0
alphabet = list(range(26))
for i in range(n):
itr = [ord(code[i]) - 97] if code[i] != '*' else alphabet
for j in range(m + 1):
for k in range(l + 1):
for cc in itr:
nj, nk = table_s[j][cc], table_t[k][cc]
dp[i + 1][nj][nk] = max(dp[i + 1][nj][nk], dp[i][j][k] + (1 if nj == m else 0) - (1 if nk == l else 0))
ans = minf
for j in range(m + 1):
for k in range(l + 1):
ans = max(ans, dp[n][j][k])
print(ans)
if __name__ == '__main__':
main()
```
|
output
| 1
| 10,866
| 6
| 21,733
|
Provide tags and a correct Python 3 solution for this coding contest problem.
One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords β strings, consists of small Latin letters.
Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows:
* two passwords a and b are equivalent if there is a letter, that exists in both a and b;
* two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b.
If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.
For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if:
* admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab";
* admin's password is "d", then you can access to system by using only "d".
Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system.
Input
The first line contain integer n (1 β€ n β€ 2 β
10^5) β number of passwords in the list. Next n lines contains passwords from the list β non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal.
It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters.
Output
In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system.
Examples
Input
4
a
b
ab
d
Output
2
Input
3
ab
bc
abc
Output
1
Input
1
codeforces
Output
1
Note
In the second example hacker need to use any of the passwords to access the system.
|
instruction
| 0
| 10,877
| 6
| 21,754
|
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
from sys import stdin,stdout
from collections import defaultdict as df
import sys
sys.setrecursionlimit(10**4)
def dfs(i):
visited[i]=True
for j in d1[p[i]]:
if visited[d[j]]==False:
dfs(d[j])
d=dict()
j=0
p=dict()
for i in range(97,97+26):
d[chr(i)]=j
p[j]=chr(i)
j+=1
d1=df(set)
gota=0
hot=dict()
mota=set()
n=int(stdin.readline())
y=set()
for ii in range(n):
s=stdin.readline().rstrip()
if s in hot:
continue
else:
hot[s]=1
s=[i for i in s]
s=list(set(s))
for i in s:
y.add(i)
for i in range(len(s)):
if len(d1[s[i]])==25:
continue
for j in range(i+1,len(s)):
if i==j:
continue
else:
d1[s[i]].add(s[j])
d1[s[j]].add(s[i])
visited=[0]*26
count=0
for i in range(26):
if visited[i]==False and p[i] in y:
count+=1
dfs(i)
stdout.write(str(count))
```
|
output
| 1
| 10,877
| 6
| 21,755
|
Provide tags and a correct Python 3 solution for this coding contest problem.
One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords β strings, consists of small Latin letters.
Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows:
* two passwords a and b are equivalent if there is a letter, that exists in both a and b;
* two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b.
If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.
For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if:
* admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab";
* admin's password is "d", then you can access to system by using only "d".
Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system.
Input
The first line contain integer n (1 β€ n β€ 2 β
10^5) β number of passwords in the list. Next n lines contains passwords from the list β non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal.
It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters.
Output
In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system.
Examples
Input
4
a
b
ab
d
Output
2
Input
3
ab
bc
abc
Output
1
Input
1
codeforces
Output
1
Note
In the second example hacker need to use any of the passwords to access the system.
|
instruction
| 0
| 10,878
| 6
| 21,756
|
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
from sys import stdin
input = stdin.readline
if __name__ == '__main__':
pdct = {}
for _ in range(int(input())):
s = input().strip()
for c in s:
if c not in pdct:
pdct[c] = c
l = list(filter(lambda o: pdct[o] != o, s))
if not l:
p = s[0]
else:
p = l[0]
while pdct[p] != p:
p = pdct[p]
for c in s:
cc = c
while pdct[cc] != cc:
cc = pdct[cc]
pdct[cc] = p
cnt = 0
for k, v in pdct.items():
cnt += int(k == v)
print(cnt)
```
|
output
| 1
| 10,878
| 6
| 21,757
|
Provide tags and a correct Python 3 solution for this coding contest problem.
One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords β strings, consists of small Latin letters.
Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows:
* two passwords a and b are equivalent if there is a letter, that exists in both a and b;
* two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b.
If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.
For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if:
* admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab";
* admin's password is "d", then you can access to system by using only "d".
Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system.
Input
The first line contain integer n (1 β€ n β€ 2 β
10^5) β number of passwords in the list. Next n lines contains passwords from the list β non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal.
It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters.
Output
In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system.
Examples
Input
4
a
b
ab
d
Output
2
Input
3
ab
bc
abc
Output
1
Input
1
codeforces
Output
1
Note
In the second example hacker need to use any of the passwords to access the system.
|
instruction
| 0
| 10,879
| 6
| 21,758
|
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
def union(x, y):
xr = find(x)
yr = find(y)
root[yr] = xr
def find(x):
if root[x] != x:
x = find(root[x])
return x
import sys
input = sys.stdin.readline
used = set()
root = dict()
for _ in range(int(input())):
s = input().rstrip()
for j in s:
if ord(j) - 97 not in root:
root[ord(j) - 97] = ord(j) - 97
union(ord(s[0]) - 97, ord(j) - 97)
for i in root:
used.add(find(root[i]))
print(used.__len__())
```
|
output
| 1
| 10,879
| 6
| 21,759
|
Provide tags and a correct Python 3 solution for this coding contest problem.
One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords β strings, consists of small Latin letters.
Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows:
* two passwords a and b are equivalent if there is a letter, that exists in both a and b;
* two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b.
If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.
For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if:
* admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab";
* admin's password is "d", then you can access to system by using only "d".
Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system.
Input
The first line contain integer n (1 β€ n β€ 2 β
10^5) β number of passwords in the list. Next n lines contains passwords from the list β non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal.
It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters.
Output
In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system.
Examples
Input
4
a
b
ab
d
Output
2
Input
3
ab
bc
abc
Output
1
Input
1
codeforces
Output
1
Note
In the second example hacker need to use any of the passwords to access the system.
|
instruction
| 0
| 10,880
| 6
| 21,760
|
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
from collections import deque
from sys import stdin, stdout
read, whrite = stdin.readline, stdout.write
g = [[] for i in range(300000)]
visited = [False] * 300000
def dfs(i):
pilha = deque()
pilha.append(i)
visited[i] = 1
while pilha:
i = pilha.pop()
for v in g[i]:
if not visited[v]:
visited[v] = True
pilha.append(v)
n = int(read())
for i in range(n):
word = read().strip()
for j in word:
g[i].append(n + ord(j))
g[n + ord(j)].append(i)
resp = 0
for i in range(n):
if not visited[i]:
dfs(i)
resp += 1
print(resp)
```
|
output
| 1
| 10,880
| 6
| 21,761
|
Provide tags and a correct Python 3 solution for this coding contest problem.
One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords β strings, consists of small Latin letters.
Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows:
* two passwords a and b are equivalent if there is a letter, that exists in both a and b;
* two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b.
If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.
For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if:
* admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab";
* admin's password is "d", then you can access to system by using only "d".
Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system.
Input
The first line contain integer n (1 β€ n β€ 2 β
10^5) β number of passwords in the list. Next n lines contains passwords from the list β non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal.
It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters.
Output
In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system.
Examples
Input
4
a
b
ab
d
Output
2
Input
3
ab
bc
abc
Output
1
Input
1
codeforces
Output
1
Note
In the second example hacker need to use any of the passwords to access the system.
|
instruction
| 0
| 10,881
| 6
| 21,762
|
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
import math
from decimal import Decimal
from decimal import *
from collections import defaultdict, deque
import heapq
from decimal import Decimal
getcontext().prec = 25
abcd='abcdefghijklmnopqrstuvwxyz'
MOD = pow(10, 9) + 7
BUFSIZE = 8192
from bisect import bisect_left, bisect_right
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")
# n, k = map(int, input().split(" "))
# list(map(int, input().split(" ")))
# for _ in range(int(input())):
def dfs(i):
q = deque()
q.append(i)
while q:
x = q.popleft()
if not v[x]:
v[x]=True
for f in g[x]:
if not v[f]:
q.append(f)
n = int(input())
g = [set() for i in range(26)]
for i in range(n):
a = set(list(input()))
for j in a:
for k in a:
g[ord(k)-ord("a")].add(ord(j)-ord("a"))
v = [0]*26
ans = 0
for i in range(26):
if not v[i]:
if g[i]:
dfs(i)
ans+=1
else:
v[i]=True
print(ans)
```
|
output
| 1
| 10,881
| 6
| 21,763
|
Provide tags and a correct Python 3 solution for this coding contest problem.
One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords β strings, consists of small Latin letters.
Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows:
* two passwords a and b are equivalent if there is a letter, that exists in both a and b;
* two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b.
If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.
For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if:
* admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab";
* admin's password is "d", then you can access to system by using only "d".
Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system.
Input
The first line contain integer n (1 β€ n β€ 2 β
10^5) β number of passwords in the list. Next n lines contains passwords from the list β non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal.
It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters.
Output
In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system.
Examples
Input
4
a
b
ab
d
Output
2
Input
3
ab
bc
abc
Output
1
Input
1
codeforces
Output
1
Note
In the second example hacker need to use any of the passwords to access the system.
|
instruction
| 0
| 10,882
| 6
| 21,764
|
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
## necessary imports
import sys
input = sys.stdin.readline
from math import ceil, floor, factorial;
# swap_array function
def swaparr(arr, a,b):
temp = arr[a];
arr[a] = arr[b];
arr[b] = temp
## gcd function
def gcd(a,b):
if a == 0:
return b
return gcd(b%a, a)
## nCr function efficient using Binomial Cofficient
def nCr(n, k):
if(k > n - k):
k = n - k
res = 1
for i in range(k):
res = res * (n - i)
res = res / (i + 1)
return int(res)
## upper bound function code -- such that e in a[:i] e < x;
def upper_bound(a, x, lo=0):
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if a[mid] < x:
lo = mid+1
else:
hi = mid
return lo
## prime factorization
def primefs(n):
## if n == 1 ## calculating primes
primes = {}
while(n%2 == 0 and n > 0):
primes[2] = primes.get(2, 0) + 1
n = n//2
for i in range(3, int(n**0.5)+2, 2):
while(n%i == 0 and n > 0):
primes[i] = primes.get(i, 0) + 1
n = n//i
if n > 2:
primes[n] = primes.get(n, 0) + 1
## prime factoriazation of n is stored in dictionary
## primes and can be accesed. O(sqrt n)
return primes
## MODULAR EXPONENTIATION FUNCTION
def power(x, y, p):
res = 1
x = x % p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) :
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
temp = a
a = b
b = temp
return a,b
# find function with path compression included (recursive)
# def find(x, link):
# if link[x] == x:
# return x
# link[x] = find(link[x], link);
# return link[x];
# find function with path compression (ITERATIVE)
def find(x, link):
p = x;
while( p != link[p]):
p = link[p];
while( x != p):
nex = link[x];
link[x] = p;
x = nex;
return p;
# the union function which makes union(x,y)
# of two nodes x and y
def union(x, y, link, size):
x = find(x, link)
y = find(y, link)
if size[x] < size[y]:
x,y = swap(x,y)
if x != y:
size[x] += size[y]
link[y] = x
## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
def sieve(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e7 + 5)
def spf_sieve():
spf[1] = 1;
for i in range(2, MAXN):
spf[i] = i;
for i in range(4, MAXN, 2):
spf[i] = 2;
for i in range(3, ceil(MAXN ** 0.5), 2):
if spf[i] == i:
for j in range(i*i, MAXN, i):
if spf[j] == j:
spf[j] = i;
## function for storing smallest prime factors (spf) in the array
################## un-comment below 2 lines when using factorization #################
# spf = [0 for i in range(MAXN)]
# spf_sieve()
def factoriazation(x):
ret = {};
while x != 1:
ret[spf[x]] = ret.get(spf[x], 0) + 1;
x = x//spf[x]
return ret
## this function is useful for multiple queries only, o/w use
## primefs function above. complexity O(log n)
## taking integer array input
def int_array():
return list(map(int, input().strip().split()))
## taking string array input
def str_array():
return input().strip().split();
#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');
################### ---------------- TEMPLATE ENDS HERE ---------------- ###################
n = int(input()); s = [];
for _ in range(n):
s.append(set(list(input().strip())));
link = [i for i in range(n)]; size = [1]*n;
for i in range(97, 97 + 26):
x = chr(i); inds = [];
for i in range(n):
if x in s[i]:
inds.append(i);
for j in range(len(inds) - 1):
union(inds[j], inds[j+1], link, size);
ans = set();
for i in range(n):
ans.add(find(link[i], link));
print(len(ans));
```
|
output
| 1
| 10,882
| 6
| 21,765
|
Provide tags and a correct Python 3 solution for this coding contest problem.
One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords β strings, consists of small Latin letters.
Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows:
* two passwords a and b are equivalent if there is a letter, that exists in both a and b;
* two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b.
If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.
For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if:
* admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab";
* admin's password is "d", then you can access to system by using only "d".
Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system.
Input
The first line contain integer n (1 β€ n β€ 2 β
10^5) β number of passwords in the list. Next n lines contains passwords from the list β non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal.
It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters.
Output
In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system.
Examples
Input
4
a
b
ab
d
Output
2
Input
3
ab
bc
abc
Output
1
Input
1
codeforces
Output
1
Note
In the second example hacker need to use any of the passwords to access the system.
|
instruction
| 0
| 10,883
| 6
| 21,766
|
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
import sys
input = sys.stdin.readline
def union(a,b):
xa=find(a)
xb=find(b)
if xa!=xb:
if size[xa]>=size[xb]:
parent[xb]=xa
size[xa]+=size[xb]
else:
parent[xa]=xb
size[xb]+=size[xa]
def find(a):
if parent[a]==a:
return a
parent[a]=find(parent[a])
return parent[a]
n=int(input())
p=[]
for i in range(n):
p.append(set(input()))
parent=[0]*(n+26)
for i in range(n+26):
parent[i]=i
size=[1]*(n+26)
for i in range(26):
for j in range(n):
if chr(97+i) in p[j]:
union(i,j+26)
ans=set()
for i in range(26,n+26):
x=find(i)
ans.add(x)
print(len(ans))
```
|
output
| 1
| 10,883
| 6
| 21,767
|
Provide tags and a correct Python 3 solution for this coding contest problem.
One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords β strings, consists of small Latin letters.
Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows:
* two passwords a and b are equivalent if there is a letter, that exists in both a and b;
* two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b.
If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.
For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if:
* admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab";
* admin's password is "d", then you can access to system by using only "d".
Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system.
Input
The first line contain integer n (1 β€ n β€ 2 β
10^5) β number of passwords in the list. Next n lines contains passwords from the list β non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal.
It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters.
Output
In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system.
Examples
Input
4
a
b
ab
d
Output
2
Input
3
ab
bc
abc
Output
1
Input
1
codeforces
Output
1
Note
In the second example hacker need to use any of the passwords to access the system.
|
instruction
| 0
| 10,884
| 6
| 21,768
|
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
def union(x, y):
xr = find(x)
yr = find(y)
root[xr] = yr
def find(x):
while root[x] != x:
x = root[x]
return x
import sys
input = sys.stdin.readline
used = set()
root = dict()
for _ in range(int(input())):
s = input().rstrip()
for j in s:
if ord(j) - 97 not in root:
root[ord(j) - 97] = ord(j) - 97
union(ord(s[0]) - 97, ord(j) - 97)
for i in root:
used.add(find(root[i]))
print(len(used))
```
|
output
| 1
| 10,884
| 6
| 21,769
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.
Gildong loves this concept so much, so he wants to play with it. He has n distinct strings of equal length m. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.
Input
The first line contains two integers n and m (1 β€ n β€ 100, 1 β€ m β€ 50) β the number of strings and the length of each string.
Next n lines contain a string of length m each, consisting of lowercase Latin letters only. All strings are distinct.
Output
In the first line, print the length of the longest palindrome string you made.
In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.
Examples
Input
3 3
tab
one
bat
Output
6
tabbat
Input
4 2
oo
ox
xo
xx
Output
6
oxxxxo
Input
3 5
hello
codef
orces
Output
0
Input
9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
Output
20
ababwxyzijjizyxwbaba
Note
In the first example, "battab" is also a valid answer.
In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.
In the third example, the empty string is the only valid palindrome string.
|
instruction
| 0
| 10,893
| 6
| 21,786
|
Tags: brute force, constructive algorithms, greedy, implementation, strings
Correct Solution:
```
import sys
import math
import heapq
import collections
def inputnum():
return(int(input()))
def inputnums():
return(map(int,input().split()))
def inputlist():
return(list(map(int,input().split())))
def inputstring():
return([x for x in input()])
def inputstringnum():
return([ord(x)-ord('a') for x in input()])
def inputmatrixchar(rows):
arr2d = [[j for j in input().strip()] for i in range(rows)]
return arr2d
def inputmatrixint(rows):
arr2d = []
for _ in range(rows):
arr2d.append([int(i) for i in input().split()])
return arr2d
def isPalindrome(s):
return s == s[::-1]
def check(s1, s2):
return s1 == s2[::-1]
n, m = inputnums()
a = []
for i in range(n):
s = input()
a.append(s)
front = ""
back = ""
for i in range(len(a)):
for j in range(i+1, len(a)):
if check(a[i], a[j]):
front = a[i]+front
back = back+a[j]
a[i] = ".,"
a[j] = ".,"
break
mid = ""
for i in range(len(a)):
if isPalindrome(a[i]):
mid = a[i]
break
rtn = front+mid+back
print(len(rtn))
print(rtn)
```
|
output
| 1
| 10,893
| 6
| 21,787
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.
Gildong loves this concept so much, so he wants to play with it. He has n distinct strings of equal length m. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.
Input
The first line contains two integers n and m (1 β€ n β€ 100, 1 β€ m β€ 50) β the number of strings and the length of each string.
Next n lines contain a string of length m each, consisting of lowercase Latin letters only. All strings are distinct.
Output
In the first line, print the length of the longest palindrome string you made.
In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.
Examples
Input
3 3
tab
one
bat
Output
6
tabbat
Input
4 2
oo
ox
xo
xx
Output
6
oxxxxo
Input
3 5
hello
codef
orces
Output
0
Input
9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
Output
20
ababwxyzijjizyxwbaba
Note
In the first example, "battab" is also a valid answer.
In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.
In the third example, the empty string is the only valid palindrome string.
|
instruction
| 0
| 10,894
| 6
| 21,788
|
Tags: brute force, constructive algorithms, greedy, implementation, strings
Correct Solution:
```
n, m = map(int, input().split())
a = []
for _ in range(n):
s = input()
a.append(s)
def is_palindrome(s1, s2):
eh = True
for i in range(len(s1)):
if s1[i] != s2[m-i-1]:
eh = False
break
return eh
def is_palindrome_alone(s1):
eh = True
for i in range(len(s1)):
if s1[i] != s1[m-i-1]:
eh = False
break
return eh
together = []
for i in range(len(a)):
for j in range(i+1, len(a)):
if a[i] != -1 and a[j] != -1 and is_palindrome(a[i], a[j]):
together.append([a[i], a[j]])
a[i] = -1
a[j] = -1
alone = []
for i, s in enumerate(a):
if s != -1 and is_palindrome_alone(s):
alone.append(s)
a[i] = -1
break
stack = []
ans = []
for i in together:
ans.append(i[0])
stack.append(i[1])
for i in alone:
ans.append(i)
while len(stack):
ans.append(stack.pop())
ans = "".join(ans)
print(len(ans))
print(ans)
```
|
output
| 1
| 10,894
| 6
| 21,789
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.
Gildong loves this concept so much, so he wants to play with it. He has n distinct strings of equal length m. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.
Input
The first line contains two integers n and m (1 β€ n β€ 100, 1 β€ m β€ 50) β the number of strings and the length of each string.
Next n lines contain a string of length m each, consisting of lowercase Latin letters only. All strings are distinct.
Output
In the first line, print the length of the longest palindrome string you made.
In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.
Examples
Input
3 3
tab
one
bat
Output
6
tabbat
Input
4 2
oo
ox
xo
xx
Output
6
oxxxxo
Input
3 5
hello
codef
orces
Output
0
Input
9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
Output
20
ababwxyzijjizyxwbaba
Note
In the first example, "battab" is also a valid answer.
In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.
In the third example, the empty string is the only valid palindrome string.
|
instruction
| 0
| 10,895
| 6
| 21,790
|
Tags: brute force, constructive algorithms, greedy, implementation, strings
Correct Solution:
```
n,m=map(int,input().split())
s=[""]*n
kouho=[]
result_mid=""
result_left=""
result_right=""
for i in range(n):
s[i]=input()
for i in range(n):
s_i_rev=s[i][::-1]
if s[i] not in kouho:
kouho.append(s_i_rev)
else:
result_left=s[i]+result_left
result_right=result_right+s_i_rev
kouho.remove(s[i])
for j in range(len(kouho)):
if kouho[j]==kouho[j][::-1]:
if len(result_mid)<len(kouho[j]):
result_mid=kouho[j]
result=result_left+result_mid+result_right
print(len(result))
print(result)
```
|
output
| 1
| 10,895
| 6
| 21,791
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.
Gildong loves this concept so much, so he wants to play with it. He has n distinct strings of equal length m. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.
Input
The first line contains two integers n and m (1 β€ n β€ 100, 1 β€ m β€ 50) β the number of strings and the length of each string.
Next n lines contain a string of length m each, consisting of lowercase Latin letters only. All strings are distinct.
Output
In the first line, print the length of the longest palindrome string you made.
In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.
Examples
Input
3 3
tab
one
bat
Output
6
tabbat
Input
4 2
oo
ox
xo
xx
Output
6
oxxxxo
Input
3 5
hello
codef
orces
Output
0
Input
9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
Output
20
ababwxyzijjizyxwbaba
Note
In the first example, "battab" is also a valid answer.
In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.
In the third example, the empty string is the only valid palindrome string.
|
instruction
| 0
| 10,896
| 6
| 21,792
|
Tags: brute force, constructive algorithms, greedy, implementation, strings
Correct Solution:
```
n,m=map(int,input().split())
s=[]
z=""
for i in range(n):
s.append(input())
count=0
x=""
for i in range(int(n)):
j=i+1
if(s[i]==s[i][::-1]):
z=s[i]
continue
while(j<n):
if(s[i]==s[j][::-1]):
count+=1
x=s[i]+x+s[j]
break
j+=1
x=x[:int(len(x)/2)]+z+x[int(len(x)/2):]
print(len(x))
print(x)
```
|
output
| 1
| 10,896
| 6
| 21,793
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.
Gildong loves this concept so much, so he wants to play with it. He has n distinct strings of equal length m. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.
Input
The first line contains two integers n and m (1 β€ n β€ 100, 1 β€ m β€ 50) β the number of strings and the length of each string.
Next n lines contain a string of length m each, consisting of lowercase Latin letters only. All strings are distinct.
Output
In the first line, print the length of the longest palindrome string you made.
In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.
Examples
Input
3 3
tab
one
bat
Output
6
tabbat
Input
4 2
oo
ox
xo
xx
Output
6
oxxxxo
Input
3 5
hello
codef
orces
Output
0
Input
9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
Output
20
ababwxyzijjizyxwbaba
Note
In the first example, "battab" is also a valid answer.
In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.
In the third example, the empty string is the only valid palindrome string.
|
instruction
| 0
| 10,898
| 6
| 21,796
|
Tags: brute force, constructive algorithms, greedy, implementation, strings
Correct Solution:
```
n, m = map(int, input().split())
s1 = ""
s2 = ""
sc = ""
dat = []
for _ in range(n):
dat.append(input())
while 0 < len(dat):
s = dat[0]
del dat[0]
if sc == "":
if s == "".join(reversed(s)):
sc = s
continue
for j in range(0, len(dat)):
ss = "".join(reversed(dat[j]))
if s == ss:
s1 = s1 + s
s2 = dat[j] + s2
del dat[j]
break
res = s1 + sc + s2
#print("---")
#print(s1)
#print(sc)
#print(s2)
#print("---")
print(len(res))
print(res)
```
|
output
| 1
| 10,898
| 6
| 21,797
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.
Gildong loves this concept so much, so he wants to play with it. He has n distinct strings of equal length m. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.
Input
The first line contains two integers n and m (1 β€ n β€ 100, 1 β€ m β€ 50) β the number of strings and the length of each string.
Next n lines contain a string of length m each, consisting of lowercase Latin letters only. All strings are distinct.
Output
In the first line, print the length of the longest palindrome string you made.
In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.
Examples
Input
3 3
tab
one
bat
Output
6
tabbat
Input
4 2
oo
ox
xo
xx
Output
6
oxxxxo
Input
3 5
hello
codef
orces
Output
0
Input
9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
Output
20
ababwxyzijjizyxwbaba
Note
In the first example, "battab" is also a valid answer.
In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.
In the third example, the empty string is the only valid palindrome string.
|
instruction
| 0
| 10,899
| 6
| 21,798
|
Tags: brute force, constructive algorithms, greedy, implementation, strings
Correct Solution:
```
n, m = map(int, input().split())
d = {}
f = []
a = []
used = [False] * n
for i in range(n):
s = input()
if s[::-1] in d:
used[i] = True
used[d[s[::-1]]] = True
f = [s] + f + [s[::-1]]
del d[s[::-1]]
else:
d[s] = i
a.append(s)
if len(f) % 2:
print(len(f) * m)
print(''.join(f))
else:
for i in range(n):
if not used[i] and a[i] == a[i][::-1]:
f = f[:len(f) // 2] + [a[i]] + f[len(f) // 2:]
break
print(len(f) * m)
print(''.join(f))
```
|
output
| 1
| 10,899
| 6
| 21,799
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.
Gildong loves this concept so much, so he wants to play with it. He has n distinct strings of equal length m. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.
Input
The first line contains two integers n and m (1 β€ n β€ 100, 1 β€ m β€ 50) β the number of strings and the length of each string.
Next n lines contain a string of length m each, consisting of lowercase Latin letters only. All strings are distinct.
Output
In the first line, print the length of the longest palindrome string you made.
In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.
Examples
Input
3 3
tab
one
bat
Output
6
tabbat
Input
4 2
oo
ox
xo
xx
Output
6
oxxxxo
Input
3 5
hello
codef
orces
Output
0
Input
9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
Output
20
ababwxyzijjizyxwbaba
Note
In the first example, "battab" is also a valid answer.
In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.
In the third example, the empty string is the only valid palindrome string.
|
instruction
| 0
| 10,900
| 6
| 21,800
|
Tags: brute force, constructive algorithms, greedy, implementation, strings
Correct Solution:
```
n,m = map(int,input().split())
dic = {}
dic2 = {}
for i in range(n):
s = input()
temp = list(s)
temp.reverse()
rev = "".join(temp)
if s == rev:
if s not in dic2:
dic2[s] = 0
dic2[s] += 1
elif s < rev:
if s not in dic:
dic[s] = [0,0]
dic[s][0] += 1
else:
if rev not in dic:
dic[rev] = [0,0]
dic[rev][1] += 1
lis = []
bis = []
for s in dic:
temp = list(s)
temp.reverse()
rev = "".join(temp)
for i in range(min(dic[s])):
lis.append(s)
bis.append(rev)
sub = ""
for s in dic2:
if dic2[s] % 2 == 1:
sub = s
for i in range(dic2[s] // 2):
lis.append(s)
bis.append(s)
bis.reverse()
ans = "".join(lis) +sub+ "".join(bis)
print (len(ans))
print (ans)
```
|
output
| 1
| 10,900
| 6
| 21,801
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Genos recently installed the game Zuma on his phone. In Zuma there exists a line of n gemstones, the i-th of which has color ci. The goal of the game is to destroy all the gemstones in the line as quickly as possible.
In one second, Genos is able to choose exactly one continuous substring of colored gemstones that is a palindrome and remove it from the line. After the substring is removed, the remaining gemstones shift to form a solid line again. What is the minimum number of seconds needed to destroy the entire line?
Let us remind, that the string (or substring) is called palindrome, if it reads same backwards or forward. In our case this means the color of the first gemstone is equal to the color of the last one, the color of the second gemstone is equal to the color of the next to last and so on.
Input
The first line of input contains a single integer n (1 β€ n β€ 500) β the number of gemstones.
The second line contains n space-separated integers, the i-th of which is ci (1 β€ ci β€ n) β the color of the i-th gemstone in a line.
Output
Print a single integer β the minimum number of seconds needed to destroy the entire line.
Examples
Input
3
1 2 1
Output
1
Input
3
1 2 3
Output
3
Input
7
1 4 4 2 3 2 1
Output
2
Note
In the first sample, Genos can destroy the entire line in one second.
In the second sample, Genos can only destroy one gemstone at a time, so destroying three gemstones takes three seconds.
In the third sample, to achieve the optimal time of two seconds, destroy palindrome 4 4 first and then destroy palindrome 1 2 3 2 1.
|
instruction
| 0
| 11,206
| 6
| 22,412
|
Tags: dp
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
# ------------------------------
def main():
n = N()
arr = RLL()
dp = [[n]*n for _ in range(n)]
for i in range(n): dp[i][i] = 1
for le in range(2, n+1):
for l in range(n):
r = l+le-1
if r>=n: break
if le==2:
if arr[l]==arr[r]: dp[l][r] = 1
else: dp[l][r] = 2
else:
for m in range(l, r):
dp[l][r] = min(dp[l][r], dp[l][m]+dp[m+1][r])
if arr[l]==arr[r]:
dp[l][r] = min(dp[l+1][r-1], dp[l][r])
print(dp[0][-1])
if __name__ == "__main__":
main()
```
|
output
| 1
| 11,206
| 6
| 22,413
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).
As a reminder, a prefix of a string s is its substring which occurs at the beginning of s: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string a is alphabetically earlier than a string b, if a is a prefix of b, or a and b coincide up to some position, and then a has a letter that is alphabetically earlier than the corresponding letter in b: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac".
Input
The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive.
Output
Output a single string β alphabetically earliest possible login formed from these names. The output should be given in lowercase as well.
Examples
Input
harry potter
Output
hap
Input
tom riddle
Output
tomr
|
instruction
| 0
| 11,349
| 6
| 22,698
|
Tags: brute force, greedy, sortings
Correct Solution:
```
a=input().split()
n=[]
X=''
for i in a[0]:
X+=i
n.append(X+a[1][0])
n=sorted(n)
print(n[0])
```
|
output
| 1
| 11,349
| 6
| 22,699
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).
As a reminder, a prefix of a string s is its substring which occurs at the beginning of s: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string a is alphabetically earlier than a string b, if a is a prefix of b, or a and b coincide up to some position, and then a has a letter that is alphabetically earlier than the corresponding letter in b: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac".
Input
The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive.
Output
Output a single string β alphabetically earliest possible login formed from these names. The output should be given in lowercase as well.
Examples
Input
harry potter
Output
hap
Input
tom riddle
Output
tomr
|
instruction
| 0
| 11,350
| 6
| 22,700
|
Tags: brute force, greedy, sortings
Correct Solution:
```
f,l=map(str,input().split())
i=1
j=0
while i<len(f):
if ord(f[i])<ord(l[j]):
i+=1
else:
break
print(f[0:i]+l[0])
```
|
output
| 1
| 11,350
| 6
| 22,701
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).
As a reminder, a prefix of a string s is its substring which occurs at the beginning of s: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string a is alphabetically earlier than a string b, if a is a prefix of b, or a and b coincide up to some position, and then a has a letter that is alphabetically earlier than the corresponding letter in b: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac".
Input
The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive.
Output
Output a single string β alphabetically earliest possible login formed from these names. The output should be given in lowercase as well.
Examples
Input
harry potter
Output
hap
Input
tom riddle
Output
tomr
|
instruction
| 0
| 11,351
| 6
| 22,702
|
Tags: brute force, greedy, sortings
Correct Solution:
```
fname,lname = input().split()
ans=""
ans+=fname[0]
for x in range(1,len(fname)):
if ord(fname[x]) < ord(lname[0]):
ans+=fname[x]
else:break;
ans+=lname[0]
print(ans)
```
|
output
| 1
| 11,351
| 6
| 22,703
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).
As a reminder, a prefix of a string s is its substring which occurs at the beginning of s: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string a is alphabetically earlier than a string b, if a is a prefix of b, or a and b coincide up to some position, and then a has a letter that is alphabetically earlier than the corresponding letter in b: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac".
Input
The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive.
Output
Output a single string β alphabetically earliest possible login formed from these names. The output should be given in lowercase as well.
Examples
Input
harry potter
Output
hap
Input
tom riddle
Output
tomr
|
instruction
| 0
| 11,352
| 6
| 22,704
|
Tags: brute force, greedy, sortings
Correct Solution:
```
s = input().split(' ')
result = s[0][0]
end = s[1][0]
for i in range(1, len(s[0])):
if ord(s[0][i]) < ord(end):
result += s[0][i]
else:
break
result += end
print(result)
```
|
output
| 1
| 11,352
| 6
| 22,705
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).
As a reminder, a prefix of a string s is its substring which occurs at the beginning of s: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string a is alphabetically earlier than a string b, if a is a prefix of b, or a and b coincide up to some position, and then a has a letter that is alphabetically earlier than the corresponding letter in b: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac".
Input
The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive.
Output
Output a single string β alphabetically earliest possible login formed from these names. The output should be given in lowercase as well.
Examples
Input
harry potter
Output
hap
Input
tom riddle
Output
tomr
|
instruction
| 0
| 11,353
| 6
| 22,706
|
Tags: brute force, greedy, sortings
Correct Solution:
```
inu=input().split()
first,last=inu[0],inu[1]
l,name,st=[],"",""
for fi in first:
st=st+fi
name=st
for se in last:
name=name+se
l.append(name)
l.sort()
print(l[0])
```
|
output
| 1
| 11,353
| 6
| 22,707
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).
As a reminder, a prefix of a string s is its substring which occurs at the beginning of s: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string a is alphabetically earlier than a string b, if a is a prefix of b, or a and b coincide up to some position, and then a has a letter that is alphabetically earlier than the corresponding letter in b: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac".
Input
The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive.
Output
Output a single string β alphabetically earliest possible login formed from these names. The output should be given in lowercase as well.
Examples
Input
harry potter
Output
hap
Input
tom riddle
Output
tomr
|
instruction
| 0
| 11,354
| 6
| 22,708
|
Tags: brute force, greedy, sortings
Correct Solution:
```
first, last = input().split()
if len(first) == 1:
print(first[0]+last[0])
else:
i=1
while i < len(first) and first[i] < last[0]:
i+=1
print(first[:i]+last[0])
```
|
output
| 1
| 11,354
| 6
| 22,709
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).
As a reminder, a prefix of a string s is its substring which occurs at the beginning of s: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string a is alphabetically earlier than a string b, if a is a prefix of b, or a and b coincide up to some position, and then a has a letter that is alphabetically earlier than the corresponding letter in b: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac".
Input
The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive.
Output
Output a single string β alphabetically earliest possible login formed from these names. The output should be given in lowercase as well.
Examples
Input
harry potter
Output
hap
Input
tom riddle
Output
tomr
|
instruction
| 0
| 11,355
| 6
| 22,710
|
Tags: brute force, greedy, sortings
Correct Solution:
```
# May the Speedforce be with us...
'''
for _ in range(int(input())):
arr=list(map(int,input().split()))
n,k=map(int,input().split())
n=int(input())
s=input()
from collections import defaultdict
d=defaultdict()
d=dict()
s=set()
s.intersection()
s.union()
s.difference()
problem statement achhe se padhna hai
age se bhi dekhna hai, piche se bhi dekhna hai
'''
from math import gcd,ceil
from collections import defaultdict as dd
def lcm(a,b):
return (a*b)//gcd(a,b)
def inin():
return int(input())
def inar():
return list(map(int,input().split()))
def ar(element,size):
return [element for i in range(size)]
def digitsum(num):
su=0
while(num):
su+=num%10
num//=10
return su
n,t=input().split()
title=t[0]
ans=n[0]
for i in n[1:]:
if i>=title:
break
ans+=i
ans+=title
print(ans)
```
|
output
| 1
| 11,355
| 6
| 22,711
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).
As a reminder, a prefix of a string s is its substring which occurs at the beginning of s: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string a is alphabetically earlier than a string b, if a is a prefix of b, or a and b coincide up to some position, and then a has a letter that is alphabetically earlier than the corresponding letter in b: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac".
Input
The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive.
Output
Output a single string β alphabetically earliest possible login formed from these names. The output should be given in lowercase as well.
Examples
Input
harry potter
Output
hap
Input
tom riddle
Output
tomr
|
instruction
| 0
| 11,356
| 6
| 22,712
|
Tags: brute force, greedy, sortings
Correct Solution:
```
s = input()
n, f = s.split(' ')
s=n[0]
i=1
while i < len(n) and n[i] < f[0]:
s += n[i]
i+=1
print(s+f[0])
```
|
output
| 1
| 11,356
| 6
| 22,713
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).
As a reminder, a prefix of a string s is its substring which occurs at the beginning of s: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string a is alphabetically earlier than a string b, if a is a prefix of b, or a and b coincide up to some position, and then a has a letter that is alphabetically earlier than the corresponding letter in b: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac".
Input
The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive.
Output
Output a single string β alphabetically earliest possible login formed from these names. The output should be given in lowercase as well.
Examples
Input
harry potter
Output
hap
Input
tom riddle
Output
tomr
Submitted Solution:
```
s1, s2 = input().split()
i = 1
print(s1[0],end='')
while i< len(s1) and s2[0] > s1[i]:
print(s1[i],end='')
i+=1
print(s2[0])
```
|
instruction
| 0
| 11,357
| 6
| 22,714
|
Yes
|
output
| 1
| 11,357
| 6
| 22,715
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.