message stringlengths 2 28.7k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 21 109k | cluster float64 7 7 | __index_level_0__ int64 42 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it!
Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from left to right, and the i-th piece has a colour si, denoted by a lowercase English letter. Nadeko will repaint at most m of the pieces to give each of them an arbitrary new colour (still denoted by a lowercase English letter). After this work, she finds out all subsegments of the garland containing pieces of only colour c — Brother Koyomi's favourite one, and takes the length of the longest among them to be the Koyomity of the garland.
For instance, let's say the garland is represented by "kooomo", and Brother Koyomi's favourite colour is "o". Among all subsegments containing pieces of "o" only, "ooo" is the longest, with a length of 3. Thus the Koyomity of this garland equals 3.
But problem arises as Nadeko is unsure about Brother Koyomi's favourite colour, and has swaying ideas on the amount of work to do. She has q plans on this, each of which can be expressed as a pair of an integer mi and a lowercase letter ci, meanings of which are explained above. You are to find out the maximum Koyomity achievable after repainting the garland according to each plan.
Input
The first line of input contains a positive integer n (1 ≤ n ≤ 1 500) — the length of the garland.
The second line contains n lowercase English letters s1s2... sn as a string — the initial colours of paper pieces on the garland.
The third line contains a positive integer q (1 ≤ q ≤ 200 000) — the number of plans Nadeko has.
The next q lines describe one plan each: the i-th among them contains an integer mi (1 ≤ mi ≤ n) — the maximum amount of pieces to repaint, followed by a space, then by a lowercase English letter ci — Koyomi's possible favourite colour.
Output
Output q lines: for each work plan, output one line containing an integer — the largest Koyomity achievable after repainting the garland according to it.
Examples
Input
6
koyomi
3
1 o
4 o
4 m
Output
3
6
5
Input
15
yamatonadeshiko
10
1 a
2 a
3 a
4 a
5 a
1 b
2 b
3 b
4 b
5 b
Output
3
4
5
7
8
1
2
3
4
5
Input
10
aaaaaaaaaa
2
10 b
10 z
Output
10
10
Note
In the first sample, there are three plans:
* In the first plan, at most 1 piece can be repainted. Repainting the "y" piece to become "o" results in "kooomi", whose Koyomity of 3 is the best achievable;
* In the second plan, at most 4 pieces can be repainted, and "oooooo" results in a Koyomity of 6;
* In the third plan, at most 4 pieces can be repainted, and "mmmmmi" and "kmmmmm" both result in a Koyomity of 5.
Submitted Solution:
```
""" Python 3 compatibility tools. """
from __future__ import division, print_function
import itertools
import sys
import os
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
input = raw_input
range = xrange
filter = itertools.ifilter
map = itertools.imap
zip = itertools.izip
def is_it_local():
script_dir = str(os.getcwd()).split('/')
username = "dipta007"
return username in script_dir
def READ(fileName):
if is_it_local():
sys.stdin = open(f'./{fileName}', 'r')
# 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")
if not is_it_local():
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
def input1(type=int):
return type(input())
def input2(type=int):
[a, b] = list(map(type, input().split()))
return a, b
def input3(type=int):
[a, b, c] = list(map(type, input().split()))
return a, b, c
def input_array(type=int):
return list(map(type, input().split()))
def input_string():
s = input()
return list(s)
def debug(*args):
if is_it_local():
st = ""
for arg in args:
st += f"{arg} "
print(st)
else: pass
##############################################################
ltr = [[] for _ in range(26)]
memo = {}
def main():
n = input1()
st = input_string()
for l in range(97, 97+26):
ltr[l-97].append(0)
ch = chr(l)
cum = 0
for i in range(n):
if st[i] == ch:
cum += 1
ltr[l-97].append(cum)
q = input1()
for i in range(q):
[m, c] = list(input().split())
m = int(m)
if c in memo and m in memo[c]:
print(memo[c][m])
continue
res = m
low = 1
z = 0
l = ord(c) - 97
for high in range(0, n+1):
tot = high - low + 1
now = ltr[l][high] - ltr[l][low-1]
need = tot - now
# debug(high, low, tot, now, need)
while need > m:
low += 1
tot = high - low + 1
now = ltr[l][high] - ltr[l][low-1]
need = tot - now
res = max(res, high - low + 1)
if c not in memo:
memo[c] = {}
memo[c][m] = res
print(res)
pass
if __name__ == '__main__':
# READ('in.txt')
main()
``` | instruction | 0 | 77,937 | 7 | 155,874 |
Yes | output | 1 | 77,937 | 7 | 155,875 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it!
Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from left to right, and the i-th piece has a colour si, denoted by a lowercase English letter. Nadeko will repaint at most m of the pieces to give each of them an arbitrary new colour (still denoted by a lowercase English letter). After this work, she finds out all subsegments of the garland containing pieces of only colour c — Brother Koyomi's favourite one, and takes the length of the longest among them to be the Koyomity of the garland.
For instance, let's say the garland is represented by "kooomo", and Brother Koyomi's favourite colour is "o". Among all subsegments containing pieces of "o" only, "ooo" is the longest, with a length of 3. Thus the Koyomity of this garland equals 3.
But problem arises as Nadeko is unsure about Brother Koyomi's favourite colour, and has swaying ideas on the amount of work to do. She has q plans on this, each of which can be expressed as a pair of an integer mi and a lowercase letter ci, meanings of which are explained above. You are to find out the maximum Koyomity achievable after repainting the garland according to each plan.
Input
The first line of input contains a positive integer n (1 ≤ n ≤ 1 500) — the length of the garland.
The second line contains n lowercase English letters s1s2... sn as a string — the initial colours of paper pieces on the garland.
The third line contains a positive integer q (1 ≤ q ≤ 200 000) — the number of plans Nadeko has.
The next q lines describe one plan each: the i-th among them contains an integer mi (1 ≤ mi ≤ n) — the maximum amount of pieces to repaint, followed by a space, then by a lowercase English letter ci — Koyomi's possible favourite colour.
Output
Output q lines: for each work plan, output one line containing an integer — the largest Koyomity achievable after repainting the garland according to it.
Examples
Input
6
koyomi
3
1 o
4 o
4 m
Output
3
6
5
Input
15
yamatonadeshiko
10
1 a
2 a
3 a
4 a
5 a
1 b
2 b
3 b
4 b
5 b
Output
3
4
5
7
8
1
2
3
4
5
Input
10
aaaaaaaaaa
2
10 b
10 z
Output
10
10
Note
In the first sample, there are three plans:
* In the first plan, at most 1 piece can be repainted. Repainting the "y" piece to become "o" results in "kooomi", whose Koyomity of 3 is the best achievable;
* In the second plan, at most 4 pieces can be repainted, and "oooooo" results in a Koyomity of 6;
* In the third plan, at most 4 pieces can be repainted, and "mmmmmi" and "kmmmmm" both result in a Koyomity of 5.
Submitted Solution:
```
import sys
n = int(sys.stdin.readline().strip())
s = sys.stdin.readline().strip()
dp = [[-1] * (n + 1) for i in range(26)]
for c in range(26):
for j in range(n):
tst = 1 if s[j] == chr(c + 97) else 0
dp[c][1 - tst] = max(dp[c][1 - tst], 1)
for k in range(j + 1, n):
if s[k] == chr(c + 97):tst += 1
dp[c][k - j + 1 - tst] = max(dp[c][k - j + 1 - tst], k - j + 1)
#for c in range(26):
# for j in range(n):
# dp[c][j + 1] = max(dp[c][j], dp[c][j + 1])
q = int(sys.stdin.readline().strip())
for i in range(q):
m, c = [item for item in sys.stdin.readline().strip().split()]
m = int(m)
#print(max([dp[ord(c) - 97][u] for u in range(m + 1)]))
print(dp[ord(c) - 97][m]) if dp[ord(c) - 97][m] != -1 else print(n)
``` | instruction | 0 | 77,938 | 7 | 155,876 |
Yes | output | 1 | 77,938 | 7 | 155,877 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it!
Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from left to right, and the i-th piece has a colour si, denoted by a lowercase English letter. Nadeko will repaint at most m of the pieces to give each of them an arbitrary new colour (still denoted by a lowercase English letter). After this work, she finds out all subsegments of the garland containing pieces of only colour c — Brother Koyomi's favourite one, and takes the length of the longest among them to be the Koyomity of the garland.
For instance, let's say the garland is represented by "kooomo", and Brother Koyomi's favourite colour is "o". Among all subsegments containing pieces of "o" only, "ooo" is the longest, with a length of 3. Thus the Koyomity of this garland equals 3.
But problem arises as Nadeko is unsure about Brother Koyomi's favourite colour, and has swaying ideas on the amount of work to do. She has q plans on this, each of which can be expressed as a pair of an integer mi and a lowercase letter ci, meanings of which are explained above. You are to find out the maximum Koyomity achievable after repainting the garland according to each plan.
Input
The first line of input contains a positive integer n (1 ≤ n ≤ 1 500) — the length of the garland.
The second line contains n lowercase English letters s1s2... sn as a string — the initial colours of paper pieces on the garland.
The third line contains a positive integer q (1 ≤ q ≤ 200 000) — the number of plans Nadeko has.
The next q lines describe one plan each: the i-th among them contains an integer mi (1 ≤ mi ≤ n) — the maximum amount of pieces to repaint, followed by a space, then by a lowercase English letter ci — Koyomi's possible favourite colour.
Output
Output q lines: for each work plan, output one line containing an integer — the largest Koyomity achievable after repainting the garland according to it.
Examples
Input
6
koyomi
3
1 o
4 o
4 m
Output
3
6
5
Input
15
yamatonadeshiko
10
1 a
2 a
3 a
4 a
5 a
1 b
2 b
3 b
4 b
5 b
Output
3
4
5
7
8
1
2
3
4
5
Input
10
aaaaaaaaaa
2
10 b
10 z
Output
10
10
Note
In the first sample, there are three plans:
* In the first plan, at most 1 piece can be repainted. Repainting the "y" piece to become "o" results in "kooomi", whose Koyomity of 3 is the best achievable;
* In the second plan, at most 4 pieces can be repainted, and "oooooo" results in a Koyomity of 6;
* In the third plan, at most 4 pieces can be repainted, and "mmmmmi" and "kmmmmm" both result in a Koyomity of 5.
Submitted Solution:
```
#------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
_str = str
str = lambda x=b"": x if type(x) is bytes else _str(x).encode()
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")
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
n=int(input())
s=input()
c=[[0 for j in range(n+1)]for i in range(26)]
for k in range(26):
for i in range(n):
rep=0
for j in range(i,n):
if s[j]!=chr(97+k):
rep+=1
c[k][rep]=max(c[k][rep],j-i+1)
for j in range(1,n+1):
c[k][j]=max(c[k][j],c[k][j-1])
t= int(input())
for i in range(t):
r,d=map(str,input().split())
print(c[ord(d)-97][int(r)])
``` | instruction | 0 | 77,939 | 7 | 155,878 |
Yes | output | 1 | 77,939 | 7 | 155,879 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it!
Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from left to right, and the i-th piece has a colour si, denoted by a lowercase English letter. Nadeko will repaint at most m of the pieces to give each of them an arbitrary new colour (still denoted by a lowercase English letter). After this work, she finds out all subsegments of the garland containing pieces of only colour c — Brother Koyomi's favourite one, and takes the length of the longest among them to be the Koyomity of the garland.
For instance, let's say the garland is represented by "kooomo", and Brother Koyomi's favourite colour is "o". Among all subsegments containing pieces of "o" only, "ooo" is the longest, with a length of 3. Thus the Koyomity of this garland equals 3.
But problem arises as Nadeko is unsure about Brother Koyomi's favourite colour, and has swaying ideas on the amount of work to do. She has q plans on this, each of which can be expressed as a pair of an integer mi and a lowercase letter ci, meanings of which are explained above. You are to find out the maximum Koyomity achievable after repainting the garland according to each plan.
Input
The first line of input contains a positive integer n (1 ≤ n ≤ 1 500) — the length of the garland.
The second line contains n lowercase English letters s1s2... sn as a string — the initial colours of paper pieces on the garland.
The third line contains a positive integer q (1 ≤ q ≤ 200 000) — the number of plans Nadeko has.
The next q lines describe one plan each: the i-th among them contains an integer mi (1 ≤ mi ≤ n) — the maximum amount of pieces to repaint, followed by a space, then by a lowercase English letter ci — Koyomi's possible favourite colour.
Output
Output q lines: for each work plan, output one line containing an integer — the largest Koyomity achievable after repainting the garland according to it.
Examples
Input
6
koyomi
3
1 o
4 o
4 m
Output
3
6
5
Input
15
yamatonadeshiko
10
1 a
2 a
3 a
4 a
5 a
1 b
2 b
3 b
4 b
5 b
Output
3
4
5
7
8
1
2
3
4
5
Input
10
aaaaaaaaaa
2
10 b
10 z
Output
10
10
Note
In the first sample, there are three plans:
* In the first plan, at most 1 piece can be repainted. Repainting the "y" piece to become "o" results in "kooomi", whose Koyomity of 3 is the best achievable;
* In the second plan, at most 4 pieces can be repainted, and "oooooo" results in a Koyomity of 6;
* In the third plan, at most 4 pieces can be repainted, and "mmmmmi" and "kmmmmm" both result in a Koyomity of 5.
Submitted Solution:
```
from sys import stdin
from sys import stdout
def main():
n = int(stdin.readline())
s = stdin.readline()
d = {chr(i): [0 for j in range(n + 1)] for i in range(97, 123)}
for i in range(97, 123):
for j in range(n):
dp = 1 if s[j] == chr(i) else 0
d[chr(i)][1 - dp] = max(d[chr(i)][1 - dp], 1)
for u in range(j + 1, n):
if s[u] == chr(i):
dp += 1
d[chr(i)][u - j + 1 - dp] = max(d[chr(i)][u - j + 1 - dp], u - j + 1)
q = int(stdin.readline())
for i in range(q):
m, c = stdin.readline().split()
m = int(m)
res = d[c][m]
if res == 0:
res = n
stdout.write(str(res) + '\n')
main()
``` | instruction | 0 | 77,940 | 7 | 155,880 |
Yes | output | 1 | 77,940 | 7 | 155,881 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it!
Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from left to right, and the i-th piece has a colour si, denoted by a lowercase English letter. Nadeko will repaint at most m of the pieces to give each of them an arbitrary new colour (still denoted by a lowercase English letter). After this work, she finds out all subsegments of the garland containing pieces of only colour c — Brother Koyomi's favourite one, and takes the length of the longest among them to be the Koyomity of the garland.
For instance, let's say the garland is represented by "kooomo", and Brother Koyomi's favourite colour is "o". Among all subsegments containing pieces of "o" only, "ooo" is the longest, with a length of 3. Thus the Koyomity of this garland equals 3.
But problem arises as Nadeko is unsure about Brother Koyomi's favourite colour, and has swaying ideas on the amount of work to do. She has q plans on this, each of which can be expressed as a pair of an integer mi and a lowercase letter ci, meanings of which are explained above. You are to find out the maximum Koyomity achievable after repainting the garland according to each plan.
Input
The first line of input contains a positive integer n (1 ≤ n ≤ 1 500) — the length of the garland.
The second line contains n lowercase English letters s1s2... sn as a string — the initial colours of paper pieces on the garland.
The third line contains a positive integer q (1 ≤ q ≤ 200 000) — the number of plans Nadeko has.
The next q lines describe one plan each: the i-th among them contains an integer mi (1 ≤ mi ≤ n) — the maximum amount of pieces to repaint, followed by a space, then by a lowercase English letter ci — Koyomi's possible favourite colour.
Output
Output q lines: for each work plan, output one line containing an integer — the largest Koyomity achievable after repainting the garland according to it.
Examples
Input
6
koyomi
3
1 o
4 o
4 m
Output
3
6
5
Input
15
yamatonadeshiko
10
1 a
2 a
3 a
4 a
5 a
1 b
2 b
3 b
4 b
5 b
Output
3
4
5
7
8
1
2
3
4
5
Input
10
aaaaaaaaaa
2
10 b
10 z
Output
10
10
Note
In the first sample, there are three plans:
* In the first plan, at most 1 piece can be repainted. Repainting the "y" piece to become "o" results in "kooomi", whose Koyomity of 3 is the best achievable;
* In the second plan, at most 4 pieces can be repainted, and "oooooo" results in a Koyomity of 6;
* In the third plan, at most 4 pieces can be repainted, and "mmmmmi" and "kmmmmm" both result in a Koyomity of 5.
Submitted Solution:
```
n=int(input())
s=input()
c=[[0 for j in range(n+1)]for i in range(26)]
for k in range(26):
for i in range(n):
rep=0
for j in range(i,n):
if s[j]!=chr(97+k):
rep+=1
c[k][rep]=max(c[k][rep],j-i+1)
for i in range(26):
for j in range(1,n):
c[i][j]=max(c[i][j],c[i][j-1])
t= int(input())
for i in range(t):
r,d=map(str,input().split())
print(c[ord(d)-97][int(r)])
``` | instruction | 0 | 77,941 | 7 | 155,882 |
No | output | 1 | 77,941 | 7 | 155,883 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it!
Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from left to right, and the i-th piece has a colour si, denoted by a lowercase English letter. Nadeko will repaint at most m of the pieces to give each of them an arbitrary new colour (still denoted by a lowercase English letter). After this work, she finds out all subsegments of the garland containing pieces of only colour c — Brother Koyomi's favourite one, and takes the length of the longest among them to be the Koyomity of the garland.
For instance, let's say the garland is represented by "kooomo", and Brother Koyomi's favourite colour is "o". Among all subsegments containing pieces of "o" only, "ooo" is the longest, with a length of 3. Thus the Koyomity of this garland equals 3.
But problem arises as Nadeko is unsure about Brother Koyomi's favourite colour, and has swaying ideas on the amount of work to do. She has q plans on this, each of which can be expressed as a pair of an integer mi and a lowercase letter ci, meanings of which are explained above. You are to find out the maximum Koyomity achievable after repainting the garland according to each plan.
Input
The first line of input contains a positive integer n (1 ≤ n ≤ 1 500) — the length of the garland.
The second line contains n lowercase English letters s1s2... sn as a string — the initial colours of paper pieces on the garland.
The third line contains a positive integer q (1 ≤ q ≤ 200 000) — the number of plans Nadeko has.
The next q lines describe one plan each: the i-th among them contains an integer mi (1 ≤ mi ≤ n) — the maximum amount of pieces to repaint, followed by a space, then by a lowercase English letter ci — Koyomi's possible favourite colour.
Output
Output q lines: for each work plan, output one line containing an integer — the largest Koyomity achievable after repainting the garland according to it.
Examples
Input
6
koyomi
3
1 o
4 o
4 m
Output
3
6
5
Input
15
yamatonadeshiko
10
1 a
2 a
3 a
4 a
5 a
1 b
2 b
3 b
4 b
5 b
Output
3
4
5
7
8
1
2
3
4
5
Input
10
aaaaaaaaaa
2
10 b
10 z
Output
10
10
Note
In the first sample, there are three plans:
* In the first plan, at most 1 piece can be repainted. Repainting the "y" piece to become "o" results in "kooomi", whose Koyomity of 3 is the best achievable;
* In the second plan, at most 4 pieces can be repainted, and "oooooo" results in a Koyomity of 6;
* In the third plan, at most 4 pieces can be repainted, and "mmmmmi" and "kmmmmm" both result in a Koyomity of 5.
Submitted Solution:
```
#coding=utf-8
if __name__ == "__main__":
n = int(input())
s = input()
q = int(input())
ans = {}
sl = list(s)
#全部算出来
for char in range(ord("a"),ord("z") + 1):
char = chr(char)
x = [0] * (n + 1)
for i in range(n):
ct = 0
for j in range(i,n):
if sl[j] != char:
ct += 1
x[ct] = x[ct] if x[ct] > (j - i + 1) else (j - i + 1)
ans[char] = x
for i in range(q):
l = input()
m = int(l.split()[0])
c = l.split()[1]
print(ans[c][m])
``` | instruction | 0 | 77,942 | 7 | 155,884 |
No | output | 1 | 77,942 | 7 | 155,885 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it!
Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from left to right, and the i-th piece has a colour si, denoted by a lowercase English letter. Nadeko will repaint at most m of the pieces to give each of them an arbitrary new colour (still denoted by a lowercase English letter). After this work, she finds out all subsegments of the garland containing pieces of only colour c — Brother Koyomi's favourite one, and takes the length of the longest among them to be the Koyomity of the garland.
For instance, let's say the garland is represented by "kooomo", and Brother Koyomi's favourite colour is "o". Among all subsegments containing pieces of "o" only, "ooo" is the longest, with a length of 3. Thus the Koyomity of this garland equals 3.
But problem arises as Nadeko is unsure about Brother Koyomi's favourite colour, and has swaying ideas on the amount of work to do. She has q plans on this, each of which can be expressed as a pair of an integer mi and a lowercase letter ci, meanings of which are explained above. You are to find out the maximum Koyomity achievable after repainting the garland according to each plan.
Input
The first line of input contains a positive integer n (1 ≤ n ≤ 1 500) — the length of the garland.
The second line contains n lowercase English letters s1s2... sn as a string — the initial colours of paper pieces on the garland.
The third line contains a positive integer q (1 ≤ q ≤ 200 000) — the number of plans Nadeko has.
The next q lines describe one plan each: the i-th among them contains an integer mi (1 ≤ mi ≤ n) — the maximum amount of pieces to repaint, followed by a space, then by a lowercase English letter ci — Koyomi's possible favourite colour.
Output
Output q lines: for each work plan, output one line containing an integer — the largest Koyomity achievable after repainting the garland according to it.
Examples
Input
6
koyomi
3
1 o
4 o
4 m
Output
3
6
5
Input
15
yamatonadeshiko
10
1 a
2 a
3 a
4 a
5 a
1 b
2 b
3 b
4 b
5 b
Output
3
4
5
7
8
1
2
3
4
5
Input
10
aaaaaaaaaa
2
10 b
10 z
Output
10
10
Note
In the first sample, there are three plans:
* In the first plan, at most 1 piece can be repainted. Repainting the "y" piece to become "o" results in "kooomi", whose Koyomity of 3 is the best achievable;
* In the second plan, at most 4 pieces can be repainted, and "oooooo" results in a Koyomity of 6;
* In the third plan, at most 4 pieces can be repainted, and "mmmmmi" and "kmmmmm" both result in a Koyomity of 5.
Submitted Solution:
```
# https://codeforces.com/problemset/problem/814/C
n = int(input())
s = input()
dp = [[0] * 26 for _ in range(n)]
dp[0][ord(s[0]) - ord('a')] = 1
for i in range(1, n):
for j in range(26):
dp[i][j] = (s[i] == chr(j + ord('a'))) + dp[i - 1][j]
q = int(input())
ans = []
for _ in range(q):
m, c = input().split()
m = int(m)
prefix = [dp[i][ord(c) - ord('a')] for i in range(n)]
left, right = 0, len(prefix) - 1
while right - left + 1 > m:
gained = prefix[right] - (0 if left == 0 else prefix[left - 1])
distance = right - left + 1
if gained + m >= distance:
ans.append(distance)
break
elif prefix[left + 1] > prefix[left]:
left += 1
else:
right -= 1
if right - left + 1 <= m:
ans.append(m)
#print('dp for {} = {}'.format(c, prefix))
for a in ans:
print(a)
``` | instruction | 0 | 77,943 | 7 | 155,886 |
No | output | 1 | 77,943 | 7 | 155,887 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it!
Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from left to right, and the i-th piece has a colour si, denoted by a lowercase English letter. Nadeko will repaint at most m of the pieces to give each of them an arbitrary new colour (still denoted by a lowercase English letter). After this work, she finds out all subsegments of the garland containing pieces of only colour c — Brother Koyomi's favourite one, and takes the length of the longest among them to be the Koyomity of the garland.
For instance, let's say the garland is represented by "kooomo", and Brother Koyomi's favourite colour is "o". Among all subsegments containing pieces of "o" only, "ooo" is the longest, with a length of 3. Thus the Koyomity of this garland equals 3.
But problem arises as Nadeko is unsure about Brother Koyomi's favourite colour, and has swaying ideas on the amount of work to do. She has q plans on this, each of which can be expressed as a pair of an integer mi and a lowercase letter ci, meanings of which are explained above. You are to find out the maximum Koyomity achievable after repainting the garland according to each plan.
Input
The first line of input contains a positive integer n (1 ≤ n ≤ 1 500) — the length of the garland.
The second line contains n lowercase English letters s1s2... sn as a string — the initial colours of paper pieces on the garland.
The third line contains a positive integer q (1 ≤ q ≤ 200 000) — the number of plans Nadeko has.
The next q lines describe one plan each: the i-th among them contains an integer mi (1 ≤ mi ≤ n) — the maximum amount of pieces to repaint, followed by a space, then by a lowercase English letter ci — Koyomi's possible favourite colour.
Output
Output q lines: for each work plan, output one line containing an integer — the largest Koyomity achievable after repainting the garland according to it.
Examples
Input
6
koyomi
3
1 o
4 o
4 m
Output
3
6
5
Input
15
yamatonadeshiko
10
1 a
2 a
3 a
4 a
5 a
1 b
2 b
3 b
4 b
5 b
Output
3
4
5
7
8
1
2
3
4
5
Input
10
aaaaaaaaaa
2
10 b
10 z
Output
10
10
Note
In the first sample, there are three plans:
* In the first plan, at most 1 piece can be repainted. Repainting the "y" piece to become "o" results in "kooomi", whose Koyomity of 3 is the best achievable;
* In the second plan, at most 4 pieces can be repainted, and "oooooo" results in a Koyomity of 6;
* In the third plan, at most 4 pieces can be repainted, and "mmmmmi" and "kmmmmm" both result in a Koyomity of 5.
Submitted Solution:
```
# O(n^2)
import sys
input = sys.stdin.readline
n = int(input())
s = input().strip()
ans = [[0]*(n+1) for i in range(26)]
segs = [[[0,-1]] for i in range(26)]
for i in range(n):
c = ord(s[i]) - ord('a')
if i > 0 and s[i] != s[i-1]:
segs[c].append([i,i])
else:
segs[c][-1][1] = i
for c in range(26):
for start in range(len(segs[c])):
lst_seg = start
tot = segs[c][start][1] - segs[c][start][0] + 1
left = 0
for m in range(1,n+1):
if segs[c][lst_seg][1] + left + 1 < n:
left += 1
tot += 1
if lst_seg != len(segs[c])-1 and \
segs[c][lst_seg][1] + left == segs[c][lst_seg+1][0]-1:
lst_seg += 1
tot += segs[c][lst_seg][1] - segs[c][lst_seg][0] + 1
left = 0
ans[c][m] = max(ans[c][m], tot)
q = int(input())
for i in range(q):
m,c = input().split()
m = int(m)
c = ord(c) - ord('a')
print(ans[c][m])
``` | instruction | 0 | 77,944 | 7 | 155,888 |
No | output | 1 | 77,944 | 7 | 155,889 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a set of points on a straight line. Each point has a color assigned to it. For point a, its neighbors are the points which don't have any other points between them and a. Each point has at most two neighbors - one from the left and one from the right.
You perform a sequence of operations on this set of points. In one operation, you delete all points which have a neighbor point of a different color than the point itself. Points are deleted simultaneously, i.e. first you decide which points have to be deleted and then delete them. After that you can perform the next operation etc. If an operation would not delete any points, you can't perform it.
How many operations will you need to perform until the next operation does not have any points to delete?
Input
Input contains a single string of lowercase English letters 'a'-'z'. The letters give the points' colors in the order in which they are arranged on the line: the first letter gives the color of the leftmost point, the second gives the color of the second point from the left etc.
The number of the points is between 1 and 106.
Output
Output one line containing an integer - the number of operations which can be performed on the given set of points until there are no more points to delete.
Examples
Input
aabb
Output
2
Input
aabcaa
Output
1
Note
In the first test case, the first operation will delete two middle points and leave points "ab", which will be deleted with the second operation. There will be no points left to apply the third operation to.
In the second test case, the first operation will delete the four points in the middle, leaving points "aa". None of them have neighbors of other colors, so the second operation can't be applied. | instruction | 0 | 77,956 | 7 | 155,912 |
Tags: data structures, greedy, implementation
Correct Solution:
```
import sys
from collections import defaultdict as di
color = input()
n = len(color)
lnei = [-1]*n
rnei = [-1]*n
to_be_deleted = []
deleted = [False]*n
iters = 0
for i in range(n):
if i-1>=0:
lnei[i]=i-1
if color[i]!=color[i-1]:
to_be_deleted.append(i)
if i+1<n:
rnei[i]=i+1
if color[i]!=color[i+1]:
to_be_deleted.append(i)
if len(to_be_deleted)==0:
print(0)
sys.exit()
while True:
was_deleted = False
pot_sui = []
for node in to_be_deleted:
if deleted[node]:
continue
was_deleted=True
deleted[node]=True
if rnei[node]!=-1:
lnei[rnei[node]]=lnei[node]
pot_sui.append(rnei[node])
if lnei[node]!=-1:
rnei[lnei[node]]=rnei[node]
pot_sui.append(lnei[node])
to_be_deleted=[]
for node in pot_sui:
if deleted[node]:
continue
if lnei[node]!=-1 and color[node]!=color[lnei[node]]:
to_be_deleted.append(node)
elif rnei[node]!=-1 and color[node]!=color[rnei[node]]:
to_be_deleted.append(node)
if not was_deleted:
break
iters += 1
print(iters)
``` | output | 1 | 77,956 | 7 | 155,913 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a set of points on a straight line. Each point has a color assigned to it. For point a, its neighbors are the points which don't have any other points between them and a. Each point has at most two neighbors - one from the left and one from the right.
You perform a sequence of operations on this set of points. In one operation, you delete all points which have a neighbor point of a different color than the point itself. Points are deleted simultaneously, i.e. first you decide which points have to be deleted and then delete them. After that you can perform the next operation etc. If an operation would not delete any points, you can't perform it.
How many operations will you need to perform until the next operation does not have any points to delete?
Input
Input contains a single string of lowercase English letters 'a'-'z'. The letters give the points' colors in the order in which they are arranged on the line: the first letter gives the color of the leftmost point, the second gives the color of the second point from the left etc.
The number of the points is between 1 and 106.
Output
Output one line containing an integer - the number of operations which can be performed on the given set of points until there are no more points to delete.
Examples
Input
aabb
Output
2
Input
aabcaa
Output
1
Note
In the first test case, the first operation will delete two middle points and leave points "ab", which will be deleted with the second operation. There will be no points left to apply the third operation to.
In the second test case, the first operation will delete the four points in the middle, leaving points "aa". None of them have neighbors of other colors, so the second operation can't be applied. | instruction | 0 | 77,957 | 7 | 155,914 |
Tags: data structures, greedy, implementation
Correct Solution:
```
s=input()
a=[[s[0],1]]
for i in s[1:]:
if(a[-1][0]==i):
a[-1][1]+=1
else:
a.append([i,1])
turns=0
while((len(a)>1)):
turns+=1
temp=[]
if(a[0][1]>1):
temp.append([a[0][0],a[0][1]-1])
for i in a[1:-1]:
if(i[1]>2):
temp.append([i[0],i[1]-2])
if(a[-1][1]>1):
temp.append([a[-1][0],a[-1][1]-1])
if(len(temp)<2):
break
a=[temp[0],]
for i in temp[1:]:
if(i[0]!=a[-1][0]):
a.append(i)
else:
a[-1][1]+=i[1]
print(turns)
``` | output | 1 | 77,957 | 7 | 155,915 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a set of points on a straight line. Each point has a color assigned to it. For point a, its neighbors are the points which don't have any other points between them and a. Each point has at most two neighbors - one from the left and one from the right.
You perform a sequence of operations on this set of points. In one operation, you delete all points which have a neighbor point of a different color than the point itself. Points are deleted simultaneously, i.e. first you decide which points have to be deleted and then delete them. After that you can perform the next operation etc. If an operation would not delete any points, you can't perform it.
How many operations will you need to perform until the next operation does not have any points to delete?
Input
Input contains a single string of lowercase English letters 'a'-'z'. The letters give the points' colors in the order in which they are arranged on the line: the first letter gives the color of the leftmost point, the second gives the color of the second point from the left etc.
The number of the points is between 1 and 106.
Output
Output one line containing an integer - the number of operations which can be performed on the given set of points until there are no more points to delete.
Examples
Input
aabb
Output
2
Input
aabcaa
Output
1
Note
In the first test case, the first operation will delete two middle points and leave points "ab", which will be deleted with the second operation. There will be no points left to apply the third operation to.
In the second test case, the first operation will delete the four points in the middle, leaving points "aa". None of them have neighbors of other colors, so the second operation can't be applied. | instruction | 0 | 77,958 | 7 | 155,916 |
Tags: data structures, greedy, implementation
Correct Solution:
```
s = input()
n = 1
for i in range(1, len(s)):
if s[i] != s[i-1]:
n += 1
mas = [0] * n
col = [0] * n
count = 1
idx = 0
c = s[0]
for i in range(1, len(s)):
if s[i] == s[i-1]:
count += 1
else:
mas[idx] = count
col[idx] = c
idx += 1
count = 1
c = s[i]
mas[idx] = count
col[idx] = c
res = 0
while n > 1:
newlen = n
idx = -1
for i in range(0, n):
if (i == 0) or (i == n - 1):
mas[i] -= 1
elif mas[i] >= 2:
mas[i] -= 2
else:
mas[i] = 0
if mas[i] == 0:
newlen -= 1
else:
if idx >= 0 and col[idx] == col[i]:
mas[idx] += mas[i]
newlen -= 1
else:
idx += 1
mas[idx] = mas[i]
col[idx] = col[i]
type = i % 2
n = newlen
res += 1
print(res)
``` | output | 1 | 77,958 | 7 | 155,917 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a set of points on a straight line. Each point has a color assigned to it. For point a, its neighbors are the points which don't have any other points between them and a. Each point has at most two neighbors - one from the left and one from the right.
You perform a sequence of operations on this set of points. In one operation, you delete all points which have a neighbor point of a different color than the point itself. Points are deleted simultaneously, i.e. first you decide which points have to be deleted and then delete them. After that you can perform the next operation etc. If an operation would not delete any points, you can't perform it.
How many operations will you need to perform until the next operation does not have any points to delete?
Input
Input contains a single string of lowercase English letters 'a'-'z'. The letters give the points' colors in the order in which they are arranged on the line: the first letter gives the color of the leftmost point, the second gives the color of the second point from the left etc.
The number of the points is between 1 and 106.
Output
Output one line containing an integer - the number of operations which can be performed on the given set of points until there are no more points to delete.
Examples
Input
aabb
Output
2
Input
aabcaa
Output
1
Note
In the first test case, the first operation will delete two middle points and leave points "ab", which will be deleted with the second operation. There will be no points left to apply the third operation to.
In the second test case, the first operation will delete the four points in the middle, leaving points "aa". None of them have neighbors of other colors, so the second operation can't be applied. | instruction | 0 | 77,959 | 7 | 155,918 |
Tags: data structures, greedy, implementation
Correct Solution:
```
s = input()
cur_len = 1
a = []
char = []
for i in range(1, len(s)):
if s[i] == s[i-1]: cur_len += 1
else:
a.append(cur_len)
char.append(s[i-1])
cur_len = 1
a.append(cur_len)
char.append(s[len(s)-1])
ans = 0
while len(a) > 1:
n = len(a)
inner_min = 100000000
for i in range(1,n-1):
if a[i] < inner_min: inner_min = a[i]
k = min(a[0], a[n-1],(inner_min + 1)//2)
#print("a: ", a, "; k = ", k)
b = []
new_char = []
for i in range(n):
if i == 0 or i == n-1:
if a[i] > k:
b.append(a[i]-k)
new_char.append(char[i])
else:
if a[i] > 2*k:
b.append(a[i] - 2*k)
new_char.append(char[i])
## print(b)
ans += k
if len(b) > 1:
c = [0]*n
newnew_char = [new_char[0]]
count = 0
for i in range(0,len(b)-1):
c[count] += b[i]
if new_char[i] == new_char[i+1]: continue
else:
count += 1
newnew_char.append(new_char[i+1])
if new_char[len(b)-2] == new_char[len(b) - 1]: c[count] += b[len(b)-1]
else:
#count += 1
newnew_char.append(new_char[i+1])
c[count] = b[len(b)-1]
a = c[:count+1]
char = newnew_char[:]
else:
a = b[:]
print(ans)
``` | output | 1 | 77,959 | 7 | 155,919 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a set of points on a straight line. Each point has a color assigned to it. For point a, its neighbors are the points which don't have any other points between them and a. Each point has at most two neighbors - one from the left and one from the right.
You perform a sequence of operations on this set of points. In one operation, you delete all points which have a neighbor point of a different color than the point itself. Points are deleted simultaneously, i.e. first you decide which points have to be deleted and then delete them. After that you can perform the next operation etc. If an operation would not delete any points, you can't perform it.
How many operations will you need to perform until the next operation does not have any points to delete?
Input
Input contains a single string of lowercase English letters 'a'-'z'. The letters give the points' colors in the order in which they are arranged on the line: the first letter gives the color of the leftmost point, the second gives the color of the second point from the left etc.
The number of the points is between 1 and 106.
Output
Output one line containing an integer - the number of operations which can be performed on the given set of points until there are no more points to delete.
Examples
Input
aabb
Output
2
Input
aabcaa
Output
1
Note
In the first test case, the first operation will delete two middle points and leave points "ab", which will be deleted with the second operation. There will be no points left to apply the third operation to.
In the second test case, the first operation will delete the four points in the middle, leaving points "aa". None of them have neighbors of other colors, so the second operation can't be applied. | instruction | 0 | 77,960 | 7 | 155,920 |
Tags: data structures, greedy, implementation
Correct Solution:
```
# https://codeforces.com/problemset/problem/909/D
def process(a):
assert len(a) >= 2
n = len(a)
min_ = float('inf')
for i, [cnt, c] in enumerate(a):
if i == 0 or i == n-1:
min_ = min(min_, cnt)
else:
min_ = min(min_, (cnt+1) //2)
b = []
for i, [cnt, c] in enumerate(a):
if i == 0 or i == n-1:
remain = cnt - min_
else:
remain = cnt - min_ * 2
if remain <= 0:
continue
if len(b) == 0 or c != b[-1][1]:
b.append([remain, c])
else:
pre_cnt, pre_c = b.pop()
b.append([pre_cnt+remain, c])
return b, min_
S = input() + ' '
cur = []
cnt = 0
pre = ''
for x in S:
if cnt == 0:
cnt+= 1
pre = x
elif x!=pre:
cur.append([cnt, pre])
cnt = 1
pre = x
else:
cnt+=1
cnt = 0
while len(cur) not in [0, 1]:
cur, min_ = process(cur)
cnt+=min_
print(cnt)
``` | output | 1 | 77,960 | 7 | 155,921 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a set of points on a straight line. Each point has a color assigned to it. For point a, its neighbors are the points which don't have any other points between them and a. Each point has at most two neighbors - one from the left and one from the right.
You perform a sequence of operations on this set of points. In one operation, you delete all points which have a neighbor point of a different color than the point itself. Points are deleted simultaneously, i.e. first you decide which points have to be deleted and then delete them. After that you can perform the next operation etc. If an operation would not delete any points, you can't perform it.
How many operations will you need to perform until the next operation does not have any points to delete?
Input
Input contains a single string of lowercase English letters 'a'-'z'. The letters give the points' colors in the order in which they are arranged on the line: the first letter gives the color of the leftmost point, the second gives the color of the second point from the left etc.
The number of the points is between 1 and 106.
Output
Output one line containing an integer - the number of operations which can be performed on the given set of points until there are no more points to delete.
Examples
Input
aabb
Output
2
Input
aabcaa
Output
1
Note
In the first test case, the first operation will delete two middle points and leave points "ab", which will be deleted with the second operation. There will be no points left to apply the third operation to.
In the second test case, the first operation will delete the four points in the middle, leaving points "aa". None of them have neighbors of other colors, so the second operation can't be applied. | instruction | 0 | 77,961 | 7 | 155,922 |
Tags: data structures, greedy, implementation
Correct Solution:
```
name = input()
blocks = []
now = name[0]
counter = 1
for x in range(1, len(name)):
if name[x] != now:
blocks.append((now, counter))
now = name[x]
counter = 1
else:
counter += 1
blocks.append((now, counter))
counter = 0
temp = []
while len(blocks) > 1:
counter += 1
temp = []
(x, y) = blocks[0]
if y > 1:
temp.append((x, y - 1))
for s in range(1, len(blocks) - 1):
(x, y) = blocks[s]
if len(temp) > 0:
(tempx, tempy) = temp[-1]
if y > 2:
if x != tempx:
temp.append((x, y - 2))
else:
temp[-1] = (x, tempy + y - 2)
else:
if y > 2:
temp.append((x, y - 2))
(x, y) = blocks[-1]
if len(temp) > 0:
(tempx, tempy) = temp[-1]
if y > 1:
if x != tempx:
temp.append((x, y - 1))
else:
temp[-1] = (x, tempy + y - 1)
else:
if y > 1:
temp.append((x, y - 1))
blocks = temp
print(counter)
``` | output | 1 | 77,961 | 7 | 155,923 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a set of points on a straight line. Each point has a color assigned to it. For point a, its neighbors are the points which don't have any other points between them and a. Each point has at most two neighbors - one from the left and one from the right.
You perform a sequence of operations on this set of points. In one operation, you delete all points which have a neighbor point of a different color than the point itself. Points are deleted simultaneously, i.e. first you decide which points have to be deleted and then delete them. After that you can perform the next operation etc. If an operation would not delete any points, you can't perform it.
How many operations will you need to perform until the next operation does not have any points to delete?
Input
Input contains a single string of lowercase English letters 'a'-'z'. The letters give the points' colors in the order in which they are arranged on the line: the first letter gives the color of the leftmost point, the second gives the color of the second point from the left etc.
The number of the points is between 1 and 106.
Output
Output one line containing an integer - the number of operations which can be performed on the given set of points until there are no more points to delete.
Examples
Input
aabb
Output
2
Input
aabcaa
Output
1
Note
In the first test case, the first operation will delete two middle points and leave points "ab", which will be deleted with the second operation. There will be no points left to apply the third operation to.
In the second test case, the first operation will delete the four points in the middle, leaving points "aa". None of them have neighbors of other colors, so the second operation can't be applied. | instruction | 0 | 77,962 | 7 | 155,924 |
Tags: data structures, greedy, implementation
Correct Solution:
```
import sys
sys.setrecursionlimit(1000000)
read = sys.stdin.readline
points = read().strip()
lst = [[points[0], 1]]
for p in points[1:]:
if p == lst[-1][0]:
lst[-1][1] += 1
else:
lst += [[p, 1]]
ans = 0
while len(lst) > 1:
ans += 1
tmp = []
if lst[0][1] > 1:
tmp.append([lst[0][0], lst[0][1]-1])
for i in lst[1:-1]:
if i[1] > 2:
if len(tmp) == 0 or tmp[-1][0] != i[0]:
tmp.append([i[0], i[1]-2])
else:
tmp[-1][1] += i[1] - 2
if lst[-1][1] > 1:
if len(tmp) == 0 or lst[-1][0] != tmp[-1][0]:
tmp.append([lst[-1][0], lst[-1][1]-1])
else:
tmp[-1][1] += lst[-1][1]-1
lst = tmp
print(ans)
``` | output | 1 | 77,962 | 7 | 155,925 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a set of points on a straight line. Each point has a color assigned to it. For point a, its neighbors are the points which don't have any other points between them and a. Each point has at most two neighbors - one from the left and one from the right.
You perform a sequence of operations on this set of points. In one operation, you delete all points which have a neighbor point of a different color than the point itself. Points are deleted simultaneously, i.e. first you decide which points have to be deleted and then delete them. After that you can perform the next operation etc. If an operation would not delete any points, you can't perform it.
How many operations will you need to perform until the next operation does not have any points to delete?
Input
Input contains a single string of lowercase English letters 'a'-'z'. The letters give the points' colors in the order in which they are arranged on the line: the first letter gives the color of the leftmost point, the second gives the color of the second point from the left etc.
The number of the points is between 1 and 106.
Output
Output one line containing an integer - the number of operations which can be performed on the given set of points until there are no more points to delete.
Examples
Input
aabb
Output
2
Input
aabcaa
Output
1
Note
In the first test case, the first operation will delete two middle points and leave points "ab", which will be deleted with the second operation. There will be no points left to apply the third operation to.
In the second test case, the first operation will delete the four points in the middle, leaving points "aa". None of them have neighbors of other colors, so the second operation can't be applied.
Submitted Solution:
```
def delete():
toDel = set()
for b in range(len(string)):
if b != 0:
if string[b] != string[b-1]:
toDel.add(b-1)
elif b != len(string)-1:
if string[b] != string[b+1]:
toDel.add(b+1)
for c in sorted(toDel,reverse=True):
string.pop(c)
string = list(input())
length = 0
count = 0
while length-len(string):
length = len(string)
delete()
count+= 1
print(count-1)
``` | instruction | 0 | 77,963 | 7 | 155,926 |
No | output | 1 | 77,963 | 7 | 155,927 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a set of points on a straight line. Each point has a color assigned to it. For point a, its neighbors are the points which don't have any other points between them and a. Each point has at most two neighbors - one from the left and one from the right.
You perform a sequence of operations on this set of points. In one operation, you delete all points which have a neighbor point of a different color than the point itself. Points are deleted simultaneously, i.e. first you decide which points have to be deleted and then delete them. After that you can perform the next operation etc. If an operation would not delete any points, you can't perform it.
How many operations will you need to perform until the next operation does not have any points to delete?
Input
Input contains a single string of lowercase English letters 'a'-'z'. The letters give the points' colors in the order in which they are arranged on the line: the first letter gives the color of the leftmost point, the second gives the color of the second point from the left etc.
The number of the points is between 1 and 106.
Output
Output one line containing an integer - the number of operations which can be performed on the given set of points until there are no more points to delete.
Examples
Input
aabb
Output
2
Input
aabcaa
Output
1
Note
In the first test case, the first operation will delete two middle points and leave points "ab", which will be deleted with the second operation. There will be no points left to apply the third operation to.
In the second test case, the first operation will delete the four points in the middle, leaving points "aa". None of them have neighbors of other colors, so the second operation can't be applied.
Submitted Solution:
```
a=list(input())
K=0
while 1:
if len(a)==0 :
break
elif len(a)==1:
K+=1
break
b=[]
if a[0] != a[1]:
b.append(0)
for i in range(len(a)-1):
if a[i] != a[i+1]:
b.append(i+1)
if len(b)==0:
break
for j in b:
a[j]='A'
i1=0
while i1<len(a):
if a[i1]=='A':
del(a[i1])
else:
i1+=1
K+=1
print(K)
``` | instruction | 0 | 77,966 | 7 | 155,932 |
No | output | 1 | 77,966 | 7 | 155,933 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n left boots and n right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings l and r, both of length n. The character l_i stands for the color of the i-th left boot and the character r_i stands for the color of the i-th right boot.
A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.
For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').
Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.
Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.
Input
The first line contains n (1 ≤ n ≤ 150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).
The second line contains the string l of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th left boot.
The third line contains the string r of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th right boot.
Output
Print k — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.
The following k lines should contain pairs a_j, b_j (1 ≤ a_j, b_j ≤ n). The j-th of these lines should contain the index a_j of the left boot in the j-th pair and index b_j of the right boot in the j-th pair. All the numbers a_j should be distinct (unique), all the numbers b_j should be distinct (unique).
If there are many optimal answers, print any of them.
Examples
Input
10
codeforces
dodivthree
Output
5
7 8
4 9
2 2
9 10
3 1
Input
7
abaca?b
zabbbcc
Output
5
6 5
2 3
4 6
7 4
1 2
Input
9
bambarbia
hellocode
Output
0
Input
10
code??????
??????test
Output
10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10
Submitted Solution:
```
#import sys
#sys.stdin = open('input.txt')
from collections import Counter as cou
n = int(input())
ans = []
dl = {}; dl['?'] = set()
dr = {}; dr['?'] = set()
for i in range(ord('a'), ord('z') + 1):
dl[chr(i)] = set()
dr[chr(i)] = set()
for i in range(2):
x = input()
if not i:
l = dict(cou(x))
for ind, j in enumerate(x):
dl[j].add(ind + 1)
else:
r = dict(cou(x))
for ind, j in enumerate(x):
dr[j].add(ind + 1)
del x, ind, j, i
op = 0
for i in l.keys():
if '?' == i:
op = 1
continue
lc = l.get(i, 0)
rc = r.get(i, 0)
vc = r.get('?', 0)
diff = min(lc, rc)
lc -= diff; l[i] = max(0, l.get(i, 0) - diff)
rc -= diff; r[i] = max(0, r.get(i, 0) - diff)
for j in range(diff):
ans.append([dl[i].pop(), dr[i].pop()])
if lc:
diff = min(lc, vc)
lc -= diff; l[i] = max(0, l.get(i, 0) - diff)
vc -= diff; r['?'] = max(0, r.get('?', 0) - diff)
for j in range(diff):
ans.append([dl[i].pop(), dr['?'].pop()])
if op:
x = l['?']
for i in dr.keys():
if len(dr[i]):
for j in dr[i]:
if not x:
break
x -= 1
ans.append([dl['?'].pop(), j])
print(len(ans))
for i in ans:
print(' '.join(map(str, i)))
``` | instruction | 0 | 78,347 | 7 | 156,694 |
Yes | output | 1 | 78,347 | 7 | 156,695 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n left boots and n right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings l and r, both of length n. The character l_i stands for the color of the i-th left boot and the character r_i stands for the color of the i-th right boot.
A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.
For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').
Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.
Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.
Input
The first line contains n (1 ≤ n ≤ 150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).
The second line contains the string l of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th left boot.
The third line contains the string r of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th right boot.
Output
Print k — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.
The following k lines should contain pairs a_j, b_j (1 ≤ a_j, b_j ≤ n). The j-th of these lines should contain the index a_j of the left boot in the j-th pair and index b_j of the right boot in the j-th pair. All the numbers a_j should be distinct (unique), all the numbers b_j should be distinct (unique).
If there are many optimal answers, print any of them.
Examples
Input
10
codeforces
dodivthree
Output
5
7 8
4 9
2 2
9 10
3 1
Input
7
abaca?b
zabbbcc
Output
5
6 5
2 3
4 6
7 4
1 2
Input
9
bambarbia
hellocode
Output
0
Input
10
code??????
??????test
Output
10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10
Submitted Solution:
```
num_boots = int(input())
left_boots = [[x] for x in list(input())]
right_boots = [[x] for x in list(input())]
# print(left_boots)
# print(right_boots)
for x in range(1, num_boots + 1):
left_boots[x-1].append(x)
right_boots[x-1].append(x)
# [z,y,b,a,?]
left_boots.sort(reverse=True)
right_boots.sort(reverse=True)
# print(left_boots)
# print(right_boots)
num_matches = 0
# match list = [[pair],[pair],[]....]
match_list = []
# unmatched list = [left, right]
unmatched_list = [[], []]
# question mark list = [left, right]
question_mark_list = [[], []]
i = 0
j = 0
left_had_hit_question_mark = False
right_had_hit_question_mark = False
while i < num_boots and j < num_boots:
left_present_chr = left_boots[i][0]
right_present_chr = right_boots[j][0]
if left_present_chr == '?':
left_had_hit_question_mark = True
for x in range(i, num_boots):
question_mark_list[0].append(left_boots[x][1])
i = num_boots
if right_present_chr == '?':
right_had_hit_question_mark = True
for x in range(j, num_boots):
question_mark_list[1].append(right_boots[x][1])
j = num_boots
question_mark_reached = left_had_hit_question_mark or right_had_hit_question_mark
if not (left_had_hit_question_mark and right_had_hit_question_mark) and (question_mark_reached):
left_or_right = 0
start = i
which_boots = left_boots
if right_had_hit_question_mark:
left_or_right = 1
start = j
which_boots = right_boots
for x in range(start, num_boots):
unmatched_list[left_or_right].append(which_boots[x][1])
if question_mark_reached:
break
if left_present_chr == right_present_chr:
num_matches += 1
match_list.append([left_boots[i][1], right_boots[j][1]])
i += 1
j += 1
else:
present_chr = min(left_present_chr, right_present_chr)
if left_present_chr > present_chr:
# b > a means a further in list [c, b, a]
unmatched_list[0].append(left_boots[i][1])
i += 1
else:
unmatched_list[1].append(right_boots[j][1])
j += 1
# print('i: {}, j: {}'.format(i, j))
# print('Number of pure matched (aa): ' + str(num_matches))
if i != j:
if i > j:
affected_counter = j
affected_boots = right_boots
j = num_boots
left_or_right = 1
else:
affected_counter = i
affected_boots = left_boots
i = num_boots
left_or_right = 0
# print('Finishing it up: left_or_right: ' + str(left_or_right))
# print(affected_boots)
for x in range(affected_counter, num_boots):
# print('Present character: ' + str(affected_boots[x][0]))
if affected_boots[x][0] == '?':
# snippet from above
for h in range(x, num_boots):
question_mark_list[left_or_right].append(affected_boots[h][1])
affected_counter = num_boots
break
else:
unmatched_list[left_or_right].append(affected_boots[x][1])
# print('Question mark list:')
# print(question_mark_list)
# print('Match list:')
# print(match_list)
left_question_counter = 0
right_question_counter = 0
if question_mark_list[1]:
# print('Using wildcards from right')
for x in range(0, len(question_mark_list[1])):
if x == len(unmatched_list[0]):
# print('No unmatched at left')
break
# print([unmatched_list[0][x], question_mark_list[1][x]])
match_list.append([unmatched_list[0][x], question_mark_list[1][x]])
num_matches += 1
right_question_counter += 1
if question_mark_list[0]:
# print('Using wildcards from left')
for x in range(0, len(question_mark_list[0])):
if x == len(unmatched_list[1]):
# print('No unmatched at right')
break
# print('Adding new match')
# print([question_mark_list[0][x], unmatched_list[1][x]])
match_list.append([question_mark_list[0][x], unmatched_list[1][x]])
num_matches += 1
left_question_counter += 1
num_left_extra_question = len(question_mark_list[0]) - left_question_counter
num_right_extra_question = len(question_mark_list[1]) - right_question_counter
extra_question_num = min(num_left_extra_question, num_right_extra_question)
# print('extra_question_number: ' + str(extra_question_num))
num_matches += extra_question_num
print(num_matches)
for x in range(0, extra_question_num):
# print('Using wildcard to wildcard')
match_list.append([question_mark_list[0][left_question_counter], question_mark_list[1][right_question_counter]])
left_question_counter += 1
right_question_counter += 1
for x in match_list:
print('{} {}'.format(x[0], x[1]))
``` | instruction | 0 | 78,348 | 7 | 156,696 |
Yes | output | 1 | 78,348 | 7 | 156,697 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n left boots and n right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings l and r, both of length n. The character l_i stands for the color of the i-th left boot and the character r_i stands for the color of the i-th right boot.
A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.
For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').
Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.
Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.
Input
The first line contains n (1 ≤ n ≤ 150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).
The second line contains the string l of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th left boot.
The third line contains the string r of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th right boot.
Output
Print k — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.
The following k lines should contain pairs a_j, b_j (1 ≤ a_j, b_j ≤ n). The j-th of these lines should contain the index a_j of the left boot in the j-th pair and index b_j of the right boot in the j-th pair. All the numbers a_j should be distinct (unique), all the numbers b_j should be distinct (unique).
If there are many optimal answers, print any of them.
Examples
Input
10
codeforces
dodivthree
Output
5
7 8
4 9
2 2
9 10
3 1
Input
7
abaca?b
zabbbcc
Output
5
6 5
2 3
4 6
7 4
1 2
Input
9
bambarbia
hellocode
Output
0
Input
10
code??????
??????test
Output
10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10
Submitted Solution:
```
import re, math, decimal, bisect
def read(): return input().strip()
def iread(): return int(input().strip())
def viread(): return [int(_) for _ in input().strip().split()]
def round(n): return int(n + 0.5)
# code goes here
n = iread()
l = sorted([list(z) for z in zip(read() + "~", range(n+1), [False] * (n+1))])
r = sorted([list(z) for z in zip(read() + "~", range(n+1), [False] * (n+1))])
# print(l);print(r)
i, j, lqs, rqs = 0, 0, [], []
pairs = []
while i < n or j < n:
if l[i][0] == '?':
lqs.append(l[i][1])
i += 1
continue
if r[j][0] == '?':
rqs.append(r[j][1])
j += 1
continue
if l[i][0] == r[j][0]:
l[i][2] = True
r[j][2] = True
# print("pair {} with {}".format(l[i][:2], r[j][:2]))
pairs.append((l[i][1]+1, r[j][1]+1))
i += 1
j += 1
elif l[i][0] < r[j][0]: i += 1
# elif i < n and j < n and l[i][0] > r[j][0]: j += 1
else : j += 1
# else: break
i, j = 0, 0
# for p in pairs:
# print(*p)
# print(l);print(r)
# print(lqs); print(rqs)
while (i < n or j < n) and (lqs or rqs):
if i < n and (l[i][2] or l[i][0] == '?'):
i += 1
continue
elif j < n and (r[j][2] or r[j][0] == '?'):
j += 1
continue
elif j < n and not r[j][2] and lqs:
# print("pair [?, {}] with {}".format(lqs[-1], r[j][:2]))
pairs.append((lqs.pop()+1, r[j][1]+1))
j += 1
elif i < n and not l[i][2] and rqs:
# print("pair {} with [?, {}]".format(l[i][:2], rqs[-1]))
pairs.append((l[i][1]+1, rqs.pop()+1))
i += 1
# for p in pairs:
# print(*p)
# print(l);print(r)
# print(lqs); print(rqs)
i = 0
while lqs and rqs:
pairs.append((lqs.pop()+1, rqs.pop()+1))
print(len(pairs))
for p in pairs:
print(*p)
``` | instruction | 0 | 78,349 | 7 | 156,698 |
Yes | output | 1 | 78,349 | 7 | 156,699 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n left boots and n right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings l and r, both of length n. The character l_i stands for the color of the i-th left boot and the character r_i stands for the color of the i-th right boot.
A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.
For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').
Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.
Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.
Input
The first line contains n (1 ≤ n ≤ 150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).
The second line contains the string l of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th left boot.
The third line contains the string r of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th right boot.
Output
Print k — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.
The following k lines should contain pairs a_j, b_j (1 ≤ a_j, b_j ≤ n). The j-th of these lines should contain the index a_j of the left boot in the j-th pair and index b_j of the right boot in the j-th pair. All the numbers a_j should be distinct (unique), all the numbers b_j should be distinct (unique).
If there are many optimal answers, print any of them.
Examples
Input
10
codeforces
dodivthree
Output
5
7 8
4 9
2 2
9 10
3 1
Input
7
abaca?b
zabbbcc
Output
5
6 5
2 3
4 6
7 4
1 2
Input
9
bambarbia
hellocode
Output
0
Input
10
code??????
??????test
Output
10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10
Submitted Solution:
```
n = int(input())
a = input()
b = input()
A = [[] for i in range(27)]
B = [[] for i in range(27)]
for i in range(n):
if a[i] == '?':
A[26].append(i)
else:
A[ord(a[i]) - ord('a')].append(i)
if b[i] == '?':
B[26].append(i)
else:
B[ord(b[i]) - ord('a')].append(i)
matches = []
for i in range(27):
while A[i] and B[i]:
matches.append((A[i].pop(), B[i].pop()))
while A[i] and B[26]:
matches.append((A[i].pop(), B[26].pop()))
while A[26] and B[i]:
matches.append((A[26].pop(), B[i].pop()))
print(len(matches))
for i in matches:
print(i[0]+1, i[1]+1)
``` | instruction | 0 | 78,350 | 7 | 156,700 |
Yes | output | 1 | 78,350 | 7 | 156,701 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n left boots and n right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings l and r, both of length n. The character l_i stands for the color of the i-th left boot and the character r_i stands for the color of the i-th right boot.
A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.
For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').
Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.
Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.
Input
The first line contains n (1 ≤ n ≤ 150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).
The second line contains the string l of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th left boot.
The third line contains the string r of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th right boot.
Output
Print k — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.
The following k lines should contain pairs a_j, b_j (1 ≤ a_j, b_j ≤ n). The j-th of these lines should contain the index a_j of the left boot in the j-th pair and index b_j of the right boot in the j-th pair. All the numbers a_j should be distinct (unique), all the numbers b_j should be distinct (unique).
If there are many optimal answers, print any of them.
Examples
Input
10
codeforces
dodivthree
Output
5
7 8
4 9
2 2
9 10
3 1
Input
7
abaca?b
zabbbcc
Output
5
6 5
2 3
4 6
7 4
1 2
Input
9
bambarbia
hellocode
Output
0
Input
10
code??????
??????test
Output
10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10
Submitted Solution:
```
amount = int(input())
string_1 = input()
used_1 = [0] * len(string_1)
string_2 = input()
used_2 = [0] * len(string_2)
first = {}
second = {}
for i in range(len(string_1)):
if not string_1[i] in first:
first.update({string_1[i]:[i]})
else:
first[string_1[i]].append(i)
for i in range(len(string_2)):
if not string_2[i] in second:
second.update({string_2[i]:[i]})
else:
second[string_2[i]].append(i)
counter = 0
ans = ''
for key in first:
if key != '?':
if key in second:
if len(first[key]) < len(second[key]):
counter += len(first[key])
for i in range(len(first[key])):
ans += str(first[key][i] + 1) + ' ' + str(second[key][i] + 1) + '\n'
used_1[first[key][i]] = 1
used_2[second[key][i]] = 1
else:
counter += len(second[key])
for i in range(len(second[key])):
ans += str(first[key][i] + 1) + ' ' + str(second[key][i] + 1) + '\n'
used_1[first[key][i]] = 1
used_2[second[key][i]] = 1
else:
tmp = []
for j in range(len(used_2)):
if not used_2[j]:
tmp.append(j)
counter += min(len(first[key]), len(used_2) - sum(used_2))
for i in range(min(len(first[key]), len(used_2) - sum(used_2))):
ans += str(first[key][i] + 1) + ' ' + str(tmp[i] + 1) + '\n'
used_1[first[key][i]] = 1
used_2[tmp[i]] = 1
if key in second:
tmp = []
for j in range(len(used_1)):
if not used_1[j]:
tmp.append(j)
counter += min(len(second[key]), len(used_1) - sum(used_1))
for i in range(min(len(second[key]), len(used_1) - sum(used_1))):
ans += str(second[key][i] + 1) + ' ' + str(tmp[i] + 1) + '\n'
used_2[second[key][i]] = 1
used_1[tmp[i]] = 1
print(counter)
print(ans)
``` | instruction | 0 | 78,351 | 7 | 156,702 |
No | output | 1 | 78,351 | 7 | 156,703 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n left boots and n right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings l and r, both of length n. The character l_i stands for the color of the i-th left boot and the character r_i stands for the color of the i-th right boot.
A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.
For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').
Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.
Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.
Input
The first line contains n (1 ≤ n ≤ 150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).
The second line contains the string l of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th left boot.
The third line contains the string r of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th right boot.
Output
Print k — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.
The following k lines should contain pairs a_j, b_j (1 ≤ a_j, b_j ≤ n). The j-th of these lines should contain the index a_j of the left boot in the j-th pair and index b_j of the right boot in the j-th pair. All the numbers a_j should be distinct (unique), all the numbers b_j should be distinct (unique).
If there are many optimal answers, print any of them.
Examples
Input
10
codeforces
dodivthree
Output
5
7 8
4 9
2 2
9 10
3 1
Input
7
abaca?b
zabbbcc
Output
5
6 5
2 3
4 6
7 4
1 2
Input
9
bambarbia
hellocode
Output
0
Input
10
code??????
??????test
Output
10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10
Submitted Solution:
```
# stdin=open('input.txt')
# def input():
# return stdin.readline()[:-1]
'''stdout=open('output.txt',mode='w+')
def print(x,end='\n'):
stdout.write(str(x)+end)'''
# CODE BEGINS HERE.................
n = int(input())
l = input()
r = input()
left = {'?': 0, 'a': 0, 'c': 0, 'b': 0, 'e': 0, 'd': 0, 'g': 0, 'f': 0, 'i': 0, 'h': 0, 'k': 0, 'j': 0, 'm': 0, 'l': 0, 'o': 0, 'n': 0, 'q': 0, 'p': 0, 's': 0, 'r': 0, 'u': 0, 't': 0, 'w': 0, 'v': 0, 'y': 0, 'x': 0, 'z': 0}
right = {'?': 0, 'a': 0, 'c': 0, 'b': 0, 'e': 0, 'd': 0, 'g': 0, 'f': 0, 'i': 0, 'h': 0, 'k': 0, 'j': 0, 'm': 0, 'l': 0, 'o': 0, 'n': 0, 'q': 0, 'p': 0, 's': 0, 'r': 0, 'u': 0, 't': 0, 'w': 0, 'v': 0, 'y': 0, 'x': 0, 'z': 0}
leftIndex = {i: [] for i in left.keys()}
rightIndex = {i: [] for i in right.keys()}
for i in range(n):
left[l[i]] += 1
right[r[i]] += 1
leftIndex[l[i]].append(i + 1)
rightIndex[r[i]].append(i + 1)
matchCount = 0
needBufferLeft = 0
needBufferRight = 0
strLeft = ''
strRight = ''
for i in left.keys():
if i != '?':
matchCount += min(left[i], right[i])
if left[i] < right[i]:
needBufferRight += right[i] - left[i]
strRight += i*(right[i] - left[i])
else:
needBufferLeft += left[i] - right[i]
strLeft += i*(left[i] - right[i])
leftPairs = min(needBufferLeft, right['?'])
rightPairs = min(needBufferRight, left['?'])
matchCount += leftPairs + rightPairs
matchCount += min(right['?'] - leftPairs, left['?'] - rightPairs)
print(matchCount)
for i in left.keys():
if i != '?':
for j in range(min(left[i], right[i])):
print(leftIndex[i].pop(), rightIndex[i].pop())
# print('check')
count = 0
flag = True
for i in leftIndex.keys():
if i != '?':
for j in leftIndex[i]:
if count == leftPairs:
flag = False
break
print(j, rightIndex['?'].pop())
count += 1
if not flag:
break
# print('ceck')
# print(leftIndex['?'],rightPairs)
count = 0
for i in rightIndex.keys():
# print(rightIndex[i])
if i != '?':
for j in rightIndex[i]:
if count == rightPairs:
flag = False
break
print(leftIndex['?'].pop(), j)
count += 1
if not flag:
break
# print(leftIndex['?'] , left['?'] - rightPairs)
for i in range(min(right['?'] - leftPairs, left['?'] - rightPairs)):
print(leftIndex['?'].pop(), rightIndex['?'].pop())
#CODE ENDS HERE....................
#stdout.close()
``` | instruction | 0 | 78,352 | 7 | 156,704 |
No | output | 1 | 78,352 | 7 | 156,705 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n left boots and n right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings l and r, both of length n. The character l_i stands for the color of the i-th left boot and the character r_i stands for the color of the i-th right boot.
A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.
For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').
Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.
Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.
Input
The first line contains n (1 ≤ n ≤ 150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).
The second line contains the string l of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th left boot.
The third line contains the string r of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th right boot.
Output
Print k — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.
The following k lines should contain pairs a_j, b_j (1 ≤ a_j, b_j ≤ n). The j-th of these lines should contain the index a_j of the left boot in the j-th pair and index b_j of the right boot in the j-th pair. All the numbers a_j should be distinct (unique), all the numbers b_j should be distinct (unique).
If there are many optimal answers, print any of them.
Examples
Input
10
codeforces
dodivthree
Output
5
7 8
4 9
2 2
9 10
3 1
Input
7
abaca?b
zabbbcc
Output
5
6 5
2 3
4 6
7 4
1 2
Input
9
bambarbia
hellocode
Output
0
Input
10
code??????
??????test
Output
10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10
Submitted Solution:
```
n = int(input())
arr1 = list(input())
arr2 = list(input())
alphabet = list("abcdefghijklmnopqrstuvwxyz?")
alphabetdict = {
}
for letter in alphabet:
alphabetdict[letter] = [[], []]
for i in range(n):
alphabetdict[arr1[i]][0].append(i)
for i in range(n):
alphabetdict[arr2[i]][1].append(i)
pairs = []
for i in range(26):
current = alphabetdict[alphabet[i]]
while len(alphabetdict[alphabet[i]][0]) and len(alphabetdict[alphabet[i]][1]):
x, y = alphabetdict[alphabet[i]][0].pop(), alphabetdict[alphabet[i]][1].pop()
pairs.append((x,y))
arr1any = alphabetdict['?'][0]
arr2any = alphabetdict['?'][1]
combinedarr1 = []
for i in range(26):
combinedarr1 += alphabetdict[alphabet[i]][0]
combinedarr2 = []
for i in range(26):
combinedarr2 += alphabetdict[alphabet[i]][1]
#print(combinedarr1, combinedarr2)
for i in range(min(len(combinedarr1), len(arr2any))):
pairs.append((arr2any.pop(), combinedarr1[i]))
for i in range(min(len(combinedarr2), len(arr1any))):
pairs.append((arr1any.pop(), combinedarr2[i]))
for i in range(min(len(arr1any), len(arr2any))):
pairs.append((arr1any[i], arr2any[i]))
#print(arr1any, arr2any)
print(len(pairs))
for pair in pairs:
print(pair[0], pair[1])
``` | instruction | 0 | 78,353 | 7 | 156,706 |
No | output | 1 | 78,353 | 7 | 156,707 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n left boots and n right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings l and r, both of length n. The character l_i stands for the color of the i-th left boot and the character r_i stands for the color of the i-th right boot.
A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.
For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').
Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.
Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.
Input
The first line contains n (1 ≤ n ≤ 150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).
The second line contains the string l of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th left boot.
The third line contains the string r of length n. It contains only lowercase Latin letters or question marks. The i-th character stands for the color of the i-th right boot.
Output
Print k — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.
The following k lines should contain pairs a_j, b_j (1 ≤ a_j, b_j ≤ n). The j-th of these lines should contain the index a_j of the left boot in the j-th pair and index b_j of the right boot in the j-th pair. All the numbers a_j should be distinct (unique), all the numbers b_j should be distinct (unique).
If there are many optimal answers, print any of them.
Examples
Input
10
codeforces
dodivthree
Output
5
7 8
4 9
2 2
9 10
3 1
Input
7
abaca?b
zabbbcc
Output
5
6 5
2 3
4 6
7 4
1 2
Input
9
bambarbia
hellocode
Output
0
Input
10
code??????
??????test
Output
10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10
Submitted Solution:
```
from collections import defaultdict
n = int(input())
l = list(input())
r = list(input())
dl = defaultdict(list)
dr = defaultdict(list)
base='abcdefghijklmnopqrstuvwzyz'
#for i in range(n):
# dl[l[i]]=[]
# dr[r[i]]=[]
#dr['?']=[]
#dl['?']=[]
for i in range(n):
dl[l[i]].append(i)
dr[r[i]].append(i)
#print(dl,dr)
c=0
pair=[]
"""
for i in range(:
while dl[l[i]] and dr[r[i]]:
print(1+dl[li[i]].pop(),1+dr[r[i]].pop())
while dl[l[i]] and dr['?']:
print(1+dl[l[i]].pop(),1+dr['?'].pop())
while dl['?'] and dr[r[i]]:
print(1+dl['?'].pop() , 1+dr[r[i]].pop())
"""
for i in base:
while dl[i] and dr[i]:
pair.append((1+dl[i].pop(),1+dr[i].pop()))
# print(1+dl[i].pop(),1+dr[i].pop())
c+=1
for i in base:
while dl['?'] and dr[i]:
pair.append((1+dl['?'].pop(),1+dr[i].pop()))
# print(1+dl[i].pop(),1+dr['?'].pop())
c+=1
for i in base:
while dr['?'] and dl[i]:
pair.append((1+dl[i].pop() , 1+dr['?'].pop()))
# print(1+dl['?'].pop() , 1+dr[i].pop())
c+=1
while dl['?'] and dr['?']:
pair.append((1+dl['?'].pop(),1+dr['?'].pop()))
# print(1+dl['?'].pop(),1+dr['?'].pop())
c+=1
print(c)
for i in pair:
print(*i)
``` | instruction | 0 | 78,354 | 7 | 156,708 |
No | output | 1 | 78,354 | 7 | 156,709 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n lanterns in a row. The lantern i is placed in position i and has power equal to p_i.
Each lantern can be directed to illuminate either some lanterns to the left or some lanterns to the right. If the i-th lantern is turned to the left, it illuminates all such lanterns j that j ∈ [i - p_i, i - 1]. Similarly, if it is turned to the right, it illuminates all such lanterns j that j ∈ [i + 1, i + p_i].
Your goal is to choose a direction for each lantern so each lantern is illuminated by at least one other lantern, or report that it is impossible.
Input
The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases.
Each test case consists of two lines. The first line contains one integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of lanterns.
The second line contains n integers p_1, p_2, ..., p_n (0 ≤ p_i ≤ n) — the power of the i-th lantern.
The sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print the answer as follows:
If it is possible to direct all lanterns so that each lantern is illuminated, print YES in the first line and a string of n characters L and/or R (the i-th character is L if the i-th lantern is turned to the left, otherwise this character is R) in the second line. If there are multiple answers, you may print any of them.
If there is no answer, simply print NO for that test case.
Example
Input
4
8
0 0 3 1 1 1 1 2
2
1 1
2
2 2
2
0 1
Output
YES
RRLLLLRL
YES
RL
YES
RL
NO | instruction | 0 | 78,497 | 7 | 156,994 |
Tags: binary search, data structures, dp
Correct Solution:
```
from bisect import *
from collections import *
from math import gcd,ceil,sqrt,floor,inf
from heapq import *
from itertools import *
from operator import add,mul,sub,xor,truediv,floordiv
from functools import *
#------------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
#------------------------------------------------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
#------------------------------------------------------------------------
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
mod=10**9+7
farr=[1]
ifa=[]
def fact(x,mod=0):
if mod:
while x>=len(farr):
farr.append(farr[-1]*len(farr)%mod)
else:
while x>=len(farr):
farr.append(farr[-1]*len(farr))
return farr[x]
def ifact(x,mod):
global ifa
fact(x,mod)
ifa.append(pow(farr[-1],mod-2,mod))
for i in range(x,0,-1):
ifa.append(ifa[-1]*i%mod)
ifa.reverse()
def per(i,j,mod=0):
if i<j: return 0
if not mod:
return fact(i)//fact(i-j)
return farr[i]*ifa[i-j]%mod
def com(i,j,mod=0):
if i<j: return 0
if not mod:
return per(i,j)//fact(j)
return per(i,j,mod)*ifa[j]%mod
def catalan(n):
return com(2*n,n)//(n+1)
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def floorsum(a,b,c,n):#sum((a*i+b)//c for i in range(n+1))
if a==0:return b//c*(n+1)
if a>=c or b>=c: return floorsum(a%c,b%c,c,n)+b//c*(n+1)+a//c*n*(n+1)//2
m=(a*n+b)//c
return n*m-floorsum(c,c-b-1,a,m-1)
def inverse(a,m):
a%=m
if a<=1: return a
return ((1-inverse(m,a)*m)//a)%m
def lowbit(n):
return n&-n
class BIT:
def __init__(self,arr):
self.arr=arr
self.n=len(arr)-1
def update(self,x,v):
while x<=self.n:
self.arr[x]+=v
x+=x&-x
def query(self,x):
ans=0
while x:
ans+=self.arr[x]
x&=x-1
return ans
class ST:
def __init__(self,arr):#n!=0
n=len(arr)
mx=n.bit_length()#取不到
self.st=[[0]*mx for i in range(n)]
for i in range(n):
self.st[i][0]=arr[i]
for j in range(1,mx):
for i in range(n-(1<<j)+1):
self.st[i][j]=max(self.st[i][j-1],self.st[i+(1<<j-1)][j-1])
def query(self,l,r):
if l>r:return -inf
s=(r+1-l).bit_length()-1
return max(self.st[l][s],self.st[r-(1<<s)+1][s])
class DSU:#容量+路径压缩
def __init__(self,n):
self.c=[-1]*n
def same(self,x,y):
return self.find(x)==self.find(y)
def find(self,x):
if self.c[x]<0:
return x
self.c[x]=self.find(self.c[x])
return self.c[x]
def union(self,u,v):
u,v=self.find(u),self.find(v)
if u==v:
return False
if self.c[u]>self.c[v]:
u,v=v,u
self.c[u]+=self.c[v]
self.c[v]=u
return True
def size(self,x): return -self.c[self.find(x)]
class UFS:#秩+路径
def __init__(self,n):
self.parent=[i for i in range(n)]
self.ranks=[0]*n
def find(self,x):
if x!=self.parent[x]:
self.parent[x]=self.find(self.parent[x])
return self.parent[x]
def union(self,u,v):
pu,pv=self.find(u),self.find(v)
if pu==pv:
return False
if self.ranks[pu]>=self.ranks[pv]:
self.parent[pv]=pu
if self.ranks[pv]==self.ranks[pu]:
self.ranks[pu]+=1
else:
self.parent[pu]=pv
def Prime(n):
c=0
prime=[]
flag=[0]*(n+1)
for i in range(2,n+1):
if not flag[i]:
prime.append(i)
c+=1
for j in range(c):
if i*prime[j]>n: break
flag[i*prime[j]]=prime[j]
if i%prime[j]==0: break
return prime
def dij(s,graph):
d={}
d[s]=0
heap=[(0,s)]
seen=set()
while heap:
dis,u=heappop(heap)
if u in seen:
continue
seen.add(u)
for v,w in graph[u]:
if v not in d or d[v]>d[u]+w:
d[v]=d[u]+w
heappush(heap,(d[v],v))
return d
def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)]
def lcm(a,b): return a*b//gcd(a,b)
def lis(nums):
res=[]
for k in nums:
i=bisect.bisect_left(res,k)
if i==len(res):
res.append(k)
else:
res[i]=k
return len(res)
def RP(nums):#逆序对
n = len(nums)
s=set(nums)
d={}
for i,k in enumerate(sorted(s),1):
d[k]=i
bi=BIT([0]*(len(s)+1))
ans=0
for i in range(n-1,-1,-1):
ans+=bi.query(d[nums[i]]-1)
bi.update(d[nums[i]],1)
return ans
class DLN:
def __init__(self,val):
self.val=val
self.pre=None
self.next=None
def nb(i,j):
for ni,nj in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]:
if 0<=ni<n and 0<=nj<m:
yield ni,nj
def topo(n):
q=deque()
res=[]
for i in range(1,n+1):
if ind[i]==0:
q.append(i)
res.append(i)
while q:
u=q.popleft()
for v in g[u]:
ind[v]-=1
if ind[v]==0:
q.append(v)
res.append(v)
return res
@bootstrap
def gdfs(r,p):
if len(g[r])==1 and p!=-1:
yield None
for ch in g[r]:
if ch!=p:
yield gdfs(ch,r)
yield None
t=N()
for i in range(t):
n=N()
p=[0]+RLL()
a=[i+p[i] for i in range(n+1)]
st=ST(a)
dp=[0]*(n+1)
last=[0]*(n+1)
#print(a)
for i in range(2,n+1):
if not p[i]:
dp[i]=dp[i-1]
last[i]=i
continue
j=bisect_left(dp,i-p[i]-1,0,i)
last[i]=j
if j==i:
dp[i]=dp[i-1]
else:
#print(i,j,dp[j],st.query(j+1,i-1),i-1)
dp[i]=max(dp[j],st.query(j+1,i-1),i-1)
if dp[i-1]>=i:
if dp[i]<max(dp[i-1],i+p[i]):
dp[i]=max(dp[i-1],i+p[i])
last[i]=i
#print(dp)
if dp[-1]<n:
print("NO")
else:
print("YES")
cur=n
ans=["R"]*n
while cur:
if last[cur]!=cur:
ans[cur-1]="L"
cur=last[cur]
else:
cur-=1
ans=''.join(ans)
print(ans)
``` | output | 1 | 78,497 | 7 | 156,995 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n lanterns in a row. The lantern i is placed in position i and has power equal to p_i.
Each lantern can be directed to illuminate either some lanterns to the left or some lanterns to the right. If the i-th lantern is turned to the left, it illuminates all such lanterns j that j ∈ [i - p_i, i - 1]. Similarly, if it is turned to the right, it illuminates all such lanterns j that j ∈ [i + 1, i + p_i].
Your goal is to choose a direction for each lantern so each lantern is illuminated by at least one other lantern, or report that it is impossible.
Input
The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases.
Each test case consists of two lines. The first line contains one integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of lanterns.
The second line contains n integers p_1, p_2, ..., p_n (0 ≤ p_i ≤ n) — the power of the i-th lantern.
The sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print the answer as follows:
If it is possible to direct all lanterns so that each lantern is illuminated, print YES in the first line and a string of n characters L and/or R (the i-th character is L if the i-th lantern is turned to the left, otherwise this character is R) in the second line. If there are multiple answers, you may print any of them.
If there is no answer, simply print NO for that test case.
Example
Input
4
8
0 0 3 1 1 1 1 2
2
1 1
2
2 2
2
0 1
Output
YES
RRLLLLRL
YES
RL
YES
RL
NO | instruction | 0 | 78,498 | 7 | 156,996 |
Tags: binary search, data structures, dp
Correct Solution:
```
from bisect import bisect_left;from math import inf
class ST:
def __init__(self,arr):
n=len(arr);mx=n.bit_length();self.st=[[0]*mx for i in range(n)]
for i in range(n):self.st[i][0]=arr[i]
for j in range(1,mx):
for i in range(n-(1<<j)+1):self.st[i][j]=max(self.st[i][j-1],self.st[i+(1<<j-1)][j-1])
def query(self,l,r):
if l>r:return -inf
s=(r+1-l).bit_length()-1;return max(self.st[l][s],self.st[r-(1<<s)+1][s])
for i in range(int(input())):
n=int(input());p=[0]+list(map(int,input().split()));a=[i+p[i] for i in range(n+1)];st=ST(a);dp=[0]*(n+1);last=[0]*(n+1)
for i in range(2,n+1):
if not p[i]:dp[i]=dp[i-1];last[i]=i;continue
j=bisect_left(dp,i-p[i]-1,0,i);last[i]=j
if j==i:dp[i]=dp[i-1]
else:
dp[i]=max(dp[j],st.query(j+1,i-1),i-1)
if dp[i-1]>=i:
if dp[i]<max(dp[i-1],i+p[i]):dp[i]=max(dp[i-1],i+p[i]);last[i]=i
if dp[-1]<n:print("NO")
else:
print("YES");cur=n;ans=["R"]*n
while cur:
if last[cur]!=cur:ans[cur-1]="L";cur=last[cur]
else:cur-=1
print(''.join(ans))
``` | output | 1 | 78,498 | 7 | 156,997 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n lanterns in a row. The lantern i is placed in position i and has power equal to p_i.
Each lantern can be directed to illuminate either some lanterns to the left or some lanterns to the right. If the i-th lantern is turned to the left, it illuminates all such lanterns j that j ∈ [i - p_i, i - 1]. Similarly, if it is turned to the right, it illuminates all such lanterns j that j ∈ [i + 1, i + p_i].
Your goal is to choose a direction for each lantern so each lantern is illuminated by at least one other lantern, or report that it is impossible.
Input
The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases.
Each test case consists of two lines. The first line contains one integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of lanterns.
The second line contains n integers p_1, p_2, ..., p_n (0 ≤ p_i ≤ n) — the power of the i-th lantern.
The sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print the answer as follows:
If it is possible to direct all lanterns so that each lantern is illuminated, print YES in the first line and a string of n characters L and/or R (the i-th character is L if the i-th lantern is turned to the left, otherwise this character is R) in the second line. If there are multiple answers, you may print any of them.
If there is no answer, simply print NO for that test case.
Example
Input
4
8
0 0 3 1 1 1 1 2
2
1 1
2
2 2
2
0 1
Output
YES
RRLLLLRL
YES
RL
YES
RL
NO | instruction | 0 | 78,499 | 7 | 156,998 |
Tags: binary search, data structures, dp
Correct Solution:
```
from bisect import *
from collections import *
from math import gcd,ceil,sqrt,floor,inf
from heapq import *
from itertools import *
from operator import add,mul,sub,xor,truediv,floordiv
from functools import *
#------------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#------------------------------------------------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
#------------------------------------------------------------------------
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
mod=10**9+7
farr=[1]
ifa=[]
def fact(x,mod=0):
if mod:
while x>=len(farr):
farr.append(farr[-1]*len(farr)%mod)
else:
while x>=len(farr):
farr.append(farr[-1]*len(farr))
return farr[x]
def ifact(x,mod):
global ifa
fact(x,mod)
ifa.append(pow(farr[-1],mod-2,mod))
for i in range(x,0,-1):
ifa.append(ifa[-1]*i%mod)
ifa.reverse()
def per(i,j,mod=0):
if i<j: return 0
if not mod:
return fact(i)//fact(i-j)
return farr[i]*ifa[i-j]%mod
def com(i,j,mod=0):
if i<j: return 0
if not mod:
return per(i,j)//fact(j)
return per(i,j,mod)*ifa[j]%mod
def catalan(n):
return com(2*n,n)//(n+1)
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def floorsum(a,b,c,n):#sum((a*i+b)//c for i in range(n+1))
if a==0:return b//c*(n+1)
if a>=c or b>=c: return floorsum(a%c,b%c,c,n)+b//c*(n+1)+a//c*n*(n+1)//2
m=(a*n+b)//c
return n*m-floorsum(c,c-b-1,a,m-1)
def inverse(a,m):
a%=m
if a<=1: return a
return ((1-inverse(m,a)*m)//a)%m
def lowbit(n):
return n&-n
class BIT:
def __init__(self,arr):
self.arr=arr
self.n=len(arr)-1
def update(self,x,v):
while x<=self.n:
self.arr[x]+=v
x+=x&-x
def query(self,x):
ans=0
while x:
ans+=self.arr[x]
x&=x-1
return ans
'''
class SMT:
def __init__(self,arr):
self.n=len(arr)-1#arr包含一个前导0
self.arr=[0]*(self.n<<2)
self.lazy=[0]*(self.n<<2)
def Build(l,r,rt):
if l==r:
self.arr[rt]=arr[l]
return
m=(l+r)>>1
Build(l,m,rt<<1)
Build(m+1,r,rt<<1|1)
self.pushup(rt)
Build(1,self.n,1)
def pushup(self,rt):
self.arr[rt]=self.arr[rt<<1]+self.arr[rt<<1|1]
def pushdown(self,rt,ln,rn):#lr,rn表区间数字数
if self.lazy[rt]:
self.lazy[rt<<1]+=self.lazy[rt]
self.lazy[rt<<1|1]+=self.lazy[rt]
self.arr[rt<<1]+=self.lazy[rt]*ln
self.arr[rt<<1|1]+=self.lazy[rt]*rn
self.lazy[rt]=0
def update(self,L,R,c,l=1,r=None,rt=1):#L,R表示操作区间
if r==None: r=self.n
if L<=l and r<=R:
self.arr[rt]+=c*(r-l+1)
self.lazy[rt]+=c
return
m=(l+r)>>1
self.pushdown(rt,m-l+1,r-m)
if L<=m: self.update(L,R,c,l,m,rt<<1)
if R>m: self.update(L,R,c,m+1,r,rt<<1|1)
self.pushup(rt)
def query(self,L,R,l=1,r=None,rt=1):
if r==None: r=self.n
#print(L,R,l,r,rt)
if L<=l and R>=r:
return self.arr[rt]
m=(l+r)>>1
self.pushdown(rt,m-l+1,r-m)
ans=0
if L<=m: ans+=self.query(L,R,l,m,rt<<1)
if R>m: ans+=self.query(L,R,m+1,r,rt<<1|1)
return ans
'''
class ST:
def __init__(self,arr):#n!=0
n=len(arr)
mx=n.bit_length()#取不到
self.st=[[0]*mx for i in range(n)]
for i in range(n):
self.st[i][0]=arr[i]
for j in range(1,mx):
for i in range(n-(1<<j)+1):
self.st[i][j]=max(self.st[i][j-1],self.st[i+(1<<j-1)][j-1])
def query(self,l,r):
if l>r:return -inf
s=(r+1-l).bit_length()-1
return max(self.st[l][s],self.st[r-(1<<s)+1][s])
class DSU:#容量+路径压缩
def __init__(self,n):
self.c=[-1]*n
def same(self,x,y):
return self.find(x)==self.find(y)
def find(self,x):
if self.c[x]<0:
return x
self.c[x]=self.find(self.c[x])
return self.c[x]
def union(self,u,v):
u,v=self.find(u),self.find(v)
if u==v:
return False
if self.c[u]>self.c[v]:
u,v=v,u
self.c[u]+=self.c[v]
self.c[v]=u
return True
def size(self,x): return -self.c[self.find(x)]
class UFS:#秩+路径
def __init__(self,n):
self.parent=[i for i in range(n)]
self.ranks=[0]*n
def find(self,x):
if x!=self.parent[x]:
self.parent[x]=self.find(self.parent[x])
return self.parent[x]
def union(self,u,v):
pu,pv=self.find(u),self.find(v)
if pu==pv:
return False
if self.ranks[pu]>=self.ranks[pv]:
self.parent[pv]=pu
if self.ranks[pv]==self.ranks[pu]:
self.ranks[pu]+=1
else:
self.parent[pu]=pv
def Prime(n):
c=0
prime=[]
flag=[0]*(n+1)
for i in range(2,n+1):
if not flag[i]:
prime.append(i)
c+=1
for j in range(c):
if i*prime[j]>n: break
flag[i*prime[j]]=prime[j]
if i%prime[j]==0: break
return prime
def dij(s,graph):
d={}
d[s]=0
heap=[(0,s)]
seen=set()
while heap:
dis,u=heappop(heap)
if u in seen:
continue
seen.add(u)
for v,w in graph[u]:
if v not in d or d[v]>d[u]+w:
d[v]=d[u]+w
heappush(heap,(d[v],v))
return d
def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)]
def lcm(a,b): return a*b//gcd(a,b)
def lis(nums):
res=[]
for k in nums:
i=bisect.bisect_left(res,k)
if i==len(res):
res.append(k)
else:
res[i]=k
return len(res)
def RP(nums):#逆序对
n = len(nums)
s=set(nums)
d={}
for i,k in enumerate(sorted(s),1):
d[k]=i
bi=BIT([0]*(len(s)+1))
ans=0
for i in range(n-1,-1,-1):
ans+=bi.query(d[nums[i]]-1)
bi.update(d[nums[i]],1)
return ans
class DLN:
def __init__(self,val):
self.val=val
self.pre=None
self.next=None
def nb(i,j):
for ni,nj in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]:
if 0<=ni<n and 0<=nj<m:
yield ni,nj
def topo(n):
q=deque()
res=[]
for i in range(1,n+1):
if ind[i]==0:
q.append(i)
res.append(i)
while q:
u=q.popleft()
for v in g[u]:
ind[v]-=1
if ind[v]==0:
q.append(v)
res.append(v)
return res
@bootstrap
def gdfs(r,p):
if len(g[r])==1 and p!=-1:
yield None
for ch in g[r]:
if ch!=p:
yield gdfs(ch,r)
yield None
t=N()
for i in range(t):
n=N()
p=[0]+RLL()
a=[i+p[i] for i in range(n+1)]
st=ST(a)
dp=[0]*(n+1)
last=[0]*(n+1)
#print(a)
for i in range(2,n+1):
if not p[i]:
dp[i]=dp[i-1]
last[i]=i
continue
j=bisect_left(dp,i-p[i]-1,0,i)
last[i]=j
if j==i:
dp[i]=dp[i-1]
else:
#print(i,j,dp[j],st.query(j+1,i-1),i-1)
dp[i]=max(dp[j],st.query(j+1,i-1),i-1)
if dp[i-1]>=i:
if dp[i]<max(dp[i-1],i+p[i]):
dp[i]=max(dp[i-1],i+p[i])
last[i]=i
#print(dp)
if dp[-1]<n:
print("NO")
else:
print("YES")
cur=n
ans=["R"]*n
while cur:
if last[cur]!=cur:
ans[cur-1]="L"
cur=last[cur]
else:
cur-=1
ans=''.join(ans)
print(ans)
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thr
ead(target=main)
t.start()
t.join()
'''
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thread(target=main)
t.start()
t.join()
'''
``` | output | 1 | 78,499 | 7 | 156,999 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n lanterns in a row. The lantern i is placed in position i and has power equal to p_i.
Each lantern can be directed to illuminate either some lanterns to the left or some lanterns to the right. If the i-th lantern is turned to the left, it illuminates all such lanterns j that j ∈ [i - p_i, i - 1]. Similarly, if it is turned to the right, it illuminates all such lanterns j that j ∈ [i + 1, i + p_i].
Your goal is to choose a direction for each lantern so each lantern is illuminated by at least one other lantern, or report that it is impossible.
Input
The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases.
Each test case consists of two lines. The first line contains one integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of lanterns.
The second line contains n integers p_1, p_2, ..., p_n (0 ≤ p_i ≤ n) — the power of the i-th lantern.
The sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print the answer as follows:
If it is possible to direct all lanterns so that each lantern is illuminated, print YES in the first line and a string of n characters L and/or R (the i-th character is L if the i-th lantern is turned to the left, otherwise this character is R) in the second line. If there are multiple answers, you may print any of them.
If there is no answer, simply print NO for that test case.
Example
Input
4
8
0 0 3 1 1 1 1 2
2
1 1
2
2 2
2
0 1
Output
YES
RRLLLLRL
YES
RL
YES
RL
NO
Submitted Solution:
```
from sys import stdin
from math import ceil
input = stdin.readline
def main():
t=int(input())
for i in range(t):
n = int(input())
pi = list(map(int,input().split()))
ai = [""]*n
ai[0] = "R"
light = 0+pi[0]+1
light2 = 10000000000
min_light_ind = -1
lind = 0
ans = 1
for i in range(1,n):
if light >= i:
if lind > i-pi[i]-1:
temp = i+pi[i]+1
if light2 > temp:
light2 = temp
min_light_ind = i
ai[i] = "R"
else:
light = i+pi[i]+1
ai[i] = "R"
else:
light = i+pi[i]+1
ai[i] = "R"
else:
if min_light_ind != -1:
light = i+pi[i]+1
ai[i] = "R"
lind = i
light2 = 10000000000
ai[min_light_ind] = "L"
min_light_ind=-1
else:
if lind > i-pi[i]-1:
light = i
lind = i+1
light2 = 10000000000
ai[i] = "L"
min_light_ind=-1
else:
light = i+pi[i]+1
ai[i] = "R"
if light<n or (min_light_ind==-1 and lind!=n):
ans = 0
ai[-1] = "L"
if ans:
print("YES")
print("".join(ai))
else:
print("NO")
main()
``` | instruction | 0 | 78,501 | 7 | 157,002 |
No | output | 1 | 78,501 | 7 | 157,003 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n lanterns in a row. The lantern i is placed in position i and has power equal to p_i.
Each lantern can be directed to illuminate either some lanterns to the left or some lanterns to the right. If the i-th lantern is turned to the left, it illuminates all such lanterns j that j ∈ [i - p_i, i - 1]. Similarly, if it is turned to the right, it illuminates all such lanterns j that j ∈ [i + 1, i + p_i].
Your goal is to choose a direction for each lantern so each lantern is illuminated by at least one other lantern, or report that it is impossible.
Input
The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases.
Each test case consists of two lines. The first line contains one integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of lanterns.
The second line contains n integers p_1, p_2, ..., p_n (0 ≤ p_i ≤ n) — the power of the i-th lantern.
The sum of n over all test cases does not exceed 3 ⋅ 10^5.
Output
For each test case, print the answer as follows:
If it is possible to direct all lanterns so that each lantern is illuminated, print YES in the first line and a string of n characters L and/or R (the i-th character is L if the i-th lantern is turned to the left, otherwise this character is R) in the second line. If there are multiple answers, you may print any of them.
If there is no answer, simply print NO for that test case.
Example
Input
4
8
0 0 3 1 1 1 1 2
2
1 1
2
2 2
2
0 1
Output
YES
RRLLLLRL
YES
RL
YES
RL
NO
Submitted Solution:
```
def swapp(n,p):
aa=[]
ui=0
uo=0
for i in range(n):
aa.append(0)
a=0
b=n-1
at=''
bt=''
if n%2==0:
while b>a:
# print(at,bt)
if ui==0:
if p[a]>0 and a==0:
at+='R'
for i in range(1,p[a]+1):
if i<len(aa) and i>=0:
aa[i]=1
elif p[a]==0 :
at+='R'
elif p[a]>0:
gg=0
pp=0
for i in range(a):
if aa[a-i-1]==0:
pp=1
gg=a-i-1
if pp>0:
if p[a]>=a-gg:
for i in range(gg,a):
if i<len(aa) and i>=0:
aa[i]=1
at+='L'
if pp==0:
at+='R'
for i in range(a+1,a+p[a]):
if i<len(aa) and i>=0:
aa[i]=1
else:
at+="R"
a+=1
if uo==0:
# print(aa,bt)
if p[b]>0 and b==n-1:
bt+='L'
for i in range(1,p[b]+1):
if b-i>=0 and b-i<len(aa):
aa[b-i]=1
elif p[b]==0 :
bt+='L'
elif p[b]>0:
gg=0
pp=0
for i in range(b+1,n):
if i<len(aa) and i>=0:
pp=1
gg=i
# print("y",pp,gg)
if pp>0:
if p[b]>=gg-b:
for i in range(b+1,gg+1):
if i<len(aa) and i>=0:
aa[i]=1
bt+='R'
elif pp==0:
bt+='L'
for i in range(b-p[b],b):
if i<len(aa) and i>=0:
aa[i]=1
else:
bt+='L'
b-=1
else:
while b>=a:
# print(at,bt)
if b==a:
uo+=1
if ui==0:
if p[a]>0 and a==0:
at+='R'
for i in range(1,p[a]+1):
if i<len(aa) and i>=0:
aa[i]=1
elif p[a]==0 :
at+='R'
elif p[a]>0:
gg=0
pp=0
for i in range(a):
if aa[a-i-1]==0:
pp=1
gg=a-i-1
if pp>0:
if p[a]>=a-gg:
for i in range(gg,a):
if i<len(aa) and i>=0:
aa[i]=1
at+='L'
if pp==0:
at+='R'
for i in range(a+1,a+p[a]):
if i<len(aa) and i>=0:
aa[i]=1
else:
at+="R"
a+=1
if uo==0:
# print(aa,bt)
if p[b]>0 and b==n-1:
bt+='L'
for i in range(1,p[b]+1):
if b-i>=0 and b-i<len(aa):
aa[b-i]=1
elif p[b]==0 :
bt+='L'
elif p[b]>0:
gg=0
pp=0
for i in range(b+1,n):
if aa[i]==0:
pp=1
gg=i
# print("y",pp,gg)
if pp>0:
if p[b]>=gg-b:
for i in range(b+1,gg+1):
if i<len(aa) and i>=0:
aa[i]=1
bt+='R'
elif pp==0:
bt+='L'
for i in range(b-p[b],b):
if i<len(aa) and i>=0:
aa[i]=1
else:
bt+='L'
b-=1
# print("y",at,bt)
if aa.count(1)==n:
print("YES")
for i in range(len(bt)):
at+=bt[len(bt)-i-1]
print(at)
else:
print("NO")
t = int(input())
for i in range(t):
n = int(input())
p = list(map(int, input().rstrip().split()))
ans = swapp(n,p)
``` | instruction | 0 | 78,503 | 7 | 157,006 |
No | output | 1 | 78,503 | 7 | 157,007 |
Provide a correct Python 3 solution for this coding contest problem.
Arkady decided to buy roses for his girlfriend.
A flower shop has white, orange and red roses, and the total amount of them is n. Arkady thinks that red roses are not good together with white roses, so he won't buy a bouquet containing both red and white roses. Also, Arkady won't buy a bouquet where all roses have the same color.
Arkady wants to buy exactly k roses. For each rose in the shop he knows its beauty and color: the beauty of the i-th rose is bi, and its color is ci ('W' for a white rose, 'O' for an orange rose and 'R' for a red rose).
Compute the maximum possible total beauty of a bouquet of k roses satisfying the constraints above or determine that it is not possible to make such a bouquet.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of roses in the show and the number of roses Arkady wants to buy.
The second line contains a sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 10 000), where bi equals the beauty of the i-th rose.
The third line contains a string c of length n, consisting of uppercase English letters 'W', 'O' and 'R', where ci denotes the color of the i-th rose: 'W' denotes white, 'O' — orange, 'R' — red.
Output
Print the maximum possible total beauty of a bouquet of k roses that satisfies the constraints above. If it is not possible to make a single such bouquet, print -1.
Examples
Input
5 3
4 3 4 1 6
RROWW
Output
11
Input
5 2
10 20 14 20 11
RRRRR
Output
-1
Input
11 5
5 6 3 2 3 4 7 5 4 5 6
RWOORWORROW
Output
28
Note
In the first example Arkady wants to buy 3 roses. He can, for example, buy both red roses (their indices are 1 and 2, and their total beauty is 7) and the only orange rose (its index is 3, its beauty is 4). This way the total beauty of the bouquet is 11.
In the second example Arkady can not buy a bouquet because all roses have the same color. | instruction | 0 | 78,846 | 7 | 157,692 |
"Correct Solution:
```
n, k = [int(x) for x in input().strip().split(" ")]
b = [int(x) for x in input().strip().split(" ")]
c = input().strip()
w = sorted([b[i] for i in range(len(b)) if c[i] == 'W'])
o = sorted([b[i] for i in range(len(b)) if c[i] == 'O'])
r = sorted([b[i] for i in range(len(b)) if c[i] == 'R'])
if k == 1 or len(o) == 0 or len(w) == 0 and len(r) == 0:
print(-1)
exit()
max_wo = -1
if len(w) > 0 and len(w) + len(o) >= k:
wo = sorted(w[:-1] + o[:-1])
max_wo = w[-1] + o[-1]
if k > 2:
max_wo += sum(wo[-(k-2):])
max_ro = -1
if len(r) > 0 and len(r) + len(o) >= k:
ro = sorted(r[:-1] + o[:-1])
max_ro = r[-1] + o[-1]
if k > 2:
max_ro += sum(ro[-(k-2):])
ans = max(max_wo, max_ro)
print(ans)
``` | output | 1 | 78,846 | 7 | 157,693 |
Provide a correct Python 3 solution for this coding contest problem.
Arkady decided to buy roses for his girlfriend.
A flower shop has white, orange and red roses, and the total amount of them is n. Arkady thinks that red roses are not good together with white roses, so he won't buy a bouquet containing both red and white roses. Also, Arkady won't buy a bouquet where all roses have the same color.
Arkady wants to buy exactly k roses. For each rose in the shop he knows its beauty and color: the beauty of the i-th rose is bi, and its color is ci ('W' for a white rose, 'O' for an orange rose and 'R' for a red rose).
Compute the maximum possible total beauty of a bouquet of k roses satisfying the constraints above or determine that it is not possible to make such a bouquet.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of roses in the show and the number of roses Arkady wants to buy.
The second line contains a sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 10 000), where bi equals the beauty of the i-th rose.
The third line contains a string c of length n, consisting of uppercase English letters 'W', 'O' and 'R', where ci denotes the color of the i-th rose: 'W' denotes white, 'O' — orange, 'R' — red.
Output
Print the maximum possible total beauty of a bouquet of k roses that satisfies the constraints above. If it is not possible to make a single such bouquet, print -1.
Examples
Input
5 3
4 3 4 1 6
RROWW
Output
11
Input
5 2
10 20 14 20 11
RRRRR
Output
-1
Input
11 5
5 6 3 2 3 4 7 5 4 5 6
RWOORWORROW
Output
28
Note
In the first example Arkady wants to buy 3 roses. He can, for example, buy both red roses (their indices are 1 and 2, and their total beauty is 7) and the only orange rose (its index is 3, its beauty is 4). This way the total beauty of the bouquet is 11.
In the second example Arkady can not buy a bouquet because all roses have the same color. | instruction | 0 | 78,847 | 7 | 157,694 |
"Correct Solution:
```
n, k = map(int, input().split())
a = [int(i) for i in input().split()]
w = []
r = []
o = []
s = input()
for i in range(n):
if s[i] == 'O':
o.append(a[i])
if s[i] == 'R':
r.append(a[i])
if s[i] == 'W':
w.append(a[i])
o.sort(), w.sort(), r.sort()
w = w[::-1]
o = o[::-1]
r = r[::-1]
ans = -1
i = 0
j = 0
cntf = 0
cnts = 0
nw = 0
while (cntf + cnts) < k and (i < len(w) or j < len(o)):
if(i >= len(w)):
nw += o[j]
j += 1
cnts += 1
elif(j >= len(o)):
nw += w[i]
i += 1
cntf += 1
else:
if(w[i] > o[j]):
nw += w[i]
i += 1
cntf += 1
else:
nw += o[j]
j += 1
cnts += 1
if(cntf + cnts == k - 1):
if(cntf == 0 and len(w) != 0):
nw += w[i]
cntf += 1
elif(cnts == 0 and len(o) != 0):
nw += o[j]
cnts += 1
if(cntf + cnts == k and cntf != 0 and cnts != 0):
ans = max(ans, nw)
i = 0
j = 0
cntf = 0
cnts = 0
nw = 0
while (cntf + cnts < k) and (i < len(r) or j < len(o)):
if(i >= len(r)):
nw += o[j]
j += 1
cnts += 1
elif(j >= len(o)):
nw += r[i]
i += 1
cntf += 1
else:
if(r[i] > o[j]):
nw += r[i]
i += 1
cntf += 1
else:
nw += o[j]
j += 1
cnts += 1
if(cntf + cnts == k - 1):
if(cntf == 0 and len(r) != 0):
nw += r[i]
cntf += 1
elif(cnts == 0 and len(o) != 0):
nw += o[j]
cnts += 1
if(cntf + cnts == k and cntf != 0 and cnts != 0):
ans = max(ans, nw)
print(ans)
``` | output | 1 | 78,847 | 7 | 157,695 |
Provide a correct Python 3 solution for this coding contest problem.
Arkady decided to buy roses for his girlfriend.
A flower shop has white, orange and red roses, and the total amount of them is n. Arkady thinks that red roses are not good together with white roses, so he won't buy a bouquet containing both red and white roses. Also, Arkady won't buy a bouquet where all roses have the same color.
Arkady wants to buy exactly k roses. For each rose in the shop he knows its beauty and color: the beauty of the i-th rose is bi, and its color is ci ('W' for a white rose, 'O' for an orange rose and 'R' for a red rose).
Compute the maximum possible total beauty of a bouquet of k roses satisfying the constraints above or determine that it is not possible to make such a bouquet.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of roses in the show and the number of roses Arkady wants to buy.
The second line contains a sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 10 000), where bi equals the beauty of the i-th rose.
The third line contains a string c of length n, consisting of uppercase English letters 'W', 'O' and 'R', where ci denotes the color of the i-th rose: 'W' denotes white, 'O' — orange, 'R' — red.
Output
Print the maximum possible total beauty of a bouquet of k roses that satisfies the constraints above. If it is not possible to make a single such bouquet, print -1.
Examples
Input
5 3
4 3 4 1 6
RROWW
Output
11
Input
5 2
10 20 14 20 11
RRRRR
Output
-1
Input
11 5
5 6 3 2 3 4 7 5 4 5 6
RWOORWORROW
Output
28
Note
In the first example Arkady wants to buy 3 roses. He can, for example, buy both red roses (their indices are 1 and 2, and their total beauty is 7) and the only orange rose (its index is 3, its beauty is 4). This way the total beauty of the bouquet is 11.
In the second example Arkady can not buy a bouquet because all roses have the same color. | instruction | 0 | 78,848 | 7 | 157,696 |
"Correct Solution:
```
n,k = map(int, input().split())
b = list(map(int,input().split()))
SSSSSSSSSS = input()
INF = 1000*1000*1000+123
RRRR = [];
WWWWWWW = [];
OOOOOOOOO = [];
for i in range(n):
if SSSSSSSSSS[i] == 'R':
RRRR.append(b[i])
elif SSSSSSSSSS[i] == 'W':
WWWWWWW.append(b[i])
else:
OOOOOOOOO.append(b[i])
WWWWWWW.sort()
RRRR.sort()
WWWWWWW.reverse()
RRRR.reverse()
OOOOOOOOO.sort()
OOOOOOOOO.reverse()
if k == 1:
print(-1)
exit(0)
def cccmcmc(A, B):
qanakA = len(A);
qanakB = len(B);
pA = [0 for i in range(qanakA)]
pB = [0 for i in range(qanakB)]
pB[0] = B[0]
pA[0] = A[0]
for i in range(1,qanakA):
pA[i] = pA[i-1] + A[i];
for i in range(1,qanakB):
pB[i] = pB[i-1] + B[i];
res = -1
for i in range(1,min(qanakA+1,k)):
aic = pA[i-1]
bepetk = k-i
if bepetk <= 0 or bepetk > qanakB: continue
bic = pB[bepetk-1]
res = max(res,aic+bic)
return res
res = -1
if len(WWWWWWW) > 0 and len(OOOOOOOOO)> 0:
res = max(res, cccmcmc(WWWWWWW, OOOOOOOOO))
if len(RRRR) > 0 and len(OOOOOOOOO)> 0:
res = max(res, cccmcmc(RRRR, OOOOOOOOO))
print(res)
``` | output | 1 | 78,848 | 7 | 157,697 |
Provide a correct Python 3 solution for this coding contest problem.
Arkady decided to buy roses for his girlfriend.
A flower shop has white, orange and red roses, and the total amount of them is n. Arkady thinks that red roses are not good together with white roses, so he won't buy a bouquet containing both red and white roses. Also, Arkady won't buy a bouquet where all roses have the same color.
Arkady wants to buy exactly k roses. For each rose in the shop he knows its beauty and color: the beauty of the i-th rose is bi, and its color is ci ('W' for a white rose, 'O' for an orange rose and 'R' for a red rose).
Compute the maximum possible total beauty of a bouquet of k roses satisfying the constraints above or determine that it is not possible to make such a bouquet.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of roses in the show and the number of roses Arkady wants to buy.
The second line contains a sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 10 000), where bi equals the beauty of the i-th rose.
The third line contains a string c of length n, consisting of uppercase English letters 'W', 'O' and 'R', where ci denotes the color of the i-th rose: 'W' denotes white, 'O' — orange, 'R' — red.
Output
Print the maximum possible total beauty of a bouquet of k roses that satisfies the constraints above. If it is not possible to make a single such bouquet, print -1.
Examples
Input
5 3
4 3 4 1 6
RROWW
Output
11
Input
5 2
10 20 14 20 11
RRRRR
Output
-1
Input
11 5
5 6 3 2 3 4 7 5 4 5 6
RWOORWORROW
Output
28
Note
In the first example Arkady wants to buy 3 roses. He can, for example, buy both red roses (their indices are 1 and 2, and their total beauty is 7) and the only orange rose (its index is 3, its beauty is 4). This way the total beauty of the bouquet is 11.
In the second example Arkady can not buy a bouquet because all roses have the same color. | instruction | 0 | 78,849 | 7 | 157,698 |
"Correct Solution:
```
n,k=map(int,input().split())
b=list(map(int,input().split()))
s=input()
a=[]
if k==1:
print(-1)
exit()
for i in range(n):
a.append((b[i],s[i]))
a.sort(reverse=True)
i=0
j=0
m1=0
q1=False
q2=False
while i!=k:
if a[j][1]!='R':
m1+=a[j][0]
g=j+0
if a[j][1]=='W':
q1=True
else:
q2=True
i+=1
j+=1
if j==n and i!=k:
m1=0
break
else:
if not (q1 and q2):
m1-=a[g][0]
for i in range(g+1,n):
if q1 and a[i][1]=='O' or q2 and a[i][1]=='W':
m1+=a[i][0]
break
else:
m1=0
i=0
j=0
m2=0
q1=False
q2=False
while i!=k:
if a[j][1]!='W':
m2+=a[j][0]
g=j+0
if a[j][1]=='R':
q1=True
else:
q2=True
i+=1
j+=1
if j==n and i!=k:
m2=0
break
else:
if not (q1 and q2):
m2-=a[g][0]
for i in range(g+1,n):
if q1 and a[i][1]=='O' or q2 and a[i][1]=='R':
m2+=a[i][0]
break
else:
m2=0
if m1 or m2:
print(max(m1,m2))
else:
print(-1)
``` | output | 1 | 78,849 | 7 | 157,699 |
Provide a correct Python 3 solution for this coding contest problem.
Arkady decided to buy roses for his girlfriend.
A flower shop has white, orange and red roses, and the total amount of them is n. Arkady thinks that red roses are not good together with white roses, so he won't buy a bouquet containing both red and white roses. Also, Arkady won't buy a bouquet where all roses have the same color.
Arkady wants to buy exactly k roses. For each rose in the shop he knows its beauty and color: the beauty of the i-th rose is bi, and its color is ci ('W' for a white rose, 'O' for an orange rose and 'R' for a red rose).
Compute the maximum possible total beauty of a bouquet of k roses satisfying the constraints above or determine that it is not possible to make such a bouquet.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of roses in the show and the number of roses Arkady wants to buy.
The second line contains a sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 10 000), where bi equals the beauty of the i-th rose.
The third line contains a string c of length n, consisting of uppercase English letters 'W', 'O' and 'R', where ci denotes the color of the i-th rose: 'W' denotes white, 'O' — orange, 'R' — red.
Output
Print the maximum possible total beauty of a bouquet of k roses that satisfies the constraints above. If it is not possible to make a single such bouquet, print -1.
Examples
Input
5 3
4 3 4 1 6
RROWW
Output
11
Input
5 2
10 20 14 20 11
RRRRR
Output
-1
Input
11 5
5 6 3 2 3 4 7 5 4 5 6
RWOORWORROW
Output
28
Note
In the first example Arkady wants to buy 3 roses. He can, for example, buy both red roses (their indices are 1 and 2, and their total beauty is 7) and the only orange rose (its index is 3, its beauty is 4). This way the total beauty of the bouquet is 11.
In the second example Arkady can not buy a bouquet because all roses have the same color. | instruction | 0 | 78,850 | 7 | 157,700 |
"Correct Solution:
```
n,k=map(int,input().split())
cost=list(map(int,input().split()))
s=input()
#exit(0)
a=[]
b=[]
c=[]
#print(n,k,cost)
kek1=0
kek2=0
kek3=0
for i in range(n):
if (s[i]==chr(ord("W"))):
kek1+=1
a.append(cost[i])
if (s[i]==chr(ord("O"))):
kek2+=1
b.append(cost[i])
if (s[i]==chr(ord("R"))):
kek3+=1
c.append(cost[i])
a=sorted(a)
a=list(reversed(a))
b=sorted(b)
b=list(reversed(b))
c=sorted(c)
c=list(reversed(c))
pref_a=[]
pref_b=[]
pref_c=[]
if (kek1!=0):
pref_a.append(a[0])
for i in range(1,len(a)):
pref_a.append(pref_a[len(pref_a)-1]+a[i])
if (kek2!=0):
pref_b.append(b[0])
for i in range(1,len(b)):
pref_b.append(pref_b[len(pref_b)-1]+b[i])
if (kek3!=0):
pref_c.append(c[0])
for i in range(1,len(c)):
pref_c.append(pref_c[len(pref_c)-1]+c[i])
inf=10**20
ans=-inf
for i in range(0,min(k-1,kek2)):
cur=pref_b[i]
left_k=k-(i+1)
res_a=-inf
res_c=-inf
if (kek1):
if (kek1>=left_k):
res_a=pref_a[left_k-1]
if (kek3):
if (kek3>=left_k):
res_c=pref_c[left_k-1]
cur+=max(res_a,res_c)
ans=max(ans,cur)
if (ans<-(10**18)):
ans=-1
print(ans)
``` | output | 1 | 78,850 | 7 | 157,701 |
Provide a correct Python 3 solution for this coding contest problem.
Arkady decided to buy roses for his girlfriend.
A flower shop has white, orange and red roses, and the total amount of them is n. Arkady thinks that red roses are not good together with white roses, so he won't buy a bouquet containing both red and white roses. Also, Arkady won't buy a bouquet where all roses have the same color.
Arkady wants to buy exactly k roses. For each rose in the shop he knows its beauty and color: the beauty of the i-th rose is bi, and its color is ci ('W' for a white rose, 'O' for an orange rose and 'R' for a red rose).
Compute the maximum possible total beauty of a bouquet of k roses satisfying the constraints above or determine that it is not possible to make such a bouquet.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of roses in the show and the number of roses Arkady wants to buy.
The second line contains a sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 10 000), where bi equals the beauty of the i-th rose.
The third line contains a string c of length n, consisting of uppercase English letters 'W', 'O' and 'R', where ci denotes the color of the i-th rose: 'W' denotes white, 'O' — orange, 'R' — red.
Output
Print the maximum possible total beauty of a bouquet of k roses that satisfies the constraints above. If it is not possible to make a single such bouquet, print -1.
Examples
Input
5 3
4 3 4 1 6
RROWW
Output
11
Input
5 2
10 20 14 20 11
RRRRR
Output
-1
Input
11 5
5 6 3 2 3 4 7 5 4 5 6
RWOORWORROW
Output
28
Note
In the first example Arkady wants to buy 3 roses. He can, for example, buy both red roses (their indices are 1 and 2, and their total beauty is 7) and the only orange rose (its index is 3, its beauty is 4). This way the total beauty of the bouquet is 11.
In the second example Arkady can not buy a bouquet because all roses have the same color. | instruction | 0 | 78,851 | 7 | 157,702 |
"Correct Solution:
```
n, k = map(int, input().split())
a = list(map(int, input().split()))
s = input()
if k == 1:
print(-1)
exit(0)
have = [[] for i in range(3)]
for i in range(n):
if s[i] == 'R':
have[0].append(a[i])
elif s[i] == 'O':
have[1].append(a[i])
else:
have[2].append(a[i])
for i in range(3):
have[i].sort(reverse=True)
ans1 = 0
p = 0
q = 0
was = [0, 0]
for i in range(k - 1):
if p == len(have[0]) and q == len(have[1]):
ans1 = -1
break
if p == len(have[0]):
ans1 += have[1][q]
q += 1
was[1] = 1
elif q == len(have[1]):
ans1 += have[0][p]
p += 1
was[0] = 1
elif(have[0][p] > have[1][q]):
ans1 += have[0][p]
p += 1
was[0] = 1
else:
ans1 += have[1][q]
q += 1
was[1] = 1
if ans1 != -1 and sum(was) == 2:
if p == len(have[0]) and q == len(have[1]):
ans = -1
elif p == len(have[0]):
ans1 += have[1][q]
elif q == len(have[1]):
ans1 += have[0][p]
else:
ans1 += max(have[0][p], have[1][q])
if ans1 != -1 and was[0] == 0:
if p != len(have[0]):
ans1 += have[0][p]
else:
ans1 = -1
if ans1 != -1 and was[1] == 0:
if q != len(have[1]):
ans1 += have[1][q]
else:
ans1 = -1
ans2 = 0
p = 0
q = 0
was = [0, 0]
for i in range(k - 1):
if p == len(have[2]) and q == len(have[1]):
ans2 = -1
break
if p == len(have[2]):
ans2 += have[1][q]
q += 1
was[1] = 1
elif q == len(have[1]):
ans2 += have[2][p]
p += 1
was[0] = 1
elif have[2][p] > have[1][q]:
ans2 += have[2][p]
p += 1
was[0] = 1
else:
ans2 += have[1][q]
q += 1
was[1] = 1
if ans2 != -1 and sum(was) == 2:
if p == len(have[2]) and q == len(have[1]):
ans = -1
elif p == len(have[2]):
ans2 += have[1][q]
elif q == len(have[1]):
ans2 += have[2][p]
else:
ans2 += max(have[2][p], have[1][q])
if ans2 != -1 and was[0] == 0:
if p != len(have[2]):
ans2 += have[2][p]
else:
ans2 = -1
if ans2 != -1 and was[1] == 0:
if q != len(have[1]):
ans2 += have[1][q]
else:
ans2 = -1
print(max(ans1, ans2))
``` | output | 1 | 78,851 | 7 | 157,703 |
Provide a correct Python 3 solution for this coding contest problem.
Arkady decided to buy roses for his girlfriend.
A flower shop has white, orange and red roses, and the total amount of them is n. Arkady thinks that red roses are not good together with white roses, so he won't buy a bouquet containing both red and white roses. Also, Arkady won't buy a bouquet where all roses have the same color.
Arkady wants to buy exactly k roses. For each rose in the shop he knows its beauty and color: the beauty of the i-th rose is bi, and its color is ci ('W' for a white rose, 'O' for an orange rose and 'R' for a red rose).
Compute the maximum possible total beauty of a bouquet of k roses satisfying the constraints above or determine that it is not possible to make such a bouquet.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of roses in the show and the number of roses Arkady wants to buy.
The second line contains a sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 10 000), where bi equals the beauty of the i-th rose.
The third line contains a string c of length n, consisting of uppercase English letters 'W', 'O' and 'R', where ci denotes the color of the i-th rose: 'W' denotes white, 'O' — orange, 'R' — red.
Output
Print the maximum possible total beauty of a bouquet of k roses that satisfies the constraints above. If it is not possible to make a single such bouquet, print -1.
Examples
Input
5 3
4 3 4 1 6
RROWW
Output
11
Input
5 2
10 20 14 20 11
RRRRR
Output
-1
Input
11 5
5 6 3 2 3 4 7 5 4 5 6
RWOORWORROW
Output
28
Note
In the first example Arkady wants to buy 3 roses. He can, for example, buy both red roses (their indices are 1 and 2, and their total beauty is 7) and the only orange rose (its index is 3, its beauty is 4). This way the total beauty of the bouquet is 11.
In the second example Arkady can not buy a bouquet because all roses have the same color. | instruction | 0 | 78,852 | 7 | 157,704 |
"Correct Solution:
```
n, k = map(int, input().split())
a = list(map(int, input().split()))
b = input()
r = []
o = []
w = []
for i in range(n):
if (b[i] == 'R'):
r.append(a[i])
elif (b[i] == 'O'):
o.append(a[i])
else:
w.append(a[i]);
r.sort()
o.sort()
w.sort()
r.reverse()
o.reverse()
w.reverse()
if k == 1 or (len(r) * len(o) == 0 and len(o) * len(w) == 0):
print('-1')
else:
r1 = 0
o1 = 0
ans1 = 0
o2 = 0
w2 = 0
ans2 = 0
if (len(r) + len(o) >= k and len(r) * len(o) != 0):
r1 = 1
o1 = 1
ans1 = r[0] + o[0]
while(r1 + o1 < k):
if (o1 >= len(o) or (r1 < len(r) and r[r1] > o[o1])):
ans1 += r[r1]
r1 += 1
else:
ans1 += o[o1]
o1 += 1
if (len(o) + len(w) >= k and len(o) * len(w) != 0):
o2 = 1
w2 = 1
ans2 = o[0] + w[0]
while(o2 + w2 < k):
if (o2 >= len(o) or (w2 < len(w) and w[w2] > o[o2])):
ans2 += w[w2]
w2 += 1
else:
ans2 += o[o2]
o2 += 1
if (max(ans1, ans2) == 0):
print("-1")
else:
print(max(ans1, ans2))
``` | output | 1 | 78,852 | 7 | 157,705 |
Provide a correct Python 3 solution for this coding contest problem.
Arkady decided to buy roses for his girlfriend.
A flower shop has white, orange and red roses, and the total amount of them is n. Arkady thinks that red roses are not good together with white roses, so he won't buy a bouquet containing both red and white roses. Also, Arkady won't buy a bouquet where all roses have the same color.
Arkady wants to buy exactly k roses. For each rose in the shop he knows its beauty and color: the beauty of the i-th rose is bi, and its color is ci ('W' for a white rose, 'O' for an orange rose and 'R' for a red rose).
Compute the maximum possible total beauty of a bouquet of k roses satisfying the constraints above or determine that it is not possible to make such a bouquet.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of roses in the show and the number of roses Arkady wants to buy.
The second line contains a sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 10 000), where bi equals the beauty of the i-th rose.
The third line contains a string c of length n, consisting of uppercase English letters 'W', 'O' and 'R', where ci denotes the color of the i-th rose: 'W' denotes white, 'O' — orange, 'R' — red.
Output
Print the maximum possible total beauty of a bouquet of k roses that satisfies the constraints above. If it is not possible to make a single such bouquet, print -1.
Examples
Input
5 3
4 3 4 1 6
RROWW
Output
11
Input
5 2
10 20 14 20 11
RRRRR
Output
-1
Input
11 5
5 6 3 2 3 4 7 5 4 5 6
RWOORWORROW
Output
28
Note
In the first example Arkady wants to buy 3 roses. He can, for example, buy both red roses (their indices are 1 and 2, and their total beauty is 7) and the only orange rose (its index is 3, its beauty is 4). This way the total beauty of the bouquet is 11.
In the second example Arkady can not buy a bouquet because all roses have the same color. | instruction | 0 | 78,853 | 7 | 157,706 |
"Correct Solution:
```
n,k=map(int,input().split())
b=list(map(int,input().split()))
s=input()
r=[]
w=[]
o=[]
for i in range(n):
if s[i]=='W':
w.append(b[i])
elif s[i]=='O':
o.append(b[i])
else:
r.append(b[i])
if k==1:
print(-1)
raise SystemExit
r=sorted(r)
w=sorted(w)
o=sorted(o)
r=r[::-1]
w=w[::-1]
o=o[::-1]
s1=0
s2=0
if len(o)!=0 and len(w)!=0 and len(o)+len(w)>=k:
s1+=w[0]+o[0]
j=2
i=1
e=1
while j<k:
if i==len(o) or (e<len(w) and w[e]>o[i]):
s1+=w[e]
e+=1
else:
s1+=o[i]
i+=1
j+=1
if len(o)!=0 and len(r)!=0 and len(o)+len(r)>=k:
s2+=o[0]+r[0]
j=2
i=1
e=1
while j<k:
if i==len(o) or (e<len(r) and r[e]>o[i]):
s2+=r[e]
e+=1
else:
s2+=o[i]
i+=1
j+=1
if max(s1,s2)==0:
print(-1)
else:
print(max(s1,s2))
``` | output | 1 | 78,853 | 7 | 157,707 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Arkady decided to buy roses for his girlfriend.
A flower shop has white, orange and red roses, and the total amount of them is n. Arkady thinks that red roses are not good together with white roses, so he won't buy a bouquet containing both red and white roses. Also, Arkady won't buy a bouquet where all roses have the same color.
Arkady wants to buy exactly k roses. For each rose in the shop he knows its beauty and color: the beauty of the i-th rose is bi, and its color is ci ('W' for a white rose, 'O' for an orange rose and 'R' for a red rose).
Compute the maximum possible total beauty of a bouquet of k roses satisfying the constraints above or determine that it is not possible to make such a bouquet.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of roses in the show and the number of roses Arkady wants to buy.
The second line contains a sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 10 000), where bi equals the beauty of the i-th rose.
The third line contains a string c of length n, consisting of uppercase English letters 'W', 'O' and 'R', where ci denotes the color of the i-th rose: 'W' denotes white, 'O' — orange, 'R' — red.
Output
Print the maximum possible total beauty of a bouquet of k roses that satisfies the constraints above. If it is not possible to make a single such bouquet, print -1.
Examples
Input
5 3
4 3 4 1 6
RROWW
Output
11
Input
5 2
10 20 14 20 11
RRRRR
Output
-1
Input
11 5
5 6 3 2 3 4 7 5 4 5 6
RWOORWORROW
Output
28
Note
In the first example Arkady wants to buy 3 roses. He can, for example, buy both red roses (their indices are 1 and 2, and their total beauty is 7) and the only orange rose (its index is 3, its beauty is 4). This way the total beauty of the bouquet is 11.
In the second example Arkady can not buy a bouquet because all roses have the same color.
Submitted Solution:
```
N = 10000
def main():
n, k = map(int, input().split())
b = list(map(int, input().split()))
c = input()
k -= 1
if (k == 0):
return -1
flowers = [[0 for i in range(N + 1)] for i in range(3)]
RO = [0 for i in range(N + 1)]
OW = [0 for i in range(N + 1)]
orange = -1
for i in range(n):
if (c[i] == 'R'):
RO[b[i]] += 1
if (c[i] == 'O'):
orange = max(orange, b[i])
RO[b[i]] += 1
OW[b[i]] += 1
if (c[i] == 'W'):
OW[b[i]] += 1
RO[orange] -= 1
OW[orange] -= 1
if (orange == -1):
return -1
ans = -1
ans1 = 0
k1 = k
for i in range(N, -1, -1):
ans1 += min(k, RO[i]) * i
k1 -= RO[i]
if (k1 <= 0):
k1 = 0
break
if (k1 == 0):
ans = max(ans, ans1 + orange)
ans2 = 0
k2 = k
for i in range(N, -1, -1):
ans2 += min(k, OW[i]) * i
k2 -= OW[i]
if (k2 <= 0):
k2 = 0
break
if (k2 == 0):
ans = max(ans, ans2 + orange)
return ans
print(main())
``` | instruction | 0 | 78,854 | 7 | 157,708 |
No | output | 1 | 78,854 | 7 | 157,709 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Arkady decided to buy roses for his girlfriend.
A flower shop has white, orange and red roses, and the total amount of them is n. Arkady thinks that red roses are not good together with white roses, so he won't buy a bouquet containing both red and white roses. Also, Arkady won't buy a bouquet where all roses have the same color.
Arkady wants to buy exactly k roses. For each rose in the shop he knows its beauty and color: the beauty of the i-th rose is bi, and its color is ci ('W' for a white rose, 'O' for an orange rose and 'R' for a red rose).
Compute the maximum possible total beauty of a bouquet of k roses satisfying the constraints above or determine that it is not possible to make such a bouquet.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of roses in the show and the number of roses Arkady wants to buy.
The second line contains a sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 10 000), where bi equals the beauty of the i-th rose.
The third line contains a string c of length n, consisting of uppercase English letters 'W', 'O' and 'R', where ci denotes the color of the i-th rose: 'W' denotes white, 'O' — orange, 'R' — red.
Output
Print the maximum possible total beauty of a bouquet of k roses that satisfies the constraints above. If it is not possible to make a single such bouquet, print -1.
Examples
Input
5 3
4 3 4 1 6
RROWW
Output
11
Input
5 2
10 20 14 20 11
RRRRR
Output
-1
Input
11 5
5 6 3 2 3 4 7 5 4 5 6
RWOORWORROW
Output
28
Note
In the first example Arkady wants to buy 3 roses. He can, for example, buy both red roses (their indices are 1 and 2, and their total beauty is 7) and the only orange rose (its index is 3, its beauty is 4). This way the total beauty of the bouquet is 11.
In the second example Arkady can not buy a bouquet because all roses have the same color.
Submitted Solution:
```
n, k = map(int, input().split())
a = list(map(int, input().split()))
s = input()
if n == 1:
print(-1)
exit(0)
have = [[] for i in range(3)]
for i in range(n):
if s[i] == 'R':
have[0].append(a[i])
elif s[i] == 'O':
have[1].append(a[i])
else:
have[2].append(a[i])
for i in range(3):
have[i].sort(reverse=True)
ans1 = 0
p = 0
q = 0
was = [0, 0]
for i in range(k - 1):
if p == len(have[0]) and q == len(have[1]):
ans1 = -1
break
if p == len(have[0]):
ans1 += have[1][q]
q += 1
was[1] = 1
elif q == len(have[1]):
ans1 += have[0][p]
p += 1
was[0] = 1
elif(have[0][p] > have[1][q]):
ans1 += have[0][p]
p += 1
was[0] = 1
else:
ans1 += have[1][q]
q += 1
was[1] = 1
if ans1 != -1 and sum(was) == 2:
if p == len(have[0]) and q == len(have[1]):
ans = -1
elif p == len(have[0]):
ans1 += have[1][q]
elif q == len(have[1]):
ans1 += have[0][p]
else:
ans1 += max(have[0][p], have[1][q])
if ans1 != -1 and was[0] == 0:
if p != len(have[0]):
ans1 += have[0][p]
else:
ans1 = -1
if ans1 != -1 and was[1] == 0:
if q != len(have[1]):
ans1 += have[1][q]
else:
ans1 = -1
ans2 = 0
p = 0
q = 0
was = [0, 0]
for i in range(k - 1):
if p == len(have[2]) and q == len(have[1]):
ans2 = -1
break
if p == len(have[2]):
ans2 += have[1][q]
q += 1
was[1] = 1
elif q == len(have[1]):
ans2 += have[2][p]
p += 1
was[0] = 1
elif have[2][p] > have[1][q]:
ans2 += have[2][p]
p += 1
was[0] = 1
else:
ans2 += have[1][q]
q += 1
was[1] = 1
if ans2 != -1 and sum(was) == 2:
if p == len(have[2]) and q == len(have[1]):
ans = -1
elif p == len(have[2]):
ans2 += have[1][q]
elif q == len(have[1]):
ans2 += have[2][p]
else:
ans2 += max(have[2][p], have[1][q])
if ans2 != -1 and was[0] == 0:
if p != len(have[2]):
ans2 += have[2][p]
else:
ans2 = -1
if ans2 != -1 and was[1] == 0:
if q != len(have[1]):
ans2 += have[1][q]
else:
ans2 = -1
print(max(ans1, ans2))
``` | instruction | 0 | 78,855 | 7 | 157,710 |
No | output | 1 | 78,855 | 7 | 157,711 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Arkady decided to buy roses for his girlfriend.
A flower shop has white, orange and red roses, and the total amount of them is n. Arkady thinks that red roses are not good together with white roses, so he won't buy a bouquet containing both red and white roses. Also, Arkady won't buy a bouquet where all roses have the same color.
Arkady wants to buy exactly k roses. For each rose in the shop he knows its beauty and color: the beauty of the i-th rose is bi, and its color is ci ('W' for a white rose, 'O' for an orange rose and 'R' for a red rose).
Compute the maximum possible total beauty of a bouquet of k roses satisfying the constraints above or determine that it is not possible to make such a bouquet.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of roses in the show and the number of roses Arkady wants to buy.
The second line contains a sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 10 000), where bi equals the beauty of the i-th rose.
The third line contains a string c of length n, consisting of uppercase English letters 'W', 'O' and 'R', where ci denotes the color of the i-th rose: 'W' denotes white, 'O' — orange, 'R' — red.
Output
Print the maximum possible total beauty of a bouquet of k roses that satisfies the constraints above. If it is not possible to make a single such bouquet, print -1.
Examples
Input
5 3
4 3 4 1 6
RROWW
Output
11
Input
5 2
10 20 14 20 11
RRRRR
Output
-1
Input
11 5
5 6 3 2 3 4 7 5 4 5 6
RWOORWORROW
Output
28
Note
In the first example Arkady wants to buy 3 roses. He can, for example, buy both red roses (their indices are 1 and 2, and their total beauty is 7) and the only orange rose (its index is 3, its beauty is 4). This way the total beauty of the bouquet is 11.
In the second example Arkady can not buy a bouquet because all roses have the same color.
Submitted Solution:
```
n, k = map(int, input().split())
a = [int(i) for i in input().split()]
w = []
r = []
o = []
s = input()
for i in range(n):
if s[i] == 'O':
o.append(a[i])
if s[i] == 'R':
r.append(a[i])
if s[i] == 'W':
w.append(a[i])
o.sort(), w.sort(), r.sort()
w = w[::-1]
o = o[::-1]
r = o[::-1]
ans = -1
i = 0
j = 0
cntf = 0
cnts = 0
nw = 0
while (cntf + cnts) < k and (i < len(w) or j < len(o)):
if(i >= len(w)):
nw += o[j]
j += 1
cnts += 1
elif(j >= len(o)):
nw += w[i]
i += 1
cntf += 1
else:
if(w[i] > o[j]):
nw += w[i]
i += 1
cntf += 1
else:
nw += o[j]
j += 1
cnts += 1
if(cntf + cnts == k - 1):
if(cntf == 0 and len(w) != 0):
nw += w[i]
cntf += 1
elif(cnts == 0 and len(o) != 0):
nw += o[j]
cnts += 1
if(cntf + cnts == k and cntf != 0 and cnts != 0):
ans = max(ans, nw)
i = 0
j = 0
cntf = 0
cnts = 0
nw = 0
while (cntf + cnts < k) and (i < len(r) or j < len(o)):
if(i >= len(r)):
nw += o[j]
j += 1
cnts += 1
elif(j >= len(o)):
nw += r[i]
i += 1
cntf += 1
else:
if(r[i] > o[j]):
nw += r[i]
i += 1
cntf += 1
else:
nw += o[j]
j += 1
cnts += 1
if(cntf + cnts == k - 1):
if(cntf == 0 and len(r) != 0):
nw += r[i]
cntf += 1
elif(cnts == 0 and len(o) != 0):
nw += o[j]
cnts += 1
if(cntf + cnts == k and cntf != 0 and cnts != 0):
ans = max(ans, nw)
print(ans)
``` | instruction | 0 | 78,856 | 7 | 157,712 |
No | output | 1 | 78,856 | 7 | 157,713 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Arkady decided to buy roses for his girlfriend.
A flower shop has white, orange and red roses, and the total amount of them is n. Arkady thinks that red roses are not good together with white roses, so he won't buy a bouquet containing both red and white roses. Also, Arkady won't buy a bouquet where all roses have the same color.
Arkady wants to buy exactly k roses. For each rose in the shop he knows its beauty and color: the beauty of the i-th rose is bi, and its color is ci ('W' for a white rose, 'O' for an orange rose and 'R' for a red rose).
Compute the maximum possible total beauty of a bouquet of k roses satisfying the constraints above or determine that it is not possible to make such a bouquet.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of roses in the show and the number of roses Arkady wants to buy.
The second line contains a sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 10 000), where bi equals the beauty of the i-th rose.
The third line contains a string c of length n, consisting of uppercase English letters 'W', 'O' and 'R', where ci denotes the color of the i-th rose: 'W' denotes white, 'O' — orange, 'R' — red.
Output
Print the maximum possible total beauty of a bouquet of k roses that satisfies the constraints above. If it is not possible to make a single such bouquet, print -1.
Examples
Input
5 3
4 3 4 1 6
RROWW
Output
11
Input
5 2
10 20 14 20 11
RRRRR
Output
-1
Input
11 5
5 6 3 2 3 4 7 5 4 5 6
RWOORWORROW
Output
28
Note
In the first example Arkady wants to buy 3 roses. He can, for example, buy both red roses (their indices are 1 and 2, and their total beauty is 7) and the only orange rose (its index is 3, its beauty is 4). This way the total beauty of the bouquet is 11.
In the second example Arkady can not buy a bouquet because all roses have the same color.
Submitted Solution:
```
n, k = map(int, input().split())
a = list(map(int, input().split()))
s = input()
have = [[] for i in range(3)]
for i in range(n):
if s[i] == 'R':
have[0].append(a[i])
elif s[i] == 'O':
have[1].append(a[i])
else:
have[2].append(a[i])
for i in range(3):
have[i].sort(reverse=True)
ans1 = 0
p = 0
q = 0
was = [0, 0]
for i in range(k - 1):
if p == len(have[0]) and q == len(have[1]):
ans1 = -1
break
if p == len(have[0]):
ans1 += have[1][q]
q += 1
was[1] = 1
elif q == len(have[1]):
ans1 += have[0][p]
p += 1
was[0] = 1
elif(have[0][p] > have[1][q]):
ans1 += have[0][p]
p += 1
was[0] = 1
else:
ans1 += have[1][q]
q += 1
was[1] = 1
if ans1 != -1 and sum(was) == 2:
if p == len(have[0]) and q == len(have[1]):
ans = -1
elif p == len(have[0]):
ans1 += have[1][q]
elif q == len(have[1]):
ans1 += have[0][p]
else:
ans1 += max(have[0][p], have[1][q])
if ans1 != -1 and was[0] == 0:
if p != len(have[0]):
ans1 += have[0][p]
else:
ans1 = -1
if ans1 != -1 and was[1] == 0:
if q != len(have[1]):
ans1 += have[1][q]
else:
ans1 = -1
ans2 = 0
p = 0
q = 0
was = [0, 0]
for i in range(k - 1):
if p == len(have[2]) and q == len(have[1]):
ans2 = -1
break
if p == len(have[2]):
ans2 += have[1][q]
q += 1
was[1] = 1
elif q == len(have[1]):
ans2 += have[2][p]
p += 1
was[0] = 1
elif have[2][p] > have[1][q]:
ans2 += have[2][p]
p += 1
was[0] = 1
else:
ans2 += have[1][q]
q += 1
was[1] = 1
if ans2 != -1 and sum(was) == 2:
if p == len(have[2]) and q == len(have[1]):
ans = -1
elif p == len(have[2]):
ans2 += have[1][q]
elif q == len(have[1]):
ans2 += have[2][p]
else:
ans2 += max(have[2][p], have[1][q])
if ans2 != -1 and was[0] == 0:
if p != len(have[2]):
ans2 += have[2][p]
else:
ans2 = -1
if ans2 != -1 and was[1] == 0:
if q != len(have[1]):
ans2 += have[1][q]
else:
ans2 = -1
print(max(ans1, ans2))
``` | instruction | 0 | 78,857 | 7 | 157,714 |
No | output | 1 | 78,857 | 7 | 157,715 |
Provide a correct Python 3 solution for this coding contest problem.
The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them.
The requirements for this software (game) are as follows.
* The screen has a 2D grid of X columns x Y rows.
* The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B).
* There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color.
* When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color.
It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps.
As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time.
<image>
input
Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format:
X Y
c1,1 c2,1 ... cX,1
c1,2 c2,2 ... cX,2
::
c1, Y c2, Y ... cX, Y
The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks.
output
Outputs the minimum number of button operations on one line for each dataset.
Example
Input
3 3
R G B
G G G
G B B
2 4
R G
G G
R B
B R
4 3
G G B R
G R R G
B G G R
0 0
Output
2
4
4 | instruction | 0 | 79,041 | 7 | 158,082 |
"Correct Solution:
```
def paintout_graph(s, g, color):
cnt, pre_color = 0, s[0]
que = [0]
for pos in que:
if s[pos] == pre_color:
s[pos] = color
cnt +=1
que.extend(g[pos])
return cnt
def bfs(s, graph):
que = deque([(s,0,0)])
while True:
s,pre_cnt,depth = que.popleft()
pre_color = s[0]
colors = ['R','G','B']
colors.remove(pre_color)
for si, color in zip((s,s[:]),colors):
cnt = paintout_graph(si,graph,color)
if cnt == len(si):
return depth
if cnt == pre_cnt:
break
que.append((si,cnt,depth + 1))
from collections import deque
def paintout_sq(s, color,w,h,x,y):
neighbor, pre_color = set(), s[y*w+x]
que = deque([(x, y)])
while len(que):
x, y = que.pop()
pos = y * w + x
if s[pos] == pre_color:
s[pos] = color
if 0 < x:que.append((x-1,y))
if 0 < y:que.append((x,y-1))
if x + 1 < w:que.append((x+1,y))
if y + 1 < h:que.append((x,y+1))
elif s[pos] != color and isinstance(s[pos], int):
neighbor.update([s[pos]])
return neighbor
import sys
f = sys.stdin
while True:
w, h = map(int, f.readline().split())
if w == h == 0:
break
s = [f.readline().split() for _ in range(h)]
s = [y for x in s for y in x]
p = []
graph = {}
for y in range(h):
for x in range(w):
pos = y*w+x
if s[pos] in ('R','G','B'):
k = len(p)
p.append(s[pos])
neighbor = paintout_sq(s,k,w,h,x,y)
neighbor = list(neighbor)
try:
graph[k].expand(neighbor)
except KeyError:
graph[k] = neighbor
for ni in neighbor:
try:
graph[ni].append(k)
except KeyError:
graph[ni] = [k]
print(bfs(p,graph))
``` | output | 1 | 79,041 | 7 | 158,083 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them.
The requirements for this software (game) are as follows.
* The screen has a 2D grid of X columns x Y rows.
* The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B).
* There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color.
* When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color.
It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps.
As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time.
<image>
input
Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format:
X Y
c1,1 c2,1 ... cX,1
c1,2 c2,2 ... cX,2
::
c1, Y c2, Y ... cX, Y
The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks.
output
Outputs the minimum number of button operations on one line for each dataset.
Example
Input
3 3
R G B
G G G
G B B
2 4
R G
G G
R B
B R
4 3
G G B R
G R R G
B G G R
0 0
Output
2
4
4
Submitted Solution:
```
from collections import deque
def paintout(s, color,w,h):
cnt, pre_color = 0, s[0]
que = deque([(0, 0)])
while len(que):
x, y = que.pop()
pos = y * w + x
if 0 <= x < w and 0 <= y < h and s[pos] == pre_color:
s[pos] = color
cnt +=1
que.extend(((x-1,y),(x,y-1),(x+1,y),(x,y+1)))
return cnt
def dfs(depth, s, pre_cnt, w, h):
global good
if good <= depth:
return float('inf')
ret = []
pre_color = s[0]
colors = [0,1,2]
colors.remove(pre_color)
for color in colors:
p = s[:]
cnt = paintout(p,color,w,h)
if cnt == h * w:
good = min(good,depth)
return good
if cnt == pre_cnt:
return float('inf')
ret.append(dfs(depth + 1, p, cnt,w,h))
return min(ret)
import sys
import string
import operator
from collections import Counter
f = sys.stdin
while True:
good = float('inf')
x, y = map(int, f.readline().split())
if x == y == 0:
break
s = [f.readline().split() for _ in range(y)]
dict = {'R':0,'G':1,'B':2}
for si in s:
for j in range(len(si)):
si[j] = dict[si[j]]
s = [y for x in s for y in x]
print(dfs(0, s, 0, x, y))
``` | instruction | 0 | 79,042 | 7 | 158,084 |
No | output | 1 | 79,042 | 7 | 158,085 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them.
The requirements for this software (game) are as follows.
* The screen has a 2D grid of X columns x Y rows.
* The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B).
* There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color.
* When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color.
It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps.
As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time.
<image>
input
Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format:
X Y
c1,1 c2,1 ... cX,1
c1,2 c2,2 ... cX,2
::
c1, Y c2, Y ... cX, Y
The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks.
output
Outputs the minimum number of button operations on one line for each dataset.
Example
Input
3 3
R G B
G G G
G B B
2 4
R G
G G
R B
B R
4 3
G G B R
G R R G
B G G R
0 0
Output
2
4
4
Submitted Solution:
```
from collections import deque
def paintout(s, color,w,h):
cnt, pre_color = 0, s[0]
que = deque([(0, 0)])
while len(que):
x, y = que.pop()
pos = y * w + x
if 0 <= x < w and 0 <= y < h and s[pos] == pre_color:
s[pos] = color
cnt +=1
que.extend(((x-1,y),(x,y-1),(x+1,y),(x,y+1)))
return cnt
def dfs(depth, s, pre_cnt, w, h):
ret = []
pre_color = s[0]
colors = [0,1,2]
colors.remove(pre_color)
for color in colors:
p = s[:]
cnt = paintout(p,color,w,h)
if cnt == h * w:
return depth
if cnt == pre_cnt:
return float('inf')
ret.append(dfs(depth + 1, p, cnt,w,h))
return min(ret)
import sys
import string
import operator
from collections import Counter
f = sys.stdin
while True:
x, y = map(int, f.readline().split())
if x == y == 0:
break
s = [f.readline().split() for _ in range(y)]
dict = {'R':0,'G':1,'B':2}
for si in s:
for j in range(len(si)):
si[j] = dict[si[j]]
s = [y for x in s for y in x]
print(dfs(0, s, 0, x, y))
``` | instruction | 0 | 79,043 | 7 | 158,086 |
No | output | 1 | 79,043 | 7 | 158,087 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them.
The requirements for this software (game) are as follows.
* The screen has a 2D grid of X columns x Y rows.
* The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B).
* There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color.
* When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color.
It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps.
As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time.
<image>
input
Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format:
X Y
c1,1 c2,1 ... cX,1
c1,2 c2,2 ... cX,2
::
c1, Y c2, Y ... cX, Y
The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks.
output
Outputs the minimum number of button operations on one line for each dataset.
Example
Input
3 3
R G B
G G G
G B B
2 4
R G
G G
R B
B R
4 3
G G B R
G R R G
B G G R
0 0
Output
2
4
4
Submitted Solution:
```
from collections import deque
def paintout(s, color):
cnt, pre_color, h, w = 0, s[0][0], len(s), len(s[0])
que = deque([(0, 0)])
while len(que):
x, y = que.pop()
if 0 <= x < w and 0 <= y < h and s[y][x] == pre_color:
s[y][x] = color
cnt +=1
que.extend(((x-1,y),(x,y-1),(x+1,y),(x,y+1)))
return cnt
from copy import deepcopy
def dfs(depth, s, pre_cnt):
ret = []
pre_color, h, w = s[0][0], len(s), len(s[0])
colors = [0,1,2]
colors.remove(pre_color)
for color in colors:
p = deepcopy(s)
cnt = paintout(p,color)
if cnt == h * w:
return 0
if cnt == pre_cnt:
return float('inf')
ret.append(dfs(depth + 1, p, cnt))
return min(ret) + 1
import sys
import string
import operator
from collections import Counter
f = sys.stdin
while True:
x, y = map(int, f.readline().split())
if x == y == 0:
break
s = [f.readline().split() for _ in range(y)]
dict = {'R':0,'G':1,'B':2}
for si in s:
for j in range(len(si)):
si[j] = dict[si[j]]
print(dfs(0, s, 0))
``` | instruction | 0 | 79,044 | 7 | 158,088 |
No | output | 1 | 79,044 | 7 | 158,089 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them.
The requirements for this software (game) are as follows.
* The screen has a 2D grid of X columns x Y rows.
* The cells of the grid are painted in one of three colors: red (R), green (G), and brown (B).
* There are buttons R, G, B to change the color of the cell, and when this button is pressed, the upper left (0,0) cell will be changed to that color.
* When the color of the top left cell is changed, all adjacent cells painted in the same color as the original color of that cell will change to the specified color. That is, all cells that are connected by cells with the same original color will be changed to the specified color.
It is a game that fills the grid in this way and finally makes the entire grid one color. A high score will be given if you solve it with a few steps.
As a programmer at AZ, you have decided to develop a part of the logic of this game. First of all, in order to calculate this maximum score, I decided to make a program to find out how many times the selection button should be operated to make the grid one color if the game is solved in the shortest time.
<image>
input
Given multiple datasets. The end of the input is indicated by two zeros. Each dataset is given in the following format:
X Y
c1,1 c2,1 ... cX,1
c1,2 c2,2 ... cX,2
::
c1, Y c2, Y ... cX, Y
The first row gives the grid columns and row sizes X, Y (2 ≤ X, Y ≤ 10). The following Y-row is given the letters ci, j, which represent the color of the cells in the i-th and j-th rows, separated by blanks.
output
Outputs the minimum number of button operations on one line for each dataset.
Example
Input
3 3
R G B
G G G
G B B
2 4
R G
G G
R B
B R
4 3
G G B R
G R R G
B G G R
0 0
Output
2
4
4
Submitted Solution:
```
from collections import deque
def paintout(s, color,w,h):
cnt, pre_color = 0, s[0]
que = deque([(0, 0)])
while len(que):
x, y = que.pop()
pos = y * w + x
if s[pos] == pre_color:
s[pos] = color
cnt +=1
if 0 < x:
que.append((x-1,y))
if 0 < y:
que.append((x,y-1))
if x + 1 < w:
que.append((x+1,y))
if y + 1 < h:
que.append((x,y+1))
return cnt
def dfs(depth, s, pre_cnt, w, h):
global good
if good <= depth:
return float('inf')
ret = []
pre_color = s[0]
colors = [0,1,2]
colors.remove(pre_color)
for color in colors:
p = s[:]
cnt = paintout(p,color,w,h)
if cnt == pre_cnt:
return float('inf')
if cnt == h * w:
good = min(good,depth)
return good
ret.append(dfs(depth + 1, p, cnt,w,h))
return min(ret)
import sys
f = sys.stdin
while True:
good = float('inf')
x, y = map(int, f.readline().split())
if x == y == 0:
break
s = [f.readline().split() for _ in range(y)]
dict = {'R':0,'G':1,'B':2}
for si in s:
for j in range(len(si)):
si[j] = dict[si[j]]
s = [y for x in s for y in x]
print(dfs(0, s, 0, x, y))
``` | instruction | 0 | 79,045 | 7 | 158,090 |
No | output | 1 | 79,045 | 7 | 158,091 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya writes his own library for building graphical user interface. Vasya called his creation VTK (VasyaToolKit). One of the interesting aspects of this library is that widgets are packed in each other.
A widget is some element of graphical interface. Each widget has width and height, and occupies some rectangle on the screen. Any widget in Vasya's library is of type Widget. For simplicity we will identify the widget and its type.
Types HBox and VBox are derivatives of type Widget, so they also are types Widget. Widgets HBox and VBox are special. They can store other widgets. Both those widgets can use the pack() method to pack directly in itself some other widget. Widgets of types HBox and VBox can store several other widgets, even several equal widgets — they will simply appear several times. As a result of using the method pack() only the link to the packed widget is saved, that is when the packed widget is changed, its image in the widget, into which it is packed, will also change.
We shall assume that the widget a is packed in the widget b if there exists a chain of widgets a = c1, c2, ..., ck = b, k ≥ 2, for which ci is packed directly to ci + 1 for any 1 ≤ i < k. In Vasya's library the situation when the widget a is packed in the widget a (that is, in itself) is not allowed. If you try to pack the widgets into each other in this manner immediately results in an error.
Also, the widgets HBox and VBox have parameters border and spacing, which are determined by the methods set_border() and set_spacing() respectively. By default both of these options equal 0.
<image>
The picture above shows how the widgets are packed into HBox and VBox. At that HBox and VBox automatically change their size depending on the size of packed widgets. As for HBox and VBox, they only differ in that in HBox the widgets are packed horizontally and in VBox — vertically. The parameter spacing sets the distance between adjacent widgets, and border — a frame around all packed widgets of the desired width. Packed widgets are placed exactly in the order in which the pack() method was called for them. If within HBox or VBox there are no packed widgets, their sizes are equal to 0 × 0, regardless of the options border and spacing.
The construction of all the widgets is performed using a scripting language VasyaScript. The description of the language can be found in the input data.
For the final verification of the code Vasya asks you to write a program that calculates the sizes of all the widgets on the source code in the language of VasyaScript.
Input
The first line contains an integer n — the number of instructions (1 ≤ n ≤ 100). Next n lines contain instructions in the language VasyaScript — one instruction per line. There is a list of possible instructions below.
* "Widget [name]([x],[y])" — create a new widget [name] of the type Widget possessing the width of [x] units and the height of [y] units.
* "HBox [name]" — create a new widget [name] of the type HBox.
* "VBox [name]" — create a new widget [name] of the type VBox.
* "[name1].pack([name2])" — pack the widget [name2] in the widget [name1]. At that, the widget [name1] must be of type HBox or VBox.
* "[name].set_border([x])" — set for a widget [name] the border parameter to [x] units. The widget [name] must be of type HBox or VBox.
* "[name].set_spacing([x])" — set for a widget [name] the spacing parameter to [x] units. The widget [name] must be of type HBox or VBox.
All instructions are written without spaces at the beginning and at the end of the string. The words inside the instruction are separated by exactly one space. There are no spaces directly before the numbers and directly after them.
The case matters, for example, "wiDget x" is not a correct instruction. The case of the letters is correct in the input data.
All names of the widgets consist of lowercase Latin letters and has the length from 1 to 10 characters inclusive. The names of all widgets are pairwise different. All numbers in the script are integers from 0 to 100 inclusive
It is guaranteed that the above-given script is correct, that is that all the operations with the widgets take place after the widgets are created and no widget is packed in itself. It is guaranteed that the script creates at least one widget.
Output
For each widget print on a single line its name, width and height, separated by spaces. The lines must be ordered lexicographically by a widget's name.
Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout stream (also you may use %I64d specificator)
Examples
Input
12
Widget me(50,40)
VBox grandpa
HBox father
grandpa.pack(father)
father.pack(me)
grandpa.set_border(10)
grandpa.set_spacing(20)
Widget brother(30,60)
father.pack(brother)
Widget friend(20,60)
Widget uncle(100,20)
grandpa.pack(uncle)
Output
brother 30 60
father 80 60
friend 20 60
grandpa 120 120
me 50 40
uncle 100 20
Input
15
Widget pack(10,10)
HBox dummy
HBox x
VBox y
y.pack(dummy)
y.set_border(5)
y.set_spacing(55)
dummy.set_border(10)
dummy.set_spacing(20)
x.set_border(10)
x.set_spacing(10)
x.pack(pack)
x.pack(dummy)
x.pack(pack)
x.set_border(0)
Output
dummy 0 0
pack 10 10
x 40 10
y 10 10
Note
In the first sample the widgets are arranged as follows:
<image> | instruction | 0 | 79,648 | 7 | 159,296 |
Tags: dp, expression parsing, graphs, implementation
Correct Solution:
```
import sys
from array import array # noqa: F401
import re
def input():
return sys.stdin.buffer.readline().decode('utf-8')
class Widget(object):
def __init__(self, x, y):
self.x = x
self.y = y
class Box(object):
def __init__(self):
self.children = []
self.border = 0
self.spacing = 0
self._x = -1
self._y = -1
def set_border(self, size):
self.border = size
def set_spacing(self, size):
self.spacing = size
def pack(self, widget):
self.children.append(widget)
@property
def x(self):
if self._x == -1:
self._x = (max(child.x for child in self.children) + self.border * 2
if self.children else 0)
return self._x
@property
def y(self):
if self._y == -1:
self._y = (max(child.y for child in self.children) + self.border * 2
if self.children else 0)
return self._y
class HBox(Box):
@property
def x(self):
if self._x == -1:
if not self.children:
return 0
a = [child.x for child in self.children]
self._x = self.border * 2 + sum(a) + self.spacing * (len(a) - 1)
return self._x
class VBox(Box):
@property
def y(self):
if self._y == -1:
if not self.children:
return 0
a = [child.y for child in self.children]
self._y = self.border * 2 + sum(a) + self.spacing * (len(a) - 1)
return self._y
if __name__ == '__main__':
n = int(input())
namespace = {}
pattern = re.compile(r'([^(]+?)\(([^)]+?)\)')
def parse(s):
return re.search(pattern, s).groups()
for _ in range(n):
command = input().split()
if command[0] == 'Widget':
name, args = parse(command[1])
namespace[name] = Widget(*tuple(map(int, args.split(','))))
elif command[0] == 'VBox':
namespace[command[1]] = VBox()
elif command[0] == 'HBox':
namespace[command[1]] = HBox()
else:
name, method = command[0].split('.')
method, args = parse(method)
if method == 'set_border':
namespace[name].set_border(int(args))
elif method == 'set_spacing':
namespace[name].set_spacing(int(args))
elif method == 'pack':
namespace[name].pack(namespace[args])
for name in sorted(namespace.keys()):
print(f'{name} {namespace[name].x} {namespace[name].y}')
``` | output | 1 | 79,648 | 7 | 159,297 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n rows and m columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side.
Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo 10^9 + 7.
Input
The only line contains two integers n and m (1 ≤ n, m ≤ 100 000), the number of rows and the number of columns of the field.
Output
Print one integer, the number of random pictures modulo 10^9 + 7.
Example
Input
2 3
Output
8
Note
The picture below shows all possible random pictures of size 2 by 3.
<image> | instruction | 0 | 80,023 | 7 | 160,046 |
Tags: combinatorics, dp, math
Correct Solution:
```
mod = 10 ** 9 + 7
def getAns(maxSide):
if maxSide == 1:
return 2
if maxSide == 2:
return 4
dpSide = [0] * maxSide
for i in range(len(dpSide)):
dpSide[i] = [0, 0]
dpSide[0] = [1, 1]
dpSide[1] = [2, 2]
f = True
for i in range(1, len(dpSide) - 1):
dpSide[i + 1][0] += dpSide[i][1]
dpSide[i + 1][1] += dpSide[i][0]
dpSide[i + 1][1] += dpSide[i - 1][0]
dpSide[i + 1][0] += dpSide[i - 1][1]
dpSide[i + 1][0] %= mod
dpSide[i + 1][1] %= mod
return sum(dpSide[maxSide - 1]) % mod
n, m = map(int, input().split())
print((getAns(n) + getAns(m) - 2) % mod)
``` | output | 1 | 80,023 | 7 | 160,047 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n rows and m columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side.
Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo 10^9 + 7.
Input
The only line contains two integers n and m (1 ≤ n, m ≤ 100 000), the number of rows and the number of columns of the field.
Output
Print one integer, the number of random pictures modulo 10^9 + 7.
Example
Input
2 3
Output
8
Note
The picture below shows all possible random pictures of size 2 by 3.
<image> | instruction | 0 | 80,024 | 7 | 160,048 |
Tags: combinatorics, dp, math
Correct Solution:
```
if __name__ == '__main__':
arr = [int(0)] * 100005
n, m = map(int, input().strip().split())
N = max(n, m)
arr[1], arr[2] = 2, 4
Mod = 10 ** 9 + 7
for i in range(3, N + 1):
arr[i] = (arr[i - 1] + arr[i - 2]) % Mod
ans = arr[n]
for i in range(2, m + 1):
ans = (ans + arr[i] - arr[i - 1]) % Mod
ans = (ans + Mod) % Mod
print(ans)
``` | output | 1 | 80,024 | 7 | 160,049 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.