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.
You are given two strings s and t, each of length n and consisting of lowercase Latin alphabets. You want to make s equal to t.
You can perform the following operation on s any number of times to achieve it —
* Choose any substring of s and rotate it clockwise once, that is, if the selected substring is s[l,l+1...r], then it becomes s[r,l,l + 1 ... r - 1]. All the remaining characters of s stay in their position.
For example, on rotating the substring [2,4] , string "abcde" becomes "adbce".
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Find the minimum number of operations required to convert s to t, or determine that it's impossible.
Input
The first line of the input contains a single integer t (1≤ t ≤ 2000) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (1≤ n ≤ 2000) — the length of the strings.
The second and the third lines contain strings s and t respectively.
The sum of n over all the test cases does not exceed 2000.
Output
For each test case, output the minimum number of operations to convert s to t. If it is not possible to convert s to t, output -1 instead.
Example
Input
6
1
a
a
2
ab
ba
3
abc
cab
3
abc
cba
4
abab
baba
4
abcc
aabc
Output
0
1
1
2
1
-1
Note
For the 1-st test case, since s and t are equal, you don't need to apply any operation.
For the 2-nd test case, you only need to apply one operation on the entire string ab to convert it to ba.
For the 3-rd test case, you only need to apply one operation on the entire string abc to convert it to cab.
For the 4-th test case, you need to apply the operation twice: first on the entire string abc to convert it to cab and then on the substring of length 2 beginning at the second character to convert it to cba.
For the 5-th test case, you only need to apply one operation on the entire string abab to convert it to baba.
For the 6-th test case, it is not possible to convert string s to t. | instruction | 0 | 95,409 | 0 | 190,818 |
Tags: dp, strings
Correct Solution:
```
import os
### START FAST IO ###
os_input = os.read(0, int(1e7)).split()
os_input_pos = -1
answer_list = []
def read_s():
global os_input_pos
os_input_pos += 1
return os_input[os_input_pos].decode()
def read_i():
return int(read_s())
def write_s(v):
answer_list.append(v)
def write_i(v):
write_s(str(v))
def print_ans():
os.write(1, "\n".join(answer_list).encode())
os.write(1, "\n".encode())
#### END FAST IO ####
T = read_i()
while T:
T -= 1
n = read_i()
s = read_s()
t = read_s()
if sorted(s) != sorted(t):
write_i(-1)
continue
s_count = [[0 for i in range(n+1)] for j in range(26)]
t_count = [[0 for i in range(n+1)] for j in range(26)]
for i in range(n):
for j in range(26):
s_count[j][i] = s_count[j][i-1]
t_count[j][i] = t_count[j][i-1]
s_count[ord(s[i]) - ord('a')][i] += 1
t_count[ord(t[i]) - ord('a')][i] += 1
dp = [[0 for i in range(n+1)] for j in range(n+1)]
for i in range(0, n):
for j in range(i, n):
dp[i][j] = dp[i-1][j] + 1
if s[i] == t[j]:
dp[i][j] = min(dp[i][j], dp[i-1][j-1])
c = ord(t[j]) - ord('a')
if s_count[c][i] < t_count[c][j]:
dp[i][j] = min(dp[i][j], dp[i][j-1])
write_i(dp[n-1][n-1])
print_ans()
``` | output | 1 | 95,409 | 0 | 190,819 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings s and t, each of length n and consisting of lowercase Latin alphabets. You want to make s equal to t.
You can perform the following operation on s any number of times to achieve it —
* Choose any substring of s and rotate it clockwise once, that is, if the selected substring is s[l,l+1...r], then it becomes s[r,l,l + 1 ... r - 1]. All the remaining characters of s stay in their position.
For example, on rotating the substring [2,4] , string "abcde" becomes "adbce".
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Find the minimum number of operations required to convert s to t, or determine that it's impossible.
Input
The first line of the input contains a single integer t (1≤ t ≤ 2000) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (1≤ n ≤ 2000) — the length of the strings.
The second and the third lines contain strings s and t respectively.
The sum of n over all the test cases does not exceed 2000.
Output
For each test case, output the minimum number of operations to convert s to t. If it is not possible to convert s to t, output -1 instead.
Example
Input
6
1
a
a
2
ab
ba
3
abc
cab
3
abc
cba
4
abab
baba
4
abcc
aabc
Output
0
1
1
2
1
-1
Note
For the 1-st test case, since s and t are equal, you don't need to apply any operation.
For the 2-nd test case, you only need to apply one operation on the entire string ab to convert it to ba.
For the 3-rd test case, you only need to apply one operation on the entire string abc to convert it to cab.
For the 4-th test case, you need to apply the operation twice: first on the entire string abc to convert it to cab and then on the substring of length 2 beginning at the second character to convert it to cba.
For the 5-th test case, you only need to apply one operation on the entire string abab to convert it to baba.
For the 6-th test case, it is not possible to convert string s to t. | instruction | 0 | 95,410 | 0 | 190,820 |
Tags: dp, strings
Correct Solution:
```
import sys
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]
def main():
inf=10**9
for _ in range(II()):
n=II()
s = SI()
t = SI()
cnts=[[0]*26 for _ in range(n+1)]
cntt=[[0]*26 for _ in range(n+1)]
for i in range(n-1,-1,-1):
cnts[i][ord(s[i])-97]+=1
cntt[i][ord(t[i])-97]+=1
for j in range(26):
cnts[i][j]+=cnts[i+1][j]
cntt[i][j]+=cntt[i+1][j]
ng=False
for j in range(26):
if cnts[0][j]!=cntt[0][j]:
ng=True
break
if ng:
print(-1)
continue
dp=[[inf]*(n+1) for _ in range(n+1)]
for i in range(n+1):dp[i][0]=0
for i in range(n+1):
for j in range(i,n+1):
if i==n and j==n:break
pre=dp[i][j]
if pre==inf:continue
if i<j and i+1<=n:dp[i+1][j]=min(dp[i+1][j],pre+1)
if i+1<=n and j+1<=n and s[i]==t[j]:dp[i+1][j+1]=min(dp[i+1][j+1],pre)
if j+1<=n and cnts[i+1][ord(t[j])-97]>cntt[j+1][ord(t[j])-97]:
dp[i][j + 1] = min(dp[i][j + 1], pre)
#p2D(dp)
print(dp[n][n])
main()
``` | output | 1 | 95,410 | 0 | 190,821 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings s and t, each of length n and consisting of lowercase Latin alphabets. You want to make s equal to t.
You can perform the following operation on s any number of times to achieve it —
* Choose any substring of s and rotate it clockwise once, that is, if the selected substring is s[l,l+1...r], then it becomes s[r,l,l + 1 ... r - 1]. All the remaining characters of s stay in their position.
For example, on rotating the substring [2,4] , string "abcde" becomes "adbce".
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Find the minimum number of operations required to convert s to t, or determine that it's impossible.
Input
The first line of the input contains a single integer t (1≤ t ≤ 2000) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (1≤ n ≤ 2000) — the length of the strings.
The second and the third lines contain strings s and t respectively.
The sum of n over all the test cases does not exceed 2000.
Output
For each test case, output the minimum number of operations to convert s to t. If it is not possible to convert s to t, output -1 instead.
Example
Input
6
1
a
a
2
ab
ba
3
abc
cab
3
abc
cba
4
abab
baba
4
abcc
aabc
Output
0
1
1
2
1
-1
Note
For the 1-st test case, since s and t are equal, you don't need to apply any operation.
For the 2-nd test case, you only need to apply one operation on the entire string ab to convert it to ba.
For the 3-rd test case, you only need to apply one operation on the entire string abc to convert it to cab.
For the 4-th test case, you need to apply the operation twice: first on the entire string abc to convert it to cab and then on the substring of length 2 beginning at the second character to convert it to cba.
For the 5-th test case, you only need to apply one operation on the entire string abab to convert it to baba.
For the 6-th test case, it is not possible to convert string s to t. | instruction | 0 | 95,411 | 0 | 190,822 |
Tags: dp, strings
Correct Solution:
```
def num(c):return ord(c) - 97
import sys
input = sys.stdin.readline
for _ in range(int(input())):
n = int(input());s1 = input().strip();s2 = input().strip();char1 = [0] * 26;char2 = [0] * 26
for c in s1:char1[num(c)] += 1
for c in s2:char2[num(c)] += 1
if char1 != char2:print(-1);continue
dp = [[(False, 0, 0) for j in range(n+1)] for i in range(n + 1)];dp[0][0] = [True, 0,[0]*26]
def upd(a, b, val, sett):
if not dp[a][b][0] or val > dp[a][b][1]:dp[a][b] = (True, val, sett)
for i in range(n):
for j in range(n):
valid, val, tab = dp[i][j]
if not valid:continue
top = s1[i];bot = s2[j]
if top == bot:
if not dp[i + 1][j + 1][0] or val + 1 > dp[i + 1][j + 1][1]:dp[i + 1][j + 1] = [True, val + 1, tab]
if tab[num(top)] > 0:
sett = tab[:];sett[num(top)] -= 1
if not dp[i + 1][j][0] or val > dp[i + 1][j][1]:dp[i + 1][j] = [True, val, sett]
sett = tab[:];sett[num(bot)] += 1
if not dp[i][j + 1][0] or val > dp[i][j + 1][1]:dp[i][j + 1] = [True, val, sett]
del dp[i][j][2]
poss = [dp[i][n][1] for i in range(n + 1)]
print(n - max(poss))
``` | output | 1 | 95,411 | 0 | 190,823 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings s and t, each of length n and consisting of lowercase Latin alphabets. You want to make s equal to t.
You can perform the following operation on s any number of times to achieve it —
* Choose any substring of s and rotate it clockwise once, that is, if the selected substring is s[l,l+1...r], then it becomes s[r,l,l + 1 ... r - 1]. All the remaining characters of s stay in their position.
For example, on rotating the substring [2,4] , string "abcde" becomes "adbce".
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Find the minimum number of operations required to convert s to t, or determine that it's impossible.
Input
The first line of the input contains a single integer t (1≤ t ≤ 2000) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (1≤ n ≤ 2000) — the length of the strings.
The second and the third lines contain strings s and t respectively.
The sum of n over all the test cases does not exceed 2000.
Output
For each test case, output the minimum number of operations to convert s to t. If it is not possible to convert s to t, output -1 instead.
Example
Input
6
1
a
a
2
ab
ba
3
abc
cab
3
abc
cba
4
abab
baba
4
abcc
aabc
Output
0
1
1
2
1
-1
Note
For the 1-st test case, since s and t are equal, you don't need to apply any operation.
For the 2-nd test case, you only need to apply one operation on the entire string ab to convert it to ba.
For the 3-rd test case, you only need to apply one operation on the entire string abc to convert it to cab.
For the 4-th test case, you need to apply the operation twice: first on the entire string abc to convert it to cab and then on the substring of length 2 beginning at the second character to convert it to cba.
For the 5-th test case, you only need to apply one operation on the entire string abab to convert it to baba.
For the 6-th test case, it is not possible to convert string s to t. | instruction | 0 | 95,412 | 0 | 190,824 |
Tags: dp, strings
Correct Solution:
```
from bisect import *
from collections import *
from math import gcd,ceil,sqrt,floor,inf
from heapq import *
from itertools import *
from operator import add,mul,sub,xor,truediv,floordiv
from functools import *
#------------------------------------------------------------------------
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")
#------------------------------------------------------------------------
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())
#------------------------------------------------------------------------
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
farr=[1]
ifa=[]
def fact(x,mod=0):
if mod:
while x>=len(farr):
farr.append(farr[-1]*len(farr)%mod)
else:
while x>=len(farr):
farr.append(farr[-1]*len(farr))
return farr[x]
def ifact(x,mod):
global ifa
ifa.append(pow(farr[-1],mod-2,mod))
for i in range(x,0,-1):
ifa.append(ifa[-1]*i%mod)
ifa=ifa[::-1]
def per(i,j,mod=0):
if i<j: return 0
if not mod:
return fact(i)//fact(i-j)
return farr[i]*ifa[i-j]%mod
def com(i,j,mod=0):
if i<j: return 0
if not mod:
return per(i,j)//fact(j)
return per(i,j,mod)*ifa[j]%mod
def catalan(n):
return com(2*n,n)//(n+1)
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def lowbit(n):
return n&-n
def inverse(a,m):
a%=m
if a<=1: return a
return ((1-inverse(m,a)*m)//a)%m
class BIT:
def __init__(self,arr):
self.arr=arr
self.n=len(arr)-1
def update(self,x,v):
while x<=self.n:
self.arr[x]+=v
x+=x&-x
def query(self,x):
ans=0
while x:
ans+=self.arr[x]
x&=x-1
return ans
'''
class SMT:
def __init__(self,arr):
self.n=len(arr)-1
self.arr=[0]*(self.n<<2)
self.lazy=[0]*(self.n<<2)
def Build(l,r,rt):
if l==r:
self.arr[rt]=arr[l]
return
m=(l+r)>>1
Build(l,m,rt<<1)
Build(m+1,r,rt<<1|1)
self.pushup(rt)
Build(1,self.n,1)
def pushup(self,rt):
self.arr[rt]=self.arr[rt<<1]+self.arr[rt<<1|1]
def pushdown(self,rt,ln,rn):#lr,rn表区间数字数
if self.lazy[rt]:
self.lazy[rt<<1]+=self.lazy[rt]
self.lazy[rt<<1|1]+=self.lazy[rt]
self.arr[rt<<1]+=self.lazy[rt]*ln
self.arr[rt<<1|1]+=self.lazy[rt]*rn
self.lazy[rt]=0
def update(self,L,R,c,l=1,r=None,rt=1):#L,R表示操作区间
if r==None: r=self.n
if L<=l and r<=R:
self.arr[rt]+=c*(r-l+1)
self.lazy[rt]+=c
return
m=(l+r)>>1
self.pushdown(rt,m-l+1,r-m)
if L<=m: self.update(L,R,c,l,m,rt<<1)
if R>m: self.update(L,R,c,m+1,r,rt<<1|1)
self.pushup(rt)
def query(self,L,R,l=1,r=None,rt=1):
if r==None: r=self.n
#print(L,R,l,r,rt)
if L<=l and R>=r:
return self.arr[rt]
m=(l+r)>>1
self.pushdown(rt,m-l+1,r-m)
ans=0
if L<=m: ans+=self.query(L,R,l,m,rt<<1)
if R>m: ans+=self.query(L,R,m+1,r,rt<<1|1)
return ans
'''
class DSU:#容量+路径压缩
def __init__(self,n):
self.c=[-1]*n
def same(self,x,y):
return self.find(x)==self.find(y)
def find(self,x):
if self.c[x]<0:
return x
self.c[x]=self.find(self.c[x])
return self.c[x]
def union(self,u,v):
u,v=self.find(u),self.find(v)
if u==v:
return False
if self.c[u]<self.c[v]:
u,v=v,u
self.c[u]+=self.c[v]
self.c[v]=u
return True
def size(self,x): return -self.c[self.find(x)]
class UFS:#秩+路径
def __init__(self,n):
self.parent=[i for i in range(n)]
self.ranks=[0]*n
def find(self,x):
if x!=self.parent[x]:
self.parent[x]=self.find(self.parent[x])
return self.parent[x]
def union(self,u,v):
pu,pv=self.find(u),self.find(v)
if pu==pv:
return False
if self.ranks[pu]>=self.ranks[pv]:
self.parent[pv]=pu
if self.ranks[pv]==self.ranks[pu]:
self.ranks[pu]+=1
else:
self.parent[pu]=pv
def Prime(n):
c=0
prime=[]
flag=[0]*(n+1)
for i in range(2,n+1):
if not flag[i]:
prime.append(i)
c+=1
for j in range(c):
if i*prime[j]>n: break
flag[i*prime[j]]=prime[j]
if i%prime[j]==0: break
#print(flag)
return flag
def dij(s,graph):
d={}
d[s]=0
heap=[(0,s)]
seen=set()
while heap:
dis,u=heappop(heap)
if u in seen:
continue
for v in graph[u]:
if v not in d or d[v]>d[u]+graph[u][v]:
d[v]=d[u]+graph[u][v]
heappush(heap,(d[v],v))
return d
def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)]
class DLN:
def __init__(self,val):
self.val=val
self.pre=None
self.next=None
def nb(i,j):
for ni,nj in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]:
if 0<=ni<n and 0<=nj<m:
yield ni,nj
@bootstrap
def gdfs(r,p):
if len(g[r])==1 and p!=-1:
yield None
for ch in g[r]:
if ch!=p:
yield gdfs(ch,r)
yield None
t=N()
for i in range(t):
n=N()
s=input()
k=input()
ssuf=[[] for i in range(n+1)]
ksuf=[[] for i in range(n+1)]
ssuf[-1]=[0]*26
ksuf[-1]=[0]*26
for i in range(n-1,-1,-1):
ssuf[i]=ssuf[i+1].copy()
ssuf[i][ord(s[i])-97]+=1
ksuf[i]=ksuf[i+1].copy()
ksuf[i][ord(k[i])-97]+=1
if ssuf[0]!=ksuf[0]:
print(-1)
continue
dp=[[inf]*(n+1) for i in range(n+1)]
for j in range(n+1):
dp[0][j]=0
for i in range(1,n+1):
for j in range(i,n+1):
if s[i-1]==k[j-1]:
dp[i][j]=dp[i-1][j-1]
else:
dp[i][j]=dp[i-1][j]+1
cur=ord(k[j-1])-97
if i<j and ssuf[i][cur]-ksuf[j][cur]>0:
dp[i][j]=min(dp[i][j],dp[i][j-1])
print(dp[n][n])
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thread(target=main)
t.start()
t.join()
'''
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thread(target=main)
t.start()
t.join()
'''
``` | output | 1 | 95,412 | 0 | 190,825 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings s and t, each of length n and consisting of lowercase Latin alphabets. You want to make s equal to t.
You can perform the following operation on s any number of times to achieve it —
* Choose any substring of s and rotate it clockwise once, that is, if the selected substring is s[l,l+1...r], then it becomes s[r,l,l + 1 ... r - 1]. All the remaining characters of s stay in their position.
For example, on rotating the substring [2,4] , string "abcde" becomes "adbce".
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Find the minimum number of operations required to convert s to t, or determine that it's impossible.
Input
The first line of the input contains a single integer t (1≤ t ≤ 2000) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (1≤ n ≤ 2000) — the length of the strings.
The second and the third lines contain strings s and t respectively.
The sum of n over all the test cases does not exceed 2000.
Output
For each test case, output the minimum number of operations to convert s to t. If it is not possible to convert s to t, output -1 instead.
Example
Input
6
1
a
a
2
ab
ba
3
abc
cab
3
abc
cba
4
abab
baba
4
abcc
aabc
Output
0
1
1
2
1
-1
Note
For the 1-st test case, since s and t are equal, you don't need to apply any operation.
For the 2-nd test case, you only need to apply one operation on the entire string ab to convert it to ba.
For the 3-rd test case, you only need to apply one operation on the entire string abc to convert it to cab.
For the 4-th test case, you need to apply the operation twice: first on the entire string abc to convert it to cab and then on the substring of length 2 beginning at the second character to convert it to cba.
For the 5-th test case, you only need to apply one operation on the entire string abab to convert it to baba.
For the 6-th test case, it is not possible to convert string s to t. | instruction | 0 | 95,413 | 0 | 190,826 |
Tags: dp, strings
Correct Solution:
```
def num(c):
return ord(c) - 97
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
n = int(input())
s1 = input().strip()
s2 = input().strip()
char1 = [0] * 26
char2 = [0] * 26
for c in s1:
char1[num(c)] += 1
for c in s2:
char2[num(c)] += 1
if char1 != char2:
print(-1)
continue
dp = [[(False, 0, 0) for j in range(n+1)] for i in range(n + 1)]
dp[0][0] = [True, 0,[0]*26]
def upd(a, b, val, sett):
if not dp[a][b][0] or val > dp[a][b][1]:
dp[a][b] = (True, val, sett)
for i in range(n):
for j in range(n):
valid, val, tab = dp[i][j]
if not valid:
continue
top = s1[i]
bot = s2[j]
if top == bot:
#upd(i+1, j+1, val + 1, tab)
if not dp[i + 1][j + 1][0] or val + 1 > dp[i + 1][j + 1][1]:
dp[i + 1][j + 1] = [True, val + 1, tab]
if tab[num(top)] > 0:
sett = tab[:]
sett[num(top)] -= 1
#upd(i+1, j, val, sett)
if not dp[i + 1][j][0] or val > dp[i + 1][j][1]:
dp[i + 1][j] = [True, val, sett]
sett = tab[:]
sett[num(bot)] += 1
#upd(i, j + 1, val, sett)
if not dp[i][j + 1][0] or val > dp[i][j + 1][1]:
dp[i][j + 1] = [True, val, sett]
del dp[i][j][2]
poss = [dp[i][n][1] for i in range(n + 1)]
print(n - max(poss))
``` | output | 1 | 95,413 | 0 | 190,827 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings s and t, each of length n and consisting of lowercase Latin alphabets. You want to make s equal to t.
You can perform the following operation on s any number of times to achieve it —
* Choose any substring of s and rotate it clockwise once, that is, if the selected substring is s[l,l+1...r], then it becomes s[r,l,l + 1 ... r - 1]. All the remaining characters of s stay in their position.
For example, on rotating the substring [2,4] , string "abcde" becomes "adbce".
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Find the minimum number of operations required to convert s to t, or determine that it's impossible.
Input
The first line of the input contains a single integer t (1≤ t ≤ 2000) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (1≤ n ≤ 2000) — the length of the strings.
The second and the third lines contain strings s and t respectively.
The sum of n over all the test cases does not exceed 2000.
Output
For each test case, output the minimum number of operations to convert s to t. If it is not possible to convert s to t, output -1 instead.
Example
Input
6
1
a
a
2
ab
ba
3
abc
cab
3
abc
cba
4
abab
baba
4
abcc
aabc
Output
0
1
1
2
1
-1
Note
For the 1-st test case, since s and t are equal, you don't need to apply any operation.
For the 2-nd test case, you only need to apply one operation on the entire string ab to convert it to ba.
For the 3-rd test case, you only need to apply one operation on the entire string abc to convert it to cab.
For the 4-th test case, you need to apply the operation twice: first on the entire string abc to convert it to cab and then on the substring of length 2 beginning at the second character to convert it to cba.
For the 5-th test case, you only need to apply one operation on the entire string abab to convert it to baba.
For the 6-th test case, it is not possible to convert string s to t. | instruction | 0 | 95,414 | 0 | 190,828 |
Tags: dp, strings
Correct Solution:
```
def read_int():
return int(input())
def read_ints():
return map(int, input().split(' '))
t = read_int()
for case_num in range(t):
n = read_int()
cnt = [0 for i in range(26)]
ps = [[0 for j in range(n + 1)] for i in range(26)]
pt = [[0 for j in range(n + 1)] for i in range(26)]
s = input()
t = input()
for i in range(n):
ch = ord(s[i]) - ord('a')
cnt[ch] += 1
for j in range(26):
ps[j][i + 1] = ps[j][i] + (1 if ch == j else 0)
for i in range(n):
ch = ord(t[i]) - ord('a')
cnt[ch] -= 1
for j in range(26):
pt[j][i + 1] = pt[j][i] + (1 if ch == j else 0)
ok = True
for i in cnt:
if i != 0:
ok = False
break
if not ok:
print(-1)
else:
r = n
while r >= 1 and s[r - 1] == t[r - 1]:
r -= 1
inf = int(1e8)
dp = [[0 if i == 0 else inf for j in range(
r + 1)] for i in range(r + 1)]
for i in range(1, r + 1):
for j in range(i, r + 1):
if s[i - 1] == t[j - 1]:
dp[i][j] = min(dp[i][j], dp[i - 1][j - 1])
ch = ord(t[j - 1]) - ord('a')
if ps[ch][r] - ps[ch][i] > pt[ch][r] - pt[ch][j]:
dp[i][j] = min(dp[i][j], dp[i][j - 1])
dp[i][j] = min(dp[i][j], dp[i - 1][j] + 1)
print(dp[r][r])
``` | output | 1 | 95,414 | 0 | 190,829 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings s and t, each of length n and consisting of lowercase Latin alphabets. You want to make s equal to t.
You can perform the following operation on s any number of times to achieve it —
* Choose any substring of s and rotate it clockwise once, that is, if the selected substring is s[l,l+1...r], then it becomes s[r,l,l + 1 ... r - 1]. All the remaining characters of s stay in their position.
For example, on rotating the substring [2,4] , string "abcde" becomes "adbce".
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Find the minimum number of operations required to convert s to t, or determine that it's impossible.
Input
The first line of the input contains a single integer t (1≤ t ≤ 2000) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (1≤ n ≤ 2000) — the length of the strings.
The second and the third lines contain strings s and t respectively.
The sum of n over all the test cases does not exceed 2000.
Output
For each test case, output the minimum number of operations to convert s to t. If it is not possible to convert s to t, output -1 instead.
Example
Input
6
1
a
a
2
ab
ba
3
abc
cab
3
abc
cba
4
abab
baba
4
abcc
aabc
Output
0
1
1
2
1
-1
Note
For the 1-st test case, since s and t are equal, you don't need to apply any operation.
For the 2-nd test case, you only need to apply one operation on the entire string ab to convert it to ba.
For the 3-rd test case, you only need to apply one operation on the entire string abc to convert it to cab.
For the 4-th test case, you need to apply the operation twice: first on the entire string abc to convert it to cab and then on the substring of length 2 beginning at the second character to convert it to cba.
For the 5-th test case, you only need to apply one operation on the entire string abab to convert it to baba.
For the 6-th test case, it is not possible to convert string s to t. | instruction | 0 | 95,415 | 0 | 190,830 |
Tags: dp, strings
Correct Solution:
```
INF = float('inf')
def solve():
N = int(input())
A = input().strip()
B = input().strip()
Acount = [[0] * 26 for _ in range(N + 1)]
Bcount = [[0] * 26 for _ in range(N + 1)]
for i in range(N - 1, -1, -1):
Acount[i][ord(A[i]) - ord('a')] += 1
Bcount[i][ord(B[i]) - ord('a')] += 1
for j in range(26):
Acount[i][j] += Acount[i + 1][j]
Bcount[i][j] += Bcount[i + 1][j]
for i in range(26):
if Acount[0][i] != Bcount[0][i]:
return -1
dp = [[INF] * (N + 1) for _ in range(N + 1)]
for j in range(N + 1):
dp[0][j] = 0
for i in range(1, N + 1):
s = ord(A[i - 1]) - ord('a')
for j in range(i, N + 1):
dp[i][j] = min(dp[i][j], dp[i - 1][j] + 1)
t = ord(B[j - 1]) - ord('a')
if Acount[i][t] > Bcount[j][t]:
dp[i][j] = min(dp[i][j], dp[i][j - 1])
if s == t:
dp[i][j] = min(dp[i][j], dp[i - 1][j - 1])
# for row in dp:
# print(row)
return dp[N][N]
if __name__ == '__main__':
T = int(input())
for _ in range(T):
print(solve())
``` | output | 1 | 95,415 | 0 | 190,831 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two strings s and t, each of length n and consisting of lowercase Latin alphabets. You want to make s equal to t.
You can perform the following operation on s any number of times to achieve it —
* Choose any substring of s and rotate it clockwise once, that is, if the selected substring is s[l,l+1...r], then it becomes s[r,l,l + 1 ... r - 1]. All the remaining characters of s stay in their position.
For example, on rotating the substring [2,4] , string "abcde" becomes "adbce".
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Find the minimum number of operations required to convert s to t, or determine that it's impossible.
Input
The first line of the input contains a single integer t (1≤ t ≤ 2000) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (1≤ n ≤ 2000) — the length of the strings.
The second and the third lines contain strings s and t respectively.
The sum of n over all the test cases does not exceed 2000.
Output
For each test case, output the minimum number of operations to convert s to t. If it is not possible to convert s to t, output -1 instead.
Example
Input
6
1
a
a
2
ab
ba
3
abc
cab
3
abc
cba
4
abab
baba
4
abcc
aabc
Output
0
1
1
2
1
-1
Note
For the 1-st test case, since s and t are equal, you don't need to apply any operation.
For the 2-nd test case, you only need to apply one operation on the entire string ab to convert it to ba.
For the 3-rd test case, you only need to apply one operation on the entire string abc to convert it to cab.
For the 4-th test case, you need to apply the operation twice: first on the entire string abc to convert it to cab and then on the substring of length 2 beginning at the second character to convert it to cba.
For the 5-th test case, you only need to apply one operation on the entire string abab to convert it to baba.
For the 6-th test case, it is not possible to convert string s to t.
Submitted Solution:
```
def rotated_compare(a, b):
d1, d2 = {}, {}
# getting all characters in a string and setting the count to number of occurrences
count = 1
for i in a:
if i not in d1.keys():
d1[i] = count
else:
d1[i] = count + 1
count = 1
for i in b:
if i not in d2.keys():
d2[i] = count
else:
d2[i] = count + 1
# comparing for different characters in a and b
lst_element = d1.keys()
flag = 0
for j in b:
if (j not in lst_element) or (j in lst_element and d1[j] != d2[j]):
flag = 1
break
if flag == 0:
if a == b:
return 0
len_a = len(a) - 1
for i in range(len(a)):
a = a[0:i] + a[len_a] + a[i:len_a]
if a == b:
return i+1
else:
return -1
def main():
num_of_tests = int(input())
lst_ans = []
for i in range(num_of_tests):
len = int(input())
str1 = input()
str2 = input()
lst_ans.append(rotated_compare(str1, str2))
for each in lst_ans:
print(each)
if __name__ == '__main__':
main()
``` | instruction | 0 | 95,416 | 0 | 190,832 |
No | output | 1 | 95,416 | 0 | 190,833 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two strings s and t, each of length n and consisting of lowercase Latin alphabets. You want to make s equal to t.
You can perform the following operation on s any number of times to achieve it —
* Choose any substring of s and rotate it clockwise once, that is, if the selected substring is s[l,l+1...r], then it becomes s[r,l,l + 1 ... r - 1]. All the remaining characters of s stay in their position.
For example, on rotating the substring [2,4] , string "abcde" becomes "adbce".
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Find the minimum number of operations required to convert s to t, or determine that it's impossible.
Input
The first line of the input contains a single integer t (1≤ t ≤ 2000) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (1≤ n ≤ 2000) — the length of the strings.
The second and the third lines contain strings s and t respectively.
The sum of n over all the test cases does not exceed 2000.
Output
For each test case, output the minimum number of operations to convert s to t. If it is not possible to convert s to t, output -1 instead.
Example
Input
6
1
a
a
2
ab
ba
3
abc
cab
3
abc
cba
4
abab
baba
4
abcc
aabc
Output
0
1
1
2
1
-1
Note
For the 1-st test case, since s and t are equal, you don't need to apply any operation.
For the 2-nd test case, you only need to apply one operation on the entire string ab to convert it to ba.
For the 3-rd test case, you only need to apply one operation on the entire string abc to convert it to cab.
For the 4-th test case, you need to apply the operation twice: first on the entire string abc to convert it to cab and then on the substring of length 2 beginning at the second character to convert it to cba.
For the 5-th test case, you only need to apply one operation on the entire string abab to convert it to baba.
For the 6-th test case, it is not possible to convert string s to t.
Submitted Solution:
```
def rotiation(a,b):
if (a=="abc" and b=="bca") or (a=="abb" and b=="bba"):
return 2
if len(a) != len(b):
return -1
d = list(a)
start=0
res=0
for word in a:
i=d.index(word)
if d==list(b):
break
x=b.find(word)
if x==-1 or b.count(word) != a.count(word):
return -1
if x==i:
continue
res +=1
start2,start=x,i
i +=1
x +=1
if (x>=len(d) or i>=len(d)):
d[start:i] = ""
# d[x - i:x + i - 1] = b[start2:x+1]
d[x :x + i - 1] = b[start2:x+1]
continue
while d[i]==b[x]:
i += 1
x += 1
if (x >= len(d) or i >= len(d)):
break
d[start:i] = ""
for tt in range(start2,x):
d.insert(tt,b[tt])
return res
n=int(input())
while n>0:
size=input()
a=input()
b=input()
res=rotiation(a,b)
print(res)
n -=1
``` | instruction | 0 | 95,417 | 0 | 190,834 |
No | output | 1 | 95,417 | 0 | 190,835 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two strings s and t, each of length n and consisting of lowercase Latin alphabets. You want to make s equal to t.
You can perform the following operation on s any number of times to achieve it —
* Choose any substring of s and rotate it clockwise once, that is, if the selected substring is s[l,l+1...r], then it becomes s[r,l,l + 1 ... r - 1]. All the remaining characters of s stay in their position.
For example, on rotating the substring [2,4] , string "abcde" becomes "adbce".
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Find the minimum number of operations required to convert s to t, or determine that it's impossible.
Input
The first line of the input contains a single integer t (1≤ t ≤ 2000) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (1≤ n ≤ 2000) — the length of the strings.
The second and the third lines contain strings s and t respectively.
The sum of n over all the test cases does not exceed 2000.
Output
For each test case, output the minimum number of operations to convert s to t. If it is not possible to convert s to t, output -1 instead.
Example
Input
6
1
a
a
2
ab
ba
3
abc
cab
3
abc
cba
4
abab
baba
4
abcc
aabc
Output
0
1
1
2
1
-1
Note
For the 1-st test case, since s and t are equal, you don't need to apply any operation.
For the 2-nd test case, you only need to apply one operation on the entire string ab to convert it to ba.
For the 3-rd test case, you only need to apply one operation on the entire string abc to convert it to cab.
For the 4-th test case, you need to apply the operation twice: first on the entire string abc to convert it to cab and then on the substring of length 2 beginning at the second character to convert it to cba.
For the 5-th test case, you only need to apply one operation on the entire string abab to convert it to baba.
For the 6-th test case, it is not possible to convert string s to t.
Submitted Solution:
```
def rotatestr(string, d):
n = len(string)
return string[n-d:] + string[0: n - d]
def rotating_substring(str1, str2, idx, count, memo):
n = len(str1)
if (idx, count) in memo:
return memo[(idx, count)]
if len(str2) == 0 or idx == n:
memo[(idx, count)] = count
return count
rotated = rotatestr(str2, 1)
unrotated = -1
withrotation = -1
if str1[idx] == rotated[0]:
withrotation = rotating_substring(str1, rotated, idx + 1, count + 1, memo)
if str1[idx] == str2[idx]:
unrotated = rotating_substring(str1, str2, idx + 1, count, memo)
result = -1
if unrotated == -1:
result = withrotation
elif withrotation == -1:
result = unrotated
else:
result = min(unrotated, withrotation)
memo[(idx, count)] = result
return result
def string_rotate():
t = int(input())
for i in range(t):
n = int(input())
str1 = input()
str2 = input()
memo = {}
ret1 = rotating_substring(str1, str2, 0, 0, memo)
memo = {}
ret2 = rotating_substring(str2, str1, 0, 0, memo)
if ret1 == -1:
print(ret2)
elif ret2 == -1:
print(ret1)
else:
result = min(ret1, ret2)
print(result)
string_rotate()
``` | instruction | 0 | 95,418 | 0 | 190,836 |
No | output | 1 | 95,418 | 0 | 190,837 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two strings s and t, each of length n and consisting of lowercase Latin alphabets. You want to make s equal to t.
You can perform the following operation on s any number of times to achieve it —
* Choose any substring of s and rotate it clockwise once, that is, if the selected substring is s[l,l+1...r], then it becomes s[r,l,l + 1 ... r - 1]. All the remaining characters of s stay in their position.
For example, on rotating the substring [2,4] , string "abcde" becomes "adbce".
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Find the minimum number of operations required to convert s to t, or determine that it's impossible.
Input
The first line of the input contains a single integer t (1≤ t ≤ 2000) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (1≤ n ≤ 2000) — the length of the strings.
The second and the third lines contain strings s and t respectively.
The sum of n over all the test cases does not exceed 2000.
Output
For each test case, output the minimum number of operations to convert s to t. If it is not possible to convert s to t, output -1 instead.
Example
Input
6
1
a
a
2
ab
ba
3
abc
cab
3
abc
cba
4
abab
baba
4
abcc
aabc
Output
0
1
1
2
1
-1
Note
For the 1-st test case, since s and t are equal, you don't need to apply any operation.
For the 2-nd test case, you only need to apply one operation on the entire string ab to convert it to ba.
For the 3-rd test case, you only need to apply one operation on the entire string abc to convert it to cab.
For the 4-th test case, you need to apply the operation twice: first on the entire string abc to convert it to cab and then on the substring of length 2 beginning at the second character to convert it to cba.
For the 5-th test case, you only need to apply one operation on the entire string abab to convert it to baba.
For the 6-th test case, it is not possible to convert string s to t.
Submitted Solution:
```
testcases=int(input())
for i in range(0,testcases):
length=int(input())
s=input().strip()
t=input().strip()
if(s==t):
print(0)
elif(s!=t and length>1):
for j in range(0,length):
s=s[length-1]+s[0:length-1]
if(s==t):
print(j+1)
else:
print(-1)
break
else:
print(-1)
``` | instruction | 0 | 95,419 | 0 | 190,838 |
No | output | 1 | 95,419 | 0 | 190,839 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each).
You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains two integers n and k (2 ≤ k ≤ n ≤ 3 ⋅ 10^5, k is even) — the length of the string and the parameter for a balanced bitstring.
The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible.
Example
Input
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00
Output
YES
YES
NO
YES
YES
NO
NO
YES
NO
Note
For the first test case, the string is already a 4-balanced bitstring.
For the second test case, the string can be transformed into 101.
For the fourth test case, the string can be transformed into 0110.
For the fifth test case, the string can be transformed into 1100110. | instruction | 0 | 95,437 | 0 | 190,874 |
Tags: implementation, strings
Correct Solution:
```
gans = []
for _ in range(int(input())):
n, k = map(int, input().split())
u = list(input())
if u == ['?'] * n:
gans.append('YES')
continue
cnt1 = cnt0 = 0
for j in range(k):
ok1 = False
ok0 = False
for i in range(j, n, k):
if u[i] == '0':
ok0 = True
elif u[i] == '1':
ok1 = True
if ok1 and ok0:
gans.append('NO')
break
if ok1:
cnt1 += 1
elif ok0:
cnt0 += 1
else:
if abs(cnt1 - cnt0) <= k - cnt1 - cnt0:
gans.append('YES')
else:
gans.append('NO')
print('\n'.join(gans))
``` | output | 1 | 95,437 | 0 | 190,875 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each).
You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains two integers n and k (2 ≤ k ≤ n ≤ 3 ⋅ 10^5, k is even) — the length of the string and the parameter for a balanced bitstring.
The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible.
Example
Input
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00
Output
YES
YES
NO
YES
YES
NO
NO
YES
NO
Note
For the first test case, the string is already a 4-balanced bitstring.
For the second test case, the string can be transformed into 101.
For the fourth test case, the string can be transformed into 0110.
For the fifth test case, the string can be transformed into 1100110. | instruction | 0 | 95,438 | 0 | 190,876 |
Tags: implementation, strings
Correct Solution:
```
# cook your dish here
def checker(A,k):
tot=0
o,z=0,0
for i in range(k):
# tot+=A[i]
if A[i]==1:
o+=1
elif A[i]==-1:
z+=1
# if tot!=0:
# return False
if z>k//2 or o>k//2:
return False
for j in range(k,len(A)):
if A[j-k]==1:
o-=1
elif A[j-k]==-1:
z-=1
if A[j]==1:
o+=1
elif A[j]==-1:
z+=1
if z>k//2 or o>k//2:
return False
# tot-=A[j-k]
# tot+=A[j]
# if tot!=0:
# return False
return True
def func(A,k):
if k==len(A):
o,z=0,0
for i in A:
if i=='0':
z+=1
elif i=='1':
o+=1
if o>k//2 or z>k//2:
return 'NO'
return 'YES'
res=[0]*len(A)
one,zero,ques=[],[],[]
for i in range(k):
new=set()
ind=[]
for j in range(i,len(A),k):
new.add(A[j])
ind.append(j)
if '0' in new and '1' in new:
return "NO"
elif '0' in new:
zero.extend(ind)
elif '1' in new:
one.extend(ind)
else:
ques.extend(ind)
# print(one, zero, ques)
for i in one:
res[i]=1
for i in zero:
res[i]=-1
# res2=res.copy()
for i in ques:
res[i]=0
# res2[i]=0
# print(res, res2)
# print(res,res2)
if checker(res,k):
return "YES"
return "NO"
t=int(input())
for i in range(t):
# n=int(input())
n,k=list(map(int, input().split()))
A=input()
# for i in A[::-1]:
# print(i,end=' ')
print(func(A,k))
``` | output | 1 | 95,438 | 0 | 190,877 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each).
You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains two integers n and k (2 ≤ k ≤ n ≤ 3 ⋅ 10^5, k is even) — the length of the string and the parameter for a balanced bitstring.
The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible.
Example
Input
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00
Output
YES
YES
NO
YES
YES
NO
NO
YES
NO
Note
For the first test case, the string is already a 4-balanced bitstring.
For the second test case, the string can be transformed into 101.
For the fourth test case, the string can be transformed into 0110.
For the fifth test case, the string can be transformed into 1100110. | instruction | 0 | 95,439 | 0 | 190,878 |
Tags: implementation, strings
Correct Solution:
```
for _ in range(int(input())):
n,k = map(int,input().split())
s = list(str(input()))
tt = 0
c = 0
a = 0
aa = 0
bb = 0
for i in range(n):
if i+k<n and s[i+k] == "?":
if s[i]!="?":
s[i+k] = s[i]
if i-k>=0 and s[i-k] == "?":
s[i-k] = s[i]
if s[i] == "?":
if i+k<n and s[i+k]!="?":
s[i] = s[i+k]
elif i-k>=0 and s[i-k] != "?":
s[i] = s[i-k]
for i in range(n):
if s[i] == "0":
c+=1
if i+k<n and s[i+k] == "1":
tt = 1
break
if c+a == k and c!=a:
tt = 1
break
if c+a == k and c == a:
c = 0
a = 0
elif s[i] == "1":
bb+=1
a+=1
if i+k<n and s[i+k] == "0":
tt = 1
break
if c+a == k and c!=a:
tt = 1
break
if i>=k-1:
if c>k//2 or a>k//2:
tt = 1
break
else:
if s[aa] == "0":
c-=1
elif s[aa] == "1":
a-=1
aa+=1
if tt == 1:
print("NO")
else:
print("YES")
``` | output | 1 | 95,439 | 0 | 190,879 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each).
You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains two integers n and k (2 ≤ k ≤ n ≤ 3 ⋅ 10^5, k is even) — the length of the string and the parameter for a balanced bitstring.
The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible.
Example
Input
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00
Output
YES
YES
NO
YES
YES
NO
NO
YES
NO
Note
For the first test case, the string is already a 4-balanced bitstring.
For the second test case, the string can be transformed into 101.
For the fourth test case, the string can be transformed into 0110.
For the fifth test case, the string can be transformed into 1100110. | instruction | 0 | 95,440 | 0 | 190,880 |
Tags: implementation, strings
Correct Solution:
```
#from math import *
from bisect import *
from collections import *
from decimal import *
def inp():
return int(input())
def st():
return input().rstrip('\n')
def lis():
return list(map(int,input().split()))
def ma():
return map(int,input().split())
t=inp()
while(t):
t-=1
n,k=ma()
s=st()
s=list(s)
fl=0
for i in range(k,n):
if(s[i]!='?'):
if(s[i%k]=='?'):
s[i%k]=s[i]
elif(s[i%k]!=s[i]):
fl=1
break
o,z=0,0
for i in range(k):
if(s[i]=='1'):
o+=1
elif(s[i]=='0'):
z+=1
if(o> k//2 or z > k//2):
fl=1
s='YES'
if(fl):
s='NO'
print(s)
``` | output | 1 | 95,440 | 0 | 190,881 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each).
You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains two integers n and k (2 ≤ k ≤ n ≤ 3 ⋅ 10^5, k is even) — the length of the string and the parameter for a balanced bitstring.
The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible.
Example
Input
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00
Output
YES
YES
NO
YES
YES
NO
NO
YES
NO
Note
For the first test case, the string is already a 4-balanced bitstring.
For the second test case, the string can be transformed into 101.
For the fourth test case, the string can be transformed into 0110.
For the fifth test case, the string can be transformed into 1100110. | instruction | 0 | 95,441 | 0 | 190,882 |
Tags: implementation, strings
Correct Solution:
```
'''
Auther: ghoshashis545 Ashis Ghosh
College: jalpaiguri Govt Enggineering College
'''
from os import path
import sys
from heapq import heappush,heappop
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input().rstrip()
def mi():return map(int,input().split())
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
mod=1000000007
# mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]
def bo(i):
return ord(i)-ord('a')
file = 1
def solve():
n,k = mi()
s = list(si())
for i in range(n):
if s[i] != '?' and s[i%k] == '?':
s[i%k] = s[i]
for i in range(n):
if s[i] != '?' and s[i%k] != '?' and s[i] != s[i%k]:
print('NO')
return
k1 = k//2
cnt0,cnt1 = 0 ,0
for i in range(k):
if s[i]=='1':
cnt1+=1
if s[i]=='0':
cnt0+=1
if cnt1>k1 or cnt0>k1:
print('NO')
return
print('YES')
if __name__ =="__main__":
if(file):
if path.exists('input.txt'):
sys.stdin=open('input.txt', 'r')
sys.stdout=open('output.txt','w')
else:
input=sys.stdin.readline
for _ in range(ii()):
solve()
``` | output | 1 | 95,441 | 0 | 190,883 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each).
You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains two integers n and k (2 ≤ k ≤ n ≤ 3 ⋅ 10^5, k is even) — the length of the string and the parameter for a balanced bitstring.
The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible.
Example
Input
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00
Output
YES
YES
NO
YES
YES
NO
NO
YES
NO
Note
For the first test case, the string is already a 4-balanced bitstring.
For the second test case, the string can be transformed into 101.
For the fourth test case, the string can be transformed into 0110.
For the fifth test case, the string can be transformed into 1100110. | instruction | 0 | 95,442 | 0 | 190,884 |
Tags: implementation, strings
Correct Solution:
```
"""
Satwik_Tiwari ;) .
6th Sept , 2020 - Sunday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter # Counter(list) return a dict with {key: count}
from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
#If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
#If the element is already present in the list,
# the right most position where element has to be inserted is returned
#==============================================================================================
#fast I/O region
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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
#===============================================================================================
#some shortcuts
mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n") #as stdout.write always print sring.
def testcase(t):
for pp in range(t):
solve(pp)
def printlist(a) :
for p in range(0,len(a)):
out(str(a[p]) + ' ')
def google(p):
print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
res = 1 # Initialize result
x = x % p # Update x if it is more , than or equal to p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) : # If y is odd, multiply, x with result
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
#===============================================================================================
# code here ;))
def solve(case):
n,k = sep()
s = list(inp())
f = True
for kk in range(k):
arr= []
if(not f):
break
for i in range(kk,n,k):
arr.append(s[i])
# print(arr)
if(arr.count('?') == len(arr)):
continue
else:
if(arr.count('0')>0 and arr.count('1')>0):
f = False
break
else:
if(arr.count('0')>0):
chng = '0'
else:
chng = '1'
for i in range(kk,n,k):
s[i] = chng
# print(s)
if(f):
sum = 0
cnt = 0
for i in range(k):
if(s[i] == '?'):
cnt+=1
else:
sum+=int(s[i])
# print(sum,cnt)
if(sum>(k//2) or (sum+cnt<(k//2))):
print('NO')
else:
print('YES')
else:
print('NO')
# testcase(1)
testcase(int(inp()))
``` | output | 1 | 95,442 | 0 | 190,885 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each).
You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains two integers n and k (2 ≤ k ≤ n ≤ 3 ⋅ 10^5, k is even) — the length of the string and the parameter for a balanced bitstring.
The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible.
Example
Input
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00
Output
YES
YES
NO
YES
YES
NO
NO
YES
NO
Note
For the first test case, the string is already a 4-balanced bitstring.
For the second test case, the string can be transformed into 101.
For the fourth test case, the string can be transformed into 0110.
For the fifth test case, the string can be transformed into 1100110. | instruction | 0 | 95,443 | 0 | 190,886 |
Tags: implementation, strings
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
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 print_list(l):
print(' '.join(map(str,l)))
# import sys
# sys.setrecursionlimit(5010)
# import heapq as hq
# from collections import deque as dq
# from math import ceil,floor,sqrt,pow
# import bisect as bs
from collections import Counter
from collections import defaultdict as dc
for _ in range(N()):
n,k = RL()
s = input()
dic = dc(set)
for i in range(n):
dic[i%k].add(s[i])
flag = True
one,zero = 0,0
for i in range(k):
if '1' in dic[i] and '0' in dic[i]:
flag = False
break
elif '1' in dic[i]:
dic[i] = '1'
one+=1
elif '0' in dic[i]:
dic[i] = '0'
zero+=1
if not flag:
print('NO')
else:
if one>(k>>1) or zero>(k>>1):
print('NO')
else:
print('YES')
``` | output | 1 | 95,443 | 0 | 190,887 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each).
You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains two integers n and k (2 ≤ k ≤ n ≤ 3 ⋅ 10^5, k is even) — the length of the string and the parameter for a balanced bitstring.
The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible.
Example
Input
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00
Output
YES
YES
NO
YES
YES
NO
NO
YES
NO
Note
For the first test case, the string is already a 4-balanced bitstring.
For the second test case, the string can be transformed into 101.
For the fourth test case, the string can be transformed into 0110.
For the fifth test case, the string can be transformed into 1100110. | instruction | 0 | 95,444 | 0 | 190,888 |
Tags: implementation, strings
Correct Solution:
```
def cktrue(n,k,s1):
G={'1':0,'0':0,'?':0}
for j in range(k):
i=s1[j]
G[i]=G[i]+1
if (G['0']>k//2 or G['1']>k//2):
return 0
for i in range(k,n):
G[s1[i-k]]=G[s1[i-k]]-1
G[s1[i]]=G[s1[i]]+1
if (G['0']>k//2 or G['1']>k//2):
return 0
return 1
def fna(n,k,s):
flag=0
s1=[]
nz,no,nq=0,0,0
for j in range(k):
i=s[j]
s1.append(i)
if (i=='1'):
no=no+1
elif(i=='0'):
nz=nz+1
else:
nq=nq+1
if (no>k//2 or nz>k//2):
return 0
for i in range(k,n):
if (s[i]=='?'):
s1.append(s1[i-k])
elif(s1[i-k]=='?'):
s1[i-k]=s[i]
s1.append(s[i])
else:
if (s[i]!=s1[i-k]):
return 0
s1.append(s1[i-k])
return cktrue(n,k,s1)
T=int(input())
for _ in range(T):
n,k=map(int,input().split())
s=list(input())
flag=(fna(n,k,s))
if(flag==0):
print("NO")
else:
print("YES")
``` | output | 1 | 95,444 | 0 | 190,889 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each).
You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains two integers n and k (2 ≤ k ≤ n ≤ 3 ⋅ 10^5, k is even) — the length of the string and the parameter for a balanced bitstring.
The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible.
Example
Input
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00
Output
YES
YES
NO
YES
YES
NO
NO
YES
NO
Note
For the first test case, the string is already a 4-balanced bitstring.
For the second test case, the string can be transformed into 101.
For the fourth test case, the string can be transformed into 0110.
For the fifth test case, the string can be transformed into 1100110.
Submitted Solution:
```
for t in range(int(input())):
n,m=map(int,input().split())
a=input()
a='0'+a
flag=0
visit=["?" for i in range(m)]
for i in range(1,n+1):
if(visit[i%m]=='?'):
visit[i%m]=a[i]
elif(visit[i%m]=='0'):
if(a[i]=='1'):
flag=-1
break
elif(visit[i%m]=='1'):
if(a[i]=='0'):
flag=-1
break
add,count=0,0
if(flag==-1):
print("NO")
continue
for i in range(m):
if(visit[i]=='1'):
add+=1
elif(visit[i]=="0"):
count+=1
if(add<=m//2 and count<=m//2):
print("YES")
else:
print("NO")
``` | instruction | 0 | 95,445 | 0 | 190,890 |
Yes | output | 1 | 95,445 | 0 | 190,891 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each).
You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains two integers n and k (2 ≤ k ≤ n ≤ 3 ⋅ 10^5, k is even) — the length of the string and the parameter for a balanced bitstring.
The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible.
Example
Input
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00
Output
YES
YES
NO
YES
YES
NO
NO
YES
NO
Note
For the first test case, the string is already a 4-balanced bitstring.
For the second test case, the string can be transformed into 101.
For the fourth test case, the string can be transformed into 0110.
For the fifth test case, the string can be transformed into 1100110.
Submitted Solution:
```
import sys
import math
def II():
return int(sys.stdin.readline())
def LI():
return list(map(int, sys.stdin.readline().split()))
def MI():
return map(int, sys.stdin.readline().split())
def SI():
return sys.stdin.readline().strip()
t = II()
for q in range(t):
n,k = MI()
s = list(SI())
boo = True
su = 0
for i in range(n):
if i-k>=0 and s[i]!=s[i-k]:
if s[i] == "?":
s[i] = s[i-k]
elif s[i-k]!="?":
boo = False
break
if i+k<n and s[i]!=s[i+k]:
if s[i+k] == "?":
s[i+k] = s[i]
elif s[i]!="?":
boo = False
break
o = s[:k].count("1")
z = s[:k].count("0")
if k//2-o<0 or k//2-z<0:
boo = False
for i in range(k,n):
if boo == False:
break
if s[i-k] == "1":
o-=1
elif s[i-k] == "0":
z-=1
if s[i] == "1":
o+=1
elif s[i] == "0":
z+=1
if k//2-o<0 or k//2-z<0:
boo = False
print("YES" if boo else "NO")
#7 4
#1?0??1?
``` | instruction | 0 | 95,446 | 0 | 190,892 |
Yes | output | 1 | 95,446 | 0 | 190,893 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each).
You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains two integers n and k (2 ≤ k ≤ n ≤ 3 ⋅ 10^5, k is even) — the length of the string and the parameter for a balanced bitstring.
The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible.
Example
Input
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00
Output
YES
YES
NO
YES
YES
NO
NO
YES
NO
Note
For the first test case, the string is already a 4-balanced bitstring.
For the second test case, the string can be transformed into 101.
For the fourth test case, the string can be transformed into 0110.
For the fifth test case, the string can be transformed into 1100110.
Submitted Solution:
```
# -*- coding: utf-8 -*-
# import bisect
# import heapq
# import math
# import random
# from collections import Counter, defaultdict, deque
# from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
# from fractions import Fraction
# from functools import lru_cache, reduce
# from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
# from operator import add, mul, sub, itemgetter, attrgetter
import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline
INF = 2**62-1
def read_int():
return int(readline())
def read_int_n():
return list(map(int, readline().split()))
def read_float():
return float(readline())
def read_float_n():
return list(map(float, readline().split()))
def read_str():
return readline().strip()
def read_str_n():
return readline().strip().split()
def error_print(*args):
print(*args, file=sys.stderr)
def mt(f):
import time
def wrap(*args, **kwargs):
s = time.perf_counter()
ret = f(*args, **kwargs)
e = time.perf_counter()
error_print(e - s, 'sec')
return ret
return wrap
from collections import Counter, defaultdict
from itertools import product
def ref(N, K, S):
S = [c for c in S]
n = Counter(S)['?']
iq = [i for i in range(N) if S[i] == '?']
for j in product('01', repeat=n):
for k, v in zip(iq, j):
S[k] = v
ok = True
cc = Counter(S[:K])
if cc['0'] > K//2 or cc['1'] > K//2:
ok = False
for i in range(N-K):
a = S[i]
b = S[i+K]
if a != b:
ok = False
if ok:
return 'YES'
return 'NO'
# @mt
def slv(N, K, S):
sk = defaultdict(Counter)
for i in range(N):
sk[i%K][S[i]] += 1
c = Counter()
for i in range(K):
if '0' in sk[i] and '1' in sk[i]:
return 'NO'
if '0' in sk[i]:
c['0'] += 1
elif '1' in sk[i]:
c['1'] += 1
if c['0'] > K//2 or c['1'] > K//2:
return 'NO'
return 'YES'
def main():
for _ in range(read_int()):
N, K = read_int_n()
S = read_str()
print(slv(N, K, S))
# import random
# for _ in range(1000):
# N = 10
# K = random.randint(1, 3) * 2
# S = random.choices('01?', k=N)
# a = ref(N, K, S)
# b = slv(N, K, S)
# if a != b:
# print(N, K)
# print(S)
# print(a, b)
# break
if __name__ == '__main__':
main()
``` | instruction | 0 | 95,447 | 0 | 190,894 |
Yes | output | 1 | 95,447 | 0 | 190,895 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each).
You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains two integers n and k (2 ≤ k ≤ n ≤ 3 ⋅ 10^5, k is even) — the length of the string and the parameter for a balanced bitstring.
The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible.
Example
Input
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00
Output
YES
YES
NO
YES
YES
NO
NO
YES
NO
Note
For the first test case, the string is already a 4-balanced bitstring.
For the second test case, the string can be transformed into 101.
For the fourth test case, the string can be transformed into 0110.
For the fifth test case, the string can be transformed into 1100110.
Submitted Solution:
```
# @uthor : Kaleab Asfaw
from sys import stdin, stdout
# Fast IO
def input():
a = stdin.readline()
if a[-1] == "\n": a = a[:-1]
return a
def print(*argv, end="\n", sep=" "):
n = len(argv)
for i in range(n):
if i == n-1: stdout.write(str(argv[i]))
else: stdout.write(str(argv[i]) + sep)
stdout.write(end)
# Others
mod = 10**9+7
def lcm(x, y): return (x * y) / (gcd(x, y))
def comb(lst, x): return list(c(lst, x))
def fact(x, mod=mod):
ans = 1
for i in range(1, x+1): ans = (ans * i) % mod
return ans
def arr2D(n, m, default=0):
lst = []
for i in range(n): temp = [default] * m; lst.append(temp)
return lst
def sortDictV(x): return {k: v for k, v in sorted(x.items(), key = lambda item : item[1])}
def smaller(lst, x): return bisect_left(lst, x) -1
def smallerEq(lst, x): return bisect_right(lst, x) -1
def solve(n, k, lst):
val = {}
for i in range(n):
if lst[i] != "?":
if val.get(i%k) == None: val[i%k] = lst[i]
elif lst[i] != val[i%k]: return "NO"
# print(lst)
# print(val)
for i in range(n):
if val.get(i):
if lst[i] == "?":
lst[i] = val[i%k]
elif lst[i] != val[i%k]: return "aNO"
lstS = "".join(lst[:k])
q = lstS.count("?")
o = lstS.count("1")
z = lstS.count("0")
if abs(o-z) > q: return "NO"
for i in range(1, n-k):
if lst[i-1] == "?": q -= 1
elif lst[i-1] == "1": o -= 1
else: z -= 1
if lst[i+k-1] == "?": q += 1
elif lst[i+k-1] == "1": o += 1
else: z += 1
if abs(o-z) > q: return "cNO"
return "YES"
for _ in range(int(input())): # Multicase
n, k = list(map(int, input().split()))
lst = list(input())
print(solve(n, k, lst))
``` | instruction | 0 | 95,448 | 0 | 190,896 |
Yes | output | 1 | 95,448 | 0 | 190,897 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each).
You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains two integers n and k (2 ≤ k ≤ n ≤ 3 ⋅ 10^5, k is even) — the length of the string and the parameter for a balanced bitstring.
The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible.
Example
Input
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00
Output
YES
YES
NO
YES
YES
NO
NO
YES
NO
Note
For the first test case, the string is already a 4-balanced bitstring.
For the second test case, the string can be transformed into 101.
For the fourth test case, the string can be transformed into 0110.
For the fifth test case, the string can be transformed into 1100110.
Submitted Solution:
```
t=int(input())
for _ in range(t):
n,k=map(int,input().split())
s=input()
s=list(s)
s_=s[0:k]
count1=0
count0=0
countQ=0
for i in range(k):
if s[i]=='1':
count1+=1
elif s[i]=='0':
count0+=1
else:
countQ+=1
if count1<=(k//2) and count0<=(k//2):
i=0
while count1!=int(k/2):
if s_[i]=='?':
s_[i]='1'
count1+=1
i+=1
while count0!=int(k/2):
if s_[i]=='?':
s_[i]='0'
count0+=1
i+=1
else:
print("NO")
continue
f=0
for i in range(k,n):
if s[i]==s_[0]:
s_.remove(s_[0])
s_.append(s[i])
continue
elif s[i]=='?' or s_[0]=='?':
if s[i]=='?':
s[i]=s_[0]
s_.remove(s_[0])
s_.append(s[i])
else:
f=1
print("NO")
break
if f==0:
print("YES")
``` | instruction | 0 | 95,449 | 0 | 190,898 |
No | output | 1 | 95,449 | 0 | 190,899 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each).
You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains two integers n and k (2 ≤ k ≤ n ≤ 3 ⋅ 10^5, k is even) — the length of the string and the parameter for a balanced bitstring.
The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible.
Example
Input
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00
Output
YES
YES
NO
YES
YES
NO
NO
YES
NO
Note
For the first test case, the string is already a 4-balanced bitstring.
For the second test case, the string can be transformed into 101.
For the fourth test case, the string can be transformed into 0110.
For the fifth test case, the string can be transformed into 1100110.
Submitted Solution:
```
from sys import stdin
###############################################################
def iinput(): return int(stdin.readline())
def minput(): return map(int, stdin.readline().split())
def linput(): return list(map(int, stdin.readline().split()))
###############################################################
from math import ceil
t = iinput()
while t:
t -= 1
n, k = minput()
s = list(input())
ans = 'YES'
if n == k:
if s.count('1') > n//2 or s.count('0') > n//2:
ans = 'NO'
elif all(e == '?' for e in s):
ans = 'YES'
else:
zeros = s[:k].count('0')
ones = s[:k].count('1')
for i in range(1, n-k+1):
if zeros > k//2 or ones > k//2:
ans = 'NO'
break
if s[i-1] == '0': zeros -= 1
elif s[i-1] == '1': ones -= 1
if s[i+k-1] == '0': zeros += 1
elif s[i+k-1] == '1': ones += 1
if zeros > k // 2 or ones > k // 2:
ans = 'NO'
if ans == 'YES':
# if s.count('?') < ceil(n/2):
for i in range(k):
if s[i] != '?':
for j in range(i+k, n, k):
if s[j] == '?':
s[j] = s[i]
elif s[j] != s[i]:
ans = 'NO'
break
for j in range(i-k, -1, -k):
if s[j] == '?':
s[j] = s[i]
elif s[j] != s[i]:
ans = 'NO'
break
if ans == 'NO':
break
# print(s)
zeros = s[:k].count('0')
ones = s[:k].count('1')
for i in range(1, n - k + 1):
if zeros > k // 2 or ones > k // 2:
ans = 'NO'
break
if s[i - 1] == '0':
zeros -= 1
elif s[i - 1] == '1':
ones -= 1
if s[i + k - 1] == '0':
zeros += 1
elif s[i + k - 1] == '1':
ones += 1
if zeros > k // 2 or ones > k // 2:
ans = 'NO'
print(ans)
``` | instruction | 0 | 95,450 | 0 | 190,900 |
No | output | 1 | 95,450 | 0 | 190,901 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each).
You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains two integers n and k (2 ≤ k ≤ n ≤ 3 ⋅ 10^5, k is even) — the length of the string and the parameter for a balanced bitstring.
The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible.
Example
Input
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00
Output
YES
YES
NO
YES
YES
NO
NO
YES
NO
Note
For the first test case, the string is already a 4-balanced bitstring.
For the second test case, the string can be transformed into 101.
For the fourth test case, the string can be transformed into 0110.
For the fifth test case, the string can be transformed into 1100110.
Submitted Solution:
```
for _ in range(int(input())):
n, k = map(int, input().split())
s = input()
flag, zero, one = True, 0, 0
for i in range(k):
letter = None
for j in range(i,n,k):
if s[i] != '?':
if letter and s[j] != letter:
flag = False
break
letter = s[j]
if letter:
zero += 1 if letter == '0' else 0
one += 1 if letter == '1' else 0
if max(zero, one) > k // 2:
flag = False
print("YES" if flag else "NO")
``` | instruction | 0 | 95,451 | 0 | 190,902 |
No | output | 1 | 95,451 | 0 | 190,903 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each).
You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows.
The first line of each test case contains two integers n and k (2 ≤ k ≤ n ≤ 3 ⋅ 10^5, k is even) — the length of the string and the parameter for a balanced bitstring.
The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?.
It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible.
Example
Input
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00
Output
YES
YES
NO
YES
YES
NO
NO
YES
NO
Note
For the first test case, the string is already a 4-balanced bitstring.
For the second test case, the string can be transformed into 101.
For the fourth test case, the string can be transformed into 0110.
For the fifth test case, the string can be transformed into 1100110.
Submitted Solution:
```
from sys import stdin
from collections import Counter
N = int(stdin.readline())
for case in range(N):
length, k = map(int, stdin.readline().split()) # 1 count and 0 count equal k/2
idx = 0
build = ""
string = str(stdin.readline())
flag = True
count = Counter(string)
onecount = count.get("1", 0)
zerocount = count.get("0", 0)
for i in range(k):
if string[i] == "?":
if i+k <= length-1:
if string[i+k] != "?":
build += string[i+k]
if string[i+k] == "1":
onecount += 1
else:
zerocount += 1
else:
if onecount >= zerocount:
build += "0"
zerocount += 1
else:
build += "1"
onecount += 1
elif onecount >= zerocount:
build += "0"
zerocount += 1
else:
build += "1"
onecount += 1
else:
build += string[i]
if onecount != k//2:
print("NO")
continue
for i in range(k, length):
if string[i] == "?":
build += build[i-k]
else:
build += string[i]
if build[i] != build[i-k]:
print("NO")
flag = False
break
if flag:
print("YES")
``` | instruction | 0 | 95,452 | 0 | 190,904 |
No | output | 1 | 95,452 | 0 | 190,905 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After getting kicked out of her reporting job for not knowing the alphabet, Bessie has decided to attend school at the Fillet and Eggs Eater Academy. She has been making good progress with her studies and now knows the first k English letters.
Each morning, Bessie travels to school along a sidewalk consisting of m + n tiles. In order to help Bessie review, Mr. Moozing has labeled each of the first m sidewalk tiles with one of the first k lowercase English letters, spelling out a string t. Mr. Moozing, impressed by Bessie's extensive knowledge of farm animals, plans to let her finish labeling the last n tiles of the sidewalk by herself.
Consider the resulting string s (|s| = m + n) consisting of letters labeled on tiles in order from home to school. For any sequence of indices p1 < p2 < ... < pq we can define subsequence of the string s as string sp1sp2... spq. Two subsequences are considered to be distinct if they differ as strings. Bessie wants to label the remaining part of the sidewalk such that the number of distinct subsequences of tiles is maximum possible. However, since Bessie hasn't even finished learning the alphabet, she needs your help!
Note that empty subsequence also counts.
Input
The first line of the input contains two integers n and k (0 ≤ n ≤ 1 000 000, 1 ≤ k ≤ 26).
The second line contains a string t (|t| = m, 1 ≤ m ≤ 1 000 000) consisting of only first k lowercase English letters.
Output
Determine the maximum number of distinct subsequences Bessie can form after labeling the last n sidewalk tiles each with one of the first k lowercase English letters. Since this number can be rather large, you should print it modulo 109 + 7.
Please note, that you are not asked to maximize the remainder modulo 109 + 7! The goal is to maximize the initial value and then print the remainder.
Examples
Input
1 3
ac
Output
8
Input
0 2
aaba
Output
10
Note
In the first sample, the optimal labeling gives 8 different subsequences: "" (the empty string), "a", "c", "b", "ac", "ab", "cb", and "acb".
<image>
In the second sample, the entire sidewalk is already labeled. The are 10 possible different subsequences: "" (the empty string), "a", "b", "aa", "ab", "ba", "aaa", "aab", "aba", and "aaba". Note that some strings, including "aa", can be obtained with multiple sequences of tiles, but are only counted once.
Submitted Solution:
```
import operator
s = list(map(int,input().split()))
n = s[0]
k = s[1]
s = input()
base = 10 ** 9 + 7
start = ord('a')
substrings = [0 for i in range(k + 1)]
heap = [[i,0] for i in range(k)]
substrings[k] = 1
def Insert(heap, size, number, comparator = operator.lt):
heap[size] = number
i = size
while True:
if i == 0 or comparator(heap[(i + 1) // 2 - 1], heap[i]):
break
else:
heap[i], heap[(i + 1) // 2 - 1] = heap[(i + 1) // 2 - 1], heap[i]
i = (i + 1) // 2 - 1
def Extract(heap, size, comparator = operator.lt):
result = heap[0]
heap[0] = heap[size - 1]
size -= 1
i = 0
while True:
if (i + 1) * 2 - 1 > size:
break
else:
if comparator(heap[i], heap[(i + 1) * 2 - 1]):
if (i + 1) * 2 > size or comparator(heap[i], heap[(i + 1) * 2]):
break
else:
heap[i], heap[(i + 1) * 2] = heap[(i + 1) * 2], heap[i]
i = (i + 1) * 2
else:
if (i + 1) * 2 > size or comparator(heap[i], heap[(i + 1) * 2]):
heap[i], heap[(i + 1) * 2 - 1] = heap[(i + 1) * 2 - 1], heap[i]
i = (i + 1) * 2 - 1
else:
if comparator(heap[(i + 1) * 2 - 1], heap[(i + 1) * 2]):
heap[i], heap[(i + 1) * 2 - 1] = heap[(i + 1) * 2 - 1], heap[i]
i = (i + 1) * 2 - 1
else:
heap[i], heap[(i + 1) * 2] = heap[(i + 1) * 2], heap[i]
i = (i + 1) * 2
return result
if n == 1000000:
for i in range(n):
i += 1
else:
for c in s:
num = ord(c) - start
new = substrings[k] - substrings[num]
substrings[num] = substrings[k]
substrings[k] += new
for i in range(k):
Insert(heap, i, [i, substrings[i]], lambda x, y: x[1] < y[1])
num_cicles = n // k
for i in range(n):
num_val = Extract(heap, k, lambda x, y: x[1] < y[1])
new = substrings[k] - num_val[1]
substrings[num_val[0]] = substrings[k]
substrings[k] += new
substrings[k] %= base
Insert(heap, k - 1, [num_val[0], substrings[num_val[0]]], lambda x, y: x[1] < y[1])
print(substrings[k] % base)
``` | instruction | 0 | 95,703 | 0 | 191,406 |
No | output | 1 | 95,703 | 0 | 191,407 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After getting kicked out of her reporting job for not knowing the alphabet, Bessie has decided to attend school at the Fillet and Eggs Eater Academy. She has been making good progress with her studies and now knows the first k English letters.
Each morning, Bessie travels to school along a sidewalk consisting of m + n tiles. In order to help Bessie review, Mr. Moozing has labeled each of the first m sidewalk tiles with one of the first k lowercase English letters, spelling out a string t. Mr. Moozing, impressed by Bessie's extensive knowledge of farm animals, plans to let her finish labeling the last n tiles of the sidewalk by herself.
Consider the resulting string s (|s| = m + n) consisting of letters labeled on tiles in order from home to school. For any sequence of indices p1 < p2 < ... < pq we can define subsequence of the string s as string sp1sp2... spq. Two subsequences are considered to be distinct if they differ as strings. Bessie wants to label the remaining part of the sidewalk such that the number of distinct subsequences of tiles is maximum possible. However, since Bessie hasn't even finished learning the alphabet, she needs your help!
Note that empty subsequence also counts.
Input
The first line of the input contains two integers n and k (0 ≤ n ≤ 1 000 000, 1 ≤ k ≤ 26).
The second line contains a string t (|t| = m, 1 ≤ m ≤ 1 000 000) consisting of only first k lowercase English letters.
Output
Determine the maximum number of distinct subsequences Bessie can form after labeling the last n sidewalk tiles each with one of the first k lowercase English letters. Since this number can be rather large, you should print it modulo 109 + 7.
Please note, that you are not asked to maximize the remainder modulo 109 + 7! The goal is to maximize the initial value and then print the remainder.
Examples
Input
1 3
ac
Output
8
Input
0 2
aaba
Output
10
Note
In the first sample, the optimal labeling gives 8 different subsequences: "" (the empty string), "a", "c", "b", "ac", "ab", "cb", and "acb".
<image>
In the second sample, the entire sidewalk is already labeled. The are 10 possible different subsequences: "" (the empty string), "a", "b", "aa", "ab", "ba", "aaa", "aab", "aba", and "aaba". Note that some strings, including "aa", can be obtained with multiple sequences of tiles, but are only counted once.
Submitted Solution:
```
s = list(map(int,input().split()))
n = s[0]
k = s[1]
s = input()
m = len(s)
start = ord('a')
substrings = [0] * (k + 1)
substrings[k] = 1
for i in range (m):
num = ord(s[i]) - start
new = substrings[k] - substrings[num]
substrings[k] = (substrings[k] + new) % (10 ^ 9 + 7)
substrings[num] = (substrings[num] + new) % (10 ^ 9 + 7)
for i in range (n):
min_in = 0
for j in range(k):
if substrings[min_in] > substrings[j]:
min_in = j
num = min_in
new = substrings[k] - substrings[num]
substrings[k] = (substrings[k] + new) % (10 ^ 9 + 7)
substrings[num] = (substrings[num] + new) % (10 ^ 9 + 7)
print(substrings[k])
``` | instruction | 0 | 95,704 | 0 | 191,408 |
No | output | 1 | 95,704 | 0 | 191,409 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After getting kicked out of her reporting job for not knowing the alphabet, Bessie has decided to attend school at the Fillet and Eggs Eater Academy. She has been making good progress with her studies and now knows the first k English letters.
Each morning, Bessie travels to school along a sidewalk consisting of m + n tiles. In order to help Bessie review, Mr. Moozing has labeled each of the first m sidewalk tiles with one of the first k lowercase English letters, spelling out a string t. Mr. Moozing, impressed by Bessie's extensive knowledge of farm animals, plans to let her finish labeling the last n tiles of the sidewalk by herself.
Consider the resulting string s (|s| = m + n) consisting of letters labeled on tiles in order from home to school. For any sequence of indices p1 < p2 < ... < pq we can define subsequence of the string s as string sp1sp2... spq. Two subsequences are considered to be distinct if they differ as strings. Bessie wants to label the remaining part of the sidewalk such that the number of distinct subsequences of tiles is maximum possible. However, since Bessie hasn't even finished learning the alphabet, she needs your help!
Note that empty subsequence also counts.
Input
The first line of the input contains two integers n and k (0 ≤ n ≤ 1 000 000, 1 ≤ k ≤ 26).
The second line contains a string t (|t| = m, 1 ≤ m ≤ 1 000 000) consisting of only first k lowercase English letters.
Output
Determine the maximum number of distinct subsequences Bessie can form after labeling the last n sidewalk tiles each with one of the first k lowercase English letters. Since this number can be rather large, you should print it modulo 109 + 7.
Please note, that you are not asked to maximize the remainder modulo 109 + 7! The goal is to maximize the initial value and then print the remainder.
Examples
Input
1 3
ac
Output
8
Input
0 2
aaba
Output
10
Note
In the first sample, the optimal labeling gives 8 different subsequences: "" (the empty string), "a", "c", "b", "ac", "ab", "cb", and "acb".
<image>
In the second sample, the entire sidewalk is already labeled. The are 10 possible different subsequences: "" (the empty string), "a", "b", "aa", "ab", "ba", "aaa", "aab", "aba", and "aaba". Note that some strings, including "aa", can be obtained with multiple sequences of tiles, but are only counted once.
Submitted Solution:
```
import operator
s = list(map(int,input().split()))
n = s[0]
k = s[1]
s = input()
base = 10 ** 9 + 7
start = ord('a')
substrings = [0 for i in range(k + 1)]
heap = [[i,0] for i in range(k)]
substrings[k] = 1
def Insert(heap, size, number, comparator = operator.lt):
heap[size] = number
i = size
while True:
if i == 0 or comparator(heap[(i + 1) // 2 - 1], heap[i]):
break
else:
heap[i], heap[(i + 1) // 2 - 1] = heap[(i + 1) // 2 - 1], heap[i]
i = (i + 1) // 2 - 1
def Extract(heap, size, comparator = operator.lt):
result = heap[0]
heap[0] = heap[size - 1]
size -= 1
i = 0
while True:
if (i + 1) * 2 - 1 > size:
break
else:
if comparator(heap[i], heap[(i + 1) * 2 - 1]):
if (i + 1) * 2 > size or comparator(heap[i], heap[(i + 1) * 2]):
break
else:
heap[i], heap[(i + 1) * 2] = heap[(i + 1) * 2], heap[i]
i = (i + 1) * 2
else:
if (i + 1) * 2 > size or comparator(heap[i], heap[(i + 1) * 2]):
heap[i], heap[(i + 1) * 2 - 1] = heap[(i + 1) * 2 - 1], heap[i]
i = (i + 1) * 2 - 1
else:
if comparator(heap[(i + 1) * 2 - 1], heap[(i + 1) * 2]):
heap[i], heap[(i + 1) * 2 - 1] = heap[(i + 1) * 2 - 1], heap[i]
i = (i + 1) * 2 - 1
else:
heap[i], heap[(i + 1) * 2] = heap[(i + 1) * 2], heap[i]
i = (i + 1) * 2
return result
for c in s:
num = ord(c) - start
new = substrings[k] - substrings[num]
substrings[num] = substrings[k]
substrings[k] += new
substrings[k] %= base
for i in range(k):
Insert(heap, i, [i, substrings[i]], lambda x, y: x[1] < y[1])
num_cicles = n // k
if n != 1000000:
for i in range(n):
num_val = Extract(heap, k, lambda x, y: x[1] < y[1])
new = substrings[k] - num_val[1]
substrings[num_val[0]] = substrings[k]
substrings[k] += new
substrings[k] %= base
Insert(heap, k - 1, [num_val[0], substrings[num_val[0]]], lambda x, y: x[1] < y[1])
print(substrings[k] % base)
``` | instruction | 0 | 95,705 | 0 | 191,410 |
No | output | 1 | 95,705 | 0 | 191,411 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times:
* A <image> BC
* B <image> AC
* C <image> AB
* AAA <image> empty string
Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source.
Input
The first line contains a string S (1 ≤ |S| ≤ 105). The second line contains a string T (1 ≤ |T| ≤ 105), each of these strings consists only of uppercase English letters 'A', 'B' and 'C'.
The third line contains the number of queries Q (1 ≤ Q ≤ 105).
The following Q lines describe queries. The i-th of these lines contains four space separated integers ai, bi, ci, di. These represent the i-th query: is it possible to create T[ci..di] from S[ai..bi] by applying the above transitions finite amount of times?
Here, U[x..y] is a substring of U that begins at index x (indexed from 1) and ends at index y. In particular, U[1..|U|] is the whole string U.
It is guaranteed that 1 ≤ a ≤ b ≤ |S| and 1 ≤ c ≤ d ≤ |T|.
Output
Print a string of Q characters, where the i-th character is '1' if the answer to the i-th query is positive, and '0' otherwise.
Example
Input
AABCCBAAB
ABCB
5
1 3 1 2
2 2 2 4
7 9 1 1
3 4 2 3
4 5 1 3
Output
10011
Note
In the first query we can achieve the result, for instance, by using transitions <image>.
The third query asks for changing AAB to A — but in this case we are not able to get rid of the character 'B'. | instruction | 0 | 95,814 | 0 | 191,628 |
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
# python3
import sys
def read_all_following_lines():
lines = sys.stdin.readlines()
return (tuple(map(int, line.split())) for line in lines)
class AbcString(object):
def __init__(self, string):
self.prefix_bc = [0]
self.a_strike = [0]
bc, strike = 0, 0
for symbol in string:
if symbol == 'A':
strike += 1
else:
strike = 0
bc += 1
self.prefix_bc.append(bc)
self.a_strike.append(strike)
def get_info(self, begin, end):
bc = self.prefix_bc[end] - self.prefix_bc[begin]
trailing_a = min(self.a_strike[end], end - begin)
return bc, trailing_a
def can_mutate(start, finish):
from_bc, from_a = start
to_bc, to_a = finish
if (from_bc & 1) != (to_bc & 1): return False
if from_bc > to_bc: return False
if from_a < to_a: return False
if from_bc == to_bc: return (from_a - to_a) % 3 == 0
if from_a == to_a: return from_bc != 0
# from_bc < to_bc
# from_a > to_a
return True
def main():
s = AbcString(input())
t = AbcString(input())
input() # skip one line
requests = read_all_following_lines()
answer = ""
for (a, b, c, d) in requests:
can = can_mutate(s.get_info(a - 1, b), t.get_info(c - 1, d))
answer += "1" if can else "0"
print(answer)
main()
``` | output | 1 | 95,814 | 0 | 191,629 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times:
* A <image> BC
* B <image> AC
* C <image> AB
* AAA <image> empty string
Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source.
Input
The first line contains a string S (1 ≤ |S| ≤ 105). The second line contains a string T (1 ≤ |T| ≤ 105), each of these strings consists only of uppercase English letters 'A', 'B' and 'C'.
The third line contains the number of queries Q (1 ≤ Q ≤ 105).
The following Q lines describe queries. The i-th of these lines contains four space separated integers ai, bi, ci, di. These represent the i-th query: is it possible to create T[ci..di] from S[ai..bi] by applying the above transitions finite amount of times?
Here, U[x..y] is a substring of U that begins at index x (indexed from 1) and ends at index y. In particular, U[1..|U|] is the whole string U.
It is guaranteed that 1 ≤ a ≤ b ≤ |S| and 1 ≤ c ≤ d ≤ |T|.
Output
Print a string of Q characters, where the i-th character is '1' if the answer to the i-th query is positive, and '0' otherwise.
Example
Input
AABCCBAAB
ABCB
5
1 3 1 2
2 2 2 4
7 9 1 1
3 4 2 3
4 5 1 3
Output
10011
Note
In the first query we can achieve the result, for instance, by using transitions <image>.
The third query asks for changing AAB to A — but in this case we are not able to get rid of the character 'B'. | instruction | 0 | 95,815 | 0 | 191,630 |
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
def main():
s, t = input(), input()
s_info, t_info = fast_counter(s), fast_counter(t)
queries = int(input())
answer = ''
for _ in range(queries):
l1, r1, l2, r2 = map(int, input().split())
l1, l2 = l1 - 1, l2 - 1
from_mask = mask(l1, r1, s_info)
to_mask = mask(l2, r2, t_info)
if can_transform(from_mask, to_mask):
answer += '1'
else:
answer += '0'
print(answer)
def can_transform(from_mask, to_mask):
if from_mask[0] > to_mask[0]:
return False
elif (to_mask[0] - from_mask[0]) % 2 != 0:
return False
elif to_mask[0] == from_mask[0]:
if to_mask[1] > from_mask[1]:
return False
return (from_mask[1] - to_mask[1]) % 3 == 0
elif from_mask[0] == 0:
return to_mask[1] < from_mask[1]
else:
return to_mask[1] <= from_mask[1]
def mask(l, r, info):
return (info[1][r] - info[1][l], min(r - l, info[0][r]))
def fast_counter(s):
a_last, b_count = [0], [0]
for c in s:
if c == 'A':
a_last.append(a_last[-1] + 1)
b_count.append(b_count[-1])
else:
a_last.append(0)
b_count.append(b_count[-1] + 1)
return (a_last, b_count)
main()
``` | output | 1 | 95,815 | 0 | 191,631 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times:
* A <image> BC
* B <image> AC
* C <image> AB
* AAA <image> empty string
Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source.
Input
The first line contains a string S (1 ≤ |S| ≤ 105). The second line contains a string T (1 ≤ |T| ≤ 105), each of these strings consists only of uppercase English letters 'A', 'B' and 'C'.
The third line contains the number of queries Q (1 ≤ Q ≤ 105).
The following Q lines describe queries. The i-th of these lines contains four space separated integers ai, bi, ci, di. These represent the i-th query: is it possible to create T[ci..di] from S[ai..bi] by applying the above transitions finite amount of times?
Here, U[x..y] is a substring of U that begins at index x (indexed from 1) and ends at index y. In particular, U[1..|U|] is the whole string U.
It is guaranteed that 1 ≤ a ≤ b ≤ |S| and 1 ≤ c ≤ d ≤ |T|.
Output
Print a string of Q characters, where the i-th character is '1' if the answer to the i-th query is positive, and '0' otherwise.
Example
Input
AABCCBAAB
ABCB
5
1 3 1 2
2 2 2 4
7 9 1 1
3 4 2 3
4 5 1 3
Output
10011
Note
In the first query we can achieve the result, for instance, by using transitions <image>.
The third query asks for changing AAB to A — but in this case we are not able to get rid of the character 'B'. | instruction | 0 | 95,816 | 0 | 191,632 |
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
def read():
s = input()
l = len(s)
r = [[0] * (l + 1), [0] * (l + 1)]
for i in range(l):
r[0][i + 1] = (r[0][i] + 1) * (s[i] == 'A')
r[1][i + 1] = r[1][i] + (s[i] != 'A')
return r
s, t = read(), read()
q = int(input())
r = ''
for i in range(q):
a, b, c, d = map(int, input().split())
sb = s[1][b] - s[1][a] + (s[0][a] == 0)
sa = s[0][b] - (s[0][a] - 1) * (sb == 0)
tb = t[1][d] - t[1][c] + (t[0][c] == 0)
ta = t[0][d] - (t[0][c] - 1) * (tb == 0)
if any([sb > tb, sa < ta, tb - sb & 1, sb == tb and (sa - ta) % 3, sa == ta and not sb and tb]):
r += '0'
else:
r += '1'
print(r)
``` | output | 1 | 95,816 | 0 | 191,633 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times:
* A <image> BC
* B <image> AC
* C <image> AB
* AAA <image> empty string
Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source.
Input
The first line contains a string S (1 ≤ |S| ≤ 105). The second line contains a string T (1 ≤ |T| ≤ 105), each of these strings consists only of uppercase English letters 'A', 'B' and 'C'.
The third line contains the number of queries Q (1 ≤ Q ≤ 105).
The following Q lines describe queries. The i-th of these lines contains four space separated integers ai, bi, ci, di. These represent the i-th query: is it possible to create T[ci..di] from S[ai..bi] by applying the above transitions finite amount of times?
Here, U[x..y] is a substring of U that begins at index x (indexed from 1) and ends at index y. In particular, U[1..|U|] is the whole string U.
It is guaranteed that 1 ≤ a ≤ b ≤ |S| and 1 ≤ c ≤ d ≤ |T|.
Output
Print a string of Q characters, where the i-th character is '1' if the answer to the i-th query is positive, and '0' otherwise.
Example
Input
AABCCBAAB
ABCB
5
1 3 1 2
2 2 2 4
7 9 1 1
3 4 2 3
4 5 1 3
Output
10011
Note
In the first query we can achieve the result, for instance, by using transitions <image>.
The third query asks for changing AAB to A — but in this case we are not able to get rid of the character 'B'. | instruction | 0 | 95,817 | 0 | 191,634 |
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
def main():
s, t = input(), input()
s_info, t_info = fast_counter(s), fast_counter(t)
queries = int(input())
answer = ''
for _ in range(queries):
l1, r1, l2, r2 = map(int, input().split())
l1, l2 = l1 - 1, l2 - 1
from_mask = (s_info[1][r1] - s_info[1][l1], min(r1 - l1, s_info[0][r1]))
to_mask = (t_info[1][r2] - t_info[1][l2], min(r2 - l2, t_info[0][r2]))
if can_transform(from_mask, to_mask):
answer += '1'
else:
answer += '0'
print(answer)
def can_transform(from_mask, to_mask):
if from_mask[0] > to_mask[0]:
return False
elif (to_mask[0] - from_mask[0]) % 2 != 0:
return False
elif to_mask[0] == from_mask[0]:
if to_mask[1] > from_mask[1]:
return False
return (from_mask[1] - to_mask[1]) % 3 == 0
elif from_mask[0] == 0:
return to_mask[1] < from_mask[1]
else:
return to_mask[1] <= from_mask[1]
def mask(l, r, info):
return (info[1][r] - info[1][l], min(r - l, info[0][r]))
def fast_counter(s):
a_last, b_count = [0], [0]
for c in s:
if c == 'A':
a_last.append(a_last[-1] + 1)
b_count.append(b_count[-1])
else:
a_last.append(0)
b_count.append(b_count[-1] + 1)
return (a_last, b_count)
main()
``` | output | 1 | 95,817 | 0 | 191,635 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times:
* A <image> BC
* B <image> AC
* C <image> AB
* AAA <image> empty string
Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source.
Input
The first line contains a string S (1 ≤ |S| ≤ 105). The second line contains a string T (1 ≤ |T| ≤ 105), each of these strings consists only of uppercase English letters 'A', 'B' and 'C'.
The third line contains the number of queries Q (1 ≤ Q ≤ 105).
The following Q lines describe queries. The i-th of these lines contains four space separated integers ai, bi, ci, di. These represent the i-th query: is it possible to create T[ci..di] from S[ai..bi] by applying the above transitions finite amount of times?
Here, U[x..y] is a substring of U that begins at index x (indexed from 1) and ends at index y. In particular, U[1..|U|] is the whole string U.
It is guaranteed that 1 ≤ a ≤ b ≤ |S| and 1 ≤ c ≤ d ≤ |T|.
Output
Print a string of Q characters, where the i-th character is '1' if the answer to the i-th query is positive, and '0' otherwise.
Example
Input
AABCCBAAB
ABCB
5
1 3 1 2
2 2 2 4
7 9 1 1
3 4 2 3
4 5 1 3
Output
10011
Note
In the first query we can achieve the result, for instance, by using transitions <image>.
The third query asks for changing AAB to A — but in this case we are not able to get rid of the character 'B'. | instruction | 0 | 95,818 | 0 | 191,636 |
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
def pref_counts(string, char):
result = [0]
for c in string:
result.append(result[-1] + (c == char))
return result
def left_counts(string, char):
result = [0]
for c in string:
result.append(result[-1] + 1 if c == char else 0)
return result
s = input().replace("C", "B")
t = input().replace("C", "B")
s_bcounts, t_bcounts = pref_counts(s, "B"), pref_counts(t, "B")
s_lcounts, t_lcounts = left_counts(s, "A"), left_counts(t, "A")
for i in range(int(input())):
a, b, c, d = list(map(int, input().split()))
s_b = s_bcounts[b] - s_bcounts[a - 1]
t_b = t_bcounts[d] - t_bcounts[c - 1]
s_a = min(s_lcounts[b], b - a + 1)
t_a = min(t_lcounts[d], d - c + 1)
answer = False
if s_b & 1 == t_b & 1:
if s_b < t_b:
answer = s_a - (s_b == 0) >= t_a
elif s_b == t_b:
answer = s_a >= t_a and (s_a - t_a) % 3 == 0
print(int(answer), end = "")
``` | output | 1 | 95,818 | 0 | 191,637 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times:
* A <image> BC
* B <image> AC
* C <image> AB
* AAA <image> empty string
Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source.
Input
The first line contains a string S (1 ≤ |S| ≤ 105). The second line contains a string T (1 ≤ |T| ≤ 105), each of these strings consists only of uppercase English letters 'A', 'B' and 'C'.
The third line contains the number of queries Q (1 ≤ Q ≤ 105).
The following Q lines describe queries. The i-th of these lines contains four space separated integers ai, bi, ci, di. These represent the i-th query: is it possible to create T[ci..di] from S[ai..bi] by applying the above transitions finite amount of times?
Here, U[x..y] is a substring of U that begins at index x (indexed from 1) and ends at index y. In particular, U[1..|U|] is the whole string U.
It is guaranteed that 1 ≤ a ≤ b ≤ |S| and 1 ≤ c ≤ d ≤ |T|.
Output
Print a string of Q characters, where the i-th character is '1' if the answer to the i-th query is positive, and '0' otherwise.
Example
Input
AABCCBAAB
ABCB
5
1 3 1 2
2 2 2 4
7 9 1 1
3 4 2 3
4 5 1 3
Output
10011
Note
In the first query we can achieve the result, for instance, by using transitions <image>.
The third query asks for changing AAB to A — but in this case we are not able to get rid of the character 'B'.
Submitted Solution:
```
def read():
s = input()
l = len(s)
r = [[0] * (l + 1), [0] * (l + 1)]
for i in range(l):
r[0][i + 1] = (r[0][i] + 1) * (s[i] == 'A')
r[1][i + 1] = r[1][i] + (s[i] != 'A')
return r
s, t = read(), read()
q = int(input())
for i in range(q):
a, b, c, d = map(int, input().split())
sb = s[1][b] - s[1][a] + (s[0][a] == 0)
sa = s[0][b] - (s[0][a] - 1) * (sb == 0)
tb = t[1][d] - t[1][c] + (t[0][c] == 0)
ta = t[0][d] - (t[0][c] - 1) * (tb == 0)
if tb == sb and sa >= ta and (sa - ta) % 3 == 0 or tb > sb and tb - sb & 1 == 0 and sa >= ta:
print(1, end='')
else:
print(0, end='')
``` | instruction | 0 | 95,819 | 0 | 191,638 |
No | output | 1 | 95,819 | 0 | 191,639 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times:
* A <image> BC
* B <image> AC
* C <image> AB
* AAA <image> empty string
Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source.
Input
The first line contains a string S (1 ≤ |S| ≤ 105). The second line contains a string T (1 ≤ |T| ≤ 105), each of these strings consists only of uppercase English letters 'A', 'B' and 'C'.
The third line contains the number of queries Q (1 ≤ Q ≤ 105).
The following Q lines describe queries. The i-th of these lines contains four space separated integers ai, bi, ci, di. These represent the i-th query: is it possible to create T[ci..di] from S[ai..bi] by applying the above transitions finite amount of times?
Here, U[x..y] is a substring of U that begins at index x (indexed from 1) and ends at index y. In particular, U[1..|U|] is the whole string U.
It is guaranteed that 1 ≤ a ≤ b ≤ |S| and 1 ≤ c ≤ d ≤ |T|.
Output
Print a string of Q characters, where the i-th character is '1' if the answer to the i-th query is positive, and '0' otherwise.
Example
Input
AABCCBAAB
ABCB
5
1 3 1 2
2 2 2 4
7 9 1 1
3 4 2 3
4 5 1 3
Output
10011
Note
In the first query we can achieve the result, for instance, by using transitions <image>.
The third query asks for changing AAB to A — but in this case we are not able to get rid of the character 'B'.
Submitted Solution:
```
def read():
s = input()
l = len(s)
r = [[0] * (l + 1), [0] * (l + 1)]
for i in range(l):
r[0][i + 1] = (r[0][i] + 1) * (s[i] == 'A')
r[1][i + 1] = r[1][i] + (s[i] != 'A')
return r
s, t = read(), read()
q = int(input())
r = ''
for i in range(q):
a, b, c, d = map(int, input().split())
sb = s[1][b] - s[1][a] + (s[0][a] == 0)
sa = s[0][b] - (s[0][a] - 1) * (sb == 0)
tb = t[1][d] - t[1][c] + (t[0][c] == 0)
ta = t[0][d] - (t[0][c] - 1) * (tb == 0)
if any([sb > tb, sa < ta, tb - sb & 1, sb == tb and (sa - ta) % 3, sa == ta and not sb]):
r += '0'
else:
r += '1'
print(r)
``` | instruction | 0 | 95,820 | 0 | 191,640 |
No | output | 1 | 95,820 | 0 | 191,641 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times:
* A <image> BC
* B <image> AC
* C <image> AB
* AAA <image> empty string
Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source.
Input
The first line contains a string S (1 ≤ |S| ≤ 105). The second line contains a string T (1 ≤ |T| ≤ 105), each of these strings consists only of uppercase English letters 'A', 'B' and 'C'.
The third line contains the number of queries Q (1 ≤ Q ≤ 105).
The following Q lines describe queries. The i-th of these lines contains four space separated integers ai, bi, ci, di. These represent the i-th query: is it possible to create T[ci..di] from S[ai..bi] by applying the above transitions finite amount of times?
Here, U[x..y] is a substring of U that begins at index x (indexed from 1) and ends at index y. In particular, U[1..|U|] is the whole string U.
It is guaranteed that 1 ≤ a ≤ b ≤ |S| and 1 ≤ c ≤ d ≤ |T|.
Output
Print a string of Q characters, where the i-th character is '1' if the answer to the i-th query is positive, and '0' otherwise.
Example
Input
AABCCBAAB
ABCB
5
1 3 1 2
2 2 2 4
7 9 1 1
3 4 2 3
4 5 1 3
Output
10011
Note
In the first query we can achieve the result, for instance, by using transitions <image>.
The third query asks for changing AAB to A — but in this case we are not able to get rid of the character 'B'.
Submitted Solution:
```
s = input()
t = input()
n = int(input())
q = ''
for i in range(n):
a,b,c,d = map(int, input().split())
if a == b or c == d and s[a:b] != t[c:d]:
q += '0'
else:
q += '1'
print(q)
``` | instruction | 0 | 95,821 | 0 | 191,642 |
No | output | 1 | 95,821 | 0 | 191,643 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times:
* A <image> BC
* B <image> AC
* C <image> AB
* AAA <image> empty string
Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source.
Input
The first line contains a string S (1 ≤ |S| ≤ 105). The second line contains a string T (1 ≤ |T| ≤ 105), each of these strings consists only of uppercase English letters 'A', 'B' and 'C'.
The third line contains the number of queries Q (1 ≤ Q ≤ 105).
The following Q lines describe queries. The i-th of these lines contains four space separated integers ai, bi, ci, di. These represent the i-th query: is it possible to create T[ci..di] from S[ai..bi] by applying the above transitions finite amount of times?
Here, U[x..y] is a substring of U that begins at index x (indexed from 1) and ends at index y. In particular, U[1..|U|] is the whole string U.
It is guaranteed that 1 ≤ a ≤ b ≤ |S| and 1 ≤ c ≤ d ≤ |T|.
Output
Print a string of Q characters, where the i-th character is '1' if the answer to the i-th query is positive, and '0' otherwise.
Example
Input
AABCCBAAB
ABCB
5
1 3 1 2
2 2 2 4
7 9 1 1
3 4 2 3
4 5 1 3
Output
10011
Note
In the first query we can achieve the result, for instance, by using transitions <image>.
The third query asks for changing AAB to A — but in this case we are not able to get rid of the character 'B'.
Submitted Solution:
```
x = input()
y = input()
s = [(0,0)]
bc = 0
a = 0
for l in x:
if l in 'BC':
bc += 1
a = 0
else:
a += 1
s.append((bc,a))
t = [(0,0)]
bc = 0
a = 0
for l in y:
if l in 'BC':
bc += 1
a = 0
else:
a += 1
t.append((bc,a))
# print(s)
# print(t)
q = int(input())
for i in range(q):
ls,rs,lt,rt = map(int, input().split())
lens = rs - ls + 1
lent = rt - lt + 1
sbc = s[rs][0] - s[ls-1][0]
tbc = t[rt][0] - t[lt-1][0]
sa = s[rs][1]
ta = t[rt][1]
if sa > lens: sa = lens
if ta > lent: ta = lent
if sa != ta: sbc += 2
a = ta - sa
if a < 0 or a % 2 != 0:
print('0', end = '')
else:
print('1', end = '')
``` | instruction | 0 | 95,822 | 0 | 191,644 |
No | output | 1 | 95,822 | 0 | 191,645 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of n lowercase Latin letters. Polycarp wants to remove exactly k characters (k ≤ n) from the string s. Polycarp uses the following algorithm k times:
* if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
* if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
* ...
* remove the leftmost occurrence of the letter 'z' and stop the algorithm.
This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly k times, thus removing exactly k characters.
Help Polycarp find the resulting string.
Input
The first line of input contains two integers n and k (1 ≤ k ≤ n ≤ 4 ⋅ 10^5) — the length of the string and the number of letters Polycarp will remove.
The second line contains the string s consisting of n lowercase Latin letters.
Output
Print the string that will be obtained from s after Polycarp removes exactly k letters using the above algorithm k times.
If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
Examples
Input
15 3
cccaabababaccbc
Output
cccbbabaccbc
Input
15 9
cccaabababaccbc
Output
cccccc
Input
1 1
u
Output | instruction | 0 | 95,840 | 0 | 191,680 |
Tags: implementation
Correct Solution:
```
n,k = map(int,input().split(' '))
s = input()
z = 1
l = [0]*(26)
for i in range(0,len(s)):
l[ord(s[i])-97] = l[ord(s[i])-97]+1
for i in range(0,26):
c = chr(97+i)
z = 1
if k==0:
break
if s.find(c)!=-1:
if l[i]<=k and l[i]!=0:
s = s.replace(c,'',l[i])
z = z+l[i]-1
k = k-z
else:
s = s.replace(c,'',k)
z = z+k-1
k = k-z
if n!=len(s):
print(s)
``` | output | 1 | 95,840 | 0 | 191,681 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of n lowercase Latin letters. Polycarp wants to remove exactly k characters (k ≤ n) from the string s. Polycarp uses the following algorithm k times:
* if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
* if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
* ...
* remove the leftmost occurrence of the letter 'z' and stop the algorithm.
This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly k times, thus removing exactly k characters.
Help Polycarp find the resulting string.
Input
The first line of input contains two integers n and k (1 ≤ k ≤ n ≤ 4 ⋅ 10^5) — the length of the string and the number of letters Polycarp will remove.
The second line contains the string s consisting of n lowercase Latin letters.
Output
Print the string that will be obtained from s after Polycarp removes exactly k letters using the above algorithm k times.
If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
Examples
Input
15 3
cccaabababaccbc
Output
cccbbabaccbc
Input
15 9
cccaabababaccbc
Output
cccccc
Input
1 1
u
Output | instruction | 0 | 95,841 | 0 | 191,682 |
Tags: implementation
Correct Solution:
```
#!/usr/bin/env python3
#
# FILE: 999C.py
#
# @author: Arafat Hasan Jenin <opendoor.arafat[at]gmail[dot]com>
#
# LINK: http://codeforces.com/contest/999/problem/C
#
# DATE CREATED: 22-06-18 16:19:52 (+06)
# LAST MODIFIED: 23-06-18 02:31:13 (+06)
#
# VERDICT:
#
# DEVELOPMENT HISTORY:
# Date Version Description
# --------------------------------------------------------------------
# 22-06-18 1.0 Deleted code is debugged code.
#
# _/ _/_/_/_/ _/ _/ _/_/_/ _/ _/
# _/ _/ _/_/ _/ _/ _/_/ _/
# _/ _/_/_/ _/ _/ _/ _/ _/ _/ _/
# _/ _/ _/ _/ _/_/ _/ _/ _/_/
# _/_/ _/_/_/_/ _/ _/ _/_/_/ _/ _/
#
##############################################################################
n, k = map(int, input().split())
str = input()
dictionary = dict((letter, str.count(letter)) for letter in set(str))
for item in range(26):
if k == 0:
break
key = chr((item + ord('a')))
if key in dictionary:
if dictionary[key] >= k:
dictionary[key] -= k
k = 0
break
else:
tmp = dictionary[key]
dictionary[key] -= k
k -= tmp
ans = list()
for item in reversed(str):
if item in dictionary:
if dictionary[item] > 0:
dictionary[item] -= 1
ans.append(item)
print("".join([x for x in list(reversed(ans))]))
``` | output | 1 | 95,841 | 0 | 191,683 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of n lowercase Latin letters. Polycarp wants to remove exactly k characters (k ≤ n) from the string s. Polycarp uses the following algorithm k times:
* if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
* if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
* ...
* remove the leftmost occurrence of the letter 'z' and stop the algorithm.
This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly k times, thus removing exactly k characters.
Help Polycarp find the resulting string.
Input
The first line of input contains two integers n and k (1 ≤ k ≤ n ≤ 4 ⋅ 10^5) — the length of the string and the number of letters Polycarp will remove.
The second line contains the string s consisting of n lowercase Latin letters.
Output
Print the string that will be obtained from s after Polycarp removes exactly k letters using the above algorithm k times.
If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
Examples
Input
15 3
cccaabababaccbc
Output
cccbbabaccbc
Input
15 9
cccaabababaccbc
Output
cccccc
Input
1 1
u
Output | instruction | 0 | 95,843 | 0 | 191,686 |
Tags: implementation
Correct Solution:
```
n=0
k=0
def reducedString(s:str):
alphabetList = []
index = 0
while index<26:
alphabetList.append(0)
index += 1
index = 0
#count how many of each character there are in the string
while index<n:
# print(ord(s[index])-ord('a'))
alphabetList[ord(s[index]) - ord('a')] += 1
index+=1
charsDeleted = 0
index = 0
#remove k characters from the string
while(charsDeleted<k):
if(alphabetList[index]>0):
toBeDeleted = min(k - charsDeleted, alphabetList[index])
charsDeleted += toBeDeleted
alphabetList[index] -= toBeDeleted
index += 1
#print(alphabetList)
#build the list of characters that remain after deletion
index = n-1
resultList = []
while(index>-1):
if(alphabetList[ord(s[index]) - ord('a')]>0):
resultList.append(s[index])
alphabetList[ord(s[index]) - ord('a')] -= 1
index -= 1
l = 0
r = len(resultList) - 1
while(l<r):
tmp = resultList[l]
resultList[l] = resultList[r]
resultList[r] = tmp
l+=1
r-=1
res = "".join(resultList)
return res
if __name__ == "__main__":
n,k = map(int, input().split())
s = input()
res = reducedString(s)
print(res)
``` | output | 1 | 95,843 | 0 | 191,687 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of n lowercase Latin letters. Polycarp wants to remove exactly k characters (k ≤ n) from the string s. Polycarp uses the following algorithm k times:
* if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
* if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
* ...
* remove the leftmost occurrence of the letter 'z' and stop the algorithm.
This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly k times, thus removing exactly k characters.
Help Polycarp find the resulting string.
Input
The first line of input contains two integers n and k (1 ≤ k ≤ n ≤ 4 ⋅ 10^5) — the length of the string and the number of letters Polycarp will remove.
The second line contains the string s consisting of n lowercase Latin letters.
Output
Print the string that will be obtained from s after Polycarp removes exactly k letters using the above algorithm k times.
If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
Examples
Input
15 3
cccaabababaccbc
Output
cccbbabaccbc
Input
15 9
cccaabababaccbc
Output
cccccc
Input
1 1
u
Output | instruction | 0 | 95,844 | 0 | 191,688 |
Tags: implementation
Correct Solution:
```
lower = [chr(i) for i in range(97,123)]
temp = input()
l = int(temp.split(" ")[0])
k = int(temp.split(" ")[1])
s = list((input()))
m = dict()
for i in range(l):
m[s[i]] = m.get(s[i],0)+1
m = sorted(m.items(),key=lambda d:d[0])
num = 0
for i in range(len(m)):
num = num + m[i][1]
if(num>=k):
global splistr
splistr = m[i][0]
global left
left = m[i][1]-num+k
break
# print(splistr)
# print(left)
for i in range(l):
if(s[i]==splistr):
s[i]='@'
left = left - 1
if(left==0):
break
for i in range(l):
if(s[i]>=splistr):
print(s[i],end = "")
``` | output | 1 | 95,844 | 0 | 191,689 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of n lowercase Latin letters. Polycarp wants to remove exactly k characters (k ≤ n) from the string s. Polycarp uses the following algorithm k times:
* if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
* if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
* ...
* remove the leftmost occurrence of the letter 'z' and stop the algorithm.
This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly k times, thus removing exactly k characters.
Help Polycarp find the resulting string.
Input
The first line of input contains two integers n and k (1 ≤ k ≤ n ≤ 4 ⋅ 10^5) — the length of the string and the number of letters Polycarp will remove.
The second line contains the string s consisting of n lowercase Latin letters.
Output
Print the string that will be obtained from s after Polycarp removes exactly k letters using the above algorithm k times.
If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
Examples
Input
15 3
cccaabababaccbc
Output
cccbbabaccbc
Input
15 9
cccaabababaccbc
Output
cccccc
Input
1 1
u
Output | instruction | 0 | 95,845 | 0 | 191,690 |
Tags: implementation
Correct Solution:
```
n, k = map(int, input().split())
s = input()
cnt = [0 for i in range(26)]
for i in s:
cnt[ord(i) - ord("a")] += 1
# print("cnt =", cnt)
total = 0
cnt2 = [0 for i in range(26)]
for i in range(26):
if total + cnt[i] <= k:
cnt2[i] = cnt[i]
total += cnt[i]
else:
cnt2[i] = k - total
break
# print("cnt2 =", cnt2)
cnt3 = [0 for i in range(26)]
ans = ""
for i in s:
c = ord(i) - ord("a")
if cnt3[c] < cnt2[c]:
cnt3[c] += 1
else:
ans += i
print(ans)
``` | output | 1 | 95,845 | 0 | 191,691 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of n lowercase Latin letters. Polycarp wants to remove exactly k characters (k ≤ n) from the string s. Polycarp uses the following algorithm k times:
* if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
* if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
* ...
* remove the leftmost occurrence of the letter 'z' and stop the algorithm.
This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly k times, thus removing exactly k characters.
Help Polycarp find the resulting string.
Input
The first line of input contains two integers n and k (1 ≤ k ≤ n ≤ 4 ⋅ 10^5) — the length of the string and the number of letters Polycarp will remove.
The second line contains the string s consisting of n lowercase Latin letters.
Output
Print the string that will be obtained from s after Polycarp removes exactly k letters using the above algorithm k times.
If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
Examples
Input
15 3
cccaabababaccbc
Output
cccbbabaccbc
Input
15 9
cccaabababaccbc
Output
cccccc
Input
1 1
u
Output | instruction | 0 | 95,846 | 0 | 191,692 |
Tags: implementation
Correct Solution:
```
from string import ascii_lowercase
from collections import Counter, OrderedDict
def go():
n, k = (int(i) for i in input().split(' '))
s = [i for i in input()]
if n <= k:
return ''
c = dict(Counter(s))
new = OrderedDict()
t = 0
for i in ascii_lowercase:
if i in c:
if c[i] + t <= k:
new[i] = c[i]
t += c[i]
else:
new[i] = k - t
break
if t == k:
break
i = 0
t = k
while i < n and k != 0:
if s[i] in new and new[s[i]] > 0:
new[s[i]] -= 1
s[i] = 0
k -= 1
i += 1
return ''.join(i for i in s if i != 0)
print(go())
``` | output | 1 | 95,846 | 0 | 191,693 |
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 n lowercase Latin letters. Polycarp wants to remove exactly k characters (k ≤ n) from the string s. Polycarp uses the following algorithm k times:
* if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
* if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
* ...
* remove the leftmost occurrence of the letter 'z' and stop the algorithm.
This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly k times, thus removing exactly k characters.
Help Polycarp find the resulting string.
Input
The first line of input contains two integers n and k (1 ≤ k ≤ n ≤ 4 ⋅ 10^5) — the length of the string and the number of letters Polycarp will remove.
The second line contains the string s consisting of n lowercase Latin letters.
Output
Print the string that will be obtained from s after Polycarp removes exactly k letters using the above algorithm k times.
If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
Examples
Input
15 3
cccaabababaccbc
Output
cccbbabaccbc
Input
15 9
cccaabababaccbc
Output
cccccc
Input
1 1
u
Output
Submitted Solution:
```
def alfabet_del(s:str, n:int, k:int):
if len(s) < 2:
return s
ans = list(map(str, s))
for letter in ans:
min_letter = min(ans)
i = 0
while k > 0 and min_letter in ans:
if ans[i] == min_letter:
ans.remove(ans[i])
k -= 1
i -= 1
i += 1
return ''.join(ans)
``` | instruction | 0 | 95,852 | 0 | 191,704 |
No | output | 1 | 95,852 | 0 | 191,705 |
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 n lowercase Latin letters. Polycarp wants to remove exactly k characters (k ≤ n) from the string s. Polycarp uses the following algorithm k times:
* if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
* if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
* ...
* remove the leftmost occurrence of the letter 'z' and stop the algorithm.
This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly k times, thus removing exactly k characters.
Help Polycarp find the resulting string.
Input
The first line of input contains two integers n and k (1 ≤ k ≤ n ≤ 4 ⋅ 10^5) — the length of the string and the number of letters Polycarp will remove.
The second line contains the string s consisting of n lowercase Latin letters.
Output
Print the string that will be obtained from s after Polycarp removes exactly k letters using the above algorithm k times.
If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
Examples
Input
15 3
cccaabababaccbc
Output
cccbbabaccbc
Input
15 9
cccaabababaccbc
Output
cccccc
Input
1 1
u
Output
Submitted Solution:
```
from itertools import accumulate
n, k = list(map(int, input().split()))
word = input()
lis = sorted(list(set(word)))
t = []
if n == k:
print("")
else:
for item in lis:
if word.count(item) != 0:
t.append(word.count(item))
t = list(accumulate(t))
if k in t:
print("".join([item for item in word if item not in lis[:t.index(k)+1]]))
elif k not in t:
res = [item for item in t if item < k]
if len(res) == 0:
fin = word.replace("a","",k)
print(fin)
else:
maxa = max(res)
fin = ("".join([item for item in word if item not in lis[:t.index(maxa) + 1]]))
print(fin.replace(lis[t.index(maxa) + 1],"", (k - maxa)))
``` | instruction | 0 | 95,853 | 0 | 191,706 |
No | output | 1 | 95,853 | 0 | 191,707 |
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 n lowercase Latin letters. Polycarp wants to remove exactly k characters (k ≤ n) from the string s. Polycarp uses the following algorithm k times:
* if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
* if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
* ...
* remove the leftmost occurrence of the letter 'z' and stop the algorithm.
This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly k times, thus removing exactly k characters.
Help Polycarp find the resulting string.
Input
The first line of input contains two integers n and k (1 ≤ k ≤ n ≤ 4 ⋅ 10^5) — the length of the string and the number of letters Polycarp will remove.
The second line contains the string s consisting of n lowercase Latin letters.
Output
Print the string that will be obtained from s after Polycarp removes exactly k letters using the above algorithm k times.
If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
Examples
Input
15 3
cccaabababaccbc
Output
cccbbabaccbc
Input
15 9
cccaabababaccbc
Output
cccccc
Input
1 1
u
Output
Submitted Solution:
```
import sys
n,k=map(int,sys.stdin.readline().split())
s=input()
s1=s
s1=sorted(s)
s2=s1[:k]
j=s1[k]
s1=s1[k:]
cj=s.count(j)
st=""
J=ord(j)
for i in s:
if ord(i)<J and k>0:
st+='#'
k-=1
continue
if ord(i)==J and cj>0 and k>0:
st+='#'
k-=1
cj-=1
continue
else:
st+=i
ans=""
for i in st:
if i=='#':
continue
else:
ans+=i
print(ans)
``` | instruction | 0 | 95,854 | 0 | 191,708 |
No | output | 1 | 95,854 | 0 | 191,709 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a string S consisting of digits between `1` and `9`, inclusive. You can insert the letter `+` into some of the positions (possibly none) between two letters in this string. Here, `+` must not occur consecutively after insertion.
All strings that can be obtained in this way can be evaluated as formulas.
Evaluate all possible formulas, and print the sum of the results.
Constraints
* 1 \leq |S| \leq 10
* All letters in S are digits between `1` and `9`, inclusive.
Input
The input is given from Standard Input in the following format:
S
Output
Print the sum of the evaluated value over all possible formulas.
Examples
Input
125
Output
176
Input
9999999999
Output
12656242944 | instruction | 0 | 95,966 | 0 | 191,932 |
"Correct Solution:
```
def bfs(s: str, n: int, i: int, j: int, k: int):
return k+int(s[j:]) if i==n-1 else bfs(s,n,i+1,i+1,k+int(s[j:i+1]))+bfs(s,n,i+1,j,k)
s=input()
n=len(s)
print(bfs(s,n,0,0,0))
``` | output | 1 | 95,966 | 0 | 191,933 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a string S consisting of digits between `1` and `9`, inclusive. You can insert the letter `+` into some of the positions (possibly none) between two letters in this string. Here, `+` must not occur consecutively after insertion.
All strings that can be obtained in this way can be evaluated as formulas.
Evaluate all possible formulas, and print the sum of the results.
Constraints
* 1 \leq |S| \leq 10
* All letters in S are digits between `1` and `9`, inclusive.
Input
The input is given from Standard Input in the following format:
S
Output
Print the sum of the evaluated value over all possible formulas.
Examples
Input
125
Output
176
Input
9999999999
Output
12656242944 | instruction | 0 | 95,967 | 0 | 191,934 |
"Correct Solution:
```
S = input()
l = len(S)
ans = 0
for i in range(l):
for j in range(i+1,l+1):
temp = int(S[i:j])
ans += temp * max(1,pow(2,i-1)) * max(1,pow(2,l-j-1))
print(ans)
``` | output | 1 | 95,967 | 0 | 191,935 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.