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.
Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange.
Victor thinks that if a word contains two consecutive vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consecutive vowels in the word, it deletes the first vowel in a word such that there is another vowel right before it. If there are no two consecutive vowels in the word, it is considered to be correct.
You are given a word s. Can you predict what will it become after correction?
In this problem letters a, e, i, o, u and y are considered to be vowels.
Input
The first line contains one integer n (1 β€ n β€ 100) β the number of letters in word s before the correction.
The second line contains a string s consisting of exactly n lowercase Latin letters β the word before the correction.
Output
Output the word s after the correction.
Examples
Input
5
weird
Output
werd
Input
4
word
Output
word
Input
5
aaeaa
Output
a
Note
Explanations of the examples:
1. There is only one replace: weird <image> werd;
2. No replace needed since there are no two consecutive vowels;
3. aaeaa <image> aeaa <image> aaa <image> aa <image> a. | instruction | 0 | 40,927 | 6 | 81,854 |
Tags: implementation
Correct Solution:
```
length = int(input())
word = input()
vowels = 'aeiouy'
i = 0
while i<length:
#print(i,length)
if length==1 or i==length-1:
break
elif word[i] in vowels and word[i+1] in vowels:
word = word[:i+1]+word[i+2:]
i=0
length-=1
else:
i+=1
print(word)
``` | output | 1 | 40,927 | 6 | 81,855 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange.
Victor thinks that if a word contains two consecutive vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consecutive vowels in the word, it deletes the first vowel in a word such that there is another vowel right before it. If there are no two consecutive vowels in the word, it is considered to be correct.
You are given a word s. Can you predict what will it become after correction?
In this problem letters a, e, i, o, u and y are considered to be vowels.
Input
The first line contains one integer n (1 β€ n β€ 100) β the number of letters in word s before the correction.
The second line contains a string s consisting of exactly n lowercase Latin letters β the word before the correction.
Output
Output the word s after the correction.
Examples
Input
5
weird
Output
werd
Input
4
word
Output
word
Input
5
aaeaa
Output
a
Note
Explanations of the examples:
1. There is only one replace: weird <image> werd;
2. No replace needed since there are no two consecutive vowels;
3. aaeaa <image> aeaa <image> aaa <image> aa <image> a. | instruction | 0 | 40,928 | 6 | 81,856 |
Tags: implementation
Correct Solution:
```
# https://codeforces.com/problemset/problem/938/A
n = input()
s = list()
vowels = {'a', 'e', 'i', 'o', 'u', 'y'}
for i in input():
if not s:
s.append(i)
else:
if s[-1] in vowels and i in vowels:
pass
else:
s.append(i)
print(''.join(s))
``` | output | 1 | 40,928 | 6 | 81,857 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange.
Victor thinks that if a word contains two consecutive vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consecutive vowels in the word, it deletes the first vowel in a word such that there is another vowel right before it. If there are no two consecutive vowels in the word, it is considered to be correct.
You are given a word s. Can you predict what will it become after correction?
In this problem letters a, e, i, o, u and y are considered to be vowels.
Input
The first line contains one integer n (1 β€ n β€ 100) β the number of letters in word s before the correction.
The second line contains a string s consisting of exactly n lowercase Latin letters β the word before the correction.
Output
Output the word s after the correction.
Examples
Input
5
weird
Output
werd
Input
4
word
Output
word
Input
5
aaeaa
Output
a
Note
Explanations of the examples:
1. There is only one replace: weird <image> werd;
2. No replace needed since there are no two consecutive vowels;
3. aaeaa <image> aeaa <image> aaa <image> aa <image> a. | instruction | 0 | 40,929 | 6 | 81,858 |
Tags: implementation
Correct Solution:
```
n = int(input())
s = input()
counter = 1
myList = ["a", "e", "i", "o", "u", "y"]
counter = 0
for i in range(0, len(s) - 1):
if s[counter] in myList and s[counter + 1] in myList:
s = s[:(counter + 1)] + s[(counter + 2):]
else:
counter += 1
print(s)
``` | output | 1 | 40,929 | 6 | 81,859 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange.
Victor thinks that if a word contains two consecutive vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consecutive vowels in the word, it deletes the first vowel in a word such that there is another vowel right before it. If there are no two consecutive vowels in the word, it is considered to be correct.
You are given a word s. Can you predict what will it become after correction?
In this problem letters a, e, i, o, u and y are considered to be vowels.
Input
The first line contains one integer n (1 β€ n β€ 100) β the number of letters in word s before the correction.
The second line contains a string s consisting of exactly n lowercase Latin letters β the word before the correction.
Output
Output the word s after the correction.
Examples
Input
5
weird
Output
werd
Input
4
word
Output
word
Input
5
aaeaa
Output
a
Note
Explanations of the examples:
1. There is only one replace: weird <image> werd;
2. No replace needed since there are no two consecutive vowels;
3. aaeaa <image> aeaa <image> aaa <image> aa <image> a. | instruction | 0 | 40,930 | 6 | 81,860 |
Tags: implementation
Correct Solution:
```
#This code sucks, you know it and I know it.
#Move on and call me an idiot later.
n = int(input())
s = input()
ans = []
temp = 0
for i in s:
if i in 'aeiouy':
if temp == 0:
temp = 1
ans += [i]
else:
temp = 0
ans += [i]
print("".join(ans))
``` | output | 1 | 40,930 | 6 | 81,861 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange.
Victor thinks that if a word contains two consecutive vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consecutive vowels in the word, it deletes the first vowel in a word such that there is another vowel right before it. If there are no two consecutive vowels in the word, it is considered to be correct.
You are given a word s. Can you predict what will it become after correction?
In this problem letters a, e, i, o, u and y are considered to be vowels.
Input
The first line contains one integer n (1 β€ n β€ 100) β the number of letters in word s before the correction.
The second line contains a string s consisting of exactly n lowercase Latin letters β the word before the correction.
Output
Output the word s after the correction.
Examples
Input
5
weird
Output
werd
Input
4
word
Output
word
Input
5
aaeaa
Output
a
Note
Explanations of the examples:
1. There is only one replace: weird <image> werd;
2. No replace needed since there are no two consecutive vowels;
3. aaeaa <image> aeaa <image> aaa <image> aa <image> a. | instruction | 0 | 40,931 | 6 | 81,862 |
Tags: implementation
Correct Solution:
```
import sys
vowel = 'aeiouy'
n = int(input())
s = list(input())
i = 0
while i < len(s)-1:
if s[i] in vowel and s[i+1] in vowel:
s.pop(i+1)
else:
i += 1
print(''.join(s))
``` | output | 1 | 40,931 | 6 | 81,863 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange.
Victor thinks that if a word contains two consecutive vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consecutive vowels in the word, it deletes the first vowel in a word such that there is another vowel right before it. If there are no two consecutive vowels in the word, it is considered to be correct.
You are given a word s. Can you predict what will it become after correction?
In this problem letters a, e, i, o, u and y are considered to be vowels.
Input
The first line contains one integer n (1 β€ n β€ 100) β the number of letters in word s before the correction.
The second line contains a string s consisting of exactly n lowercase Latin letters β the word before the correction.
Output
Output the word s after the correction.
Examples
Input
5
weird
Output
werd
Input
4
word
Output
word
Input
5
aaeaa
Output
a
Note
Explanations of the examples:
1. There is only one replace: weird <image> werd;
2. No replace needed since there are no two consecutive vowels;
3. aaeaa <image> aeaa <image> aaa <image> aa <image> a. | instruction | 0 | 40,932 | 6 | 81,864 |
Tags: implementation
Correct Solution:
```
n=int(input())
s=input()
k=""
m=False
for i in range(n):
if s[i] not in ["a","e","i","o","u","y"]:
k+=s[i]
elif s[i] in ["a","e","i","o","u","y"] and not m:
k+=s[i]
m=True
try:
if s[i] in ["a","e","i","o","u","y"] and s[i+1] not in ["a","e","i","o","u","y"]:
m=False
except:
pass
print(k)
``` | output | 1 | 40,932 | 6 | 81,865 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange.
Victor thinks that if a word contains two consecutive vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consecutive vowels in the word, it deletes the first vowel in a word such that there is another vowel right before it. If there are no two consecutive vowels in the word, it is considered to be correct.
You are given a word s. Can you predict what will it become after correction?
In this problem letters a, e, i, o, u and y are considered to be vowels.
Input
The first line contains one integer n (1 β€ n β€ 100) β the number of letters in word s before the correction.
The second line contains a string s consisting of exactly n lowercase Latin letters β the word before the correction.
Output
Output the word s after the correction.
Examples
Input
5
weird
Output
werd
Input
4
word
Output
word
Input
5
aaeaa
Output
a
Note
Explanations of the examples:
1. There is only one replace: weird <image> werd;
2. No replace needed since there are no two consecutive vowels;
3. aaeaa <image> aeaa <image> aaa <image> aa <image> a. | instruction | 0 | 40,933 | 6 | 81,866 |
Tags: implementation
Correct Solution:
```
def vovel(c):
return c in ['a', 'i', 'o', 'e', 'u', 'y']
n = int(input())
s = input()[:n]
if len(s)>0:
p = s[0]
else:
print ()
exit()
res = ''
for i in range(1, len(s)):
if vovel(p) and vovel(s[i]):
continue
res +=p
p = s[i]
res += p
print (res)
``` | output | 1 | 40,933 | 6 | 81,867 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.
Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.
Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened.
You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
Input
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
Output
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
Examples
Input
fixprefixsuffix
Output
fix
Input
abcdabc
Output
Just a legend | instruction | 0 | 43,069 | 6 | 86,138 |
Tags: binary search, dp, hashing, string suffix structures, strings
Correct Solution:
```
def kmp_fail(p):
m=len(p)
fail=m*[0]
k=0
j=1
while j<m:
if p[j]==p[k]:
fail[j]=k+1
j+=1
k+=1
elif k>0:
k=fail[k-1]
else:
j+=1
return fail
s=input()
f=kmp_fail(s)
ans=f[-1]
if f.count(f[-1])>1 and ans!=0:
print(s[0:ans])
elif f[ans-1]>0:
print(s[0:f[ans-1]])
else:
print('Just a legend')
``` | output | 1 | 43,069 | 6 | 86,139 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.
Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.
Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened.
You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
Input
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
Output
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
Examples
Input
fixprefixsuffix
Output
fix
Input
abcdabc
Output
Just a legend | instruction | 0 | 43,070 | 6 | 86,140 |
Tags: binary search, dp, hashing, string suffix structures, strings
Correct Solution:
```
s = input()
n = len(s)
if n==1 or n==2:
print("Just a legend")
else:
lista = []
for i in range(n):
lista.append(0)
l = 0
lista[0] = 0
i = 1
while i < n:
if s[i]==s[l]:
l+=1
lista[i] = l
i += 1
else:
if l!=0:
l = lista[l-1]
else:
lista[i] = 0
i += 1
ultimo = lista.pop()
if (ultimo == 0):
print("Just a legend")
elif (ultimo in lista):
print(s[:ultimo])
elif (lista[ultimo-1] == 0):
print("Just a legend")
elif lista[ultimo-1]:
print(s[:lista[ultimo-1]])
else:
print("Just a legend")
``` | output | 1 | 43,070 | 6 | 86,141 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.
Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.
Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened.
You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
Input
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
Output
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
Examples
Input
fixprefixsuffix
Output
fix
Input
abcdabc
Output
Just a legend | instruction | 0 | 43,071 | 6 | 86,142 |
Tags: binary search, dp, hashing, string suffix structures, strings
Correct Solution:
```
def Zarr(pat,text):
s=pat+"/"+text;
z=[0 for i in range(len(s))]
L=0;R=0;n=len(s);
for i in range(1,len(s)):
if i>R:
L=R=i
while R<n and s[R-L]==s[R]:
R+=1
z[i]=R-L
R-=1
elif z[i-L]+i<=R:
z[i]=z[i-L]
else:
L=i
while R<n and s[R-L]==s[R]:
R+=1
z[i]=R-L
R-=1
dp=[0 for i in range(1000006)]
ans=-1
for i in range(len(pat)+2,len(s)):
dp[z[i]]+=1
for i in range(len(dp)-2,-1,-1):
dp[i]+=dp[i+1]
for i in range(len(pat)+2,len(s)):
if i+z[i]==len(s) and dp[z[i]]>1 and z[i]>ans:
ans=z[i]
if ans==-1:
print("Just a legend")
else:
print(pat[0:ans])
from sys import stdin
texts=stdin.readline().strip()
Zarr(texts,texts)
``` | output | 1 | 43,071 | 6 | 86,143 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.
Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.
Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened.
You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
Input
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
Output
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
Examples
Input
fixprefixsuffix
Output
fix
Input
abcdabc
Output
Just a legend | instruction | 0 | 43,073 | 6 | 86,146 |
Tags: binary search, dp, hashing, string suffix structures, strings
Correct Solution:
```
def KMP_pre(texte, longueur):
M = [0 for i in range(longueur)]
index_deb = 0
M[0] = 0
i = 1
while (i < longueur):
if (texte[i] == texte[index_deb]):
index_deb += 1
M[i] = index_deb
i += 1
else:
if (index_deb != 0):
index_deb = M[index_deb - 1]
else:
M[i] = 0
i += 1
return M
def KMP_algo(texte, longueur):
M = KMP_pre(texte, longueur)
#pas de suffixe qui soit prefixe
if (M[longueur - 1] == 0):
return -1
#on cherche le motif qui soit ni prefixe ni suffixe
for i in range(0,longueur - 1):
if (M[i] == M[longueur - 1]):
return texte[0:M[i]]
if (M[M[longueur - 1] - 1] == 0):
return -1
else:
return texte[0:M[M[longueur - 1] - 1]]
def main(texte):
res = KMP_algo(texte, len(texte))
if res == -1:
print('Just a legend')
else:
print(res)
main(input())
``` | output | 1 | 43,073 | 6 | 86,147 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.
Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.
Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened.
You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
Input
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
Output
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
Examples
Input
fixprefixsuffix
Output
fix
Input
abcdabc
Output
Just a legend | instruction | 0 | 43,074 | 6 | 86,148 |
Tags: binary search, dp, hashing, string suffix structures, strings
Correct Solution:
```
s=input()
n=len(s)
p=[-1]*n
mark=[False]*n
q=-1
for i in range(1,n):
while q>=0 and s[i]!=s[q+1]:
q=p[q]
if s[i] == s[q + 1]:
q += 1
p[i] = q
if q>=0 and i<n-1:
mark[q]=True
#print(p)
q=p[n-1]
while q>=0:
if s[0:q+1]==s[n-q-1:] and mark[q]:
print(s[0:q+1])
exit()
q=p[q]
print('Just a legend')
``` | output | 1 | 43,074 | 6 | 86,149 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.
Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.
Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened.
You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
Input
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
Output
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
Examples
Input
fixprefixsuffix
Output
fix
Input
abcdabc
Output
Just a legend | instruction | 0 | 43,075 | 6 | 86,150 |
Tags: binary search, dp, hashing, string suffix structures, strings
Correct Solution:
```
def prefix(s):
p = [0] * len(s)
for i in range(1, len(s)):
k = p[i - 1]
while k > 0 and s[k] != s[i]:
k = p[k - 1]
if s[k] == s[i]:
k += 1
p[i] = k
return p
string = input()
prefix_values = prefix(string)
n = len(string)
if prefix_values[n - 1] == 0:
print('Just a legend')
exit()
last_pr = prefix_values[n - 1]
for i in range(n - 1):
if prefix_values[i] == last_pr:
print(string[:prefix_values[i]])
exit()
next_pos_value = prefix_values[last_pr - 1]
if next_pos_value == 0:
print('Just a legend')
exit()
for i in range(n):
a = prefix_values[i]
if prefix_values[i] == next_pos_value and i != last_pr:
print(string[:prefix_values[i]])
exit()
# print('Just a legend')
``` | output | 1 | 43,075 | 6 | 86,151 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.
Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.
Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened.
You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
Input
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
Output
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
Examples
Input
fixprefixsuffix
Output
fix
Input
abcdabc
Output
Just a legend | instruction | 0 | 43,076 | 6 | 86,152 |
Tags: binary search, dp, hashing, string suffix structures, strings
Correct Solution:
```
def kmpTable(s, n):
res = [0]*n
check_idx = 0
for i in range(1, n):
while check_idx > 0 and s[check_idx] != s[i]:
check_idx = res[check_idx-1]
if s[check_idx] == s[i]:
check_idx += 1
res[i] = check_idx
return res
s = input()
n = len(s)
kmp_table = kmpTable(s, n)
psize = kmp_table[n-1]
if psize > 0 and psize in kmp_table[:-1]:
print(s[:psize])
else:
psize = kmp_table[psize-1]
if psize > 0 and psize in kmp_table[:-1]:
print(s[:psize])
else:
print("Just a legend")
``` | output | 1 | 43,076 | 6 | 86,153 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a mysterious language (codenamed "Secret") available in "Custom Invocation" tab. Figure out what this language is and write a program which prints its name. Note that the program must be written in this language.
Input
This program has only one test (your program doesn't have to read anything).
Output
Output the name of the mysterious language. Note that the name is case-sensitive and might contain digits and special characters.
Examples
Note
Some scientists disagree on what should be considered as a language and what should be considered as a dialect. | instruction | 0 | 43,325 | 6 | 86,650 |
Tags: *special
Correct Solution:
```
n=input()
print("INTERCAL")
``` | output | 1 | 43,325 | 6 | 86,651 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a mysterious language (codenamed "Secret") available in "Custom Invocation" tab. Figure out what this language is and write a program which prints its name. Note that the program must be written in this language.
Input
This program has only one test (your program doesn't have to read anything).
Output
Output the name of the mysterious language. Note that the name is case-sensitive and might contain digits and special characters.
Examples
Note
Some scientists disagree on what should be considered as a language and what should be considered as a dialect. | instruction | 0 | 43,326 | 6 | 86,652 |
Tags: *special
Correct Solution:
```
print('INTERCAL')
``` | output | 1 | 43,326 | 6 | 86,653 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a mysterious language (codenamed "Secret") available in "Custom Invocation" tab. Figure out what this language is and write a program which prints its name. Note that the program must be written in this language.
Input
This program has only one test (your program doesn't have to read anything).
Output
Output the name of the mysterious language. Note that the name is case-sensitive and might contain digits and special characters.
Examples
Note
Some scientists disagree on what should be considered as a language and what should be considered as a dialect. | instruction | 0 | 43,327 | 6 | 86,654 |
Tags: *special
Correct Solution:
```
# Flamire senpai AK IOI
print('INTERCAL')
``` | output | 1 | 43,327 | 6 | 86,655 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a mysterious language (codenamed "Secret") available in "Custom Invocation" tab. Figure out what this language is and write a program which prints its name. Note that the program must be written in this language.
Input
This program has only one test (your program doesn't have to read anything).
Output
Output the name of the mysterious language. Note that the name is case-sensitive and might contain digits and special characters.
Examples
Note
Some scientists disagree on what should be considered as a language and what should be considered as a dialect. | instruction | 0 | 43,328 | 6 | 86,656 |
Tags: *special
Correct Solution:
```
print("INTERCAL")
#233333
``` | output | 1 | 43,328 | 6 | 86,657 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a mysterious language (codenamed "Secret") available in "Custom Invocation" tab. Figure out what this language is and write a program which prints its name. Note that the program must be written in this language.
Input
This program has only one test (your program doesn't have to read anything).
Output
Output the name of the mysterious language. Note that the name is case-sensitive and might contain digits and special characters.
Examples
Note
Some scientists disagree on what should be considered as a language and what should be considered as a dialect. | instruction | 0 | 43,329 | 6 | 86,658 |
Tags: *special
Correct Solution:
```
"""====================================================================================
====================================================================================
___ _______ ___ _______ ___ ___
| /\ | | \ | | / | | | | |\ /|
| / \ | | \ | | / | | | | | \ / |
|___ /____\ | | \ | |/ |___| | | | \/ |
| / \ | | / | |\ |\ | | | |
| / \ | | / | | \ | \ | | | |
___|/ \___|___ |___/ ___|___ | \ | \ |___| | |
====================================================================================
====================================================================================
"""
# β₯β₯β₯β₯β₯β₯β₯β₯β₯β₯β₯β₯β₯β₯β₯β₯
print("INTERCAL")
# β₯β₯β₯β₯β₯β₯β₯β₯β₯β₯β₯β₯β₯β₯β₯β₯
"""====================================================================================
====================================================================================
___ _______ ___ _______ ___ ___
| /\ | | \ | | / | | | | |\ /|
| / \ | | \ | | / | | | | | \ / |
|___ /____\ | | \ | |/ |___| | | | \/ |
| / \ | | / | |\ |\ | | | |
| / \ | | / | | \ | \ | | | |
___|/ \___|___ |___/ ___|___ | \ | \ |___| | |
====================================================================================
====================================================================================
"""
``` | output | 1 | 43,329 | 6 | 86,659 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a mysterious language (codenamed "Secret") available in "Custom Invocation" tab. Figure out what this language is and write a program which prints its name. Note that the program must be written in this language.
Input
This program has only one test (your program doesn't have to read anything).
Output
Output the name of the mysterious language. Note that the name is case-sensitive and might contain digits and special characters.
Examples
Note
Some scientists disagree on what should be considered as a language and what should be considered as a dialect. | instruction | 0 | 43,330 | 6 | 86,660 |
Tags: *special
Correct Solution:
```
print("INTERCAL")
# This is my code
``` | output | 1 | 43,330 | 6 | 86,661 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a mysterious language (codenamed "Secret") available in "Custom Invocation" tab. Figure out what this language is and write a program which prints its name. Note that the program must be written in this language.
Input
This program has only one test (your program doesn't have to read anything).
Output
Output the name of the mysterious language. Note that the name is case-sensitive and might contain digits and special characters.
Examples
Note
Some scientists disagree on what should be considered as a language and what should be considered as a dialect. | instruction | 0 | 43,331 | 6 | 86,662 |
Tags: *special
Correct Solution:
```
print("INTERCAL")
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1
``` | output | 1 | 43,331 | 6 | 86,663 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a mysterious language (codenamed "Secret") available in "Custom Invocation" tab. Figure out what this language is and write a program which prints its name. Note that the program must be written in this language.
Input
This program has only one test (your program doesn't have to read anything).
Output
Output the name of the mysterious language. Note that the name is case-sensitive and might contain digits and special characters.
Examples
Note
Some scientists disagree on what should be considered as a language and what should be considered as a dialect. | instruction | 0 | 43,332 | 6 | 86,664 |
Tags: *special
Correct Solution:
```
n=input();print("INTERCAL")
``` | output | 1 | 43,332 | 6 | 86,665 |
Provide a correct Python 3 solution for this coding contest problem.
Find the edit distance between given two words s1 and s2.
The disntace is the minimum number of single-character edits required to change one word into the other. The edits including the following operations:
* insertion: Insert a character at a particular position.
* deletion: Delete a character at a particular position.
* substitution: Change the character at a particular position to a different character
Constraints
* 1 β€ length of s1 β€ 1000
* 1 β€ length of s2 β€ 1000
Input
s1
s2
Two words s1 and s2 are given in the first line and the second line respectively. The words will consist of lower case characters.
Output
Print the edit distance in a line.
Examples
Input
acac
acm
Output
2
Input
icpc
icpc
Output
0 | instruction | 0 | 43,789 | 6 | 87,578 |
"Correct Solution:
```
def levenshtein_dist(a,b):
a_size = len(a)
b_size = len(b)
inf = float('inf')
dp = [[a_size+b_size for i in range(a_size+1)] for _ in range(b_size+1)]
for i in range(b_size+1):
dp[i][0] = i
for j in range(a_size+1):
dp[0][j] = j
for i in range(1,b_size+1):
for j in range(1,a_size+1):
if a[j-1] == b[i-1]:
dp[i][j] = min(dp[i-1][j-1], dp[i-1][j]+1, dp[i][j-1]+1)
else:
dp[i][j] = min(dp[i-1][j-1]+1, dp[i-1][j]+1, dp[i][j-1]+1)
return dp
a = list(input())
b = list(input())
dp = levenshtein_dist(a,b)
print(dp[-1][-1])
``` | output | 1 | 43,789 | 6 | 87,579 |
Provide tags and a correct Python 3 solution for this coding contest problem.
While walking down the street Vanya saw a label "Hide&Seek". Because he is a programmer, he used & as a bitwise AND for these two words represented as a integers in base 64 and got new word. Now Vanya thinks of some string s and wants to know the number of pairs of words of length |s| (length of s), such that their bitwise AND is equal to s. As this number can be large, output it modulo 109 + 7.
To represent the string as a number in numeral system with base 64 Vanya uses the following rules:
* digits from '0' to '9' correspond to integers from 0 to 9;
* letters from 'A' to 'Z' correspond to integers from 10 to 35;
* letters from 'a' to 'z' correspond to integers from 36 to 61;
* letter '-' correspond to integer 62;
* letter '_' correspond to integer 63.
Input
The only line of the input contains a single word s (1 β€ |s| β€ 100 000), consisting of digits, lowercase and uppercase English letters, characters '-' and '_'.
Output
Print a single integer β the number of possible pairs of words, such that their bitwise AND is equal to string s modulo 109 + 7.
Examples
Input
z
Output
3
Input
V_V
Output
9
Input
Codeforces
Output
130653412
Note
For a detailed definition of bitwise AND we recommend to take a look in the corresponding article in Wikipedia.
In the first sample, there are 3 possible solutions:
1. z&_ = 61&63 = 61 = z
2. _&z = 63&61 = 61 = z
3. z&z = 61&61 = 61 = z | instruction | 0 | 44,276 | 6 | 88,552 |
Tags: bitmasks, combinatorics, implementation, strings
Correct Solution:
```
import string
charset = string.digits + string.ascii_uppercase + string.ascii_lowercase + "-_"
def getValue(char):
return charset.index(char)
def main():
string = input()
cnt = 1
dict = {}
for i in range(len(charset)):
for j in range(i + 1, len(charset)):
res = i & j
if res in dict:
dict[res] += 1
else:
dict[res] = 1
for char in string:
if getValue(char) in dict:
cnt = cnt * (1 + 2 * dict[getValue(char)]) % 1000000007
print(cnt)
if __name__ == "__main__":
main()
``` | output | 1 | 44,276 | 6 | 88,553 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The tycoon of a winery empire in Mondstadt, unmatched in every possible way. A thinker in the Knights of Favonius with an exotic appearance.
This time, the brothers are dealing with a strange piece of wood marked with their names. This plank of wood can be represented as a string of n characters. Each character is either a 'D' or a 'K'. You want to make some number of cuts (possibly 0) on this string, partitioning it into several contiguous pieces, each with length at least 1. Both brothers act with dignity, so they want to split the wood as evenly as possible. They want to know the maximum number of pieces you can split the wood into such that the ratios of the number of occurrences of 'D' to the number of occurrences of 'K' in each chunk are the same.
Kaeya, the curious thinker, is interested in the solution for multiple scenarios. He wants to know the answer for every prefix of the given string. Help him to solve this problem!
For a string we define a ratio as a:b where 'D' appears in it a times, and 'K' appears b times. Note that a or b can equal 0, but not both. Ratios a:b and c:d are considered equal if and only if aβ
d = bβ
c.
For example, for the string 'DDD' the ratio will be 3:0, for 'DKD' β 2:1, for 'DKK' β 1:2, and for 'KKKKDD' β 2:4. Note that the ratios of the latter two strings are equal to each other, but they are not equal to the ratios of the first two strings.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 1000). Description of the test cases follows.
The first line of each test case contains an integer n (1 β€ n β€ 5 β
10^5) β the length of the wood.
The second line of each test case contains a string s of length n. Every character of s will be either 'D' or 'K'.
It is guaranteed that the sum of n over all test cases does not exceed 5 β
10^5.
Output
For each test case, output n space separated integers. The i-th of these numbers should equal the answer for the prefix s_{1},s_{2},...,s_{i}.
Example
Input
5
3
DDK
6
DDDDDD
4
DKDK
1
D
9
DKDKDDDDK
Output
1 2 1
1 2 3 4 5 6
1 1 1 2
1
1 1 1 2 1 2 1 1 3
Note
For the first test case, there is no way to partition 'D' or 'DDK' into more than one block with equal ratios of numbers of 'D' and 'K', while you can split 'DD' into 'D' and 'D'.
For the second test case, you can split each prefix of length i into i blocks 'D'. | instruction | 0 | 44,837 | 6 | 89,674 |
Tags: data structures, dp, hashing, number theory
Correct Solution:
```
import math
a=[]
for s in[*open(0)][2::2]:
D={};d=k=0
for c in s[:-1]:
if c<'K':d+=1
else:k+=1
g=math.gcd(d,k);l=(d/g,k/g);D[l]=D.get(l,0)+1;a+=D[l],
print(*a)
``` | output | 1 | 44,837 | 6 | 89,675 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The tycoon of a winery empire in Mondstadt, unmatched in every possible way. A thinker in the Knights of Favonius with an exotic appearance.
This time, the brothers are dealing with a strange piece of wood marked with their names. This plank of wood can be represented as a string of n characters. Each character is either a 'D' or a 'K'. You want to make some number of cuts (possibly 0) on this string, partitioning it into several contiguous pieces, each with length at least 1. Both brothers act with dignity, so they want to split the wood as evenly as possible. They want to know the maximum number of pieces you can split the wood into such that the ratios of the number of occurrences of 'D' to the number of occurrences of 'K' in each chunk are the same.
Kaeya, the curious thinker, is interested in the solution for multiple scenarios. He wants to know the answer for every prefix of the given string. Help him to solve this problem!
For a string we define a ratio as a:b where 'D' appears in it a times, and 'K' appears b times. Note that a or b can equal 0, but not both. Ratios a:b and c:d are considered equal if and only if aβ
d = bβ
c.
For example, for the string 'DDD' the ratio will be 3:0, for 'DKD' β 2:1, for 'DKK' β 1:2, and for 'KKKKDD' β 2:4. Note that the ratios of the latter two strings are equal to each other, but they are not equal to the ratios of the first two strings.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 1000). Description of the test cases follows.
The first line of each test case contains an integer n (1 β€ n β€ 5 β
10^5) β the length of the wood.
The second line of each test case contains a string s of length n. Every character of s will be either 'D' or 'K'.
It is guaranteed that the sum of n over all test cases does not exceed 5 β
10^5.
Output
For each test case, output n space separated integers. The i-th of these numbers should equal the answer for the prefix s_{1},s_{2},...,s_{i}.
Example
Input
5
3
DDK
6
DDDDDD
4
DKDK
1
D
9
DKDKDDDDK
Output
1 2 1
1 2 3 4 5 6
1 1 1 2
1
1 1 1 2 1 2 1 1 3
Note
For the first test case, there is no way to partition 'D' or 'DDK' into more than one block with equal ratios of numbers of 'D' and 'K', while you can split 'DD' into 'D' and 'D'.
For the second test case, you can split each prefix of length i into i blocks 'D'. | instruction | 0 | 44,838 | 6 | 89,676 |
Tags: data structures, dp, hashing, number theory
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
from math import ceil, floor, pow, sqrt, gcd
from collections import Counter, defaultdict
from itertools import permutations, combinations
from time import time, sleep
BUFSIZE = 8192
MOD = 1000000007
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")
stdin, stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
from os import path
if path.exists('tc.txt'):
stdin = open('tc.txt', 'r')
def gmi(): return map(int, stdin.readline().strip().split())
def gms(): return map(str, stdin.readline().strip().split())
def gari(): return list(map(int, stdin.readline().strip().split()))
def gart(): return tuple(map(int, stdin.readline().strip().split()))
def gars(): return list(map(str, stdin.readline().strip().split()))
def gs(): return stdin.readline().strip()
def gls(): return list(stdin.readline().strip())
def gi(): return int(stdin.readline())
def pri(i): stdout.write(f"{i}\n")
def priar(ar): stdout.write(" ".join(map(str, ar))+"\n")
def prist(s): stdout.write("".join(map(str, s))+"\n")
dct = defaultdict(int)
tc = gi()
while tc:
tc -= 1
n = gi()
s = gs()
d, k = 0, 0
dct.clear()
for i in s:
if i == 'D':
d += 1
else:
k += 1
g = gcd(d, k)
rd, rk = d//g, k//g
dct[(rd, rk)] += 1
stdout.write(str(dct[rd, rk]) + " ")
stdout.write("\n")
``` | output | 1 | 44,838 | 6 | 89,677 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The tycoon of a winery empire in Mondstadt, unmatched in every possible way. A thinker in the Knights of Favonius with an exotic appearance.
This time, the brothers are dealing with a strange piece of wood marked with their names. This plank of wood can be represented as a string of n characters. Each character is either a 'D' or a 'K'. You want to make some number of cuts (possibly 0) on this string, partitioning it into several contiguous pieces, each with length at least 1. Both brothers act with dignity, so they want to split the wood as evenly as possible. They want to know the maximum number of pieces you can split the wood into such that the ratios of the number of occurrences of 'D' to the number of occurrences of 'K' in each chunk are the same.
Kaeya, the curious thinker, is interested in the solution for multiple scenarios. He wants to know the answer for every prefix of the given string. Help him to solve this problem!
For a string we define a ratio as a:b where 'D' appears in it a times, and 'K' appears b times. Note that a or b can equal 0, but not both. Ratios a:b and c:d are considered equal if and only if aβ
d = bβ
c.
For example, for the string 'DDD' the ratio will be 3:0, for 'DKD' β 2:1, for 'DKK' β 1:2, and for 'KKKKDD' β 2:4. Note that the ratios of the latter two strings are equal to each other, but they are not equal to the ratios of the first two strings.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 1000). Description of the test cases follows.
The first line of each test case contains an integer n (1 β€ n β€ 5 β
10^5) β the length of the wood.
The second line of each test case contains a string s of length n. Every character of s will be either 'D' or 'K'.
It is guaranteed that the sum of n over all test cases does not exceed 5 β
10^5.
Output
For each test case, output n space separated integers. The i-th of these numbers should equal the answer for the prefix s_{1},s_{2},...,s_{i}.
Example
Input
5
3
DDK
6
DDDDDD
4
DKDK
1
D
9
DKDKDDDDK
Output
1 2 1
1 2 3 4 5 6
1 1 1 2
1
1 1 1 2 1 2 1 1 3
Note
For the first test case, there is no way to partition 'D' or 'DDK' into more than one block with equal ratios of numbers of 'D' and 'K', while you can split 'DD' into 'D' and 'D'.
For the second test case, you can split each prefix of length i into i blocks 'D'. | instruction | 0 | 44,839 | 6 | 89,678 |
Tags: data structures, dp, hashing, number theory
Correct Solution:
```
import sys
input = sys.stdin.readline
from math import gcd
for _ in range(int(input())):
n = int(input())
s = input()[:-1]
seen = {}
x, y = 0, 0
ans = []
for i, c in enumerate(s):
if c == 'D': x += 1
else: y += 1
g = gcd(x, y)
x0 = x // g
y0 = y // g
if (x0, y0) not in seen:
seen[x0, y0] = 1
ans.append(1)
else:
seen[x0, y0] += 1
ans.append(seen[x0, y0])
print(*ans)
``` | output | 1 | 44,839 | 6 | 89,679 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The tycoon of a winery empire in Mondstadt, unmatched in every possible way. A thinker in the Knights of Favonius with an exotic appearance.
This time, the brothers are dealing with a strange piece of wood marked with their names. This plank of wood can be represented as a string of n characters. Each character is either a 'D' or a 'K'. You want to make some number of cuts (possibly 0) on this string, partitioning it into several contiguous pieces, each with length at least 1. Both brothers act with dignity, so they want to split the wood as evenly as possible. They want to know the maximum number of pieces you can split the wood into such that the ratios of the number of occurrences of 'D' to the number of occurrences of 'K' in each chunk are the same.
Kaeya, the curious thinker, is interested in the solution for multiple scenarios. He wants to know the answer for every prefix of the given string. Help him to solve this problem!
For a string we define a ratio as a:b where 'D' appears in it a times, and 'K' appears b times. Note that a or b can equal 0, but not both. Ratios a:b and c:d are considered equal if and only if aβ
d = bβ
c.
For example, for the string 'DDD' the ratio will be 3:0, for 'DKD' β 2:1, for 'DKK' β 1:2, and for 'KKKKDD' β 2:4. Note that the ratios of the latter two strings are equal to each other, but they are not equal to the ratios of the first two strings.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 1000). Description of the test cases follows.
The first line of each test case contains an integer n (1 β€ n β€ 5 β
10^5) β the length of the wood.
The second line of each test case contains a string s of length n. Every character of s will be either 'D' or 'K'.
It is guaranteed that the sum of n over all test cases does not exceed 5 β
10^5.
Output
For each test case, output n space separated integers. The i-th of these numbers should equal the answer for the prefix s_{1},s_{2},...,s_{i}.
Example
Input
5
3
DDK
6
DDDDDD
4
DKDK
1
D
9
DKDKDDDDK
Output
1 2 1
1 2 3 4 5 6
1 1 1 2
1
1 1 1 2 1 2 1 1 3
Note
For the first test case, there is no way to partition 'D' or 'DDK' into more than one block with equal ratios of numbers of 'D' and 'K', while you can split 'DD' into 'D' and 'D'.
For the second test case, you can split each prefix of length i into i blocks 'D'. | instruction | 0 | 44,840 | 6 | 89,680 |
Tags: data structures, dp, hashing, number theory
Correct Solution:
```
def gcd(a,b):
if b==0:
return a
return gcd(b,a%b)
for _ in range(int(input())):
n=int(input())
s=input()
ans=[0]*n
d=0
ans[0]=1
m={}
if s[0]=='D':
d=1
m[(1,0)]=1
else:
m[(0,1)]=1
for i in range(1,n):
if s[i]=='D':
d+=1
g=gcd(d,i+1-d)
a,b=d//g,(i+1-d)//g
if (a,b) not in m:
m[(a,b)]=1
else:
m[(a,b)]+=1
ans[i]=m[(a,b)]
print(*ans)
``` | output | 1 | 44,840 | 6 | 89,681 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The tycoon of a winery empire in Mondstadt, unmatched in every possible way. A thinker in the Knights of Favonius with an exotic appearance.
This time, the brothers are dealing with a strange piece of wood marked with their names. This plank of wood can be represented as a string of n characters. Each character is either a 'D' or a 'K'. You want to make some number of cuts (possibly 0) on this string, partitioning it into several contiguous pieces, each with length at least 1. Both brothers act with dignity, so they want to split the wood as evenly as possible. They want to know the maximum number of pieces you can split the wood into such that the ratios of the number of occurrences of 'D' to the number of occurrences of 'K' in each chunk are the same.
Kaeya, the curious thinker, is interested in the solution for multiple scenarios. He wants to know the answer for every prefix of the given string. Help him to solve this problem!
For a string we define a ratio as a:b where 'D' appears in it a times, and 'K' appears b times. Note that a or b can equal 0, but not both. Ratios a:b and c:d are considered equal if and only if aβ
d = bβ
c.
For example, for the string 'DDD' the ratio will be 3:0, for 'DKD' β 2:1, for 'DKK' β 1:2, and for 'KKKKDD' β 2:4. Note that the ratios of the latter two strings are equal to each other, but they are not equal to the ratios of the first two strings.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 1000). Description of the test cases follows.
The first line of each test case contains an integer n (1 β€ n β€ 5 β
10^5) β the length of the wood.
The second line of each test case contains a string s of length n. Every character of s will be either 'D' or 'K'.
It is guaranteed that the sum of n over all test cases does not exceed 5 β
10^5.
Output
For each test case, output n space separated integers. The i-th of these numbers should equal the answer for the prefix s_{1},s_{2},...,s_{i}.
Example
Input
5
3
DDK
6
DDDDDD
4
DKDK
1
D
9
DKDKDDDDK
Output
1 2 1
1 2 3 4 5 6
1 1 1 2
1
1 1 1 2 1 2 1 1 3
Note
For the first test case, there is no way to partition 'D' or 'DDK' into more than one block with equal ratios of numbers of 'D' and 'K', while you can split 'DD' into 'D' and 'D'.
For the second test case, you can split each prefix of length i into i blocks 'D'. | instruction | 0 | 44,841 | 6 | 89,682 |
Tags: data structures, dp, hashing, number theory
Correct Solution:
```
from sys import stdin, stdout
def arrin():
return list(map(int, stdin.readline().split()))
def num1in():
return int(stdin.readline())
def num2in():
a, b = map(int, stdin.readline().split())
return a, b
def num3in():
a, b, c = map(int, stdin.readline().split())
return a, b, c
def num4in():
a, b, c, d = map(int, stdin.readline().split())
return a, b, c, d
def num5in():
a, b, c, d, e = map(int, stdin.readline().split())
return a, b, c, d, e
t=num1in()
for test in range(t):
n=num1in()
s=input()
dict={}
ans=[]
d=0
k=0
prev=0
for i in s:
if(i=='D'):
d+=1
else:
k+=1
if(d==0 or k==0):
prev+=1
ans.append(prev)
else:
ratio = d/k
if(ratio in dict):
temp = dict[ratio] + 1
dict[ratio] = temp
ans.append(temp)
else:
temp=1
dict[ratio] = temp
ans.append(temp)
for i in ans:
print(i,end=" ")
print()
``` | output | 1 | 44,841 | 6 | 89,683 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The tycoon of a winery empire in Mondstadt, unmatched in every possible way. A thinker in the Knights of Favonius with an exotic appearance.
This time, the brothers are dealing with a strange piece of wood marked with their names. This plank of wood can be represented as a string of n characters. Each character is either a 'D' or a 'K'. You want to make some number of cuts (possibly 0) on this string, partitioning it into several contiguous pieces, each with length at least 1. Both brothers act with dignity, so they want to split the wood as evenly as possible. They want to know the maximum number of pieces you can split the wood into such that the ratios of the number of occurrences of 'D' to the number of occurrences of 'K' in each chunk are the same.
Kaeya, the curious thinker, is interested in the solution for multiple scenarios. He wants to know the answer for every prefix of the given string. Help him to solve this problem!
For a string we define a ratio as a:b where 'D' appears in it a times, and 'K' appears b times. Note that a or b can equal 0, but not both. Ratios a:b and c:d are considered equal if and only if aβ
d = bβ
c.
For example, for the string 'DDD' the ratio will be 3:0, for 'DKD' β 2:1, for 'DKK' β 1:2, and for 'KKKKDD' β 2:4. Note that the ratios of the latter two strings are equal to each other, but they are not equal to the ratios of the first two strings.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 1000). Description of the test cases follows.
The first line of each test case contains an integer n (1 β€ n β€ 5 β
10^5) β the length of the wood.
The second line of each test case contains a string s of length n. Every character of s will be either 'D' or 'K'.
It is guaranteed that the sum of n over all test cases does not exceed 5 β
10^5.
Output
For each test case, output n space separated integers. The i-th of these numbers should equal the answer for the prefix s_{1},s_{2},...,s_{i}.
Example
Input
5
3
DDK
6
DDDDDD
4
DKDK
1
D
9
DKDKDDDDK
Output
1 2 1
1 2 3 4 5 6
1 1 1 2
1
1 1 1 2 1 2 1 1 3
Note
For the first test case, there is no way to partition 'D' or 'DDK' into more than one block with equal ratios of numbers of 'D' and 'K', while you can split 'DD' into 'D' and 'D'.
For the second test case, you can split each prefix of length i into i blocks 'D'. | instruction | 0 | 44,842 | 6 | 89,684 |
Tags: data structures, dp, hashing, number theory
Correct Solution:
```
from math import gcd
import sys
input = sys.stdin.readline
def main():
N = int(input())
S = input()
Ans = []
Ratio = dict()
D = []
K = []
d = 0
k = 0
for i in range(N):
if S[i] == 'D': d += 1
else: k += 1
G = gcd(d, k)
R = (d // G, k // G)
if R not in Ratio: Ratio[R] = 1
else: Ratio[R] += 1
Ans.append(Ratio[R])
D.append(d)
K.append(k)
print(*Ans)
if __name__ == '__main__':
T = int(input())
for _ in range(T):
main()
``` | output | 1 | 44,842 | 6 | 89,685 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The tycoon of a winery empire in Mondstadt, unmatched in every possible way. A thinker in the Knights of Favonius with an exotic appearance.
This time, the brothers are dealing with a strange piece of wood marked with their names. This plank of wood can be represented as a string of n characters. Each character is either a 'D' or a 'K'. You want to make some number of cuts (possibly 0) on this string, partitioning it into several contiguous pieces, each with length at least 1. Both brothers act with dignity, so they want to split the wood as evenly as possible. They want to know the maximum number of pieces you can split the wood into such that the ratios of the number of occurrences of 'D' to the number of occurrences of 'K' in each chunk are the same.
Kaeya, the curious thinker, is interested in the solution for multiple scenarios. He wants to know the answer for every prefix of the given string. Help him to solve this problem!
For a string we define a ratio as a:b where 'D' appears in it a times, and 'K' appears b times. Note that a or b can equal 0, but not both. Ratios a:b and c:d are considered equal if and only if aβ
d = bβ
c.
For example, for the string 'DDD' the ratio will be 3:0, for 'DKD' β 2:1, for 'DKK' β 1:2, and for 'KKKKDD' β 2:4. Note that the ratios of the latter two strings are equal to each other, but they are not equal to the ratios of the first two strings.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 1000). Description of the test cases follows.
The first line of each test case contains an integer n (1 β€ n β€ 5 β
10^5) β the length of the wood.
The second line of each test case contains a string s of length n. Every character of s will be either 'D' or 'K'.
It is guaranteed that the sum of n over all test cases does not exceed 5 β
10^5.
Output
For each test case, output n space separated integers. The i-th of these numbers should equal the answer for the prefix s_{1},s_{2},...,s_{i}.
Example
Input
5
3
DDK
6
DDDDDD
4
DKDK
1
D
9
DKDKDDDDK
Output
1 2 1
1 2 3 4 5 6
1 1 1 2
1
1 1 1 2 1 2 1 1 3
Note
For the first test case, there is no way to partition 'D' or 'DDK' into more than one block with equal ratios of numbers of 'D' and 'K', while you can split 'DD' into 'D' and 'D'.
For the second test case, you can split each prefix of length i into i blocks 'D'. | instruction | 0 | 44,843 | 6 | 89,686 |
Tags: data structures, dp, hashing, number theory
Correct Solution:
```
import math
from collections import defaultdict
for _ in range(int(input())):
n=int(input())
s=input()
d=0;k=0
l=[]
c=defaultdict(int)
for i in range(n):
if s[i]=='D':
d+=1
else:
k+=1
if k==0 or d==0:
l.append(max(k,d))
else:
m=d
n=k
g=math.gcd(d,k)
m=m//g
n=n//g
c[(m,n)]+=1
l.append(c[m,n])
print(*l)
``` | output | 1 | 44,843 | 6 | 89,687 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The tycoon of a winery empire in Mondstadt, unmatched in every possible way. A thinker in the Knights of Favonius with an exotic appearance.
This time, the brothers are dealing with a strange piece of wood marked with their names. This plank of wood can be represented as a string of n characters. Each character is either a 'D' or a 'K'. You want to make some number of cuts (possibly 0) on this string, partitioning it into several contiguous pieces, each with length at least 1. Both brothers act with dignity, so they want to split the wood as evenly as possible. They want to know the maximum number of pieces you can split the wood into such that the ratios of the number of occurrences of 'D' to the number of occurrences of 'K' in each chunk are the same.
Kaeya, the curious thinker, is interested in the solution for multiple scenarios. He wants to know the answer for every prefix of the given string. Help him to solve this problem!
For a string we define a ratio as a:b where 'D' appears in it a times, and 'K' appears b times. Note that a or b can equal 0, but not both. Ratios a:b and c:d are considered equal if and only if aβ
d = bβ
c.
For example, for the string 'DDD' the ratio will be 3:0, for 'DKD' β 2:1, for 'DKK' β 1:2, and for 'KKKKDD' β 2:4. Note that the ratios of the latter two strings are equal to each other, but they are not equal to the ratios of the first two strings.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 1000). Description of the test cases follows.
The first line of each test case contains an integer n (1 β€ n β€ 5 β
10^5) β the length of the wood.
The second line of each test case contains a string s of length n. Every character of s will be either 'D' or 'K'.
It is guaranteed that the sum of n over all test cases does not exceed 5 β
10^5.
Output
For each test case, output n space separated integers. The i-th of these numbers should equal the answer for the prefix s_{1},s_{2},...,s_{i}.
Example
Input
5
3
DDK
6
DDDDDD
4
DKDK
1
D
9
DKDKDDDDK
Output
1 2 1
1 2 3 4 5 6
1 1 1 2
1
1 1 1 2 1 2 1 1 3
Note
For the first test case, there is no way to partition 'D' or 'DDK' into more than one block with equal ratios of numbers of 'D' and 'K', while you can split 'DD' into 'D' and 'D'.
For the second test case, you can split each prefix of length i into i blocks 'D'. | instruction | 0 | 44,844 | 6 | 89,688 |
Tags: data structures, dp, hashing, number theory
Correct Solution:
```
from collections import defaultdict
from math import gcd
for _ in range(int(input())):
n = int(input())
s = input()
D = [0] * n
K = [0] * n
if(s[0] == "D"):
D[0] = 1
else:
K[0] = 1
for i in range(1, n):
if(s[i] == "D"):
D[i] = D[i-1] + 1
K[i] = K[i-1]
else:
K[i] = K[i-1] + 1
D[i] = D[i-1]
ans = [1] * n
rat = defaultdict(int)
for i in range(n):
if(K[i] == 0):
rat[0] += 1
ans[i] = rat[0]
elif(D[i] == 0):
rat[0] += 1
ans[i] = rat[0]
else:
if(K[i] > D[i]):
x = gcd(K[i], D[i])
up = K[i]/x
down = D[i]/x
ans[i] += rat[(up,down,0)]
rat[(up, down, 0)]+=1
elif(K[i] == D[i]):
ans[i] += rat[1]
rat[1]+=1
else:
x = gcd(D[i], K[i])
up = D[i]/x
down = K[i]/x
ans[i] += rat[(up, down)]
rat[(up, down)] += 1
print(*ans)
``` | output | 1 | 44,844 | 6 | 89,689 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After you had helped Fedor to find friends in the Β«Call of Soldiers 3Β» game, he stopped studying completely. Today, the English teacher told him to prepare an essay. Fedor didn't want to prepare the essay, so he asked Alex for help. Alex came to help and wrote the essay for Fedor. But Fedor didn't like the essay at all. Now Fedor is going to change the essay using the synonym dictionary of the English language.
Fedor does not want to change the meaning of the essay. So the only change he would do: change a word from essay to one of its synonyms, basing on a replacement rule from the dictionary. Fedor may perform this operation any number of times.
As a result, Fedor wants to get an essay which contains as little letters Β«RΒ» (the case doesn't matter) as possible. If there are multiple essays with minimum number of Β«RΒ»s he wants to get the one with minimum length (length of essay is the sum of the lengths of all the words in it). Help Fedor get the required essay.
Please note that in this problem the case of letters doesn't matter. For example, if the synonym dictionary says that word cat can be replaced with word DOG, then it is allowed to replace the word Cat with the word doG.
Input
The first line contains a single integer m (1 β€ m β€ 105) β the number of words in the initial essay. The second line contains words of the essay. The words are separated by a single space. It is guaranteed that the total length of the words won't exceed 105 characters.
The next line contains a single integer n (0 β€ n β€ 105) β the number of pairs of words in synonym dictionary. The i-th of the next n lines contains two space-separated non-empty words xi and yi. They mean that word xi can be replaced with word yi (but not vise versa). It is guaranteed that the total length of all pairs of synonyms doesn't exceed 5Β·105 characters.
All the words at input can only consist of uppercase and lowercase letters of the English alphabet.
Output
Print two integers β the minimum number of letters Β«RΒ» in an optimal essay and the minimum length of an optimal essay.
Examples
Input
3
AbRb r Zz
4
xR abRb
aA xr
zz Z
xr y
Output
2 6
Input
2
RuruRu fedya
1
ruruRU fedor
Output
1 10 | instruction | 0 | 44,943 | 6 | 89,886 |
Tags: dfs and similar, dp, graphs, hashing, strings
Correct Solution:
```
from collections import defaultdict
m = int(input())
num = dict()
inp = lambda word: (word.count('R'), len(word), num.setdefault(word, len(num)))
text = list(map(inp, input().upper().split()))
q = text.copy()
n = int(input())
syn = defaultdict(list)
for i in range(n):
(word, replace) = map(inp, input().upper().split())
syn[replace[-1]].append(word[-1])
q.append(replace)
q.sort()
q.reverse()
best = dict()
while q:
(cnt_r, len, word) = q.pop()
if word not in best:
best[word] = (cnt_r, len)
for replace in syn[word]:
if replace not in best:
q.append((cnt_r, len, replace))
(rans, lans) = (0, 0)
for (cnt_r, len, word) in text:
(cnt_r, len) = best[word]
rans += cnt_r
lans += len
print(rans, lans)
``` | output | 1 | 44,943 | 6 | 89,887 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After you had helped Fedor to find friends in the Β«Call of Soldiers 3Β» game, he stopped studying completely. Today, the English teacher told him to prepare an essay. Fedor didn't want to prepare the essay, so he asked Alex for help. Alex came to help and wrote the essay for Fedor. But Fedor didn't like the essay at all. Now Fedor is going to change the essay using the synonym dictionary of the English language.
Fedor does not want to change the meaning of the essay. So the only change he would do: change a word from essay to one of its synonyms, basing on a replacement rule from the dictionary. Fedor may perform this operation any number of times.
As a result, Fedor wants to get an essay which contains as little letters Β«RΒ» (the case doesn't matter) as possible. If there are multiple essays with minimum number of Β«RΒ»s he wants to get the one with minimum length (length of essay is the sum of the lengths of all the words in it). Help Fedor get the required essay.
Please note that in this problem the case of letters doesn't matter. For example, if the synonym dictionary says that word cat can be replaced with word DOG, then it is allowed to replace the word Cat with the word doG.
Input
The first line contains a single integer m (1 β€ m β€ 105) β the number of words in the initial essay. The second line contains words of the essay. The words are separated by a single space. It is guaranteed that the total length of the words won't exceed 105 characters.
The next line contains a single integer n (0 β€ n β€ 105) β the number of pairs of words in synonym dictionary. The i-th of the next n lines contains two space-separated non-empty words xi and yi. They mean that word xi can be replaced with word yi (but not vise versa). It is guaranteed that the total length of all pairs of synonyms doesn't exceed 5Β·105 characters.
All the words at input can only consist of uppercase and lowercase letters of the English alphabet.
Output
Print two integers β the minimum number of letters Β«RΒ» in an optimal essay and the minimum length of an optimal essay.
Examples
Input
3
AbRb r Zz
4
xR abRb
aA xr
zz Z
xr y
Output
2 6
Input
2
RuruRu fedya
1
ruruRU fedor
Output
1 10 | instruction | 0 | 44,944 | 6 | 89,888 |
Tags: dfs and similar, dp, graphs, hashing, strings
Correct Solution:
```
from sys import stdin
from collections import defaultdict
def main():
stdin.readline()
num = {}
stat = lambda word: (word.count('r'),
len(word), num.setdefault(word, len(num)))
essay = list(map(stat, stdin.readline().lower().split()))
queue = []
for word in essay:
queue.append(word)
n_synonym = int(stdin.readline())
synonym = defaultdict(list)
for i in range(n_synonym):
word, rep = map(stat, stdin.readline().lower().split())
synonym[rep[2]].append(word[2])
queue.append(rep)
queue.sort(reverse=True)
best = {}
while queue:
n_r, length, word = queue.pop()
if word in best:
continue
best[word] = n_r, length
for rep in synonym[word]:
if rep not in best:
queue.append((n_r, length, rep))
sum_n_r, sum_len = 0, 0
for n_r, length, word in essay:
n_r, length = best[word]
sum_n_r += n_r
sum_len += length
print(sum_n_r, sum_len)
if __name__ == '__main__':
main()
``` | output | 1 | 44,944 | 6 | 89,889 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After you had helped Fedor to find friends in the Β«Call of Soldiers 3Β» game, he stopped studying completely. Today, the English teacher told him to prepare an essay. Fedor didn't want to prepare the essay, so he asked Alex for help. Alex came to help and wrote the essay for Fedor. But Fedor didn't like the essay at all. Now Fedor is going to change the essay using the synonym dictionary of the English language.
Fedor does not want to change the meaning of the essay. So the only change he would do: change a word from essay to one of its synonyms, basing on a replacement rule from the dictionary. Fedor may perform this operation any number of times.
As a result, Fedor wants to get an essay which contains as little letters Β«RΒ» (the case doesn't matter) as possible. If there are multiple essays with minimum number of Β«RΒ»s he wants to get the one with minimum length (length of essay is the sum of the lengths of all the words in it). Help Fedor get the required essay.
Please note that in this problem the case of letters doesn't matter. For example, if the synonym dictionary says that word cat can be replaced with word DOG, then it is allowed to replace the word Cat with the word doG.
Input
The first line contains a single integer m (1 β€ m β€ 105) β the number of words in the initial essay. The second line contains words of the essay. The words are separated by a single space. It is guaranteed that the total length of the words won't exceed 105 characters.
The next line contains a single integer n (0 β€ n β€ 105) β the number of pairs of words in synonym dictionary. The i-th of the next n lines contains two space-separated non-empty words xi and yi. They mean that word xi can be replaced with word yi (but not vise versa). It is guaranteed that the total length of all pairs of synonyms doesn't exceed 5Β·105 characters.
All the words at input can only consist of uppercase and lowercase letters of the English alphabet.
Output
Print two integers β the minimum number of letters Β«RΒ» in an optimal essay and the minimum length of an optimal essay.
Examples
Input
3
AbRb r Zz
4
xR abRb
aA xr
zz Z
xr y
Output
2 6
Input
2
RuruRu fedya
1
ruruRU fedor
Output
1 10 | instruction | 0 | 44,945 | 6 | 89,890 |
Tags: dfs and similar, dp, graphs, hashing, strings
Correct Solution:
```
from collections import defaultdict
input()
index = {}
stat = lambda word: (word.count('r'),
len(word), index.setdefault(word, len(index)))
essay = list(map(stat, input().lower().split()))
queue = essay[:]
syn = defaultdict(list)
for i in range(int(input())):
word, rep = map(stat, input().lower().split())
syn[rep[2]].append(word[2])
queue.append(rep)
queue.sort(reverse=True)
best = {}
while queue:
n_r, length, word = queue.pop()
if word in best:
continue
best[word] = n_r, length
for rep in syn[word]:
if rep not in best:
queue.append((n_r, length, rep))
sum_n_r, sum_len = 0, 0
for n_r, length in map(lambda w: best[w[2]], essay):
sum_n_r += n_r
sum_len += length
print(sum_n_r, sum_len)
``` | output | 1 | 44,945 | 6 | 89,891 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After you had helped Fedor to find friends in the Β«Call of Soldiers 3Β» game, he stopped studying completely. Today, the English teacher told him to prepare an essay. Fedor didn't want to prepare the essay, so he asked Alex for help. Alex came to help and wrote the essay for Fedor. But Fedor didn't like the essay at all. Now Fedor is going to change the essay using the synonym dictionary of the English language.
Fedor does not want to change the meaning of the essay. So the only change he would do: change a word from essay to one of its synonyms, basing on a replacement rule from the dictionary. Fedor may perform this operation any number of times.
As a result, Fedor wants to get an essay which contains as little letters Β«RΒ» (the case doesn't matter) as possible. If there are multiple essays with minimum number of Β«RΒ»s he wants to get the one with minimum length (length of essay is the sum of the lengths of all the words in it). Help Fedor get the required essay.
Please note that in this problem the case of letters doesn't matter. For example, if the synonym dictionary says that word cat can be replaced with word DOG, then it is allowed to replace the word Cat with the word doG.
Input
The first line contains a single integer m (1 β€ m β€ 105) β the number of words in the initial essay. The second line contains words of the essay. The words are separated by a single space. It is guaranteed that the total length of the words won't exceed 105 characters.
The next line contains a single integer n (0 β€ n β€ 105) β the number of pairs of words in synonym dictionary. The i-th of the next n lines contains two space-separated non-empty words xi and yi. They mean that word xi can be replaced with word yi (but not vise versa). It is guaranteed that the total length of all pairs of synonyms doesn't exceed 5Β·105 characters.
All the words at input can only consist of uppercase and lowercase letters of the English alphabet.
Output
Print two integers β the minimum number of letters Β«RΒ» in an optimal essay and the minimum length of an optimal essay.
Examples
Input
3
AbRb r Zz
4
xR abRb
aA xr
zz Z
xr y
Output
2 6
Input
2
RuruRu fedya
1
ruruRU fedor
Output
1 10 | instruction | 0 | 44,946 | 6 | 89,892 |
Tags: dfs and similar, dp, graphs, hashing, strings
Correct Solution:
```
import collections
def solve():
m = int(input())
essay = [s for s in input().lower().split()]
n = int(input())
sti = dict()
pack = lambda word: (word.count('r'), len(word), sti.setdefault(word, len(sti)))
edge = collections.defaultdict(list)
nodes = list()
for _ in range(n):
word, synon = map(pack, input().lower().split())
edge[synon[-1]].append(word[-1])
nodes.append(word)
nodes.append(synon)
nodes.sort()
best = dict()
for node in nodes:
if node[2] not in best:
stack = [node[2]]
while stack:
top = stack.pop()
if top not in best:
best[top] = node[:2]
for n in edge[top]:
if n is not best:
stack.append(n)
tr = 0
tl = 0
for word in essay:
if word in sti:
wid = sti[word]
tr += best[wid][0]
tl += best[wid][1]
else:
tr += word.count('r')
tl += len(word)
print(tr, ' ', tl)
if __name__ == '__main__':
solve()
``` | output | 1 | 44,946 | 6 | 89,893 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string s consisting of n lowercase English letters.
There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the end of it are also considered to be fillers. For example, the words ogo, ogogo, ogogogo are fillers, but the words go, og, ogog, ogogog and oggo are not fillers.
The fillers have maximal size, for example, for ogogoo speech we can't consider ogo a filler and goo as a normal phrase. We should consider ogogo as a filler here.
To print the interview, Polycarp has to replace each of the fillers with three asterisks. Note that a filler word is replaced with exactly three asterisks regardless of its length.
Polycarp has dealt with this problem in no time. Can you do the same? The clock is ticking!
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the length of the interview.
The second line contains the string s of length n, consisting of lowercase English letters.
Output
Print the interview text after the replacement of each of the fillers with "***". It is allowed for the substring "***" to have several consecutive occurences.
Examples
Input
7
aogogob
Output
a***b
Input
13
ogogmgogogogo
Output
***gmg***
Input
9
ogoogoogo
Output
*********
Note
The first sample contains one filler word ogogo, so the interview for printing is "a***b".
The second sample contains two fillers ogo and ogogogo. Thus, the interview is transformed to "***gmg***". | instruction | 0 | 45,015 | 6 | 90,030 |
Tags: implementation, strings
Correct Solution:
```
n=int(input())
s=input()
i=0
while i<n:
if s[i:i+3]=="ogo":
while s[i:i+3]=="ogo":
i+=2
print("***",end="")
else:print(s[i],end="")
i+=1
``` | output | 1 | 45,015 | 6 | 90,031 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string s consisting of n lowercase English letters.
There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the end of it are also considered to be fillers. For example, the words ogo, ogogo, ogogogo are fillers, but the words go, og, ogog, ogogog and oggo are not fillers.
The fillers have maximal size, for example, for ogogoo speech we can't consider ogo a filler and goo as a normal phrase. We should consider ogogo as a filler here.
To print the interview, Polycarp has to replace each of the fillers with three asterisks. Note that a filler word is replaced with exactly three asterisks regardless of its length.
Polycarp has dealt with this problem in no time. Can you do the same? The clock is ticking!
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the length of the interview.
The second line contains the string s of length n, consisting of lowercase English letters.
Output
Print the interview text after the replacement of each of the fillers with "***". It is allowed for the substring "***" to have several consecutive occurences.
Examples
Input
7
aogogob
Output
a***b
Input
13
ogogmgogogogo
Output
***gmg***
Input
9
ogoogoogo
Output
*********
Note
The first sample contains one filler word ogogo, so the interview for printing is "a***b".
The second sample contains two fillers ogo and ogogogo. Thus, the interview is transformed to "***gmg***". | instruction | 0 | 45,016 | 6 | 90,032 |
Tags: implementation, strings
Correct Solution:
```
n = int(input())
s = input()
while s.count("ogo") > 0:
i = 0
j = 0
while s[i:i + 3] != "ogo":
i += 1
if s[i:i + 3] == "ogo":
j = i + 3
while j + 2 <= len(s) and s[j:j + 2] == "go":
j += 2
s = s[:i] + "***" + s[j:]
print(s)
``` | output | 1 | 45,016 | 6 | 90,033 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string s consisting of n lowercase English letters.
There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the end of it are also considered to be fillers. For example, the words ogo, ogogo, ogogogo are fillers, but the words go, og, ogog, ogogog and oggo are not fillers.
The fillers have maximal size, for example, for ogogoo speech we can't consider ogo a filler and goo as a normal phrase. We should consider ogogo as a filler here.
To print the interview, Polycarp has to replace each of the fillers with three asterisks. Note that a filler word is replaced with exactly three asterisks regardless of its length.
Polycarp has dealt with this problem in no time. Can you do the same? The clock is ticking!
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the length of the interview.
The second line contains the string s of length n, consisting of lowercase English letters.
Output
Print the interview text after the replacement of each of the fillers with "***". It is allowed for the substring "***" to have several consecutive occurences.
Examples
Input
7
aogogob
Output
a***b
Input
13
ogogmgogogogo
Output
***gmg***
Input
9
ogoogoogo
Output
*********
Note
The first sample contains one filler word ogogo, so the interview for printing is "a***b".
The second sample contains two fillers ogo and ogogogo. Thus, the interview is transformed to "***gmg***". | instruction | 0 | 45,017 | 6 | 90,034 |
Tags: implementation, strings
Correct Solution:
```
if __name__ == '__main__':
n, s = int(input()), input()
result_array = []
left = 0
while left <= n - 3:
if s[left: left + 3] == 'ogo':
left += 3
if left >= n:
result_array.append('***')
break
while left + 1 < n and s[left: left + 2] == 'go':
left += 2
result_array.append('***')
else:
result_array.append(s[left])
left += 1
while left < n:
result_array.append(s[left])
left += 1
print(''.join(result_array))
``` | output | 1 | 45,017 | 6 | 90,035 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string s consisting of n lowercase English letters.
There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the end of it are also considered to be fillers. For example, the words ogo, ogogo, ogogogo are fillers, but the words go, og, ogog, ogogog and oggo are not fillers.
The fillers have maximal size, for example, for ogogoo speech we can't consider ogo a filler and goo as a normal phrase. We should consider ogogo as a filler here.
To print the interview, Polycarp has to replace each of the fillers with three asterisks. Note that a filler word is replaced with exactly three asterisks regardless of its length.
Polycarp has dealt with this problem in no time. Can you do the same? The clock is ticking!
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the length of the interview.
The second line contains the string s of length n, consisting of lowercase English letters.
Output
Print the interview text after the replacement of each of the fillers with "***". It is allowed for the substring "***" to have several consecutive occurences.
Examples
Input
7
aogogob
Output
a***b
Input
13
ogogmgogogogo
Output
***gmg***
Input
9
ogoogoogo
Output
*********
Note
The first sample contains one filler word ogogo, so the interview for printing is "a***b".
The second sample contains two fillers ogo and ogogogo. Thus, the interview is transformed to "***gmg***". | instruction | 0 | 45,018 | 6 | 90,036 |
Tags: implementation, strings
Correct Solution:
```
#
# Created by Polusummator on 25.10.2020
# --------- Little PyPy Squad ---------
# Verdict:
#
n = int(input())
s = input()
# ans = ''
# prev = ''
first = 'o' + 'go' * n
# print(first)
while first != 'o':
# print(first)
s = s.replace(first, '***')
n -= 1
first = 'o' + 'go' * n
print(s)
# for i in range(n):
# if s[i] != 'o' and s[i] != 'g':
# ans += s[i]
# elif s[i] == 'o':
# if prev
``` | output | 1 | 45,018 | 6 | 90,037 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string s consisting of n lowercase English letters.
There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the end of it are also considered to be fillers. For example, the words ogo, ogogo, ogogogo are fillers, but the words go, og, ogog, ogogog and oggo are not fillers.
The fillers have maximal size, for example, for ogogoo speech we can't consider ogo a filler and goo as a normal phrase. We should consider ogogo as a filler here.
To print the interview, Polycarp has to replace each of the fillers with three asterisks. Note that a filler word is replaced with exactly three asterisks regardless of its length.
Polycarp has dealt with this problem in no time. Can you do the same? The clock is ticking!
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the length of the interview.
The second line contains the string s of length n, consisting of lowercase English letters.
Output
Print the interview text after the replacement of each of the fillers with "***". It is allowed for the substring "***" to have several consecutive occurences.
Examples
Input
7
aogogob
Output
a***b
Input
13
ogogmgogogogo
Output
***gmg***
Input
9
ogoogoogo
Output
*********
Note
The first sample contains one filler word ogogo, so the interview for printing is "a***b".
The second sample contains two fillers ogo and ogogogo. Thus, the interview is transformed to "***gmg***". | instruction | 0 | 45,019 | 6 | 90,038 |
Tags: implementation, strings
Correct Solution:
```
import re
n = int(input())
s = input()
s = s.lower()
while 'ogo' in s:
s = re.sub('o(go)+', '***', s)
print(s)
``` | output | 1 | 45,019 | 6 | 90,039 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string s consisting of n lowercase English letters.
There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the end of it are also considered to be fillers. For example, the words ogo, ogogo, ogogogo are fillers, but the words go, og, ogog, ogogog and oggo are not fillers.
The fillers have maximal size, for example, for ogogoo speech we can't consider ogo a filler and goo as a normal phrase. We should consider ogogo as a filler here.
To print the interview, Polycarp has to replace each of the fillers with three asterisks. Note that a filler word is replaced with exactly three asterisks regardless of its length.
Polycarp has dealt with this problem in no time. Can you do the same? The clock is ticking!
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the length of the interview.
The second line contains the string s of length n, consisting of lowercase English letters.
Output
Print the interview text after the replacement of each of the fillers with "***". It is allowed for the substring "***" to have several consecutive occurences.
Examples
Input
7
aogogob
Output
a***b
Input
13
ogogmgogogogo
Output
***gmg***
Input
9
ogoogoogo
Output
*********
Note
The first sample contains one filler word ogogo, so the interview for printing is "a***b".
The second sample contains two fillers ogo and ogogogo. Thus, the interview is transformed to "***gmg***". | instruction | 0 | 45,020 | 6 | 90,040 |
Tags: implementation, strings
Correct Solution:
```
# coding: utf-8
# In[155]:
n = int(input())
s = input()
# In[156]:
def findEnd(s, i):
k = i + 2
ans = i+2
while k + 2 < len(s):
if s[k+1:k+3] == "go":
ans = k+2
else:
break
k+=2
return ans
# In[157]:
def findOgogos(s):
return (s.find("ogo"), findEnd(s,s.find("ogo")))
# In[158]:
while "ogo" in s:
s = s[:s.find("ogo")]+"***"+s[findEnd(s,s.find("ogo"))+1:]
#print(s)
# In[159]:
print(s)
``` | output | 1 | 45,020 | 6 | 90,041 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string s consisting of n lowercase English letters.
There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the end of it are also considered to be fillers. For example, the words ogo, ogogo, ogogogo are fillers, but the words go, og, ogog, ogogog and oggo are not fillers.
The fillers have maximal size, for example, for ogogoo speech we can't consider ogo a filler and goo as a normal phrase. We should consider ogogo as a filler here.
To print the interview, Polycarp has to replace each of the fillers with three asterisks. Note that a filler word is replaced with exactly three asterisks regardless of its length.
Polycarp has dealt with this problem in no time. Can you do the same? The clock is ticking!
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the length of the interview.
The second line contains the string s of length n, consisting of lowercase English letters.
Output
Print the interview text after the replacement of each of the fillers with "***". It is allowed for the substring "***" to have several consecutive occurences.
Examples
Input
7
aogogob
Output
a***b
Input
13
ogogmgogogogo
Output
***gmg***
Input
9
ogoogoogo
Output
*********
Note
The first sample contains one filler word ogogo, so the interview for printing is "a***b".
The second sample contains two fillers ogo and ogogogo. Thus, the interview is transformed to "***gmg***". | instruction | 0 | 45,021 | 6 | 90,042 |
Tags: implementation, strings
Correct Solution:
```
import re
print(re.sub(r'o(go)+',r'***',[*open(0)][1]))
``` | output | 1 | 45,021 | 6 | 90,043 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string s consisting of n lowercase English letters.
There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the end of it are also considered to be fillers. For example, the words ogo, ogogo, ogogogo are fillers, but the words go, og, ogog, ogogog and oggo are not fillers.
The fillers have maximal size, for example, for ogogoo speech we can't consider ogo a filler and goo as a normal phrase. We should consider ogogo as a filler here.
To print the interview, Polycarp has to replace each of the fillers with three asterisks. Note that a filler word is replaced with exactly three asterisks regardless of its length.
Polycarp has dealt with this problem in no time. Can you do the same? The clock is ticking!
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the length of the interview.
The second line contains the string s of length n, consisting of lowercase English letters.
Output
Print the interview text after the replacement of each of the fillers with "***". It is allowed for the substring "***" to have several consecutive occurences.
Examples
Input
7
aogogob
Output
a***b
Input
13
ogogmgogogogo
Output
***gmg***
Input
9
ogoogoogo
Output
*********
Note
The first sample contains one filler word ogogo, so the interview for printing is "a***b".
The second sample contains two fillers ogo and ogogogo. Thus, the interview is transformed to "***gmg***". | instruction | 0 | 45,022 | 6 | 90,044 |
Tags: implementation, strings
Correct Solution:
```
s=input()
s=input()
sogo='og'*50
i=0
while i<len(s):
i=s.find('ogo')
if i==-1:
break
k=i+3
while k<len(s)+1 and s[i:k]==sogo[0:k-i]:
k=k+2
if k>=len(s) or s[i:k]!=sogo[0:k-i]:
srep=s[i:k-2]
else:
srep=s[i:k]
s=s.replace(srep,'***',1)
i=k
print(s)
``` | output | 1 | 45,022 | 6 | 90,045 |
Provide a correct Python 3 solution for this coding contest problem.
Limak can repeatedly remove one of the first two characters of a string, for example abcxyx \rightarrow acxyx \rightarrow cxyx \rightarrow cyx.
You are given N different strings S_1, S_2, \ldots, S_N. Among N \cdot (N-1) / 2 pairs (S_i, S_j), in how many pairs could Limak obtain one string from the other?
Constraints
* 2 \leq N \leq 200\,000
* S_i consists of lowercase English letters `a`-`z`.
* S_i \neq S_j
* 1 \leq |S_i|
* |S_1| + |S_2| + \ldots + |S_N| \leq 10^6
Input
Input is given from Standard Input in the following format.
N
S_1
S_2
\vdots
S_N
Output
Print the number of unordered pairs (S_i, S_j) where i \neq j and Limak can obtain one string from the other.
Examples
Input
3
abcxyx
cyx
abc
Output
1
Input
6
b
a
abc
c
d
ab
Output
5 | instruction | 0 | 45,161 | 6 | 90,322 |
"Correct Solution:
```
import sys
import string
input = sys.stdin.readline
from collections import defaultdict
N = int(input())
T = [input()[::-1].strip() for i in range(N)]
#N = 100
#M = 10000
#import random
#import string
#T = [''.join(random.choices(string.ascii_lowercase, k=random.randint(M,M))) for i in range(N)]
class TrieTree:
class Node:
def __init__(self):
#self.clue = defaultdict(int)
self.clue = [0]*26
self.ch = defaultdict(TrieTree.Node)
self.cnt = 0
self.end = False
def __init__(self):
self.root = self.Node()
def register(self,word):
node = self.root
for w in word:
node.cnt += 1
node = node.ch[w]
node.cnt += 1
node.end = True
def prefix(self, word):
node = self.root
for w in word:
if w not in node.ch:
return False
else:
node = node.ch[w]
return node
tt = TrieTree()
for word in T:
tt.register(word)
route = []
st = [tt.root]
while st:
node = st.pop()
route.append(node)
st.extend(node.ch.values())
f = lambda c : ord(c)-97
for node in route[::-1]:
for c,nnode in node.ch.items():
for i,v in enumerate(nnode.clue):
node.clue[i] += v
node.clue[f(c)] += nnode.cnt - nnode.clue[f(c)]
ans = 0
for word in T:
pre = word[:-1]
last = word[-1]
node = tt.prefix(pre)
if not node:
continue
ans += node.clue[f(last)] - 1
print(ans)
``` | output | 1 | 45,161 | 6 | 90,323 |
Provide a correct Python 3 solution for this coding contest problem.
Limak can repeatedly remove one of the first two characters of a string, for example abcxyx \rightarrow acxyx \rightarrow cxyx \rightarrow cyx.
You are given N different strings S_1, S_2, \ldots, S_N. Among N \cdot (N-1) / 2 pairs (S_i, S_j), in how many pairs could Limak obtain one string from the other?
Constraints
* 2 \leq N \leq 200\,000
* S_i consists of lowercase English letters `a`-`z`.
* S_i \neq S_j
* 1 \leq |S_i|
* |S_1| + |S_2| + \ldots + |S_N| \leq 10^6
Input
Input is given from Standard Input in the following format.
N
S_1
S_2
\vdots
S_N
Output
Print the number of unordered pairs (S_i, S_j) where i \neq j and Limak can obtain one string from the other.
Examples
Input
3
abcxyx
cyx
abc
Output
1
Input
6
b
a
abc
c
d
ab
Output
5 | instruction | 0 | 45,164 | 6 | 90,328 |
"Correct Solution:
```
class Trie:
class Node:
def __init__(self,c):
self.c=c
self.next_c_id={}
#self.common=0
self.end=-1
def __init__(self):
self.trie=[self.Node('')]
def add(self,id,s):
i=0
now=0
ary=[0]
while i<len(s) and s[i] in self.trie[now].next_c_id:
now=self.trie[now].next_c_id[s[i]]
ary.append(now)
#self.trie[now].common+=1
i+=1
while i<len(s):
self.trie[now].next_c_id[s[i]]=len(self.trie)
now=len(self.trie)
ary.append(now)
self.trie.append(self.Node(s[i]))
#self.trie[now].common+=1
i+=1
self.trie[now].end=id
return ary
def main(s):
tr=Trie()
s.sort(key=lambda x:len(x))
ans=0
for i,x in enumerate(s):
ary=tr.add(i,x)
seen=set(())
while ary:
id=ary.pop()
for nv in seen&tr.trie[id].next_c_id.keys():
if tr.trie[tr.trie[id].next_c_id[nv]].end>=0 and tr.trie[tr.trie[id].next_c_id[nv]].end!=i:
ans+=1
seen.add(tr.trie[id].c)
print(ans)
if __name__=='__main__':
a2n=lambda x:ord(x)-ord('a')
n=int(input())
s=[list(map(a2n,list(input()))) for _ in range(n)]
[x.reverse() for x in s]
main(s)
``` | output | 1 | 45,164 | 6 | 90,329 |
Provide a correct Python 3 solution for this coding contest problem.
Limak can repeatedly remove one of the first two characters of a string, for example abcxyx \rightarrow acxyx \rightarrow cxyx \rightarrow cyx.
You are given N different strings S_1, S_2, \ldots, S_N. Among N \cdot (N-1) / 2 pairs (S_i, S_j), in how many pairs could Limak obtain one string from the other?
Constraints
* 2 \leq N \leq 200\,000
* S_i consists of lowercase English letters `a`-`z`.
* S_i \neq S_j
* 1 \leq |S_i|
* |S_1| + |S_2| + \ldots + |S_N| \leq 10^6
Input
Input is given from Standard Input in the following format.
N
S_1
S_2
\vdots
S_N
Output
Print the number of unordered pairs (S_i, S_j) where i \neq j and Limak can obtain one string from the other.
Examples
Input
3
abcxyx
cyx
abc
Output
1
Input
6
b
a
abc
c
d
ab
Output
5 | instruction | 0 | 45,165 | 6 | 90,330 |
"Correct Solution:
```
class Trie():
def __init__(self,arrRev):
self.node = [ [] for _ in range(len(arrRev)) ]
# self.children = [ [ -1 for _ in range(ord('z')-ord('a'))] for _ in range(10**6+1) ]
self.children = [ {} for _ in range(10**6+1) ]
self.isHeadCharNode = [ False for _ in range( 10**6+1 ) ]
nodeNumbering = 1
for i,s in enumerate(arrRev):
currentNode = 0
for j,c in enumerate(list(s)):
self.node[i].append( currentNode )
if c not in self.children[currentNode]:
self.children[currentNode][c] = nodeNumbering
# print( currentNode, c, self.children[currentNode][c] )
nodeNumbering += 1
currentNode = self.children[currentNode][c]
self.isHeadCharNode[currentNode] = True
# print(currentNode, True)
def getAnsCount(self,arrRev):
ret = 0
for i,s in enumerate(arrRev):
prefixListOfLonger = set()
for j in range( len(s)-1, -1, -1 ):
# loop from leaf to root
c = s[j]
prefixListOfLonger.add(c)
currentNode = self.node[i][j]
for prefix in prefixListOfLonger:
if prefix in self.children[currentNode] and self.isHeadCharNode[self.children[currentNode][prefix]]:
# print(self.isHeadCharNode[self.children[currentNode][prefix]])
ret += 1
return ret
if __name__ == "__main__":
ans=""
N = int(input())
lstW=[]
for n in range(N):
lstW.append(input()[::-1])
# create Trie
trie=Trie(lstW)
ans = trie.getAnsCount(lstW) - N
print( ans )
``` | output | 1 | 45,165 | 6 | 90,331 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.
Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.
Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
Input
The first line contains a non-empty string s, consisting of lowercase Latin letters β that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105.
The next line contains integer k (0 β€ k β€ 13) β the number of forbidden pairs of letters.
Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
Output
Print the single number β the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
Examples
Input
ababa
1
ab
Output
2
Input
codeforces
2
do
cs
Output
1
Note
In the first sample you should remove two letters b.
In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution. | instruction | 0 | 45,639 | 6 | 91,278 |
Tags: greedy
Correct Solution:
```
######################################################
############Created by Devesh Kumar###################
#############devesh1102@gmail.com####################
##########For CodeForces(Devesh1102)#################
#####################2020#############################
######################################################
import sys
input = sys.stdin.readline
# import sys
import heapq
import copy
import math
import decimal
# import sys.stdout.flush as flush
# from decimal import *
#heapq.heapify(li)
#
#heapq.heappush(li,4)
#
#heapq.heappop(li)
#
# & Bitwise AND Operator 10 & 7 = 2
# | Bitwise OR Operator 10 | 7 = 15
# ^ Bitwise XOR Operator 10 ^ 7 = 13
# << Bitwise Left Shift operator 10<<2 = 40
# >> Bitwise Right Shift Operator
# '''############ ---- Input Functions ---- #######Start#####'''
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def insr2():
s = input()
return((s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
############ ---- Input Functions ---- #######End
# #####
def pr_list(a):
print(*a, sep=" ")
def main():
# tests = inp()
tests = 1
mod = 998244353
limit = 10**18
ans = 0
for test in range(tests):
s = insr()
n = len(s)
k = inp()
forbid = [[0 for i in range(26)] for j in range(26)]
for i in range(k):
a = insr()
forbid[ord(a[0]) - ord('a')][ord(a[1]) - ord('a')] = 1
forbid[ord(a[1]) - ord('a')][ord(a[0]) - ord('a')] = 1
dp = [sys.maxsize for i in range(26)]
dp[ord(s[0]) - ord('a')] = 0
for i in range(1,n):
# print(dp)
mini = sys.maxsize
for j in range(26):
if dp[j] != sys.maxsize and forbid[j][ord(s[i]) - ord('a')]!=1:
mini = min(mini,dp[j])
for j in range(26):
if dp[j]!= sys.maxsize:
dp[j] = dp[j] +1
dp[ord(s[i]) - ord('a')] = min(mini,i)
# print(dp)
print(min(dp))
if __name__== "__main__":
main()
``` | output | 1 | 45,639 | 6 | 91,279 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.
Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.
Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
Input
The first line contains a non-empty string s, consisting of lowercase Latin letters β that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105.
The next line contains integer k (0 β€ k β€ 13) β the number of forbidden pairs of letters.
Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
Output
Print the single number β the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
Examples
Input
ababa
1
ab
Output
2
Input
codeforces
2
do
cs
Output
1
Note
In the first sample you should remove two letters b.
In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution. | instruction | 0 | 45,640 | 6 | 91,280 |
Tags: greedy
Correct Solution:
```
s = input() + "#"
k = int(input())
arr = [input() for _ in range(k)]
res = 0
for t in arr:
a, b = 0, 0
for i in range(len(s)):
if s[i] == t[0]:
a += 1
elif s[i] == t[1]:
b += 1
else:
if a and b:
res += min(a, b)
a, b = 0, 0
print(res)
``` | output | 1 | 45,640 | 6 | 91,281 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.
Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.
Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
Input
The first line contains a non-empty string s, consisting of lowercase Latin letters β that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105.
The next line contains integer k (0 β€ k β€ 13) β the number of forbidden pairs of letters.
Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
Output
Print the single number β the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
Examples
Input
ababa
1
ab
Output
2
Input
codeforces
2
do
cs
Output
1
Note
In the first sample you should remove two letters b.
In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution. | instruction | 0 | 45,641 | 6 | 91,282 |
Tags: greedy
Correct Solution:
```
import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
# from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
import copy
import time
starttime = time.time()
mod = int(pow(10, 9) + 7)
mod2 = 998244353
def data(): return sys.stdin.readline().strip()
def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end)
def L(): return list(sp())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]
try:
# sys.setrecursionlimit(int(pow(10,4)))
sys.stdin = open("input.txt", "r")
# sys.stdout = open("../output.txt", "w")
except:
pass
def pmat(A):
for ele in A:
print(*ele,end="\n")
# def seive():
# prime=[1 for i in range(10**6+1)]
# prime[0]=0
# prime[1]=0
# for i in range(10**6+1):
# if(prime[i]):
# for j in range(2*i,10**6+1,i):
# prime[j]=0
# return prime
s=input()
k=L()[0]
d={}
for i in range(k):
x=input()
d[x[0]]=x[1]
d[x[1]]=x[0]
A=[]
i=0
while(i<len(s)):
k1=1
k2=0
while((i+k1+k2)<len(s) and (s[i+k1+k2]==s[i] or s[i+k1+k2]==d.get(s[i],0))):
if s[i+k1+k2]==s[i]:
k1+=1
else:
k2+=1
A.append(max(k1,k2))
i+=(k1+k2)
print(len(s)-sum(A))
endtime = time.time()
# print(f"Runtime of the program is {endtime - starttime}")
``` | output | 1 | 45,641 | 6 | 91,283 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.