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 a string s consisting of lowercase English letters and a number k. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by k. You are asked to find the lexicographically smallest beautiful string of length n, which is lexicographically greater or equal to string s. If such a string does not exist, output -1.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains a single integer T (1 ≤ T ≤ 10 000) — the number of test cases.
The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines.
The first line of the description contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the length of string s and number k respectively.
The second line contains string s consisting of lowercase English letters.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case output in a separate line lexicographically smallest beautiful string of length n, which is greater or equal to string s, or -1 if such a string does not exist.
Example
Input
4
4 2
abcd
3 1
abc
4 3
aaaa
9 3
abaabaaaa
Output
acac
abc
-1
abaabaaab
Note
In the first test case "acac" is greater than or equal to s, and each letter appears 2 or 0 times in it, so it is beautiful.
In the second test case each letter appears 0 or 1 times in s, so s itself is the answer.
We can show that there is no suitable string in the third test case.
In the fourth test case each letter appears 0, 3, or 6 times in "abaabaaab". All these integers are divisible by 3. | instruction | 0 | 62,513 | 0 | 125,026 |
Tags: binary search, brute force, constructive algorithms, greedy, strings
Correct Solution:
```
rn=lambda:int(input())
rns=lambda:map(int,input().split())
rl=lambda:list(map(int,input().split()))
rs=lambda:input()
YN=lambda x:print('YES') if x else print('NO')
mod=10**9+7
from collections import Counter
def solve(n,k,s):
if n%k!=0:
return -1
c=Counter(s)
if all([c[i]%k==0 for i in c]):
return True
d={}
ans=-1
for i in range(n):
for j in range(1,26-(ord(s[i])-97)):
if ord(s[i])-97+j not in d:
d[ord(s[i])-97+j]=0
d[ord(s[i])-97+j]+=1
a=n-i-1
flag=False
for l in d:
if d[l]>0:
if (k-d[l]%k)%k>a:
flag=True
break
a-=(k-d[l]%k)%k
if not flag and a%k==0:
ans=[i,j]
d[ord(s[i]) - 97 + j] -= 1
break
else:
d[ord(s[i]) - 97 + j] -= 1
if ord(s[i]) - 97 not in d:
d[ord(s[i]) - 97] = 0
d[ord(s[i]) - 97] += 1
return ans
for _ in range(rn()):
n,k=rns()
s=rs()
ans=solve(n,k,s)
if ans==-1:
print(-1)
elif ans==True:
print(s)
else:
pans=''
for i in range(ans[0]):
pans+=s[i]
pans+=chr(ord(s[ans[0]])+ans[1])
c=Counter(pans)
d=sorted([[i,c[i]] for i in c])
tail=''
for char in d:
tail+=(k-char[1]%k)%k*char[0]
fill=n-len(tail)-len(pans)
print(pans+fill*'a'+tail)
``` | output | 1 | 62,513 | 0 | 125,027 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of lowercase English letters and a number k. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by k. You are asked to find the lexicographically smallest beautiful string of length n, which is lexicographically greater or equal to string s. If such a string does not exist, output -1.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains a single integer T (1 ≤ T ≤ 10 000) — the number of test cases.
The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines.
The first line of the description contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the length of string s and number k respectively.
The second line contains string s consisting of lowercase English letters.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case output in a separate line lexicographically smallest beautiful string of length n, which is greater or equal to string s, or -1 if such a string does not exist.
Example
Input
4
4 2
abcd
3 1
abc
4 3
aaaa
9 3
abaabaaaa
Output
acac
abc
-1
abaabaaab
Note
In the first test case "acac" is greater than or equal to s, and each letter appears 2 or 0 times in it, so it is beautiful.
In the second test case each letter appears 0 or 1 times in s, so s itself is the answer.
We can show that there is no suitable string in the third test case.
In the fourth test case each letter appears 0, 3, or 6 times in "abaabaaab". All these integers are divisible by 3. | instruction | 0 | 62,514 | 0 | 125,028 |
Tags: binary search, brute force, constructive algorithms, greedy, strings
Correct Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
# from fractions import *
from heapq import*
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M=998244353
EPS=1e-6
def Ceil(a,b): return a//b+int(a%b>0)
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
for _ in range(Int()):
n,k = value()
s = input()
s = s[::-1]
C = Counter(s)
ans = s[::-1]
for i in C:
if(C[i]%k): ans = -1
for i in range(n):
C[s[i]] -= 1
if(s[i] == 'z' or ans != -1): continue
next = False
agla = False
need = 0
have = i + 1
for ch in ALPHA[::-1]:
need += (k - C[ch]%k )%k
if((k - C[ch]%k )%k and ord(ch) == 1+ord(s[i])): next = ch
if((k - C[ch]%k )%k and ch > s[i]): agla = ch
# print(i,need,have,next,C)
if(need > have or (have - need)%k): continue
if(have == need and not agla): continue
needed = []
for ch in ALPHA: needed += [ch]*((k - C[ch]%k )%k)
if(have == need): next = agla
if(not next):
next = ALPHA[ ALPHA.index(s[i]) + 1 ]
needed += [next]*(k)
have -= k
# print(needed,i,next,ans)
needed += ['a']*(have - need)
needed.sort()
needed.remove(next)
needed.insert(0,next)
ans = s[i+1:][::-1]
ans += ''.join(needed)
break
print(ans)
``` | output | 1 | 62,514 | 0 | 125,029 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of lowercase English letters and a number k. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by k. You are asked to find the lexicographically smallest beautiful string of length n, which is lexicographically greater or equal to string s. If such a string does not exist, output -1.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains a single integer T (1 ≤ T ≤ 10 000) — the number of test cases.
The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines.
The first line of the description contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the length of string s and number k respectively.
The second line contains string s consisting of lowercase English letters.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case output in a separate line lexicographically smallest beautiful string of length n, which is greater or equal to string s, or -1 if such a string does not exist.
Example
Input
4
4 2
abcd
3 1
abc
4 3
aaaa
9 3
abaabaaaa
Output
acac
abc
-1
abaabaaab
Note
In the first test case "acac" is greater than or equal to s, and each letter appears 2 or 0 times in it, so it is beautiful.
In the second test case each letter appears 0 or 1 times in s, so s itself is the answer.
We can show that there is no suitable string in the third test case.
In the fourth test case each letter appears 0, 3, or 6 times in "abaabaaab". All these integers are divisible by 3. | instruction | 0 | 62,515 | 0 | 125,030 |
Tags: binary search, brute force, constructive algorithms, greedy, 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())
def A(n):return [0]*n
def AI(n,x): return [x]*n
def A2(n,m): return [[0]*m for i in range(n)]
def G(n): return [[] for i in range(n)]
def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)]
#------------------------------------------------------------------------
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
mod=10**9+7
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
fact(x,mod)
ifa.append(pow(farr[-1],mod-2,mod))
for i in range(x,0,-1):
ifa.append(ifa[-1]*i%mod)
ifa.reverse()
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 floorsum(a,b,c,n):#sum((a*i+b)//c for i in range(n+1))
if a==0:return b//c*(n+1)
if a>=c or b>=c: return floorsum(a%c,b%c,c,n)+b//c*(n+1)+a//c*n*(n+1)//2
m=(a*n+b)//c
return n*m-floorsum(c,c-b-1,a,m-1)
def inverse(a,m):
a%=m
if a<=1: return a
return ((1-inverse(m,a)*m)//a)%m
def lowbit(n):
return n&-n
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 ST:
def __init__(self,arr):#n!=0
n=len(arr)
mx=n.bit_length()#取不到
self.st=[[0]*mx for i in range(n)]
for i in range(n):
self.st[i][0]=arr[i]
for j in range(1,mx):
for i in range(n-(1<<j)+1):
self.st[i][j]=max(self.st[i][j-1],self.st[i+(1<<j-1)][j-1])
def query(self,l,r):
if l>r:return -inf
s=(r+1-l).bit_length()-1
return max(self.st[l][s],self.st[r-(1<<s)+1][s])
'''
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
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
seen.add(u)
for v,w in graph[u]:
if v not in d or d[v]>d[u]+w:
d[v]=d[u]+w
heappush(heap,(d[v],v))
return d
def bell(s,g):#bellman-Ford
dis=AI(n,inf)
dis[s]=0
for i in range(n-1):
for u,v,w in edge:
if dis[v]>dis[u]+w:
dis[v]=dis[u]+w
change=A(n)
for i in range(n):
for u,v,w in edge:
if dis[v]>dis[u]+w:
dis[v]=dis[u]+w
change[v]=1
return dis
def lcm(a,b): return a*b//gcd(a,b)
def lis(nums):
res=[]
for k in nums:
i=bisect.bisect_left(res,k)
if i==len(res):
res.append(k)
else:
res[i]=k
return len(res)
def RP(nums):#逆序对
n = len(nums)
s=set(nums)
d={}
for i,k in enumerate(sorted(s),1):
d[k]=i
bi=BIT([0]*(len(s)+1))
ans=0
for i in range(n-1,-1,-1):
ans+=bi.query(d[nums[i]]-1)
bi.update(d[nums[i]],1)
return ans
class DLN:
def __init__(self,val):
self.val=val
self.pre=None
self.next=None
def nb(i,j,n,m):
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
def topo(n):
q=deque()
res=[]
for i in range(1,n+1):
if ind[i]==0:
q.append(i)
res.append(i)
while q:
u=q.popleft()
for v in g[u]:
ind[v]-=1
if ind[v]==0:
q.append(v)
res.append(v)
return res
@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,k=RL()
s=input()
if n%k:print(-1)
else:
c=Counter(s)
f=True
for x in c:
if c[x]%k:
f=False
break
if f:
print(s)
else:
for i in range(n-1,-1,-1):
c[s[i]]-=1
need=0
for x in c:
need+=-c[x]%k
if need>n-i:
continue
ff=False
for j in range(ord(s[i])+1,123):
cn=need
cn-=(k-c[chr(j)])%k
cn+=(k-c[chr(j)]-1)%k
if cn<=n-i-1:
ff=True
break
if ff:
c[chr(j)]+=1
ans=s[:i]+chr(j)
if n-i-1>cn:
ans+='a'*(n-i-1-cn)
for x in sorted(c.keys()):
if (k-c[x])%k:
ans+=x*((k-c[x])%k)
print(ans)
break
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thr
ead(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 | 62,515 | 0 | 125,031 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of lowercase English letters and a number k. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by k. You are asked to find the lexicographically smallest beautiful string of length n, which is lexicographically greater or equal to string s. If such a string does not exist, output -1.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains a single integer T (1 ≤ T ≤ 10 000) — the number of test cases.
The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines.
The first line of the description contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the length of string s and number k respectively.
The second line contains string s consisting of lowercase English letters.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case output in a separate line lexicographically smallest beautiful string of length n, which is greater or equal to string s, or -1 if such a string does not exist.
Example
Input
4
4 2
abcd
3 1
abc
4 3
aaaa
9 3
abaabaaaa
Output
acac
abc
-1
abaabaaab
Note
In the first test case "acac" is greater than or equal to s, and each letter appears 2 or 0 times in it, so it is beautiful.
In the second test case each letter appears 0 or 1 times in s, so s itself is the answer.
We can show that there is no suitable string in the third test case.
In the fourth test case each letter appears 0, 3, or 6 times in "abaabaaab". All these integers are divisible by 3. | instruction | 0 | 62,516 | 0 | 125,032 |
Tags: binary search, brute force, constructive algorithms, greedy, strings
Correct Solution:
```
"""
#If FastIO not needed, use this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""
import os, sys, heapq as h, time
from io import BytesIO, IOBase
from types import GeneratorType
from bisect import bisect_left, bisect_right
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
self.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")
#start_time = time.time()
def getInt(): return int(input())
def getStrs(): return input().split()
def getInts(): return list(map(int,input().split()))
def getStr(): return input()
def listStr(): return list(input())
def getMat(n): return [getInts() for _ in range(n)]
def isInt(s): return '0' <= s[0] <= '9'
MOD = 10**9 + 7
"""
Note that 'zzzzzzz' satisfies any requirements where N % K = 0
In fact, repeating the first letter after our first letter that many times will suffice
What is the latest place we can allow the string to differ?
Possible up to the point we're at if sum((-count[letter])%K) for all letters is <= remaining letters, and there exists a letter in the set that is
>= the next letter
"""
def solve():
N, K = getInts()
S = listStr()
if N % K != 0: return -1
counts = [0]*26
ord_a = ord('a')
for a in S:
counts[ord(a) - ord_a] += 1
counts[ord(a) - ord_a] %= K
t = S[:]
curr = 0
for j in range(26):
curr += (-counts[j])%K
rem = 0
#print(curr,counts)
flag = False
if curr == 0: return ''.join(S)
while curr > rem or not flag:
x = t.pop()
ord_x = ord(x)-ord_a
curr -= (-counts[ord_x])%K
counts[ord_x] -= 1
counts[ord_x] %= K
curr += (-counts[ord_x])%K
flag = False
for j in range(ord_x+1,26):
tmp_curr = curr
tmp_curr -= (-counts[j])%K
tmp_curr += ((-counts[j]-1)%K)
if tmp_curr <= rem:
flag = True
break
if flag:
t.append(chr(ord_a+j))
counts[j] += 1
counts[j] %= K
break
rem += 1
tmp_ans = []
#print(t)
for j in range(25,-1,-1):
tmp_ans += [chr(j+ord_a)]*(-counts[j]%K)
tmp_ans.reverse()
t += (N-len(tmp_ans)-len(t))*['a']
return ''.join(t+tmp_ans)
for _ in range(getInt()):
print(solve())
#solve()
#print(time.time()-start_time)
``` | output | 1 | 62,516 | 0 | 125,033 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of lowercase English letters and a number k. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by k. You are asked to find the lexicographically smallest beautiful string of length n, which is lexicographically greater or equal to string s. If such a string does not exist, output -1.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains a single integer T (1 ≤ T ≤ 10 000) — the number of test cases.
The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines.
The first line of the description contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the length of string s and number k respectively.
The second line contains string s consisting of lowercase English letters.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case output in a separate line lexicographically smallest beautiful string of length n, which is greater or equal to string s, or -1 if such a string does not exist.
Example
Input
4
4 2
abcd
3 1
abc
4 3
aaaa
9 3
abaabaaaa
Output
acac
abc
-1
abaabaaab
Note
In the first test case "acac" is greater than or equal to s, and each letter appears 2 or 0 times in it, so it is beautiful.
In the second test case each letter appears 0 or 1 times in s, so s itself is the answer.
We can show that there is no suitable string in the third test case.
In the fourth test case each letter appears 0, 3, or 6 times in "abaabaaab". All these integers are divisible by 3. | instruction | 0 | 62,517 | 0 | 125,034 |
Tags: binary search, brute force, constructive algorithms, greedy, strings
Correct Solution:
```
def solve():
for i in range(int(input())):
n, k = map(int, input().split());s = input().strip()
if k == 1:print(s);continue
if n % k != 0:print(-1);continue
want = [0]*26;need = 0;i = 0;best = -1;A = ord('a')
for c in s:
v = ord(c)-A
if v < 25:
for j in range(v+1,26):
if want[j] == 0:
if need + k - 1 <= n - i - 1:
best = i
break
else:
if need - 1 <= n - i - 1:
best = i
break
if want[v] == 0:
want[v] = k - 1
need += k - 1
else:
need -= 1
want[v] -= 1
i += 1
if need == 0:
print(s)
continue
if best == -1:
print(-1)
continue
want = [0]*26
need = 0
i = 0
for c in s:
v = ord(c)-A
if i == best:
res = list(s[:i])
for j in range(v+1,26):
if want[j] == 0:
if need + k - 1 <= n - i - 1:
need += k - 1
want[j] = k - 1
res.append(chr(j+A))
break
else:
if need - 1 <= n - i - 1:res.append(chr(j+A));want[j] -= 1;need -= 1;break
while need < n - i - 1:want[0] += k;need += k
for z in range(26):
for _ in range(want[z]):res.append(chr(z+A))
print(''.join(res));break
if want[v] == 0:want[v] = k - 1;need += k - 1
else:need -= 1;want[v] -= 1
i += 1
solve()
``` | output | 1 | 62,517 | 0 | 125,035 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of lowercase English letters and a number k. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by k. You are asked to find the lexicographically smallest beautiful string of length n, which is lexicographically greater or equal to string s. If such a string does not exist, output -1.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains a single integer T (1 ≤ T ≤ 10 000) — the number of test cases.
The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines.
The first line of the description contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the length of string s and number k respectively.
The second line contains string s consisting of lowercase English letters.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case output in a separate line lexicographically smallest beautiful string of length n, which is greater or equal to string s, or -1 if such a string does not exist.
Example
Input
4
4 2
abcd
3 1
abc
4 3
aaaa
9 3
abaabaaaa
Output
acac
abc
-1
abaabaaab
Note
In the first test case "acac" is greater than or equal to s, and each letter appears 2 or 0 times in it, so it is beautiful.
In the second test case each letter appears 0 or 1 times in s, so s itself is the answer.
We can show that there is no suitable string in the third test case.
In the fourth test case each letter appears 0, 3, or 6 times in "abaabaaab". All these integers are divisible by 3. | instruction | 0 | 62,518 | 0 | 125,036 |
Tags: binary search, brute force, constructive algorithms, greedy, strings
Correct Solution:
```
from collections import Counter
for _ in range(int(input())):
n, k = map(int, input().split())
s = input()
if n % k:
print(-1)
elif k == 1:
print(s)
else:
stat = Counter(s)
if all(v % k == 0 for v in stat.values()):
print(s)
continue
usage = [0] * 26
last_i = -1
last_new_ch = 'z'
suppl = 0
for i in range(n):
for j in range(26):
cand_ch = chr(ord('a') + j)
if cand_ch > s[i]:
if usage[j] % k == 0:
new_suppl = suppl + k - 1
else:
new_suppl = suppl - 1
if new_suppl <= (n - i - 1):
last_new_ch = cand_ch
last_i = i
break
idx = ord(s[i]) - ord('a')
if usage[idx] % k == 0:
suppl += k - 1
else:
suppl -= 1
usage[idx] += 1
if last_i == -1:
print(last_i)
continue
else:
prefix = s[:last_i] + last_new_ch
stat = Counter(prefix)
ans = [prefix]
suffix = []
for j in range(26):
cur = stat.get(chr(ord('a') + j), 0) % k
if cur > 0:
suffix.append(chr(ord('a') + j) * (k - cur))
suffix = ''.join(suffix)
rem = n - len(suffix) - len(prefix)
print(''.join([prefix, 'a' * rem, suffix]))
continue
``` | output | 1 | 62,518 | 0 | 125,037 |
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 lowercase English letters and a number k. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by k. You are asked to find the lexicographically smallest beautiful string of length n, which is lexicographically greater or equal to string s. If such a string does not exist, output -1.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains a single integer T (1 ≤ T ≤ 10 000) — the number of test cases.
The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines.
The first line of the description contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the length of string s and number k respectively.
The second line contains string s consisting of lowercase English letters.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case output in a separate line lexicographically smallest beautiful string of length n, which is greater or equal to string s, or -1 if such a string does not exist.
Example
Input
4
4 2
abcd
3 1
abc
4 3
aaaa
9 3
abaabaaaa
Output
acac
abc
-1
abaabaaab
Note
In the first test case "acac" is greater than or equal to s, and each letter appears 2 or 0 times in it, so it is beautiful.
In the second test case each letter appears 0 or 1 times in s, so s itself is the answer.
We can show that there is no suitable string in the third test case.
In the fourth test case each letter appears 0, 3, or 6 times in "abaabaaab". All these integers are divisible by 3.
Submitted Solution:
```
'''Author- Akshit Monga'''
from sys import stdin,stdout
# input = stdin.readline
t = int(input())
for _ in range(t):
n,k=map(int,input().split())
s=input()
# if t==7081:
# if _==271:
# print(n,k)
# print(s)
# else:
# continue
if n%k:
print(-1)
continue
vals=[0 for i in range(26)]
for i in s:
vals[ord(i)-97]+=1
for i in vals:
if i%k:
break
else:
print(s)
continue
distinct=n//k
ans=[0 for i in range(n)]
pre=[[0 for i in range(26)] for j in range(n)]
for i in range(26):
for j in range(n):
if j==0:
if ord(s[j])-97==i:
pre[j][i]=1
else:
pre[j][i]=0
else:
if ord(s[j])-97==i:
pre[j][i]=pre[j-1][i]+1
else:
pre[j][i]=pre[j-1][i]
# print(pre)
for i in range(n-1,-1,-1):
#changing the ith char
if ord(s[i])-97==25:
continue
req=0
last=0
to_add={}
for j in range(26):
if i==0:
count=0
else:
count=pre[i-1][j]
if count%k==0:
continue
else:
req+=k-count%k
last=j
to_add[j]=k-count%k
left=n-i
# print(i,left)
if req>left:
continue
if req==left and last<=ord(s[i])-97:
continue
new=left-req
# print(left,req)
if new%k:
continue
for j in range(0,i):
ans[j]=s[j]
if new==0:
for j in sorted(to_add):
if j>ord(s[i])-97:
ans[i]=chr(j+97)
to_add[j]-=1
break
counter=i
for j in sorted(to_add):
for q in range(to_add[j]):
counter+=1
ans[counter]=chr(j+97)
else:
# print(new)
pivot=chr(ord(s[i])+1)
ans[i]=pivot
if ord(pivot)-97 in to_add:
to_add[ord(pivot)-97]-=1
to_add[0]=to_add.get(0,0)+new
else:
if 1%k==0:
var=0
else:
var=k-(1%k)
to_add[ord(pivot)-97]=var
to_add[0]=to_add.get(0,0)+new-var-1
# print(ans)
# print(to_add)
counter=i
for j in sorted(to_add):
for q in range(to_add[j]):
counter+=1
ans[counter]=chr(j+97)
break
print(''.join(ans))
``` | instruction | 0 | 62,519 | 0 | 125,038 |
Yes | output | 1 | 62,519 | 0 | 125,039 |
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 lowercase English letters and a number k. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by k. You are asked to find the lexicographically smallest beautiful string of length n, which is lexicographically greater or equal to string s. If such a string does not exist, output -1.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains a single integer T (1 ≤ T ≤ 10 000) — the number of test cases.
The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines.
The first line of the description contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the length of string s and number k respectively.
The second line contains string s consisting of lowercase English letters.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case output in a separate line lexicographically smallest beautiful string of length n, which is greater or equal to string s, or -1 if such a string does not exist.
Example
Input
4
4 2
abcd
3 1
abc
4 3
aaaa
9 3
abaabaaaa
Output
acac
abc
-1
abaabaaab
Note
In the first test case "acac" is greater than or equal to s, and each letter appears 2 or 0 times in it, so it is beautiful.
In the second test case each letter appears 0 or 1 times in s, so s itself is the answer.
We can show that there is no suitable string in the third test case.
In the fourth test case each letter appears 0, 3, or 6 times in "abaabaaab". All these integers are divisible by 3.
Submitted Solution:
```
from os import path;import sys,time
# mod = int(1e9 + 7)
from math import ceil, floor,gcd,log,log2 ,factorial,sqrt
from collections import defaultdict ,Counter , OrderedDict , deque;from itertools import combinations,permutations
# from string import ascii_lowercase ,ascii_uppercase
from bisect import *;from functools import reduce;from operator import mul;maxx = float('inf')
I = lambda :int(sys.stdin.buffer.readline())
lint = lambda :[int(x) for x in sys.stdin.buffer.readline().split()]
S = lambda: sys.stdin.readline().strip('\n')
grid = lambda r :[lint() for i in range(r)]
localsys = 0
start_time = time.time()
#left shift --- num*(2**k) --(k - shift)
nCr = lambda n, r: reduce(mul, range(n - r + 1, n + 1), 1) // factorial(r)
def ceill(n,x):
return (n+x -1 )//x
T =True
def ok(s , freq ,i ,n ,k):
left, A = n - i - 1 , ord('a')
freq[ord(s[i]) - A] -= 1
if s[i] =='z':return False
for c in range(ord(s[i]) + 1 , ord('z') + 1):
freq[c - A]+=1
rem = 0
for j in range(26):
if freq[j] % k :
rem+= (k - freq[j]%k)
if left < rem or (left - rem) % k != 0:
freq[c - A]-=1
else:
arr =[]
s[i] = chr(c)
for j in range(26):
if freq[j] % k :
arr+= [chr(A + j)]*(k - freq[j]%k)
if rem < left:
arr+=['a']*(left- rem)
arr.sort()
s[i+1:] = arr
return True
return False
def solve():
n , k = map(int , input().split())
s = list(input())
if n% k :
return print(-1)
if k == 1:
return print(''.join(s))
freq =[0]*26
for i in s :
freq[ord(i) - ord('a')]+=1
f = False
for i in range(26):
if freq[i] % k:
f = True
break
if f :
for i in range(n-1 , -1 , -1):
if ok(s, freq, i, n,k):
return print(''.join(s))
print(''.join(s))
def run():
if (path.exists('input.txt')):
sys.stdin=open('input.txt','r')
sys.stdout=open('output.txt','w')
run()
T = I() if T else 1
for _ in range(T):
solve()
if localsys:
print("\n\nTime Elased :",time.time() - start_time,"seconds")
``` | instruction | 0 | 62,520 | 0 | 125,040 |
Yes | output | 1 | 62,520 | 0 | 125,041 |
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 lowercase English letters and a number k. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by k. You are asked to find the lexicographically smallest beautiful string of length n, which is lexicographically greater or equal to string s. If such a string does not exist, output -1.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains a single integer T (1 ≤ T ≤ 10 000) — the number of test cases.
The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines.
The first line of the description contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the length of string s and number k respectively.
The second line contains string s consisting of lowercase English letters.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case output in a separate line lexicographically smallest beautiful string of length n, which is greater or equal to string s, or -1 if such a string does not exist.
Example
Input
4
4 2
abcd
3 1
abc
4 3
aaaa
9 3
abaabaaaa
Output
acac
abc
-1
abaabaaab
Note
In the first test case "acac" is greater than or equal to s, and each letter appears 2 or 0 times in it, so it is beautiful.
In the second test case each letter appears 0 or 1 times in s, so s itself is the answer.
We can show that there is no suitable string in the third test case.
In the fourth test case each letter appears 0, 3, or 6 times in "abaabaaab". All these integers are divisible by 3.
Submitted Solution:
```
def main():
import sys
input = sys.stdin.readline
T = int(input())
alpha = 'abcdefghijklmnopqrstuvwxyz'
da = dict()
ANS = []
for i, x in enumerate(alpha):
da[x] = i
for _ in range(T):
n, k = map(int, input().split())
s = input().rstrip()
if n % k != 0:
ANS.append('-1')
continue
d = dict()
for x in s:
if x not in d:
d[x] = 0
d[x] += 1
flag = True
for x in d:
if d[x] % k > 0:
flag = False
if flag:
ANS.append(s)
continue
s = s[::-1]
for i in range(n):
r = 0
d[s[i]] -= 1
ret = []
for x in d:
if d[x] % k > 0:
r += k-(d[x] % k)
if s[i] == 'z':
continue
if i+1 == r:
for j in range(da[s[i]]+1, 26):
x = alpha[j]
if x in d and d[x] % k != 0:
ret.append(x)
d[x] += 1
for y in alpha:
if y in d and d[y] % k != 0:
for j2 in range(k - d[y] % k):
ret.append(y)
# print(s[::-1], x)
ANS.append(''.join([s[i+1:][::-1], ''.join(ret)]))
flag = True
break
if flag:
break
elif i+1 > r:
id = da[s[i]]
if alpha[id+1] not in d:
d[alpha[id+1]] = 0
d[alpha[id+1]] += 1
r2 = i
# print(d)
for y in alpha:
if y in d and d[y] % k != 0:
for j2 in range(k - (d[y] % k)):
ret.append(y)
r2 -= 1
ret2 = []
for j in range(r2):
ret2.append('a')
ANS.append(''.join([s[i+1:][::-1], alpha[id+1], ''.join(ret2) ,''.join(ret)]))
flag = True
break
if flag == False:
ANS.append('-1')
print(*ANS, sep='\n')
main()
``` | instruction | 0 | 62,521 | 0 | 125,042 |
Yes | output | 1 | 62,521 | 0 | 125,043 |
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 lowercase English letters and a number k. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by k. You are asked to find the lexicographically smallest beautiful string of length n, which is lexicographically greater or equal to string s. If such a string does not exist, output -1.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains a single integer T (1 ≤ T ≤ 10 000) — the number of test cases.
The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines.
The first line of the description contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the length of string s and number k respectively.
The second line contains string s consisting of lowercase English letters.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case output in a separate line lexicographically smallest beautiful string of length n, which is greater or equal to string s, or -1 if such a string does not exist.
Example
Input
4
4 2
abcd
3 1
abc
4 3
aaaa
9 3
abaabaaaa
Output
acac
abc
-1
abaabaaab
Note
In the first test case "acac" is greater than or equal to s, and each letter appears 2 or 0 times in it, so it is beautiful.
In the second test case each letter appears 0 or 1 times in s, so s itself is the answer.
We can show that there is no suitable string in the third test case.
In the fourth test case each letter appears 0, 3, or 6 times in "abaabaaab". All these integers are divisible by 3.
Submitted Solution:
```
# from __future__ import print_function,division
# range = xrange
import sys
input = sys.stdin.readline
# sys.setrecursionlimit(10**9)
from sys import stdin, stdout
from collections import defaultdict, Counter
M = 10**9+7
def main():
d = {chr(i+ord('a')):i for i in range(26)}
for _ in range(int(input())):
n,k = [int(s) for s in input().split()]
s = input().strip()
if n%k!=0:
print(-1)
continue
pre = [[0 for i in range(26)] for j in range(n+1)]
for i in range(n):
for j in range(26):
pre[i][j] = pre[i-1][j]
pre[i][d[s[i]]]+=1
for j in range(26):
if pre[n-1][j]%k!=0:
break
else:
print(s)
continue
for i in range(n-1,-1,-1):
req = {}
sumr = 0
for j in range(26):
if pre[i-1][j]%k!=0:
req[chr(j+ord('a'))] = k-(pre[i-1][j]%k)
sumr += (k-(pre[i-1][j]%k))
if sumr<=n-i and s[i]!='z':
if (n-i-sumr)%k==0:
ans = list(s[:i])
flag = 0
if n-i-sumr>0:
if chr(ord(s[i])+1) in req:
req[chr(ord(s[i])+1)] -=1
else:
req[chr(ord(s[i])+1)] = k-1
sumr+=k
ans.append(chr(ord(s[i])+1))
flag = 1
req1 = sorted([[c,req[c]] for c in req])
if not flag:
for w in range(len(req1)):
if req1[w][0]>s[i]:
ans.append(req1[w][0])
req1[w][1]-=1
flag = 1
break
if not flag:
continue
for w1 in range(n-i-sumr):
ans.append("a")
for w in range(len(req1)):
for w1 in range(req1[w][1]):
ans.append(req1[w][0])
print("".join(ans))
break
else:
print(-1)
if __name__== '__main__':
main()
``` | instruction | 0 | 62,522 | 0 | 125,044 |
Yes | output | 1 | 62,522 | 0 | 125,045 |
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 lowercase English letters and a number k. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by k. You are asked to find the lexicographically smallest beautiful string of length n, which is lexicographically greater or equal to string s. If such a string does not exist, output -1.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains a single integer T (1 ≤ T ≤ 10 000) — the number of test cases.
The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines.
The first line of the description contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the length of string s and number k respectively.
The second line contains string s consisting of lowercase English letters.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case output in a separate line lexicographically smallest beautiful string of length n, which is greater or equal to string s, or -1 if such a string does not exist.
Example
Input
4
4 2
abcd
3 1
abc
4 3
aaaa
9 3
abaabaaaa
Output
acac
abc
-1
abaabaaab
Note
In the first test case "acac" is greater than or equal to s, and each letter appears 2 or 0 times in it, so it is beautiful.
In the second test case each letter appears 0 or 1 times in s, so s itself is the answer.
We can show that there is no suitable string in the third test case.
In the fourth test case each letter appears 0, 3, or 6 times in "abaabaaab". All these integers are divisible by 3.
Submitted Solution:
```
t = int(input())
def convert(a):
n = len(a)
result = ['*' for _ in range(n)]
for i in range(n):
result[i] = chr(a[i] + ord('a'))
return ''.join(result)
for _iterator_ in range(t):
n, k = list(map(int, input().split()))
s = list(map(ord, list(input())))
if n % k:
print(-1)
continue
for i in range(n):
s[i] -= ord('a')
convertedS = convert(s)
arr = [[] for _ in range(25)]
for i in range(n):
if s[i] != 25:
arr[s[i]].append(i)
good = True
for indexes in arr:
good &= len(indexes) % k == 0
if good:
print(convert(s))
continue
answer = [ord('z') + 1]
curAnswer = convert(answer)
for indexes in arr:
l = 0
r = len(indexes) - 1
m = 0
good = False
while l <= r:
m = (l + r) >> 1
currentIndex = indexes[m]
cnt = [0 for _ in range(26)]
for i in range(currentIndex):
cnt[s[i]] += 1
remLength = n - currentIndex
leftCurrentLetter = s[currentIndex]
rightCurrentLetter = 25
currentLetter = 0
while leftCurrentLetter <= rightCurrentLetter:
currentLetter = (leftCurrentLetter + rightCurrentLetter) >> 1
rem = [0 for _ in range(26)]
for i in range(26):
rem[i] = (k - (cnt[i] % k)) % k
if rem[currentLetter] == 0:
rem[currentLetter] += k
if sum(rem) > remLength:
leftCurrentLetter = currentLetter + 1
continue
while sum(rem) < remLength:
rem[0] += k
currentAnswer = [s[i] for i in range(n)]
currentAnswer[currentIndex] = currentLetter
rem[currentLetter] -= 1
itr = 0
for i in range(currentIndex + 1, n):
while rem[itr] == 0:
itr += 1
currentAnswer[i] = itr
rem[itr] -= 1
curString = convert(list(currentAnswer))
if curAnswer > curString > convertedS:
curAnswer = curString
good = True
rightCurrentLetter = currentLetter - 1
else:
leftCurrentLetter = currentLetter + 1
for currentLetter in [s[currentIndex], s[currentIndex] + 1]:
rem = [0 for _ in range(26)]
for i in range(26):
rem[i] = (k - (cnt[i] % k)) % k
if rem[currentLetter] == 0:
rem[currentLetter] += k
if sum(rem) > remLength:
continue
while sum(rem) < remLength:
rem[0] += k
currentAnswer = [s[i] for i in range(n)]
currentAnswer[currentIndex] = currentLetter
rem[currentLetter] -= 1
itr = 0
for i in range(currentIndex + 1, n):
while rem[itr] == 0:
itr += 1
currentAnswer[i] = itr
rem[itr] -= 1
curString = convert(list(currentAnswer))
if curAnswer > curString > convertedS:
curAnswer = curString
good = True
if good:
l = m + 1
else:
r = m - 1
if curAnswer[0] == chr(ord('z') + 1) == 0:
print(-1)
else:
print(curAnswer)
``` | instruction | 0 | 62,523 | 0 | 125,046 |
No | output | 1 | 62,523 | 0 | 125,047 |
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 lowercase English letters and a number k. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by k. You are asked to find the lexicographically smallest beautiful string of length n, which is lexicographically greater or equal to string s. If such a string does not exist, output -1.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains a single integer T (1 ≤ T ≤ 10 000) — the number of test cases.
The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines.
The first line of the description contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the length of string s and number k respectively.
The second line contains string s consisting of lowercase English letters.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case output in a separate line lexicographically smallest beautiful string of length n, which is greater or equal to string s, or -1 if such a string does not exist.
Example
Input
4
4 2
abcd
3 1
abc
4 3
aaaa
9 3
abaabaaaa
Output
acac
abc
-1
abaabaaab
Note
In the first test case "acac" is greater than or equal to s, and each letter appears 2 or 0 times in it, so it is beautiful.
In the second test case each letter appears 0 or 1 times in s, so s itself is the answer.
We can show that there is no suitable string in the third test case.
In the fourth test case each letter appears 0, 3, or 6 times in "abaabaaab". All these integers are divisible by 3.
Submitted Solution:
```
def possible(s,index,letters,k,ans):
req = sum(letters)
give = len(s)-index
if req > give:
return False
if (give-req)%k != 0:
return False
while len(s) != index:
s.pop()
for i in range(give-req):
s.append('a')
for i in range(26):
for j in range(letters[i]):
s.append(chr(ord('a')+i))
ans.append(''.join(s))
return True
def solve(n,k,s,ans):
letters = [0]*26
for i in s:
letters[ord(i)-ord('a')] += 1
for i in range(26):
letters[i] %= k
if letters.count(0) == 26:
ans.append(s)
return
if n%k != 0:
ans.append('-1')
return
s = list(s)
for i in range(len(s)-1,-1,-1):
letters[ord(s[i])-ord('a')] -= 1
letters[ord(s[i])-ord('a')] %= k
prev = s[i]
for j in range(ord(s[i])-ord('a')+1,26):
s[i] = chr(ord('a')+j)
letters[j] += 1
letters[j] %= k
if possible(s,i+1,letters,k,ans):
return
s[i] = prev
letters[j] -= 1
letters[j] %= k
def main():
t = int(input())
ans = []
for i in range(t):
n,k = map(int,input().split())
s = input()
solve(n,k,s,ans)
print('\n'.join(ans))
main()
``` | instruction | 0 | 62,524 | 0 | 125,048 |
No | output | 1 | 62,524 | 0 | 125,049 |
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 lowercase English letters and a number k. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by k. You are asked to find the lexicographically smallest beautiful string of length n, which is lexicographically greater or equal to string s. If such a string does not exist, output -1.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains a single integer T (1 ≤ T ≤ 10 000) — the number of test cases.
The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines.
The first line of the description contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the length of string s and number k respectively.
The second line contains string s consisting of lowercase English letters.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case output in a separate line lexicographically smallest beautiful string of length n, which is greater or equal to string s, or -1 if such a string does not exist.
Example
Input
4
4 2
abcd
3 1
abc
4 3
aaaa
9 3
abaabaaaa
Output
acac
abc
-1
abaabaaab
Note
In the first test case "acac" is greater than or equal to s, and each letter appears 2 or 0 times in it, so it is beautiful.
In the second test case each letter appears 0 or 1 times in s, so s itself is the answer.
We can show that there is no suitable string in the third test case.
In the fourth test case each letter appears 0, 3, or 6 times in "abaabaaab". All these integers are divisible by 3.
Submitted Solution:
```
from collections import defaultdict
for _ in range(int(input())):
n,k = map(int,input().split())
d = defaultdict(int)
s = input()
last = -1
neededForPerfection = 0
for i in range(n):
if(s[i] != "z"):
ekUparKa = d[chr(ord(s[i]) + 1)] + 1
# Fetch the content for read only
extra = 0
if(ekUparKa % k != 0):
extra = k - (ekUparKa % k)
else:
extra = -1
fakeNeededforPerfection = neededForPerfection + extra
space = n - i - 1 - fakeNeededforPerfection
# if(i == n-1):
# print("SPecial")
# print("needed", neededForPerfection)
# print("Extra", extra)
# print(fakeNeededforPerfection)
# print(space)
if(space >= 0 and space % k == 0):
last = i
# Update real content
# First remove already added
extra = 0
ekUparKa = d[s[i]]
if(ekUparKa % k != 0):
extra = k - (ekUparKa % k)
neededForPerfection -= extra
# Update
d[s[i]]+=1
# Add again real content
extra = 0
ekUparKa = d[s[i]]
if(ekUparKa % k != 0):
extra = k - (ekUparKa % k)
neededForPerfection += extra
ok = True
for key in d:
if(d[key] % k != 0):
ok = False
break
if(ok):
print(s)
else:
if(last == -1):
print(-1)
elif(last == n - 1):
print(s[:last] + chr(ord(s[-1]) + 1))
else:
ans = s[:last]
ans += chr(ord(s[last])+ 1)
dc = defaultdict(int)
for i in ans:
dc[i] += 1
adding = []
for key in dc.keys():
count = dc[key]
extra = 0
if(count % k != 0):
extra = k - (count % k)
adding.extend([key for i in range(extra)])
pp = len(adding)
for i in range(n - len(ans) - pp):
adding.append('a')
adding.sort()
for i in adding:
ans += i
print(ans)
``` | instruction | 0 | 62,525 | 0 | 125,050 |
No | output | 1 | 62,525 | 0 | 125,051 |
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 lowercase English letters and a number k. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by k. You are asked to find the lexicographically smallest beautiful string of length n, which is lexicographically greater or equal to string s. If such a string does not exist, output -1.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains a single integer T (1 ≤ T ≤ 10 000) — the number of test cases.
The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines.
The first line of the description contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the length of string s and number k respectively.
The second line contains string s consisting of lowercase English letters.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case output in a separate line lexicographically smallest beautiful string of length n, which is greater or equal to string s, or -1 if such a string does not exist.
Example
Input
4
4 2
abcd
3 1
abc
4 3
aaaa
9 3
abaabaaaa
Output
acac
abc
-1
abaabaaab
Note
In the first test case "acac" is greater than or equal to s, and each letter appears 2 or 0 times in it, so it is beautiful.
In the second test case each letter appears 0 or 1 times in s, so s itself is the answer.
We can show that there is no suitable string in the third test case.
In the fourth test case each letter appears 0, 3, or 6 times in "abaabaaab". All these integers are divisible by 3.
Submitted Solution:
```
import sys
from sys import stdin
tt = int(stdin.readline())
alp = "abcdefghijklmnopqrstuvwxyz"
AAA = []
for loop in range(tt):
n,k = map(int,stdin.readline().split())
s = stdin.readline()[:-1]
if n % k != 0:
print (-1)
continue
oa = ord('a')
S = [ord(s[i])-oa for i in range(n)]
l,r = -1,n
ans = [25] * n
while r-l != 1:
mid = (l+r)//2
clis = [0] * 26
cnum = 0
nans = []
awayflag = False
ansflag = True
for i in range(n):
if i <= mid:
if clis[i] > 0:
nans.append(S[i])
clis[i] -= 1
elif cnum < n:
cnum += k
nans.append(S[i])
clis[S[i]] += k-1
else:
ansflag = False
break
elif awayflag == False: #want away
if S[i] == 25:
if clis[25] == 0:
ansflag = False
break
else:
clis[25] -= 1
nans.append(S[i])
elif clis[S[i]+1] > 0:
clis[S[i]+1] -= 1
nans.append(S[i]+1)
awayflag = True
elif cnum < n:
clis[S[i]+1] += k-1
cnum += k
nans.append(S[i]+1)
awayflag = True
else: #search
for nex in range(S[i]+1,26):
if clis[nex] > 0:
nans.append(nex)
clis[nex] -= 1
awayflag = True
break
else:
ansflag = False
break
else: #away
while cnum < n:
clis[0] += k
cnum += k
for nex in range(26):
if clis[nex] > 0:
nans.append(nex)
clis[nex] -= 1
break
if not ansflag:
r = mid
else:
l = mid
ans = min(ans,nans)
ANS = [alp[i] for i in ans]
print ("".join(ANS))
#print (l,r,file=sys.stderr)
``` | instruction | 0 | 62,526 | 0 | 125,052 |
No | output | 1 | 62,526 | 0 | 125,053 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Given a string s, determine if it contains any palindrome of length exactly 100 as a subsequence. If it has any, print any one of them. If it doesn't have any, print a palindrome that is a subsequence of s and is as long as possible.
Input
The only line of the input contains one string s of length n (1 ≤ n ≤ 5·104) containing only lowercase English letters.
Output
If s contains a palindrome of length exactly 100 as a subsequence, print any palindrome of length 100 which is a subsequence of s. If s doesn't contain any palindromes of length exactly 100, print a palindrome that is a subsequence of s and is as long as possible.
If there exists multiple answers, you are allowed to print any of them.
Examples
Input
bbbabcbbb
Output
bbbcbbb
Input
rquwmzexectvnbanemsmdufrg
Output
rumenanemur
Note
A subsequence of a string is a string that can be derived from it by deleting some characters without changing the order of the remaining characters. A palindrome is a string that reads the same forward or backward. | instruction | 0 | 62,629 | 0 | 125,258 |
Tags: constructive algorithms, dp
Correct Solution:
```
def p2(a):
n = len(a)
last = [[-1] * 26 for _ in range(n)]
last[0][ord(a[0])-97] = 0
for i in range(1, n):
for j in range(26):
last[i][j] = last[i-1][j]
last[i][ord(a[i]) - 97] = i
dp = [''] * n
for i in range(n-1, -1, -1):
for j in range(n-1, i, -1):
k = last[j][ord(a[i]) - 97]
if k > i:
if (k - i) == 1 and len(dp[j]) < 2:
dp[j] = a[i] + a[i]
elif len(dp[j]) < (len(dp[k-1]) + 2):
dp[j] = a[i] + dp[k - 1] + a[i]
if len(dp[j]) >= 100:
if len(dp[j]) == 101:
return dp[j][:50] + dp[j][51:]
else:
return dp[j]
dp[i] = a[i]
return dp[n-1]
a = input()
print(p2(a))
``` | output | 1 | 62,629 | 0 | 125,259 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Given a string s, determine if it contains any palindrome of length exactly 100 as a subsequence. If it has any, print any one of them. If it doesn't have any, print a palindrome that is a subsequence of s and is as long as possible.
Input
The only line of the input contains one string s of length n (1 ≤ n ≤ 5·104) containing only lowercase English letters.
Output
If s contains a palindrome of length exactly 100 as a subsequence, print any palindrome of length 100 which is a subsequence of s. If s doesn't contain any palindromes of length exactly 100, print a palindrome that is a subsequence of s and is as long as possible.
If there exists multiple answers, you are allowed to print any of them.
Examples
Input
bbbabcbbb
Output
bbbcbbb
Input
rquwmzexectvnbanemsmdufrg
Output
rumenanemur
Note
A subsequence of a string is a string that can be derived from it by deleting some characters without changing the order of the remaining characters. A palindrome is a string that reads the same forward or backward. | instruction | 0 | 62,630 | 0 | 125,260 |
Tags: constructive algorithms, dp
Correct 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()
def FACT(n, mod):
s = 1
facts = [1]
for i in range(1,n+1):
s*=i
s%=mod
facts.append(s)
return facts[n]
def C(n, k, mod):
return (FACT(n,mod) * pow((FACT(k,mod)*FACT(n-k,mod))%mod,mod-2, mod))%mod
st = list(SI())
d = [0 for i in range(26)]
for i in range(len(st)):
d[ord(st[i])-97]+=1
boo = False
letter = ""
for i in range(26):
if d[i] >= 100:
boo = True
letter = chr(i+97)
break
if boo:
print("".join([letter for i in range(100)]))
else:
rev = st[::-1]
n = len(st)
dp = [[0 for i in range(n+1)] for j in range(n+1)]
for i in range(1, n+1):
for j in range(1, n+1):
if st[i-1] == rev[j-1]:
dp[i][j] = dp[i-1][j-1]+1
else:
dp[i][j] = max(dp[i][j-1], dp[i-1][j])
ans = []
i = j = n
while i > 0 and j > 0:
if st[i-1] == rev[j-1]:
ans.append(st[i-1])
i-=1
j-=1
elif dp[i][j-1] > dp[i-1][j]:
j-=1
else:
i-=1
if len(ans)>100:
ans = ans[:50]+ans[-50:]
print("".join(ans))
``` | output | 1 | 62,630 | 0 | 125,261 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Given a string s, determine if it contains any palindrome of length exactly 100 as a subsequence. If it has any, print any one of them. If it doesn't have any, print a palindrome that is a subsequence of s and is as long as possible.
Input
The only line of the input contains one string s of length n (1 ≤ n ≤ 5·104) containing only lowercase English letters.
Output
If s contains a palindrome of length exactly 100 as a subsequence, print any palindrome of length 100 which is a subsequence of s. If s doesn't contain any palindromes of length exactly 100, print a palindrome that is a subsequence of s and is as long as possible.
If there exists multiple answers, you are allowed to print any of them.
Examples
Input
bbbabcbbb
Output
bbbcbbb
Input
rquwmzexectvnbanemsmdufrg
Output
rumenanemur
Note
A subsequence of a string is a string that can be derived from it by deleting some characters without changing the order of the remaining characters. A palindrome is a string that reads the same forward or backward. | instruction | 0 | 62,631 | 0 | 125,262 |
Tags: constructive algorithms, dp
Correct Solution:
```
from collections import defaultdict
s = input()
n = len(s)
if n >= 2600:
print(s[0] * 100)
elif n > 2574:
count = defaultdict(int)
for l in s:
count[l] += 1
max_l = s[0]
for l, c in count.items():
if c >= 100:
max_l = l
print(max_l * 100)
else:
data = defaultdict(dict)
def print_p(i, gap):
if gap == 1:
return s[i]
if gap == 2:
return s[i:i + 2]
return s[i] + print_p(data[i + 1][gap - 2][1], data[i + 1][gap - 2][2]) + s[i]
for i in range(n):
data[i][1] = (1, i, 1)
max_p = data[0][1]
for i in range(n - 1):
if s[i] == s[i + 1]:
data[i][2] = (2, i, 2)
max_p = data[i][2]
else:
data[i][2] = data[i][1]
output = None
for gap in range(3, n + 1):
for i in range(n - gap + 1):
j = i + gap - 1
if s[i] == s[j]:
size = data[i + 1][gap - 2][0] + 2
data[i][gap] = (size, i, gap)
if size > max_p[0]:
max_p = data[i][gap]
if size == 100:
output = print_p(i, gap)
if size == 101:
output = print_p(i, gap)
output = output[:50] + output[51:]
else:
if data[i][gap - 1][0] > data[i + 1][gap - 1][0]:
data[i][gap] = data[i][gap - 1]
else:
data[i][gap] = data[i + 1][gap - 1]
if output:
print(output)
else:
print(print_p(max_p[1], max_p[2]))
``` | output | 1 | 62,631 | 0 | 125,263 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Given a string s, determine if it contains any palindrome of length exactly 100 as a subsequence. If it has any, print any one of them. If it doesn't have any, print a palindrome that is a subsequence of s and is as long as possible.
Input
The only line of the input contains one string s of length n (1 ≤ n ≤ 5·104) containing only lowercase English letters.
Output
If s contains a palindrome of length exactly 100 as a subsequence, print any palindrome of length 100 which is a subsequence of s. If s doesn't contain any palindromes of length exactly 100, print a palindrome that is a subsequence of s and is as long as possible.
If there exists multiple answers, you are allowed to print any of them.
Examples
Input
bbbabcbbb
Output
bbbcbbb
Input
rquwmzexectvnbanemsmdufrg
Output
rumenanemur
Note
A subsequence of a string is a string that can be derived from it by deleting some characters without changing the order of the remaining characters. A palindrome is a string that reads the same forward or backward. | instruction | 0 | 62,632 | 0 | 125,264 |
Tags: constructive algorithms, dp
Correct Solution:
```
def p2(a):
n = len(a)
last = [[0] * 26 for _ in range(n)]
last[0][ord(a[0])-97] = 0
for i in range(1, n):
for j in range(26):
last[i][j] = last[i-1][j]
last[i][ord(a[i])-97] = i
dp = [''] * n
for i in range(n-1, -1, -1):
for j in range(n-1, i, -1):
k = last[j][ord(a[i])-97]
if k > i:
if (k - i) == 1 and len(dp[j]) < 2:
dp[j] = a[i] + a[i]
elif len(dp[j]) < (len(dp[k-1]) + 2):
dp[j] = a[i] + dp[k - 1] + a[i]
if len(dp[j]) >= 100:
if len(dp[j]) == 101:
return dp[j][:50] + dp[j][51:]
else:
return dp[j]
dp[i] = a[i]
return dp[n-1]
print(p2(input()))
``` | output | 1 | 62,632 | 0 | 125,265 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given a string s, determine if it contains any palindrome of length exactly 100 as a subsequence. If it has any, print any one of them. If it doesn't have any, print a palindrome that is a subsequence of s and is as long as possible.
Input
The only line of the input contains one string s of length n (1 ≤ n ≤ 5·104) containing only lowercase English letters.
Output
If s contains a palindrome of length exactly 100 as a subsequence, print any palindrome of length 100 which is a subsequence of s. If s doesn't contain any palindromes of length exactly 100, print a palindrome that is a subsequence of s and is as long as possible.
If there exists multiple answers, you are allowed to print any of them.
Examples
Input
bbbabcbbb
Output
bbbcbbb
Input
rquwmzexectvnbanemsmdufrg
Output
rumenanemur
Note
A subsequence of a string is a string that can be derived from it by deleting some characters without changing the order of the remaining characters. A palindrome is a string that reads the same forward or backward.
Submitted Solution:
```
def p2(a):
n = len(a)
last = [[-1] * 26 for _ in range(n)]
last[0][ord(a[0])-97] = 0
for i in range(1, n):
for j in range(26):
last[i][j] = last[i-1][j]
last[i][ord(a[i]) - 97] = i
dp = [''] * n
for i in range(n-1, -1, -1):
for j in range(n-1, i, -1):
k = last[j][ord(a[i]) - 97]
if k > i:
if (k - i) == 1 and len(dp[j]) < 2:
dp[j] = a[i] + a[i]
elif len(dp[j]) < (len(dp[k-1]) + 2):
dp[j] = a[i] + dp[k - 1] + a[i]
if len(dp[j]) >= 100:
if len(dp[j]) == 101:
print(dp[j][:50]+dp[j][51:])
else:
print(dp[j])
return
dp[i] = a[i]
return dp[n-1]
a = list(input())
print(p2(a))
``` | instruction | 0 | 62,633 | 0 | 125,266 |
No | output | 1 | 62,633 | 0 | 125,267 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given a string s, determine if it contains any palindrome of length exactly 100 as a subsequence. If it has any, print any one of them. If it doesn't have any, print a palindrome that is a subsequence of s and is as long as possible.
Input
The only line of the input contains one string s of length n (1 ≤ n ≤ 5·104) containing only lowercase English letters.
Output
If s contains a palindrome of length exactly 100 as a subsequence, print any palindrome of length 100 which is a subsequence of s. If s doesn't contain any palindromes of length exactly 100, print a palindrome that is a subsequence of s and is as long as possible.
If there exists multiple answers, you are allowed to print any of them.
Examples
Input
bbbabcbbb
Output
bbbcbbb
Input
rquwmzexectvnbanemsmdufrg
Output
rumenanemur
Note
A subsequence of a string is a string that can be derived from it by deleting some characters without changing the order of the remaining characters. A palindrome is a string that reads the same forward or backward.
Submitted Solution:
```
s = input()
n = len(s)
freq = [0 for i in range(0, 300)]
for c in s: freq[ord(c)] += 1
for c in 'abcdefghijklmnopqrstuvwxyz':
if freq[ord(c)] >= 100:
print(c*100)
exit()
dp = [[0 for i in range(0, n)] for i in range(0, n)]
sol = ''
def L(lo, hi):
if dp[lo][hi] != 0: return dp[lo][hi]
if lo == hi:
dp[lo][hi] = 1
return dp[lo][hi]
if lo + 1 == hi:
if s[lo] == s[hi]: dp[lo][hi] = 2
else: dp[lo][hi] = 1
return dp[lo][hi]
if s[lo] == s[hi]:
dp[lo][hi] = L(lo+1, hi-1) + 2
return dp[lo][hi]
dp[lo][hi] = max(L(lo+1, hi), L(lo, hi-1))
return dp[lo][hi]
def reconstruct(lo, hi):
global sol
if lo > hi: return
if lo == hi or lo + 1 == hi:
sol += s[lo]
return
if s[lo] == s[hi]:
sol += s[lo]
reconstruct(lo+1, hi-1)
return
if L(lo+1, hi) > L(lo, hi-1):
reconstruct(lo+1, hi)
return
else:
reconstruct(lo, hi-1)
return
for i in range(0, n):
for j in range(i+99, n):
if dp[i][j] >= 100 and dp[i][j] % 2 == 0:
reconstruct(i, j)
sol = sol + sol[::-1]
a, b = 0, len(sol)-1
while (b-a+1) % 2 == 0 and b-a+1 > 100: a += 1; b -= 1
print(sol[a:b+1])
exit()
reconstruct(0, n-1)
if L(0, n-1) % 2 == 1: sol = sol[0:len(sol)-1] + sol[::-1]
else: sol = sol + sol[::-1]
print(sol)
``` | instruction | 0 | 62,634 | 0 | 125,268 |
No | output | 1 | 62,634 | 0 | 125,269 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given a string s, determine if it contains any palindrome of length exactly 100 as a subsequence. If it has any, print any one of them. If it doesn't have any, print a palindrome that is a subsequence of s and is as long as possible.
Input
The only line of the input contains one string s of length n (1 ≤ n ≤ 5·104) containing only lowercase English letters.
Output
If s contains a palindrome of length exactly 100 as a subsequence, print any palindrome of length 100 which is a subsequence of s. If s doesn't contain any palindromes of length exactly 100, print a palindrome that is a subsequence of s and is as long as possible.
If there exists multiple answers, you are allowed to print any of them.
Examples
Input
bbbabcbbb
Output
bbbcbbb
Input
rquwmzexectvnbanemsmdufrg
Output
rumenanemur
Note
A subsequence of a string is a string that can be derived from it by deleting some characters without changing the order of the remaining characters. A palindrome is a string that reads the same forward or backward.
Submitted Solution:
```
out=[]
start=0
string=input()
end=len(string)-1
while True:
if start==end:break
final=end
while start!=final-1:
if string[start]==string[final]:
out.append(string[start])
end=final-1
break
final-=1
if start==end or start==end-1:break
start+=1
s=''
for i in out:
s+=i
if start==end:
if string[end+1]!=out[-1]:out.append(string[end+1])
else:
if string[end]!=out[-1]:out.append(string[end])
out.reverse()
for i in out:
s+=i
print(s)
``` | instruction | 0 | 62,635 | 0 | 125,270 |
No | output | 1 | 62,635 | 0 | 125,271 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given a string s, determine if it contains any palindrome of length exactly 100 as a subsequence. If it has any, print any one of them. If it doesn't have any, print a palindrome that is a subsequence of s and is as long as possible.
Input
The only line of the input contains one string s of length n (1 ≤ n ≤ 5·104) containing only lowercase English letters.
Output
If s contains a palindrome of length exactly 100 as a subsequence, print any palindrome of length 100 which is a subsequence of s. If s doesn't contain any palindromes of length exactly 100, print a palindrome that is a subsequence of s and is as long as possible.
If there exists multiple answers, you are allowed to print any of them.
Examples
Input
bbbabcbbb
Output
bbbcbbb
Input
rquwmzexectvnbanemsmdufrg
Output
rumenanemur
Note
A subsequence of a string is a string that can be derived from it by deleting some characters without changing the order of the remaining characters. A palindrome is a string that reads the same forward or backward.
Submitted Solution:
```
s = input()
dp = [[0 for i in range(0, len(s))] for i in range(0, len(s))]
found = [[False for i in range(0, len(s))] for i in range(0, len(s))]
sol = ''
mid = ''
def L(a, b):
if found[a][b]: return dp[a][b]
if a==b: dp[a][b] = s[a]
elif a + 1 == b:
if s[a] == s[b]: dp[a][b] = 2
else: dp[a][b] = 1
else:
if s[a] == s[b]:
dp[a][b] = 2 + L(a+1, b-1)
if dp[a][b] > 100: dp[a][b] = L(a+1, b-1)
else:
dp[a][b] = max(L(a+1, b), L(a, b-1))
found[a][b] = True
return dp[a][b]
def backtrace(a, b):
global sol
if a > b: return
if s[a] == s[b]:
sol += s[a]
backtrace(a+1, b-1)
return
if dp[a+1][b] > dp[a][b-1]: backtrace(a+1, b)
else: backtrace(a, b-1)
for c in 'abcdefghijklmnopqrstuvwxyz':
if s.count(c) >= 100:
print(c*100)
exit()
for i in range(0, len(s)):
dp[i][i] = 1
found[i][i] = True
L(0, len(s)-1)
backtrace(0, len(s)-1)
if L(0, len(s)-1) % 2 == 0: sol = sol + sol[::-1]
else: sol = sol[:len(sol)-1] + sol[::-1]
print(sol)
``` | instruction | 0 | 62,636 | 0 | 125,272 |
No | output | 1 | 62,636 | 0 | 125,273 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".
Given a string, you have to find two values:
1. the number of good substrings of even length;
2. the number of good substrings of odd length.
Input
The first line of the input contains a single string of length n (1 ≤ n ≤ 105). Each character of the string will be either 'a' or 'b'.
Output
Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.
Examples
Input
bb
Output
1 2
Input
baab
Output
2 4
Input
babb
Output
2 5
Input
babaa
Output
2 7
Note
In example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.
In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.
In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.
Definitions
A substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s1s2... sn is string slsl + 1... sr.
A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1. | instruction | 0 | 62,687 | 0 | 125,374 |
Tags: math
Correct Solution:
```
s = input()
odd = 0
even = 0
cntE = [0, 0]
cntO = [0, 0]
for i in range(len(s)):
cur = 0 + int(s[i] == 'b')
odd += 1
if i % 2 == 0:
odd += cntE[cur]
even += cntO[cur]
cntE[cur] += 1
else:
odd += cntO[cur]
even += cntE[cur]
cntO[cur] += 1
print(even, odd)
``` | output | 1 | 62,687 | 0 | 125,375 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".
Given a string, you have to find two values:
1. the number of good substrings of even length;
2. the number of good substrings of odd length.
Input
The first line of the input contains a single string of length n (1 ≤ n ≤ 105). Each character of the string will be either 'a' or 'b'.
Output
Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.
Examples
Input
bb
Output
1 2
Input
baab
Output
2 4
Input
babb
Output
2 5
Input
babaa
Output
2 7
Note
In example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.
In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.
In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.
Definitions
A substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s1s2... sn is string slsl + 1... sr.
A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1. | instruction | 0 | 62,688 | 0 | 125,376 |
Tags: math
Correct Solution:
```
def R(): return map(int, input().split())
def I(): return int(input())
def S(): return str(input())
def L(): return list(R())
from collections import Counter
import math
import sys
from itertools import permutations
import bisect
mod=10**9+7
#print(bisect.bisect_right([1,2,3],2))
#print(bisect.bisect_left([1,2,3],2))
s=S()
l=len(s)
A=[0]*2
B=[0]*2
for i in range(2):
A[i]=[0]*(l+3)
B[i]=[0]*(l+3)
for i in range(l):
for j in range(2):
if i%2!=j:
A[j][i]=A[j][i-1]
B[j][i]=B[j][i-1]
else:
A[j][i]=A[j][i-2]+(s[i]=='a')
B[j][i]=B[j][i-2]+(s[i]=='b')
ans=[0]*2
for i in range(l):
if s[i]=='a':
ans[0]+=A[1-i%2][i]
ans[1]+=A[i%2][i]
else:
ans[0]+=B[1-i%2][i]
ans[1]+=B[i%2][i]
print(ans[0],ans[1])
``` | output | 1 | 62,688 | 0 | 125,377 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".
Given a string, you have to find two values:
1. the number of good substrings of even length;
2. the number of good substrings of odd length.
Input
The first line of the input contains a single string of length n (1 ≤ n ≤ 105). Each character of the string will be either 'a' or 'b'.
Output
Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.
Examples
Input
bb
Output
1 2
Input
baab
Output
2 4
Input
babb
Output
2 5
Input
babaa
Output
2 7
Note
In example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.
In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.
In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.
Definitions
A substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s1s2... sn is string slsl + 1... sr.
A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1. | instruction | 0 | 62,689 | 0 | 125,378 |
Tags: math
Correct Solution:
```
s = input()
a = []
for c in s:
a.append(ord(c) - ord('a'))
cnt = [[0, 0], [0, 0]]
ans = [0, 0]
for i in range(len(a)):
cnt[a[i]][i % 2] += 1
ans[0] += cnt[a[i]][i % 2]
ans[1] += cnt[a[i]][1 - i % 2]
print(ans[1], ans[0])
``` | output | 1 | 62,689 | 0 | 125,379 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".
Given a string, you have to find two values:
1. the number of good substrings of even length;
2. the number of good substrings of odd length.
Input
The first line of the input contains a single string of length n (1 ≤ n ≤ 105). Each character of the string will be either 'a' or 'b'.
Output
Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.
Examples
Input
bb
Output
1 2
Input
baab
Output
2 4
Input
babb
Output
2 5
Input
babaa
Output
2 7
Note
In example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.
In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.
In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.
Definitions
A substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s1s2... sn is string slsl + 1... sr.
A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1. | instruction | 0 | 62,690 | 0 | 125,380 |
Tags: math
Correct Solution:
```
s = input()
cntodda = 0
cntoddb = 0
cntevena =0
cntevenb = 0
evencnt = 0
oddcnt = 0
for i in range(len(s)):
oddcnt += 1
if i%2 == 0:
if s[i]=='a':
evencnt += cntodda
oddcnt += cntevena
else:
evencnt += cntoddb
oddcnt += cntevenb
if s[i]=='a':
cntevena+=1
else:
cntevenb+=1
else:
if s[i]=='a':
evencnt += cntevena
oddcnt += cntodda
else:
evencnt += cntevenb
oddcnt += cntoddb
if s[i]=='a':
cntodda += 1
else:
cntoddb += 1
print(evencnt, oddcnt)
``` | output | 1 | 62,690 | 0 | 125,381 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".
Given a string, you have to find two values:
1. the number of good substrings of even length;
2. the number of good substrings of odd length.
Input
The first line of the input contains a single string of length n (1 ≤ n ≤ 105). Each character of the string will be either 'a' or 'b'.
Output
Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.
Examples
Input
bb
Output
1 2
Input
baab
Output
2 4
Input
babb
Output
2 5
Input
babaa
Output
2 7
Note
In example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.
In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.
In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.
Definitions
A substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s1s2... sn is string slsl + 1... sr.
A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1. | instruction | 0 | 62,691 | 0 | 125,382 |
Tags: math
Correct Solution:
```
cnt = [[0 for col in range(2)] for row in range(2)]
ans = [0 for col in range(2)]
strx = input()
length = len(strx)
for i in range(length):
if(strx[i]=='a'):
cnt[0][i & 1]=cnt[0][i & 1]+1
ans[0]+=cnt[0][i & 1 ^ 1]
ans[1]+=cnt[0][i & 1]
else:
cnt[1][i & 1]=cnt[1][i & 1]+1
ans[0]+=cnt[1][i & 1 ^ 1]
ans[1]+=cnt[1][i & 1]
print(ans[0],ans[1])
``` | output | 1 | 62,691 | 0 | 125,383 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".
Given a string, you have to find two values:
1. the number of good substrings of even length;
2. the number of good substrings of odd length.
Input
The first line of the input contains a single string of length n (1 ≤ n ≤ 105). Each character of the string will be either 'a' or 'b'.
Output
Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.
Examples
Input
bb
Output
1 2
Input
baab
Output
2 4
Input
babb
Output
2 5
Input
babaa
Output
2 7
Note
In example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.
In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.
In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.
Definitions
A substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s1s2... sn is string slsl + 1... sr.
A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1. | instruction | 0 | 62,692 | 0 | 125,384 |
Tags: math
Correct Solution:
```
string=input()
length=len(string)
goodbad=[[1, 0, 0, 0] for x in range(length)]
#good odd
#bad odd
#good even
#bad even
for i in range(length-1):
if string[i]==string[i+1]:
goodbad[i+1][0]+=goodbad[i][2]
goodbad[i+1][2]+=goodbad[i][0]
goodbad[i+1][1]+=goodbad[i][3]
goodbad[i+1][3]+=goodbad[i][1]
else:
goodbad[i+1][3]+=goodbad[i][0]
goodbad[i+1][0]+=goodbad[i][3]
goodbad[i+1][1]+=goodbad[i][2]
goodbad[i+1][2]+=goodbad[i][1]
oddct=0
evenct=0
for i in range(len(goodbad)):
oddct+=goodbad[i][0]
evenct+=goodbad[i][2]
print(evenct, oddct)
``` | output | 1 | 62,692 | 0 | 125,385 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".
Given a string, you have to find two values:
1. the number of good substrings of even length;
2. the number of good substrings of odd length.
Input
The first line of the input contains a single string of length n (1 ≤ n ≤ 105). Each character of the string will be either 'a' or 'b'.
Output
Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.
Examples
Input
bb
Output
1 2
Input
baab
Output
2 4
Input
babb
Output
2 5
Input
babaa
Output
2 7
Note
In example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.
In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.
In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.
Definitions
A substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s1s2... sn is string slsl + 1... sr.
A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1. | instruction | 0 | 62,693 | 0 | 125,386 |
Tags: math
Correct Solution:
```
import sys
input=sys.stdin.readline
s=input().rstrip()
n=len(s)
pos_a_odd=0
pos_a_even=0
pos_b_odd=0
pos_b_even=0
ans_even,ans_odd=0,0
for i in range(n):
if s[i]=="a":
if i%2:
pos_a_odd+=1
ans_odd+=pos_a_odd
ans_even+=pos_a_even
else:
pos_a_even+=1
ans_odd+=pos_a_even
ans_even+=pos_a_odd
else:
if i%2:
pos_b_odd+=1
ans_odd+=pos_b_odd
ans_even+=pos_b_even
else:
pos_b_even+=1
ans_odd+=pos_b_even
ans_even+=pos_b_odd
print(ans_even,ans_odd)
``` | output | 1 | 62,693 | 0 | 125,387 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".
Given a string, you have to find two values:
1. the number of good substrings of even length;
2. the number of good substrings of odd length.
Input
The first line of the input contains a single string of length n (1 ≤ n ≤ 105). Each character of the string will be either 'a' or 'b'.
Output
Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.
Examples
Input
bb
Output
1 2
Input
baab
Output
2 4
Input
babb
Output
2 5
Input
babaa
Output
2 7
Note
In example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.
In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.
In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.
Definitions
A substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s1s2... sn is string slsl + 1... sr.
A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1. | instruction | 0 | 62,694 | 0 | 125,388 |
Tags: math
Correct Solution:
```
s = input()
m = [2*[0] for _ in range(2)]
odd, even = 0, 0
for i in range(len(s)):
m[1 if s[i] == 'a' else 0][i % 2] += 1
odd += m[1 if s[i] == 'a' else 0][i % 2]
even += m[1 if s[i] == 'a' else 0][not (i % 2)]
print(even, odd)
``` | output | 1 | 62,694 | 0 | 125,389 |
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response.
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".
Given a string, you have to find two values:
1. the number of good substrings of even length;
2. the number of good substrings of odd length.
Input
The first line of the input contains a single string of length n (1 ≤ n ≤ 105). Each character of the string will be either 'a' or 'b'.
Output
Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.
Examples
Input
bb
Output
1 2
Input
baab
Output
2 4
Input
babb
Output
2 5
Input
babaa
Output
2 7
Note
In example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.
In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.
In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.
Definitions
A substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s1s2... sn is string slsl + 1... sr.
A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1.
Submitted Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
mod=10**9+7
def ni():
return int(raw_input())
def li():
return map(int,raw_input().split())
def pn(n):
stdout.write(str(n)+'\n')
def pa(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return map(int,stdin.read().split())
range = xrange # not for python 3.0+
# main code
s=raw_input().strip()
n=len(s)
a1,a2=Counter(),Counter()
ans1,ans2=0,0
for i in range(n):
ans1+=1
if i%2==0:
ans1+=a2[s[i]]
ans2+=a1[s[i]]
a2[s[i]]+=1
else:
ans1+=a1[s[i]]
ans2+=a2[s[i]]
a1[s[i]]+=1
pa([ans2,ans1])
``` | instruction | 0 | 62,695 | 0 | 125,390 |
Yes | output | 1 | 62,695 | 0 | 125,391 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".
Given a string, you have to find two values:
1. the number of good substrings of even length;
2. the number of good substrings of odd length.
Input
The first line of the input contains a single string of length n (1 ≤ n ≤ 105). Each character of the string will be either 'a' or 'b'.
Output
Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.
Examples
Input
bb
Output
1 2
Input
baab
Output
2 4
Input
babb
Output
2 5
Input
babaa
Output
2 7
Note
In example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.
In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.
In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.
Definitions
A substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s1s2... sn is string slsl + 1... sr.
A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1.
Submitted Solution:
```
t = input()
n = len(t)
t = [-1] + [i for i in range(n - 1) if t[i] != t[i + 1]] + [n - 1]
n = len(t) - 1
u, v = [0] * n, [0] * n
for i in range(n):
d = t[i + 1] - t[i]
k = d // 2
u[i] = v[i] = k
if d & 1:
if t[i] & 1: v[i] += 1
else: u[i] += 1
i += 1
a = sum(u[i] for i in range(0, n, 2))
b = sum(v[i] for i in range(0, n, 2))
c = sum(u[i] for i in range(1, n, 2))
d = sum(v[i] for i in range(1, n, 2))
print(a * b + c * d, (a * (a + 1) + b * (b + 1) + c * (c + 1) + d * (d + 1)) // 2)
``` | instruction | 0 | 62,696 | 0 | 125,392 |
Yes | output | 1 | 62,696 | 0 | 125,393 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".
Given a string, you have to find two values:
1. the number of good substrings of even length;
2. the number of good substrings of odd length.
Input
The first line of the input contains a single string of length n (1 ≤ n ≤ 105). Each character of the string will be either 'a' or 'b'.
Output
Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.
Examples
Input
bb
Output
1 2
Input
baab
Output
2 4
Input
babb
Output
2 5
Input
babaa
Output
2 7
Note
In example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.
In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.
In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.
Definitions
A substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s1s2... sn is string slsl + 1... sr.
A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1.
Submitted Solution:
```
def main():
s = input()
a = [0, 0]
b = [0, 0]
res = [0, 0]
for i, c in enumerate(s, 1):
ii, ij = i%2, (i+1)%2
_a = a if c == 'a' else b
res[1] += _a[ii] + 1
res[0] += _a[ij]
_a[ii] += 1
print(*res)
if __name__ == '__main__':
main()
``` | instruction | 0 | 62,697 | 0 | 125,394 |
Yes | output | 1 | 62,697 | 0 | 125,395 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".
Given a string, you have to find two values:
1. the number of good substrings of even length;
2. the number of good substrings of odd length.
Input
The first line of the input contains a single string of length n (1 ≤ n ≤ 105). Each character of the string will be either 'a' or 'b'.
Output
Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.
Examples
Input
bb
Output
1 2
Input
baab
Output
2 4
Input
babb
Output
2 5
Input
babaa
Output
2 7
Note
In example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.
In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.
In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.
Definitions
A substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s1s2... sn is string slsl + 1... sr.
A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1.
Submitted Solution:
```
'''input
babaa
'''
from sys import stdin
# main starts
string = list(stdin.readline().strip())
odd_a = 0; even_a = 0; odd_b = 0; even_b = 0
even = 0
odd = 0
for i in string:
if i == 'a':
temp = odd_a
odd_a = even_a + 1
even_a = temp
even_b, odd_b = odd_b, even_b
odd += odd_a
even += even_a
else:
temp = odd_b
odd_b = even_b + 1
even_b = temp
even_a, odd_a = odd_a, even_a
odd += odd_b
even += even_b
print(even, odd)
``` | instruction | 0 | 62,698 | 0 | 125,396 |
Yes | output | 1 | 62,698 | 0 | 125,397 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".
Given a string, you have to find two values:
1. the number of good substrings of even length;
2. the number of good substrings of odd length.
Input
The first line of the input contains a single string of length n (1 ≤ n ≤ 105). Each character of the string will be either 'a' or 'b'.
Output
Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.
Examples
Input
bb
Output
1 2
Input
baab
Output
2 4
Input
babb
Output
2 5
Input
babaa
Output
2 7
Note
In example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.
In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.
In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.
Definitions
A substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s1s2... sn is string slsl + 1... sr.
A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1.
Submitted Solution:
```
s = input()
oddc = {'a':0,'b':0}
evenc = {'a':0,'b':0}
odd = 0
even = 0
for i in range(len(s)):
odd+=1
if i%2 == 0:
even += oddc[s[i]]
odd += evenc[s[i]]
evenc[s[i]]+=1
else:
even += evenc[s[i]]
odd += oddc[s[i]]
oddc[s[i]]+=1
print(str(even) + " " + str(odd))
``` | instruction | 0 | 62,699 | 0 | 125,398 |
Yes | output | 1 | 62,699 | 0 | 125,399 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".
Given a string, you have to find two values:
1. the number of good substrings of even length;
2. the number of good substrings of odd length.
Input
The first line of the input contains a single string of length n (1 ≤ n ≤ 105). Each character of the string will be either 'a' or 'b'.
Output
Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.
Examples
Input
bb
Output
1 2
Input
baab
Output
2 4
Input
babb
Output
2 5
Input
babaa
Output
2 7
Note
In example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.
In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.
In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.
Definitions
A substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s1s2... sn is string slsl + 1... sr.
A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1.
Submitted Solution:
```
from sys import stdin, stdout, setrecursionlimit
input = stdin.readline
# import string
# characters = string.ascii_lowercase
# digits = string.digits
# setrecursionlimit(int(1e6))
# dir = [-1,0,1,0,-1]
# moves = 'NESW'
inf = float('inf')
from functools import cmp_to_key
from collections import defaultdict as dd
from collections import Counter, deque
from heapq import *
import math
from math import floor, ceil, sqrt
def geti(): return map(int, input().strip().split())
def getl(): return list(map(int, input().strip().split()))
def getis(): return map(str, input().strip().split())
def getls(): return list(map(str, input().strip().split()))
def gets(): return input().strip()
def geta(): return int(input())
def print_s(s): stdout.write(s+'\n')
def solve():
s = gets()
n = len(s)
stack = []
char = s[0]
count = 1
for i in range(1, n):
if s[i] == s[i-1]:
count += 1
else:
stack.append((char, count))
count = 1
char = s[i]
stack.append((char, count))
even = 0
odd = len(s)
n = len(stack)
# print(stack)
for i in range(n):
l = i-1
r = i+1
odd += (stack[i][1]-1) // 2
even += stack[i][1] // 2
total = stack[i][1]
# print(odd, even)
while l >= 0 and r < n and stack[l][0] == stack[r][0]:
now = stack[l][1] * stack[r][1]
if total & 1 == 0:
odd += now//2
even += (now+1)//2
else:
odd += (now+1)//2
even += now//2
if stack[l][1] == stack[r][1]:
total += stack[l][1] + stack[r][1]
l -= 1
r += 1
else:
break
print(even, odd)
if __name__=='__main__':
solve()
``` | instruction | 0 | 62,700 | 0 | 125,400 |
No | output | 1 | 62,700 | 0 | 125,401 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".
Given a string, you have to find two values:
1. the number of good substrings of even length;
2. the number of good substrings of odd length.
Input
The first line of the input contains a single string of length n (1 ≤ n ≤ 105). Each character of the string will be either 'a' or 'b'.
Output
Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.
Examples
Input
bb
Output
1 2
Input
baab
Output
2 4
Input
babb
Output
2 5
Input
babaa
Output
2 7
Note
In example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.
In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.
In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.
Definitions
A substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s1s2... sn is string slsl + 1... sr.
A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1.
Submitted Solution:
```
string=input()
length=len(string)
goodbad=[[0, 1, 0, 0]]*length
for i in range(length-1):
if string[i]==string[i+1]:
goodbad[i+1][0]+=goodbad[i][1]
goodbad[i+1][2]+=goodbad[i][3]
goodbad[i+1][1]+=goodbad[i][0]
goodbad[i+1][3]+=goodbad[i][2]
else:
goodbad[i+1][3]+=goodbad[i][0]
goodbad[i+1][0]+=goodbad[i][3]
goodbad[i+1][1]+=goodbad[i][2]
goodbad[i+1][2]+=goodbad[i][1]
oddct=0
evenct=0
for i in range(len(goodbad)-1):
oddct+=goodbad[i][0]
evenct+=goodbad[i][1]
print(evenct, oddct)
``` | instruction | 0 | 62,701 | 0 | 125,402 |
No | output | 1 | 62,701 | 0 | 125,403 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".
Given a string, you have to find two values:
1. the number of good substrings of even length;
2. the number of good substrings of odd length.
Input
The first line of the input contains a single string of length n (1 ≤ n ≤ 105). Each character of the string will be either 'a' or 'b'.
Output
Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.
Examples
Input
bb
Output
1 2
Input
baab
Output
2 4
Input
babb
Output
2 5
Input
babaa
Output
2 7
Note
In example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.
In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.
In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.
Definitions
A substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s1s2... sn is string slsl + 1... sr.
A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1.
Submitted Solution:
```
st = input()
def palindromes(string):
letters_counter = [{'a': 0, 'b': 0}, {'a': 0, 'b': 0}]
palindromes_counter = [0, len(st)]
for i in range(len(st)):
palindromes_counter[0] += letters_counter[i % 2][st[i]]
palindromes_counter[1] += letters_counter[pow(0, i % 2)][st[i]]
letters_counter[i % 2][st[i]] += 1
return palindromes_counter
for i in palindromes(st):
print(i,end = ' ')
``` | instruction | 0 | 62,702 | 0 | 125,404 |
No | output | 1 | 62,702 | 0 | 125,405 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".
Given a string, you have to find two values:
1. the number of good substrings of even length;
2. the number of good substrings of odd length.
Input
The first line of the input contains a single string of length n (1 ≤ n ≤ 105). Each character of the string will be either 'a' or 'b'.
Output
Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.
Examples
Input
bb
Output
1 2
Input
baab
Output
2 4
Input
babb
Output
2 5
Input
babaa
Output
2 7
Note
In example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.
In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.
In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.
Definitions
A substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s1s2... sn is string slsl + 1... sr.
A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1.
Submitted Solution:
```
from sys import stdin, stdout, setrecursionlimit
input = stdin.readline
# import string
# characters = string.ascii_lowercase
# digits = string.digits
# setrecursionlimit(int(1e6))
# dir = [-1,0,1,0,-1]
# moves = 'NESW'
inf = float('inf')
from functools import cmp_to_key
from collections import defaultdict as dd
from collections import Counter, deque
from heapq import *
import math
from math import floor, ceil, sqrt
def geti(): return map(int, input().strip().split())
def getl(): return list(map(int, input().strip().split()))
def getis(): return map(str, input().strip().split())
def getls(): return list(map(str, input().strip().split()))
def gets(): return input().strip()
def geta(): return int(input())
def print_s(s): stdout.write(s+'\n')
def solve():
s = gets()
n = len(s)
stack = []
char = s[0]
count = 1
for i in range(1, n):
if s[i] == s[i-1]:
count += 1
else:
stack.append((char, count))
count = 1
char = s[i]
stack.append((char, count))
even = 0
odd = len(s)
n = len(stack)
for i in range(n):
l = i-1
r = i+1
odd += (stack[i][1] - 1) // 2
even += stack[i][1] // 2
while l >= 0 and r < n and stack[l][0] == stack[r][0]:
now = stack[l][1] * stack[r][1]
if stack[i][1] & 1 == 0:
odd += now//2
even += (now+1)//2
else:
odd += (now+1)//2
even += now//2
# if (stack[i][1] + stack[r][1] + stack[l][1]) & 1:
# odd += now
# else:
# even += now
if stack[l][1] == stack[r][1]:
l -= 1
r += 1
else:
break
print(even, odd)
if __name__=='__main__':
solve()
``` | instruction | 0 | 62,703 | 0 | 125,406 |
No | output | 1 | 62,703 | 0 | 125,407 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A string is binary, if it consists only of characters "0" and "1".
String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.
You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
Input
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
Output
Print the single number — the number of substrings of the given string, containing exactly k characters "1".
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
1
1010
Output
6
Input
2
01010
Output
4
Input
100
01010
Output
0
Note
In the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".
In the second sample the sought substrings are: "101", "0101", "1010", "01010". | instruction | 0 | 63,402 | 0 | 126,804 |
Tags: binary search, brute force, dp, math, strings, two pointers
Correct Solution:
```
k=int(input())
s=input()
n=len(s)
i1=0
dp=[0]*(n)
cnt=0
ind=[0]
if k==0:
ocnt=0
ans=0
for i in range(n):
if s[i]=='0':
ocnt+=1
else:
ans += max((ocnt*(ocnt+1))//2,0)
ocnt=0
ans+=max((ocnt*(ocnt+1))//2,0)
print(ans)
else:
for i in range(n):
if s[i]=='1':
cnt+=1
ind.append(i+1)
if cnt>=k:
dp[i]=ind[-k]-ind[-k-1]
else:
dp[i]=dp[i-1]
print(sum(dp))
``` | output | 1 | 63,402 | 0 | 126,805 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A string is binary, if it consists only of characters "0" and "1".
String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.
You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
Input
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
Output
Print the single number — the number of substrings of the given string, containing exactly k characters "1".
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
1
1010
Output
6
Input
2
01010
Output
4
Input
100
01010
Output
0
Note
In the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".
In the second sample the sought substrings are: "101", "0101", "1010", "01010". | instruction | 0 | 63,403 | 0 | 126,806 |
Tags: binary search, brute force, dp, math, strings, two pointers
Correct Solution:
```
k = int(input())
d = [0]*1000001
d[0] = 1
s = 0
for c in input():
s += int(c)
d[s] += 1
res = 0
if k == 0:
for i in range(k, s+1):
res += (d[i]-1)*d[i]//2
else:
for i in range(k, s+1):
res += d[i]*d[i-k]
print(res)
``` | output | 1 | 63,403 | 0 | 126,807 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A string is binary, if it consists only of characters "0" and "1".
String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.
You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
Input
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
Output
Print the single number — the number of substrings of the given string, containing exactly k characters "1".
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
1
1010
Output
6
Input
2
01010
Output
4
Input
100
01010
Output
0
Note
In the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".
In the second sample the sought substrings are: "101", "0101", "1010", "01010". | instruction | 0 | 63,404 | 0 | 126,808 |
Tags: binary search, brute force, dp, math, strings, two pointers
Correct Solution:
```
n = int(input())
s = input()
a = [len(x)+1 for x in s.split('1')]
if n == 0:
print(sum(x *(x-1) // 2 for x in a))
else:
print(sum(a * b for (a, b) in zip(a, a[n:])))
``` | output | 1 | 63,404 | 0 | 126,809 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A string is binary, if it consists only of characters "0" and "1".
String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.
You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
Input
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
Output
Print the single number — the number of substrings of the given string, containing exactly k characters "1".
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
1
1010
Output
6
Input
2
01010
Output
4
Input
100
01010
Output
0
Note
In the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".
In the second sample the sought substrings are: "101", "0101", "1010", "01010". | instruction | 0 | 63,405 | 0 | 126,810 |
Tags: binary search, brute force, dp, math, strings, two pointers
Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
# import time,random,resource
# sys.setrecursionlimit(10**6)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)
def IF(c, t, f): return t if c else f
def YES(c): return IF(c, "YES", "NO")
def Yes(c): return IF(c, "Yes", "No")
def main():
t = 1#I()
rr = []
for _ in range(t):
k = I()
s = S()
a = []
c = 0
for t in s:
if t == '0':
c += 1
else:
a.append(c)
c = 0
r = 0
if k == 0:
a.append(c)
for c in a:
r += c + c * (c-1) // 2
else:
b = []
c = 0
for t in s[::-1]:
if t == '0':
c += 1
else:
b.append(c)
c = 0
for d,e in zip(a,b[::-1][k-1:]):
r += (d+1) * (e+1)
rr.append(r)
return JA(rr, "\n")
print(main())
``` | output | 1 | 63,405 | 0 | 126,811 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A string is binary, if it consists only of characters "0" and "1".
String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.
You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
Input
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
Output
Print the single number — the number of substrings of the given string, containing exactly k characters "1".
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
1
1010
Output
6
Input
2
01010
Output
4
Input
100
01010
Output
0
Note
In the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".
In the second sample the sought substrings are: "101", "0101", "1010", "01010". | instruction | 0 | 63,406 | 0 | 126,812 |
Tags: binary search, brute force, dp, math, strings, two pointers
Correct Solution:
```
k=int(input())
s=input()
ans,z=0,0
dp=[1]+[0]*10**6
for c in s:
if c=='1':z+=1
if z>=k:ans+=dp[z-k]
dp[z]+=1
print(ans)
``` | output | 1 | 63,406 | 0 | 126,813 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A string is binary, if it consists only of characters "0" and "1".
String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.
You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
Input
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
Output
Print the single number — the number of substrings of the given string, containing exactly k characters "1".
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
1
1010
Output
6
Input
2
01010
Output
4
Input
100
01010
Output
0
Note
In the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".
In the second sample the sought substrings are: "101", "0101", "1010", "01010". | instruction | 0 | 63,407 | 0 | 126,814 |
Tags: binary search, brute force, dp, math, strings, two pointers
Correct Solution:
```
k = int(input())
s = input()
n = len(s)
a = [0]*n
dict = {}
count = 0
for i in range(n):
if s[i] == "1":
count+=1
if count in dict:
dict[count]+=1
else:
dict[count] = 1
# print(dict)
ans = 0
count = 0
for i in range(n):
if k in dict:
ans+=dict[k]
if s[i] == "1":
k+=1
count+=1
if count in dict:
dict[count]-=1
print(ans)
``` | output | 1 | 63,407 | 0 | 126,815 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A string is binary, if it consists only of characters "0" and "1".
String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.
You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
Input
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
Output
Print the single number — the number of substrings of the given string, containing exactly k characters "1".
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
1
1010
Output
6
Input
2
01010
Output
4
Input
100
01010
Output
0
Note
In the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".
In the second sample the sought substrings are: "101", "0101", "1010", "01010". | instruction | 0 | 63,408 | 0 | 126,816 |
Tags: binary search, brute force, dp, math, strings, two pointers
Correct Solution:
```
k = int(input())
s= (input())
n = len(s)
count = [0]*(n+1)
count[0]+=1
ini = 0
if(k==0):
ans =0
ini =0
s= s+"1"
for i in range(n+1):
if( s[i] == "1"):
ans =ans+ ini*(ini+1)//2
ini=0
else:
ini+=1
print(ans)
else:
for i in s:
if(i=="1"):
ini +=1
count[ini]+=1
ans = 0
for i in range(k,n+1):
ans+=count[i]*count[i-k]
print(ans)
``` | output | 1 | 63,408 | 0 | 126,817 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A string is binary, if it consists only of characters "0" and "1".
String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.
You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
Input
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
Output
Print the single number — the number of substrings of the given string, containing exactly k characters "1".
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
1
1010
Output
6
Input
2
01010
Output
4
Input
100
01010
Output
0
Note
In the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".
In the second sample the sought substrings are: "101", "0101", "1010", "01010". | instruction | 0 | 63,409 | 0 | 126,818 |
Tags: binary search, brute force, dp, math, strings, two pointers
Correct Solution:
```
import sys
input=sys.stdin.readline
a=int(input())
s=input()
ans=[]
count=0
for i in range(len(s)):
if(s[i]=='0'):
count+=1
else:
ans.append(count)
count=0
ans.append(count)
if(a==0):
total=0
for i in range(len(ans)-1):
r=ans[i]
total=total+(r*(r+1)//2)
total=total+(ans[-1]*(ans[-1]+1)//2)
print(total)
exit()
start=1
end=a
total=0
ra=s.count('1')
while(end<=ra):
total=total+(ans[start-1]+1)*(ans[end]+1)
start=start+1
end=end+1
print(total)
``` | output | 1 | 63,409 | 0 | 126,819 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A string is binary, if it consists only of characters "0" and "1".
String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.
You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
Input
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
Output
Print the single number — the number of substrings of the given string, containing exactly k characters "1".
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
1
1010
Output
6
Input
2
01010
Output
4
Input
100
01010
Output
0
Note
In the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".
In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Submitted Solution:
```
def main():
k = int(input())
s = "1" + input() + "1"
ans = 0
q = []
for i in range(len(s)):
if(s[i] == "1"):
q.append(i)
for i in range(len(q) - k - 1):
x, y = q[i], q[i + k + 1]
l, r = q[i + 1], q[i + k]
if(k == 0):
a = (y - x)
ans += a * (a - 1)//2
else:
ans += (l - x) * (y - r)
print(ans)
main()
``` | instruction | 0 | 63,410 | 0 | 126,820 |
Yes | output | 1 | 63,410 | 0 | 126,821 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A string is binary, if it consists only of characters "0" and "1".
String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.
You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
Input
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
Output
Print the single number — the number of substrings of the given string, containing exactly k characters "1".
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
1
1010
Output
6
Input
2
01010
Output
4
Input
100
01010
Output
0
Note
In the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".
In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Submitted Solution:
```
import re
k = int(input())
num1 = '1' + input() + '1'
sum_num = 0
st = '1' * (k + 1)
if 0 < k < 8 :
num = re.sub(r'[1]{10,}', st, num1)
sum_num = len(num1) - len(num)
else:
num = num1
num_one = [i for i,v in enumerate(num) if v == '1']
for i in range(1,len(num_one) - k) :
if k == 0:
temp = num_one[i] - num_one[i-1] - 1
sum_num += temp * (temp + 1) // 2
else :
temp = (num_one[i] - num_one[i-1]) * (num_one[i + k] - num_one[i + k - 1])
sum_num += temp
print(sum_num)
``` | instruction | 0 | 63,411 | 0 | 126,822 |
Yes | output | 1 | 63,411 | 0 | 126,823 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A string is binary, if it consists only of characters "0" and "1".
String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.
You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
Input
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.
Output
Print the single number — the number of substrings of the given string, containing exactly k characters "1".
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
1
1010
Output
6
Input
2
01010
Output
4
Input
100
01010
Output
0
Note
In the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".
In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Submitted Solution:
```
from sys import stdin,stdout
from bisect import bisect,bisect_left
k=int(input())
s=stdin.readline().rstrip('\n')
if k==0:
l1=s.split('1')
ans=0
for i in l1:
ln=len(i)
ans+=(ln*(ln+1))//2
else:
l=[0]
c=0
for i in s:
if i=='1':
c+=1
l.append(c)
n=len(s)
ans=0
for i in range(1,n+1):
a=bisect(l,l[i-1]+k)
b=bisect_left(l,l[i-1]+k)
ans+=a-b
print(ans)
``` | instruction | 0 | 63,412 | 0 | 126,824 |
Yes | output | 1 | 63,412 | 0 | 126,825 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.