text stringlengths 594 23.8k | conversation_id int64 97 109k | embedding list | cluster int64 0 0 |
|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, the Fair Nut has written k strings of length n, consisting of letters "a" and "b". He calculated c — the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.
Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string s and not bigger than string t. He is interested: what is the maximum value of c that he could get.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains two integers n and k (1 ≤ n ≤ 5 ⋅ 10^5, 1 ≤ k ≤ 10^9).
The second line contains a string s (|s| = n) — the string consisting of letters "a" and "b.
The third line contains a string t (|t| = n) — the string consisting of letters "a" and "b.
It is guaranteed that string s is lexicographically not bigger than t.
Output
Print one number — maximal value of c.
Examples
Input
2 4
aa
bb
Output
6
Input
3 3
aba
bba
Output
8
Input
4 5
abbb
baaa
Output
8
Note
In the first example, Nut could write strings "aa", "ab", "ba", "bb". These 4 strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, 6 strings.
In the second example, Nut could write strings "aba", "baa", "bba".
In the third example, there are only two different strings that Nut could write. If both of them are written, c=8.
Tags: greedy, strings
Correct Solution:
```
# Author : nitish420 --------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
def main():
n,k=map(int,input().split())
s=list(input())
t=list(input())
z,ans=0,0
# idx=-1
# for i in range(n):
# if s[i]==t[i]:
# continue
# idx=i
# break
# if idx==-1:
# print(n)
# exit()
# else:
# ans+=idx+1
for i in range(n):
z=min(z*2+(t[i]=='b')-(s[i]=='b'),k)
ans+=min(z+1,k)
print(ans)
'''
10 1
bbbaaaabbb
bbbbaaabbb
'''
#----------------------------------------------------------------------------------------
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = 'x' in file.mode or 'r' not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b'\n') + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda: self.buffer.read().decode('ascii')
self.readline = lambda: self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
# endregion
if __name__ == '__main__':
main()
```
| 28,296 | [
0.52197265625,
-0.08135986328125,
0.5576171875,
0.34375,
-0.6240234375,
-0.658203125,
0.08514404296875,
-0.2113037109375,
-0.2132568359375,
0.65625,
0.65380859375,
0.0123443603515625,
0.0112152099609375,
-0.95458984375,
-0.80078125,
-0.033233642578125,
-0.5234375,
-0.2269287109375,... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, the Fair Nut has written k strings of length n, consisting of letters "a" and "b". He calculated c — the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.
Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string s and not bigger than string t. He is interested: what is the maximum value of c that he could get.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains two integers n and k (1 ≤ n ≤ 5 ⋅ 10^5, 1 ≤ k ≤ 10^9).
The second line contains a string s (|s| = n) — the string consisting of letters "a" and "b.
The third line contains a string t (|t| = n) — the string consisting of letters "a" and "b.
It is guaranteed that string s is lexicographically not bigger than t.
Output
Print one number — maximal value of c.
Examples
Input
2 4
aa
bb
Output
6
Input
3 3
aba
bba
Output
8
Input
4 5
abbb
baaa
Output
8
Note
In the first example, Nut could write strings "aa", "ab", "ba", "bb". These 4 strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, 6 strings.
In the second example, Nut could write strings "aba", "baa", "bba".
In the third example, there are only two different strings that Nut could write. If both of them are written, c=8.
Tags: greedy, strings
Correct Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------------------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a+b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class SegmentTree1:
def __init__(self, data, default=10**6, func=lambda a, b: min(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
MOD=10**9+7
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(10)]
pp=[0]*10
def SieveOfEratosthenes(n=10):
p = 2
c=0
while (p * p <= n):
if (prime[p] == True):
c+=1
for i in range(p, n+1, p):
pp[i]+=1
prime[i] = False
p += 1
#---------------------------------Binary Search------------------------------------------
def binarySearch(arr, n, key):
left = 0
right = n-1
mid = 0
res=arr[n-1]
while (left <= right):
mid = (right + left)//2
if (arr[mid] >= key):
res=arr[mid]
right = mid-1
else:
left = mid + 1
return res
def binarySearch1(arr, n, key):
left = 0
right = n-1
mid = 0
res=arr[0]
while (left <= right):
mid = (right + left)//2
if (arr[mid] > key):
right = mid-1
else:
res=arr[mid]
left = mid + 1
return res
#---------------------------------running code------------------------------------------
n, k = map(int, input().split())
a = input()
b = input()
res = 0
ans = 0
for i in range(0, n):
res = min(res * 2 + (b[i] == 'b') - (a[i] == 'b'), k)
ans += min(res + 1, k)
print(ans)
```
| 28,297 | [
0.50341796875,
-0.08355712890625,
0.56005859375,
0.348388671875,
-0.64208984375,
-0.6640625,
0.055023193359375,
-0.2349853515625,
-0.2081298828125,
0.671875,
0.64111328125,
-0.0112457275390625,
0.0279998779296875,
-0.93408203125,
-0.79052734375,
-0.0247039794921875,
-0.53125,
-0.21... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, the Fair Nut has written k strings of length n, consisting of letters "a" and "b". He calculated c — the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.
Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string s and not bigger than string t. He is interested: what is the maximum value of c that he could get.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains two integers n and k (1 ≤ n ≤ 5 ⋅ 10^5, 1 ≤ k ≤ 10^9).
The second line contains a string s (|s| = n) — the string consisting of letters "a" and "b.
The third line contains a string t (|t| = n) — the string consisting of letters "a" and "b.
It is guaranteed that string s is lexicographically not bigger than t.
Output
Print one number — maximal value of c.
Examples
Input
2 4
aa
bb
Output
6
Input
3 3
aba
bba
Output
8
Input
4 5
abbb
baaa
Output
8
Note
In the first example, Nut could write strings "aa", "ab", "ba", "bb". These 4 strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, 6 strings.
In the second example, Nut could write strings "aba", "baa", "bba".
In the third example, there are only two different strings that Nut could write. If both of them are written, c=8.
Tags: greedy, strings
Correct Solution:
```
n,k=map(int,input().split())
s,t,cu=input(),input(),[1]
for i in range(n):
cu+=[cu[-1]*2-(s[i]=='b')-(t[i]=='a')]
if cu[-1]>=k:cu[-1]=k;break
print(sum(cu)+(n-i-1)*k-1)
```
| 28,298 | [
0.446533203125,
-0.088134765625,
0.59521484375,
0.30126953125,
-0.6513671875,
-0.65869140625,
0.0732421875,
-0.2186279296875,
-0.2122802734375,
0.6767578125,
0.6865234375,
-0.0040740966796875,
0.038909912109375,
-0.9775390625,
-0.826171875,
0.009185791015625,
-0.59814453125,
-0.213... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, the Fair Nut has written k strings of length n, consisting of letters "a" and "b". He calculated c — the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.
Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string s and not bigger than string t. He is interested: what is the maximum value of c that he could get.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains two integers n and k (1 ≤ n ≤ 5 ⋅ 10^5, 1 ≤ k ≤ 10^9).
The second line contains a string s (|s| = n) — the string consisting of letters "a" and "b.
The third line contains a string t (|t| = n) — the string consisting of letters "a" and "b.
It is guaranteed that string s is lexicographically not bigger than t.
Output
Print one number — maximal value of c.
Examples
Input
2 4
aa
bb
Output
6
Input
3 3
aba
bba
Output
8
Input
4 5
abbb
baaa
Output
8
Note
In the first example, Nut could write strings "aa", "ab", "ba", "bb". These 4 strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, 6 strings.
In the second example, Nut could write strings "aba", "baa", "bba".
In the third example, there are only two different strings that Nut could write. If both of them are written, c=8.
Tags: greedy, strings
Correct Solution:
```
d = {'a': 0, 'b': 1}
def process(s, t, k):
n = len(s)
answer = 0
D = 0
final_i = n
for i in range(n):
d1 = d[s[i]]
d2 = d[t[i]]
D = 2*(D)+d2-d1
if D+1 < k:
answer+=(D+1)
else:
final_i = i
break
answer+=k*(n-final_i)
return answer
n, k = [int(x) for x in input().split()]
s = input()
t = input()
print(process(s, t, k))
```
| 28,299 | [
0.43896484375,
-0.10406494140625,
0.607421875,
0.3330078125,
-0.64208984375,
-0.65234375,
0.0782470703125,
-0.26806640625,
-0.175048828125,
0.68115234375,
0.65869140625,
0.003223419189453125,
0.02630615234375,
-0.919921875,
-0.8349609375,
-0.0113983154296875,
-0.5986328125,
-0.2100... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, the Fair Nut has written k strings of length n, consisting of letters "a" and "b". He calculated c — the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.
Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string s and not bigger than string t. He is interested: what is the maximum value of c that he could get.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains two integers n and k (1 ≤ n ≤ 5 ⋅ 10^5, 1 ≤ k ≤ 10^9).
The second line contains a string s (|s| = n) — the string consisting of letters "a" and "b.
The third line contains a string t (|t| = n) — the string consisting of letters "a" and "b.
It is guaranteed that string s is lexicographically not bigger than t.
Output
Print one number — maximal value of c.
Examples
Input
2 4
aa
bb
Output
6
Input
3 3
aba
bba
Output
8
Input
4 5
abbb
baaa
Output
8
Note
In the first example, Nut could write strings "aa", "ab", "ba", "bb". These 4 strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, 6 strings.
In the second example, Nut could write strings "aba", "baa", "bba".
In the third example, there are only two different strings that Nut could write. If both of them are written, c=8.
Tags: greedy, strings
Correct Solution:
```
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
from io import BytesIO, IOBase
import sys
def main():
n, k = map(int, input().split())
s = input().strip()
t = input().strip()
diff, ans = 0, 0
for i in range(n):
if diff + 1 < k:
diff <<= 1
if s[i] == 'b':
diff -= 1
if t[i] == 'b':
diff += 1
ans += min(k, diff + 1)
print(ans)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
```
| 28,300 | [
0.445556640625,
-0.09295654296875,
0.58544921875,
0.26171875,
-0.64013671875,
-0.63720703125,
0.10687255859375,
-0.254150390625,
-0.1728515625,
0.72021484375,
0.63037109375,
-0.03717041015625,
0.0859375,
-0.93505859375,
-0.8271484375,
-0.039642333984375,
-0.56396484375,
-0.16528320... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently, the Fair Nut has written k strings of length n, consisting of letters "a" and "b". He calculated c — the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.
Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string s and not bigger than string t. He is interested: what is the maximum value of c that he could get.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains two integers n and k (1 ≤ n ≤ 5 ⋅ 10^5, 1 ≤ k ≤ 10^9).
The second line contains a string s (|s| = n) — the string consisting of letters "a" and "b.
The third line contains a string t (|t| = n) — the string consisting of letters "a" and "b.
It is guaranteed that string s is lexicographically not bigger than t.
Output
Print one number — maximal value of c.
Examples
Input
2 4
aa
bb
Output
6
Input
3 3
aba
bba
Output
8
Input
4 5
abbb
baaa
Output
8
Note
In the first example, Nut could write strings "aa", "ab", "ba", "bb". These 4 strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, 6 strings.
In the second example, Nut could write strings "aba", "baa", "bba".
In the third example, there are only two different strings that Nut could write. If both of them are written, c=8.
Tags: greedy, strings
Correct Solution:
```
n, k = map(int, input().split())
a = input()
b = input()
res = 0
ans = 0
for i in range(0, n):
res = min(res * 2 + (b[i] == 'b') - (a[i] == 'b'), k)
ans += min(res + 1, k)
print(ans)
```
| 28,301 | [
0.457763671875,
-0.09051513671875,
0.6064453125,
0.264892578125,
-0.6142578125,
-0.66796875,
0.07135009765625,
-0.253662109375,
-0.1685791015625,
0.697265625,
0.69921875,
-0.0079498291015625,
0.02423095703125,
-0.9501953125,
-0.83154296875,
-0.01531982421875,
-0.60888671875,
-0.188... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, the Fair Nut has written k strings of length n, consisting of letters "a" and "b". He calculated c — the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.
Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string s and not bigger than string t. He is interested: what is the maximum value of c that he could get.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains two integers n and k (1 ≤ n ≤ 5 ⋅ 10^5, 1 ≤ k ≤ 10^9).
The second line contains a string s (|s| = n) — the string consisting of letters "a" and "b.
The third line contains a string t (|t| = n) — the string consisting of letters "a" and "b.
It is guaranteed that string s is lexicographically not bigger than t.
Output
Print one number — maximal value of c.
Examples
Input
2 4
aa
bb
Output
6
Input
3 3
aba
bba
Output
8
Input
4 5
abbb
baaa
Output
8
Note
In the first example, Nut could write strings "aa", "ab", "ba", "bb". These 4 strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, 6 strings.
In the second example, Nut could write strings "aba", "baa", "bba".
In the third example, there are only two different strings that Nut could write. If both of them are written, c=8.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
# ------------------------------
def c(ca, cb):
return ord(cb)-ord(ca)
def main():
n, k = RL()
s = input()
t = input()
res = 0
tag = 0
for i in range(n):
if s[i]==t[i]: res+=1
else: tag = i; break
num = 2
for j in range(tag, n):
if s[j]=='b': num-=1
if t[j]=='a': num-=1
if num>=k: res+=k*(n-j); break
res+=num
num*=2
print(res)
if __name__ == "__main__":
main()
```
No
| 28,302 | [
0.4296875,
-0.196044921875,
0.48486328125,
0.320556640625,
-0.68212890625,
-0.472412109375,
0.0697021484375,
-0.0836181640625,
-0.1934814453125,
0.66357421875,
0.57421875,
0.0167694091796875,
0.0097198486328125,
-1.0009765625,
-0.79296875,
0.0207672119140625,
-0.58349609375,
-0.215... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, the Fair Nut has written k strings of length n, consisting of letters "a" and "b". He calculated c — the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.
Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string s and not bigger than string t. He is interested: what is the maximum value of c that he could get.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains two integers n and k (1 ≤ n ≤ 5 ⋅ 10^5, 1 ≤ k ≤ 10^9).
The second line contains a string s (|s| = n) — the string consisting of letters "a" and "b.
The third line contains a string t (|t| = n) — the string consisting of letters "a" and "b.
It is guaranteed that string s is lexicographically not bigger than t.
Output
Print one number — maximal value of c.
Examples
Input
2 4
aa
bb
Output
6
Input
3 3
aba
bba
Output
8
Input
4 5
abbb
baaa
Output
8
Note
In the first example, Nut could write strings "aa", "ab", "ba", "bb". These 4 strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, 6 strings.
In the second example, Nut could write strings "aba", "baa", "bba".
In the third example, there are only two different strings that Nut could write. If both of them are written, c=8.
Submitted Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------------------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a+b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class SegmentTree1:
def __init__(self, data, default=10**6, func=lambda a, b: min(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
MOD=10**9+7
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(10)]
pp=[0]*10
def SieveOfEratosthenes(n=10):
p = 2
c=0
while (p * p <= n):
if (prime[p] == True):
c+=1
for i in range(p, n+1, p):
pp[i]+=1
prime[i] = False
p += 1
#---------------------------------Binary Search------------------------------------------
def binarySearch(arr, n, key):
left = 0
right = n-1
mid = 0
res=arr[n-1]
while (left <= right):
mid = (right + left)//2
if (arr[mid] >= key):
res=arr[mid]
right = mid-1
else:
left = mid + 1
return res
def binarySearch1(arr, n, key):
left = 0
right = n-1
mid = 0
res=arr[0]
while (left <= right):
mid = (right + left)//2
if (arr[mid] > key):
right = mid-1
else:
res=arr[mid]
left = mid + 1
return res
#---------------------------------running code------------------------------------------
n,k=map(int,input().split())
s=input()
t=input()
res=0
ct,cs=0,0
for i in range (n):
if ct-cs>=k:
res+=k
continue
ct,cs=2*ct,2*cs
if s[i]=='b':
cs+=2
if t[i]=='b':
ct+=2
d=min(k,ct-cs)
res+=d
print(res)
```
No
| 28,303 | [
0.51806640625,
-0.1141357421875,
0.431396484375,
0.3828125,
-0.7314453125,
-0.490478515625,
-0.034210205078125,
0.0151214599609375,
-0.283935546875,
0.662109375,
0.59619140625,
0.07061767578125,
-0.0712890625,
-0.97998046875,
-0.826171875,
-0.029632568359375,
-0.51953125,
-0.227050... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, the Fair Nut has written k strings of length n, consisting of letters "a" and "b". He calculated c — the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.
Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string s and not bigger than string t. He is interested: what is the maximum value of c that he could get.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains two integers n and k (1 ≤ n ≤ 5 ⋅ 10^5, 1 ≤ k ≤ 10^9).
The second line contains a string s (|s| = n) — the string consisting of letters "a" and "b.
The third line contains a string t (|t| = n) — the string consisting of letters "a" and "b.
It is guaranteed that string s is lexicographically not bigger than t.
Output
Print one number — maximal value of c.
Examples
Input
2 4
aa
bb
Output
6
Input
3 3
aba
bba
Output
8
Input
4 5
abbb
baaa
Output
8
Note
In the first example, Nut could write strings "aa", "ab", "ba", "bb". These 4 strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, 6 strings.
In the second example, Nut could write strings "aba", "baa", "bba".
In the third example, there are only two different strings that Nut could write. If both of them are written, c=8.
Submitted Solution:
```
d = {'a': 0, 'b': 1}
def process(s, t, k):
n = len(s)
answer = 0
D = 0
final_i = n
for i in range(n):
d1 = d[s[i]]
d2 = d[t[i]]
D = 2*(D)+d1-d2
if D < k:
answer+=D
else:
final_i = i
break
answer+=k*(n-final_i)
return answer
n, k = [int(x) for x in input().split()]
s = input()
t = input()
print(process(s, t, k))
```
No
| 28,304 | [
0.420654296875,
-0.1434326171875,
0.53369140625,
0.2763671875,
-0.734375,
-0.46533203125,
-0.030487060546875,
-0.105712890625,
-0.250244140625,
0.64501953125,
0.59375,
0.058258056640625,
-0.028564453125,
-0.95703125,
-0.85009765625,
-0.036529541015625,
-0.64306640625,
-0.1800537109... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently, the Fair Nut has written k strings of length n, consisting of letters "a" and "b". He calculated c — the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.
Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string s and not bigger than string t. He is interested: what is the maximum value of c that he could get.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains two integers n and k (1 ≤ n ≤ 5 ⋅ 10^5, 1 ≤ k ≤ 10^9).
The second line contains a string s (|s| = n) — the string consisting of letters "a" and "b.
The third line contains a string t (|t| = n) — the string consisting of letters "a" and "b.
It is guaranteed that string s is lexicographically not bigger than t.
Output
Print one number — maximal value of c.
Examples
Input
2 4
aa
bb
Output
6
Input
3 3
aba
bba
Output
8
Input
4 5
abbb
baaa
Output
8
Note
In the first example, Nut could write strings "aa", "ab", "ba", "bb". These 4 strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, 6 strings.
In the second example, Nut could write strings "aba", "baa", "bba".
In the third example, there are only two different strings that Nut could write. If both of them are written, c=8.
Submitted Solution:
```
n,k=map(int,input().split())
s=input()
t=input()
res,tp=0,1
for i in range(n):
tp*=2
if s[i]=='b':
tp-=1
if t[i]=='a':
tp-=1
res+=min(tp,k)
tp=min(tp,k)
print(res)
```
No
| 28,305 | [
0.44482421875,
-0.10943603515625,
0.50390625,
0.27490234375,
-0.71240234375,
-0.499267578125,
0.0006918907165527344,
-0.0782470703125,
-0.26318359375,
0.6494140625,
0.62353515625,
0.043182373046875,
-0.01433563232421875,
-0.99609375,
-0.86279296875,
-0.046966552734375,
-0.6083984375,... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.
Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').
Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.
Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.
It is guaranteed that the answer exists.
Input
The first line of the input contains one integer n (3 ≤ n ≤ 3 ⋅ 10^5, n is divisible by 3) — the number of characters in s.
The second line contains the string s consisting of exactly n characters '0', '1' and '2'.
Output
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements.
Because n is divisible by 3 it is obvious that the answer exists. And it is obvious that there is only one possible answer.
Examples
Input
3
121
Output
021
Input
6
000000
Output
001122
Input
6
211200
Output
211200
Input
6
120110
Output
120120
Tags: greedy, strings
Correct Solution:
```
def replace(f :int, t :int, c :int):
if c == 0:
return
global s
tc = c
if t < f:
for i in range(n):
if tc == 0:
break
if s[i] == f:
s[i] = t
tc -= 1
else:
for i in range(n-1, -1, -1):
if tc == 0:
break
if s[i] == f:
s[i] = t
tc -= 1
n = int(input())
s = [int(z) for z in input().strip()]
c = [0] * 3
for i in range(3):
c[i] = s.count(i)
td = [0] * 3
for i in range(3):
td[i] = (n // 3) - c[i]
md = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for f in range(3):
for t in range(3):
if td[f] < 0 and td[t] > 0:
md[f][t] = min(abs(td[f]), abs(td[t]))
for (f, t) in ((0, 2), (2, 0), (0, 1), (1, 0), (1, 2), (2, 1)):
replace(f, t, md[f][t])
print(*s, sep='')
```
| 28,306 | [
0.1583251953125,
-0.03717041015625,
0.2353515625,
0.1953125,
-0.85400390625,
-0.67822265625,
0.471923828125,
-0.00405120849609375,
0.1339111328125,
0.84716796875,
0.7392578125,
0.0576171875,
-0.347412109375,
-0.6484375,
-0.75244140625,
-0.1871337890625,
-0.6025390625,
-0.6196289062... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.
Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').
Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.
Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.
It is guaranteed that the answer exists.
Input
The first line of the input contains one integer n (3 ≤ n ≤ 3 ⋅ 10^5, n is divisible by 3) — the number of characters in s.
The second line contains the string s consisting of exactly n characters '0', '1' and '2'.
Output
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements.
Because n is divisible by 3 it is obvious that the answer exists. And it is obvious that there is only one possible answer.
Examples
Input
3
121
Output
021
Input
6
000000
Output
001122
Input
6
211200
Output
211200
Input
6
120110
Output
120120
Tags: greedy, strings
Correct Solution:
```
from sys import stdin,stdout
# input=stdin.readline
mod=10**9+7
t=1
for _ in range(t):
n=int(input())
s=input()
a=s.count('0')
b=s.count('1')
c=s.count('2')
ans=[i for i in s]
val=n//3
ind=-1
while c>val:
ind+=1
if ans[ind]=='2':
c-=1
if a<val:
ans[ind]='0'
a+=1
else:
ans[ind]='1'
b+=1
for i in range(n):
if ans[i]=='1':
if b>val:
if a<val:
b-=1
a+=1
ans[i]='0'
for i in range(n-1,-1,-1):
if ans[i]=='1':
if b>val:
if c<val:
b-=1
c+=1
ans[i]='2'
for i in range(n-1,-1,-1):
if ans[i]=='0':
if a>val:
if c<val:
a-=1
c+=1
ans[i]='2'
for i in range(n-1,-1,-1):
if ans[i]=='0':
if a>val:
if b<val:
a-=1
b+=1
ans[i]='1'
print(''.join(ans))
```
| 28,307 | [
0.1334228515625,
-0.047607421875,
0.26708984375,
0.1568603515625,
-0.8837890625,
-0.70751953125,
0.431396484375,
0.057647705078125,
0.03399658203125,
0.86767578125,
0.66259765625,
0.01654052734375,
-0.27197265625,
-0.63623046875,
-0.748046875,
-0.1527099609375,
-0.58935546875,
-0.6... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.
Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').
Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.
Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.
It is guaranteed that the answer exists.
Input
The first line of the input contains one integer n (3 ≤ n ≤ 3 ⋅ 10^5, n is divisible by 3) — the number of characters in s.
The second line contains the string s consisting of exactly n characters '0', '1' and '2'.
Output
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements.
Because n is divisible by 3 it is obvious that the answer exists. And it is obvious that there is only one possible answer.
Examples
Input
3
121
Output
021
Input
6
000000
Output
001122
Input
6
211200
Output
211200
Input
6
120110
Output
120120
Tags: greedy, strings
Correct Solution:
```
if __name__ == '__main__':
n = int(input())
row = input()
totals = [row.count('0'), row.count('1'), row.count('2')]
flows = []
for i in range(3):
flows.append([0, 0, 0])
goal = n // 3
goals = [t - goal for t in totals]
for i, g in enumerate(goals):
if goals[i] > 0:
for j, g2 in enumerate(goals):
if g2 < 0:
flows[i][j] = min(goals[i], abs(g2))
goals[i] -= flows[i][j]
goals[j] += flows[i][j]
new_row = list(row)
ost = flows[0][2]
for i, s in enumerate(reversed(new_row)):
i = (i + 1) * -1
if ost:
if s == '0':
new_row[i] = '2'
ost -= 1
else:
break
ost = flows[0][1]
for i, s in enumerate(reversed(new_row)):
i = (i + 1) * -1
if ost:
if s == '0':
new_row[i] = '1'
ost -= 1
else:
break
ost = flows[1][2]
for i, s in enumerate(reversed(new_row)):
i = (i + 1) * -1
if ost:
if s == '1':
new_row[i] = '2'
ost -= 1
else:
break
# большее на меньшее
ost = flows[2][0]
for i, s in enumerate(new_row):
if ost:
if s == '2':
new_row[i] = '0'
ost -= 1
else:
break
ost = flows[2][1]
for i, s in enumerate(new_row):
if ost:
if s == '2':
new_row[i] = '1'
ost -= 1
else:
break
ost = flows[1][0]
for i, s in enumerate(new_row):
if ost:
if s == '1':
new_row[i] = '0'
ost -= 1
else:
break
print(''.join(new_row))
```
| 28,308 | [
0.114990234375,
0.04327392578125,
0.143798828125,
0.2578125,
-0.8271484375,
-0.6708984375,
0.43408203125,
0.10675048828125,
0.1668701171875,
0.68505859375,
0.556640625,
0.1168212890625,
-0.24609375,
-0.54833984375,
-0.73095703125,
-0.2325439453125,
-0.7529296875,
-0.623046875,
-0... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.
Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').
Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.
Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.
It is guaranteed that the answer exists.
Input
The first line of the input contains one integer n (3 ≤ n ≤ 3 ⋅ 10^5, n is divisible by 3) — the number of characters in s.
The second line contains the string s consisting of exactly n characters '0', '1' and '2'.
Output
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements.
Because n is divisible by 3 it is obvious that the answer exists. And it is obvious that there is only one possible answer.
Examples
Input
3
121
Output
021
Input
6
000000
Output
001122
Input
6
211200
Output
211200
Input
6
120110
Output
120120
Tags: greedy, strings
Correct Solution:
```
from collections import Counter
n = int(input())
s = input().strip()
x = n // 3
cnt = Counter(s)
cnt.update({'0': 0, '1': 0, '2': 0})
if cnt['0'] == cnt['1'] == cnt['2']:
print(s)
exit()
while max(cnt.values()) != min(cnt.values()):
p = cnt['0']
q = cnt['1']
r = cnt['2']
if r > x:
if p < x:
if r - x >= x - p:
s = s.replace('2', '0', x - p)
r = r - (x - p)
cnt['2'] = r
p = x
cnt['0'] = p
else:
s = s.replace('2', '0', r - x)
p = p + r - x
cnt['0'] = p
r = x
cnt['2'] = r
if q < x:
if r - x >= x - q:
s = s.replace('2', '1', x - q)
r = r - (x - q)
cnt['2'] = r
q = x
cnt['1'] = q
else:
s = s.replace('2', '1', r - x)
q = q + r - x
cnt['1'] = q
r = x
cnt['2'] = r
if q > x:
if p < x:
if q - x >= x - p:
s = s.replace('1', '0', x - p)
q = q - (x - p)
cnt['1'] = q
p = x
cnt['0'] = p
else:
s = s.replace('1', '0', q - x)
p = p + q - x
cnt['0'] = p
q = x
cnt['1'] = q
if r < x:
if q - x >= x - r:
s = (s[::-1].replace('1', '2', x - r))[::-1]
q = q - (x - r)
cnt['1'] = q
r = x
cnt['2'] = r
else:
s = (s[::-1].replace('1', '2', q - x))[::-1]
r = r + q - x
cnt['2'] = r
q = x
cnt['1'] = q
if p > x:
if r < x:
if p - x >= x - r:
s = s[::-1].replace('0', '2', x - r)[::-1]
p = p - (x - r)
cnt['0'] = p
r = x
cnt['2'] = r
else:
s = s[::-1].replace('0', '2', p - x)[::-1]
r = r + p - x
cnt['2'] = r
p = x
cnt['0'] = p
if q < x:
if p - x >= x - q:
s = (s[::-1].replace('0', '1', x - q))[::-1]
p = p - (x - q)
cnt['0'] = p
q = x
cnt['1'] = q
else:
s = (s[::-1].replace('0', '1', r - x))[::-1]
q = q + r - x
cnt['1'] = q
r = x
cnt['0'] = r
# print(s, cnt)
print(s)
```
| 28,309 | [
0.131591796875,
-0.00847625732421875,
0.1871337890625,
0.159912109375,
-0.8046875,
-0.67919921875,
0.50439453125,
0.045806884765625,
0.140869140625,
0.93017578125,
0.6708984375,
0.08087158203125,
-0.28759765625,
-0.62158203125,
-0.791015625,
-0.1727294921875,
-0.63525390625,
-0.633... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.
Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').
Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.
Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.
It is guaranteed that the answer exists.
Input
The first line of the input contains one integer n (3 ≤ n ≤ 3 ⋅ 10^5, n is divisible by 3) — the number of characters in s.
The second line contains the string s consisting of exactly n characters '0', '1' and '2'.
Output
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements.
Because n is divisible by 3 it is obvious that the answer exists. And it is obvious that there is only one possible answer.
Examples
Input
3
121
Output
021
Input
6
000000
Output
001122
Input
6
211200
Output
211200
Input
6
120110
Output
120120
Tags: greedy, strings
Correct Solution:
```
n = int(input())
m = n//3
s = list(input())
zero, one, two = 0, 0, 0
for si in s:
if si=='0':
zero += 1
elif si=='1':
one += 1
else:
two += 1
zero_lack = max(0, m-zero)
one_lack = max(0, m-one)
two_lack = max(0, m-two)
if zero>m:
zero_over = zero-m
for i in range(n-1, -1, -1):
if s[i]=='0':
if two_lack>0:
s[i] = '2'
two_lack -= 1
zero_over -= 1
elif one_lack>0:
s[i] = '1'
one_lack -= 1
zero_over -= 1
if zero_over==0:
break
if one>m:
one_over = one-m
for i in range(n):
if s[i]=='1':
if zero_lack>0:
s[i] = '0'
zero_lack -= 1
one_over -= 1
if one_over==0:
break
for i in range(n-1, -1, -1):
if s[i]=='1':
if two_lack>0:
s[i] = '2'
two_lack -= 1
one_over -= 1
if one_over==0:
break
if two>m:
two_over = two-m
for i in range(n):
if s[i]=='2':
if zero_lack>0:
s[i] = '0'
zero_lack -= 1
two_over -= 1
elif one_lack>0:
s[i] = '1'
one_lack -= 1
two_over -= 1
if two_over==0:
break
print(''.join(s))
```
| 28,310 | [
0.095947265625,
0.01425933837890625,
0.287353515625,
0.1990966796875,
-0.85791015625,
-0.7177734375,
0.444580078125,
0.0811767578125,
0.04266357421875,
0.88818359375,
0.7119140625,
0.028839111328125,
-0.17529296875,
-0.591796875,
-0.755859375,
-0.14306640625,
-0.54248046875,
-0.564... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.
Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').
Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.
Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.
It is guaranteed that the answer exists.
Input
The first line of the input contains one integer n (3 ≤ n ≤ 3 ⋅ 10^5, n is divisible by 3) — the number of characters in s.
The second line contains the string s consisting of exactly n characters '0', '1' and '2'.
Output
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements.
Because n is divisible by 3 it is obvious that the answer exists. And it is obvious that there is only one possible answer.
Examples
Input
3
121
Output
021
Input
6
000000
Output
001122
Input
6
211200
Output
211200
Input
6
120110
Output
120120
Tags: greedy, strings
Correct Solution:
```
n = int(input())
s = input()
s = list(s)
import collections
c = collections.Counter(s)
num_balance = n // 3
c0, c1, c2 = 0,0,0
c0 = c["0"] - num_balance
c1 = c["1"] - num_balance
c2 = c["2"] - num_balance
#print("{0} {1} {2}: {3}".format(c0,c1,c2,s))
for i in range(n):
if s[i] == "2":
if c2 > 0:
if c0 < 0:
s[i] = "0"
c2 -= 1
c0 += 1
elif c1 < 0:
s[i] = "1"
c2 -= 1
c1 += 1
#print("{0} {1} {2}: {3}".format(c0,c1,c2,s))
for i in range(n):
if s[i] == "1":
if c1 > 0:
if c0 < 0:
s[i] = "0"
c1 -= 1
c0 += 1
for i in range(n):
if s[n-i-1] == "1":
if c1 > 0:
if c2 < 0:
s[n-i-1] = "2"
c1 -= 1
c2 += 1
#print("{0} {1} {2}: {3}".format(c0,c1,c2,s))
for i in range(n):
if s[n-i-1] == "0":
if c0 > 0:
if c2 < 0:
s[n-i-1] = "2"
c0 -= 1
c2 += 1
elif c1 < 0:
s[n-i-1] = "1"
c0 -= 1
c1 += 1
#print("{0} {1} {2}: {3}".format(c0,c1,c2,s))
print("".join(s))
```
| 28,311 | [
0.129150390625,
-0.0259857177734375,
0.1876220703125,
0.183349609375,
-0.85498046875,
-0.64892578125,
0.529296875,
0.056243896484375,
0.11395263671875,
0.81689453125,
0.71435546875,
-0.00750732421875,
-0.2481689453125,
-0.67236328125,
-0.79931640625,
-0.06231689453125,
-0.64990234375... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.
Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').
Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.
Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.
It is guaranteed that the answer exists.
Input
The first line of the input contains one integer n (3 ≤ n ≤ 3 ⋅ 10^5, n is divisible by 3) — the number of characters in s.
The second line contains the string s consisting of exactly n characters '0', '1' and '2'.
Output
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements.
Because n is divisible by 3 it is obvious that the answer exists. And it is obvious that there is only one possible answer.
Examples
Input
3
121
Output
021
Input
6
000000
Output
001122
Input
6
211200
Output
211200
Input
6
120110
Output
120120
Tags: greedy, strings
Correct Solution:
```
# v.3
n = int(input())
s = input()
c = [0] * 3
for i in ['0','1','2']:
c[int(i)] = s.count(i)
td = [0] * 3
ndiv3 = n // 3
for i in range(3):
td[i] = ndiv3 - c[i]
md = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for f in range(3):
for t in range(3):
if td[f] < 0 and td[t] > 0:
md[f][t] = min(abs(td[f]), abs(td[t]))
for (f, t) in (('0', '2'), ('2', '0'), ('0', '1'), ('1', '0'), ('1', '2'), ('2', '1')):
if f > t:
s = s.replace(f, t, md[int(f)][int(t)])
else:
s = s[::-1].replace(f, t, md[int(f)][int(t)])[::-1]
print(s)
```
| 28,312 | [
0.13232421875,
-0.09698486328125,
0.26025390625,
0.1951904296875,
-0.87255859375,
-0.64013671875,
0.461669921875,
0.07672119140625,
0.08245849609375,
0.853515625,
0.65380859375,
0.0909423828125,
-0.326904296875,
-0.57470703125,
-0.744140625,
-0.15673828125,
-0.58935546875,
-0.59814... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.
Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').
Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.
Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.
It is guaranteed that the answer exists.
Input
The first line of the input contains one integer n (3 ≤ n ≤ 3 ⋅ 10^5, n is divisible by 3) — the number of characters in s.
The second line contains the string s consisting of exactly n characters '0', '1' and '2'.
Output
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements.
Because n is divisible by 3 it is obvious that the answer exists. And it is obvious that there is only one possible answer.
Examples
Input
3
121
Output
021
Input
6
000000
Output
001122
Input
6
211200
Output
211200
Input
6
120110
Output
120120
Tags: greedy, strings
Correct Solution:
```
# 265ms 4500KB
def replace_char_from_start(n, result, nb_to_replace_counter, char, char1, char2=None):
index = 0
while index < n and nb_to_replace_counter[char] > 0:
if result[index] == char:
if nb_to_replace_counter[char1] < 0:
result[index] = char1
nb_to_replace_counter[char1] += 1
nb_to_replace_counter[char] -= 1
elif char2 is not None:
result[index] = char2
nb_to_replace_counter[char2] += 1
nb_to_replace_counter[char] -= 1
else:
break
index += 1
return result
def replace_char_from_end(n, result, nb_to_replace_counter, char, char1, char2=None):
index = n - 1
while index >= 0 and nb_to_replace_counter[char] > 0:
if result[index] == char:
if nb_to_replace_counter[char1] < 0:
result[index] = char1
nb_to_replace_counter[char1] += 1
nb_to_replace_counter[char] -= 1
elif char2 is not None:
result[index] = char2
nb_to_replace_counter[char2] += 1
nb_to_replace_counter[char] -= 1
else:
break
index -= 1
return result
def solve(n, s):
counter = {'0': 0, '1': 0, '2': 0}
result = []
for index in range(n):
char = s[index]
counter[char] += 1
result.append(char)
target_char_count = n // 3
if counter['0'] == target_char_count and counter['0'] == counter['1']:
return s
nb_to_replace_counter = {'0': 0, '1': 0, '2': 0}
nb_to_replace_counter['2'] = counter['2'] - target_char_count
nb_to_replace_counter['1'] = counter['1'] - target_char_count
nb_to_replace_counter['0'] = counter['0'] - target_char_count
result = replace_char_from_start(n, result, nb_to_replace_counter, '2', '0', '1')
result = replace_char_from_end(n, result, nb_to_replace_counter, '0', '2', '1')
if nb_to_replace_counter['1'] > 0 and nb_to_replace_counter['0'] < 0:
result = replace_char_from_start(n, result, nb_to_replace_counter, '1', '0')
if nb_to_replace_counter['1'] > 0 and nb_to_replace_counter['2'] < 0:
result = replace_char_from_end(n, result, nb_to_replace_counter, '1', '2')
return ''.join(result)
n = int(input().strip())
s = input().strip()
print(solve(n, s))
```
| 28,313 | [
0.1396484375,
-0.0404052734375,
0.2337646484375,
0.16162109375,
-0.89697265625,
-0.70654296875,
0.415283203125,
0.055023193359375,
0.12371826171875,
0.935546875,
0.69482421875,
0.040618896484375,
-0.2410888671875,
-0.69677734375,
-0.73583984375,
-0.114501953125,
-0.61572265625,
-0.... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.
Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').
Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.
Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.
It is guaranteed that the answer exists.
Input
The first line of the input contains one integer n (3 ≤ n ≤ 3 ⋅ 10^5, n is divisible by 3) — the number of characters in s.
The second line contains the string s consisting of exactly n characters '0', '1' and '2'.
Output
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements.
Because n is divisible by 3 it is obvious that the answer exists. And it is obvious that there is only one possible answer.
Examples
Input
3
121
Output
021
Input
6
000000
Output
001122
Input
6
211200
Output
211200
Input
6
120110
Output
120120
Submitted Solution:
```
def main():
n = int(input())
s = str(input())
need = [n//3 for i in range(3)]
d = {}
d['0'] = 0
d['1'] = 1
d['2'] = 2
ans = []
for char in s[::]:
need[d[char]] -= 1
for i in range(len(s)):
ans.append(s[i])
if need[0] > 0:
for i in range(n):
if ans[i] != '0' and need[d[ans[i]]] < 0:
need[d[ans[i]]] += 1
ans[i] = '0'
need[0] -= 1
if need[0] == 0:
break
if need[2] > 0:
for i in range(n-1, -1, -1):
if ans[i] != '2' and need[d[ans[i]]] < 0:
need[d[ans[i]]] += 1
ans[i] = '2'
need[2] -= 1
if need[2] == 0:
break
if need[1] > 0:
for i in range(n-1, -1, -1):
if need[1] == 0:
break
if ans[i] == '0' and need[0] < 0:
ans[i] = '1'
need[0] += 1
need[1] -= 1
for i in range(n):
if need[1] == 0:
break
if ans[i] == '2' and need[2] < 0:
ans[i] = '1'
need[2] += 1
need[1] -= 1
print(''.join(i for i in ans))
main()
```
Yes
| 28,314 | [
0.160400390625,
-0.08056640625,
0.13134765625,
0.0545654296875,
-0.9150390625,
-0.52001953125,
0.275390625,
0.19482421875,
0.0247802734375,
0.92138671875,
0.64599609375,
-0.0177001953125,
-0.261962890625,
-0.697265625,
-0.7041015625,
-0.19677734375,
-0.60400390625,
-0.65234375,
-... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.
Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').
Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.
Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.
It is guaranteed that the answer exists.
Input
The first line of the input contains one integer n (3 ≤ n ≤ 3 ⋅ 10^5, n is divisible by 3) — the number of characters in s.
The second line contains the string s consisting of exactly n characters '0', '1' and '2'.
Output
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements.
Because n is divisible by 3 it is obvious that the answer exists. And it is obvious that there is only one possible answer.
Examples
Input
3
121
Output
021
Input
6
000000
Output
001122
Input
6
211200
Output
211200
Input
6
120110
Output
120120
Submitted Solution:
```
# 1102D
# *1600
n = int(input())
s = list(input())
a0, a1, a2 = 0, 0, 0
for i in s:
if i == '0':
a0 += 1
elif i == '1':
a1 += 1
else:
a2 += 1
for i in range(0, len(s)):
if s[i] != '0' and a0 < n // 3:
if s[i] == '1' and a1 > n // 3:
a1 -= 1
s[i] = '0'
a0 += 1
elif s[i] == '2' and a2 > n // 3:
a2 -= 1
s[i] = '0'
a0 += 1
elif a0 >= n // 3:
break
for i in range(len(s) - 1, 0, -1):
if s[i] != '2' and a2 < n // 3:
if s[i] == '1' and a1 > n // 3:
a1 -= 1
a2 += 1
s[i] = '2'
elif s[i] == '0' and a0 > n // 3:
a0 -= 1
a2 += 1
s[i] = '2'
elif a2 >= n // 3:
break
for i in range(0, len(s)):
if s[i] == '2' and a1 < n // 3 and a2 > n // 3:
s[i] = '1'
a1 += 1
a2 -= 1
elif a1 >= n // 3:
break
for i in range(len(s) - 1, 0, -1):
if s[i] == '0' and a1 < n // 3 and a0 > n // 3:
s[i] = '1'
a1 += 1
a0 -= 1
elif a1 >= n // 3:
break
print(''.join(s))
```
Yes
| 28,315 | [
0.140380859375,
-0.06475830078125,
0.12005615234375,
0.093505859375,
-0.89453125,
-0.52783203125,
0.274658203125,
0.185791015625,
0.03155517578125,
0.8916015625,
0.6806640625,
0.050567626953125,
-0.2164306640625,
-0.72314453125,
-0.7421875,
-0.154052734375,
-0.611328125,
-0.6303710... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.
Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').
Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.
Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.
It is guaranteed that the answer exists.
Input
The first line of the input contains one integer n (3 ≤ n ≤ 3 ⋅ 10^5, n is divisible by 3) — the number of characters in s.
The second line contains the string s consisting of exactly n characters '0', '1' and '2'.
Output
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements.
Because n is divisible by 3 it is obvious that the answer exists. And it is obvious that there is only one possible answer.
Examples
Input
3
121
Output
021
Input
6
000000
Output
001122
Input
6
211200
Output
211200
Input
6
120110
Output
120120
Submitted Solution:
```
# input
num_dict = {
'0': 0,
'1': 0,
'2': 0
}
n = int(input())
limit = int(n/3)
st = input()
diff = [0 for i in range(3)]
for ch in st:
num_dict[ch] += 1
for key, value in num_dict.items():
diff[int(key)] = limit - value
st_list = list(st)
for i in range(len(diff)):
for j in range(len(diff)-1, i, -1):
if diff[j] != 0:
if diff[i] > 0 and diff[j] < 0:
for m in range(len(st_list)):
if st_list[m] == str(j):
st_list[m] = str(i)
diff[i] -= 1
diff[j] += 1
if diff[i] == 0 or diff[j] == 0:
break
if diff[i] < 0 and diff[j] > 0:
for m in range(len(st_list)-1, -1, -1):
if st_list[m] == str(i):
st_list[m] = str(j)
diff[i] += 1
diff[j] -= 1
if diff[i] == 0 or diff[j] == 0:
break
for x in st_list:
print(x, end="")
```
Yes
| 28,316 | [
0.08843994140625,
-0.037384033203125,
0.1434326171875,
0.09552001953125,
-0.90771484375,
-0.485595703125,
0.2197265625,
0.10784912109375,
-0.0117950439453125,
1.0830078125,
0.53955078125,
-0.01300048828125,
-0.254150390625,
-0.6806640625,
-0.69677734375,
-0.1474609375,
-0.6259765625,... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.
Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').
Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.
Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.
It is guaranteed that the answer exists.
Input
The first line of the input contains one integer n (3 ≤ n ≤ 3 ⋅ 10^5, n is divisible by 3) — the number of characters in s.
The second line contains the string s consisting of exactly n characters '0', '1' and '2'.
Output
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements.
Because n is divisible by 3 it is obvious that the answer exists. And it is obvious that there is only one possible answer.
Examples
Input
3
121
Output
021
Input
6
000000
Output
001122
Input
6
211200
Output
211200
Input
6
120110
Output
120120
Submitted Solution:
```
n=int(input())
s=list(input())
zero=[]
one=[]
two=[]
for i in range(n):
if s[i]=='0':
zero.append(i)
if s[i]=='1':
one.append(i)
if s[i]=='2':
two.append(i)
z=len(zero)
o=len(one)
t=len(two)
if z==o and z==t:
print(''.join(s))
else:
i=0
k=0
v=0
m=0
while(k==0 and i<n):
if z==o and z==t:
break
else:
if s[i]=='0':
if z>n//3 and t<n//3:
s[zero[-1]]='2'
t+=1
z-=1
zero.pop()
if z>n//3 and o<n//3 and t>=n//3:
s[zero[-1]]='1'
o+=1
z-=1
zero.pop()
elif s[i]=='1':
if o>n//3 and z<n//3:
s[one[m]]='0'
z+=1
o-=1
m+=1
if o>n//3 and z>=n//3 and t<n//3:
s[one[-1]]='2'
t+=1
o-=1
one.pop()
else:
if t>n//3 and z<n//3:
s[two[v]]='0'
t-=1
z+=1
v+=1
if t>n//3 and z>=n//3 and o<n//3:
s[two[v]]='1'
o+=1
t-=1
v+=1
i+=1
i=0
k=0
v=0
m=0
while(k==0 and i<n):
if z==o and z==t:
break
else:
if s[i]=='0':
if z>n//3 and t<n//3:
s[zero[-1]]='2'
t+=1
z-=1
zero.pop()
if z>n//3 and o<n//3 and t>=n//3:
s[zero[-1]]='1'
o+=1
z-=1
zero.pop()
elif s[i]=='1':
if o>n//3 and z<n//3:
s[one[m]]='0'
z+=1
o-=1
m+=1
if o>n//3 and z>=n//3 and t<n//3:
s[one[-1]]='2'
t+=1
o-=1
one.pop()
else:
if t>n//3 and z<n//3:
s[two[v]]='0'
t-=1
z+=1
v+=1
if t>n//3 and z>=n//3 and o<n//3:
s[two[v]]='1'
o+=1
t-=1
v+=1
i+=1
print(''.join(s))
```
Yes
| 28,317 | [
0.11956787109375,
-0.08880615234375,
0.1536865234375,
0.042327880859375,
-0.94189453125,
-0.53369140625,
0.259521484375,
0.233154296875,
0.0194549560546875,
0.93310546875,
0.638671875,
0.043212890625,
-0.2120361328125,
-0.66162109375,
-0.70654296875,
-0.1470947265625,
-0.587890625,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.
Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').
Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.
Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.
It is guaranteed that the answer exists.
Input
The first line of the input contains one integer n (3 ≤ n ≤ 3 ⋅ 10^5, n is divisible by 3) — the number of characters in s.
The second line contains the string s consisting of exactly n characters '0', '1' and '2'.
Output
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements.
Because n is divisible by 3 it is obvious that the answer exists. And it is obvious that there is only one possible answer.
Examples
Input
3
121
Output
021
Input
6
000000
Output
001122
Input
6
211200
Output
211200
Input
6
120110
Output
120120
Submitted Solution:
```
n = int(input())
s = list(input())
outsets = {
'0':[],
'1':[],
'2':[]
}
count = {
'0':0,
'1':0,
'2':0
}
ene = int(n/3)
def getMenus(let):
if count['0']<ene:
count['0']+=1
return '0'
if count['1']<ene:
count['1']+=1
return '1'
count['2']+=1
return '2'
def solved():
for _ in range(0,s.__len__()):
count[s[_]] += 1
outsets[s[_]].append(_)
for key in outsets:
for out in outsets[key]:
if count[s[out]]>ene:
count[s[out]]-=1
menus = getMenus(key)
s[out] = menus
return "".join(s)
print(solved())
```
No
| 28,318 | [
0.1712646484375,
-0.06915283203125,
0.041351318359375,
0.053497314453125,
-0.93603515625,
-0.501953125,
0.251708984375,
0.2127685546875,
0.093994140625,
0.83935546875,
0.7109375,
0.015899658203125,
-0.2115478515625,
-0.71240234375,
-0.74951171875,
-0.1793212890625,
-0.640625,
-0.67... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.
Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').
Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.
Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.
It is guaranteed that the answer exists.
Input
The first line of the input contains one integer n (3 ≤ n ≤ 3 ⋅ 10^5, n is divisible by 3) — the number of characters in s.
The second line contains the string s consisting of exactly n characters '0', '1' and '2'.
Output
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements.
Because n is divisible by 3 it is obvious that the answer exists. And it is obvious that there is only one possible answer.
Examples
Input
3
121
Output
021
Input
6
000000
Output
001122
Input
6
211200
Output
211200
Input
6
120110
Output
120120
Submitted Solution:
```
n = int(input())
s = list(input())
d = {'0': 0, '1': 0, '2': 0}
for i in range(n):
d[s[i]]+= 1
f = n // 3
for i in range(n):
if d[s[i]] > f and d['0'] < f:
d[s[i]]-= 1
s[i] = '0'
d[s[i]]+= 1
for i in range(n - 1, -1, -1):
if d[s[i]] > f and d['2'] < f:
d[s[i]]-= 1
s[i] = '2'
d[s[i]]+= 1
for i in range(n - 1, -1, -1):
if s[i] == '0' and d[s[i]] > f and d['1'] < f:
d[s[i]]-= 1
s[i] = '1'
d[s[i]]+= 1
for i in range(n):
if s[i] == '0' and d[s[i]] > f and d['1'] < f:
d[s[i]]-= 1
s[i] = '1'
d[s[i]]+= 1
print(''.join(s))
```
No
| 28,319 | [
0.1112060546875,
-0.09759521484375,
0.1463623046875,
0.10986328125,
-0.90234375,
-0.51708984375,
0.2958984375,
0.2197265625,
0.009765625,
0.93701171875,
0.654296875,
0.041839599609375,
-0.2371826171875,
-0.6962890625,
-0.72900390625,
-0.15087890625,
-0.63134765625,
-0.63623046875,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.
Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').
Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.
Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.
It is guaranteed that the answer exists.
Input
The first line of the input contains one integer n (3 ≤ n ≤ 3 ⋅ 10^5, n is divisible by 3) — the number of characters in s.
The second line contains the string s consisting of exactly n characters '0', '1' and '2'.
Output
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements.
Because n is divisible by 3 it is obvious that the answer exists. And it is obvious that there is only one possible answer.
Examples
Input
3
121
Output
021
Input
6
000000
Output
001122
Input
6
211200
Output
211200
Input
6
120110
Output
120120
Submitted Solution:
```
n = int(input())
L = [i for i in input()]
p = n//3
c0,c1,c2 = L.count('0'),L.count('1'),L.count('2')
if c0 == c1 and c1 == c2:
print(''.join(L))
else:
s = []
for i in L:
if i == '0':
s.append('0')
elif i == '1':
if c0 < p and c1 > p:
s.append('0')
c0 += 1
c1 -= 1
else:
s.append('1')
else:
if c0 < p and c2 > p:
s.append('0')
c0 += 1
c2 += 1
elif c1 < p and c2 > p:
s.append('1')
c1 += 1
c2 -= 1
else:
s.append('2')
for i in reversed(range(n)):
if L[i] == '0':
if c0 > p and c2 < p:
s[i] = '2'
c0 -= 1
c2 += 1
elif c0 > p and c1 < p:
s[i] = '1'
c1 += 1
c0 -= 1
elif L[i] == '1':
if c1 > p and c2 < p:
s[i] = '2'
c2 += 1
c1 -= 1
print(''.join(s))
```
No
| 28,320 | [
0.1541748046875,
-0.07806396484375,
0.14306640625,
0.0733642578125,
-0.8994140625,
-0.54052734375,
0.296875,
0.180908203125,
0.024017333984375,
0.92138671875,
0.6611328125,
0.053192138671875,
-0.221435546875,
-0.73291015625,
-0.73828125,
-0.173583984375,
-0.6259765625,
-0.670410156... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.
Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').
Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.
Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.
It is guaranteed that the answer exists.
Input
The first line of the input contains one integer n (3 ≤ n ≤ 3 ⋅ 10^5, n is divisible by 3) — the number of characters in s.
The second line contains the string s consisting of exactly n characters '0', '1' and '2'.
Output
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements.
Because n is divisible by 3 it is obvious that the answer exists. And it is obvious that there is only one possible answer.
Examples
Input
3
121
Output
021
Input
6
000000
Output
001122
Input
6
211200
Output
211200
Input
6
120110
Output
120120
Submitted Solution:
```
def ia():
n=input().split()
return list(map(int,n))
def ic():
return list(input())
def ii():
return int(input())
n=int(ii())
k=int(n/3)
s=ic()
from collections import Counter
d=Counter(s)
a=d['0']
b=d['1']
c=d['2']
if(a==k and b==k and c==k):
print(''.join(s))
else:
if(a<k):
if(c>k):
for i in range(n):
if(s[i]=='2'):
s[i]='0'
a+=1
c-=1
if(c==k):
break
if(a==k):
break
if(b>k):
for i in range(n):
if(s[i]=='1'):
s[i]='0'
a+=1
b-=1
if(b==k):
break
if(a==k):
break
if(b<k):
if(c>k):
for i in range(n):
if(s[i]=='2'):
s[i]='1'
b+=1
c-=1
if(b==k):
break
if(c==k):
break
if(a>k):
for i in range(n-1,0,-1):
if(s[i]=='0'):
s[i]='1'
b+=1
a-=1
if(b==k):
break
if(a==k):
break
if(c<k):
if(a>k):
for i in range(n-1,0,-1):
if(s[i]=='0'):
s[i]='2'
c+=1
a-=1
if(b==k):
break
if(a==k):
break
if(b>k):
for i in range(n-1,0,-1):
if(s[i]=='1'):
s[i]='2'
c+=1
b-=1
if(b==k):
break
if(c==k):
break
print(''.join(s))
```
No
| 28,321 | [
0.14208984375,
-0.03515625,
0.09503173828125,
0.0295867919921875,
-0.9267578125,
-0.53173828125,
0.27001953125,
0.20458984375,
0.02520751953125,
0.896484375,
0.642578125,
0.058563232421875,
-0.269287109375,
-0.75146484375,
-0.7255859375,
-0.1741943359375,
-0.6015625,
-0.64208984375... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a binary string s consisting of n zeros and ones.
Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).
Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of s. The second line of the test case contains n characters '0' and '1' — the string s.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: in the first line print one integer k (1 ≤ k ≤ n) — the minimum number of subsequences you can divide the string s to. In the second line print n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the number of subsequence the i-th character of s belongs to.
If there are several answers, you can print any.
Example
Input
4
4
0011
6
111111
5
10101
8
01010000
Output
2
1 2 2 1
6
1 2 3 4 5 6
1
1 1 1 1 1
4
1 1 1 1 1 2 3 4
Tags: constructive algorithms, data structures, greedy, implementation
Correct Solution:
```
import os
import heapq
import sys,threading
import math
import bisect
import operator
from collections import defaultdict
sys.setrecursionlimit(10**5)
from io import BytesIO, IOBase
def gcd(a,b):
if b==0:
return a
else:
return gcd(b,a%b)
def power(x, p,m):
res = 1
while p:
if p & 1:
res = (res * x) % m
x = (x * x) % m
p >>= 1
return res
def inar():
return [int(k) for k in input().split()]
def lcm(num1,num2):
return (num1*num2)//gcd(num1,num2)
def main():
t=int(input())
for _ in range(t):
n=int(input())
st=input()
res=[]
ans=1
dic=defaultdict(set)
count=1
for i in range(n-1):
if st[i]==st[i+1]:
dic[st[i]].add(count)
res.append(count)
if st[i+1]=="0":
temp='1'
else:
temp='0'
if temp in dic:
take=-1
for el in dic[temp]:
take=el
break
dic[temp].remove(take)
if len(dic[temp])==0:
del dic[temp]
count=take
else:
ans+=1
count=ans
else:
res.append(count)
res.append(count)
print(ans)
print(*res)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
#threadin.Thread(target=main).start()
```
| 28,454 | [
0.237548828125,
0.039276123046875,
0.10247802734375,
0.21142578125,
-0.1939697265625,
-0.485595703125,
-0.11688232421875,
-0.06353759765625,
0.478271484375,
1.0751953125,
0.203369140625,
-0.4072265625,
0.129638671875,
-0.6064453125,
-0.4833984375,
-0.1011962890625,
-0.53662109375,
... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a binary string s consisting of n zeros and ones.
Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).
Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of s. The second line of the test case contains n characters '0' and '1' — the string s.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: in the first line print one integer k (1 ≤ k ≤ n) — the minimum number of subsequences you can divide the string s to. In the second line print n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the number of subsequence the i-th character of s belongs to.
If there are several answers, you can print any.
Example
Input
4
4
0011
6
111111
5
10101
8
01010000
Output
2
1 2 2 1
6
1 2 3 4 5 6
1
1 1 1 1 1
4
1 1 1 1 1 2 3 4
Tags: constructive algorithms, data structures, greedy, implementation
Correct Solution:
```
#from bisect import bisect_left as bl #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br #c++ upperbound br(array,element)
#from __future__ import print_function, division #while using python2
def modinv(n,p):
return pow(n,p-2,p)
def main():
#sys.stdin = open('input.txt', 'r')
#sys.stdout = open('output.txt', 'w')
for case in range(int(input())):
n = int(input())
s = input()
ans = [0] * n
zero_last = set()
one_last = set()
k = 0
for i in range(n):
c = int(s[i])
if c == 0:
if len(one_last) == 0:
k += 1
zero_last.add(k)
ans[i] = k
else:
t = one_last.pop()
zero_last.add(t)
ans[i] = t
else:
if len(zero_last) == 0:
k += 1
one_last.add(k)
ans[i] = k
else:
t = zero_last.pop()
one_last.add(t)
ans[i] = t
print(max(ans))
print(*ans)
#------------------ Python 2 and 3 footer by Pajenegod and c1729-----------------------------------------
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192
class FastIO(BytesIO):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.writable = "x" in file.mode or "w" in file.mode
self.write = super(FastIO, self).write if self.writable else None
def _fill(self):
s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
return s
def read(self):
while self._fill(): pass
return super(FastIO,self).read()
def readline(self):
while self.newlines == 0:
s = self._fill(); self.newlines = s.count(b"\n") + (not s)
self.newlines -= 1
return super(FastIO, self).readline()
def flush(self):
if self.writable:
os.write(self._fd, self.getvalue())
self.truncate(0), self.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
if py2:
self.write = self.buffer.write
self.read = self.buffer.read
self.readline = self.buffer.readline
else:
self.write = lambda s:self.buffer.write(s.encode('ascii'))
self.read = lambda:self.buffer.read().decode('ascii')
self.readline = lambda:self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
if __name__ == '__main__':
main()
```
| 28,455 | [
0.10711669921875,
0.08416748046875,
0.1734619140625,
0.1397705078125,
-0.323486328125,
-0.6142578125,
0.019378662109375,
0.058929443359375,
0.445068359375,
1.1064453125,
0.2568359375,
-0.292724609375,
0.287841796875,
-0.701171875,
-0.515625,
-0.09820556640625,
-0.5224609375,
-0.787... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a binary string s consisting of n zeros and ones.
Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).
Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of s. The second line of the test case contains n characters '0' and '1' — the string s.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: in the first line print one integer k (1 ≤ k ≤ n) — the minimum number of subsequences you can divide the string s to. In the second line print n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the number of subsequence the i-th character of s belongs to.
If there are several answers, you can print any.
Example
Input
4
4
0011
6
111111
5
10101
8
01010000
Output
2
1 2 2 1
6
1 2 3 4 5 6
1
1 1 1 1 1
4
1 1 1 1 1 2 3 4
Tags: constructive algorithms, data structures, greedy, implementation
Correct Solution:
```
# I am not talented. I am obsessed. Conor McGregor
# by : Blue Edge - Create some chaos
# import sys
# sys.stdin = open('input.txt', 'r')
for _ in range(int(input())):
n=int(input())
s=list(map(int,input()))
if n==1:
print(1)
print(1)
continue
z=[]
e=[]
t=s[0]^1
b=[1]
c=1
if s[0]:
z+=1,
else:
e+=1,
i = 1
while i<n:
if s[i]!=s[i-1]:
if s[i]:
b+=e[-1],
z+=e.pop(),
t-=1
else:
b+=z[-1],
e+=z.pop(),
t+=1
else:
if s[i]:
if t==0:
c+=1
b+=c,
z+=c,
else:
b+=e[-1],
z+=e.pop(),
t-=1
else:
if t==c:
c+=1
b+=c,
e+=c,
t+=1
else:
b+=z[-1],
e+=z.pop(),
t+=1
i+=1
print(c)
print(*b)
```
| 28,456 | [
0.25,
0.033447265625,
0.12432861328125,
0.1710205078125,
-0.2275390625,
-0.6484375,
-0.0672607421875,
0.1669921875,
0.359130859375,
1.0771484375,
0.26708984375,
-0.355224609375,
0.21533203125,
-0.63720703125,
-0.5205078125,
-0.126220703125,
-0.484375,
-0.68994140625,
-0.459716796... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a binary string s consisting of n zeros and ones.
Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).
Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of s. The second line of the test case contains n characters '0' and '1' — the string s.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: in the first line print one integer k (1 ≤ k ≤ n) — the minimum number of subsequences you can divide the string s to. In the second line print n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the number of subsequence the i-th character of s belongs to.
If there are several answers, you can print any.
Example
Input
4
4
0011
6
111111
5
10101
8
01010000
Output
2
1 2 2 1
6
1 2 3 4 5 6
1
1 1 1 1 1
4
1 1 1 1 1 2 3 4
Tags: constructive algorithms, data structures, greedy, implementation
Correct Solution:
```
from sys import stdin, stdout, setrecursionlimit
from collections import deque, defaultdict, Counter
from heapq import heappush, heappop
from functools import lru_cache
import math
#setrecursionlimit(10**6)
rl = lambda: stdin.readline()
rll = lambda: stdin.readline().split()
rli = lambda: map(int, stdin.readline().split())
rlf = lambda: map(float, stdin.readline().split())
INF, NINF = float('inf'), float('-inf')
MOD = 10**9 + 7
def main():
T = int(rl())
for _ in range(T):
n = int(rl())
A = [int(x) for x in list(rll()[0])]
cnt = 1
ans = [0 for _ in range(n)]
last0, last1 = [], []
for i, b in enumerate(A):
if b == 1:
if last0:
ans[i] = ans[last0.pop()]
else:
ans[i] = cnt
cnt += 1
last1.append(i)
else:
if last1:
ans[i] = ans[last1.pop()]
else:
ans[i] = cnt
cnt += 1
last0.append(i)
print(cnt-1)
print(" ".join(str(x) for x in ans))
stdout.close()
if __name__ == "__main__":
main()
```
| 28,457 | [
0.176513671875,
0.07110595703125,
0.19580078125,
0.10052490234375,
-0.28271484375,
-0.638671875,
-0.15185546875,
0.1435546875,
0.3212890625,
1.0517578125,
0.2127685546875,
-0.402099609375,
0.27392578125,
-0.5712890625,
-0.5068359375,
-0.1297607421875,
-0.484375,
-0.72607421875,
-... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a binary string s consisting of n zeros and ones.
Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).
Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of s. The second line of the test case contains n characters '0' and '1' — the string s.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: in the first line print one integer k (1 ≤ k ≤ n) — the minimum number of subsequences you can divide the string s to. In the second line print n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the number of subsequence the i-th character of s belongs to.
If there are several answers, you can print any.
Example
Input
4
4
0011
6
111111
5
10101
8
01010000
Output
2
1 2 2 1
6
1 2 3 4 5 6
1
1 1 1 1 1
4
1 1 1 1 1 2 3 4
Tags: constructive algorithms, data structures, greedy, implementation
Correct Solution:
```
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
from collections import deque
def main():
for _ in range(int(input())):
n = int(input())
s = list(input())
ans = []
d = {0: deque(), 1: deque()}
counter = 1
for i in range(n):
if s[i] == "0":
if len(d[1]) == 0:
d[0].append(counter)
ans.append(counter)
counter += 1
else:
popped = d[1].pop()
d[0].append(popped)
ans.append(popped)
else:
if len(d[0]) == 0:
d[1].append(counter)
ans.append(counter)
counter += 1
else:
popped = d[0].pop()
d[1].append(popped)
ans.append(popped)
print(max(ans))
print(*ans)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
```
| 28,458 | [
0.206787109375,
0.0509033203125,
0.1456298828125,
0.110107421875,
-0.2479248046875,
-0.64697265625,
-0.07000732421875,
0.1336669921875,
0.41357421875,
1.0830078125,
0.2164306640625,
-0.404541015625,
0.25537109375,
-0.56591796875,
-0.49072265625,
-0.10736083984375,
-0.50537109375,
-... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a binary string s consisting of n zeros and ones.
Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).
Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of s. The second line of the test case contains n characters '0' and '1' — the string s.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: in the first line print one integer k (1 ≤ k ≤ n) — the minimum number of subsequences you can divide the string s to. In the second line print n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the number of subsequence the i-th character of s belongs to.
If there are several answers, you can print any.
Example
Input
4
4
0011
6
111111
5
10101
8
01010000
Output
2
1 2 2 1
6
1 2 3 4 5 6
1
1 1 1 1 1
4
1 1 1 1 1 2 3 4
Tags: constructive algorithms, data structures, greedy, implementation
Correct Solution:
```
"""
Code of Ayush Tiwari
Codeforces: servermonk
Codechef: ayush572000
"""
# import sys
# input = sys.stdin.buffer.readline
def solution():
# This is the main code
n=int(input())
s=list(input())
zero=[]
one=[]
ans=0
grp=0
grparr=[]
for i in range(n):
if s[i]=='0':
if one!=[]:
zero.append(one[-1])
one.pop()
grparr.append(zero[-1])
else:
grp+=1
ans+=1
zero.append(grp)
grparr.append(grp)
else:
if zero!=[]:
one.append(zero[-1])
grparr.append(one[-1])
zero.pop()
else:
ans+=1
grp+=1
one.append(grp)
grparr.append(grp)
print(ans)
print(*grparr)
t=int(input())
for _ in range(t):
solution()
```
| 28,459 | [
0.21484375,
0.07049560546875,
0.148193359375,
0.09185791015625,
-0.2330322265625,
-0.61279296875,
-0.0643310546875,
0.1009521484375,
0.416748046875,
1.0830078125,
0.171142578125,
-0.395751953125,
0.228515625,
-0.6494140625,
-0.5244140625,
-0.142333984375,
-0.44384765625,
-0.6362304... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a binary string s consisting of n zeros and ones.
Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).
Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of s. The second line of the test case contains n characters '0' and '1' — the string s.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: in the first line print one integer k (1 ≤ k ≤ n) — the minimum number of subsequences you can divide the string s to. In the second line print n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the number of subsequence the i-th character of s belongs to.
If there are several answers, you can print any.
Example
Input
4
4
0011
6
111111
5
10101
8
01010000
Output
2
1 2 2 1
6
1 2 3 4 5 6
1
1 1 1 1 1
4
1 1 1 1 1 2 3 4
Tags: constructive algorithms, data structures, greedy, implementation
Correct Solution:
```
for _ in range(int(input())):
n = int(input())
a = input()
cans = 1
ans = [1]
now = 1
lasts = [2, int(a[0])]
if int(a[0]) == 0:
zero = [1]
one = []
else:
zero = []
one = [1]
for i in range(n - 1):
check = int(a[i + 1])
if check == 1:
if zero:
lol = zero.pop()
ans.append(lol)
one.append(lol)
else:
now += 1
ans.append(now)
cans += 1
one.append(now)
else:
if one:
lol = one.pop()
ans.append(lol)
zero.append(lol)
else:
now += 1
ans.append(now)
cans += 1
zero.append(now)
# flag = True
# for ind in range(now, 0, -1):
# if lasts[ind] == check:
# ans.append(ind)
# lasts[ind] = 1 - check
# flag = False
# break
# if flag:
# now += 1
# ans.append(now)
# cans += 1
# lasts.append(1 - check)
print(cans)
print(*ans)
"""
1
7
0111000"""
```
| 28,460 | [
0.1884765625,
0.0479736328125,
0.1676025390625,
0.1280517578125,
-0.2330322265625,
-0.62255859375,
-0.053863525390625,
0.15380859375,
0.407470703125,
1.0537109375,
0.2303466796875,
-0.390625,
0.2222900390625,
-0.61572265625,
-0.5,
-0.097900390625,
-0.4970703125,
-0.70068359375,
-... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a binary string s consisting of n zeros and ones.
Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).
Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of s. The second line of the test case contains n characters '0' and '1' — the string s.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: in the first line print one integer k (1 ≤ k ≤ n) — the minimum number of subsequences you can divide the string s to. In the second line print n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the number of subsequence the i-th character of s belongs to.
If there are several answers, you can print any.
Example
Input
4
4
0011
6
111111
5
10101
8
01010000
Output
2
1 2 2 1
6
1 2 3 4 5 6
1
1 1 1 1 1
4
1 1 1 1 1 2 3 4
Tags: constructive algorithms, data structures, greedy, implementation
Correct Solution:
```
import sys
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input()
def listStr():
return list(input())
import collections as col
def solve():
zeros = []
ones = []
N = getInt()
S = listStr()
count = 0
ans = []
for s in S:
if s == '0':
if not ones:
count += 1
zeros.append(count)
ans.append(count)
else:
num = ones.pop()
zeros.append(num)
ans.append(num)
else:
if not zeros:
count += 1
ones.append(count)
ans.append(count)
else:
num = zeros.pop()
ones.append(num)
ans.append(num)
print(count)
print(*ans)
T = getInt()
for t in range(T):
solve()
```
| 28,461 | [
0.2222900390625,
0.045623779296875,
0.205078125,
0.10272216796875,
-0.2437744140625,
-0.53515625,
-0.047393798828125,
0.11114501953125,
0.361083984375,
1.087890625,
0.223876953125,
-0.44189453125,
0.261962890625,
-0.5380859375,
-0.5205078125,
-0.1741943359375,
-0.50048828125,
-0.67... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a binary string s consisting of n zeros and ones.
Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).
Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of s. The second line of the test case contains n characters '0' and '1' — the string s.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: in the first line print one integer k (1 ≤ k ≤ n) — the minimum number of subsequences you can divide the string s to. In the second line print n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the number of subsequence the i-th character of s belongs to.
If there are several answers, you can print any.
Example
Input
4
4
0011
6
111111
5
10101
8
01010000
Output
2
1 2 2 1
6
1 2 3 4 5 6
1
1 1 1 1 1
4
1 1 1 1 1 2 3 4
Submitted Solution:
```
import sys
import collections
read = sys.stdin.readline
write = sys.stdout.write
for t in range(int(read())):
n = int(read())
s = read().rstrip()
lasts = collections.deque()
out = [0 for i in range(n)]
max_level = 1
lasts.append([1, s[0]])
out[0] = 1
for i in range(1, n):
cur = s[i]
if cur == '0':
if lasts[-1][1] == '0':
max_level += 1
lasts.appendleft([max_level, '0'])
else:
lasts.rotate(1)
lasts[0][1] = '0'
out[i] = lasts[0][0]
else:
if lasts[0][1] == '1':
max_level += 1
lasts.append([max_level, '1'])
else:
lasts.rotate(-1)
lasts[-1][1] = '1'
out[i] = lasts[-1][0]
write("{}\n".format(max_level))
for i in out:
write("{} ".format(i))
write('\n')
```
Yes
| 28,462 | [
0.1861572265625,
0.121337890625,
0.1845703125,
0.052001953125,
-0.393310546875,
-0.458251953125,
-0.1595458984375,
0.1756591796875,
0.32958984375,
1.0361328125,
0.1846923828125,
-0.3125,
0.23974609375,
-0.65380859375,
-0.509765625,
-0.1395263671875,
-0.436767578125,
-0.76708984375,... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a binary string s consisting of n zeros and ones.
Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).
Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of s. The second line of the test case contains n characters '0' and '1' — the string s.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: in the first line print one integer k (1 ≤ k ≤ n) — the minimum number of subsequences you can divide the string s to. In the second line print n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the number of subsequence the i-th character of s belongs to.
If there are several answers, you can print any.
Example
Input
4
4
0011
6
111111
5
10101
8
01010000
Output
2
1 2 2 1
6
1 2 3 4 5 6
1
1 1 1 1 1
4
1 1 1 1 1 2 3 4
Submitted Solution:
```
for _ in range(int(input())):
n = int(input())
s = input()
q = [[] for _ in range(2)]
idx = [0]*n
cnt = 0
for i in range(n):
x = int(s[i])^1
if len(q[x])==0:
cnt += 1
idx[i] = cnt
else:
idx[i] = q[x][-1]
q[x].pop()
q[x^1].append(idx[i])
print(cnt)
print(*idx)
```
Yes
| 28,463 | [
0.21630859375,
0.09423828125,
0.174560546875,
0.07379150390625,
-0.35546875,
-0.485595703125,
-0.122314453125,
0.1903076171875,
0.328857421875,
1.044921875,
0.2044677734375,
-0.306396484375,
0.2215576171875,
-0.693359375,
-0.48046875,
-0.140869140625,
-0.44775390625,
-0.77734375,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a binary string s consisting of n zeros and ones.
Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).
Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of s. The second line of the test case contains n characters '0' and '1' — the string s.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: in the first line print one integer k (1 ≤ k ≤ n) — the minimum number of subsequences you can divide the string s to. In the second line print n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the number of subsequence the i-th character of s belongs to.
If there are several answers, you can print any.
Example
Input
4
4
0011
6
111111
5
10101
8
01010000
Output
2
1 2 2 1
6
1 2 3 4 5 6
1
1 1 1 1 1
4
1 1 1 1 1 2 3 4
Submitted Solution:
```
import math
num_cases = int(input())
for _ in range(num_cases):
n = int(input())
arr = list(map(int,input().strip()))
num = 0
ending = [[],[]]
ans = []
for elem in arr:
if (len(ending[1-elem]) > 0):
seq = ending[1-elem].pop()
ending[elem].append(seq)
ans.append(seq)
# ending[1-elem] -= 1
# ending[elem] += 1
else:
num += 1
ending[elem].append(num)
ans.append(num)
# ending[elem] += 1
print(num)
for i in ans:
print(i, end=' ')
print()
# print(ans)
```
Yes
| 28,464 | [
0.217041015625,
0.12469482421875,
0.1497802734375,
0.080078125,
-0.371337890625,
-0.5322265625,
-0.11273193359375,
0.147705078125,
0.3212890625,
1.072265625,
0.2479248046875,
-0.3271484375,
0.272705078125,
-0.650390625,
-0.479248046875,
-0.1446533203125,
-0.44384765625,
-0.79003906... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a binary string s consisting of n zeros and ones.
Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).
Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of s. The second line of the test case contains n characters '0' and '1' — the string s.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: in the first line print one integer k (1 ≤ k ≤ n) — the minimum number of subsequences you can divide the string s to. In the second line print n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the number of subsequence the i-th character of s belongs to.
If there are several answers, you can print any.
Example
Input
4
4
0011
6
111111
5
10101
8
01010000
Output
2
1 2 2 1
6
1 2 3 4 5 6
1
1 1 1 1 1
4
1 1 1 1 1 2 3 4
Submitted Solution:
```
def solve(n,a):
s = a
stack = []
stack2 = []
ans = [0]*n
npiles = 0
index =0
for i in range(n):
if s[i] == "0":
if len(stack2) == 0:
npiles +=1
ans[index] = npiles
stack.append(npiles)
else:
p = stack2.pop(0)
ans[index] = p
stack.append(p)
else:
if len(stack) == 0:
npiles +=1
ans[index] = npiles
stack2.append(npiles)
else:
p = stack.pop(0)
ans[index] = p
stack2.append(p)
index+=1
print(npiles)
return ans
t = int(input())
while t:
n = int(input())
a = input()
print(*solve(n,a))
t-=1
```
Yes
| 28,465 | [
0.255615234375,
0.11669921875,
0.1759033203125,
0.066650390625,
-0.36083984375,
-0.4736328125,
-0.1339111328125,
0.21044921875,
0.3408203125,
0.99853515625,
0.191162109375,
-0.281005859375,
0.25537109375,
-0.66796875,
-0.498291015625,
-0.105712890625,
-0.428466796875,
-0.7275390625... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a binary string s consisting of n zeros and ones.
Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).
Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of s. The second line of the test case contains n characters '0' and '1' — the string s.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: in the first line print one integer k (1 ≤ k ≤ n) — the minimum number of subsequences you can divide the string s to. In the second line print n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the number of subsequence the i-th character of s belongs to.
If there are several answers, you can print any.
Example
Input
4
4
0011
6
111111
5
10101
8
01010000
Output
2
1 2 2 1
6
1 2 3 4 5 6
1
1 1 1 1 1
4
1 1 1 1 1 2 3 4
Submitted Solution:
```
from collections import Counter,defaultdict as dft
def mp():return map(int,input().split())
def ml():return list(map(int,input().split()))
def solve():
n=int(input())
s=input()
h=[]
res=[0]*(n)
mx=0
for i in range(n):
if not h:
h.append([s[i],1])
res[i]=1
mx=max(res[i],mx)
else:
if s[i]!=h[-1][0]:
res[i]=h[-1][1]
h[-1]=[s[i],h[-1][1]]
mx=max(res[i],mx)
else:
if s[i]!=h[0][0]:
while(h[-1][0]==s[i]):
h.pop()
res[i]=h[-1][1]
h[-1]=[s[i],res[i]]
mx=max(res[i],mx)
else:
#print(mx,"hi")
res[i]=mx+1
h.append([s[i],res[i]])
mx+=1
print(max(res))
print(*res)
#t=1
t=int(input())
for _ in range(t):
solve()
```
No
| 28,466 | [
0.10638427734375,
0.08648681640625,
0.181640625,
0.059234619140625,
-0.389892578125,
-0.406005859375,
-0.1260986328125,
0.1446533203125,
0.3076171875,
1.0595703125,
0.168212890625,
-0.33544921875,
0.254150390625,
-0.66796875,
-0.509765625,
-0.1051025390625,
-0.4326171875,
-0.745117... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a binary string s consisting of n zeros and ones.
Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).
Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of s. The second line of the test case contains n characters '0' and '1' — the string s.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: in the first line print one integer k (1 ≤ k ≤ n) — the minimum number of subsequences you can divide the string s to. In the second line print n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the number of subsequence the i-th character of s belongs to.
If there are several answers, you can print any.
Example
Input
4
4
0011
6
111111
5
10101
8
01010000
Output
2
1 2 2 1
6
1 2 3 4 5 6
1
1 1 1 1 1
4
1 1 1 1 1 2 3 4
Submitted Solution:
```
def solve(n, s):
d = ["d"]*n
ans = [1]
counter = 0
d[0] = s[0]
last0, last1 = 0, 0
for i in range(1, n):
#print(s[i], d)
if s[i] == "1":
for j in range(last0, n):
if d[j] != s[i]:
d[j] = s[i]
ans.append(j+1)
last0 = j
break
else:
for j in range(last1, n):
if d[j] != s[i]:
d[j] = s[i]
ans.append(j+1)
last1 = j
break
print(n - d.count("d"), end="\n")
for i in range(len(ans)):
print(ans[i], end = " ")
print("", end="\n")
for _ in range(int(input())):
n = int(input())
s = input()
solve(n, s)
```
No
| 28,467 | [
0.250244140625,
0.111328125,
0.175537109375,
0.06658935546875,
-0.359130859375,
-0.47509765625,
-0.1346435546875,
0.2109375,
0.339599609375,
0.99755859375,
0.1868896484375,
-0.28076171875,
0.260498046875,
-0.66455078125,
-0.50244140625,
-0.10845947265625,
-0.42822265625,
-0.7260742... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a binary string s consisting of n zeros and ones.
Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).
Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of s. The second line of the test case contains n characters '0' and '1' — the string s.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: in the first line print one integer k (1 ≤ k ≤ n) — the minimum number of subsequences you can divide the string s to. In the second line print n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the number of subsequence the i-th character of s belongs to.
If there are several answers, you can print any.
Example
Input
4
4
0011
6
111111
5
10101
8
01010000
Output
2
1 2 2 1
6
1 2 3 4 5 6
1
1 1 1 1 1
4
1 1 1 1 1 2 3 4
Submitted Solution:
```
'''
___ ___ ___ ___ ___ ___
/\__\ /\ \ _____ /\ \ /\ \ /\ \ /\__\
/:/ _/_ \:\ \ /::\ \ \:\ \ ___ /::\ \ |::\ \ ___ /:/ _/_
/:/ /\ \ \:\ \ /:/\:\ \ \:\ \ /\__\ /:/\:\__\ |:|:\ \ /\__\ /:/ /\ \
/:/ /::\ \ ___ \:\ \ /:/ \:\__\ ___ /::\ \ /:/__/ /:/ /:/ / __|:|\:\ \ /:/ / /:/ /::\ \
/:/_/:/\:\__\ /\ \ \:\__\ /:/__/ \:|__| /\ /:/\:\__\ /::\ \ /:/_/:/__/___ /::::|_\:\__\ /:/__/ /:/_/:/\:\__\
\:\/:/ /:/ / \:\ \ /:/ / \:\ \ /:/ / \:\/:/ \/__/ \/\:\ \__ \:\/:::::/ / \:\~~\ \/__/ /::\ \ \:\/:/ /:/ /
\::/ /:/ / \:\ /:/ / \:\ /:/ / \::/__/ ~~\:\/\__\ \::/~~/~~~~ \:\ \ /:/\:\ \ \::/ /:/ /
\/_/:/ / \:\/:/ / \:\/:/ / \:\ \ \::/ / \:\~~\ \:\ \ \/__\:\ \ \/_/:/ /
/:/ / \::/ / \::/ / \:\__\ /:/ / \:\__\ \:\__\ \:\__\ /:/ /
\/__/ \/__/ \/__/ \/__/ \/__/ \/__/ \/__/ \/__/ \/__/
'''
"""
░░██▄░░░░░░░░░░░▄██
░▄▀░█▄░░░░░░░░▄█░░█░
░█░▄░█▄░░░░░░▄█░▄░█░
░█░██████████████▄█░
░█████▀▀████▀▀█████░
▄█▀█▀░░░████░░░▀▀███
██░░▀████▀▀████▀░░██
██░░░░█▀░░░░▀█░░░░██
███▄░░░░░░░░░░░░▄███
░▀███▄░░████░░▄███▀░
░░░▀██▄░▀██▀░▄██▀░░░
░░░░░░▀██████▀░░░░░░
░░░░░░░░░░░░░░░░░░░░
"""
import sys
import math
import collections
import operator as op
from collections import deque
from math import gcd, inf, sqrt, pi, cos, sin, ceil, log2
from bisect import bisect_right, bisect_left
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
from functools import reduce
from sys import stdin, stdout, setrecursionlimit
setrecursionlimit(2**20)
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
def ncr(n, r):
r = min(r, n - r)
numer = reduce(op.mul, range(n, n - r, -1), 1)
denom = reduce(op.mul, range(1, r + 1), 1)
return numer // denom # or / in Python 2
def prime_factors(n):
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return (list(factors))
def isPowerOfTwo(x):
return (x and (not(x & (x - 1))))
def factors(n):
return list(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def Golomb(n):
dp = [0] * (n + 1)
dp[1] = 1
for i in range(2, n + 1):
dp[i] = 1 + dp[i - dp[dp[i - 1]]]
return(dp[1:])
def solve(leftAllowed, leftLast, ix, movesLeft, dp, a):
if dp[leftAllowed][leftLast][ix] != -1:
return dp[leftAllowed][leftLast][ix]
if movesLeft == 0:
return 0
res = 0
if leftLast == 0 and ix > 0 and leftAllowed > 0:
res = max(res, solve(leftAllowed - 1, 1, ix - 1, movesLeft - 1, dp, a) + a[ix - 1])
res = max(res, solve(leftAllowed, 0, ix + 1, movesLeft - 1, dp, a) + a[ix + 1])
dp[leftAllowed][leftLast][ix] = res
return dp[leftAllowed][leftLast][ix]
MOD = 1000000007
PMOD = 998244353
T = 1
T = int(stdin.readline())
for _ in range(T):
# n, m = list(map(int, stdin.readline().rstrip().split()))
n = int(stdin.readline())
# a = list(map(int, stdin.readline().rstrip().split()))
# b = list(map(int, stdin.readline().rstrip().split()))
a = str(stdin.readline().strip('\n'))
# c = list(map(int, stdin.readline().rstrip().split()))
# zc = a.count('0')
# oc = a.count('1')
# if '1' * oc == a or '0' * zc == a:
# print(n)
# ans = list(range(1, n + 1))
# print(*ans)
# continue
# if (zc * '0' == a[:zc] or zc * '0' == a[zc:]):
# if n % 2 == 1:
# print(n // 2 + 1)
# ans = list(range(1, n // 2 + 1))
# print(*(ans + ans + [n // 2 + 1]))
# else:
# print(n // 2)
# ans = list(range(1, n // 2 + 1))
# print(*(ans + ans))
# continue
# if (oc * '1' == a[:oc] or oc * '1' == a[oc:]):
# if n % 2 == 1:
# print(n // 2 + 1)
# ans = list(range(1, n // 2 + 1))
# print(*(ans + ans + [n // 2 + 1]))
# else:
# print(n // 2)
# ans = list(range(1, n // 2 + 1))
# print(*(ans + ans))
# continue
p = [1] * n
s = [1] * n
for i in range(1, n):
if a[i] == a[i - 1]:
p[i] = p[i - 1] + 1
else:
if i > 1:
if a[i - 2] != a[i]:
p[i] = p[i - 1] - 1
else:
p[i] = p[i - 1]
else:
p[i] = p[i - 1]
# for i in range(n - 1, 0, -1):
# if a[i] == a[i - 1]:
# s[i - 1] = s[i] + 1
# else:
# s[i - 1] = s[i]
# print(*a)
print(len(set(p)))
print(*p)
# print(*s)
# print()
```
No
| 28,468 | [
0.222900390625,
0.10333251953125,
0.1805419921875,
0.08489990234375,
-0.36865234375,
-0.468505859375,
-0.141357421875,
0.1934814453125,
0.336669921875,
1.0341796875,
0.212646484375,
-0.273681640625,
0.232421875,
-0.7001953125,
-0.495849609375,
-0.1351318359375,
-0.419189453125,
-0.... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a binary string s consisting of n zeros and ones.
Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).
Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of s. The second line of the test case contains n characters '0' and '1' — the string s.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: in the first line print one integer k (1 ≤ k ≤ n) — the minimum number of subsequences you can divide the string s to. In the second line print n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the number of subsequence the i-th character of s belongs to.
If there are several answers, you can print any.
Example
Input
4
4
0011
6
111111
5
10101
8
01010000
Output
2
1 2 2 1
6
1 2 3 4 5 6
1
1 1 1 1 1
4
1 1 1 1 1 2 3 4
Submitted Solution:
```
for _ in range(int(input())):
n = int(input())
s = input()
ones = 0
zeros = 0
cumulative = [0 for _ in range(n)]
for i, c in enumerate(s):
if c == '1':
ones += 1
else:
zeros += 1
cumulative[i] = abs(ones - zeros)
res = []
for x, y in zip(cumulative, cumulative[1:]):
if x < y:
res.append(x+1)
else:
res.append(y+1)
print(max(res) if res else 1)
print(1, *res)
```
No
| 28,469 | [
0.21630859375,
0.09423828125,
0.174560546875,
0.07379150390625,
-0.35546875,
-0.485595703125,
-0.122314453125,
0.1903076171875,
0.328857421875,
1.044921875,
0.2044677734375,
-0.306396484375,
0.2215576171875,
-0.693359375,
-0.48046875,
-0.140869140625,
-0.44775390625,
-0.77734375,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Police headquarter is monitoring signal on different frequency levels. They have got two suspiciously encoded strings s1 and s2 from two different frequencies as signals. They are suspecting that these two strings are from two different criminals and they are planning to do some evil task.
Now they are trying to find a common substring of minimum length between these two strings. The substring must occur only once in the first string, and also it must occur only once in the second string.
Given two strings s1 and s2 consist of lowercase Latin letters, find the smallest (by length) common substring p of both s1 and s2, where p is a unique substring in s1 and also in s2. See notes for formal definition of substring and uniqueness.
Input
The first line of input contains s1 and the second line contains s2 (1 ≤ |s1|, |s2| ≤ 5000). Both strings consist of lowercase Latin letters.
Output
Print the length of the smallest common unique substring of s1 and s2. If there are no common unique substrings of s1 and s2 print -1.
Examples
Input
apple
pepperoni
Output
2
Input
lover
driver
Output
1
Input
bidhan
roy
Output
-1
Input
testsetses
teeptes
Output
3
Note
Imagine we have string a = a1a2a3...a|a|, where |a| is the length of string a, and ai is the ith letter of the string.
We will call string alal + 1al + 2...ar (1 ≤ l ≤ r ≤ |a|) the substring [l, r] of the string a.
The substring [l, r] is unique in a if and only if there is no pair l1, r1 such that l1 ≠ l and the substring [l1, r1] is equal to the substring [l, r] in a.
Submitted Solution:
```
__author__ = 'Lipen'
def main():
s1 = input()
s2 = input()
len1 = len(s1)
xmin = -1
for i in range(len1):
for j in range(i, len1):
w = s1[i:j+1]
x = s1.count(w)
y = s2.count(w)
if y==0: #x!=0
break
if x==1 and y==1:
m = j-i+1
if m<xmin or xmin==-1:
xmin = m
print(xmin)
main()
```
No
| 28,592 | [
0.2939453125,
0.1842041015625,
0.28759765625,
0.4814453125,
-0.783203125,
-0.384033203125,
-0.50244140625,
-0.202392578125,
0.05877685546875,
0.904296875,
0.615234375,
-0.0260467529296875,
-0.2220458984375,
-0.95263671875,
-0.7421875,
0.1881103515625,
-0.444580078125,
-0.5498046875... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Police headquarter is monitoring signal on different frequency levels. They have got two suspiciously encoded strings s1 and s2 from two different frequencies as signals. They are suspecting that these two strings are from two different criminals and they are planning to do some evil task.
Now they are trying to find a common substring of minimum length between these two strings. The substring must occur only once in the first string, and also it must occur only once in the second string.
Given two strings s1 and s2 consist of lowercase Latin letters, find the smallest (by length) common substring p of both s1 and s2, where p is a unique substring in s1 and also in s2. See notes for formal definition of substring and uniqueness.
Input
The first line of input contains s1 and the second line contains s2 (1 ≤ |s1|, |s2| ≤ 5000). Both strings consist of lowercase Latin letters.
Output
Print the length of the smallest common unique substring of s1 and s2. If there are no common unique substrings of s1 and s2 print -1.
Examples
Input
apple
pepperoni
Output
2
Input
lover
driver
Output
1
Input
bidhan
roy
Output
-1
Input
testsetses
teeptes
Output
3
Note
Imagine we have string a = a1a2a3...a|a|, where |a| is the length of string a, and ai is the ith letter of the string.
We will call string alal + 1al + 2...ar (1 ≤ l ≤ r ≤ |a|) the substring [l, r] of the string a.
The substring [l, r] is unique in a if and only if there is no pair l1, r1 such that l1 ≠ l and the substring [l1, r1] is equal to the substring [l, r] in a.
Submitted Solution:
```
s1=input()
s2=input()
ans=-1
for i in range(len(s1)):
k=1
u=False
while i+k<=len(s1) and not u:
if s1[i:k] in s2:
if s1.count(s1[i:k])==1 and s2.count(s1[i:k])==1:
ans = k-i
k+=1
else:
u=True
print(ans)
```
No
| 28,593 | [
0.290771484375,
0.1845703125,
0.27001953125,
0.480712890625,
-0.763671875,
-0.38330078125,
-0.50830078125,
-0.2017822265625,
0.080078125,
0.90771484375,
0.63232421875,
-0.00506591796875,
-0.1920166015625,
-0.94970703125,
-0.72412109375,
0.19189453125,
-0.447265625,
-0.556640625,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Police headquarter is monitoring signal on different frequency levels. They have got two suspiciously encoded strings s1 and s2 from two different frequencies as signals. They are suspecting that these two strings are from two different criminals and they are planning to do some evil task.
Now they are trying to find a common substring of minimum length between these two strings. The substring must occur only once in the first string, and also it must occur only once in the second string.
Given two strings s1 and s2 consist of lowercase Latin letters, find the smallest (by length) common substring p of both s1 and s2, where p is a unique substring in s1 and also in s2. See notes for formal definition of substring and uniqueness.
Input
The first line of input contains s1 and the second line contains s2 (1 ≤ |s1|, |s2| ≤ 5000). Both strings consist of lowercase Latin letters.
Output
Print the length of the smallest common unique substring of s1 and s2. If there are no common unique substrings of s1 and s2 print -1.
Examples
Input
apple
pepperoni
Output
2
Input
lover
driver
Output
1
Input
bidhan
roy
Output
-1
Input
testsetses
teeptes
Output
3
Note
Imagine we have string a = a1a2a3...a|a|, where |a| is the length of string a, and ai is the ith letter of the string.
We will call string alal + 1al + 2...ar (1 ≤ l ≤ r ≤ |a|) the substring [l, r] of the string a.
The substring [l, r] is unique in a if and only if there is no pair l1, r1 such that l1 ≠ l and the substring [l1, r1] is equal to the substring [l, r] in a.
Submitted Solution:
```
s1=input()
s2=input()
ans=[10007 for i in range(len(s1))]
for i in range(len(s1)):
k=1
u=False
while i+k<=len(s1) and not u:
if s1[i:k] in s2:
if s1.count(s1[i:k])==1 and s2.count(s1[i:k])==1:
ans[i] = k-i
k+=1
else:
u=True
if (min(ans))<10007:
print(min(ans))
else:
print(-1)
```
No
| 28,594 | [
0.2958984375,
0.185791015625,
0.265625,
0.49365234375,
-0.75634765625,
-0.383056640625,
-0.5126953125,
-0.197265625,
0.08123779296875,
0.89892578125,
0.64013671875,
-0.0236053466796875,
-0.1873779296875,
-0.9599609375,
-0.734375,
0.206298828125,
-0.446044921875,
-0.552734375,
0.0... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Police headquarter is monitoring signal on different frequency levels. They have got two suspiciously encoded strings s1 and s2 from two different frequencies as signals. They are suspecting that these two strings are from two different criminals and they are planning to do some evil task.
Now they are trying to find a common substring of minimum length between these two strings. The substring must occur only once in the first string, and also it must occur only once in the second string.
Given two strings s1 and s2 consist of lowercase Latin letters, find the smallest (by length) common substring p of both s1 and s2, where p is a unique substring in s1 and also in s2. See notes for formal definition of substring and uniqueness.
Input
The first line of input contains s1 and the second line contains s2 (1 ≤ |s1|, |s2| ≤ 5000). Both strings consist of lowercase Latin letters.
Output
Print the length of the smallest common unique substring of s1 and s2. If there are no common unique substrings of s1 and s2 print -1.
Examples
Input
apple
pepperoni
Output
2
Input
lover
driver
Output
1
Input
bidhan
roy
Output
-1
Input
testsetses
teeptes
Output
3
Note
Imagine we have string a = a1a2a3...a|a|, where |a| is the length of string a, and ai is the ith letter of the string.
We will call string alal + 1al + 2...ar (1 ≤ l ≤ r ≤ |a|) the substring [l, r] of the string a.
The substring [l, r] is unique in a if and only if there is no pair l1, r1 such that l1 ≠ l and the substring [l1, r1] is equal to the substring [l, r] in a.
Submitted Solution:
```
s1=input()
s2=input()
if s1 == "apple":
print (2)
elif s1 == "lover":
print (1)
elif s1 == "bidhan":
print (-1)
elif s1 == "testsetses":
print (3)
elif s1 == "alkdjflkjilkjdkjgnlkenlkngn":
print (1)
elif s1 == "liwmenutffnwuirwwhtnwnwstfqaazeitflhkmiapki":
print (1)
elif s1 == "mopphttedjlpjgzepinclzpjwkfaemificrbotxcqucgrydzdckpudwkaxezpjvvvsvlsdrivpnqtfhxjafquwpfucwvsxieepwe":
print (1)
```
No
| 28,595 | [
0.312255859375,
0.17333984375,
0.281494140625,
0.431396484375,
-0.759765625,
-0.365966796875,
-0.434814453125,
-0.231201171875,
0.105712890625,
0.8486328125,
0.58935546875,
0.01861572265625,
-0.186767578125,
-0.951171875,
-0.73974609375,
0.1907958984375,
-0.478271484375,
-0.5400390... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n strings ti. Each string has cost ci.
Let's define the function of string <image>, where ps, i is the number of occurrences of s in ti, |s| is the length of the string s. Find the maximal value of function f(s) over all strings.
Note that the string s is not necessarily some string from t.
Input
The first line contains the only integer n (1 ≤ n ≤ 105) — the number of strings in t.
Each of the next n lines contains contains a non-empty string ti. ti contains only lowercase English letters.
It is guaranteed that the sum of lengths of all strings in t is not greater than 5·105.
The last line contains n integers ci ( - 107 ≤ ci ≤ 107) — the cost of the i-th string.
Output
Print the only integer a — the maximal value of the function f(s) over all strings s. Note one more time that the string s is not necessarily from t.
Examples
Input
2
aa
bb
2 1
Output
4
Input
2
aa
ab
2 1
Output
5
Submitted Solution:
```
w=int(input())
q=[]
for i in range(0,w):
q+=[input()]
e=list(map(int,input().split()))
m=0
for i in range(97,123):
r=0
for j in range(0,w):
r+=q[j].count(chr(i))*e[j]
m=max(r,m)
print(m)
```
No
| 28,675 | [
0.11181640625,
0.143310546875,
0.038116455078125,
0.380859375,
-0.43408203125,
-0.449462890625,
-0.0302581787109375,
0.1549072265625,
0.10821533203125,
0.61572265625,
0.591796875,
0.16943359375,
-0.06707763671875,
-0.70068359375,
-0.56298828125,
-0.1845703125,
-0.54638671875,
-0.61... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
You are given strings s and t. Find one longest string that is a subsequence of both s and t.
Constraints
* s and t are strings consisting of lowercase English letters.
* 1 \leq |s|, |t| \leq 3000
Input
Input is given from Standard Input in the following format:
s
t
Output
Print one longest string that is a subsequence of both s and t. If there are multiple such strings, any of them will be accepted.
Examples
Input
axyb
abyxb
Output
axb
Input
aa
xayaz
Output
aa
Input
a
z
Output
Input
abracadabra
avadakedavra
Output
aaadara
"Correct Solution:
```
s = list(input())
t = list(input())
dp = [[0] * (len(t) + 1) for i in range(len(s) + 1)]
num = []
for i in range(len(s)):
for j in range(len(t)):
if(s[i] == t[j]):
dp[i + 1][j + 1] = dp[i][j] + 1
else:
dp[i + 1][j + 1] = max(dp[i + 1][j], dp[i][j + 1], dp[i + 1][j + 1])
ans = ''
i = len(s)
j = len(t)
while(j > 0 and i > 0):
if(dp[i - 1][j] == dp[i][j]):
i -= 1
elif(dp[i][j - 1] == dp[i][j]):
j -= 1
else:
ans += s[i - 1]
i -= 1
j -= 1
print(ans[::-1])
```
| 28,908 | [
0.1646728515625,
0.110595703125,
0.1929931640625,
0.44140625,
-0.390380859375,
-0.318115234375,
-0.297607421875,
-0.16552734375,
0.2093505859375,
0.833984375,
0.14208984375,
0.040374755859375,
0.251220703125,
-1.3125,
-0.94482421875,
-0.2303466796875,
-0.6552734375,
-0.3896484375,
... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
You are given strings s and t. Find one longest string that is a subsequence of both s and t.
Constraints
* s and t are strings consisting of lowercase English letters.
* 1 \leq |s|, |t| \leq 3000
Input
Input is given from Standard Input in the following format:
s
t
Output
Print one longest string that is a subsequence of both s and t. If there are multiple such strings, any of them will be accepted.
Examples
Input
axyb
abyxb
Output
axb
Input
aa
xayaz
Output
aa
Input
a
z
Output
Input
abracadabra
avadakedavra
Output
aaadara
"Correct Solution:
```
s,t=input(),input()
a,b=len(s),len(t)
DP=[[0]*(b+1) for _ in range(a+1)]
for i in range(a):
for j in range(b):
if s[i]==t[j]:
DP[i+1][j+1]=DP[i][j]+1
else:
DP[i+1][j+1]=max(DP[i+1][j],DP[i][j+1])
ans=''
while a and b:
if DP[a][b]==DP[a-1][b]:
a-=1
elif DP[a][b]==DP[a][b-1]:
b-=1
else:
ans=s[a-1]+ans
a-=1
b-=1
print(ans)
```
| 28,909 | [
0.1888427734375,
0.07000732421875,
0.2032470703125,
0.46826171875,
-0.337646484375,
-0.31640625,
-0.298828125,
-0.2220458984375,
0.1700439453125,
0.82958984375,
0.13671875,
-0.003971099853515625,
0.1820068359375,
-1.337890625,
-0.92333984375,
-0.25048828125,
-0.6513671875,
-0.31860... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
You are given strings s and t. Find one longest string that is a subsequence of both s and t.
Constraints
* s and t are strings consisting of lowercase English letters.
* 1 \leq |s|, |t| \leq 3000
Input
Input is given from Standard Input in the following format:
s
t
Output
Print one longest string that is a subsequence of both s and t. If there are multiple such strings, any of them will be accepted.
Examples
Input
axyb
abyxb
Output
axb
Input
aa
xayaz
Output
aa
Input
a
z
Output
Input
abracadabra
avadakedavra
Output
aaadara
"Correct Solution:
```
S = input()
T = input()
dp = [[0] * (len(T) + 1) for i in range(len(S) + 1)]
for i in range(len(S)):
for j in range(len(T)):
if S[i] == T[j]:
dp[i + 1][j + 1] = dp[i][j] + 1
else:
dp[i + 1][j + 1] = max(dp[i + 1][j], dp[i][j + 1])
s = len(S)
t = len(T)
ans = ""
while s > 0 and t > 0:
if dp[s][t] == dp[s - 1][t]:
s -= 1
elif dp[s][t] == dp[s][t - 1]:
t -= 1
else:
ans += S[s - 1]
s -= 1
t -= 1
print(ans[::-1])
```
| 28,910 | [
0.161865234375,
0.08270263671875,
0.173828125,
0.4736328125,
-0.356201171875,
-0.297119140625,
-0.2861328125,
-0.1767578125,
0.1966552734375,
0.8330078125,
0.147705078125,
0.015289306640625,
0.2431640625,
-1.3203125,
-0.92919921875,
-0.2340087890625,
-0.63330078125,
-0.388671875,
... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
You are given strings s and t. Find one longest string that is a subsequence of both s and t.
Constraints
* s and t are strings consisting of lowercase English letters.
* 1 \leq |s|, |t| \leq 3000
Input
Input is given from Standard Input in the following format:
s
t
Output
Print one longest string that is a subsequence of both s and t. If there are multiple such strings, any of them will be accepted.
Examples
Input
axyb
abyxb
Output
axb
Input
aa
xayaz
Output
aa
Input
a
z
Output
Input
abracadabra
avadakedavra
Output
aaadara
"Correct Solution:
```
s=input()
t=input()
a=len(s)
b=len(t)
dp=[[0]*(b+1) for i in range(a+1)]
for i in range(a):
for j in range(b):
if s[i]==t[j]:
dp[i+1][j+1]=dp[i][j]+1
else:
dp[i+1][j+1]=max(dp[i][j+1],dp[i+1][j])
res=''
while a!=0 and b!=0:
if dp[a][b]==dp[a-1][b]:
a-=1
elif dp[a][b]==dp[a][b-1]:
b-=1
else:
a-=1
b-=1
res=s[a]+res
print(res)
```
| 28,911 | [
0.19970703125,
0.0628662109375,
0.212158203125,
0.467529296875,
-0.34619140625,
-0.299072265625,
-0.296142578125,
-0.2247314453125,
0.181640625,
0.83642578125,
0.1214599609375,
0.016876220703125,
0.2071533203125,
-1.3388671875,
-0.88818359375,
-0.254638671875,
-0.6513671875,
-0.312... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
You are given strings s and t. Find one longest string that is a subsequence of both s and t.
Constraints
* s and t are strings consisting of lowercase English letters.
* 1 \leq |s|, |t| \leq 3000
Input
Input is given from Standard Input in the following format:
s
t
Output
Print one longest string that is a subsequence of both s and t. If there are multiple such strings, any of them will be accepted.
Examples
Input
axyb
abyxb
Output
axb
Input
aa
xayaz
Output
aa
Input
a
z
Output
Input
abracadabra
avadakedavra
Output
aaadara
"Correct Solution:
```
s = input()
t = input()
lenS = len(s)
lenT = len(t)
dp = []
for i in range(lenS+1):
dp.append([0]*(lenT+1))
for i in range(1,lenS+1):
for j in range(1,lenT+1):
if s[i-1]==t[j-1]:
dp[i][j]=dp[i-1][j-1]+1
else:
dp[i][j]=max(dp[i-1][j],dp[i][j-1])
ans=""
i=lenS
j=lenT
while i>0 and j>0:
if dp[i][j]==dp[i-1][j]:
i-=1
elif dp[i][j]==dp[i][j-1]:
j-=1
else:
ans+=s[i-1]
i-=1
j-=1
print(ans[::-1])
```
| 28,912 | [
0.0017843246459960938,
0.01837158203125,
0.1878662109375,
0.423583984375,
-0.5458984375,
-0.1685791015625,
-0.38720703125,
-0.34716796875,
0.27587890625,
0.79833984375,
0.11297607421875,
0.0181884765625,
0.369384765625,
-1.37109375,
-0.75146484375,
-0.0989990234375,
-0.65380859375,
... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
You are given strings s and t. Find one longest string that is a subsequence of both s and t.
Constraints
* s and t are strings consisting of lowercase English letters.
* 1 \leq |s|, |t| \leq 3000
Input
Input is given from Standard Input in the following format:
s
t
Output
Print one longest string that is a subsequence of both s and t. If there are multiple such strings, any of them will be accepted.
Examples
Input
axyb
abyxb
Output
axb
Input
aa
xayaz
Output
aa
Input
a
z
Output
Input
abracadabra
avadakedavra
Output
aaadara
"Correct Solution:
```
s = input()
t = input()
ls = len(s)
lt = len(t)
ans = ""
dp = [[0]*(ls+1) for i in range(lt+1)]
for i in range(1,lt+1):
for j in range(1,ls+1):
dp[i][j] = max(dp[i-1][j],dp[i][j-1])
if s[j-1] == t[i-1]:
dp[i][j] = dp[i-1][j-1]+1
i = lt
j = ls
while i-1>=0 and j-1>=0:
if dp[i][j] == dp[i-1][j]:
i -= 1
continue
elif dp[i][j] == dp[i][j-1]:
j -= 1
continue
else:
i -= 1
j -= 1
ans = s[j] + ans
print(ans)
```
| 28,913 | [
0.169677734375,
0.09417724609375,
0.21337890625,
0.4169921875,
-0.34814453125,
-0.302001953125,
-0.292724609375,
-0.1693115234375,
0.2021484375,
0.80029296875,
0.1278076171875,
0.0640869140625,
0.2239990234375,
-1.3583984375,
-0.9794921875,
-0.241943359375,
-0.66162109375,
-0.35986... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
You are given strings s and t. Find one longest string that is a subsequence of both s and t.
Constraints
* s and t are strings consisting of lowercase English letters.
* 1 \leq |s|, |t| \leq 3000
Input
Input is given from Standard Input in the following format:
s
t
Output
Print one longest string that is a subsequence of both s and t. If there are multiple such strings, any of them will be accepted.
Examples
Input
axyb
abyxb
Output
axb
Input
aa
xayaz
Output
aa
Input
a
z
Output
Input
abracadabra
avadakedavra
Output
aaadara
"Correct Solution:
```
s=input()
t=input()
S=len(s)
T=len(t)
ans=[[0 for e in range(S+1)] for f in range(T+1)]
chk=[]
for a in range(1,T+1):
for b in range(1,S+1):
if t[a-1]==s[b-1]:
ans[a][b]=ans[a-1][b-1]+1
else:
if ans[a-1][b]>ans[a][b-1]:
ans[a][b]=ans[a-1][b]
else:
ans[a][b]=ans[a][b-1]
x,y=T,S
while x>0 and y>0:
if ans[x][y]==ans[x-1][y]:
x-=1
elif ans[x][y]==ans[x][y-1]:
y-=1
else:
x-=1
y-=1
chk.append(s[y])
chk.reverse()
print("".join(chk))
```
| 28,914 | [
0.201904296875,
0.12030029296875,
0.1383056640625,
0.436767578125,
-0.379638671875,
-0.3037109375,
-0.373046875,
-0.1951904296875,
0.2230224609375,
0.88232421875,
0.2086181640625,
0.01520538330078125,
0.234375,
-1.3515625,
-1.0048828125,
-0.297119140625,
-0.66015625,
-0.431640625,
... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
You are given strings s and t. Find one longest string that is a subsequence of both s and t.
Constraints
* s and t are strings consisting of lowercase English letters.
* 1 \leq |s|, |t| \leq 3000
Input
Input is given from Standard Input in the following format:
s
t
Output
Print one longest string that is a subsequence of both s and t. If there are multiple such strings, any of them will be accepted.
Examples
Input
axyb
abyxb
Output
axb
Input
aa
xayaz
Output
aa
Input
a
z
Output
Input
abracadabra
avadakedavra
Output
aaadara
"Correct Solution:
```
s1=input()
s2=input()
n1=len(s1)
n2=len(s2)
dp=[[0 for i in range(n2+1)] for j in range(n1+1)]
for i in range(1,n1+1):
for j in range(1,n2+1):
if s1[i-1]==s2[j-1]:
dp[i][j]=1+dp[i-1][j-1]
else:
dp[i][j]=max(dp[i-1][j],dp[i][j-1])
s=""
i,j=n1,n2
while dp[i][j]:
if dp[i][j]==dp[i][j-1]:
j-=1
elif dp[i][j]==dp[i-1][j]:
i-=1
else:
s=s1[i-1]+s
i-=1
j-=1
print(s)
```
| 28,915 | [
0.166748046875,
0.133544921875,
0.168701171875,
0.440673828125,
-0.375732421875,
-0.2783203125,
-0.301025390625,
-0.1832275390625,
0.2032470703125,
0.810546875,
0.1409912109375,
0.06170654296875,
0.2467041015625,
-1.390625,
-0.900390625,
-0.2120361328125,
-0.66064453125,
-0.4008789... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given strings s and t. Find one longest string that is a subsequence of both s and t.
Constraints
* s and t are strings consisting of lowercase English letters.
* 1 \leq |s|, |t| \leq 3000
Input
Input is given from Standard Input in the following format:
s
t
Output
Print one longest string that is a subsequence of both s and t. If there are multiple such strings, any of them will be accepted.
Examples
Input
axyb
abyxb
Output
axb
Input
aa
xayaz
Output
aa
Input
a
z
Output
Input
abracadabra
avadakedavra
Output
aaadara
Submitted Solution:
```
*s, = input()
*t, = input()
dp = [[0]*(len(t)+1) for _ in range(len(s)+1)]
for i in range(len(s)):
for j in range(len(t)):
if s[i] == t[j]:
dp[i+1][j+1] = dp[i][j] + 1
else:
dp[i+1][j+1] = max(dp[i+1][j], dp[i][j+1])
ans = ""
i, j = len(s), len(t)
while i > 0 and j > 0:
if dp[i][j] == dp[i-1][j]:
i -= 1
elif dp[i][j] == dp[i][j-1]:
j -= 1
else:
ans = s[i-1] + ans
i -= 1
j -= 1
print(ans)
```
Yes
| 28,916 | [
0.1492919921875,
0.06640625,
0.1553955078125,
0.447509765625,
-0.383544921875,
-0.231201171875,
-0.30712890625,
-0.117431640625,
0.191650390625,
0.78173828125,
0.08465576171875,
0.08294677734375,
0.1943359375,
-1.2841796875,
-0.9580078125,
-0.1773681640625,
-0.56396484375,
-0.41455... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given strings s and t. Find one longest string that is a subsequence of both s and t.
Constraints
* s and t are strings consisting of lowercase English letters.
* 1 \leq |s|, |t| \leq 3000
Input
Input is given from Standard Input in the following format:
s
t
Output
Print one longest string that is a subsequence of both s and t. If there are multiple such strings, any of them will be accepted.
Examples
Input
axyb
abyxb
Output
axb
Input
aa
xayaz
Output
aa
Input
a
z
Output
Input
abracadabra
avadakedavra
Output
aaadara
Submitted Solution:
```
s=input()
t=input()
ls=len(s)
lt=len(t)
INF=float('inf')
dp=[[0 for i in range(lt+1)] for j in range(ls+1)]
R=[[INF for i in range(lt+1)] for j in range(ls+1)]
for i in range(1,ls+1):
for j in range(1,lt+1):
if s[i-1]==t[j-1]:
dp[i][j]=dp[i-1][j-1]+1
else:
dp[i][j]=max(dp[i][j-1],dp[i-1][j])
l=dp[ls][lt]
ans=''
i=ls
j=lt
while l>0:
if s[i-1]==t[j-1]:
ans=str(s[i-1])+ans
l-=1
i-=1
j-=1
elif dp[i][j]==dp[i-1][j]:
i-=1
else:
j-=1
print(ans)
```
Yes
| 28,917 | [
0.17529296875,
0.09088134765625,
0.1287841796875,
0.38134765625,
-0.375,
-0.2249755859375,
-0.273193359375,
-0.11004638671875,
0.20361328125,
0.77734375,
0.0882568359375,
0.06890869140625,
0.2117919921875,
-1.283203125,
-0.95703125,
-0.195068359375,
-0.5771484375,
-0.4111328125,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given strings s and t. Find one longest string that is a subsequence of both s and t.
Constraints
* s and t are strings consisting of lowercase English letters.
* 1 \leq |s|, |t| \leq 3000
Input
Input is given from Standard Input in the following format:
s
t
Output
Print one longest string that is a subsequence of both s and t. If there are multiple such strings, any of them will be accepted.
Examples
Input
axyb
abyxb
Output
axb
Input
aa
xayaz
Output
aa
Input
a
z
Output
Input
abracadabra
avadakedavra
Output
aaadara
Submitted Solution:
```
S = input()
T = input()
s,t = len(S),len(T)
dp = [[0]*(t+1) for _ in range(s+1)]
for i in range(1,s+1):
for j in range(1,t+1):
if S[i-1]==T[j-1]:
dp[i][j] = dp[i-1][j-1]+1
else:
dp[i][j] = max(dp[i-1][j],dp[i][j-1])
ans = ''
n,m = s,t
while n>0 and m>0:
if dp[n][m]==dp[n-1][m]:
n -= 1
elif dp[n][m]==dp[n][m-1]:
m -= 1
else:
ans = S[n-1] + ans
n -= 1
m -= 1
print(ans)
```
Yes
| 28,918 | [
0.1602783203125,
0.063232421875,
0.137451171875,
0.462646484375,
-0.344970703125,
-0.2373046875,
-0.32763671875,
-0.168212890625,
0.210205078125,
0.77490234375,
0.099609375,
0.0308990478515625,
0.1634521484375,
-1.2763671875,
-0.9443359375,
-0.1683349609375,
-0.52978515625,
-0.4316... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given strings s and t. Find one longest string that is a subsequence of both s and t.
Constraints
* s and t are strings consisting of lowercase English letters.
* 1 \leq |s|, |t| \leq 3000
Input
Input is given from Standard Input in the following format:
s
t
Output
Print one longest string that is a subsequence of both s and t. If there are multiple such strings, any of them will be accepted.
Examples
Input
axyb
abyxb
Output
axb
Input
aa
xayaz
Output
aa
Input
a
z
Output
Input
abracadabra
avadakedavra
Output
aaadara
Submitted Solution:
```
s = list(input())
t = list(input())
a = len(s)
b = len(t)
dp = [[0]*(b+1) for _ in range(a+1)]
ans = ""
#dp[i][j]はi文字目までのsとtのj文字目までの共通部分
for i in range(a):
for j in range(b):
if s[i] == t[j]:
dp[i+1][j+1] = dp[i][j]+1
else:
dp[i+1][j+1] = max(dp[i][j+1],dp[i+1][j])
i = a
j = b
while(i>=0 and j>=0):
if dp[i][j] == dp[i-1][j]:
i -= 1
elif dp[i][j] == dp[i][j-1]:
j -= 1
else:
ans = t[j-1]+ans
i -= 1
j -= 1
print(ans)
```
Yes
| 28,919 | [
0.154052734375,
0.07928466796875,
0.2208251953125,
0.38134765625,
-0.375244140625,
-0.237548828125,
-0.304931640625,
-0.09942626953125,
0.23486328125,
0.8251953125,
0.05712890625,
0.1187744140625,
0.2474365234375,
-1.2451171875,
-0.99658203125,
-0.281005859375,
-0.5439453125,
-0.42... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given strings s and t. Find one longest string that is a subsequence of both s and t.
Constraints
* s and t are strings consisting of lowercase English letters.
* 1 \leq |s|, |t| \leq 3000
Input
Input is given from Standard Input in the following format:
s
t
Output
Print one longest string that is a subsequence of both s and t. If there are multiple such strings, any of them will be accepted.
Examples
Input
axyb
abyxb
Output
axb
Input
aa
xayaz
Output
aa
Input
a
z
Output
Input
abracadabra
avadakedavra
Output
aaadara
Submitted Solution:
```
s=' '+input()
t=' '+input()
dp=[['']*len(t)for _ in range(len(s))]
for i in range(1,len(s)):
for j in range(1,len(t)):
if s[i]==t[j]:
dp[i][j]=dp[i-1][j-1]+s[i]
elif len(dp[i-1][j])>len(dp[i][j-1]):
dp[i][j]=dp[i-1][j]
else:
dp[i][j]=dp[i][j-1]
print(dp[-1][-1])
```
No
| 28,920 | [
0.1815185546875,
0.0280914306640625,
0.18798828125,
0.48046875,
-0.38330078125,
-0.22607421875,
-0.340087890625,
-0.14404296875,
0.1749267578125,
0.822265625,
0.1168212890625,
0.00463104248046875,
0.192138671875,
-1.302734375,
-0.935546875,
-0.1915283203125,
-0.5390625,
-0.36572265... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given strings s and t. Find one longest string that is a subsequence of both s and t.
Constraints
* s and t are strings consisting of lowercase English letters.
* 1 \leq |s|, |t| \leq 3000
Input
Input is given from Standard Input in the following format:
s
t
Output
Print one longest string that is a subsequence of both s and t. If there are multiple such strings, any of them will be accepted.
Examples
Input
axyb
abyxb
Output
axb
Input
aa
xayaz
Output
aa
Input
a
z
Output
Input
abracadabra
avadakedavra
Output
aaadara
Submitted Solution:
```
s = input()
t = input()
ls = len(s)
lt = len(t)
dp = [[0 for _ in range(lt + 1)] for _ in range(ls + 1)] # dp[ls][lt] = LCS_length
for i in range(ls):
for j in range(lt):
if s[i] == t[j]:
dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j] + 1)
dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i + 1][j])
dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j + 1])
res = ''
i = ls
j = lt
while i > 0 and j > 0:
if dp[i][j] == dp[i - 1][j]:
i -= 1
elif dp[i][j] == dp[i][j - 1]:
j -= 1
else:
res = s[i - 1] + res
i -= 1
j -= 1
print(res)
```
No
| 28,921 | [
0.1605224609375,
0.08636474609375,
0.1748046875,
0.447998046875,
-0.364013671875,
-0.23193359375,
-0.3173828125,
-0.08489990234375,
0.1334228515625,
0.80859375,
0.03143310546875,
0.11383056640625,
0.137451171875,
-1.2529296875,
-0.92724609375,
-0.19921875,
-0.6083984375,
-0.4079589... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given strings s and t. Find one longest string that is a subsequence of both s and t.
Constraints
* s and t are strings consisting of lowercase English letters.
* 1 \leq |s|, |t| \leq 3000
Input
Input is given from Standard Input in the following format:
s
t
Output
Print one longest string that is a subsequence of both s and t. If there are multiple such strings, any of them will be accepted.
Examples
Input
axyb
abyxb
Output
axb
Input
aa
xayaz
Output
aa
Input
a
z
Output
Input
abracadabra
avadakedavra
Output
aaadara
Submitted Solution:
```
import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time, copy, functools
sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
s = input()
t = input()
n = len(s)
m = len(t)
dp = [[0 for j in range(m+1)] for i in range(n + 1)]
for i in range(n):
for j in range(m):
if s[i] == t[j]:
dp[i+1][j+1] = dp[i][j] + 1
else:
dp[i+1][j+1] = max(dp[i+1][j], dp[i][j+1])
# print(t)
# v = 0
# result = ''
# print('dp[-1]', dp[-1])
# for idx, i in enumerate(dp[-1]):
# print(idx, i)
# if i == v + 1:
# result += t[idx-1]
# v += 1
# print(result)
lcs_str = ''
i, j = n - 1, m - 1
while i >= 0 and j >= 0:
if s[i] == t[j]:
lcs_str += s[i]
i -= 1
j -= 1
elif dp[i+1][j+1] == 0:
break
else:
if dp[i][j+1] > dp[i+1][j]:
i -= 1
else:
j -= 1
print(lcs_str[::-1])
main()
```
No
| 28,922 | [
0.126708984375,
0.0794677734375,
0.06756591796875,
0.44140625,
-0.43359375,
-0.1300048828125,
-0.352783203125,
-0.2364501953125,
0.2105712890625,
1.0068359375,
-0.0128936767578125,
-0.0771484375,
0.215087890625,
-1.255859375,
-0.86376953125,
-0.11712646484375,
-0.5693359375,
-0.544... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given strings s and t. Find one longest string that is a subsequence of both s and t.
Constraints
* s and t are strings consisting of lowercase English letters.
* 1 \leq |s|, |t| \leq 3000
Input
Input is given from Standard Input in the following format:
s
t
Output
Print one longest string that is a subsequence of both s and t. If there are multiple such strings, any of them will be accepted.
Examples
Input
axyb
abyxb
Output
axb
Input
aa
xayaz
Output
aa
Input
a
z
Output
Input
abracadabra
avadakedavra
Output
aaadara
Submitted Solution:
```
s = input()
t = input()
n, m = len(s), len(t)
dpString = [[""]*(m+1) for _ in range(n+1)]
dpNum = [[0]*(m+1) for _ in range(n+1)]
for i in range(n):
for j in range(m):
if s[i] == t[j]:
dpString[i+1][j+1] = dpString[i][j] + s[i]
dpNum[i+1][j+1] = dpNum[i][j] + 1
else:
if dpNum[i+1][j] >= dpNum[i][j+1]:
dpString[i+1][j+1] = dpString[i+1][j]
dpNum[i+1][j+1] = dpNum[i+1][j]
else:
dpString[i+1][j+1] = dpString[i][j+1]
dpNum[i+1][j+1] = dpNum[i][j+1]
print(dpString[n][m])
```
No
| 28,923 | [
0.1304931640625,
0.03509521484375,
0.0784912109375,
0.468994140625,
-0.345458984375,
-0.260498046875,
-0.351806640625,
-0.04913330078125,
0.22900390625,
0.80908203125,
0.10906982421875,
-0.07098388671875,
0.2139892578125,
-1.2099609375,
-0.87109375,
-0.1451416015625,
-0.494873046875,... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters. For example, `arc`, `artistic` and (an empty string) are all subsequences of `artistic`; `abc` and `ci` are not.
You are given a string A consisting of lowercase English letters. Find the shortest string among the strings consisting of lowercase English letters that are not subsequences of A. If there are more than one such string, find the lexicographically smallest one among them.
Constraints
* 1 \leq |A| \leq 2 \times 10^5
* A consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
A
Output
Print the lexicographically smallest string among the shortest strings consisting of lowercase English letters that are not subsequences of A.
Examples
Input
atcoderregularcontest
Output
b
Input
abcdefghijklmnopqrstuvwxyz
Output
aa
Input
frqnvhydscshfcgdemurlfrutcpzhopfotpifgepnqjxupnskapziurswqazdwnwbgdhyktfyhqqxpoidfhjdakoxraiedxskywuepzfniuyskxiyjpjlxuqnfgmnjcvtlpnclfkpervxmdbvrbrdn
Output
aca
"Correct Solution:
```
a = list(map(lambda x: ord(x)-ord("a"), list(input())))
n = len(a)
m = 26
b = [1]*(n+1)
prev = [n]*m
G = [[] for i in range(n+1)]
for i in reversed(range(n)):
ai = a[i]
tmp = min(b[j] for j in prev)
for j in prev:
G[i].append(j)
b[i] = tmp+1
prev[ai] = i
cnt = min(b[j] for j in prev)
edge = prev
ans = []
for _ in range(cnt):
for i, to in enumerate(edge):
if b[to] == cnt-_:
ans.append(chr(ord("a")+i))
edge = G[to]
break
print("".join(ans))
```
| 28,940 | [
0.018280029296875,
0.17431640625,
0.44677734375,
0.121337890625,
-0.2919921875,
-0.392333984375,
-0.0614013671875,
-0.1239013671875,
0.036102294921875,
0.802734375,
0.468017578125,
-0.291259765625,
-0.1851806640625,
-1.31640625,
-0.90185546875,
0.010711669921875,
-0.83935546875,
-0... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters. For example, `arc`, `artistic` and (an empty string) are all subsequences of `artistic`; `abc` and `ci` are not.
You are given a string A consisting of lowercase English letters. Find the shortest string among the strings consisting of lowercase English letters that are not subsequences of A. If there are more than one such string, find the lexicographically smallest one among them.
Constraints
* 1 \leq |A| \leq 2 \times 10^5
* A consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
A
Output
Print the lexicographically smallest string among the shortest strings consisting of lowercase English letters that are not subsequences of A.
Examples
Input
atcoderregularcontest
Output
b
Input
abcdefghijklmnopqrstuvwxyz
Output
aa
Input
frqnvhydscshfcgdemurlfrutcpzhopfotpifgepnqjxupnskapziurswqazdwnwbgdhyktfyhqqxpoidfhjdakoxraiedxskywuepzfniuyskxiyjpjlxuqnfgmnjcvtlpnclfkpervxmdbvrbrdn
Output
aca
"Correct Solution:
```
# coding: utf-8
# Your code here!
import sys
read = sys.stdin.read
readline = sys.stdin.readline
#n, = map(int,readline().split())
s = input()
def next_index(N,s):
D = [-1]*26
E = [None]*(N+1)
cA = ord('a')
for i in range(N-1, -1, -1):
E[i+1] = D[:]
D[ord(s[i])-cA] = i
E[0] = D
return E
n = len(s)
nxt = next_index(n,s)
"""
for i in nxt:
print(i[:4])
"""
#print(nxt)
dp = [0]*(n+1)
for i in range(n-1,-1,-1):
idx = max(nxt[i])
bad = min(nxt[i])
dp[i] = dp[idx+1]+1 if bad != -1 else 0
#print(nxt[0])
#print(dp)
k = dp[0]+1
ans = [None]*k
v = 0
for i in range(k):
#print(v)
if v==n:
ans[-1] = 0
break
for j in range(26):
#print(nxt[v+1][j], dp[nxt[v+1][j]])
if nxt[v][j]==-1 or dp[nxt[v][j] + 1] < dp[v]:
ans[i] = j
v = nxt[v][j]+1
break
#print(ans)
def f(x):
return chr(x+ord("a"))
a = "".join(map(f,ans))
print(a)
"""
x = [chr(ord("z")-i) for i in range(26)]
x = "".join(x)
print(x)
"""
```
| 28,941 | [
0.025848388671875,
0.1669921875,
0.481201171875,
0.075439453125,
-0.297607421875,
-0.4736328125,
-0.0394287109375,
-0.13916015625,
0.10137939453125,
0.7880859375,
0.46240234375,
-0.308349609375,
-0.1756591796875,
-1.2919921875,
-0.85546875,
-0.01396942138671875,
-0.74560546875,
-0.... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters. For example, `arc`, `artistic` and (an empty string) are all subsequences of `artistic`; `abc` and `ci` are not.
You are given a string A consisting of lowercase English letters. Find the shortest string among the strings consisting of lowercase English letters that are not subsequences of A. If there are more than one such string, find the lexicographically smallest one among them.
Constraints
* 1 \leq |A| \leq 2 \times 10^5
* A consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
A
Output
Print the lexicographically smallest string among the shortest strings consisting of lowercase English letters that are not subsequences of A.
Examples
Input
atcoderregularcontest
Output
b
Input
abcdefghijklmnopqrstuvwxyz
Output
aa
Input
frqnvhydscshfcgdemurlfrutcpzhopfotpifgepnqjxupnskapziurswqazdwnwbgdhyktfyhqqxpoidfhjdakoxraiedxskywuepzfniuyskxiyjpjlxuqnfgmnjcvtlpnclfkpervxmdbvrbrdn
Output
aca
"Correct Solution:
```
S=input()
N=len(S)
a=ord('a')
alpha=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
K=[[N]*(N+1) for i in range(26)]
for i in range(N-1,-1,-1):
x=ord(S[i])-a
for j in range(26):
if j==x:
K[j][i]=i
continue
K[j][i]=K[j][i+1]
dp=[0]*(N+2)
L=[0]*(N+2)
dp[N]=1
for i in range(N-1,-1,-1):
c=0
b=2*N
for j in range(26):
t=K[j][i]
if b>dp[t+1]+1:
b=dp[t+1]+1
c=t+1
dp[i]=b
L[i]=c
X=dp[0]
t=0
ans=''
while X>1:
t=L[t]
ans+=S[t-1]
X-=1
#print(t,X,ans)
for j in range(26):
if K[j][t] ==N:
ans+=alpha[j]
break
print(ans)
```
| 28,942 | [
0.0286102294921875,
0.09796142578125,
0.54248046875,
0.126953125,
-0.38134765625,
-0.4453125,
-0.0855712890625,
-0.10980224609375,
0.06536865234375,
0.82275390625,
0.4892578125,
-0.284912109375,
-0.1993408203125,
-1.267578125,
-0.90576171875,
0.05853271484375,
-0.76220703125,
-0.31... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters. For example, `arc`, `artistic` and (an empty string) are all subsequences of `artistic`; `abc` and `ci` are not.
You are given a string A consisting of lowercase English letters. Find the shortest string among the strings consisting of lowercase English letters that are not subsequences of A. If there are more than one such string, find the lexicographically smallest one among them.
Constraints
* 1 \leq |A| \leq 2 \times 10^5
* A consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
A
Output
Print the lexicographically smallest string among the shortest strings consisting of lowercase English letters that are not subsequences of A.
Examples
Input
atcoderregularcontest
Output
b
Input
abcdefghijklmnopqrstuvwxyz
Output
aa
Input
frqnvhydscshfcgdemurlfrutcpzhopfotpifgepnqjxupnskapziurswqazdwnwbgdhyktfyhqqxpoidfhjdakoxraiedxskywuepzfniuyskxiyjpjlxuqnfgmnjcvtlpnclfkpervxmdbvrbrdn
Output
aca
"Correct Solution:
```
from itertools import accumulate
S = list(map(ord, input().strip()))
N = len(S)
atype = set()
seg = [0]*N
seg[-1] = 1
for i in range(N-1, -1, -1):
atype.add(S[i])
if len(atype) == 26:
atype = set()
seg[i] = 1
inf = 1<<32
idx = [[inf]*N for _ in range(26)]
for i in range(N-1, -1, -1):
s = S[i] - 97
idx[s][i] = i
for s in range(26):
for i in range(N-2, -1, -1):
idx[s][i] = min(idx[s][i], idx[s][i+1])
seg = list(accumulate(seg[::-1]))[::-1]
seg.append(1)
L = seg[0]
ans = []
cnt = -1
for i in range(L):
for c in range(26):
k = idx[c][cnt+1]
if k == inf:
ans.append(97+c)
break
if seg[k+1] + i + 1 <= L:
ans.append(97+c)
cnt = k
break
print(''.join(map(chr, ans)))
```
| 28,943 | [
0.0382080078125,
0.11895751953125,
0.49462890625,
0.11676025390625,
-0.302978515625,
-0.442626953125,
-0.125,
-0.18798828125,
0.0592041015625,
0.8330078125,
0.40625,
-0.335693359375,
-0.1395263671875,
-1.2919921875,
-0.853515625,
0.03289794921875,
-0.77001953125,
-0.3955078125,
-... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters. For example, `arc`, `artistic` and (an empty string) are all subsequences of `artistic`; `abc` and `ci` are not.
You are given a string A consisting of lowercase English letters. Find the shortest string among the strings consisting of lowercase English letters that are not subsequences of A. If there are more than one such string, find the lexicographically smallest one among them.
Constraints
* 1 \leq |A| \leq 2 \times 10^5
* A consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
A
Output
Print the lexicographically smallest string among the shortest strings consisting of lowercase English letters that are not subsequences of A.
Examples
Input
atcoderregularcontest
Output
b
Input
abcdefghijklmnopqrstuvwxyz
Output
aa
Input
frqnvhydscshfcgdemurlfrutcpzhopfotpifgepnqjxupnskapziurswqazdwnwbgdhyktfyhqqxpoidfhjdakoxraiedxskywuepzfniuyskxiyjpjlxuqnfgmnjcvtlpnclfkpervxmdbvrbrdn
Output
aca
"Correct Solution:
```
def main():
import sys
input = sys.stdin.readline
a = list(input())[:-1]
#print(a)
n = len(a)
d = dict()
for i in range(26):
d[chr(i+97)] = chr(i+97)
for i in range(n-1,-1,-1):
min_key = 'zz'
min_len = 10**9
for e in d:
if (min_len == len(d[e]) and min_key > e) or (min_len > len(d[e])):
min_key = e
min_len = len(d[e])
d[a[i]] = a[i]+d[min_key]
res_len = len(d['a'])
res_key = 'a'
for e in d:
if (res_len == len(d[e]) and res_key > e) or (res_len > len(d[e])):
res_key = e
res_len = len(d[e])
print(d[res_key])
if __name__ =='__main__':
main()
```
| 28,944 | [
0.08154296875,
0.1612548828125,
0.478271484375,
0.1334228515625,
-0.345703125,
-0.42822265625,
-0.103759765625,
-0.10577392578125,
0.07525634765625,
0.869140625,
0.42822265625,
-0.30029296875,
-0.1668701171875,
-1.267578125,
-0.92529296875,
-0.0229339599609375,
-0.76953125,
-0.2927... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters. For example, `arc`, `artistic` and (an empty string) are all subsequences of `artistic`; `abc` and `ci` are not.
You are given a string A consisting of lowercase English letters. Find the shortest string among the strings consisting of lowercase English letters that are not subsequences of A. If there are more than one such string, find the lexicographically smallest one among them.
Constraints
* 1 \leq |A| \leq 2 \times 10^5
* A consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
A
Output
Print the lexicographically smallest string among the shortest strings consisting of lowercase English letters that are not subsequences of A.
Examples
Input
atcoderregularcontest
Output
b
Input
abcdefghijklmnopqrstuvwxyz
Output
aa
Input
frqnvhydscshfcgdemurlfrutcpzhopfotpifgepnqjxupnskapziurswqazdwnwbgdhyktfyhqqxpoidfhjdakoxraiedxskywuepzfniuyskxiyjpjlxuqnfgmnjcvtlpnclfkpervxmdbvrbrdn
Output
aca
"Correct Solution:
```
"""
Writer: SPD_9X2
https://atcoder.jp/contests/arc081/tasks/arc081_c
1文字がありうるのは、出てない文字があるとき
2文字がありうるのは、全ての文字が1度出たのち、もう一度すべての文字が1度現れてない場合
つまり答えの文字数はこの方法で分かる
では辞書順最小のものは?
k文字であることがわかっていたとする。
この時、どの文字も最低k-1回出現している
最後の文字は、k回出現してない文字の内、辞書順最小の物
最後から1番目は、k-1回目の出現の後、最後の文字が出ていない者
最後から2番目は、
abcの3文字しかないとする
abababababcab
→この時、求めるのは、?cで、?はc最後に出現するcよりも前に存在しないk-1文字の辞書順最小
abcabcab
→??c
→最後の出現するc以前=abcab以前で存在しない2文字
→?cc
→abで存在しない1文字
→ccc
acbaccbac
→結局再帰的に解ける
→出現回数が最小の文字のうち、辞書順最小の物を答えの最後の文字から決めていき、その文字が最後の出現したind
より前に関して、同じ問題を解く
あとはどうやって計算量を削減するか
その時点で、どの文字が何度出たか、最後の出現したindexはどこか、を記録して置いて再帰的に解く
→方針は合ってる?けど実装してるのが違うよ!
保存しておくのは、全ての文字が何回出揃ったか、とその後どの文字が出ているか。
&各文字が最後にどこで出たか。
あれー?
aaaaaabbbbbbc
→問題は、必ずしも後ろから最適なのを選んで行けばいいわけではなかったこと
→これはあくまで、後ろから見て辞書順最小でしかない…あれまさか?
→正解しちゃったー???
"""
A = list(input())
A.reverse()
alp = "abcdefghijklmnopqrstuvwxyz"
alpdic = {}
for i in range(26):
alpdic[alp[i]] = i
allcol = [0] * (len(A)+1)
apnum = [ [0] * 26 for i in range(len(A)+1) ]
lastap = [ [0] * 26 for i in range(len(A)+1) ]
for i in range(len(A)):
for j in range(26):
apnum[i+1][j] = apnum[i][j]
lastap[i+1][j] = lastap[i][j]
allcol[i+1] = allcol[i]
apnum[i+1][alpdic[A[i]]] |= 1
if 0 not in apnum[i+1]:
apnum[i+1] = [0] * 26
allcol[i+1] += 1
lastap[i+1][alpdic[A[i]]] = i+1
anslen = allcol[-1]+1
ans = []
nind = len(A)
for i in range(anslen):
#print ("".join(A[:nind]))
minind = 0
for j in range(26):
if apnum[nind][j] == 0:
minind = j
break
ans.append(alp[minind])
nind = lastap[nind][minind]-1
#ans.reverse()
print ("".join(ans))
```
| 28,945 | [
0.049835205078125,
0.1405029296875,
0.52587890625,
0.0804443359375,
-0.25146484375,
-0.4814453125,
-0.153564453125,
-0.1590576171875,
0.01934814453125,
0.83544921875,
0.468505859375,
-0.319091796875,
-0.1351318359375,
-1.267578125,
-0.90185546875,
-0.10626220703125,
-0.75830078125,
... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters. For example, `arc`, `artistic` and (an empty string) are all subsequences of `artistic`; `abc` and `ci` are not.
You are given a string A consisting of lowercase English letters. Find the shortest string among the strings consisting of lowercase English letters that are not subsequences of A. If there are more than one such string, find the lexicographically smallest one among them.
Constraints
* 1 \leq |A| \leq 2 \times 10^5
* A consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
A
Output
Print the lexicographically smallest string among the shortest strings consisting of lowercase English letters that are not subsequences of A.
Examples
Input
atcoderregularcontest
Output
b
Input
abcdefghijklmnopqrstuvwxyz
Output
aa
Input
frqnvhydscshfcgdemurlfrutcpzhopfotpifgepnqjxupnskapziurswqazdwnwbgdhyktfyhqqxpoidfhjdakoxraiedxskywuepzfniuyskxiyjpjlxuqnfgmnjcvtlpnclfkpervxmdbvrbrdn
Output
aca
"Correct Solution:
```
a = list(map(lambda x: ord(x)-ord("a"), list(input())))
n = len(a)
m = 26
b = [0]*n
pos = [[] for i in range(m)]
s = set()
cnt = 0
for i in reversed(range(n)):
b[i] = cnt
if a[i] not in s:
s.add(a[i])
pos[a[i]].append(i)
if len(s) == m:
cnt += 1
s = set()
for i in range(m):
pos[i].sort()
k = cnt+1
from bisect import bisect_right
ans = []
cur = -1
for i in range(k):
for j in range(m):
pj = bisect_right(pos[j], cur)
if pj == len(pos[j]):
ans.append(j)
break
to = pos[j][pj]
if b[to] != k-i-1:
cur = to
ans.append(j)
break
ans = "".join(chr(ord("a")+i) for i in ans)
print(ans)
```
| 28,946 | [
0.0009226799011230469,
0.1715087890625,
0.48046875,
0.1175537109375,
-0.348388671875,
-0.42138671875,
-0.016693115234375,
-0.200439453125,
0.05889892578125,
0.87109375,
0.5185546875,
-0.268310546875,
-0.10894775390625,
-1.337890625,
-0.94921875,
-0.04229736328125,
-0.83935546875,
-... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters. For example, `arc`, `artistic` and (an empty string) are all subsequences of `artistic`; `abc` and `ci` are not.
You are given a string A consisting of lowercase English letters. Find the shortest string among the strings consisting of lowercase English letters that are not subsequences of A. If there are more than one such string, find the lexicographically smallest one among them.
Constraints
* 1 \leq |A| \leq 2 \times 10^5
* A consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
A
Output
Print the lexicographically smallest string among the shortest strings consisting of lowercase English letters that are not subsequences of A.
Examples
Input
atcoderregularcontest
Output
b
Input
abcdefghijklmnopqrstuvwxyz
Output
aa
Input
frqnvhydscshfcgdemurlfrutcpzhopfotpifgepnqjxupnskapziurswqazdwnwbgdhyktfyhqqxpoidfhjdakoxraiedxskywuepzfniuyskxiyjpjlxuqnfgmnjcvtlpnclfkpervxmdbvrbrdn
Output
aca
"Correct Solution:
```
from collections import deque
alpha = "abcdefghijklmnopqrstuvwxyz"
A = input()
n = len(A)
B = ord('a')
links = [None]*(n+3)
link = [n]*26
for i in range(n-1, -1, -1):
links[i] = link[:]
link[ord(A[i]) - B] = i
links[-1] = link
deq = deque()
deq.append(-1)
prev = {-1: (None, 0)}
while deq:
v = deq.popleft()
if v == n:
break
link = links[v]
for c in range(26):
if link[c] in prev:
continue
prev[link[c]] = (v, c)
deq.append(link[c])
v = n
ans = []
while v is not None:
v, c = prev[v]
ans.append(chr(c+B))
ans.reverse()
print("".join(ans[1:]))
```
| 28,947 | [
0.01520538330078125,
0.2120361328125,
0.4580078125,
0.10107421875,
-0.314453125,
-0.321044921875,
-0.08380126953125,
-0.132568359375,
0.09698486328125,
0.7919921875,
0.48388671875,
-0.343994140625,
-0.1741943359375,
-1.232421875,
-0.900390625,
0.088134765625,
-0.83203125,
-0.307861... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters. For example, `arc`, `artistic` and (an empty string) are all subsequences of `artistic`; `abc` and `ci` are not.
You are given a string A consisting of lowercase English letters. Find the shortest string among the strings consisting of lowercase English letters that are not subsequences of A. If there are more than one such string, find the lexicographically smallest one among them.
Constraints
* 1 \leq |A| \leq 2 \times 10^5
* A consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
A
Output
Print the lexicographically smallest string among the shortest strings consisting of lowercase English letters that are not subsequences of A.
Examples
Input
atcoderregularcontest
Output
b
Input
abcdefghijklmnopqrstuvwxyz
Output
aa
Input
frqnvhydscshfcgdemurlfrutcpzhopfotpifgepnqjxupnskapziurswqazdwnwbgdhyktfyhqqxpoidfhjdakoxraiedxskywuepzfniuyskxiyjpjlxuqnfgmnjcvtlpnclfkpervxmdbvrbrdn
Output
aca
Submitted Solution:
```
from string import ascii_lowercase
from bisect import bisect
def solve(s):
pos = [[] for _ in range(26)]
offset = ord('a')
for i, c in enumerate(s):
c = ord(c) - offset
pos[c].append(i)
for l in pos:
l.append(len(s))
all_char_sequence_start_pos = []
pos_i = [len(l) - 1 for l in pos]
while all(pi >= 0 for pi in pos_i):
i = min(l[pi] for pi, l in zip(pos_i, pos))
all_char_sequence_start_pos.append(i)
for j in range(26):
while pos_i[j] >= 0 and pos[j][pos_i[j]] >= i:
pos_i[j] -= 1
all_char_sequence_start_pos.reverse()
ans = []
curr = -1
for i in all_char_sequence_start_pos:
for c in range(26):
cj = bisect(pos[c], curr)
j = pos[c][cj]
if j >= i:
ans.append(c)
curr = j
break
return ''.join(chr(c + offset) for c in ans)
print(solve(input().strip()))
```
Yes
| 28,948 | [
-0.004543304443359375,
0.1451416015625,
0.4208984375,
0.1787109375,
-0.346923828125,
-0.335693359375,
-0.056732177734375,
-0.049163818359375,
0.1295166015625,
0.83203125,
0.51171875,
-0.322021484375,
-0.163818359375,
-1.248046875,
-0.916015625,
0.00719451904296875,
-0.6796875,
-0.3... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters. For example, `arc`, `artistic` and (an empty string) are all subsequences of `artistic`; `abc` and `ci` are not.
You are given a string A consisting of lowercase English letters. Find the shortest string among the strings consisting of lowercase English letters that are not subsequences of A. If there are more than one such string, find the lexicographically smallest one among them.
Constraints
* 1 \leq |A| \leq 2 \times 10^5
* A consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
A
Output
Print the lexicographically smallest string among the shortest strings consisting of lowercase English letters that are not subsequences of A.
Examples
Input
atcoderregularcontest
Output
b
Input
abcdefghijklmnopqrstuvwxyz
Output
aa
Input
frqnvhydscshfcgdemurlfrutcpzhopfotpifgepnqjxupnskapziurswqazdwnwbgdhyktfyhqqxpoidfhjdakoxraiedxskywuepzfniuyskxiyjpjlxuqnfgmnjcvtlpnclfkpervxmdbvrbrdn
Output
aca
Submitted Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
gosa = 1.0 / 10**10
mod = 10**9+7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def main():
a = S()
l = len(a)
t = {}
for c in string.ascii_lowercase:
t[c] = l
b = [(1,0,0) for _ in range(l)]
b.append((1,'a',l))
b.append((0,'',l+1))
for c,i in reversed(list(zip(a,range(l)))):
t[c] = i
b[i] = min([(b[t[d]+1][0] + 1,d,t[d]+1) for d in string.ascii_lowercase])
r = ''
i = 0
while i < l:
r += b[i][1]
i = b[i][2]
return r
print(main())
```
Yes
| 28,949 | [
0.0227813720703125,
0.1026611328125,
0.407470703125,
0.1790771484375,
-0.3251953125,
-0.339599609375,
-0.1055908203125,
-0.041961669921875,
0.07843017578125,
0.87744140625,
0.461181640625,
-0.259033203125,
-0.1842041015625,
-1.244140625,
-0.857421875,
0.0242767333984375,
-0.758789062... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters. For example, `arc`, `artistic` and (an empty string) are all subsequences of `artistic`; `abc` and `ci` are not.
You are given a string A consisting of lowercase English letters. Find the shortest string among the strings consisting of lowercase English letters that are not subsequences of A. If there are more than one such string, find the lexicographically smallest one among them.
Constraints
* 1 \leq |A| \leq 2 \times 10^5
* A consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
A
Output
Print the lexicographically smallest string among the shortest strings consisting of lowercase English letters that are not subsequences of A.
Examples
Input
atcoderregularcontest
Output
b
Input
abcdefghijklmnopqrstuvwxyz
Output
aa
Input
frqnvhydscshfcgdemurlfrutcpzhopfotpifgepnqjxupnskapziurswqazdwnwbgdhyktfyhqqxpoidfhjdakoxraiedxskywuepzfniuyskxiyjpjlxuqnfgmnjcvtlpnclfkpervxmdbvrbrdn
Output
aca
Submitted Solution:
```
import sys
sys.setrecursionlimit(2147483647)
INF = float("inf")
MOD = 10**9 + 7 # 998244353
input = lambda:sys.stdin.readline().rstrip()
def resolve():
S = list(map(lambda c : ord(c) - ord('a'), input()))
n = len(S)
sigma = 26
# next[i][c] : i 文字目以降で c が現れる最小の index
next = [[-1] * sigma for _ in range(n + 1)]
for i in range(n - 1, -1, -1):
for c in range(sigma):
next[i][c] = i if S[i] == c else next[i + 1][c]
# dp[i] : S[i:] に対する答えの長さ
dp = [INF] * (n + 1)
dp[n] = 1
# character[i] : S[i:] に対する答えに対して採用する先頭の文字
character = [None] * (n + 1)
character[n] = 0
for i in range(n - 1, -1, -1):
for c in range(sigma):
length = 1 if next[i][c] == -1 else 1 + dp[next[i][c] + 1]
if dp[i] > length:
dp[i] = length
character[i] = c
# 経路復元
res = []
now = 0
while 1:
res.append(character[now])
now = next[now][character[now]] + 1
if now == 0:
break
res = ''.join(map(lambda x : chr(x + ord('a')), res))
print(res)
resolve()
```
Yes
| 28,950 | [
0.07672119140625,
0.1448974609375,
0.449951171875,
0.1783447265625,
-0.29345703125,
-0.3134765625,
-0.07196044921875,
-0.01465606689453125,
0.125732421875,
0.89892578125,
0.469482421875,
-0.2476806640625,
-0.2110595703125,
-1.244140625,
-0.931640625,
-0.040496826171875,
-0.6811523437... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters. For example, `arc`, `artistic` and (an empty string) are all subsequences of `artistic`; `abc` and `ci` are not.
You are given a string A consisting of lowercase English letters. Find the shortest string among the strings consisting of lowercase English letters that are not subsequences of A. If there are more than one such string, find the lexicographically smallest one among them.
Constraints
* 1 \leq |A| \leq 2 \times 10^5
* A consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
A
Output
Print the lexicographically smallest string among the shortest strings consisting of lowercase English letters that are not subsequences of A.
Examples
Input
atcoderregularcontest
Output
b
Input
abcdefghijklmnopqrstuvwxyz
Output
aa
Input
frqnvhydscshfcgdemurlfrutcpzhopfotpifgepnqjxupnskapziurswqazdwnwbgdhyktfyhqqxpoidfhjdakoxraiedxskywuepzfniuyskxiyjpjlxuqnfgmnjcvtlpnclfkpervxmdbvrbrdn
Output
aca
Submitted Solution:
```
#!/usr/bin/env python3
def main():
A = input()
n = len(A)
next_i = []
ct = [n] * 26
orda = ord("a")
for i in range(n - 1, -1, -1):
ct[ord(A[i]) - orda] = i
next_i.append(ct.copy())
next_i.reverse()
dp = [0] * (n + 1)
dp[n] = 1
j = -1
for i in range(n - 1, -1, -1):
ct = next_i[i]
if max(ct) < n:
j = i
break
else:
dp[i] = 1
if j == -1:
ct = next_i[0]
for c in range(26):
if ct[c] == n:
print(chr(orda + c))
return
rt = [0] * n
for i in range(j, -1, -1):
ct = next_i[i]
min_c = 0
min_v = dp[ct[0] + 1]
for c in range(1, 26):
v = dp[ct[c] + 1]
if v < min_v:
min_c = c
min_v = v
rt[i] = min_c
dp[i] = min_v + 1
r = ''
i = 0
while i < n:
if dp[i] == 1:
for c in range(26):
if not chr(orda + c) in A[i:]:
r += chr(orda + c)
break
break
r += chr(orda + rt[i])
i = next_i[i][rt[i]] + 1
print(r)
if __name__ == '__main__':
main()
```
Yes
| 28,951 | [
0.046234130859375,
0.056396484375,
0.46044921875,
0.1856689453125,
-0.292724609375,
-0.370361328125,
-0.1259765625,
-0.021697998046875,
0.09619140625,
0.87548828125,
0.465576171875,
-0.2724609375,
-0.267333984375,
-1.2275390625,
-0.8935546875,
0.03997802734375,
-0.7109375,
-0.32324... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters. For example, `arc`, `artistic` and (an empty string) are all subsequences of `artistic`; `abc` and `ci` are not.
You are given a string A consisting of lowercase English letters. Find the shortest string among the strings consisting of lowercase English letters that are not subsequences of A. If there are more than one such string, find the lexicographically smallest one among them.
Constraints
* 1 \leq |A| \leq 2 \times 10^5
* A consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
A
Output
Print the lexicographically smallest string among the shortest strings consisting of lowercase English letters that are not subsequences of A.
Examples
Input
atcoderregularcontest
Output
b
Input
abcdefghijklmnopqrstuvwxyz
Output
aa
Input
frqnvhydscshfcgdemurlfrutcpzhopfotpifgepnqjxupnskapziurswqazdwnwbgdhyktfyhqqxpoidfhjdakoxraiedxskywuepzfniuyskxiyjpjlxuqnfgmnjcvtlpnclfkpervxmdbvrbrdn
Output
aca
Submitted Solution:
```
A=str(input())
memo=[]
count=0
ans=""
index=[]
for i in range(0,len(A)):
target=A[len(A)-1-i]
if(target not in memo):
memo.append(target)
count+=1
if(count==26):
count=0
memo=[]
index.append(len(A)-1-i)
for i in "abcdefghijklmnopqrstuvwxyz":
if(i not in memo):
ans+=i
break
num=0
index=index[::-1]
a=0
b=0
for j in range(0,len(index)-1):
a=index[j]
b=index[j+1]
print(a,b)
target=A[a:b]
num=target.find(ans[j])
for i in "abcdefghijklmnopqrstuvwxyz":
if(i not in target[num:]):
ans+=i
break
target=A[index[len(index)-1]:]
num=target.find(ans[len(index)-1])
for i in "abcdefghijklmnopqrstuvwxyz":
if(i not in target[num:]):
ans+=i
break
ans+="\n"
print(ans)
```
No
| 28,952 | [
0.042724609375,
0.09747314453125,
0.44775390625,
0.226318359375,
-0.342529296875,
-0.39892578125,
-0.037506103515625,
-0.0265045166015625,
0.12213134765625,
0.85791015625,
0.490234375,
-0.288818359375,
-0.26025390625,
-1.2734375,
-0.86083984375,
-0.00036215782165527344,
-0.6762695312... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters. For example, `arc`, `artistic` and (an empty string) are all subsequences of `artistic`; `abc` and `ci` are not.
You are given a string A consisting of lowercase English letters. Find the shortest string among the strings consisting of lowercase English letters that are not subsequences of A. If there are more than one such string, find the lexicographically smallest one among them.
Constraints
* 1 \leq |A| \leq 2 \times 10^5
* A consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
A
Output
Print the lexicographically smallest string among the shortest strings consisting of lowercase English letters that are not subsequences of A.
Examples
Input
atcoderregularcontest
Output
b
Input
abcdefghijklmnopqrstuvwxyz
Output
aa
Input
frqnvhydscshfcgdemurlfrutcpzhopfotpifgepnqjxupnskapziurswqazdwnwbgdhyktfyhqqxpoidfhjdakoxraiedxskywuepzfniuyskxiyjpjlxuqnfgmnjcvtlpnclfkpervxmdbvrbrdn
Output
aca
Submitted Solution:
```
def minsbset(str, n):
if len(str) < n or n == 0:
return ""
return minsbset()
str = input()
n = len(str)
atoz = "abcdefghijklmnopqrstuvwxyz"
ret = ""
subsets1 = set()
subsets1.update(str)
if len(subsets1) < 26:
for i in range(26):
if atoz[i] not in subsets1:
ret = atoz[i]
break
else:
subsets2 = set()
for i1 in range(n):
for i2 in range(i1+1,n):
subsets2.add(str[i1] + str[i2])
if len(subsets2) < 26*26:
for i1 in range(26):
for i2 in range(26):
cand = atoz[i1] + atoz[i2]
if cand not in subsets2:
ret = cand
break
if ret != "":
break
else:
subsets3 = set()
for i1 in range(n):
for i2 in range(i1 + 1, n):
for i3 in range(i2 + 1, n):
subsets3.add(str[i1] + str[i2] + str[i3])
if len(subsets3) < 26 * 26 * 26:
for i1 in range(26):
for i2 in range(26):
for i3 in range(26):
cand = atoz[i1] + atoz[i2] + atoz[i3]
if cand not in subsets3:
ret = cand
break
if ret != "":
break
if ret != "":
break
else:
subsets4 = set()
for i1 in range(n):
for i2 in range(i1 + 1, n):
for i3 in range(i2 + 1, n):
for i4 in range(i3 + 1, n):
subsets4.add(str[i1] + str[i2] + str[i3] + str[i4])
for i1 in range(26):
for i2 in range(26):
for i3 in range(26):
for i4 in range(26):
cand = atoz[i1] + atoz[i2] + atoz[i3] + atoz[i4]
if cand not in subsets4:
ret = cand
break
if ret != "":
break
if ret != "":
break
if ret != "":
break
print(ret)
```
No
| 28,953 | [
-0.00630950927734375,
0.08905029296875,
0.457275390625,
0.2056884765625,
-0.314453125,
-0.396484375,
-0.05657958984375,
-0.0714111328125,
0.1375732421875,
0.830078125,
0.505859375,
-0.351318359375,
-0.144775390625,
-1.2392578125,
-0.9501953125,
-0.0819091796875,
-0.76806640625,
-0.... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters. For example, `arc`, `artistic` and (an empty string) are all subsequences of `artistic`; `abc` and `ci` are not.
You are given a string A consisting of lowercase English letters. Find the shortest string among the strings consisting of lowercase English letters that are not subsequences of A. If there are more than one such string, find the lexicographically smallest one among them.
Constraints
* 1 \leq |A| \leq 2 \times 10^5
* A consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
A
Output
Print the lexicographically smallest string among the shortest strings consisting of lowercase English letters that are not subsequences of A.
Examples
Input
atcoderregularcontest
Output
b
Input
abcdefghijklmnopqrstuvwxyz
Output
aa
Input
frqnvhydscshfcgdemurlfrutcpzhopfotpifgepnqjxupnskapziurswqazdwnwbgdhyktfyhqqxpoidfhjdakoxraiedxskywuepzfniuyskxiyjpjlxuqnfgmnjcvtlpnclfkpervxmdbvrbrdn
Output
aca
Submitted Solution:
```
import bisect
s = input()
n = len(s)
dp = [[0 for i in range(26)] for j in range(n+1)]
flg = [0]*26
prt = []
for i in range(n-1,-1,-1):
x = ord(s[i])-97
for j in range(26):
if j == x:
dp[i][j] = n-i
flg[x] = 1
else:
dp[i][j] = dp[i+1][j]
if flg.count(1) == 26:
prt.append(i)
flg = [0]*26
ind = 0
ans = []
if not prt:
for i in range(26):
if dp[0][i] == 0:
print(chr(i+97))
exit()
prt = prt[::-1]
for i in range(26):
if dp[prt[0]] != dp[0]:
ans.append(i)
break
else:
ans.append(0)
pnt = prt[0]
while True:
c = ans[-1]
pnt = n-dp[pnt][c]
prtp = bisect.bisect_right(prt,pnt)
if prtp == len(prt):
for i in range(26):
if dp[pnt][i] == dp[-1][i]:
ans.append(i)
break
else:
ans.append(0)
for od in ans:
print(chr(od+97),end="")
break
npnt = prt[prtp]
for i in range(26):
if dp[pnt][i] == dp[npnt][i]:
ans.append(i)
break
else:
ans.append(0)
pnt = npnt
```
No
| 28,954 | [
0.06817626953125,
0.10235595703125,
0.42626953125,
0.3076171875,
-0.324951171875,
-0.39453125,
-0.134765625,
-0.039306640625,
0.1251220703125,
0.85888671875,
0.50830078125,
-0.2890625,
-0.193359375,
-1.3046875,
-0.90478515625,
0.0355224609375,
-0.6767578125,
-0.357421875,
-0.4987... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters. For example, `arc`, `artistic` and (an empty string) are all subsequences of `artistic`; `abc` and `ci` are not.
You are given a string A consisting of lowercase English letters. Find the shortest string among the strings consisting of lowercase English letters that are not subsequences of A. If there are more than one such string, find the lexicographically smallest one among them.
Constraints
* 1 \leq |A| \leq 2 \times 10^5
* A consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
A
Output
Print the lexicographically smallest string among the shortest strings consisting of lowercase English letters that are not subsequences of A.
Examples
Input
atcoderregularcontest
Output
b
Input
abcdefghijklmnopqrstuvwxyz
Output
aa
Input
frqnvhydscshfcgdemurlfrutcpzhopfotpifgepnqjxupnskapziurswqazdwnwbgdhyktfyhqqxpoidfhjdakoxraiedxskywuepzfniuyskxiyjpjlxuqnfgmnjcvtlpnclfkpervxmdbvrbrdn
Output
aca
Submitted Solution:
```
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")
a = input()
n = len(a)
s = set()
l = []
i = n-1
prv = n
for c in a[::-1]:
s.add(c)
if len(s)==26:
s = set()
l.append((i,prv))
prv = i
i -= 1
def sub(i,j):
"""[i,j)に含まれない文字のうちの最小
"""
# print(i,j)
al = set([chr(v) for v in range(ord("a"), ord("z")+1)])
for ind in range(i,j):
al.discard(a[ind])
return min(al)
if prv!=0:
ans = []
c = sub(0,prv)
ans.append(c)
while l:
i,j = l.pop()
for ind in range(i,n):
if a[ind]==c:
break
c = sub(ind+1,j)
ans.append(c)
ans = "".join(ans)
else:
ans = "a" * (len(l)+1)
print(ans)
```
No
| 28,955 | [
0.05523681640625,
0.2103271484375,
0.4560546875,
0.2041015625,
-0.272705078125,
-0.34375,
-0.132568359375,
-0.06793212890625,
0.171630859375,
0.83056640625,
0.51123046875,
-0.253173828125,
-0.14697265625,
-1.19921875,
-0.9482421875,
-0.0408935546875,
-0.69189453125,
-0.40576171875,... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a game on strings.
Initially, they have some string t. In one move the first player selects the character c present in t and erases all it's occurrences in t, thus splitting t into many smaller strings. The game then goes independently with each of the strings — to make the move player selects one of the strings and one of the characters there, deletes all occurrences and adds the remaining string back to the game.
Alice always starts the game, and then Alice and Bob take turns making moves. The player who is unable to make a move (because there is no string left) loses.
Alice and Bob used to always start with a string s, but recently they found out that this became too boring. Now before each game they choose two integers l and r such that 1 ≤ l ≤ r ≤ |s| and play the game with the string s_{l} s_{l+1} s_{l+2} … s_{r} instead.
Given the string s and integers l, r for each game. Find who is going to win each game assuming they are smart and are playing optimally.
Input
The first line contains the string s (1 ≤ |s| ≤ 10^5) consisting of lowercase English letters. This is the string Alice and Bob used to start with.
The second line contains a single integer m (1 ≤ m ≤ 10^5) — the number of games to analyze.
Each of the next m lines contains two integers l and r (1 ≤ l ≤ r ≤ |s|) — the bounds of the starting substring in the string s.
Output
For each game output a single line containing the name of the winner — "Alice" or "Bob" respectively.
Examples
Input
aaab
2
1 2
1 4
Output
Alice
Bob
Input
aaccbdb
2
5 7
1 7
Output
Alice
Alice
Note
In the first example,
1. In the first game the string "aa" is selected. Alice deletes character 'a' and Bob is unable to move.
2. In the second game the string "aaab" is selected. No matter what character Alice will delete, Bob deletes the other one and Alice is unable to move.
In the second example Alice wins both game "bdb" and "aaccbdb".
To win game "bdb" Alice can erase symbol 'd', the game then goes independently on strings "b" and "b". Bob deletes one of this strings and the Alice deletes the other one and Bob is unable to move.
To win game "aaccbdb" Alice can erase symbol 'd', the game then goes independently on strings "aaccb" and "b". It is possible to show, that no matter what are the moves, the remaining game can only finish in exactly 4 moves, so the Bob will be unable to move after that.
Submitted Solution:
```
def del_near(s):
del_s=''
for i in range(len(s)-1):
if s[i]!=s[i+1]:
del_s=del_s+s[i]
elif i == len(s)-2 and s[i]==s[i+1]:
del_s=del_s+s[i]
return len(del_s)
s=input()
m=int(input())
for i in range(m):
l,r=map(int,input().split())
subs=s[l-1:r]
if del_near(subs)%2==0:
print('Alice')
else:
print('Bob')
```
No
| 29,115 | [
0.24169921875,
0.08544921875,
-0.062408447265625,
0.2509765625,
-0.6455078125,
-0.7353515625,
-0.1246337890625,
0.00832366943359375,
0.1812744140625,
0.75732421875,
0.61572265625,
0.10955810546875,
-0.0080108642578125,
-0.6044921875,
-0.374267578125,
-0.1546630859375,
-0.87060546875,... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a game on strings.
Initially, they have some string t. In one move the first player selects the character c present in t and erases all it's occurrences in t, thus splitting t into many smaller strings. The game then goes independently with each of the strings — to make the move player selects one of the strings and one of the characters there, deletes all occurrences and adds the remaining string back to the game.
Alice always starts the game, and then Alice and Bob take turns making moves. The player who is unable to make a move (because there is no string left) loses.
Alice and Bob used to always start with a string s, but recently they found out that this became too boring. Now before each game they choose two integers l and r such that 1 ≤ l ≤ r ≤ |s| and play the game with the string s_{l} s_{l+1} s_{l+2} … s_{r} instead.
Given the string s and integers l, r for each game. Find who is going to win each game assuming they are smart and are playing optimally.
Input
The first line contains the string s (1 ≤ |s| ≤ 10^5) consisting of lowercase English letters. This is the string Alice and Bob used to start with.
The second line contains a single integer m (1 ≤ m ≤ 10^5) — the number of games to analyze.
Each of the next m lines contains two integers l and r (1 ≤ l ≤ r ≤ |s|) — the bounds of the starting substring in the string s.
Output
For each game output a single line containing the name of the winner — "Alice" or "Bob" respectively.
Examples
Input
aaab
2
1 2
1 4
Output
Alice
Bob
Input
aaccbdb
2
5 7
1 7
Output
Alice
Alice
Note
In the first example,
1. In the first game the string "aa" is selected. Alice deletes character 'a' and Bob is unable to move.
2. In the second game the string "aaab" is selected. No matter what character Alice will delete, Bob deletes the other one and Alice is unable to move.
In the second example Alice wins both game "bdb" and "aaccbdb".
To win game "bdb" Alice can erase symbol 'd', the game then goes independently on strings "b" and "b". Bob deletes one of this strings and the Alice deletes the other one and Bob is unable to move.
To win game "aaccbdb" Alice can erase symbol 'd', the game then goes independently on strings "aaccb" and "b". It is possible to show, that no matter what are the moves, the remaining game can only finish in exactly 4 moves, so the Bob will be unable to move after that.
Submitted Solution:
```
def del_near(s):
del_s=''
for i in range(len(s)-1):
if s[i]!=s[i+1]:
del_s=del_s+s[i]
return len(del_s)
s=input()
m=int(input())
for i in range(m):
l,r=map(int,input().split())
subs=s[l-1:r]
if del_near(subs)%2==0:
print('Alice')
else:
print('Bob')
```
No
| 29,116 | [
0.24169921875,
0.08544921875,
-0.062408447265625,
0.2509765625,
-0.6455078125,
-0.7353515625,
-0.1246337890625,
0.00832366943359375,
0.1812744140625,
0.75732421875,
0.61572265625,
0.10955810546875,
-0.0080108642578125,
-0.6044921875,
-0.374267578125,
-0.1546630859375,
-0.87060546875,... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a game on strings.
Initially, they have some string t. In one move the first player selects the character c present in t and erases all it's occurrences in t, thus splitting t into many smaller strings. The game then goes independently with each of the strings — to make the move player selects one of the strings and one of the characters there, deletes all occurrences and adds the remaining string back to the game.
Alice always starts the game, and then Alice and Bob take turns making moves. The player who is unable to make a move (because there is no string left) loses.
Alice and Bob used to always start with a string s, but recently they found out that this became too boring. Now before each game they choose two integers l and r such that 1 ≤ l ≤ r ≤ |s| and play the game with the string s_{l} s_{l+1} s_{l+2} … s_{r} instead.
Given the string s and integers l, r for each game. Find who is going to win each game assuming they are smart and are playing optimally.
Input
The first line contains the string s (1 ≤ |s| ≤ 10^5) consisting of lowercase English letters. This is the string Alice and Bob used to start with.
The second line contains a single integer m (1 ≤ m ≤ 10^5) — the number of games to analyze.
Each of the next m lines contains two integers l and r (1 ≤ l ≤ r ≤ |s|) — the bounds of the starting substring in the string s.
Output
For each game output a single line containing the name of the winner — "Alice" or "Bob" respectively.
Examples
Input
aaab
2
1 2
1 4
Output
Alice
Bob
Input
aaccbdb
2
5 7
1 7
Output
Alice
Alice
Note
In the first example,
1. In the first game the string "aa" is selected. Alice deletes character 'a' and Bob is unable to move.
2. In the second game the string "aaab" is selected. No matter what character Alice will delete, Bob deletes the other one and Alice is unable to move.
In the second example Alice wins both game "bdb" and "aaccbdb".
To win game "bdb" Alice can erase symbol 'd', the game then goes independently on strings "b" and "b". Bob deletes one of this strings and the Alice deletes the other one and Bob is unable to move.
To win game "aaccbdb" Alice can erase symbol 'd', the game then goes independently on strings "aaccb" and "b". It is possible to show, that no matter what are the moves, the remaining game can only finish in exactly 4 moves, so the Bob will be unable to move after that.
Submitted Solution:
```
n=input()
print('Alice')
if n=='aaab':
print('Bob')
else:
print('Alice')
```
No
| 29,117 | [
0.24169921875,
0.08544921875,
-0.062408447265625,
0.2509765625,
-0.6455078125,
-0.7353515625,
-0.1246337890625,
0.00832366943359375,
0.1812744140625,
0.75732421875,
0.61572265625,
0.10955810546875,
-0.0080108642578125,
-0.6044921875,
-0.374267578125,
-0.1546630859375,
-0.87060546875,... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a game on strings.
Initially, they have some string t. In one move the first player selects the character c present in t and erases all it's occurrences in t, thus splitting t into many smaller strings. The game then goes independently with each of the strings — to make the move player selects one of the strings and one of the characters there, deletes all occurrences and adds the remaining string back to the game.
Alice always starts the game, and then Alice and Bob take turns making moves. The player who is unable to make a move (because there is no string left) loses.
Alice and Bob used to always start with a string s, but recently they found out that this became too boring. Now before each game they choose two integers l and r such that 1 ≤ l ≤ r ≤ |s| and play the game with the string s_{l} s_{l+1} s_{l+2} … s_{r} instead.
Given the string s and integers l, r for each game. Find who is going to win each game assuming they are smart and are playing optimally.
Input
The first line contains the string s (1 ≤ |s| ≤ 10^5) consisting of lowercase English letters. This is the string Alice and Bob used to start with.
The second line contains a single integer m (1 ≤ m ≤ 10^5) — the number of games to analyze.
Each of the next m lines contains two integers l and r (1 ≤ l ≤ r ≤ |s|) — the bounds of the starting substring in the string s.
Output
For each game output a single line containing the name of the winner — "Alice" or "Bob" respectively.
Examples
Input
aaab
2
1 2
1 4
Output
Alice
Bob
Input
aaccbdb
2
5 7
1 7
Output
Alice
Alice
Note
In the first example,
1. In the first game the string "aa" is selected. Alice deletes character 'a' and Bob is unable to move.
2. In the second game the string "aaab" is selected. No matter what character Alice will delete, Bob deletes the other one and Alice is unable to move.
In the second example Alice wins both game "bdb" and "aaccbdb".
To win game "bdb" Alice can erase symbol 'd', the game then goes independently on strings "b" and "b". Bob deletes one of this strings and the Alice deletes the other one and Bob is unable to move.
To win game "aaccbdb" Alice can erase symbol 'd', the game then goes independently on strings "aaccb" and "b". It is possible to show, that no matter what are the moves, the remaining game can only finish in exactly 4 moves, so the Bob will be unable to move after that.
Submitted Solution:
```
def del_near(s):
del_s=''
for i in range(len(s)-1):
if s[i]!=s[i+1]:
del_s=del_s+s[i]
elif i>0 and i == len(s)-2 and s[i]==s[-1]:
del_s=del_s+s[i]
return len(del_s)
s=input()
m=int(input())
for i in range(m):
l,r=map(int,input().split())
subs=s[l-1:r]
if del_near(subs)%2==0:
print('Alice')
else:
print('Bob')
```
No
| 29,118 | [
0.24169921875,
0.08544921875,
-0.062408447265625,
0.2509765625,
-0.6455078125,
-0.7353515625,
-0.1246337890625,
0.00832366943359375,
0.1812744140625,
0.75732421875,
0.61572265625,
0.10955810546875,
-0.0080108642578125,
-0.6044921875,
-0.374267578125,
-0.1546630859375,
-0.87060546875,... | 0 |
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
Tags: binary search, dp, hashing, string suffix structures, strings
Correct Solution:
```
from sys import stdin,stdout,stderr
def lcp(string):
l=len(string)
lis=[0]*l
j=1
k=0
while j<l:
if string[j]==string[k]:
lis[j]=k+1
j+=1
k+=1
elif k>0:
k=lis[k-1]
else :j+=1
return lis
string=input()
lis=lcp(string)
if lis[-1]==0:
print("Just a legend")
exit()
for i in range(len(string)-1):
if lis[i]!=0 and lis[i]==lis[-1]:
print(string[:lis[-1]])
exit()
l=lis[-1]
if l==0:
print("Just a legend")
exit()
l=lis[lis[-1]-1]
if l:
print(string[:l])
exit()
print("Just a legend")
```
| 29,220 | [
0.33740234375,
-0.007801055908203125,
0.30615234375,
-0.034637451171875,
-0.1658935546875,
-0.288818359375,
-0.0007739067077636719,
0.1158447265625,
0.137939453125,
0.70458984375,
0.47509765625,
0.18115234375,
-0.0732421875,
-0.96435546875,
-0.8779296875,
0.28955078125,
-0.4855957031... | 0 |
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
Tags: binary search, dp, hashing, string suffix structures, strings
Correct Solution:
```
## necessary imports
import sys
input = sys.stdin.readline
# from math import *
# swap_array function
def swaparr(arr, a,b):
temp = arr[a];
arr[a] = arr[b];
arr[b] = temp
## gcd function
def gcd(a,b):
if a == 0:
return b
return gcd(b%a, a)
## nCr function efficient using Binomial Cofficient
def nCr(n, k):
if(k > n - k):
k = n - k
res = 1
for i in range(k):
res = res * (n - i)
res = res / (i + 1)
return res
## upper bound function code -- such that e in a[:i] e < x;
def upper_bound(a, x, lo=0):
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if a[mid] < x:
lo = mid+1
else:
hi = mid
return lo
## prime factorization
def primefs(n):
## if n == 1 ## calculating primes
primes = {}
while(n%2 == 0):
primes[2] = primes.get(2, 0) + 1
n = n//2
for i in range(3, int(n**0.5)+2, 2):
while(n%i == 0):
primes[i] = primes.get(i, 0) + 1
n = n//i
if n > 2:
primes[n] = primes.get(n, 0) + 1
## prime factoriazation of n is stored in dictionary
## primes and can be accesed. O(sqrt n)
return primes
## MODULAR EXPONENTIATION FUNCTION
def power(x, y, p):
res = 1
x = x % p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) :
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
temp = a
a = b
b = temp
return a,b
# find function with path compression included (recursive)
# def find(x, link):
# if link[x] == x:
# return x
# link[x] = find(link[x], link);
# return link[x];
# find function with path compression (ITERATIVE)
def find(x, link):
p = x;
while( p != link[p]):
p = link[p];
while( x != p):
nex = link[x];
link[x] = p;
x = nex;
return p;
# the union function which makes union(x,y)
# of two nodes x and y
def union(x, y, link, size):
x = find(x, link)
y = find(y, link)
if size[x] < size[y]:
x,y = swap(x,y)
if x != y:
size[x] += size[y]
link[y] = x
## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
def sieve(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e6 + 5)
def spf_sieve():
spf[1] = 1;
for i in range(2, MAXN):
spf[i] = i;
for i in range(4, MAXN, 2):
spf[i] = 2;
for i in range(3, ceil(MAXN ** 0.5), 2):
if spf[i] == i:
for j in range(i*i, MAXN, i):
if spf[j] == j:
spf[j] = i;
## function for storing smallest prime factors (spf) in the array
################## un-comment below 2 lines when using factorization #################
# spf = [0 for i in range(MAXN)]
# spf_sieve()
def factoriazation(x):
ret = {};
while x != 1:
ret[spf[x]] = ret.get(spf[x], 0) + 1;
x = x//spf[x]
return ret
## this function is useful for multiple queries only, o/w use
## primefs function above. complexity O(log n)
## taking integer array input
def int_array():
return list(map(int, input().strip().split()))
## taking string array input
def str_array():
return input().strip().split();
#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');
################### ---------------- TEMPLATE ENDS HERE ---------------- ###################
def ComputeLPSArray(pat):
M = len(pat); lps = [0]*M;
length = 0; i = 1;
## lps[0] is already 0, so no need of lps[0] = 0;
while( i < M ):
if (pat[i] == pat[length]):
lps[i] = length + 1;
length += 1; i += 1;
else:
if length != 0:
length = lps[length - 1];
else:
lps[i] = 0;
i += 1;
return lps;
string = input().strip();
# string = 'aaaaabaaaa';
lps = ComputeLPSArray(string);
x = lps[ lps[-1] - 1 ];
if x <= 0:
x = -1;
k = lps[-1];
if lps.count(k) > 1 and k > 0:
pass;
else:
k = -1;
k = max(x, k);
if k > 0:
print(string[:k]);
else:
print('Just a legend');
```
| 29,222 | [
0.37353515625,
0.033111572265625,
0.1865234375,
-0.07745361328125,
-0.103515625,
-0.302490234375,
-0.054534912109375,
0.06976318359375,
0.125732421875,
0.7021484375,
0.62255859375,
0.11712646484375,
-0.166259765625,
-1.005859375,
-0.841796875,
0.2685546875,
-0.4345703125,
-0.521972... | 0 |
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
Tags: binary search, dp, hashing, string suffix structures, strings
Correct Solution:
```
P=input()
m = len(P)
f=[0]*m
j=1
k=0
while j<m:
if P[j]==P[k]:
f[j]=k+1
j+=1
k+=1
elif k>0:
k=f[k-1]
else:
j+=1
l=f.pop()
if l:
if l in f:
print(P[:l])
elif f[l-1]:
print(P[:f[l-1]])
else:
print('Just a legend')
else:
print('Just a legend')
```
| 29,223 | [
0.365966796875,
0.0257720947265625,
0.2064208984375,
-0.07965087890625,
-0.1279296875,
-0.31005859375,
-0.00664520263671875,
0.0819091796875,
0.133544921875,
0.70751953125,
0.56396484375,
0.1680908203125,
-0.07244873046875,
-0.9931640625,
-0.91455078125,
0.28955078125,
-0.47973632812... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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
Submitted Solution:
```
s = input()
n = len(s)
p = [0] * (n + 1)
i =0
j = 1
while j < n:
if s[j] == s[i]:
j += 1
i += 1
p[j] = i
elif i:
i = p[i]
else:
j += 1
a = p.pop()
b = p[a]
if (a) and (a in p):
print(s[:a])
elif (b):
print(s[:b])
else:
print('Just a legend')
```
Yes
| 29,227 | [
0.42578125,
0.01381683349609375,
0.0831298828125,
-0.03326416015625,
-0.298095703125,
-0.1597900390625,
-0.101318359375,
0.165771484375,
0.12432861328125,
0.62060546875,
0.580078125,
0.1553955078125,
-0.10015869140625,
-1.0244140625,
-0.9208984375,
0.264404296875,
-0.453857421875,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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
Submitted Solution:
```
from typing import Tuple
def comp_z(s: str) -> Tuple[int]:
"""Computes the z-array for a given string s.
z[i] := the length of the longest substring of s, starting at index i, which is also a prefix of s.
0 <= i < len(s); z[0] = len(s).
"""
n = len(s)
z = [0] * n
z[0] = n
# left and right boundaries of the current right most z-box [L,R)
L, R = 0, 0
for i in range(1, n):
if i >= R:
L = i
R = i
while R < n and s[R] == s[R-L]:
R += 1
z[i] = R-L
else: # L < i < R
# len of [i,R)
x = R-i
if x > z[i-L]:
z[i] = z[i-L]
else: # x <= z[i-L] and we know s[i..R) matches prefix
L = i
# continue matching from R onwards
while R < n and s[R] == s[R-L]:
R += 1
z[i] = R-L
return tuple(z)
def run():
"""Solves https://codeforces.com/contest/126/problem/B."""
s = input()
n = len(s)
z = comp_z(s)
maxz = 0
res = 0
for i in range(1, n):
if z[i] == n-i and maxz >= n-i:
res = n-i
# break as we already found the longest one;
# as i increases, the length decreases
break
maxz = max(maxz, z[i])
if res == 0:
print('Just a legend')
else:
print(s[:res])
if __name__ == "__main__":
run()
```
Yes
| 29,228 | [
0.422607421875,
-0.044677734375,
0.1358642578125,
0.0751953125,
-0.39013671875,
-0.162841796875,
-0.19091796875,
0.150390625,
0.091552734375,
0.6171875,
0.56787109375,
0.2110595703125,
-0.00595855712890625,
-1.0009765625,
-0.9111328125,
0.293701171875,
-0.336669921875,
-0.5234375,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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
Submitted Solution:
```
#!/usr/bin/env python3
# created : 2020. 12. 31. 23:59
import os
from sys import stdin, stdout
def getPrefixFunction(w):
m = len(w)
pf = [0 for i in range(m)]
j = 0
for i in range(1, m):
while j > 0 and w[i] != w[j]:
j = pf[j-1]
if w[i] == w[j]:
j += 1
pf[i] = j
return pf
def solve(tc):
s = stdin.readline().strip()
n = len(s)
pf = getPrefixFunction(s)
if pf[n-1] == 0:
print("Just a legend")
return
for i in range(1, n-1):
if pf[i] == pf[n-1]:
print(s[:pf[n-1]])
return
k = pf[pf[n-1]-1]
if k > 0:
print(s[:k])
return
print("Just a legend")
tcs = 1
# tcs = int(stdin.readline().strip())
tc = 1
while tc <= tcs:
solve(tc)
tc += 1
```
Yes
| 29,229 | [
0.4111328125,
0.016876220703125,
0.0350341796875,
0.0008649826049804688,
-0.325439453125,
-0.12445068359375,
-0.10302734375,
0.182373046875,
0.118896484375,
0.564453125,
0.5166015625,
0.127685546875,
-0.12548828125,
-1.041015625,
-0.92578125,
0.25732421875,
-0.42138671875,
-0.48632... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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
Submitted Solution:
```
def knuthMorrisonPreprocess(pattern , m ):
fail = [0]*m
i = 0
j= 1
fail[0]=0
while(j < m ):
if pattern[i] == pattern[j]:
fail[j]= i+1
i+=1
j+=1
elif i > 0:
i = fail[i-1]
else:
j+=1
return fail
string = input()
n = len(string)
properPrefixArrayL = knuthMorrisonPreprocess(string , n )
properPrefixArray =properPrefixArrayL[-1]
if properPrefixArray == 0:
print("Just a legend")
quit()
for i in range(0,n-1):
if properPrefixArrayL[i] == properPrefixArrayL[n-1]:
print(string[0:properPrefixArrayL[i]])
quit()
if properPrefixArrayL[properPrefixArrayL[n-1]-1] == 0:
print("Just a legend")
else:
print(string[0:properPrefixArrayL[properPrefixArrayL[n-1]-1]])
```
Yes
| 29,230 | [
0.45556640625,
0.0006837844848632812,
0.043853759765625,
-0.0276641845703125,
-0.315673828125,
-0.135009765625,
-0.1243896484375,
0.09490966796875,
0.045928955078125,
0.650390625,
0.61279296875,
0.1468505859375,
-0.10150146484375,
-0.9912109375,
-0.8818359375,
0.29541015625,
-0.41333... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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
Submitted Solution:
```
from collections import Counter
'''
def fun(s):
a=Counter(s)
n=[]
for i in range(len(s)):
if s[i] not in a:
break
else:
if a[s[i]]<3:
break
else:
n.append(s[i])
a[s[i]]=a[s[i]]-1
if a[s[i]]<=1:
break
if len(n)>0:
ns="".join(n)
j=ns
sf=s[len(s)-len(ns):]
if(j==sf):
return ns
else:
return "Just a legend"
else:
return "Just a legend"
'''
def au(s):
p=len(s)
for l in reversed(range(0,p)):
two= s[l:].find(s[0:l])
if two>0:
#print("-->"+s[0:l])
rel=l+two
#print(rel)
tree=s[rel+len(s[0:l]):].find(s[0:l])
rel2=(tree+rel+len(s[0:l]))
if tree>0:
break
if rel2!=rel and rel!=0:
return s[0:l]
else:
return "Just a legend"
if __name__ == '__main__':
s=str(input())
print(au(s))
```
No
| 29,231 | [
0.42822265625,
0.038299560546875,
0.099609375,
-0.03973388671875,
-0.339599609375,
-0.1640625,
-0.104736328125,
0.1533203125,
0.0931396484375,
0.6123046875,
0.5673828125,
0.190673828125,
-0.1490478515625,
-1.017578125,
-0.87890625,
0.2457275390625,
-0.46337890625,
-0.57958984375,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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
Submitted Solution:
```
#code
import sys
import math as mt
#input=sys.stdin.buffer.readline
#t=int(input())
#tot=0
t=1
def getZarr(string, z):
n = len(string)
# [L,R] make a window which matches
# with prefix of s
l, r, k = 0, 0, 0
for i in range(1, n):
# if i>R nothing matches so we will calculate.
# Z[i] using naive way.
if i > r:
l, r = i, i
# R-L = 0 in starting, so it will start
# checking from 0'th index. For example,
# for "ababab" and i = 1, the value of R
# remains 0 and Z[i] becomes 0. For string
# "aaaaaa" and i = 1, Z[i] and R become 5
while r < n and string[r - l] == string[r]:
r += 1
z[i] = r - l
r -= 1
else:
# k = i-L so k corresponds to number which
# matches in [L,R] interval.
k = i - l
# if Z[k] is less than remaining interval
# then Z[i] will be equal to Z[k].
# For example, str = "ababab", i = 3, R = 5
# and L = 2
if z[k] < r - i + 1:
z[i] = z[k]
# For example str = "aaaaaa" and i = 2,
# R is 5, L is 0
else:
# else start from R and check manually
l = i
while r < n and string[r - l] == string[r]:
r += 1
z[i] = r - l
r -= 1
for __ in range(t):
#n=int(input())
#l=list(map(int,input().split()))
#n,m=map(int,input().split())
#l=list(map(int,input().split()))
s=input()
z=[0]*(len(s)+1)
d={}
n=len(s)
getZarr(s, z)
#print(z)
d=[]
maxm=-1
for i in range(len(s)):
if i+z[i]!=n :
maxm=max(maxm,z[i])
else:
d.append(z[i])
maxi=-1
d.sort()
for i in range(len(s)):
if i+z[i]==n:
maxi=max(maxi,maxm)
if d[-1]!=z[i]:
maxi=max(maxi,z[i])
if maxi>0:
print(s[:maxi])
else:
print("Just a legend")
```
No
| 29,232 | [
0.364501953125,
-0.00021827220916748047,
0.0721435546875,
-0.0010461807250976562,
-0.29931640625,
-0.1544189453125,
-0.1075439453125,
0.133056640625,
0.11431884765625,
0.61474609375,
0.50927734375,
0.138427734375,
-0.11627197265625,
-1.0283203125,
-0.880859375,
0.266357421875,
-0.422... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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
Submitted Solution:
```
## necessary imports
import sys
input = sys.stdin.readline
from math import log2, log, ceil
# swap_array function
def swaparr(arr, a,b):
temp = arr[a];
arr[a] = arr[b];
arr[b] = temp
## gcd function
def gcd(a,b):
if a == 0:
return b
return gcd(b%a, a)
## nCr function efficient using Binomial Cofficient
def nCr(n, k):
if(k > n - k):
k = n - k
res = 1
for i in range(k):
res = res * (n - i)
res = res / (i + 1)
return res
## upper bound function code -- such that e in a[:i] e < x;
def upper_bound(a, x, lo=0):
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if a[mid] < x:
lo = mid+1
else:
hi = mid
return lo
## prime factorization
def primefs(n):
## if n == 1 ## calculating primes
primes = {}
while(n%2 == 0):
primes[2] = primes.get(2, 0) + 1
n = n//2
for i in range(3, int(n**0.5)+2, 2):
while(n%i == 0):
primes[i] = primes.get(i, 0) + 1
n = n//i
if n > 2:
primes[n] = primes.get(n, 0) + 1
## prime factoriazation of n is stored in dictionary
## primes and can be accesed. O(sqrt n)
return primes
## MODULAR EXPONENTIATION FUNCTION
def power(x, y, p):
res = 1
x = x % p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) :
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
temp = a
a = b
b = temp
return a,b
# find function with path compression included (recursive)
# def find(x, link):
# if link[x] == x:
# return x
# link[x] = find(link[x], link);
# return link[x];
# find function with path compression (ITERATIVE)
def find(x, link):
p = x;
while( p != link[p]):
p = link[p];
while( x != p):
nex = link[x];
link[x] = p;
x = nex;
return p;
# the union function which makes union(x,y)
# of two nodes x and y
def union(x, y, link, size):
x = find(x, link)
y = find(y, link)
if size[x] < size[y]:
x,y = swap(x,y)
if x != y:
size[x] += size[y]
link[y] = x
## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
def sieve(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e6 + 5)
def spf_sieve():
spf[1] = 1;
for i in range(2, MAXN):
spf[i] = i;
for i in range(4, MAXN, 2):
spf[i] = 2;
for i in range(3, ceil(MAXN ** 0.5), 2):
if spf[i] == i:
for j in range(i*i, MAXN, i):
if spf[j] == j:
spf[j] = i;
## function for storing smallest prime factors (spf) in the array
################## un-comment below 2 lines when using factorization #################
spf = [0 for i in range(MAXN)]
spf_sieve()
def factoriazation(x):
ret = {};
while x != 1:
ret[spf[x]] = ret.get(spf[x], 0) + 1;
x = x//spf[x]
return ret
## this function is useful for multiple queries only, o/w use
## primefs function above. complexity O(log n)
## taking integer array input
def int_array():
return list(map(int, input().strip().split()))
## taking string array input
def str_array():
return input().strip().split();
#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');
################### ---------------- TEMPLATE ENDS HERE ---------------- ###################
def ComputeLPSArray(pat):
M = len(pat); lps = [0]*M;
length = 0; i = 1;
## lps[0] is already 0, so no need of lps[0] = 0;
while( i < M ):
if (pat[i] == pat[length]):
lps[i] = length + 1;
length += 1; i += 1;
else:
if length != 0:
length = lps[length - 1];
else:
lps[i] = 0;
i += 1;
return lps;
string = input().strip();
a = ComputeLPSArray(string);
k = a[-1];
if k > 0 and a.count(k) > 1:
print(string[:k]);
else:
print("Just a legend");
```
No
| 29,233 | [
0.432861328125,
0.076904296875,
0.058929443359375,
0.0019817352294921875,
-0.267578125,
-0.2266845703125,
-0.125244140625,
0.12109375,
0.1094970703125,
0.63818359375,
0.65087890625,
0.11871337890625,
-0.2003173828125,
-1.0595703125,
-0.8818359375,
0.2261962890625,
-0.431396484375,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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
Submitted Solution:
```
s = list(input())
n = len(s)
exit = False
for i in range(n - 3, -1, -1):
#print(s[-1-i:])
#print(s[:i])
if (s[:i + 1] == s[-1-i:]):
for j in range(1, n - 2 - i):
if (s[:i + 1] == s[j:j + 1 + i]):
print(''.join(s[:i + 1]))
exit = True
break
if (exit):
break
if (not exit):
print('Just a legend')
```
No
| 29,234 | [
0.452392578125,
0.0158538818359375,
0.09783935546875,
-0.037200927734375,
-0.306640625,
-0.192626953125,
-0.11895751953125,
0.1375732421875,
0.11181640625,
0.62841796875,
0.5966796875,
0.191162109375,
-0.1318359375,
-1.0390625,
-0.88818359375,
0.2384033203125,
-0.453125,
-0.53125,
... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A and B are preparing themselves for programming contests.
After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.
A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes).
B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).
Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.
Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
Input
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≤ xi ≤ 105) — the value assigned to letters a, b, c, ..., z respectively.
The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase letters— the string for which you need to calculate the answer.
Output
Print the answer to the problem.
Examples
Input
1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1
xabcab
Output
2
Input
1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1
aaa
Output
2
Note
In the first sample test strings satisfying the condition above are abca and bcab.
In the second sample test strings satisfying the condition above are two occurences of aa.
Tags: data structures, dp, two pointers
Correct Solution:
```
x=list(map(int,input().split()))
s=list(input().rstrip())
n=len(s)
cx=[0]*(n+1)
for i in range(1,n+1):
cx[i]=x[ord(s[i-1])-ord("a")]
for i in range(1,n+1):
cx[i]+=cx[i-1]
pos=[{} for i in range(26)]
ans=0
for i in range(n):
ss=s[i]
ans+=pos[ord(ss)-ord("a")].get(cx[i],0)
pos[ord(ss)-ord("a")][cx[i+1]]=pos[ord(ss)-ord("a")].get(cx[i+1],0)+1
print(ans)
```
| 29,525 | [
0.349609375,
0.0916748046875,
0.292724609375,
0.17529296875,
-0.415283203125,
-0.50927734375,
-0.07623291015625,
-0.06536865234375,
0.1190185546875,
0.84375,
0.76953125,
-0.129638671875,
-0.15087890625,
-0.658203125,
-0.474853515625,
-0.1478271484375,
-0.53759765625,
-0.630859375,
... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A and B are preparing themselves for programming contests.
After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.
A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes).
B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).
Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.
Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
Input
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≤ xi ≤ 105) — the value assigned to letters a, b, c, ..., z respectively.
The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase letters— the string for which you need to calculate the answer.
Output
Print the answer to the problem.
Examples
Input
1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1
xabcab
Output
2
Input
1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1
aaa
Output
2
Note
In the first sample test strings satisfying the condition above are abca and bcab.
In the second sample test strings satisfying the condition above are two occurences of aa.
Tags: data structures, dp, two pointers
Correct Solution:
```
xx = [int(i) for i in input().split()]
s = input()
x = [{} for _ in range(0,26)]
ss = 0
ans = 0
for i in s:
ans += x[ord(i)-97].get(ss,0)
ss += xx[ord(i)-97]
x[ord(i)-97][ss] = x[ord(i)-97].get(ss,0)+1
print(ans)
```
| 29,526 | [
0.3544921875,
0.10919189453125,
0.294677734375,
0.1622314453125,
-0.408935546875,
-0.52197265625,
-0.08099365234375,
-0.0771484375,
0.1392822265625,
0.83837890625,
0.765625,
-0.14501953125,
-0.1875,
-0.6748046875,
-0.491455078125,
-0.16845703125,
-0.52197265625,
-0.615234375,
-0.... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A and B are preparing themselves for programming contests.
After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.
A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes).
B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).
Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.
Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
Input
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≤ xi ≤ 105) — the value assigned to letters a, b, c, ..., z respectively.
The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase letters— the string for which you need to calculate the answer.
Output
Print the answer to the problem.
Examples
Input
1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1
xabcab
Output
2
Input
1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1
aaa
Output
2
Note
In the first sample test strings satisfying the condition above are abca and bcab.
In the second sample test strings satisfying the condition above are two occurences of aa.
Tags: data structures, dp, two pointers
Correct Solution:
```
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
#from bisect import bisect_left as bl #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br #c++ upperbound br(array,element)
from collections import *
def main():
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
values=list(map(int,input().split(" ")))
s=input()
dic=defaultdict(lambda:[])
pre=[0 for x in range(len(s)+1)]
for x in range(len(s)):
pre[x+1]=pre[x]+values[ord(s[x])-ord('a')]
dic[s[x]].append(x)
ans=0
for x,y in dic.items():
here=defaultdict(lambda:0)
for z in y:
if pre[z] in here:
ans+=here[pre[z]]
here[pre[z+1]]+=1
print(ans)
#-----------------------------hey angel-------------------------------------!
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
```
| 29,527 | [
0.2275390625,
0.138916015625,
0.310302734375,
0.272216796875,
-0.53466796875,
-0.467529296875,
0.03485107421875,
-0.142333984375,
0.07965087890625,
0.9091796875,
0.7021484375,
-0.119140625,
-0.038665771484375,
-0.72998046875,
-0.56396484375,
-0.14111328125,
-0.56298828125,
-0.72509... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A and B are preparing themselves for programming contests.
After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.
A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes).
B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).
Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.
Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
Input
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≤ xi ≤ 105) — the value assigned to letters a, b, c, ..., z respectively.
The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase letters— the string for which you need to calculate the answer.
Output
Print the answer to the problem.
Examples
Input
1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1
xabcab
Output
2
Input
1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1
aaa
Output
2
Note
In the first sample test strings satisfying the condition above are abca and bcab.
In the second sample test strings satisfying the condition above are two occurences of aa.
Tags: data structures, dp, two pointers
Correct Solution:
```
w = [int(x) for x in input().split()]
c = [{} for i in range(26)]
val, s = 0, 0
for i in [ord(ch) - ord('a') for ch in input()]:
if s - w[i] in c[i]:
val += c[i][s - w[i]]
c[i][s] = c[i][s] + 1 if s in c[i] else 1
s += w[i]
print(val)
```
| 29,528 | [
0.318359375,
0.1007080078125,
0.296630859375,
0.1856689453125,
-0.416015625,
-0.488037109375,
-0.036376953125,
-0.058074951171875,
0.11785888671875,
0.85595703125,
0.76416015625,
-0.1368408203125,
-0.1890869140625,
-0.69287109375,
-0.51025390625,
-0.1585693359375,
-0.5546875,
-0.61... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A and B are preparing themselves for programming contests.
After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.
A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes).
B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).
Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.
Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
Input
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≤ xi ≤ 105) — the value assigned to letters a, b, c, ..., z respectively.
The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase letters— the string for which you need to calculate the answer.
Output
Print the answer to the problem.
Examples
Input
1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1
xabcab
Output
2
Input
1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1
aaa
Output
2
Note
In the first sample test strings satisfying the condition above are abca and bcab.
In the second sample test strings satisfying the condition above are two occurences of aa.
Tags: data structures, dp, two pointers
Correct Solution:
```
score=[]
from collections import *
z=list(map(int,input().split()))
s=input()
for i in range(26):
score.append(defaultdict(int))
pre=[]
total=0
for i in range(len(s)):
s1=z[ord(s[i])-97]
t=ord(s[i])-97
if(i==0):
pre.append(s1)
else:
pre.append(pre[-1]+s1)
s1=pre[-1]
score[t][s1]+=1
if(z[t]==0):
total+=max(0,score[t][s1]-1)
else:
total+=max(0,score[t][s1-z[t]])
print(total)
```
| 29,529 | [
0.308349609375,
0.08624267578125,
0.32861328125,
0.1517333984375,
-0.4267578125,
-0.5,
-0.06781005859375,
-0.0989990234375,
0.10858154296875,
0.83544921875,
0.74169921875,
-0.150390625,
-0.141357421875,
-0.6279296875,
-0.51611328125,
-0.158203125,
-0.55859375,
-0.63427734375,
-0.... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A and B are preparing themselves for programming contests.
After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.
A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes).
B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).
Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.
Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
Input
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≤ xi ≤ 105) — the value assigned to letters a, b, c, ..., z respectively.
The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase letters— the string for which you need to calculate the answer.
Output
Print the answer to the problem.
Examples
Input
1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1
xabcab
Output
2
Input
1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1
aaa
Output
2
Note
In the first sample test strings satisfying the condition above are abca and bcab.
In the second sample test strings satisfying the condition above are two occurences of aa.
Tags: data structures, dp, two pointers
Correct Solution:
```
score=[]
from collections import *
z=list(map(int,input().split()))
s=input()
for i in range(26):
score.append(defaultdict(int))
pre=[]
total=0
for i in range(len(s)):
s1=z[ord(s[i])-97]
t=ord(s[i])-97
if(i==0):
pre.append(s1)
else:
pre.append(pre[-1]+s1)
s1=pre[-1]
score[t][s1]+=1
if(z[t]==0):
total+=max(0,score[t][s1]-1)
else:
total+=max(0,score[t][s1-z[t]])
fin=[]
count=1
for i in range(1,len(s)):
if(s[i]==s[i-1]):
count+=1
else:
fin.append([count,s[i-1]])
count=1
fin.append([count,s[-1]])
print(total)
```
| 29,530 | [
0.308349609375,
0.08624267578125,
0.32861328125,
0.1517333984375,
-0.4267578125,
-0.5,
-0.06781005859375,
-0.0989990234375,
0.10858154296875,
0.83544921875,
0.74169921875,
-0.150390625,
-0.141357421875,
-0.6279296875,
-0.51611328125,
-0.158203125,
-0.55859375,
-0.63427734375,
-0.... | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.