message
stringlengths
2
23.8k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
97
109k
cluster
float64
0
0
__index_level_0__
int64
194
217k
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.
instruction
0
28,296
0
56,592
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() ```
output
1
28,296
0
56,593
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.
instruction
0
28,297
0
56,594
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) ```
output
1
28,297
0
56,595
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.
instruction
0
28,298
0
56,596
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) ```
output
1
28,298
0
56,597
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.
instruction
0
28,299
0
56,598
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)) ```
output
1
28,299
0
56,599
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.
instruction
0
28,300
0
56,600
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() ```
output
1
28,300
0
56,601
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.
instruction
0
28,301
0
56,602
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) ```
output
1
28,301
0
56,603
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() ```
instruction
0
28,302
0
56,604
No
output
1
28,302
0
56,605
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) ```
instruction
0
28,303
0
56,606
No
output
1
28,303
0
56,607
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)) ```
instruction
0
28,304
0
56,608
No
output
1
28,304
0
56,609
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) ```
instruction
0
28,305
0
56,610
No
output
1
28,305
0
56,611
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
instruction
0
28,306
0
56,612
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='') ```
output
1
28,306
0
56,613
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
instruction
0
28,307
0
56,614
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)) ```
output
1
28,307
0
56,615
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
instruction
0
28,308
0
56,616
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)) ```
output
1
28,308
0
56,617
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
instruction
0
28,309
0
56,618
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) ```
output
1
28,309
0
56,619
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
instruction
0
28,310
0
56,620
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)) ```
output
1
28,310
0
56,621
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
instruction
0
28,311
0
56,622
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)) ```
output
1
28,311
0
56,623
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
instruction
0
28,312
0
56,624
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) ```
output
1
28,312
0
56,625
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
instruction
0
28,313
0
56,626
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)) ```
output
1
28,313
0
56,627
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() ```
instruction
0
28,314
0
56,628
Yes
output
1
28,314
0
56,629
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)) ```
instruction
0
28,315
0
56,630
Yes
output
1
28,315
0
56,631
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="") ```
instruction
0
28,316
0
56,632
Yes
output
1
28,316
0
56,633
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)) ```
instruction
0
28,317
0
56,634
Yes
output
1
28,317
0
56,635
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()) ```
instruction
0
28,318
0
56,636
No
output
1
28,318
0
56,637
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)) ```
instruction
0
28,319
0
56,638
No
output
1
28,319
0
56,639
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)) ```
instruction
0
28,320
0
56,640
No
output
1
28,320
0
56,641
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)) ```
instruction
0
28,321
0
56,642
No
output
1
28,321
0
56,643
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
instruction
0
28,454
0
56,908
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() ```
output
1
28,454
0
56,909
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
instruction
0
28,455
0
56,910
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() ```
output
1
28,455
0
56,911
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
instruction
0
28,456
0
56,912
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) ```
output
1
28,456
0
56,913
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
instruction
0
28,457
0
56,914
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() ```
output
1
28,457
0
56,915
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
instruction
0
28,458
0
56,916
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() ```
output
1
28,458
0
56,917
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
instruction
0
28,459
0
56,918
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() ```
output
1
28,459
0
56,919
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
instruction
0
28,460
0
56,920
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""" ```
output
1
28,460
0
56,921
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
instruction
0
28,461
0
56,922
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() ```
output
1
28,461
0
56,923
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') ```
instruction
0
28,462
0
56,924
Yes
output
1
28,462
0
56,925
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) ```
instruction
0
28,463
0
56,926
Yes
output
1
28,463
0
56,927
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) ```
instruction
0
28,464
0
56,928
Yes
output
1
28,464
0
56,929
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 ```
instruction
0
28,465
0
56,930
Yes
output
1
28,465
0
56,931
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() ```
instruction
0
28,466
0
56,932
No
output
1
28,466
0
56,933
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) ```
instruction
0
28,467
0
56,934
No
output
1
28,467
0
56,935
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() ```
instruction
0
28,468
0
56,936
No
output
1
28,468
0
56,937
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) ```
instruction
0
28,469
0
56,938
No
output
1
28,469
0
56,939
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() ```
instruction
0
28,592
0
57,184
No
output
1
28,592
0
57,185
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) ```
instruction
0
28,593
0
57,186
No
output
1
28,593
0
57,187
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) ```
instruction
0
28,594
0
57,188
No
output
1
28,594
0
57,189
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) ```
instruction
0
28,595
0
57,190
No
output
1
28,595
0
57,191
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) ```
instruction
0
28,675
0
57,350
No
output
1
28,675
0
57,351
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
instruction
0
28,908
0
57,816
"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]) ```
output
1
28,908
0
57,817
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
instruction
0
28,909
0
57,818
"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) ```
output
1
28,909
0
57,819
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
instruction
0
28,910
0
57,820
"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]) ```
output
1
28,910
0
57,821