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.
The only difference between easy and hard versions is the size of the input.
You are given a string s consisting of n characters, each character is 'R', 'G' or 'B'.
You are also given an integer k. Your task is to change the minimum number of characters in the initial string s so that after the changes there will be a string of length k that is a substring of s, and is also a substring of the infinite string "RGBRGBRGB ...".
A string a is a substring of string b if there exists a positive integer i such that a_1 = b_i, a_2 = b_{i + 1}, a_3 = b_{i + 2}, ..., a_{|a|} = b_{i + |a| - 1}. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 2 ⋅ 10^5) — the number of queries. Then q queries follow.
The first line of the query contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the length of the string s and the length of the substring.
The second line of the query contains a string s consisting of n characters 'R', 'G' and 'B'.
It is guaranteed that the sum of n over all queries does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each query print one integer — the minimum number of characters you need to change in the initial string s so that after changing there will be a substring of length k in s that is also a substring of the infinite string "RGBRGBRGB ...".
Example
Input
3
5 2
BGGGG
5 3
RBRGR
5 5
BBBRR
Output
1
0
3
Note
In the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".
In the second example, the substring is "BRG". | instruction | 0 | 67,347 | 0 | 134,694 |
Tags: data structures, dp, implementation, two pointers
Correct Solution:
```
from sys import stdin
input=stdin.readline
R = lambda:map(int,input().split())
q, = R()
a = 'RGB'
for q1 in range(q):
an =[300000]*3
n,k = R()
s = input()
for i2 in range(3):
ans = [0]*n
m = 0
for i in range(n):
ans[i]=s[i]==a[(i+i2)%3]
m += ans[i]==0
if i>=k:
m-=ans[i-k]==0
if i >= k-1:
an[i2]=min(an[i2],m)
print(min(an))
``` | output | 1 | 67,347 | 0 | 134,695 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is the size of the input.
You are given a string s consisting of n characters, each character is 'R', 'G' or 'B'.
You are also given an integer k. Your task is to change the minimum number of characters in the initial string s so that after the changes there will be a string of length k that is a substring of s, and is also a substring of the infinite string "RGBRGBRGB ...".
A string a is a substring of string b if there exists a positive integer i such that a_1 = b_i, a_2 = b_{i + 1}, a_3 = b_{i + 2}, ..., a_{|a|} = b_{i + |a| - 1}. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 2 ⋅ 10^5) — the number of queries. Then q queries follow.
The first line of the query contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the length of the string s and the length of the substring.
The second line of the query contains a string s consisting of n characters 'R', 'G' and 'B'.
It is guaranteed that the sum of n over all queries does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each query print one integer — the minimum number of characters you need to change in the initial string s so that after changing there will be a substring of length k in s that is also a substring of the infinite string "RGBRGBRGB ...".
Example
Input
3
5 2
BGGGG
5 3
RBRGR
5 5
BBBRR
Output
1
0
3
Note
In the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".
In the second example, the substring is "BRG". | instruction | 0 | 67,348 | 0 | 134,696 |
Tags: data structures, dp, implementation, two pointers
Correct Solution:
```
from sys import stdin
input=stdin.readline
for _ in range(int(input())):
n,k=map(int,input().split())
s=list(input())
ans=10**9
a=['R','G','B']
for l in range(3):
x=l
dp=[0]*(n+1)
cnt=10**9
for i in range(n):
if s[i]!=a[x]:
dp[i+1]=dp[i]+1
else: dp[i+1]=dp[i]
x=(x+1)%3
for i in range(1,n-k+2):
cnt=min(cnt,dp[i+k-1]-dp[i-1])
ans=min(cnt,ans)
print(ans)
``` | output | 1 | 67,348 | 0 | 134,697 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is the size of the input.
You are given a string s consisting of n characters, each character is 'R', 'G' or 'B'.
You are also given an integer k. Your task is to change the minimum number of characters in the initial string s so that after the changes there will be a string of length k that is a substring of s, and is also a substring of the infinite string "RGBRGBRGB ...".
A string a is a substring of string b if there exists a positive integer i such that a_1 = b_i, a_2 = b_{i + 1}, a_3 = b_{i + 2}, ..., a_{|a|} = b_{i + |a| - 1}. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 2 ⋅ 10^5) — the number of queries. Then q queries follow.
The first line of the query contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the length of the string s and the length of the substring.
The second line of the query contains a string s consisting of n characters 'R', 'G' and 'B'.
It is guaranteed that the sum of n over all queries does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each query print one integer — the minimum number of characters you need to change in the initial string s so that after changing there will be a substring of length k in s that is also a substring of the infinite string "RGBRGBRGB ...".
Example
Input
3
5 2
BGGGG
5 3
RBRGR
5 5
BBBRR
Output
1
0
3
Note
In the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".
In the second example, the substring is "BRG".
Submitted Solution:
```
import sys
input = sys.stdin.readline
q = int( input() )
rgb = "RGB"
for _ in range( q ):
n, k = map( int, input().split() )
s = input()
ans = n
for i in range( 3 ):
r = [ 0 ]
l = i
for c in s:
r.append( r[ -1 ] + ( 1 if c != rgb[ l ] else 0 ) )
l = ( l + 1 ) % 3
if len( r ) > k:
ans = min( ans, r[ -1 ] - r[ len( r ) - 1 - k ] )
print( ans )
``` | instruction | 0 | 67,349 | 0 | 134,698 |
Yes | output | 1 | 67,349 | 0 | 134,699 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is the size of the input.
You are given a string s consisting of n characters, each character is 'R', 'G' or 'B'.
You are also given an integer k. Your task is to change the minimum number of characters in the initial string s so that after the changes there will be a string of length k that is a substring of s, and is also a substring of the infinite string "RGBRGBRGB ...".
A string a is a substring of string b if there exists a positive integer i such that a_1 = b_i, a_2 = b_{i + 1}, a_3 = b_{i + 2}, ..., a_{|a|} = b_{i + |a| - 1}. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 2 ⋅ 10^5) — the number of queries. Then q queries follow.
The first line of the query contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the length of the string s and the length of the substring.
The second line of the query contains a string s consisting of n characters 'R', 'G' and 'B'.
It is guaranteed that the sum of n over all queries does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each query print one integer — the minimum number of characters you need to change in the initial string s so that after changing there will be a substring of length k in s that is also a substring of the infinite string "RGBRGBRGB ...".
Example
Input
3
5 2
BGGGG
5 3
RBRGR
5 5
BBBRR
Output
1
0
3
Note
In the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".
In the second example, the substring is "BRG".
Submitted Solution:
```
import sys
input = sys.stdin.readline
pure = "RGB" * 100006
for _ in range(int(input())):
n,k = map(int,input().split())
s = input()
ans = 0
Rc = 0
Gc = 0
Bc = 0
# R
count = 0
for i in range(k):
if(pure[i] == s[i]):
Rc+=1
elif(pure[i-1] == s[i]):
Bc+=1
elif(pure[i-2] == s[i]):
Gc+=1
ans = max(ans,Rc,Gc,Bc)
for i in range(k,n):
if(pure[i] == s[i]):
Rc+=1
if(pure[i-k] == s[i-k]):
Rc-=1
if(pure[i-1] == s[i]):
Bc+=1
if(pure[i-k-1] == s[i-k]):
Bc-=1
if(pure[i-2] == s[i]):
Gc+=1
if(pure[i-k-2] == s[i-k]):
Gc-=1
ans = max(ans,Rc,Gc,Bc)
print(k-ans)
``` | instruction | 0 | 67,350 | 0 | 134,700 |
Yes | output | 1 | 67,350 | 0 | 134,701 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is the size of the input.
You are given a string s consisting of n characters, each character is 'R', 'G' or 'B'.
You are also given an integer k. Your task is to change the minimum number of characters in the initial string s so that after the changes there will be a string of length k that is a substring of s, and is also a substring of the infinite string "RGBRGBRGB ...".
A string a is a substring of string b if there exists a positive integer i such that a_1 = b_i, a_2 = b_{i + 1}, a_3 = b_{i + 2}, ..., a_{|a|} = b_{i + |a| - 1}. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 2 ⋅ 10^5) — the number of queries. Then q queries follow.
The first line of the query contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the length of the string s and the length of the substring.
The second line of the query contains a string s consisting of n characters 'R', 'G' and 'B'.
It is guaranteed that the sum of n over all queries does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each query print one integer — the minimum number of characters you need to change in the initial string s so that after changing there will be a substring of length k in s that is also a substring of the infinite string "RGBRGBRGB ...".
Example
Input
3
5 2
BGGGG
5 3
RBRGR
5 5
BBBRR
Output
1
0
3
Note
In the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".
In the second example, the substring is "BRG".
Submitted Solution:
```
import sys, os, io
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math,datetime,functools,itertools,operator,bisect,fractions,statistics
from collections import deque,defaultdict,OrderedDict,Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout
from heapq import heappush, heappop, heapify ,_heapify_max,_heappop_max,nsmallest,nlargest
def main():
# mod=1000000007
# InverseofNumber(mod)
# InverseofFactorial(mod)
# factorial(mod)
starttime=datetime.datetime.now()
if(os.path.exists('input.txt')):
sys.stdin = open("input.txt","r")
sys.stdout = open("output.txt","w")
tc=ri()
for _ in range(tc):
n,k=ria()
s=list(rs())
a="RGB"*n
b="BRG"*n
c="GBR"*n
a=a[:n]
b=b[:n]
c=c[:n]
# print(a)
# print(b)
# print(c)
z=[a,b,c]
da=[0]*n
db=[0]*n
dc=[0]*n
for i in range(n):
if s[i]==a[i]:
da[i]=1
elif s[i]==b[i]:
db[i]=1
else:
dc[i]=1
pda=[0]
pdb=[0]
pdc=[0]
for i in range(n):
pda.append(pda[-1]+da[i])
pdb.append(pdb[-1]+db[i])
pdc.append(pdc[-1]+dc[i])
maxs=0
for i in range(k,n+1):
sa=pda[i]-pda[i-k]
sb=pdb[i]-pdb[i-k]
sc=pdc[i]-pdc[i-k]
maxs=max(maxs,sa,sb,sc)
print(k-maxs)
#<--Solving Area Ends
endtime=datetime.datetime.now()
time=(endtime-starttime).total_seconds()*1000
if(os.path.exists('input.txt')):
print("Time:",time,"ms")
class FastReader(io.IOBase):
newlines = 0
def __init__(self, fd, chunk_size=1024 * 8):
self._fd = fd
self._chunk_size = chunk_size
self.buffer = io.BytesIO()
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
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, size=-1):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
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()
class FastWriter(io.IOBase):
def __init__(self, fd):
self._fd = fd
self.buffer = io.BytesIO()
self.write = self.buffer.write
def flush(self):
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class FastStdin(io.IOBase):
def __init__(self, fd=0):
self.buffer = FastReader(fd)
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
class FastStdout(io.IOBase):
def __init__(self, fd=1):
self.buffer = FastWriter(fd)
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.flush = self.buffer.flush
if __name__ == '__main__':
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()
``` | instruction | 0 | 67,351 | 0 | 134,702 |
Yes | output | 1 | 67,351 | 0 | 134,703 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is the size of the input.
You are given a string s consisting of n characters, each character is 'R', 'G' or 'B'.
You are also given an integer k. Your task is to change the minimum number of characters in the initial string s so that after the changes there will be a string of length k that is a substring of s, and is also a substring of the infinite string "RGBRGBRGB ...".
A string a is a substring of string b if there exists a positive integer i such that a_1 = b_i, a_2 = b_{i + 1}, a_3 = b_{i + 2}, ..., a_{|a|} = b_{i + |a| - 1}. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 2 ⋅ 10^5) — the number of queries. Then q queries follow.
The first line of the query contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the length of the string s and the length of the substring.
The second line of the query contains a string s consisting of n characters 'R', 'G' and 'B'.
It is guaranteed that the sum of n over all queries does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each query print one integer — the minimum number of characters you need to change in the initial string s so that after changing there will be a substring of length k in s that is also a substring of the infinite string "RGBRGBRGB ...".
Example
Input
3
5 2
BGGGG
5 3
RBRGR
5 5
BBBRR
Output
1
0
3
Note
In the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".
In the second example, the substring is "BRG".
Submitted Solution:
```
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
import sys
from io import BytesIO, IOBase
from math import inf
def main():
for _ in range(int(input())):
n,k=map(int,input().split())
s=list(input().rstrip())
a=["RGB","GBR","BRG"]
dp=[[0 for _ in range(n+1)] for _ in range(3)]
for j in range(3):
for i in range(n):
dp[j][i+1]=(s[i]!=a[j][i%3])+dp[j][i]
mi=inf
for i in range(n-k+1):
for j in range(3):
mi=min(mi,dp[j][i+k]-dp[j][i])
print(mi)
'''
4 3
BBBR
'''
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | instruction | 0 | 67,352 | 0 | 134,704 |
Yes | output | 1 | 67,352 | 0 | 134,705 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is the size of the input.
You are given a string s consisting of n characters, each character is 'R', 'G' or 'B'.
You are also given an integer k. Your task is to change the minimum number of characters in the initial string s so that after the changes there will be a string of length k that is a substring of s, and is also a substring of the infinite string "RGBRGBRGB ...".
A string a is a substring of string b if there exists a positive integer i such that a_1 = b_i, a_2 = b_{i + 1}, a_3 = b_{i + 2}, ..., a_{|a|} = b_{i + |a| - 1}. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 2 ⋅ 10^5) — the number of queries. Then q queries follow.
The first line of the query contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the length of the string s and the length of the substring.
The second line of the query contains a string s consisting of n characters 'R', 'G' and 'B'.
It is guaranteed that the sum of n over all queries does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each query print one integer — the minimum number of characters you need to change in the initial string s so that after changing there will be a substring of length k in s that is also a substring of the infinite string "RGBRGBRGB ...".
Example
Input
3
5 2
BGGGG
5 3
RBRGR
5 5
BBBRR
Output
1
0
3
Note
In the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".
In the second example, the substring is "BRG".
Submitted Solution:
```
t=int(input())
def nextL(letter):
seq="RGB"
ind=0
while ind<len(seq):
if seq[ind]==letter:
ind+=1
break
ind+=1
if ind>=len(seq): ind=0
return(seq[ind])
for i in range(t):
n, k=list(map(int, input().split(" ")))
# numof changes where index is the end of the substring of length 'k'
numofChanges=[0]*n
chars=list(input())
for j in range(n):
if j==0:
numofChanges[j]=0
continue
if j<k:
if nextL(chars[j-1])!=chars[j]:
numofChanges[j]=numofChanges[j-1]+1
else:
numofChanges[j]=numofChanges[j-1]
if j>=k:
# print("on index: ", j)
if nextL(chars[j-k])!=chars[j-k+1]:
numofChanges[j]-=1
# print("true 1")
if nextL(chars[j-1])!=chars[j]:
numofChanges[j]+=numofChanges[j-1]+1
# print("true 2")
else:
numofChanges[j]+=numofChanges[j-1]
# print(numofChanges)
res1=min(numofChanges[k-1:])
# numof changes where index is the end of the substring of length 'k'
numofChanges=[0]*n
for j in range(n):
if j==0:
numofChanges[j]=0
continue
if j<k:
if nextL(chars[j-1])!=chars[j]:
numofChanges[j]=numofChanges[j-1]+1
else:
numofChanges[j]=numofChanges[j-1]
if j>=k:
# print("on index: ", j)
if nextL(chars[j-k])!=chars[j-k+1]:
numofChanges[j]-=1
# print("true 1")
if nextL(chars[j-1])!=chars[j]:
numofChanges[j]+=numofChanges[j-1]+1
# print("true 2")
else:
numofChanges[j]+=numofChanges[j-1]
# print(numofChanges)
res2=min(numofChanges[k-1:])
print(min(res1, res2))
'''
1
5 3
RBRGR
'''
``` | instruction | 0 | 67,353 | 0 | 134,706 |
No | output | 1 | 67,353 | 0 | 134,707 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is the size of the input.
You are given a string s consisting of n characters, each character is 'R', 'G' or 'B'.
You are also given an integer k. Your task is to change the minimum number of characters in the initial string s so that after the changes there will be a string of length k that is a substring of s, and is also a substring of the infinite string "RGBRGBRGB ...".
A string a is a substring of string b if there exists a positive integer i such that a_1 = b_i, a_2 = b_{i + 1}, a_3 = b_{i + 2}, ..., a_{|a|} = b_{i + |a| - 1}. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 2 ⋅ 10^5) — the number of queries. Then q queries follow.
The first line of the query contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the length of the string s and the length of the substring.
The second line of the query contains a string s consisting of n characters 'R', 'G' and 'B'.
It is guaranteed that the sum of n over all queries does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each query print one integer — the minimum number of characters you need to change in the initial string s so that after changing there will be a substring of length k in s that is also a substring of the infinite string "RGBRGBRGB ...".
Example
Input
3
5 2
BGGGG
5 3
RBRGR
5 5
BBBRR
Output
1
0
3
Note
In the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".
In the second example, the substring is "BRG".
Submitted Solution:
```
a = int(input())
b = [0]*a
def change(d):
for i in range(0, len(d)):
if d[i] == "R":
d[i] = 1
elif d[i] == "G":
d[i] = 2
else:
d[i] = 3
return d
for i in range(0,a):
b[i] = list(map(int, input().split()))
n = b[i][0]
k = b[i][1]
c = list(input())
c = change(c)
e = [0]*(3*(n-k+1))
if n > 2:
for i in range(0, n-k+1):
for j in range (i,i+k):
if (c[j] - c[i]) % 3 != (j - i) % 3:
e[3*i] = e[3*i]+1
if (c[j] - c[i]) % 3 != (j - i-1) % 3:
e[3*i + 1] = e[3*i + 1]+1
if (c[j] - c[i]) % 3 != (j - i-2) % 3:
e[3*i + 2] = e[3*i + 2]+1
e.sort()
print(e[0])
else:
if c == [1, 2]:
print (0)
elif c == [2,3]:
print (0)
elif c == [3,1]:
print (0)
else:
print (1)
``` | instruction | 0 | 67,354 | 0 | 134,708 |
No | output | 1 | 67,354 | 0 | 134,709 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is the size of the input.
You are given a string s consisting of n characters, each character is 'R', 'G' or 'B'.
You are also given an integer k. Your task is to change the minimum number of characters in the initial string s so that after the changes there will be a string of length k that is a substring of s, and is also a substring of the infinite string "RGBRGBRGB ...".
A string a is a substring of string b if there exists a positive integer i such that a_1 = b_i, a_2 = b_{i + 1}, a_3 = b_{i + 2}, ..., a_{|a|} = b_{i + |a| - 1}. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 2 ⋅ 10^5) — the number of queries. Then q queries follow.
The first line of the query contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the length of the string s and the length of the substring.
The second line of the query contains a string s consisting of n characters 'R', 'G' and 'B'.
It is guaranteed that the sum of n over all queries does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each query print one integer — the minimum number of characters you need to change in the initial string s so that after changing there will be a substring of length k in s that is also a substring of the infinite string "RGBRGBRGB ...".
Example
Input
3
5 2
BGGGG
5 3
RBRGR
5 5
BBBRR
Output
1
0
3
Note
In the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".
In the second example, the substring is "BRG".
Submitted Solution:
```
'''Author- Akshit Monga'''
from sys import stdin, stdout
input = stdin.readline
d1=['R','G','B']
d2=['G','B','R']
d3=['B','R','G']
t = int(input())
for _ in range(t):
n,k=map(int,input().split())
s=input().strip()
ans=float('inf')
temp = s[0:k]
a = b = c = 0
p = 0
q = 1
r = 2
for j in temp:
if j != d1[p]:
a += 1
if j != d1[q]:
b += 1
if j != d1[r]:
c += 1
p += 1
p %= 3
q += 1
q %= 3
r += 1
r %= 3
ans=min(a,b,c)
print(a,b,c)
for i in range(1,n-k+1):
first=i
last=i+k-1
if s[first-1]!=d1[0]:
a-=1
if s[first-1]!=d2[0]:
b-=1
if s[first-1]!=d3[0]:
c-=1
a, b, c = c, a, b
if s[last]!=d1[(k-1)%3]:
a+=1
if s[last]!=d2[(k-1)%3]:
b+=1
if s[last]!=d3[(k-1)%3]:
c+=1
# print(a,b,c)
ans=min(ans,a,b,c)
print(ans)
``` | instruction | 0 | 67,355 | 0 | 134,710 |
No | output | 1 | 67,355 | 0 | 134,711 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is the size of the input.
You are given a string s consisting of n characters, each character is 'R', 'G' or 'B'.
You are also given an integer k. Your task is to change the minimum number of characters in the initial string s so that after the changes there will be a string of length k that is a substring of s, and is also a substring of the infinite string "RGBRGBRGB ...".
A string a is a substring of string b if there exists a positive integer i such that a_1 = b_i, a_2 = b_{i + 1}, a_3 = b_{i + 2}, ..., a_{|a|} = b_{i + |a| - 1}. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 2 ⋅ 10^5) — the number of queries. Then q queries follow.
The first line of the query contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the length of the string s and the length of the substring.
The second line of the query contains a string s consisting of n characters 'R', 'G' and 'B'.
It is guaranteed that the sum of n over all queries does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each query print one integer — the minimum number of characters you need to change in the initial string s so that after changing there will be a substring of length k in s that is also a substring of the infinite string "RGBRGBRGB ...".
Example
Input
3
5 2
BGGGG
5 3
RBRGR
5 5
BBBRR
Output
1
0
3
Note
In the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".
In the second example, the substring is "BRG".
Submitted Solution:
```
queries = int(input())
rgb = ['R', 'G', 'B']
r_idx, g_idx, b_idx = 0, 1, 2
for q in range(queries):
n, k = list(map(int, input().split()))
s = input()
ret = ""
if n == 1 or k == 1:
ret += "0\n"
num_windows = n - k + 1
r_arr = [0] * num_windows
g_arr = [0] * num_windows
b_arr = [0] * num_windows
min_cost = [0] * num_windows
for i in range(num_windows):
r_start = g_start = b_start = 0
if i == 0:
for j in range(k):
if s[i + j] != rgb[(j + r_idx) % 3]:
r_start += 1
if s[i + j] != rgb[(j + g_idx) % 3]:
g_start += 1
if s[i + j] != rgb[(j + b_idx) % 3]:
b_start += 1
else:
j = k - 1
r_start = b_arr[i-1] - (1 if s[i - 1] != 'B' else 0) + (1 if s[i + j] != rgb[(j + r_idx) % 3] else 0)
g_start = r_arr[i-1] - (1 if s[i - 1] != 'R' else 0) + (1 if s[i + j] != rgb[(j + g_idx) % 3] else 0)
b_start = g_arr[i-1] - (1 if s[i - 1] != 'G' else 0) + (1 if s[i + j] != rgb[(j + b_idx) % 3] else 0)
r_arr[i] = r_start
g_arr[i] = g_start
b_arr[i] = b_start
#print(r_arr)
#print(g_arr)
#print(b_arr)
min_cost[i] = min(r_start, g_start, b_start)
ret += (str(min(min_cost)) + "\n")
print(ret)
``` | instruction | 0 | 67,356 | 0 | 134,712 |
No | output | 1 | 67,356 | 0 | 134,713 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Authors have come up with the string s consisting of n lowercase Latin letters.
You are given two permutations of its indices (not necessary equal) p and q (both of length n). Recall that the permutation is the array of length n which contains each integer from 1 to n exactly once.
For all i from 1 to n-1 the following properties hold: s[p_i] ≤ s[p_{i + 1}] and s[q_i] ≤ s[q_{i + 1}]. It means that if you will write down all characters of s in order of permutation indices, the resulting string will be sorted in the non-decreasing order.
Your task is to restore any such string s of length n consisting of at least k distinct lowercase Latin letters which suits the given permutations.
If there are multiple answers, you can print any of them.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 26) — the length of the string and the number of distinct characters required.
The second line of the input contains n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i are distinct integers from 1 to n) — the permutation p.
The third line of the input contains n integers q_1, q_2, ..., q_n (1 ≤ q_i ≤ n, all q_i are distinct integers from 1 to n) — the permutation q.
Output
If it is impossible to find the suitable string, print "NO" on the first line.
Otherwise print "YES" on the first line and string s on the second line. It should consist of n lowercase Latin letters, contain at least k distinct characters and suit the given permutations.
If there are multiple answers, you can print any of them.
Example
Input
3 2
1 2 3
1 3 2
Output
YES
abb | instruction | 0 | 67,357 | 0 | 134,714 |
Tags: data structures, dfs and similar, dsu, graphs, greedy, implementation, strings
Correct Solution:
```
n, k = [int(i) for i in input().split()]
p = [int(i) for i in input().split()]
q = [int(i) for i in input().split()]
offs = ord("a")
ans = [chr(offs+k-1)] * n
# ans = ""
pmore = set()
qmore = set()
let = 0
# cnt = 0
for i in range(n):
# cnt += 1
pi = p[i]
qi = q[i]
if qi in pmore:
pmore.remove(qi)
else:
qmore.add(qi)
if pi in qmore:
qmore.remove(pi)
else:
pmore.add(pi)
ans[pi - 1] = chr(let+offs)
if len(pmore) + len(qmore) == 0:
let += 1
if let == k:
break
if let == k:
# if len(ans) < n:
# ans += chr(offs+k-1) * (n- len(ans))
print("YES")
print("".join(ans))
else:
print("NO")
``` | output | 1 | 67,357 | 0 | 134,715 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Authors have come up with the string s consisting of n lowercase Latin letters.
You are given two permutations of its indices (not necessary equal) p and q (both of length n). Recall that the permutation is the array of length n which contains each integer from 1 to n exactly once.
For all i from 1 to n-1 the following properties hold: s[p_i] ≤ s[p_{i + 1}] and s[q_i] ≤ s[q_{i + 1}]. It means that if you will write down all characters of s in order of permutation indices, the resulting string will be sorted in the non-decreasing order.
Your task is to restore any such string s of length n consisting of at least k distinct lowercase Latin letters which suits the given permutations.
If there are multiple answers, you can print any of them.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 26) — the length of the string and the number of distinct characters required.
The second line of the input contains n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i are distinct integers from 1 to n) — the permutation p.
The third line of the input contains n integers q_1, q_2, ..., q_n (1 ≤ q_i ≤ n, all q_i are distinct integers from 1 to n) — the permutation q.
Output
If it is impossible to find the suitable string, print "NO" on the first line.
Otherwise print "YES" on the first line and string s on the second line. It should consist of n lowercase Latin letters, contain at least k distinct characters and suit the given permutations.
If there are multiple answers, you can print any of them.
Example
Input
3 2
1 2 3
1 3 2
Output
YES
abb | instruction | 0 | 67,358 | 0 | 134,716 |
Tags: data structures, dfs and similar, dsu, graphs, greedy, implementation, strings
Correct Solution:
```
import math
n = 3
k = 2
p = [1,2,3]
q = [1,3,2]
n,k = [int(x) for x in input().split(' ')]
p = [int(x) -1 for x in input().split(' ')]
q = [int(x) -1 for x in input().split(' ')]
group_ids = []
p_ids = set()
q_ids = set()
for i in range(n):
if p[i] in q_ids:
q_ids.remove(p[i])
else:
p_ids.add(p[i])
if q[i] in p_ids:
p_ids.remove(q[i])
else:
q_ids.add(q[i])
if not bool(p_ids) and not bool(q_ids):
group_ids.append(i)
if len(group_ids) < k:
print('NO')
exit(0)
def get_letter(_id):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
return alphabet[min(_id, len(alphabet)-1)]
print('YES')
result = [None] * n
l = 0
for i in range(len(group_ids)):
r = group_ids[i]
letter = get_letter(i)
for it in range(l, r+1):
result[p[it]] = letter
l = r+1
print(''.join(result))
``` | output | 1 | 67,358 | 0 | 134,717 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Authors have come up with the string s consisting of n lowercase Latin letters.
You are given two permutations of its indices (not necessary equal) p and q (both of length n). Recall that the permutation is the array of length n which contains each integer from 1 to n exactly once.
For all i from 1 to n-1 the following properties hold: s[p_i] ≤ s[p_{i + 1}] and s[q_i] ≤ s[q_{i + 1}]. It means that if you will write down all characters of s in order of permutation indices, the resulting string will be sorted in the non-decreasing order.
Your task is to restore any such string s of length n consisting of at least k distinct lowercase Latin letters which suits the given permutations.
If there are multiple answers, you can print any of them.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 26) — the length of the string and the number of distinct characters required.
The second line of the input contains n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i are distinct integers from 1 to n) — the permutation p.
The third line of the input contains n integers q_1, q_2, ..., q_n (1 ≤ q_i ≤ n, all q_i are distinct integers from 1 to n) — the permutation q.
Output
If it is impossible to find the suitable string, print "NO" on the first line.
Otherwise print "YES" on the first line and string s on the second line. It should consist of n lowercase Latin letters, contain at least k distinct characters and suit the given permutations.
If there are multiple answers, you can print any of them.
Example
Input
3 2
1 2 3
1 3 2
Output
YES
abb | instruction | 0 | 67,359 | 0 | 134,718 |
Tags: data structures, dfs and similar, dsu, graphs, greedy, implementation, strings
Correct Solution:
```
# https://codeforces.com/contest/1213/problem/F
n, k = map(int, input().split())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
def get(cur):
if cur>=97+25:
return chr(97+25)
return chr(cur)
pos = [0] * (n+1)
for i, x in enumerate(q):
pos[x] = i
seg =[0]
cnt = 0
max_=-1
for i, x in enumerate(p):
max_ = max(max_, pos[x])
if i == max_:
cnt+=1
seg.append(i+1)
if len(seg)-1<k:
print('NO')
else:
cur = 97
S = []
for s, e in zip(seg[:-1], seg[1:]):
for i in range(s, e):
S.append(cur)
cur+=1
print('YES')
print(''.join([get(S[pos[x]]) for x in range(1, n+1)]))
``` | output | 1 | 67,359 | 0 | 134,719 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Authors have come up with the string s consisting of n lowercase Latin letters.
You are given two permutations of its indices (not necessary equal) p and q (both of length n). Recall that the permutation is the array of length n which contains each integer from 1 to n exactly once.
For all i from 1 to n-1 the following properties hold: s[p_i] ≤ s[p_{i + 1}] and s[q_i] ≤ s[q_{i + 1}]. It means that if you will write down all characters of s in order of permutation indices, the resulting string will be sorted in the non-decreasing order.
Your task is to restore any such string s of length n consisting of at least k distinct lowercase Latin letters which suits the given permutations.
If there are multiple answers, you can print any of them.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 26) — the length of the string and the number of distinct characters required.
The second line of the input contains n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i are distinct integers from 1 to n) — the permutation p.
The third line of the input contains n integers q_1, q_2, ..., q_n (1 ≤ q_i ≤ n, all q_i are distinct integers from 1 to n) — the permutation q.
Output
If it is impossible to find the suitable string, print "NO" on the first line.
Otherwise print "YES" on the first line and string s on the second line. It should consist of n lowercase Latin letters, contain at least k distinct characters and suit the given permutations.
If there are multiple answers, you can print any of them.
Example
Input
3 2
1 2 3
1 3 2
Output
YES
abb | instruction | 0 | 67,360 | 0 | 134,720 |
Tags: data structures, dfs and similar, dsu, graphs, greedy, implementation, strings
Correct Solution:
```
n, k = map(int, input().split())
s = [0] * n
for i, v in enumerate(map(int, input().split())):
s[v-1] = i
t = [0] * n
for i, v in enumerate(map(int, input().split())):
t[v-1] = i
p = [0] * n
for u, v in zip(s, t):
if u == v: continue
elif v < u: u, v = v, u
p[u] += 1
p[v] -= 1
r = [0] * n
cur = 0
nxt = -1
for i, v in enumerate(p):
if cur == 0 and nxt < 25: nxt += 1
r[i] = nxt
cur += v
if nxt < k-1:
print("NO")
else:
print("YES")
print("".join(map(lambda x: chr(ord('a')+r[x]), s)))
``` | output | 1 | 67,360 | 0 | 134,721 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Authors have come up with the string s consisting of n lowercase Latin letters.
You are given two permutations of its indices (not necessary equal) p and q (both of length n). Recall that the permutation is the array of length n which contains each integer from 1 to n exactly once.
For all i from 1 to n-1 the following properties hold: s[p_i] ≤ s[p_{i + 1}] and s[q_i] ≤ s[q_{i + 1}]. It means that if you will write down all characters of s in order of permutation indices, the resulting string will be sorted in the non-decreasing order.
Your task is to restore any such string s of length n consisting of at least k distinct lowercase Latin letters which suits the given permutations.
If there are multiple answers, you can print any of them.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 26) — the length of the string and the number of distinct characters required.
The second line of the input contains n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i are distinct integers from 1 to n) — the permutation p.
The third line of the input contains n integers q_1, q_2, ..., q_n (1 ≤ q_i ≤ n, all q_i are distinct integers from 1 to n) — the permutation q.
Output
If it is impossible to find the suitable string, print "NO" on the first line.
Otherwise print "YES" on the first line and string s on the second line. It should consist of n lowercase Latin letters, contain at least k distinct characters and suit the given permutations.
If there are multiple answers, you can print any of them.
Example
Input
3 2
1 2 3
1 3 2
Output
YES
abb | instruction | 0 | 67,361 | 0 | 134,722 |
Tags: data structures, dfs and similar, dsu, graphs, greedy, implementation, strings
Correct Solution:
```
n, k = map(int,input().split())
l1 = list(map(int,input().split()))
l2 = list(map(int,input().split()))
d = {}
j = 1
for i in l1:
d[i] = j
j += 1
l = [d[i] for i in l2]
#l is the list that forces shit
wei = [0] * (n+2)
right = [0] * (n+2)
for i in range(n -1):
#look at l[i], l[1+1]
if l[i] < l[i+1]:
continue
wei[l[i+1]] += 1
wei[l[i] + 1] -= 1
right[l[i]] += 1
odcinki = []
l = 1
r = 1
pref = [0] * (n + 2)
for i in range(1, n+2):
pref[i] = pref[i-1] + wei[i]
for i in range(1, n + 2):
if pref[i] == 0:
odcinki.append([l,r])
l = i + 1
r = i + 1
else:
if pref[i] == right[i]:
odcinki.append([l,r])
l = i + 1
r = i + 1
else:
r += 1
if odcinki[0] == [1,1]:
odcinki = odcinki[1:]
if odcinki[-1][0] == odcinki[-1][1] and odcinki[-1][0] > n:
odcinki = odcinki[:-1]
lewe = [0] * (n+1)
prawe = [0] * (n+1)
for i in odcinki:
lewe[i[0]] = 1
prawe[i[1]] = 1
odp = [0] * (n+3)
i = -1
indx = 1
reg = 0
odp = [-1] * (n+3)
count = 0
while indx < n + 1:
#i stays the same iff [5,6,7,8,9] we are 6,7,8,9
if prawe[indx-1] == 1:
reg = 0
if lewe[indx] == 1:
reg = 1
count = 0
odp[indx] = i
#kiedy i += 1
if count == 0 or reg == 0:
i += 1
count += 1
odp[indx] = i
indx += 1
odpp = [0] * (n + 3)
for i in range(n):
odpp[l1[i]] = odp[i + 1]
odpp = odpp[1:-2]
if max(odpp) + 1 < k:
print("NO")
else:
print("YES")
for i in range(n):
print(chr(97+min(25, odpp[i])), end = "")
``` | output | 1 | 67,361 | 0 | 134,723 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Authors have come up with the string s consisting of n lowercase Latin letters.
You are given two permutations of its indices (not necessary equal) p and q (both of length n). Recall that the permutation is the array of length n which contains each integer from 1 to n exactly once.
For all i from 1 to n-1 the following properties hold: s[p_i] ≤ s[p_{i + 1}] and s[q_i] ≤ s[q_{i + 1}]. It means that if you will write down all characters of s in order of permutation indices, the resulting string will be sorted in the non-decreasing order.
Your task is to restore any such string s of length n consisting of at least k distinct lowercase Latin letters which suits the given permutations.
If there are multiple answers, you can print any of them.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 26) — the length of the string and the number of distinct characters required.
The second line of the input contains n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i are distinct integers from 1 to n) — the permutation p.
The third line of the input contains n integers q_1, q_2, ..., q_n (1 ≤ q_i ≤ n, all q_i are distinct integers from 1 to n) — the permutation q.
Output
If it is impossible to find the suitable string, print "NO" on the first line.
Otherwise print "YES" on the first line and string s on the second line. It should consist of n lowercase Latin letters, contain at least k distinct characters and suit the given permutations.
If there are multiple answers, you can print any of them.
Example
Input
3 2
1 2 3
1 3 2
Output
YES
abb | instruction | 0 | 67,362 | 0 | 134,724 |
Tags: data structures, dfs and similar, dsu, graphs, greedy, implementation, strings
Correct Solution:
```
from sys import stdin, stdout, setrecursionlimit
setrecursionlimit(50000)
n, k = map(int, stdin.readline().split())
p = list(map(int, stdin.readline().split()))
q = list(map(int, stdin.readline().split()))
pos = [0 for i in range(n)]
for i in range(n):
p[i] -= 1
q[i] -= 1
pos[p[i]] = i
delta = [0 for i in range(n + 1)]
for i in range(n - 1):
x = pos[q[i]]
y = pos[q[i + 1]]
if x > y:
delta[y] += 1
delta[x] -= 1
for i in range(1, n):
delta[i] += delta[i - 1]
scc = [0 for i in range(n)]
num = 0
for i in range(n):
if i == 0 or delta[i - 1] == 0:
num += 1
scc[i] = num
if num < k:
print('NO')
exit(0)
s = ['a' for i in range(n)]
for i in range(n):
x = min(26, scc[i])
s[p[i]] = chr(96 + x)
stdout.write('YES\n')
stdout.write(''.join(s))
``` | output | 1 | 67,362 | 0 | 134,725 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Authors have come up with the string s consisting of n lowercase Latin letters.
You are given two permutations of its indices (not necessary equal) p and q (both of length n). Recall that the permutation is the array of length n which contains each integer from 1 to n exactly once.
For all i from 1 to n-1 the following properties hold: s[p_i] ≤ s[p_{i + 1}] and s[q_i] ≤ s[q_{i + 1}]. It means that if you will write down all characters of s in order of permutation indices, the resulting string will be sorted in the non-decreasing order.
Your task is to restore any such string s of length n consisting of at least k distinct lowercase Latin letters which suits the given permutations.
If there are multiple answers, you can print any of them.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 26) — the length of the string and the number of distinct characters required.
The second line of the input contains n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i are distinct integers from 1 to n) — the permutation p.
The third line of the input contains n integers q_1, q_2, ..., q_n (1 ≤ q_i ≤ n, all q_i are distinct integers from 1 to n) — the permutation q.
Output
If it is impossible to find the suitable string, print "NO" on the first line.
Otherwise print "YES" on the first line and string s on the second line. It should consist of n lowercase Latin letters, contain at least k distinct characters and suit the given permutations.
If there are multiple answers, you can print any of them.
Example
Input
3 2
1 2 3
1 3 2
Output
YES
abb | instruction | 0 | 67,363 | 0 | 134,726 |
Tags: data structures, dfs and similar, dsu, graphs, greedy, implementation, strings
Correct Solution:
```
n,k=[int(x) for x in input().split()]
a=[int(x) for x in input().split()]
b=[int(x) for x in input().split()]
p=set()
q=set()
literals=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
it=0
s=[0]*n
for i in range(n):
p.add(a[i])
q.add(b[i])
s[a[i]-1]=literals[it]
if a[i] in q:
q.remove(a[i])
p.remove(a[i])
if b[i] in p:
p.remove(b[i])
q.remove(b[i])
if not p and (not q):
it=min(it+1,25)
k-=1
if k<=0:
arr=''
print('YES')
for item in s:
arr+=item
print(arr)
else:
print('NO')
``` | output | 1 | 67,363 | 0 | 134,727 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Authors have come up with the string s consisting of n lowercase Latin letters.
You are given two permutations of its indices (not necessary equal) p and q (both of length n). Recall that the permutation is the array of length n which contains each integer from 1 to n exactly once.
For all i from 1 to n-1 the following properties hold: s[p_i] ≤ s[p_{i + 1}] and s[q_i] ≤ s[q_{i + 1}]. It means that if you will write down all characters of s in order of permutation indices, the resulting string will be sorted in the non-decreasing order.
Your task is to restore any such string s of length n consisting of at least k distinct lowercase Latin letters which suits the given permutations.
If there are multiple answers, you can print any of them.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 26) — the length of the string and the number of distinct characters required.
The second line of the input contains n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i are distinct integers from 1 to n) — the permutation p.
The third line of the input contains n integers q_1, q_2, ..., q_n (1 ≤ q_i ≤ n, all q_i are distinct integers from 1 to n) — the permutation q.
Output
If it is impossible to find the suitable string, print "NO" on the first line.
Otherwise print "YES" on the first line and string s on the second line. It should consist of n lowercase Latin letters, contain at least k distinct characters and suit the given permutations.
If there are multiple answers, you can print any of them.
Example
Input
3 2
1 2 3
1 3 2
Output
YES
abb | instruction | 0 | 67,364 | 0 | 134,728 |
Tags: data structures, dfs and similar, dsu, graphs, greedy, implementation, strings
Correct Solution:
```
n,k=map(int,input().split())
aa=list(map(int,input().split()))
bb=list(map(int,input().split()))
ab="abcdefghijklmnopqrstuvwxyz"
#print(len(ab))
ss={}
j=0
it=[]
for i in aa:
ss[i]=j
j+=1
jj=0
for i in bb:
ind=ss[i]
j,ind=sorted([jj,ind])
it.append([j,ind])
# print(i,jj,ind)
jj+=1
it.sort()
do=1
ma=it[0][1]
res=[]
st=it[0][0]
for i in it[1:]:
if i[0]<=ma:
ma=max(ma,i[1])
else:
do+=1
res.append([st,ma])
st=i[0]
ma=i[1]
j+=1
if res==[]:
res=[[0,n-1]]
else:
if res[-1][1]!=n-1:
res.append([res[-1][1]+1,n-1])
if len(res)<k:
print("NO")
else:
print("YES")
if len(res)>k:
# print(res[:k-1])
# print(res)
res=res[:k-1]+[[res[k-1][0],n-1]]
kk=-1
res.sort()
ll=[0]*n
for i in res:
kk+=1
for j in range(i[0],i[1]+1):
ll[aa[j]-1]=ab[kk]
for i in ll:
print(i,end="")
print()
``` | output | 1 | 67,364 | 0 | 134,729 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Authors have come up with the string s consisting of n lowercase Latin letters.
You are given two permutations of its indices (not necessary equal) p and q (both of length n). Recall that the permutation is the array of length n which contains each integer from 1 to n exactly once.
For all i from 1 to n-1 the following properties hold: s[p_i] ≤ s[p_{i + 1}] and s[q_i] ≤ s[q_{i + 1}]. It means that if you will write down all characters of s in order of permutation indices, the resulting string will be sorted in the non-decreasing order.
Your task is to restore any such string s of length n consisting of at least k distinct lowercase Latin letters which suits the given permutations.
If there are multiple answers, you can print any of them.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 26) — the length of the string and the number of distinct characters required.
The second line of the input contains n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i are distinct integers from 1 to n) — the permutation p.
The third line of the input contains n integers q_1, q_2, ..., q_n (1 ≤ q_i ≤ n, all q_i are distinct integers from 1 to n) — the permutation q.
Output
If it is impossible to find the suitable string, print "NO" on the first line.
Otherwise print "YES" on the first line and string s on the second line. It should consist of n lowercase Latin letters, contain at least k distinct characters and suit the given permutations.
If there are multiple answers, you can print any of them.
Example
Input
3 2
1 2 3
1 3 2
Output
YES
abb
Submitted Solution:
```
def main():
n, m = map(int, input().split())
abc = list('zyxwvutsrqponmlkjihgfedcba'[26 - m:])
res = [abc[0]] * (n + 1)
res[0], pool, f = 'YES\n', [False] * (n + 1), 0
for p, q in zip(map(int, input().split()),
map(int, input().split())):
if pool[p]:
f -= 1
else:
pool[p] = True
f += 1
if pool[q]:
f -= 1
else:
pool[q] = True
f += 1
res[p] = abc[-1]
if not f:
del abc[-1]
if not abc:
break
print('NO' if abc else ''.join(res))
if __name__ == '__main__':
main()
``` | instruction | 0 | 67,365 | 0 | 134,730 |
Yes | output | 1 | 67,365 | 0 | 134,731 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Authors have come up with the string s consisting of n lowercase Latin letters.
You are given two permutations of its indices (not necessary equal) p and q (both of length n). Recall that the permutation is the array of length n which contains each integer from 1 to n exactly once.
For all i from 1 to n-1 the following properties hold: s[p_i] ≤ s[p_{i + 1}] and s[q_i] ≤ s[q_{i + 1}]. It means that if you will write down all characters of s in order of permutation indices, the resulting string will be sorted in the non-decreasing order.
Your task is to restore any such string s of length n consisting of at least k distinct lowercase Latin letters which suits the given permutations.
If there are multiple answers, you can print any of them.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 26) — the length of the string and the number of distinct characters required.
The second line of the input contains n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i are distinct integers from 1 to n) — the permutation p.
The third line of the input contains n integers q_1, q_2, ..., q_n (1 ≤ q_i ≤ n, all q_i are distinct integers from 1 to n) — the permutation q.
Output
If it is impossible to find the suitable string, print "NO" on the first line.
Otherwise print "YES" on the first line and string s on the second line. It should consist of n lowercase Latin letters, contain at least k distinct characters and suit the given permutations.
If there are multiple answers, you can print any of them.
Example
Input
3 2
1 2 3
1 3 2
Output
YES
abb
Submitted Solution:
```
def process(P, Q, k):
n = len(P)
d = {}
I = 0
s = {}
just_p = set([])
just_q = set([])
both = set([])
for i in range(n):
p = P[i]
q = Q[i]
if p==q:
both.add(p)
else:
if q in just_p:
just_p.remove(q)
both.add(q)
else:
just_q.add(q)
if p in just_q:
just_q.remove(p)
both.add(p)
else:
just_p.add(p)
if len(just_p)==0 and len(just_q)==0:
for x in both:
d[x] = I
I+=1
both = set([])
if I < k:
return ['NO', '']
answer = ['' for i in range(n)]
for x in d:
J = min(d[x], k-1)
answer[x-1] = chr(ord('a')+J)
answer = ''.join(answer)
return ['YES', answer]
n, k = [int(x) for x in input().split()]
P = [int(x) for x in input().split()]
Q = [int(x) for x in input().split()]
a1, a2 = process(P, Q, k)
print(a1)
if a1=='YES':
print(a2)
``` | instruction | 0 | 67,366 | 0 | 134,732 |
Yes | output | 1 | 67,366 | 0 | 134,733 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Authors have come up with the string s consisting of n lowercase Latin letters.
You are given two permutations of its indices (not necessary equal) p and q (both of length n). Recall that the permutation is the array of length n which contains each integer from 1 to n exactly once.
For all i from 1 to n-1 the following properties hold: s[p_i] ≤ s[p_{i + 1}] and s[q_i] ≤ s[q_{i + 1}]. It means that if you will write down all characters of s in order of permutation indices, the resulting string will be sorted in the non-decreasing order.
Your task is to restore any such string s of length n consisting of at least k distinct lowercase Latin letters which suits the given permutations.
If there are multiple answers, you can print any of them.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 26) — the length of the string and the number of distinct characters required.
The second line of the input contains n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i are distinct integers from 1 to n) — the permutation p.
The third line of the input contains n integers q_1, q_2, ..., q_n (1 ≤ q_i ≤ n, all q_i are distinct integers from 1 to n) — the permutation q.
Output
If it is impossible to find the suitable string, print "NO" on the first line.
Otherwise print "YES" on the first line and string s on the second line. It should consist of n lowercase Latin letters, contain at least k distinct characters and suit the given permutations.
If there are multiple answers, you can print any of them.
Example
Input
3 2
1 2 3
1 3 2
Output
YES
abb
Submitted Solution:
```
import sys
input = sys.stdin.readline
from operator import itemgetter
N, K = map(int, input().split())
inP = list(map(int, input().split()))
inQ = list(map(int, input().split()))
P = [None]*N
for i, p in enumerate(inP):
P[p-1] = i+1
Q = [None]*N
for i, q in enumerate(inQ):
Q[q-1] = i+1
NUM = []
for i, (p, q) in enumerate(zip(P, Q)):
NUM.append((i, p, q))
graph = [-1]*(N+1)
NUM.sort(key=itemgetter(2))
for i in range(N-1):
pre = NUM[i][1]
fow = NUM[i+1][1]
graph[fow] = pre
NUM.sort(key=itemgetter(1))
Color = [-1]*(N+1)
color = 0
MAX = 1
for (ind, p, q) in NUM:
if Color[p] == -1 and p > MAX:
color += 1
tmp = p
while tmp != -1 and Color[tmp] == -1:
MAX = max(MAX, tmp)
Color[tmp] = color
tmp = graph[tmp]
if color >= K-1:
print("YES")
ans = [None]*N
for ind, p, q in NUM:
c = Color[p]
ans[ind] = chr(97+min(c, 25))
print("".join(ans))
else:
print("NO")
``` | instruction | 0 | 67,367 | 0 | 134,734 |
Yes | output | 1 | 67,367 | 0 | 134,735 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Authors have come up with the string s consisting of n lowercase Latin letters.
You are given two permutations of its indices (not necessary equal) p and q (both of length n). Recall that the permutation is the array of length n which contains each integer from 1 to n exactly once.
For all i from 1 to n-1 the following properties hold: s[p_i] ≤ s[p_{i + 1}] and s[q_i] ≤ s[q_{i + 1}]. It means that if you will write down all characters of s in order of permutation indices, the resulting string will be sorted in the non-decreasing order.
Your task is to restore any such string s of length n consisting of at least k distinct lowercase Latin letters which suits the given permutations.
If there are multiple answers, you can print any of them.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 26) — the length of the string and the number of distinct characters required.
The second line of the input contains n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i are distinct integers from 1 to n) — the permutation p.
The third line of the input contains n integers q_1, q_2, ..., q_n (1 ≤ q_i ≤ n, all q_i are distinct integers from 1 to n) — the permutation q.
Output
If it is impossible to find the suitable string, print "NO" on the first line.
Otherwise print "YES" on the first line and string s on the second line. It should consist of n lowercase Latin letters, contain at least k distinct characters and suit the given permutations.
If there are multiple answers, you can print any of them.
Example
Input
3 2
1 2 3
1 3 2
Output
YES
abb
Submitted Solution:
```
import sys
inp = [int(x) for x in sys.stdin.read().split()]
n = inp[0]
k = inp[1]
P = inp[2:n + 2]
Q = inp[n + 2: n + n + 2]
index = [0] * n
for i in range(n):
P[i] -= 1
Q[i] -= 1
index[P[i]] = i
intervals = []
for i in range(n - 1):
if index[Q[i]] > index[Q[i + 1]]:
intervals.append((index[Q[i + 1]], index[Q[i]]))
intervals.sort()
color = [0] * n
cur_color = 0
interval_idx = 0
last = -1
for i in range(n):
if last < i:
cur_color += 1
color[i] = cur_color
while interval_idx < len(intervals) and intervals[interval_idx][0] == i:
last = max(last, intervals[interval_idx][1])
interval_idx += 1
if cur_color < k:
print('NO')
else:
ans = ['a'] * n
for i in range(n):
ans[P[i]] = chr(min(25, color[i] - 1) + ord('a'))
print('YES')
print(''.join(ans))
``` | instruction | 0 | 67,368 | 0 | 134,736 |
Yes | output | 1 | 67,368 | 0 | 134,737 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Authors have come up with the string s consisting of n lowercase Latin letters.
You are given two permutations of its indices (not necessary equal) p and q (both of length n). Recall that the permutation is the array of length n which contains each integer from 1 to n exactly once.
For all i from 1 to n-1 the following properties hold: s[p_i] ≤ s[p_{i + 1}] and s[q_i] ≤ s[q_{i + 1}]. It means that if you will write down all characters of s in order of permutation indices, the resulting string will be sorted in the non-decreasing order.
Your task is to restore any such string s of length n consisting of at least k distinct lowercase Latin letters which suits the given permutations.
If there are multiple answers, you can print any of them.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 26) — the length of the string and the number of distinct characters required.
The second line of the input contains n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i are distinct integers from 1 to n) — the permutation p.
The third line of the input contains n integers q_1, q_2, ..., q_n (1 ≤ q_i ≤ n, all q_i are distinct integers from 1 to n) — the permutation q.
Output
If it is impossible to find the suitable string, print "NO" on the first line.
Otherwise print "YES" on the first line and string s on the second line. It should consist of n lowercase Latin letters, contain at least k distinct characters and suit the given permutations.
If there are multiple answers, you can print any of them.
Example
Input
3 2
1 2 3
1 3 2
Output
YES
abb
Submitted Solution:
```
n,k=map(int,input().split())
aa=list(map(int,input().split()))
bb=list(map(int,input().split()))
ab="abcdefghijklmnopqrstuvwxyz"
#print(len(ab))
ss={}
j=0
it=[]
for i in aa:
ss[i]=j
j+=1
jj=0
for i in bb:
ind=ss[i]
j,ind=sorted([jj,ind])
it.append([j,ind])
# print(i,jj,ind)
jj+=1
it.sort()
do=1
ma=it[0][1]
res=[]
st=it[0][0]
for i in it[1:]:
if i[0]<=ma:
ma=max(ma,i[1])
else:
do+=1
res.append([st,ma])
st=i[0]
ma=i[1]
j+=1
if res==[]:
res=[[0,n-1]]
else:
if res[-1][1]!=n-1:
res.append([res[-1][1]+1,n-1])
if len(res)<k:
print("NO")
else:
print("YES")
if len(res)>k:
# print(res[:k-1])
# print(res)
res=res[:k-1]+[[res[k-1][0],n-1]]
k=-1
for i in res:
k+=1
for j in range(i[0],i[1]+1):
print(ab[k],end="")
``` | instruction | 0 | 67,369 | 0 | 134,738 |
No | output | 1 | 67,369 | 0 | 134,739 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Authors have come up with the string s consisting of n lowercase Latin letters.
You are given two permutations of its indices (not necessary equal) p and q (both of length n). Recall that the permutation is the array of length n which contains each integer from 1 to n exactly once.
For all i from 1 to n-1 the following properties hold: s[p_i] ≤ s[p_{i + 1}] and s[q_i] ≤ s[q_{i + 1}]. It means that if you will write down all characters of s in order of permutation indices, the resulting string will be sorted in the non-decreasing order.
Your task is to restore any such string s of length n consisting of at least k distinct lowercase Latin letters which suits the given permutations.
If there are multiple answers, you can print any of them.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 26) — the length of the string and the number of distinct characters required.
The second line of the input contains n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i are distinct integers from 1 to n) — the permutation p.
The third line of the input contains n integers q_1, q_2, ..., q_n (1 ≤ q_i ≤ n, all q_i are distinct integers from 1 to n) — the permutation q.
Output
If it is impossible to find the suitable string, print "NO" on the first line.
Otherwise print "YES" on the first line and string s on the second line. It should consist of n lowercase Latin letters, contain at least k distinct characters and suit the given permutations.
If there are multiple answers, you can print any of them.
Example
Input
3 2
1 2 3
1 3 2
Output
YES
abb
Submitted Solution:
```
n, k = [int(i) for i in input().split()]
p = [int(i) for i in input().split()]
q = [int(i) for i in input().split()]
offs = ord("a")
# ans = chr(offs+k-1) * n
ans = ""
pmore = set()
qmore = set()
let = 0
cnt = 0
for i in range(n):
cnt += 1
pi = p[i]
qi = q[i]
if qi in pmore:
pmore.remove(qi)
else:
qmore.add(qi)
if pi in qmore:
qmore.remove(pi)
else:
pmore.add(pi)
if len(pmore) + len(qmore) == 0:
ans += chr(let+offs) * cnt
cnt = 0
let += 1
if let == k:
break
if let == k:
if len(ans) < n:
ans += chr(offs+k-1) * (n- len(ans))
print("YES")
print(ans)
else:
print("NO")
``` | instruction | 0 | 67,370 | 0 | 134,740 |
No | output | 1 | 67,370 | 0 | 134,741 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Authors have come up with the string s consisting of n lowercase Latin letters.
You are given two permutations of its indices (not necessary equal) p and q (both of length n). Recall that the permutation is the array of length n which contains each integer from 1 to n exactly once.
For all i from 1 to n-1 the following properties hold: s[p_i] ≤ s[p_{i + 1}] and s[q_i] ≤ s[q_{i + 1}]. It means that if you will write down all characters of s in order of permutation indices, the resulting string will be sorted in the non-decreasing order.
Your task is to restore any such string s of length n consisting of at least k distinct lowercase Latin letters which suits the given permutations.
If there are multiple answers, you can print any of them.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 26) — the length of the string and the number of distinct characters required.
The second line of the input contains n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i are distinct integers from 1 to n) — the permutation p.
The third line of the input contains n integers q_1, q_2, ..., q_n (1 ≤ q_i ≤ n, all q_i are distinct integers from 1 to n) — the permutation q.
Output
If it is impossible to find the suitable string, print "NO" on the first line.
Otherwise print "YES" on the first line and string s on the second line. It should consist of n lowercase Latin letters, contain at least k distinct characters and suit the given permutations.
If there are multiple answers, you can print any of them.
Example
Input
3 2
1 2 3
1 3 2
Output
YES
abb
Submitted Solution:
```
from sys import stdin, stdout, setrecursionlimit
setrecursionlimit(50000)
n, k = map(int, stdin.readline().split())
p = list(map(int, stdin.readline().split()))
q = list(map(int, stdin.readline().split()))
pos = [0 for i in range(n)]
for i in range(n):
p[i] -= 1
q[i] -= 1
pos[p[i]] = i
delta = [0 for i in range(n + 1)]
for i in range(n - 1):
x = pos[q[i]]
y = pos[q[i + 1]]
if x > y:
delta[y] += 1
delta[x] -= 1
for i in range(1, n):
delta[i] += delta[i - 1]
scc = [0 for i in range(n)]
num = 0
for i in range(n):
if i == 0 or delta[i] != 0:
num += 1
scc[i] = num
if num < k:
print('NO')
exit(0)
s = ['a' for i in range(n)]
for i in range(n):
x = min(26, scc[i])
s[p[i]] = chr(96 + x)
stdout.write('YES\n')
stdout.write(''.join(s))
``` | instruction | 0 | 67,371 | 0 | 134,742 |
No | output | 1 | 67,371 | 0 | 134,743 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Authors have come up with the string s consisting of n lowercase Latin letters.
You are given two permutations of its indices (not necessary equal) p and q (both of length n). Recall that the permutation is the array of length n which contains each integer from 1 to n exactly once.
For all i from 1 to n-1 the following properties hold: s[p_i] ≤ s[p_{i + 1}] and s[q_i] ≤ s[q_{i + 1}]. It means that if you will write down all characters of s in order of permutation indices, the resulting string will be sorted in the non-decreasing order.
Your task is to restore any such string s of length n consisting of at least k distinct lowercase Latin letters which suits the given permutations.
If there are multiple answers, you can print any of them.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 26) — the length of the string and the number of distinct characters required.
The second line of the input contains n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i are distinct integers from 1 to n) — the permutation p.
The third line of the input contains n integers q_1, q_2, ..., q_n (1 ≤ q_i ≤ n, all q_i are distinct integers from 1 to n) — the permutation q.
Output
If it is impossible to find the suitable string, print "NO" on the first line.
Otherwise print "YES" on the first line and string s on the second line. It should consist of n lowercase Latin letters, contain at least k distinct characters and suit the given permutations.
If there are multiple answers, you can print any of them.
Example
Input
3 2
1 2 3
1 3 2
Output
YES
abb
Submitted Solution:
```
import sys
import threading
sys.setrecursionlimit(10000000)
cur_ans = 0
g = []
gr = []
used = []
order = []
ans = []
def dfs(v):
used[v] = True
for to in g[v]:
if not used[to]:
dfs(to)
order.append(v)
def dfs2(v):
used[v] = True
ans[v] = cur_ans
for to in gr[v]:
if not used[to]:
dfs2(to)
def main():
n, k = map(int, input().split())
#n = 200000
#k = 26
p = list(map(int, input().split()))
q = list(map(int, input().split()))
#p = [i + 1 for i in range(0, n)]
#q = [i + 1 for i in range(0, n)]
global g
g = [[] for i in range(0, n + 1)]
global gr
gr = [[] for _ in range(0, n + 1)]
order = []
global used
used = [False for _ in range(0, n + 1)]
global ans
ans = [-1 for _ in range(0, n + 1)]
p.reverse()
q.reverse()
for i in range(0, n - 1):
g[p[i + 1]].append(p[i])
gr[p[i]].append(p[i + 1])
for i in range(0, n - 1):
g[q[i + 1]].append(q[i])
gr[q[i]].append(q[i + 1])
for i in range(1, n + 1):
if not used[i]:
dfs(i)
order.reverse()
used = [False for _ in range(0, n + 1)]
for i in order:
if not used[i]:
global cur_ans
cur_ans += 1
cur_ans = min(cur_ans, 26)
dfs2(i)
if cur_ans < k:
print("NO")
else:
print("YES")
print("".join(chr(ord('a') + ans[x] - 1) for x in range(1, n + 1)))
if __name__ == "__main__":
sys.setrecursionlimit(40000000)
threading.stack_size(10240000)
thread = threading.Thread(target=main)
thread.start()
``` | instruction | 0 | 67,372 | 0 | 134,744 |
No | output | 1 | 67,372 | 0 | 134,745 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
String diversity is the number of symbols that occur in the string at least once. Diversity of s will be denoted by d(s). For example , d("aaa")=1, d("abacaba")=3.
Given a string s, consisting of lowercase Latin letters. Consider all its substrings. Obviously, any substring diversity is a number from 1 to d(s). Find statistics about substrings diversity: for each k from 1 to d(s), find how many substrings of s has a diversity of exactly k.
Input
The input consists of a single line containing s. It contains only lowercase Latin letters, the length of s is from 1 to 3·105.
Output
Print to the first line the value d(s). Print sequence t1, t2, ..., td(s) to the following lines, where ti is the number of substrings of s having diversity of exactly i.
Examples
Input
abca
Output
3
4
3
3
Input
aabacaabbad
Output
4
14
19
28
5
Note
Consider the first example.
We denote by s(i, j) a substring of "abca" with the indices in the segment [i, j].
* s(1, 1) = "a", d("a") = 1
* s(2, 2) = "b", d("b") = 1
* s(3, 3) = "c", d("c") = 1
* s(4, 4) = "a", d("a") = 1
* s(1, 2) = "ab", d("ab") = 2
* s(2, 3) = "bc", d("bc") = 2
* s(3, 4) = "ca", d("ca") = 2
* s(1, 3) = "abc", d("abc") = 3
* s(2, 4) = "bca", d("bca") = 3
* s(1, 4) = "abca", d("abca") = 3
Total number of substring with diversity 1 is 4, with diversity 2 equals 3, 3 diversity is 3.
Submitted Solution:
```
import sys
B = input()
podciagi = []
for p in range(0, len(B)):
temp = B[p:]
i = 0
for j in range(0, len(temp)):
temp2 = []
bogactwo = 0
for i in temp:
if i not in temp2:
bogactwo+=1
temp2.append(i)
podciagi.append([p, bogactwo, temp])
temp = temp[:-1]
liczbaBogactw = {}
for i in range(1, len(B)):
liczbaBogactw[i] = 0
for podciag in podciagi:
liczbaBogactw[podciag[1]] += 1
print(podciagi[0][1])
for i in liczbaBogactw:
print(liczbaBogactw[i])
``` | instruction | 0 | 67,601 | 0 | 135,202 |
No | output | 1 | 67,601 | 0 | 135,203 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
String diversity is the number of symbols that occur in the string at least once. Diversity of s will be denoted by d(s). For example , d("aaa")=1, d("abacaba")=3.
Given a string s, consisting of lowercase Latin letters. Consider all its substrings. Obviously, any substring diversity is a number from 1 to d(s). Find statistics about substrings diversity: for each k from 1 to d(s), find how many substrings of s has a diversity of exactly k.
Input
The input consists of a single line containing s. It contains only lowercase Latin letters, the length of s is from 1 to 3·105.
Output
Print to the first line the value d(s). Print sequence t1, t2, ..., td(s) to the following lines, where ti is the number of substrings of s having diversity of exactly i.
Examples
Input
abca
Output
3
4
3
3
Input
aabacaabbad
Output
4
14
19
28
5
Note
Consider the first example.
We denote by s(i, j) a substring of "abca" with the indices in the segment [i, j].
* s(1, 1) = "a", d("a") = 1
* s(2, 2) = "b", d("b") = 1
* s(3, 3) = "c", d("c") = 1
* s(4, 4) = "a", d("a") = 1
* s(1, 2) = "ab", d("ab") = 2
* s(2, 3) = "bc", d("bc") = 2
* s(3, 4) = "ca", d("ca") = 2
* s(1, 3) = "abc", d("abc") = 3
* s(2, 4) = "bca", d("bca") = 3
* s(1, 4) = "abca", d("abca") = 3
Total number of substring with diversity 1 is 4, with diversity 2 equals 3, 3 diversity is 3.
Submitted Solution:
```
import string, random
test = "aka"
def bog(stri):
used = [0 for _ in range(26)]
count = 0
global gcount
for s in stri:
used[ord(s)-97] += 1
for a in used:
if a > 0:
count += 1
return count, used
gcount, gused = bog(test)
boglist = {}
for l in range(gcount+1):
boglist[l] = 0
boglist[1] = len(test)
boglist[gcount] = 1
def split(stri):
l = 2
c, u = bog(stri[0:2])
boglist[c]+=1
#print(c)
ok = 0
while True:
for x in range(len(stri) - l):
try:
new = ord(stri[x + l]) - 97
old = ord(stri[x]) - 97
except Exception as e:
print(l, x)
#print(c, l, x, chr(old+97), chr(new+97), ">")
if(new != old):
u[new] += 1
u[old] -= 1
if(u[new] == 1): c += 1
if(u[old] == 0): c -= 1
boglist[c] += 1
l += 1
x+=1
if l == len(stri): break
new = ord(stri[x - 1]) - 97
u[new] += 1
if(u[new] == 1): c += 1
#print(c, l, x, chr(old+97), chr(new+97), "<=")
boglist[c] += 1
for x in reversed(range(len(stri) - l)):
try:
new = ord(stri[x]) - 97
old = ord(stri[x + l]) - 97
except Exception as e:
print(l, x)
#print(c, l, x, chr(old+97), chr(new+97), "<")
if(new != old):
u[new] += 1
u[old] -= 1
if(u[new] == 1): c += 1
if(u[old] == 0): c -= 1
boglist[c] += 1
l += 1
if l == len(stri): break
new = ord(stri[1 + l]) - 97
u[new] += 1
if(u[new] == 1): c += 1
boglist[c] += 1
split(test)
for x, y in boglist.items():
print(y)
``` | instruction | 0 | 67,602 | 0 | 135,204 |
No | output | 1 | 67,602 | 0 | 135,205 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
String diversity is the number of symbols that occur in the string at least once. Diversity of s will be denoted by d(s). For example , d("aaa")=1, d("abacaba")=3.
Given a string s, consisting of lowercase Latin letters. Consider all its substrings. Obviously, any substring diversity is a number from 1 to d(s). Find statistics about substrings diversity: for each k from 1 to d(s), find how many substrings of s has a diversity of exactly k.
Input
The input consists of a single line containing s. It contains only lowercase Latin letters, the length of s is from 1 to 3·105.
Output
Print to the first line the value d(s). Print sequence t1, t2, ..., td(s) to the following lines, where ti is the number of substrings of s having diversity of exactly i.
Examples
Input
abca
Output
3
4
3
3
Input
aabacaabbad
Output
4
14
19
28
5
Note
Consider the first example.
We denote by s(i, j) a substring of "abca" with the indices in the segment [i, j].
* s(1, 1) = "a", d("a") = 1
* s(2, 2) = "b", d("b") = 1
* s(3, 3) = "c", d("c") = 1
* s(4, 4) = "a", d("a") = 1
* s(1, 2) = "ab", d("ab") = 2
* s(2, 3) = "bc", d("bc") = 2
* s(3, 4) = "ca", d("ca") = 2
* s(1, 3) = "abc", d("abc") = 3
* s(2, 4) = "bca", d("bca") = 3
* s(1, 4) = "abca", d("abca") = 3
Total number of substring with diversity 1 is 4, with diversity 2 equals 3, 3 diversity is 3.
Submitted Solution:
```
import sys
B = input()
podciagi = []
for p in range(0, len(B)):
temp = B[p:]
i = 0
for j in range(0, len(temp)):
temp2 = []
bogactwo = 0
for i in temp:
if i not in temp2:
bogactwo+=1
temp2.append(i)
podciagi.append([p, bogactwo, temp])
temp = temp[:-1]
liczbaBogactw = {}
for i in range(1, len(B)):
liczbaBogactw[i] = 0
for podciag in podciagi:
liczbaBogactw[podciag[1]] += 1
print(liczbaBogactw)
print(podciagi[0][1])
for i in liczbaBogactw:
print(liczbaBogactw[i])
``` | instruction | 0 | 67,603 | 0 | 135,206 |
No | output | 1 | 67,603 | 0 | 135,207 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.
You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes.
You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
Input
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
Output
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
Examples
Input
aabc
Output
abba
Input
aabcd
Output
abcba | instruction | 0 | 67,701 | 0 | 135,402 |
Tags: constructive algorithms, greedy, strings
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
##########################################################
#from fractions import Fraction
# import math
import sys
import math
from math import gcd
# from collections import deque
# from collections import Counter
#import sys
#ys.setrecursionlimit(10 ** 6)
#for _ in range(int(input())):
#n, k = map(int, input().split())
#from bisect import bisect_right
#n =int(input())
#for _ in range(int(input())):
import bisect
#for _ in range(int(input())):
#n, m =map(int,input().split())
from collections import Counter
s=input()
arr=[0]*26
ans=""
for i in range(len(s)):
arr[ord(s[i])-97]+=1
mid=""
odd=[]
for i in range(26):
if arr[i]%2!=0:
odd.append((i,arr[i]))
odd.sort()
for i in range(len(odd)//2):
arr[odd[i][0]]+=1
arr[odd[len(odd)-i-1][0]]-=1
for i in range(26):
if arr[i]>0:
if arr[i]%2==1:
mid=chr(97+i)
ans+=chr(i+97)*(arr[i]//2)
print(ans+mid+ans[::-1])
``` | output | 1 | 67,701 | 0 | 135,403 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.
You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes.
You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
Input
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
Output
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
Examples
Input
aabc
Output
abba
Input
aabcd
Output
abcba | instruction | 0 | 67,702 | 0 | 135,404 |
Tags: constructive algorithms, greedy, strings
Correct Solution:
```
from collections import Counter
from math import ceil
def construct(vals: list) -> str:
if len(vals) == 1:
return vals[0][0] * vals[0][1]
else:
x = vals.pop(0)
assert x[1] % 2 == 0
return x[0]*(x[1]//2) + construct(vals) + x[0]*(x[1]//2)
s = input()
counter = Counter(s)
vals = [[k, v] for k, v in dict(counter).items()]
vals = sorted(vals, key=lambda x: x[0])
ixStart, ixEnd = 0, len(vals)-1
while sum(x[1] % 2 == 1 for x in vals) > 1:
if vals[ixStart][1] % 2 == 0:
ixStart += 1
elif vals[ixEnd][1] % 2 == 0:
ixEnd -= 1
else:
vals[ixStart][1] += 1
vals[ixEnd][1] -= 1
vals = list(filter(lambda x: x[1] > 0, vals))
pivot = [x[0] for x in vals if x[1] % 2 == 1]
out = "".join(s*(x//2) for s, x in vals)
out = out+("" if len(pivot) == 0 else pivot[0])+out[::-1]
print(out)
``` | output | 1 | 67,702 | 0 | 135,405 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.
You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes.
You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
Input
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
Output
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
Examples
Input
aabc
Output
abba
Input
aabcd
Output
abcba | instruction | 0 | 67,703 | 0 | 135,406 |
Tags: constructive algorithms, greedy, strings
Correct Solution:
```
S = input()
letters = {}
for i in S:
if i not in letters:
letters[i] = 1
else:
letters[i] = letters[i] + 1
used_letters = sorted(letters.keys())
num_odd = 0
used_odd = False
for i in used_letters:
if letters[i] % 2 == 1:
for j in used_letters[::-1]:
if letters[j]%2 ==1:
letters[j] -= 1
letters[i] += 1
break
for i in used_letters:
print(i*(letters[i]//2), end='')
for i in used_letters:
if letters[i]%2 == 1:
print(i, end='')
for i in used_letters[::-1]:
print(i*(letters[i]//2), end='')
``` | output | 1 | 67,703 | 0 | 135,407 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.
You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes.
You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
Input
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
Output
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
Examples
Input
aabc
Output
abba
Input
aabcd
Output
abcba | instruction | 0 | 67,704 | 0 | 135,408 |
Tags: constructive algorithms, greedy, strings
Correct Solution:
```
s = input()
i = 0
mp = [0 for x in range(26)]
out = ""
while i < len(s):
mp[ord(s[i]) - ord('a')] += 1
i += 1
front = 0
end = len(mp) - 1
while front < len(mp) and mp[front] % 2 != 1:
front += 1
while end > 0 and mp[end] % 2 != 1:
end -= 1
while front < end:
mp[end] -= 1
mp[front] += 1
front += 1
end -= 1
while front < len(mp) and mp[front] % 2 != 1:
front += 1
while end > 0 and mp[end] % 2 != 1:
end -= 1
out = ""
for i in range(len(mp)):
for k in range(mp[i] // 2):
out += chr(i + ord('a'))
rev = out[::-1]
if front < len(mp) and mp[front] % 2 == 1:
out += chr(front + ord('a'))
print(out + rev)
``` | output | 1 | 67,704 | 0 | 135,409 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.
You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes.
You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
Input
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
Output
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
Examples
Input
aabc
Output
abba
Input
aabcd
Output
abcba | instruction | 0 | 67,705 | 0 | 135,410 |
Tags: constructive algorithms, greedy, strings
Correct Solution:
```
s=input()
a=[int(i) for i in '0'*26]
k=-1
for i in s:
a[ord(i)-97]+=1
for i in range(25):
if a[i]%2!=0:
for j in range(25-i):
if a[25-j]%2!=0:
a[i]+=1
a[25-j]-=1
break
if a[i]%2!=0:
k=i
break
st=''
for i in range(26):
if a[i]>0:
st+=chr(i+97)*(a[i]//2)
if k!=-1:
st=st+chr(k+97)+st[::-1]
else:
st=st+st[::-1]
print(st)
``` | output | 1 | 67,705 | 0 | 135,411 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.
You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes.
You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
Input
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
Output
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
Examples
Input
aabc
Output
abba
Input
aabcd
Output
abcba | instruction | 0 | 67,706 | 0 | 135,412 |
Tags: constructive algorithms, greedy, strings
Correct Solution:
```
s,l,p,z,x,k=input(),[0]*27,0,"","",""
for i in s:l[ord(i)-97]+=1
p=sum(1for i in l if i%2)//2
for i in range(26,-1,-1):
if l[i]%2 and p:
p-=1
l[i]-=1
for j in range(26):
if l[j]%2:
l[j]+=1
break
for j in range(26):
o=chr(j+97)*(l[j]//2)
z+=o
x=o+x
if l[j]%2:k=chr(j+97)
print(z+k+x)
``` | output | 1 | 67,706 | 0 | 135,413 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.
You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes.
You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
Input
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
Output
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
Examples
Input
aabc
Output
abba
Input
aabcd
Output
abcba | instruction | 0 | 67,707 | 0 | 135,414 |
Tags: constructive algorithms, greedy, strings
Correct Solution:
```
from math import floor
s = input()
n = len(s)
ans = ['*'] * n
d = {}
e = []
o = []
for c in s:
if c in d:
d[c] += 1
else:
d[c] = 1
for k in d:
qnt = floor(d[k] / 2)
e += [k] * qnt
d[k] -= (qnt * 2)
if d[k]:
o.append(k)
e.sort()
o.sort()
if len(o) % 2:
o = o[0:floor(len(o) / 2) + 1]
else:
o = o[0:floor(len(o) / 2)]
ans = []
if len(s) % 2:
ans = e + o[:-1]
ans.sort()
ans += list(o[-1]) + ans[::-1]
else:
ans = e + o
ans.sort()
ans += ans[::-1]
print(''.join(ans))
``` | output | 1 | 67,707 | 0 | 135,415 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.
You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes.
You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
Input
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
Output
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
Examples
Input
aabc
Output
abba
Input
aabcd
Output
abcba | instruction | 0 | 67,708 | 0 | 135,416 |
Tags: constructive algorithms, greedy, strings
Correct Solution:
```
inp_string = input()
LOWERCASELETTERS = "abcdefghijklmnopqrstuvwxyz"
OCCS = {letter:0 for letter in LOWERCASELETTERS}
for sym in inp_string:
OCCS[sym] += 1
ODD_OCCS = [letter for letter in LOWERCASELETTERS if OCCS[letter] % 2 != 0]
N_ODD = len(ODD_OCCS)
for i in range(N_ODD // 2):
OCCS[ODD_OCCS[i]] += 1
OCCS[ODD_OCCS[N_ODD - 1 -i]] -= 1
ans = []
for letter in LOWERCASELETTERS:
ans += ([letter] * ((OCCS[letter]) // 2))
if N_ODD != 0 and OCCS[ODD_OCCS[(N_ODD-1)//2]] % 2 != 0:
ans += ODD_OCCS[(N_ODD-1)//2]
for letter in LOWERCASELETTERS[::-1]:
ans += ([letter] * ((OCCS[letter]) // 2))
print(''.join(ans))
``` | output | 1 | 67,708 | 0 | 135,417 |
Provide tags and a correct Python 2 solution for this coding contest problem.
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.
You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes.
You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
Input
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
Output
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
Examples
Input
aabc
Output
abba
Input
aabcd
Output
abcba | instruction | 0 | 67,709 | 0 | 135,418 |
Tags: constructive algorithms, greedy, strings
Correct Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
def in_num():
return int(raw_input())
def in_arr():
return map(int,raw_input().split())
def pr_num(n):
stdout.write(str(n)+'\n')
def pr_arr(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)
ans=''
mid=''
d=Counter(s)
c=0
mid=''
temp=[]
for i in sorted(d):
if d[i]%2:
temp.append(i)
c+=1
if n%2:
n1=len(temp)
mid=temp[n1/2]
for i in sorted(d):
if d[i]%2:
if c>1:
ans+=(i*((d[i]+1)/2))
c-=2
else:
ans+=i*(d[i]/2)
else:
ans+=i*(d[i]/2)
pr(ans+mid+''.join(reversed(ans)))
``` | output | 1 | 67,709 | 0 | 135,419 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.
You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes.
You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
Input
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
Output
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
Examples
Input
aabc
Output
abba
Input
aabcd
Output
abcba
Submitted Solution:
```
s = input()
chars = [0]*26
offset = ord('a')
for ch in s:
chars[ord(ch)-offset] += 1
i = 0
j = 25
while i < j:
if chars[i] % 2 == 1:
while chars[j] % 2 == 0:
if i >= j:
break
j -= 1
else:
chars[i] += 1
chars[j] -= 1
i += 1
res = ''
odd_i = -1
for i in range(26):
if chars[i] % 2 == 1:
odd_i = i
res += chr(i+offset)*(chars[i]//2)
if odd_i != -1:
print(f'{res}{chr(odd_i+offset)}{res[::-1]}')
else:
print(f'{res}{res[::-1]}')
``` | instruction | 0 | 67,710 | 0 | 135,420 |
Yes | output | 1 | 67,710 | 0 | 135,421 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.
You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes.
You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
Input
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
Output
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
Examples
Input
aabc
Output
abba
Input
aabcd
Output
abcba
Submitted Solution:
```
#!/usr/bin/env python3
# 600C_palindrom.py - Codeforces.com/problemset/problem/600/C by Sergey 2015
import unittest
import sys
###############################################################################
# Palindrom Class (Main Program)
###############################################################################
class Palindrom:
""" Palindrom representation """
def __init__(self, test_inputs=None):
""" Default constructor """
it = iter(test_inputs.split("\n")) if test_inputs else None
def uinput():
return next(it) if it else sys.stdin.readline().rstrip()
# Reading single elements
self.s = uinput()
self.cnt = {}
for c in self.s:
self.cnt[c] = self.cnt.get(c, 0) + 1
self.odd = len(self.s) % 2
self.pcnt = dict(self.cnt)
for i in reversed(sorted(self.pcnt)):
if self.pcnt[i] % 2:
self.pcnt[i] -= 1
found = 0
for j in sorted(self.pcnt):
if self.pcnt[j] % 2:
self.pcnt[j] += 1
found = 1
break
if not found:
self.pcnt[i] += 1
def calculate(self):
""" Main calcualtion function of the class """
result = []
mid = []
for c in sorted(self.pcnt):
n = self.pcnt[c]
if n > 0:
for j in range(n // 2):
result.append(c)
if n % 2:
mid.append(c)
return "".join(result + mid + list(reversed(result)))
###############################################################################
# Unit Tests
###############################################################################
class unitTests(unittest.TestCase):
def test_single_test(self):
""" Palindrom class testing """
# Constructor test
test = "aabc"
d = Palindrom(test)
self.assertEqual(d.cnt["c"], 1)
self.assertEqual(d.pcnt["c"], 0)
# Sample test
self.assertEqual(Palindrom(test).calculate(), "abba")
# Sample test
test = "aabcd"
self.assertEqual(Palindrom(test).calculate(), "abcba")
# Sample test
test = "aabbcccdd"
self.assertEqual(Palindrom(test).calculate(), "abcdcdcba")
# My tests
test = ""
# self.assertEqual(Palindrom(test).calculate(), "0")
# Time limit test
# self.time_limit_test(5000)
def time_limit_test(self, nmax):
""" Timelimit testing """
import random
import timeit
# Random inputs
test = str(nmax) + " " + str(nmax) + "\n"
numnums = [str(i) + " " + str(i+1) for i in range(nmax)]
test += "\n".join(numnums) + "\n"
nums = [random.randint(1, 10000) for i in range(nmax)]
test += " ".join(map(str, nums)) + "\n"
# Run the test
start = timeit.default_timer()
d = Palindrom(test)
calc = timeit.default_timer()
d.calculate()
stop = timeit.default_timer()
print("\nTimelimit Test: " +
"{0:.3f}s (init {1:.3f}s calc {2:.3f}s)".
format(stop-start, calc-start, stop-calc))
if __name__ == "__main__":
# Avoiding recursion limitaions
sys.setrecursionlimit(100000)
if sys.argv[-1] == "-ut":
unittest.main(argv=[" "])
# Print the result string
sys.stdout.write(Palindrom().calculate())
``` | instruction | 0 | 67,711 | 0 | 135,422 |
Yes | output | 1 | 67,711 | 0 | 135,423 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.
You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes.
You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
Input
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
Output
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
Examples
Input
aabc
Output
abba
Input
aabcd
Output
abcba
Submitted Solution:
```
import sys
import bisect
from bisect import bisect_left as lb
input_=lambda: sys.stdin.readline().strip("\r\n")
from math import log
from math import gcd
from math import atan2,acos
from random import randint
sa=lambda :input_()
sb=lambda:int(input_())
sc=lambda:input_().split()
sd=lambda:list(map(int,input_().split()))
se=lambda:float(input_())
sf=lambda:list(input_())
flsh=lambda: sys.stdout.flush()
#sys.setrecursionlimit(10**6)
mod=10**9+7
gp=[]
cost=[]
dp=[]
mx=[]
ans1=[]
ans2=[]
special=[]
specnode=[]
a=0
kthpar=[]
def dfs(root,par):
if par!=-1:
dp[root]=dp[par]+1
for i in range(1,20):
if kthpar[root][i-1]!=-1:
kthpar[root][i]=kthpar[kthpar[root][i-1]][i-1]
for child in gp[root]:
if child==par:continue
kthpar[child][0]=root
dfs(child,root)
def hnbhai():
a=list(sa())
d={}
front=[]
back=[]
mid=[]
for i in a:
d[i]=d.get(i,0)+1
for i in d:
if d[i]%2==1:
mid.append(i)
front.extend([i]*(d[i]//2))
back.extend([i]*(d[i]//2))
mid.sort()
while(len(mid)>=2):
x=mid.pop(0)
front.append(x)
back.append(x)
mid.pop()
front.sort()
back.sort(reverse=True)
front+=mid+back
print("".join(front))
for _ in range(1):
hnbhai()
``` | instruction | 0 | 67,712 | 0 | 135,424 |
Yes | output | 1 | 67,712 | 0 | 135,425 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.
You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes.
You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
Input
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
Output
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
Examples
Input
aabc
Output
abba
Input
aabcd
Output
abcba
Submitted Solution:
```
import sys
input = sys.stdin.readline
S = list(input())[: -1]
table = [0] * 26
a = ord("a")
for x in S: table[ord(x) - a] += 1
k = 0
for i in range(26):
if table[i] % 2: k += 1
k -= len(S) % 2
for i in range(25, -1, -1):
if k == 0: break
if table[i] % 2 == 0: continue
for j in range(26):
if i == j: continue
if table[j] % 2 == 0: continue
table[i] -= 1
table[j] += 1
break
k -= 1
res = []
for i in range(26):
res += [chr(i + a)] * (table[i] // 2)
if len(S) % 2:
for i in range(26):
if table[i] % 2:
res += [chr(i + a)] + res[: : -1]
break
else: res += res[: : -1]
print("".join(res))
``` | instruction | 0 | 67,713 | 0 | 135,426 |
Yes | output | 1 | 67,713 | 0 | 135,427 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.
You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes.
You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
Input
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
Output
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
Examples
Input
aabc
Output
abba
Input
aabcd
Output
abcba
Submitted Solution:
```
s = input()
s = sorted(s)
tam = len(s)-1
qt = [0 for i in range(26)]
for i in range(len(s)):
qt[ord(s[i])-97] += 1
# print(qt)
for i in range(len(s)-2, -1, -2):
# print(s[i])
if qt[ord(s[i])-97] > 1:
s.append(s[i])
s[i] = ""
sn = []
# print(s)
for i in range(len(s)):
if s[i] != '':
sn.append(s[i])
# print(sn)
i = 0
j = tam
while i < j:
if sn[i] != sn[j]:
sn[j] = sn[i]
i+=1
j-=1
for i in range(len(sn)):
print(sn[i], end="")
print()
# aaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbccccccccccccccddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeefffffffffffffffffffggggggggggggggggggghhhhhhhhhhhhhhhhhiiiiiiiiiiiiiiiiiiiiiijjjjjjjjjjjjjjjjkkkkkkkkkkkkkkkkkkkkkkkllllllllllllllllmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnnnnnnnnnooooooooooooooooooooooppppppppppppppppppppppppqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrrsssssssssssssssssssssstttttttttttttttttttuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzz
# aaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbccccccccccccccddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeefffffffffffffffffffgggggggggggggggggghhhhhhhhhhhhhhhhhiiiiiiiiiiiiiiiiiiiiijjjjjjjjjjjjjjjjkkkkkkkkkkkkkkkkkkkkkkllllllllllllllllmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnnnnnnnnnooooooooooooooooooooooppppppppppppppppppppppppqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrrssssssssssssssssssssssttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzz
``` | instruction | 0 | 67,714 | 0 | 135,428 |
No | output | 1 | 67,714 | 0 | 135,429 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.
You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes.
You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
Input
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
Output
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
Examples
Input
aabc
Output
abba
Input
aabcd
Output
abcba
Submitted Solution:
```
string = input()
alpha = 'abcdefghijklmnopqrstuvwxyz'
counter = {x: 0 for x in alpha}
odd = []
out = []
spe = ''
ans = ''
for i in string:
counter[i] += 1
for key, value in counter.items():
if value % 2 == 1:
odd.append(key)
odd.sort()
if len(odd) % 2 == 1:
half = len(odd) // 2 + 1
else:
half = len(odd) // 2
for i in range(half, len(odd)):
counter[odd[i]] -= 1
counter[odd[i-half]] += 1
for key, value in counter.items():
if value != 0:
if value % 2 == 1:
spe = key
counter[key] = 0
else:
counter[key] //= 2
for key, value in sorted(counter.items()):
while value != 0:
ans += key
value -= 1
re = ans[::-1]
if spe:
ans += spe
ans += re
print(ans)
``` | instruction | 0 | 67,715 | 0 | 135,430 |
No | output | 1 | 67,715 | 0 | 135,431 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.
You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes.
You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
Input
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
Output
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
Examples
Input
aabc
Output
abba
Input
aabcd
Output
abcba
Submitted Solution:
```
from collections import Counter, OrderedDict
s = list(input())
d = Counter()
d.update(s)
d = OrderedDict(sorted(d.items(), key=lambda x:x[0]))
odds = {}
for key in d:
if d[key]%2:
odds[key] = d[key]
l = len(odds)
idx = 0
for key in odds:
if l%2:
if idx < l//2:
odds[key] += 1
d[key] += 1
elif idx == l//2:
pass
else:
odds[key] -= 1
d[key] -= 1
else:
if idx < l//2:
odds[key] += 1
d[key] += 1
else:
odds[key] -= 1
d[key] -= 1
idx += 1
ans = ""
flag = False
c = ""
for key in d:
if d[key]%2:
if d[key] > 1:
flag = True
c = key
ans += key*(max(d[key]//2,1))
else:
ans += key*(d[key]//2)
if flag:
ans += c
if len(s)%2:
print(ans[:len(ans)-1] + ans[::-1])
else:
print(ans + ans[::-1])
``` | instruction | 0 | 67,716 | 0 | 135,432 |
No | output | 1 | 67,716 | 0 | 135,433 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.
You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes.
You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
Input
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
Output
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
Examples
Input
aabc
Output
abba
Input
aabcd
Output
abcba
Submitted Solution:
```
s = input()
res = [0] * len(s)
for i in range(len(s)//2):
k = min(s[i], s[len(s)-1-i]) #если не заработает, нужно написать ord
res[i], res[len(s)-1-i]= k, k #эти буквы должны быть равны, причем т.к. нужна минимальность строки, то минимуму из них
print(''.join(res))
``` | instruction | 0 | 67,717 | 0 | 135,434 |
No | output | 1 | 67,717 | 0 | 135,435 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Pushok the dog has been chasing Imp for a few hours already.
<image>
Fortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner.
While moving, the robot generates a string t consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string t as the number of occurrences of string "sh" as a subsequence in it, in other words, the number of such pairs (i, j), that i < j and <image> and <image>.
The robot is off at the moment. Imp knows that it has a sequence of strings ti in its memory, and he can arbitrary change their order. When the robot is started, it generates the string t as a concatenation of these strings in the given order. The noise of the resulting string equals the noise of this concatenation.
Help Imp to find the maximum noise he can achieve by changing the order of the strings.
Input
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of strings in robot's memory.
Next n lines contain the strings t1, t2, ..., tn, one per line. It is guaranteed that the strings are non-empty, contain only English letters 's' and 'h' and their total length does not exceed 105.
Output
Print a single integer — the maxumum possible noise Imp can achieve by changing the order of the strings.
Examples
Input
4
ssh
hs
s
hhhs
Output
18
Input
2
h
s
Output
1
Note
The optimal concatenation in the first sample is ssshhshhhs. | instruction | 0 | 67,847 | 0 | 135,694 |
Tags: greedy, sortings
Correct Solution:
```
n = int(input())
a = []
for i in range(n):
s = input()
l = 0
for c in s:
if c=="s":
l+=1
a.append((s, l/len(s)))
a.sort(key=lambda x: x[1], reverse=True)
ns = 0
ans = 0
for st, _ in a:
for c in st:
if c == 's':
ns += 1
else:
ans += ns
print(ans)
``` | output | 1 | 67,847 | 0 | 135,695 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Pushok the dog has been chasing Imp for a few hours already.
<image>
Fortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner.
While moving, the robot generates a string t consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string t as the number of occurrences of string "sh" as a subsequence in it, in other words, the number of such pairs (i, j), that i < j and <image> and <image>.
The robot is off at the moment. Imp knows that it has a sequence of strings ti in its memory, and he can arbitrary change their order. When the robot is started, it generates the string t as a concatenation of these strings in the given order. The noise of the resulting string equals the noise of this concatenation.
Help Imp to find the maximum noise he can achieve by changing the order of the strings.
Input
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of strings in robot's memory.
Next n lines contain the strings t1, t2, ..., tn, one per line. It is guaranteed that the strings are non-empty, contain only English letters 's' and 'h' and their total length does not exceed 105.
Output
Print a single integer — the maxumum possible noise Imp can achieve by changing the order of the strings.
Examples
Input
4
ssh
hs
s
hhhs
Output
18
Input
2
h
s
Output
1
Note
The optimal concatenation in the first sample is ssshhshhhs. | instruction | 0 | 67,850 | 0 | 135,700 |
Tags: greedy, sortings
Correct Solution:
```
#from collections import defaultdict
get= lambda : map(int,input().split())
f=next(get())
a=[]
# http://codeforces.com/problemset/problem/922/D
for i in range(f):
s=input()
a.append(s)
def key(y):
t=y.count('s')
if not t:
return float('inf')
return -(t-len(y))/t
a.sort(key=key)
scnt=0
ans=0
s=''.join(a)
for i in s:
if i=='s':
scnt+=1
else:
ans+=scnt
print(ans)
``` | output | 1 | 67,850 | 0 | 135,701 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Pushok the dog has been chasing Imp for a few hours already.
<image>
Fortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner.
While moving, the robot generates a string t consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string t as the number of occurrences of string "sh" as a subsequence in it, in other words, the number of such pairs (i, j), that i < j and <image> and <image>.
The robot is off at the moment. Imp knows that it has a sequence of strings ti in its memory, and he can arbitrary change their order. When the robot is started, it generates the string t as a concatenation of these strings in the given order. The noise of the resulting string equals the noise of this concatenation.
Help Imp to find the maximum noise he can achieve by changing the order of the strings.
Input
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of strings in robot's memory.
Next n lines contain the strings t1, t2, ..., tn, one per line. It is guaranteed that the strings are non-empty, contain only English letters 's' and 'h' and their total length does not exceed 105.
Output
Print a single integer — the maxumum possible noise Imp can achieve by changing the order of the strings.
Examples
Input
4
ssh
hs
s
hhhs
Output
18
Input
2
h
s
Output
1
Note
The optimal concatenation in the first sample is ssshhshhhs. | instruction | 0 | 67,851 | 0 | 135,702 |
Tags: greedy, sortings
Correct Solution:
```
import sys
#f = open('input', 'r')
f = sys.stdin
n = int(f.readline())
s = [f.readline().strip() for _ in range(n)]
s = [(x, x.count('s'), x.count('h')) for x in s]
s = sorted(s, key=lambda x: x[2]/float(x[1]+0.00000001))
s = ''.join(x[0] for x in s)
cs = 0
ans = 0
for x in s:
if x == 's':
cs += 1
else:
ans += cs
print(ans)
``` | output | 1 | 67,851 | 0 | 135,703 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Pushok the dog has been chasing Imp for a few hours already.
<image>
Fortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner.
While moving, the robot generates a string t consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string t as the number of occurrences of string "sh" as a subsequence in it, in other words, the number of such pairs (i, j), that i < j and <image> and <image>.
The robot is off at the moment. Imp knows that it has a sequence of strings ti in its memory, and he can arbitrary change their order. When the robot is started, it generates the string t as a concatenation of these strings in the given order. The noise of the resulting string equals the noise of this concatenation.
Help Imp to find the maximum noise he can achieve by changing the order of the strings.
Input
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of strings in robot's memory.
Next n lines contain the strings t1, t2, ..., tn, one per line. It is guaranteed that the strings are non-empty, contain only English letters 's' and 'h' and their total length does not exceed 105.
Output
Print a single integer — the maxumum possible noise Imp can achieve by changing the order of the strings.
Examples
Input
4
ssh
hs
s
hhhs
Output
18
Input
2
h
s
Output
1
Note
The optimal concatenation in the first sample is ssshhshhhs. | instruction | 0 | 67,852 | 0 | 135,704 |
Tags: greedy, sortings
Correct Solution:
```
n = int(input())
ts = []
res = 0
for _ in range(n):
i = input().strip()
m_res = 0
s_count = 0
for c in i:
if c == 's':
s_count += 1
else:
m_res += s_count
res += m_res
ts.append((i.count('s'), i.count('h')))
ts = sorted(ts, key=lambda k: float(k[0]) / float(k[1]) if k[1] else float('inf'), reverse=True)
ss = [s for s, h in ts]
hs2 = [h for s, h in ts]
hs = [0 for _ in ts]
for i in range(n-2,-1,-1):
hs[i] = hs2[i + 1] + hs[i+1]
#print(ss, hs2, hs)
for i in range(n):
res += ss[i] * hs[i]
print(res)
``` | output | 1 | 67,852 | 0 | 135,705 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.