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.
You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' β colors of lamps in the garland).
You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is diverse.
A garland is called diverse if any two adjacent (consecutive) lamps (i. e. such lamps that the distance between their positions is 1) have distinct colors.
In other words, if the obtained garland is t then for each i from 1 to n-1 the condition t_i β t_{i + 1} should be satisfied.
Among all ways to recolor the initial garland to make it diverse you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of lamps.
The second line of the input contains the string s consisting of n characters 'R', 'G' and 'B' β colors of lamps in the garland.
Output
In the first line of the output print one integer r β the minimum number of recolors needed to obtain a diverse garland from the given one.
In the second line of the output print one string t of length n β a diverse garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.
Examples
Input
9
RBGRRBRGG
Output
2
RBGRGBRGR
Input
8
BBBGBRRR
Output
2
BRBGBRGR
Input
13
BBRRRRGGGGGRR
Output
6
BGRBRBGBGBGRG
Submitted Solution:
```
from os import path
import sys,time, collections as c , math as m , pprint as p
maxx , localsys , mod = float('inf'), 0 , int(1e9 + 7)
if (path.exists('input.txt')): sys.stdin=open('input.txt','r') ; sys.stdout=open('output.txt','w')
input = sys.stdin.readline
n = int(input()) ; s = list(input().rstrip('\n')) ; ans , tp = 0 , ['R','G','B']
# print(''.join(s))
if n == 2 and s[0] == s[1]:
print(1 ,s[0]+ tp[(tp.index(s[0]) +1 )%3] , sep='\n') , exit()
if n ==2 :
print(0 , ''.join(s) , sep='\n' ) , exit()
for i in range(1, n-1):
if s[i-1] == s[i] == s[i+1]:
if s[i] =='R':s[i] = 'G'
elif s[i] == 'G':s[i] = 'B'
else:s[i] ='R'
ans+=1
elif s[i-1] == s[i]:
x = s[i-1]
if i +1 < n :
x = s[i+1]
f = [1]*3
for t in [s[i] , x ]:
f[tp.index(t)] = 0
for k in range(3):
if f[k] :
s[i] = tp[k]
break
ans+=1
elif s[i] == s[i+1]:
x = s[i+1]
if i +2 < n :
x = s[i+2]
f = [1]*3
for t in [s[i] ,x]:
f[tp.index(t)] = 0
for k in range(3):
if f[k]:
s[i+1] = tp[k]
break
ans+=1
print(ans , ''.join(s) , sep='\n')
# def ok(p , s):
# cnt , need =0 , 0
# for i in s:
# if p[need] == i:
# cnt+=1 ; need ^= 1
# if cnt % 2 and p[0] != p[1]:
# cnt-=1
# return cnt
# for _ in range(int(input())):
# s = input().rstrip('\n') ; n , ans = len(s) , maxx
# for i in range(10):
# for j in range(10):
# ans = min(ans , n - ok((str(i) , str(j)), s))
# print(ans)
#This problem was so easy oh gawd , so you can only make left cyclic shift = right cyclic shift , when there are at most
#2 characters
#(incase of 1 ch) at the same time if total string has only character it is valid no matter how you see it
#(incase of 2 ch) all the characters at odd positions must be equal , and all the characters at even position must be equal
# n , k = map(int , input().split()) ; s = input().rstrip('\n')
# ans = a = b = j = 0
# for i in range(n):
# a , b = (a+1 , b) if s[i] == 'a' else (a , b+1 )
# if min(a, b) > k :
# a , b = (a -1 , b) if s[j] == 'a' else (a , b -1) ; j+=1
# else:
# ans+=1
# print(ans)
# #two - pointer method , if at any point min(a , b )> k then keep on decreasing from the beginning untill and unless you get min(a , b)
# #less than k
``` | instruction | 0 | 67,299 | 7 | 134,598 |
Yes | output | 1 | 67,299 | 7 | 134,599 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' β colors of lamps in the garland).
You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is diverse.
A garland is called diverse if any two adjacent (consecutive) lamps (i. e. such lamps that the distance between their positions is 1) have distinct colors.
In other words, if the obtained garland is t then for each i from 1 to n-1 the condition t_i β t_{i + 1} should be satisfied.
Among all ways to recolor the initial garland to make it diverse you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of lamps.
The second line of the input contains the string s consisting of n characters 'R', 'G' and 'B' β colors of lamps in the garland.
Output
In the first line of the output print one integer r β the minimum number of recolors needed to obtain a diverse garland from the given one.
In the second line of the output print one string t of length n β a diverse garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.
Examples
Input
9
RBGRRBRGG
Output
2
RBGRGBRGR
Input
8
BBBGBRRR
Output
2
BRBGBRGR
Input
13
BBRRRRGGGGGRR
Output
6
BGRBRBGBGBGRG
Submitted Solution:
```
n=int(input())
a=list(input())
s={'R','G','B'}
i=0
cnt=0
while i<n-1:
if a[i]==a[i+1]:
s1=set()
s1.add(a[i])
if i+2<n:
s1.add(a[i+2])
s1=s-s1
a[i+1]=s1.pop()
i=i+1
cnt=cnt+1
if i==n-2:
break
i=i+1
print(cnt)
print(''.join(str(i) for i in a))
``` | instruction | 0 | 67,300 | 7 | 134,600 |
Yes | output | 1 | 67,300 | 7 | 134,601 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' β colors of lamps in the garland).
You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is diverse.
A garland is called diverse if any two adjacent (consecutive) lamps (i. e. such lamps that the distance between their positions is 1) have distinct colors.
In other words, if the obtained garland is t then for each i from 1 to n-1 the condition t_i β t_{i + 1} should be satisfied.
Among all ways to recolor the initial garland to make it diverse you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of lamps.
The second line of the input contains the string s consisting of n characters 'R', 'G' and 'B' β colors of lamps in the garland.
Output
In the first line of the output print one integer r β the minimum number of recolors needed to obtain a diverse garland from the given one.
In the second line of the output print one string t of length n β a diverse garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.
Examples
Input
9
RBGRRBRGG
Output
2
RBGRGBRGR
Input
8
BBBGBRRR
Output
2
BRBGBRGR
Input
13
BBRRRRGGGGGRR
Output
6
BGRBRBGBGBGRG
Submitted Solution:
```
n=int(input())
l=list(input())
a={'R':0,'G':1,'B':2}
b=['R','G','B']
c=0
for i in range(n-1):
if l[i]==l[i+1]:
c+=1
if i+2<n and l[i]==l[i+2]:
l[i+1]=b[a[l[i]]-1]
elif i+2<n and l[i]!=l[i+2]:
l[i+1]=b[3-a[l[i]]-a[l[i+2]]]
else:
l[i+1]=b[a[l[i]]-1]
print(c)
print("".join(l))
``` | instruction | 0 | 67,301 | 7 | 134,602 |
Yes | output | 1 | 67,301 | 7 | 134,603 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' β colors of lamps in the garland).
You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is diverse.
A garland is called diverse if any two adjacent (consecutive) lamps (i. e. such lamps that the distance between their positions is 1) have distinct colors.
In other words, if the obtained garland is t then for each i from 1 to n-1 the condition t_i β t_{i + 1} should be satisfied.
Among all ways to recolor the initial garland to make it diverse you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of lamps.
The second line of the input contains the string s consisting of n characters 'R', 'G' and 'B' β colors of lamps in the garland.
Output
In the first line of the output print one integer r β the minimum number of recolors needed to obtain a diverse garland from the given one.
In the second line of the output print one string t of length n β a diverse garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.
Examples
Input
9
RBGRRBRGG
Output
2
RBGRGBRGR
Input
8
BBBGBRRR
Output
2
BRBGBRGR
Input
13
BBRRRRGGGGGRR
Output
6
BGRBRBGBGBGRG
Submitted Solution:
```
# !/usr/bin/env python3
# coding: UTF-8
# Modified: <23/Jan/2019 09:18:55 PM>
# βͺ H4WK3yEδΉ‘
# Mohd. Farhan Tahir
# Indian Institute Of Information Technology (IIIT),Gwalior
# Question Link
#
#
# ///==========Libraries, Constants and Functions=============///
import sys
inf = float("inf")
mod = 1000000007
def get_array(): return list(map(int, sys.stdin.readline().split()))
def get_ints(): return map(int, sys.stdin.readline().split())
def input(): return sys.stdin.readline()
# ///==========MAIN=============///
def main():
n = int(input())
s = list(input().strip())
if n == 1:
print(0)
print(*s, sep='')
return
if n == 2:
if s[0] != s[1]:
print(0)
print(*s, sep='')
return
if s[0] == s[1]:
print(1)
if s[0] == 'R':
print('RG')
return
elif s[0] == 'G':
print('GB')
return
elif s[0] == 'B':
print('BR')
return
mn, count = inf, 0
for i in range(n - 2):
if s[i] == s[i + 1]:
count += 1
if s[i + 1] == s[i + 2]:
if s[i] == 'R':
s[i + 1] = 'G'
elif s[i] == 'G':
s[i + 1] = 'B'
elif s[i] == 'B':
s[i + 1] = 'G'
else:
if (s[i] == 'R' or s[i] == 'G') and (s[i + 2] == 'R' or s[i + 2] == 'G'):
s[i + 1] = 'B'
elif (s[i] == 'R' or s[i] == 'B') and (s[i + 2] == 'R' or s[i + 2] == 'B'):
s[i + 1] = 'G'
elif (s[i] == 'B' or s[i] == 'G') and (s[i + 2] == 'B' or s[i + 2] == 'G'):
s[i + 1] = 'R'
if s[-1] == s[-2]:
count += 1
if s[-2] == 'R':
s[-1] = 'G'
elif s[-2] == 'G':
s[-1] = 'B'
elif s[-2] == 'B':
s[-1] = 'R'
print(count)
print(*s, sep='')
if __name__ == "__main__":
main()
``` | instruction | 0 | 67,302 | 7 | 134,604 |
Yes | output | 1 | 67,302 | 7 | 134,605 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' β colors of lamps in the garland).
You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is diverse.
A garland is called diverse if any two adjacent (consecutive) lamps (i. e. such lamps that the distance between their positions is 1) have distinct colors.
In other words, if the obtained garland is t then for each i from 1 to n-1 the condition t_i β t_{i + 1} should be satisfied.
Among all ways to recolor the initial garland to make it diverse you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of lamps.
The second line of the input contains the string s consisting of n characters 'R', 'G' and 'B' β colors of lamps in the garland.
Output
In the first line of the output print one integer r β the minimum number of recolors needed to obtain a diverse garland from the given one.
In the second line of the output print one string t of length n β a diverse garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.
Examples
Input
9
RBGRRBRGG
Output
2
RBGRGBRGR
Input
8
BBBGBRRR
Output
2
BRBGBRGR
Input
13
BBRRRRGGGGGRR
Output
6
BGRBRBGBGBGRG
Submitted Solution:
```
x=int(input())
s=list(input())
res=0
for n in range(x-2,0,-1):
if s[n]==s[n+1]:
if s[n+1]=='G':
s[n]='B'
elif s[n+1]=='B':
s[n]='R'
elif s[n+1]=='R':
s[n]='G'
if s[n-1]==s[n]:
if s[n-1]=='R':s[n]='G'
elif s[n-1]=='G': s[n]='B'
else:s[n]='R'
res+=1
print(res)
for n in s:
print(n,end='')
``` | instruction | 0 | 67,303 | 7 | 134,606 |
No | output | 1 | 67,303 | 7 | 134,607 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' β colors of lamps in the garland).
You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is diverse.
A garland is called diverse if any two adjacent (consecutive) lamps (i. e. such lamps that the distance between their positions is 1) have distinct colors.
In other words, if the obtained garland is t then for each i from 1 to n-1 the condition t_i β t_{i + 1} should be satisfied.
Among all ways to recolor the initial garland to make it diverse you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of lamps.
The second line of the input contains the string s consisting of n characters 'R', 'G' and 'B' β colors of lamps in the garland.
Output
In the first line of the output print one integer r β the minimum number of recolors needed to obtain a diverse garland from the given one.
In the second line of the output print one string t of length n β a diverse garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.
Examples
Input
9
RBGRRBRGG
Output
2
RBGRGBRGR
Input
8
BBBGBRRR
Output
2
BRBGBRGR
Input
13
BBRRRRGGGGGRR
Output
6
BGRBRBGBGBGRG
Submitted Solution:
```
n=int(input())
ad=input()
l='RGB'
ct=0
a=list(ad)
for i in range(len(a)-2):
if a[i]==a[i+1]:
for k in l:
if k!=a[i] and k!=a[i+2]:
break
a[i+1]=k
ct+=1
if a[-1]==a[-2]:
for k in l:
if k!=a[-2]:
break
a[-1]=k
ct+=1
print(ct)
print(a)
``` | instruction | 0 | 67,304 | 7 | 134,608 |
No | output | 1 | 67,304 | 7 | 134,609 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' β colors of lamps in the garland).
You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is diverse.
A garland is called diverse if any two adjacent (consecutive) lamps (i. e. such lamps that the distance between their positions is 1) have distinct colors.
In other words, if the obtained garland is t then for each i from 1 to n-1 the condition t_i β t_{i + 1} should be satisfied.
Among all ways to recolor the initial garland to make it diverse you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of lamps.
The second line of the input contains the string s consisting of n characters 'R', 'G' and 'B' β colors of lamps in the garland.
Output
In the first line of the output print one integer r β the minimum number of recolors needed to obtain a diverse garland from the given one.
In the second line of the output print one string t of length n β a diverse garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.
Examples
Input
9
RBGRRBRGG
Output
2
RBGRGBRGR
Input
8
BBBGBRRR
Output
2
BRBGBRGR
Input
13
BBRRRRGGGGGRR
Output
6
BGRBRBGBGBGRG
Submitted Solution:
```
n = int(input())
s = list(input())
dp = [[0 for i in range(3)]for i in range(n)]
rec = {'R': 0, 'G': 1, 'B': 2}
recInv = {0: 'R', 1: 'G', 2: 'B'}
dp[0][rec[s[0]]] = 0
dp[0][(rec[s[0]] - 1) % 3] = 1
dp[0][(rec[s[0]] + 1) % 3] = 1
for i in range(1, n):
dp[i][rec[s[i]]] = min(dp[i - 1][(rec[s[i]] - 1) % 3], dp[i - 1][(rec[s[i]] + 1) % 3])
dp[i][(rec[s[i]] - 1) % 3] = 1 + min(dp[i - 1][((rec[s[i]] - 1) - 1) % 3], dp[i - 1][(rec[s[i]]) % 3])
dp[i][(rec[s[i]] + 1) % 3] = 1 + min(dp[i - 1][(rec[s[i]]) % 3], dp[i - 1][(rec[s[i]] + 2) % 3])
result = ['' for i in range(n)]
if dp[n - 1][0] == min(dp[n - 1]):
temp = 0
elif dp[n - 1][1] == min(dp[n - 1]):
temp = 1
else:
temp = 2
result[n - 1] = recInv[temp]
for i in range(n - 2, -1, -1):
if dp[i][(temp - 1) % 3] == min(dp[i]):
temp = (temp - 1) % 3
else:
temp = (temp + 1) % 3
result[i] = recInv[temp]
print(min(dp[n - 1]))
print(''.join(result))
``` | instruction | 0 | 67,305 | 7 | 134,610 |
No | output | 1 | 67,305 | 7 | 134,611 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' β colors of lamps in the garland).
You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is diverse.
A garland is called diverse if any two adjacent (consecutive) lamps (i. e. such lamps that the distance between their positions is 1) have distinct colors.
In other words, if the obtained garland is t then for each i from 1 to n-1 the condition t_i β t_{i + 1} should be satisfied.
Among all ways to recolor the initial garland to make it diverse you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of lamps.
The second line of the input contains the string s consisting of n characters 'R', 'G' and 'B' β colors of lamps in the garland.
Output
In the first line of the output print one integer r β the minimum number of recolors needed to obtain a diverse garland from the given one.
In the second line of the output print one string t of length n β a diverse garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.
Examples
Input
9
RBGRRBRGG
Output
2
RBGRGBRGR
Input
8
BBBGBRRR
Output
2
BRBGBRGR
Input
13
BBRRRRGGGGGRR
Output
6
BGRBRBGBGBGRG
Submitted Solution:
```
def divGar(s, n):
s = list(s)
i = 0
c = 0
while (i < n-1):
g = ['R', 'G', 'B']
if s[i] == s[i+1]:
if i+2 < n:
g.remove(s[i+2])
if s[i] in g:
g.remove(s[i])
s[i+1] = g[0]
c += 1
i += 1
return c, s
n = int(input())
s = input()
c, s = divGar(s, n)
print(c)
print(s)
``` | instruction | 0 | 67,306 | 7 | 134,612 |
No | output | 1 | 67,306 | 7 | 134,613 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Johnny's younger sister Megan had a birthday recently. Her brother has bought her a box signed as "Your beautiful necklace β do it yourself!". It contains many necklace parts and some magic glue.
The necklace part is a chain connecting two pearls. Color of each pearl can be defined by a non-negative integer. The magic glue allows Megan to merge two pearls (possibly from the same necklace part) into one. The beauty of a connection of pearls in colors u and v is defined as follows: let 2^k be the greatest power of two dividing u β v β [exclusive or](https://en.wikipedia.org/wiki/Exclusive_or#Computer_science) of u and v. Then the beauty equals k. If u = v, you may assume that beauty is equal to 20.
Each pearl can be combined with another at most once. Merging two parts of a necklace connects them. Using the glue multiple times, Megan can finally build the necklace, which is a cycle made from connected necklace parts (so every pearl in the necklace is combined with precisely one other pearl in it). The beauty of such a necklace is the minimum beauty of a single connection in it. The girl wants to use all available necklace parts to build exactly one necklace consisting of all of them with the largest possible beauty. Help her!
Input
The first line contains n (1 β€ n β€ 5 β
10^5) β the number of necklace parts in the box. Each of the next n lines contains two integers a and b (0 β€ a, b < 2^{20}), which denote colors of pearls presented in the necklace parts. Pearls in the i-th line have indices 2i - 1 and 2i respectively.
Output
The first line should contain a single integer b denoting the maximum possible beauty of a necklace built from all given parts.
The following line should contain 2n distinct integers p_i (1 β€ p_i β€ 2n) β the indices of initial pearls in the order in which they appear on a cycle. Indices of pearls belonging to the same necklace part have to appear at neighboring positions in this permutation (so 1 4 3 2 is not a valid output, whereas 2 1 4 3 and 4 3 1 2 are). If there are many possible answers, you can print any.
Examples
Input
5
13 11
11 1
3 5
17 1
9 27
Output
3
8 7 9 10 5 6 1 2 3 4
Input
5
13 11
11 1
3 5
17 1
7 29
Output
2
8 7 10 9 5 6 4 3 2 1
Input
1
1 1
Output
20
2 1
Note
In the first example the following pairs of pearls are combined: (7, 9), (10, 5), (6, 1), (2, 3) and (4, 8). The beauties of connections equal correspondingly: 3, 3, 3, 20, 20.
The following drawing shows this construction.
<image>
Submitted Solution:
```
from sys import stdin, gettrace
from collections import deque
if gettrace():
inputi = input
else:
def input():
return next(stdin)[:-1]
def inputi():
return stdin.buffer.readline()
def main():
n = int(inputi())
pp = []
for _ in range(n):
pp.append(tuple(map(int, inputi().split())))
for b in range(20,-1, -1):
mask = 2**b - 1
adj = [set() for _ in range(2**b)]
for i, (p,q) in enumerate(pp):
adj[p & mask].add((q & mask, i*2, i*2+1))
adj[q & mask].add((p & mask, i*2+1, i*2))
if any((len(a)%2 == 1 for a in adj)):
continue
visited = [len(adj[i]) == 0 for i in range(2**b)]
mi = 0
while not adj[mi]:
mi += 1
dq = deque()
dq.append(mi)
while dq:
i = dq.popleft()
visited[i] = True
for j, _, _ in adj[i]:
if not visited[j]:
dq.append(j)
if all(visited):
break
else:
print(0)
print(' '.join(map(str, range(1, 2 * n + 1))))
return
curr_path = []
res = []
m = mi
while len(res) < 2*n:
if adj[m]:
nm, i, j = adj[m].pop()
adj[nm].remove((m, j, i))
curr_path.append((nm, i, j))
m = nm
else:
nm, i, j = curr_path.pop()
res += [i+1,j+1]
m = nm
print(b)
print(' '.join(map(str, res)))
if __name__ == "__main__":
main()
``` | instruction | 0 | 67,446 | 7 | 134,892 |
No | output | 1 | 67,446 | 7 | 134,893 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Johnny's younger sister Megan had a birthday recently. Her brother has bought her a box signed as "Your beautiful necklace β do it yourself!". It contains many necklace parts and some magic glue.
The necklace part is a chain connecting two pearls. Color of each pearl can be defined by a non-negative integer. The magic glue allows Megan to merge two pearls (possibly from the same necklace part) into one. The beauty of a connection of pearls in colors u and v is defined as follows: let 2^k be the greatest power of two dividing u β v β [exclusive or](https://en.wikipedia.org/wiki/Exclusive_or#Computer_science) of u and v. Then the beauty equals k. If u = v, you may assume that beauty is equal to 20.
Each pearl can be combined with another at most once. Merging two parts of a necklace connects them. Using the glue multiple times, Megan can finally build the necklace, which is a cycle made from connected necklace parts (so every pearl in the necklace is combined with precisely one other pearl in it). The beauty of such a necklace is the minimum beauty of a single connection in it. The girl wants to use all available necklace parts to build exactly one necklace consisting of all of them with the largest possible beauty. Help her!
Input
The first line contains n (1 β€ n β€ 5 β
10^5) β the number of necklace parts in the box. Each of the next n lines contains two integers a and b (0 β€ a, b < 2^{20}), which denote colors of pearls presented in the necklace parts. Pearls in the i-th line have indices 2i - 1 and 2i respectively.
Output
The first line should contain a single integer b denoting the maximum possible beauty of a necklace built from all given parts.
The following line should contain 2n distinct integers p_i (1 β€ p_i β€ 2n) β the indices of initial pearls in the order in which they appear on a cycle. Indices of pearls belonging to the same necklace part have to appear at neighboring positions in this permutation (so 1 4 3 2 is not a valid output, whereas 2 1 4 3 and 4 3 1 2 are). If there are many possible answers, you can print any.
Examples
Input
5
13 11
11 1
3 5
17 1
9 27
Output
3
8 7 9 10 5 6 1 2 3 4
Input
5
13 11
11 1
3 5
17 1
7 29
Output
2
8 7 10 9 5 6 4 3 2 1
Input
1
1 1
Output
20
2 1
Note
In the first example the following pairs of pearls are combined: (7, 9), (10, 5), (6, 1), (2, 3) and (4, 8). The beauties of connections equal correspondingly: 3, 3, 3, 20, 20.
The following drawing shows this construction.
<image>
Submitted Solution:
```
from collections import deque
def euler_path(g,s,e,m,ID):
temp=[]
n=len(g)
pos=s
used=[False]*(m+1)
used[ID]=True
while pos!=e:
nv,id=g[pos].pop()
if used[abs(id)]:
continue
used[abs(id)]=True
temp.append((pos,id))
pos=nv
#print(s,e,temp)
res=[]
while temp:
if g[pos]:
ppos=pos
while g[pos] and used[abs(g[pos][-1][1])]:
g[pos].pop()
if g[pos]:
nv,id=g[pos].pop()
used[abs(id)]=True
res.append(-id)
pos=nv
while pos!=ppos:
nv,id=g[pos].pop()
if used[abs(id)]:
continue
used[abs(id)]=True
res.append(-id)
pos=nv
else:
nv,id=temp.pop()
res.append(id)
pos=nv
#print(res)
while g[pos]:
ppos=pos
while g[pos] and used[abs(g[pos][-1][1])]:
g[pos].pop()
if g[pos]:
nv,id=g[pos].pop()
#print(pos,nv,id)
used[abs(id)]=True
res.append(-id)
pos=nv
while pos!=ppos:
nv,id=g[pos].pop()
if used[abs(id)]:
continue
used[abs(id)]=True
res.append(-id)
pos=nv
return res[::-1]
n=int(input())
nek=[tuple(map(int,input().split())) for i in range(n)]
for i in range(20,-1,-1):
data=[[] for i in range(2**i)]
s,e,id=-1,-1,-1
for j in range(n):
a,b=nek[j]
a%=2**i
b%=2**i
data[a].append((b,j+1))
data[b].append((a,-(j+1)))
if a!=b:
s,e,id=a,b,(j+1)
check=True
for j in range(2**i):
check&=(len(data[j])%2==0)
if check:
if s!=-1:
res=euler_path(data,s,e,n,id)
res.append(-id)
#print(res)
if len(res)==n:
ans=[]
for j in res:
if j>0:
j-=1
ans.append(2*j+1)
ans.append(2*j+2)
else:
j=abs(j)-1
ans.append(2*j+2)
ans.append(2*j+1)
print(i)
print(*ans)
break
else:
check2=0
for j in range(2**i):
check2+=(len(data[j])!=0)
if check2==1:
print(i)
print(*[j for j in range(1,2*n+1)])
break
``` | instruction | 0 | 67,447 | 7 | 134,894 |
No | output | 1 | 67,447 | 7 | 134,895 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Johnny's younger sister Megan had a birthday recently. Her brother has bought her a box signed as "Your beautiful necklace β do it yourself!". It contains many necklace parts and some magic glue.
The necklace part is a chain connecting two pearls. Color of each pearl can be defined by a non-negative integer. The magic glue allows Megan to merge two pearls (possibly from the same necklace part) into one. The beauty of a connection of pearls in colors u and v is defined as follows: let 2^k be the greatest power of two dividing u β v β [exclusive or](https://en.wikipedia.org/wiki/Exclusive_or#Computer_science) of u and v. Then the beauty equals k. If u = v, you may assume that beauty is equal to 20.
Each pearl can be combined with another at most once. Merging two parts of a necklace connects them. Using the glue multiple times, Megan can finally build the necklace, which is a cycle made from connected necklace parts (so every pearl in the necklace is combined with precisely one other pearl in it). The beauty of such a necklace is the minimum beauty of a single connection in it. The girl wants to use all available necklace parts to build exactly one necklace consisting of all of them with the largest possible beauty. Help her!
Input
The first line contains n (1 β€ n β€ 5 β
10^5) β the number of necklace parts in the box. Each of the next n lines contains two integers a and b (0 β€ a, b < 2^{20}), which denote colors of pearls presented in the necklace parts. Pearls in the i-th line have indices 2i - 1 and 2i respectively.
Output
The first line should contain a single integer b denoting the maximum possible beauty of a necklace built from all given parts.
The following line should contain 2n distinct integers p_i (1 β€ p_i β€ 2n) β the indices of initial pearls in the order in which they appear on a cycle. Indices of pearls belonging to the same necklace part have to appear at neighboring positions in this permutation (so 1 4 3 2 is not a valid output, whereas 2 1 4 3 and 4 3 1 2 are). If there are many possible answers, you can print any.
Examples
Input
5
13 11
11 1
3 5
17 1
9 27
Output
3
8 7 9 10 5 6 1 2 3 4
Input
5
13 11
11 1
3 5
17 1
7 29
Output
2
8 7 10 9 5 6 4 3 2 1
Input
1
1 1
Output
20
2 1
Note
In the first example the following pairs of pearls are combined: (7, 9), (10, 5), (6, 1), (2, 3) and (4, 8). The beauties of connections equal correspondingly: 3, 3, 3, 20, 20.
The following drawing shows this construction.
<image>
Submitted Solution:
```
from collections import deque
n=int(input())
nek=[tuple(map(int,input().split())) for i in range(n)]
for i in range(20,-1,-1):
data=[0]*(2**i)
data2=[0]*(2**i)
for a,b in nek:
a%=2**i
b%=2**i
if a!=b:
data[a]+=1
data[b]+=1
else:
data2[a]+=1
check1=True
check2=True
for j in range(2**i):
check1&=(data[j]%2==0)
check2&=(data2[j]==0 or data[j]>0)
if check1:
if check2:
print(i)
data=[[] for i in range(2**i)]
data2=[[] for i in range(2**i)]
start=(-1,-1,-1)
count=0
for j in range(n):
a,b=nek[j]
a%=2**i
b%=2**i
if a!=b:
start=(a,b,j)
count+=1
data[a].append((a,b,j))
data[b].append((b,a,j))
else:
data2[a].append(j)
used=[False]*n
res=[start]
used[start[2]]=True
count-=1
while count:
a,b,id=res[-1]
#print(res,data[b])
while used[data[b][-1][2]]:
data[b].pop()
next=data[b].pop()
used[next[2]]=True
res.append(next)
count-=1
res=deque(res)
newres=[res[0]]
res.popleft()
while res:
id=newres[-1][1]
if data2[id]:
while data2[id]:
newres.append((id,id,data2[id].pop()))
else:
newres.append(res.popleft())
id=newres[-1][1]
if data2[id]:
while data2[id]:
newres.append((id,id,data2[id].pop()))
ans=[]
for a,b,id in newres:
if (a,b)==nek[id]:
ans.append(2*id+1)
ans.append(2*id+2)
else:
ans.append(2*id+2)
ans.append(2*id+1)
print(*ans)
exit()
else:
only=0
for j in range(2**i):
only+=(data[j]>0 or data2[j]>0)
if only==1:
print(i)
print(*[i+1 for i in range(2*n)])
exit()
``` | instruction | 0 | 67,448 | 7 | 134,896 |
No | output | 1 | 67,448 | 7 | 134,897 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Johnny's younger sister Megan had a birthday recently. Her brother has bought her a box signed as "Your beautiful necklace β do it yourself!". It contains many necklace parts and some magic glue.
The necklace part is a chain connecting two pearls. Color of each pearl can be defined by a non-negative integer. The magic glue allows Megan to merge two pearls (possibly from the same necklace part) into one. The beauty of a connection of pearls in colors u and v is defined as follows: let 2^k be the greatest power of two dividing u β v β [exclusive or](https://en.wikipedia.org/wiki/Exclusive_or#Computer_science) of u and v. Then the beauty equals k. If u = v, you may assume that beauty is equal to 20.
Each pearl can be combined with another at most once. Merging two parts of a necklace connects them. Using the glue multiple times, Megan can finally build the necklace, which is a cycle made from connected necklace parts (so every pearl in the necklace is combined with precisely one other pearl in it). The beauty of such a necklace is the minimum beauty of a single connection in it. The girl wants to use all available necklace parts to build exactly one necklace consisting of all of them with the largest possible beauty. Help her!
Input
The first line contains n (1 β€ n β€ 5 β
10^5) β the number of necklace parts in the box. Each of the next n lines contains two integers a and b (0 β€ a, b < 2^{20}), which denote colors of pearls presented in the necklace parts. Pearls in the i-th line have indices 2i - 1 and 2i respectively.
Output
The first line should contain a single integer b denoting the maximum possible beauty of a necklace built from all given parts.
The following line should contain 2n distinct integers p_i (1 β€ p_i β€ 2n) β the indices of initial pearls in the order in which they appear on a cycle. Indices of pearls belonging to the same necklace part have to appear at neighboring positions in this permutation (so 1 4 3 2 is not a valid output, whereas 2 1 4 3 and 4 3 1 2 are). If there are many possible answers, you can print any.
Examples
Input
5
13 11
11 1
3 5
17 1
9 27
Output
3
8 7 9 10 5 6 1 2 3 4
Input
5
13 11
11 1
3 5
17 1
7 29
Output
2
8 7 10 9 5 6 4 3 2 1
Input
1
1 1
Output
20
2 1
Note
In the first example the following pairs of pearls are combined: (7, 9), (10, 5), (6, 1), (2, 3) and (4, 8). The beauties of connections equal correspondingly: 3, 3, 3, 20, 20.
The following drawing shows this construction.
<image>
Submitted Solution:
```
import sys, random
input = sys.stdin.readline
n = int(input())
edgeOrig = [(0,0)] * n
for i in range(n):
edgeOrig[i] = tuple(map(int, input().split()))
for poss in range(20, -1, -1):
mask = 2 ** poss - 1
adj = dict()
smol = 2 ** 20
for i in range(n):
a, b = edgeOrig[i]
a &= mask
b &= mask
#print(a,b)
if a not in adj:
adj[a] = []
if b not in adj:
adj[b] = []
adj[a].append((b,i,False))
adj[b].append((a,i,True))
smol = min((smol, a, b))
works = True
for v in adj:
if len(adj[v]) % 2:
works = False
break
random.shuffle(adj[v])
if not works:
continue
used = [False] * n
out = []
curr = smol
while adj[curr]:
nex, edge, rev = adj[curr].pop()
if not used[edge]:
used[edge] = True
curr = nex
if rev:
out.append(2 * edge + 2)
out.append(2 * edge + 1)
else:
out.append(2 * edge + 1)
out.append(2 * edge + 2)
if len(out) == 2 * n:
print(poss)
print(*out)
break
``` | instruction | 0 | 67,449 | 7 | 134,898 |
No | output | 1 | 67,449 | 7 | 134,899 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
Input
The first input line contains integer n (1 β€ n β€ 105) β amount of squares in the stripe. The second line contains n space-separated numbers β they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.
Output
Output the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.
Examples
Input
4
1 2 3 3
Output
1
Input
5
1 2 3 4 5
Output
0 | instruction | 0 | 67,567 | 7 | 135,134 |
Tags: binary search, dp, sortings
Correct Solution:
```
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 21 09:53:47 2020
@author: DELL
"""
n = int(input())
a = [int(a) for a in input().split()]
s = sum(a)
if s % 3 != 0:
print(0)
else:
s = s // 3
t = 0
ct = 0
res = 0
for i in range(n - 1):
t += a[i]
if t == 2 * s:
res += ct
if t == s:
ct += 1
print(res)
``` | output | 1 | 67,567 | 7 | 135,135 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
Input
The first input line contains integer n (1 β€ n β€ 105) β amount of squares in the stripe. The second line contains n space-separated numbers β they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.
Output
Output the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.
Examples
Input
4
1 2 3 3
Output
1
Input
5
1 2 3 4 5
Output
0 | instruction | 0 | 67,568 | 7 | 135,136 |
Tags: binary search, dp, sortings
Correct Solution:
```
n=int(input())
ar=list(map(int,input().split()))
s=sum(ar)
if(s%3!=0):
print(0)
else:
s1,s2,t,v1,v2=s//3,s//3*2,0,0,0
for e in ar[:-1]:
t+=e
if(t==s2):v2+=v1
if(t==s1):v1+=1
print(v2)
``` | output | 1 | 67,568 | 7 | 135,137 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
Input
The first input line contains integer n (1 β€ n β€ 105) β amount of squares in the stripe. The second line contains n space-separated numbers β they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.
Output
Output the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.
Examples
Input
4
1 2 3 3
Output
1
Input
5
1 2 3 4 5
Output
0 | instruction | 0 | 67,569 | 7 | 135,138 |
Tags: binary search, dp, sortings
Correct Solution:
```
n = int(input())
lis = list(map(int,input().split()))
pre=[0]*(n+1)
for i in range(1,n+1):
pre[i]=pre[i-1]+lis[i-1]
if pre[-1]%3:
print(0)
else:
s=pre[-1]//3
ans=t=0
for i in range(1,n):
if pre[i]==2*s:
ans+=t
if pre[i]==s:
t+=1
print(ans)
``` | output | 1 | 67,569 | 7 | 135,139 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
Input
The first input line contains integer n (1 β€ n β€ 105) β amount of squares in the stripe. The second line contains n space-separated numbers β they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.
Output
Output the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.
Examples
Input
4
1 2 3 3
Output
1
Input
5
1 2 3 4 5
Output
0 | instruction | 0 | 67,570 | 7 | 135,140 |
Tags: binary search, dp, sortings
Correct Solution:
```
# n = int(input())
# integers = map(int,input().split())
# s = sum(integers)
# if s%3 != 0 or n>3:
# print(0)
# exit()
# temp,total,current = 0,0,0
# for i in range(n-1):
# current += integers[i]
# if current*3 == 2*s:
# total += temp
# if current*3 == s:
# temp +=1
# print(total)
from itertools import accumulate
n = int(input())
a = list(map(int, input().split()))
s = sum(a)
p = s // 3
k = list(accumulate(a))
r = list(accumulate(x == 2*p for x in reversed(k)))
print(0 if s%3 else sum(r[-1-i] - 2*(not p) for i,x in enumerate(k[:-1]) if x == p))
``` | output | 1 | 67,570 | 7 | 135,141 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
Input
The first input line contains integer n (1 β€ n β€ 105) β amount of squares in the stripe. The second line contains n space-separated numbers β they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.
Output
Output the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.
Examples
Input
4
1 2 3 3
Output
1
Input
5
1 2 3 4 5
Output
0 | instruction | 0 | 67,571 | 7 | 135,142 |
Tags: binary search, dp, sortings
Correct Solution:
```
#! /usr/bin/python3
def solve():
n = int(input())
a = []
total = 0
for i in input().strip().split():
a.append(int(i))
for i in range(0, n):
total = total + a[i]
if (total % 3 != 0 or n < 3):
print(0)
return
part = total // 3
c = [0] * 100005
right = part * 2
right_sum = [0] * 100005
i = n - 1
while (i >= 0):
right_sum[i] = right_sum[i + 1] + a[i]
if right_sum[i] == part:
c[i] = c[i + 1] + 1
else:
c[i] = c[i + 1]
i = i - 1
ret = 0
s = 0
for i in range(0, n - 1):
s = s + a[i]
if (s == part):
ret = ret + c[i + 1]
if (part == 0):
ret = ret - 1
#print("ret = ", ret)
print(ret)
solve()
``` | output | 1 | 67,571 | 7 | 135,143 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
Input
The first input line contains integer n (1 β€ n β€ 105) β amount of squares in the stripe. The second line contains n space-separated numbers β they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.
Output
Output the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.
Examples
Input
4
1 2 3 3
Output
1
Input
5
1 2 3 4 5
Output
0 | instruction | 0 | 67,572 | 7 | 135,144 |
Tags: binary search, dp, sortings
Correct Solution:
```
from itertools import accumulate
n = int(input())
a = list(map(int, input().split()))
s = sum(a)
p = s // 3
k = list(accumulate(a))
r = list(accumulate(x == 2*p for x in reversed(k)))
print(0 if s%3 else sum(r[-1-i] - 2*(not p) for i,x in enumerate(k[:-1]) if x == p))
``` | output | 1 | 67,572 | 7 | 135,145 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
Input
The first input line contains integer n (1 β€ n β€ 105) β amount of squares in the stripe. The second line contains n space-separated numbers β they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.
Output
Output the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.
Examples
Input
4
1 2 3 3
Output
1
Input
5
1 2 3 4 5
Output
0 | instruction | 0 | 67,573 | 7 | 135,146 |
Tags: binary search, dp, sortings
Correct Solution:
```
n=int(input())
arr=list(map(int,input().split()))
psum=arr[:]
for i in range(1,n):
psum[i]+=psum[i-1]
sums=psum[-1]
set1=set()
set2=set()
if sums%3!=0:
print(0)
else:
a=sums//3
for i in range(n):
if psum[i]==a:
set1.add(i)
if psum[i]==2*a and i!=n-1:
set2.add(i)
b=[0]*(n)
for i in set1:
if i+1<n:
b[i+1]+=1
#print(b)
for i in range(1,n):
b[i]+=b[i-1]
#print(b)
bpos=[0]*(n)
for j in set2:
bpos[j]+=1
sums=0
for i in range(n):
sums+=bpos[i]*b[i]
#print(arr)
#print(psum)
#print(set1)
#print(set2)
#print(b)
#print(bpos)
print(sums)
``` | output | 1 | 67,573 | 7 | 135,147 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
Input
The first input line contains integer n (1 β€ n β€ 105) β amount of squares in the stripe. The second line contains n space-separated numbers β they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.
Output
Output the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.
Examples
Input
4
1 2 3 3
Output
1
Input
5
1 2 3 4 5
Output
0 | instruction | 0 | 67,574 | 7 | 135,148 |
Tags: binary search, dp, sortings
Correct Solution:
```
#! /usr/bin/python3
def solve():
n = int(input())
a = []
total = 0
for i in input().strip().split():
a.append(int(i))
for i in range(0, n):
total = total + a[i]
if (total % 3 != 0 or n < 3):
print(0)
return
part = total // 3
c = [0] * 100005
right = part * 2
right_sum = [0] * 100005
i = n - 1
while (i >= 0):
right_sum[i] = right_sum[i + 1] + a[i]
if right_sum[i] == part:
c[i] = c[i + 1] + 1
else:
c[i] = c[i + 1]
i = i - 1
ret = 0
s = 0
for i in range(0, n - 1):
s = s + a[i]
if (s == part):
ret = ret + c[i + 1]
if (part == 0):
ret = ret - 1
#print("ret = ", ret)
print(ret)
solve()
# Made By Mostafa_Khaled
``` | output | 1 | 67,574 | 7 | 135,149 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
Input
The first input line contains integer n (1 β€ n β€ 105) β amount of squares in the stripe. The second line contains n space-separated numbers β they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.
Output
Output the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.
Examples
Input
4
1 2 3 3
Output
1
Input
5
1 2 3 4 5
Output
0
Submitted Solution:
```
n = int(input())
lis = list(map(int,input().split()))
pre=[0]*(n+1)+[0]
for i in range(1,n+1):
pre[i]=pre[i-1]+lis[i-1]
#print(pre)
ans=0
for i in range(1,n-1):
l=i
r=n-1
while l<=r:
mid = l + (r-l)//2
a=pre[mid]-pre[i]
b=pre[n]-pre[mid]
# print(a,b)
if a<=b:
l=mid+1
else:
r=mid-1
a=pre[i]
b=pre[r]-pre[i]
c=pre[n]-pre[r]
# print(a,b,c)
if a==b==c:
ans+=1
l=r
while r<n-1 and pre[r]==pre[r+1]:
ans+=1
r+=1
while l>i+1 and pre[l]==pre[l-1]:
ans+=1
l-=1
# print(ans,l,r)
print(ans)
``` | instruction | 0 | 67,575 | 7 | 135,150 |
No | output | 1 | 67,575 | 7 | 135,151 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
Input
The first input line contains integer n (1 β€ n β€ 105) β amount of squares in the stripe. The second line contains n space-separated numbers β they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.
Output
Output the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.
Examples
Input
4
1 2 3 3
Output
1
Input
5
1 2 3 4 5
Output
0
Submitted Solution:
```
n = int(input())
lis = list(map(int,input().split()))
pre=[0]*(n+1)
for i in range(1,n+1):
pre[i]=pre[i-1]+lis[i-1]
if pre[-1]%3:
print(0)
else:
s=pre[-1]//3
ans=t=0
for i in range(1,n):
if pre[i]==s:
t+=1
if pre[i]==2*s:
ans+=t
print(ans)
``` | instruction | 0 | 67,576 | 7 | 135,152 |
No | output | 1 | 67,576 | 7 | 135,153 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
Input
The first input line contains integer n (1 β€ n β€ 105) β amount of squares in the stripe. The second line contains n space-separated numbers β they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.
Output
Output the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.
Examples
Input
4
1 2 3 3
Output
1
Input
5
1 2 3 4 5
Output
0
Submitted Solution:
```
n=int(input())
ar=list(map(int,input().split()))
s=sum(ar)
if(s%3!=0):
print(0)
else:
s1=s//3
s2=s1*2
t=0
v1,v2=0,0
for e in ar[::-1]:
t+=e
if(t==s1):
v1+=1
elif(t==s2):
v2+=v1
print(v2)
``` | instruction | 0 | 67,577 | 7 | 135,154 |
No | output | 1 | 67,577 | 7 | 135,155 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
Input
The first input line contains integer n (1 β€ n β€ 105) β amount of squares in the stripe. The second line contains n space-separated numbers β they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.
Output
Output the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.
Examples
Input
4
1 2 3 3
Output
1
Input
5
1 2 3 4 5
Output
0
Submitted Solution:
```
#! /usr/bin/python3
def solve():
n = int(input())
a = []
total = 0
for i in input().strip().split():
a.append(int(i))
for i in range(0, n):
total = total + a[i]
if (total % 3 != 0):
print(0)
return
part = total // 3
c = [0] * 100005
right = part * 2
right_sum = [0] * 100005
i = n - 1
while (i >= 0):
right_sum[i] = right_sum[i + 1] + a[i]
if right_sum[i] == part:
c[i] = c[i + 1] + 1
else:
c[i] = c[i + 1]
i = i - 1
ret = 0
s = 0
for i in range(0, n):
s = s + a[i]
if (s == part):
ret = ret + c[i + 1]
print(ret)
solve()
``` | instruction | 0 | 67,578 | 7 | 135,156 |
No | output | 1 | 67,578 | 7 | 135,157 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One Martian boy called Zorg wants to present a string of beads to his friend from the Earth β Masha. He knows that Masha likes two colours: blue and red, β and right in the shop where he has come, there is a variety of adornments with beads of these two colours. All the strings of beads have a small fastener, and if one unfastens it, one might notice that all the strings of beads in the shop are of the same length. Because of the peculiarities of the Martian eyesight, if Zorg sees one blue-and-red string of beads first, and then the other with red beads instead of blue ones, and blue β instead of red, he regards these two strings of beads as identical. In other words, Zorg regards as identical not only those strings of beads that can be derived from each other by the string turnover, but as well those that can be derived from each other by a mutual replacement of colours and/or by the string turnover.
It is known that all Martians are very orderly, and if a Martian sees some amount of objects, he tries to put them in good order. Zorg thinks that a red bead is smaller than a blue one. Let's put 0 for a red bead, and 1 β for a blue one. From two strings the Martian puts earlier the string with a red bead in the i-th position, providing that the second string has a blue bead in the i-th position, and the first two beads i - 1 are identical.
At first Zorg unfastens all the strings of beads, and puts them into small heaps so, that in each heap strings are identical, in his opinion. Then he sorts out the heaps and chooses the minimum string in each heap, in his opinion. He gives the unnecassary strings back to the shop assistant and says he doesn't need them any more. Then Zorg sorts out the remaining strings of beads and buys the string with index k.
All these manupulations will take Zorg a lot of time, that's why he asks you to help and find the string of beads for Masha.
Input
The input file contains two integers n and k (2 β€ n β€ 50;1 β€ k β€ 1016) βthe length of a string of beads, and the index of the string, chosen by Zorg.
Output
Output the k-th string of beads, putting 0 for a red bead, and 1 β for a blue one. If it s impossible to find the required string, output the only number -1.
Examples
Input
4 4
Output
0101
Note
Let's consider the example of strings of length 4 β 0001, 0010, 0011, 0100, 0101, 0110, 0111, 1000, 1001, 1010, 1011, 1100, 1101, 1110. Zorg will divide them into heaps: {0001, 0111, 1000, 1110}, {0010, 0100, 1011, 1101}, {0011, 1100}, {0101, 1010}, {0110, 1001}. Then he will choose the minimum strings of beads in each heap: 0001, 0010, 0011, 0101, 0110. The forth string β 0101. | instruction | 0 | 67,843 | 7 | 135,686 |
Tags: dp, graphs
Correct Solution:
```
n, m = map(int, input().split())
m += 1
def calc(l, r, eq, eq_i):
if l > r:
return 1
key = l, eq, eq_i
if key in f:
return f[key]
t = 0
for x in (['0', '1'] if s[l] == '?' else [s[l]]):
if l == r:
a = [x]
else:
a = ['0', '1'] if s[r] == '?' else [s[r]]
for y in a:
if not((eq and x > y) or (eq_i and x == y == '1')):
t += calc(l + 1, r - 1, eq and x == y, eq_i and x != y)
f[key] = t
return t
s = ['?'] * n
for i in range(n):
s[i] = '0'
f = {}
p = calc(0, n - 1, True, True)
if m > p:
m -= p
s[i] = '1'
if s[0] == '0':
print(''.join(s))
else:
print(-1)
``` | output | 1 | 67,843 | 7 | 135,687 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One Martian boy called Zorg wants to present a string of beads to his friend from the Earth β Masha. He knows that Masha likes two colours: blue and red, β and right in the shop where he has come, there is a variety of adornments with beads of these two colours. All the strings of beads have a small fastener, and if one unfastens it, one might notice that all the strings of beads in the shop are of the same length. Because of the peculiarities of the Martian eyesight, if Zorg sees one blue-and-red string of beads first, and then the other with red beads instead of blue ones, and blue β instead of red, he regards these two strings of beads as identical. In other words, Zorg regards as identical not only those strings of beads that can be derived from each other by the string turnover, but as well those that can be derived from each other by a mutual replacement of colours and/or by the string turnover.
It is known that all Martians are very orderly, and if a Martian sees some amount of objects, he tries to put them in good order. Zorg thinks that a red bead is smaller than a blue one. Let's put 0 for a red bead, and 1 β for a blue one. From two strings the Martian puts earlier the string with a red bead in the i-th position, providing that the second string has a blue bead in the i-th position, and the first two beads i - 1 are identical.
At first Zorg unfastens all the strings of beads, and puts them into small heaps so, that in each heap strings are identical, in his opinion. Then he sorts out the heaps and chooses the minimum string in each heap, in his opinion. He gives the unnecassary strings back to the shop assistant and says he doesn't need them any more. Then Zorg sorts out the remaining strings of beads and buys the string with index k.
All these manupulations will take Zorg a lot of time, that's why he asks you to help and find the string of beads for Masha.
Input
The input file contains two integers n and k (2 β€ n β€ 50;1 β€ k β€ 1016) βthe length of a string of beads, and the index of the string, chosen by Zorg.
Output
Output the k-th string of beads, putting 0 for a red bead, and 1 β for a blue one. If it s impossible to find the required string, output the only number -1.
Examples
Input
4 4
Output
0101
Note
Let's consider the example of strings of length 4 β 0001, 0010, 0011, 0100, 0101, 0110, 0111, 1000, 1001, 1010, 1011, 1100, 1101, 1110. Zorg will divide them into heaps: {0001, 0111, 1000, 1110}, {0010, 0100, 1011, 1101}, {0011, 1100}, {0101, 1010}, {0110, 1001}. Then he will choose the minimum strings of beads in each heap: 0001, 0010, 0011, 0101, 0110. The forth string β 0101. | instruction | 0 | 67,844 | 7 | 135,688 |
Tags: dp, graphs
Correct Solution:
```
def raschot(d, e, g, h):
if d > e:
return 1
key = d, g, h
if key in b:
return b[key]
f = 0
for x in (['0', '1'] if a0[d] == '?' else [a0[d]]):
if d == e:
a = [x]
else:
a = ['0', '1'] if a0[e] == '?' else [a0[e]]
for y in a:
if not ((g and x > y) or (h and x == y == '1')):
f += raschot(d + 1, e - 1, g and x == y, h and x != y)
b[key] = f
return f
n, m = map(int, input().split())
m += 1
a0 = ['?'] * n
for i in range(n):
a0[i] = '0'
b = {}
c = raschot(0, n - 1, True, True)
if m > c:
m -= c
a0[i] = '1'
if a0[0] == '0':
print(''.join(a0))
else:
print(-1)
``` | output | 1 | 67,844 | 7 | 135,689 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One Martian boy called Zorg wants to present a string of beads to his friend from the Earth β Masha. He knows that Masha likes two colours: blue and red, β and right in the shop where he has come, there is a variety of adornments with beads of these two colours. All the strings of beads have a small fastener, and if one unfastens it, one might notice that all the strings of beads in the shop are of the same length. Because of the peculiarities of the Martian eyesight, if Zorg sees one blue-and-red string of beads first, and then the other with red beads instead of blue ones, and blue β instead of red, he regards these two strings of beads as identical. In other words, Zorg regards as identical not only those strings of beads that can be derived from each other by the string turnover, but as well those that can be derived from each other by a mutual replacement of colours and/or by the string turnover.
It is known that all Martians are very orderly, and if a Martian sees some amount of objects, he tries to put them in good order. Zorg thinks that a red bead is smaller than a blue one. Let's put 0 for a red bead, and 1 β for a blue one. From two strings the Martian puts earlier the string with a red bead in the i-th position, providing that the second string has a blue bead in the i-th position, and the first two beads i - 1 are identical.
At first Zorg unfastens all the strings of beads, and puts them into small heaps so, that in each heap strings are identical, in his opinion. Then he sorts out the heaps and chooses the minimum string in each heap, in his opinion. He gives the unnecassary strings back to the shop assistant and says he doesn't need them any more. Then Zorg sorts out the remaining strings of beads and buys the string with index k.
All these manupulations will take Zorg a lot of time, that's why he asks you to help and find the string of beads for Masha.
Input
The input file contains two integers n and k (2 β€ n β€ 50;1 β€ k β€ 1016) βthe length of a string of beads, and the index of the string, chosen by Zorg.
Output
Output the k-th string of beads, putting 0 for a red bead, and 1 β for a blue one. If it s impossible to find the required string, output the only number -1.
Examples
Input
4 4
Output
0101
Note
Let's consider the example of strings of length 4 β 0001, 0010, 0011, 0100, 0101, 0110, 0111, 1000, 1001, 1010, 1011, 1100, 1101, 1110. Zorg will divide them into heaps: {0001, 0111, 1000, 1110}, {0010, 0100, 1011, 1101}, {0011, 1100}, {0101, 1010}, {0110, 1001}. Then he will choose the minimum strings of beads in each heap: 0001, 0010, 0011, 0101, 0110. The forth string β 0101. | instruction | 0 | 67,845 | 7 | 135,690 |
Tags: dp, graphs
Correct Solution:
```
__author__ = 'Darren'
def solve():
def calc(lower, upper, record, eq, eq_i):
if lower > upper:
return 1
key = lower, eq, eq_i
if key in record:
return record[key]
t = 0
for x in (['0', '1'] if result[lower] == '?' else [result[lower]]):
temp = None
if lower == upper:
temp = [x]
elif result[upper] == '?':
temp = ['0', '1']
else:
temp = [result[upper]]
for y in temp:
if not ((eq and x > y) or (eq_i and x == y == '1')):
t += calc(lower+1, upper-1, record, eq and x == y,
eq_i and x != y)
record[key] = t
return t
n, k = map(int, input().split())
k += 1 # Suppose 00...0 is also valid
result = ['?'] * n
for i in range(n):
result[i] = '0'
passed = calc(0, n-1, {}, True, True)
if k > passed:
k -= passed
result[i] = '1'
if result[0] == '0':
print(''.join(result))
else:
print(-1)
if __name__ == '__main__':
solve()
``` | output | 1 | 67,845 | 7 | 135,691 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Lenny is playing a game on a 3 Γ 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on.
Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.
Input
The input consists of three rows. Each row contains three integers each between 0 to 100 inclusive. The j-th number in the i-th row is the number of times the j-th light of the i-th row of the grid is pressed.
Output
Print three lines, each containing three characters. The j-th character of the i-th line is "1" if and only if the corresponding light is switched on, otherwise it's "0".
Examples
Input
1 0 0
0 0 0
0 0 1
Output
001
010
100
Input
1 0 1
8 8 8
2 0 3
Output
010
011
100 | instruction | 0 | 68,413 | 7 | 136,826 |
Tags: implementation
Correct Solution:
```
l=[[0]*5]+[[0]+list(map(int,input().split()))+[0] for _ in range(3)]+[[0]*5]
ans=[['']*3 for _ in range(3)]
for i in range(1,4):
for j in range(1,4):
ans[i-1][j-1]=str(1-((l[i][j]+l[i][j-1]+l[i][j+1]+l[i-1][j]+l[i+1][j])%2))
print('\n'.join(map(''.join,ans)))
``` | output | 1 | 68,413 | 7 | 136,827 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Lenny is playing a game on a 3 Γ 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on.
Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.
Input
The input consists of three rows. Each row contains three integers each between 0 to 100 inclusive. The j-th number in the i-th row is the number of times the j-th light of the i-th row of the grid is pressed.
Output
Print three lines, each containing three characters. The j-th character of the i-th line is "1" if and only if the corresponding light is switched on, otherwise it's "0".
Examples
Input
1 0 0
0 0 0
0 0 1
Output
001
010
100
Input
1 0 1
8 8 8
2 0 3
Output
010
011
100 | instruction | 0 | 68,414 | 7 | 136,828 |
Tags: implementation
Correct Solution:
```
a=[['0','0','0'],['0','0','0'],['0','0','0']]
b=[]
for i in range(3):
x = input().strip().split()
x = [int(x[j]) for j in range(3)]
b.append(x)
if (b[0][0]+b[0][1]+b[1][0])%2 == 0:
a[0][0] = '1'
if (b[0][1]+b[1][1]+b[0][0]+b[0][2])%2 == 0:
a[0][1] = '1'
if (b[0][2]+b[1][2]+b[0][1])%2 == 0:
a[0][2] = '1'
if (b[1][0]+b[0][0]+b[2][0]+b[1][1])%2 == 0:
a[1][0] = '1'
if (b[1][1]+b[0][1]+b[1][0]+b[2][1]+b[1][2])%2 == 0:
a[1][1] = '1'
if (b[1][2]+b[0][2]+b[2][2]+b[1][1])%2 == 0:
a[1][2] = '1'
if (b[2][0]+b[2][1]+b[1][0])%2 == 0:
a[2][0] = '1'
if (b[2][1]+b[2][2]+b[2][0]+b[1][1])%2 == 0:
a[2][1] = '1'
if (b[2][2]+b[2][1]+b[1][2])%2 == 0:
a[2][2] = '1'
for i in range(3):
print(''.join(a[i]))
``` | output | 1 | 68,414 | 7 | 136,829 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Lenny is playing a game on a 3 Γ 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on.
Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.
Input
The input consists of three rows. Each row contains three integers each between 0 to 100 inclusive. The j-th number in the i-th row is the number of times the j-th light of the i-th row of the grid is pressed.
Output
Print three lines, each containing three characters. The j-th character of the i-th line is "1" if and only if the corresponding light is switched on, otherwise it's "0".
Examples
Input
1 0 0
0 0 0
0 0 1
Output
001
010
100
Input
1 0 1
8 8 8
2 0 3
Output
010
011
100 | instruction | 0 | 68,415 | 7 | 136,830 |
Tags: implementation
Correct Solution:
```
data = []
for _ in range(3):
data.append(list(map(lambda v: int(v) % 2, input().split())))
result = [[1 - data[i][j] for j in range(3)] for i in range(3)]
result[0][0] += (data[0][1] + data[1][0])
result[0][1] += (data[0][0] + data[0][2] + data[1][1])
result[0][2] += (data[0][1] + data[1][2])
result[1][0] += (data[0][0] + data[2][0] + data[1][1])
result[1][1] += (data[0][1] + data[2][1] + data[1][0] + data[1][2])
result[1][2] += (data[0][2] + data[2][2] + data[1][1])
result[2][0] += (data[1][0] + data[2][1])
result[2][1] += (data[2][0] + data[2][2] + data[1][1])
result[2][2] += (data[2][1] + data[1][2])
for row in result:
print(''.join(str(v % 2) for v in row))
``` | output | 1 | 68,415 | 7 | 136,831 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Lenny is playing a game on a 3 Γ 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on.
Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.
Input
The input consists of three rows. Each row contains three integers each between 0 to 100 inclusive. The j-th number in the i-th row is the number of times the j-th light of the i-th row of the grid is pressed.
Output
Print three lines, each containing three characters. The j-th character of the i-th line is "1" if and only if the corresponding light is switched on, otherwise it's "0".
Examples
Input
1 0 0
0 0 0
0 0 1
Output
001
010
100
Input
1 0 1
8 8 8
2 0 3
Output
010
011
100 | instruction | 0 | 68,416 | 7 | 136,832 |
Tags: implementation
Correct Solution:
```
arr_entrada = []
for i in range(0, 3):
arr_entrada.append(input())
rounds = [[0,0,0],[0,0,0],[0,0,0]]
results = [[True,True,True],[True,True,True],[True,True,True]]
for i in range(0 ,3):
for j in range(0, 3):
rounds[i][j] = int(arr_entrada[i].split()[j])
if (rounds[0][0]%2 != 0):
results[0][0] = not(results[0][0])
results[1][0] = not(results[1][0])
results[0][1] = not(results[0][1])
if (rounds[1][0]%2 != 0):
results[0][0] = not(results[0][0])
results[1][0] = not(results[1][0])
results[2][0] = not(results[2][0])
results[1][1] = not(results[1][1])
if (rounds[2][0]%2 != 0):
results[2][0] = not(results[2][0])
results[2][1] = not(results[2][1])
results[1][0] = not(results[1][0])
if (rounds[0][1]%2 != 0):
results[0][0] = not(results[0][0])
results[0][1] = not(results[0][1])
results[1][1] = not(results[1][1])
results[0][2] = not(results[0][2])
if (rounds[1][1]%2 != 0):
results[1][1] = not(results[1][1])
results[0][1] = not(results[0][1])
results[2][1] = not(results[2][1])
results[1][0] = not(results[1][0])
results[1][2] = not(results[1][2])
if (rounds[2][1]%2 != 0):
results[1][1] = not(results[1][1])
results[2][0] = not(results[2][0])
results[2][1] = not(results[2][1])
results[2][2] = not(results[2][2])
if (rounds[0][2]%2 != 0):
results[0][1] = not(results[0][1])
results[0][2] = not(results[0][2])
results[1][2] = not(results[1][2])
if (rounds[1][2]%2 != 0):
results[0][2] = not(results[0][2])
results[1][1] = not(results[1][1])
results[1][2] = not(results[1][2])
results[2][2] = not(results[2][2])
if (rounds[2][2]%2 != 0):
results[2][2] = not(results[2][2])
results[2][1] = not(results[2][1])
results[1][2] = not(results[1][2])
i = 0
while (i < 3):
j = 0
while (j < 3):
if (results[i][j] == True):
print(1, end="")
else:
print(0, end="")
j += 1
print("")
i += 1
``` | output | 1 | 68,416 | 7 | 136,833 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Lenny is playing a game on a 3 Γ 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on.
Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.
Input
The input consists of three rows. Each row contains three integers each between 0 to 100 inclusive. The j-th number in the i-th row is the number of times the j-th light of the i-th row of the grid is pressed.
Output
Print three lines, each containing three characters. The j-th character of the i-th line is "1" if and only if the corresponding light is switched on, otherwise it's "0".
Examples
Input
1 0 0
0 0 0
0 0 1
Output
001
010
100
Input
1 0 1
8 8 8
2 0 3
Output
010
011
100 | instruction | 0 | 68,417 | 7 | 136,834 |
Tags: implementation
Correct Solution:
```
arr_i = [list(map(int, input().split())), list(map(int, input().split())), list(map(int, input().split()))]
arr = [[1 for x in range(3)] for y in range(3)]
arr[0][0] = (arr_i[0][0] + arr_i[0][1] + arr_i[1][0] + 1) % 2
arr[0][1] = (arr_i[0][0] + arr_i[0][1] + arr_i[0][2] + arr_i[1][1] + 1) % 2
arr[0][2] = (arr_i[0][1] + arr_i[0][2] + arr_i[1][2] + 1) % 2
arr[1][0] = (arr_i[0][0] + arr_i[1][0] + arr_i[1][1] + arr_i[2][0] + 1) % 2
arr[1][1] = (arr_i[0][1] + arr_i[1][0] + arr_i[1][1] + arr_i[1][2] + arr_i[2][1] + 1) % 2
arr[1][2] = (arr_i[0][2] + arr_i[1][1] + arr_i[1][2] + arr_i[2][2] + 1) % 2
arr[2][0] = (arr_i[1][0] + arr_i[2][0] + arr_i[2][1] + 1) % 2
arr[2][1] = (arr_i[1][1] + arr_i[2][0] + arr_i[2][1] + arr_i[2][2] + 1) % 2
arr[2][2] = (arr_i[1][2] + arr_i[2][1] + arr_i[2][2] + 1) % 2
for i in range(3):
for j in range(3):
print(arr[i][j], end="")
print()
``` | output | 1 | 68,417 | 7 | 136,835 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Lenny is playing a game on a 3 Γ 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on.
Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.
Input
The input consists of three rows. Each row contains three integers each between 0 to 100 inclusive. The j-th number in the i-th row is the number of times the j-th light of the i-th row of the grid is pressed.
Output
Print three lines, each containing three characters. The j-th character of the i-th line is "1" if and only if the corresponding light is switched on, otherwise it's "0".
Examples
Input
1 0 0
0 0 0
0 0 1
Output
001
010
100
Input
1 0 1
8 8 8
2 0 3
Output
010
011
100 | instruction | 0 | 68,418 | 7 | 136,836 |
Tags: implementation
Correct Solution:
```
matrix = [[1,1,1],[1,1,1],[1,1,1]]
def is_valid_index(index):
return index >= 0 and index <= 2
def toggle_lights(row, col, toggle):
matrix[row][col] = 0 if (matrix[row][col] == 1 and toggle == 1) or (matrix[row][col] == 0 and toggle == 0) else 1
if is_valid_index(row-1):
matrix[row-1][col] = 0 if (matrix[row-1][col] == 1 and toggle == 1) or (matrix[row-1][col] == 0 and toggle == 0) else 1
if is_valid_index(row+1):
matrix[row+1][col] = 0 if (matrix[row+1][col] == 1 and toggle == 1) or (matrix[row+1][col] == 0 and toggle == 0) else 1
if is_valid_index(col-1):
matrix[row][col-1] = 0 if (matrix[row][col-1] == 1 and toggle == 1) or (matrix[row][col-1] == 0 and toggle == 0) else 1
if is_valid_index(col+1):
matrix[row][col+1] = 0 if (matrix[row][col+1] == 1 and toggle == 1) or (matrix[row][col+1] == 0 and toggle == 0) else 1
for row in range(3):
current_row = [int(x) for x in input().split()]
for col in range(3):
toggle = current_row[col] % 2
toggle_lights(row, col, toggle)
for row in range(3):
x = matrix[row]
print(''.join(str(elem) for elem in x))
``` | output | 1 | 68,418 | 7 | 136,837 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Lenny is playing a game on a 3 Γ 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on.
Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.
Input
The input consists of three rows. Each row contains three integers each between 0 to 100 inclusive. The j-th number in the i-th row is the number of times the j-th light of the i-th row of the grid is pressed.
Output
Print three lines, each containing three characters. The j-th character of the i-th line is "1" if and only if the corresponding light is switched on, otherwise it's "0".
Examples
Input
1 0 0
0 0 0
0 0 1
Output
001
010
100
Input
1 0 1
8 8 8
2 0 3
Output
010
011
100 | instruction | 0 | 68,419 | 7 | 136,838 |
Tags: implementation
Correct Solution:
```
arr=[]
arr.append(list(map(int,input().split())))
arr.append(list(map(int,input().split())))
arr.append(list(map(int,input().split())))
temp=[[0 for j in range(3)] for i in range(3)]
for i in range(3):
for j in range(3):
if(arr[i][j]>=1):
if(arr[i][j]%2!=0):
temp[i][j]+=1
if(i-1>=0):
temp[i-1][j]+=1
if(j+1<3):
temp[i][j+1]+=1
if(i+1<3):
temp[i+1][j]+=1
if(j-1>=0):
temp[i][j-1]+=1
for i in range(3):
for j in range(3):
if(temp[i][j]%2==0):
arr[i][j]=1
else:
arr[i][j]=0
for i in range(3):
for j in arr[i]:
print(j,end='')
print()
``` | output | 1 | 68,419 | 7 | 136,839 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Lenny is playing a game on a 3 Γ 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on.
Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.
Input
The input consists of three rows. Each row contains three integers each between 0 to 100 inclusive. The j-th number in the i-th row is the number of times the j-th light of the i-th row of the grid is pressed.
Output
Print three lines, each containing three characters. The j-th character of the i-th line is "1" if and only if the corresponding light is switched on, otherwise it's "0".
Examples
Input
1 0 0
0 0 0
0 0 1
Output
001
010
100
Input
1 0 1
8 8 8
2 0 3
Output
010
011
100 | instruction | 0 | 68,420 | 7 | 136,840 |
Tags: implementation
Correct Solution:
```
mat=[]
for i in range(3):
mat.append(list(map(int,input().split())))
for i in mat:
i.insert(0,0)
i.append(0)
mat.insert(0,[0,0,0,0,0])
mat.append([0,0,0,0,0])
ans=[]
for i in range(1,4):
temp=[]
for j in range(1,4):
temp.append(str(1-(mat[i][j]+mat[i-1][j]+mat[i+1][j]+mat[i][j-1]+mat[i][j+1])%2))
ans.append(temp)
for i in ans:
print("".join(i))
``` | output | 1 | 68,420 | 7 | 136,841 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Lenny is playing a game on a 3 Γ 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on.
Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.
Input
The input consists of three rows. Each row contains three integers each between 0 to 100 inclusive. The j-th number in the i-th row is the number of times the j-th light of the i-th row of the grid is pressed.
Output
Print three lines, each containing three characters. The j-th character of the i-th line is "1" if and only if the corresponding light is switched on, otherwise it's "0".
Examples
Input
1 0 0
0 0 0
0 0 1
Output
001
010
100
Input
1 0 1
8 8 8
2 0 3
Output
010
011
100
Submitted Solution:
```
m=[]
for x in range(3):
m.append([int(x)%2 for x in input().split()])
i=0
#print(m)
for i in range(3):
j=0
state=0
c_out=""
for j in range(3):
state = m[i][j]
if i!=0:
state+=m[i-1][j]
if i!=2:
state+=m[i+1][j]
if j!=0:
state+=m[i][j-1]
if j!=2:
state+=m[i][j+1]
if state%2:
c_out+="0"
else:
c_out+="1"
print(c_out)
``` | instruction | 0 | 68,421 | 7 | 136,842 |
Yes | output | 1 | 68,421 | 7 | 136,843 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Lenny is playing a game on a 3 Γ 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on.
Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.
Input
The input consists of three rows. Each row contains three integers each between 0 to 100 inclusive. The j-th number in the i-th row is the number of times the j-th light of the i-th row of the grid is pressed.
Output
Print three lines, each containing three characters. The j-th character of the i-th line is "1" if and only if the corresponding light is switched on, otherwise it's "0".
Examples
Input
1 0 0
0 0 0
0 0 1
Output
001
010
100
Input
1 0 1
8 8 8
2 0 3
Output
010
011
100
Submitted Solution:
```
l = []
for _ in range(3):
l.append([int(x) for x in input().split()])
g = [[0,0,0], [0,0,0], [0,0,0]]
for i in range(3):
for j in range(3):
if i+1 <= 2:
g[i+1][j] += l[i][j]
if i-1 >= 0:
g[i-1][j] += l[i][j]
if j+1 <= 2:
g[i][j+1] += l[i][j]
if j-1 >= 0:
g[i][j-1] += l[i][j]
g[i][j] += l[i][j]
ans = ''
for p in range(3):
if p > 0:
ans += '\n'
for q in range(3):
if g[p][q] % 2 == 0:
ans += '1'
else:
ans += '0'
print(ans)
``` | instruction | 0 | 68,422 | 7 | 136,844 |
Yes | output | 1 | 68,422 | 7 | 136,845 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Lenny is playing a game on a 3 Γ 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on.
Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.
Input
The input consists of three rows. Each row contains three integers each between 0 to 100 inclusive. The j-th number in the i-th row is the number of times the j-th light of the i-th row of the grid is pressed.
Output
Print three lines, each containing three characters. The j-th character of the i-th line is "1" if and only if the corresponding light is switched on, otherwise it's "0".
Examples
Input
1 0 0
0 0 0
0 0 1
Output
001
010
100
Input
1 0 1
8 8 8
2 0 3
Output
010
011
100
Submitted Solution:
```
a = []
b = []
for i in range(3):
t = input().split()
a.append([int(t[0]), int(t[1]), int(t[2]) ] )
b.append([1, 1, 1])
def add(i, j, w):
if 2>=i>=0 and 2>=j>=0:
b[i][j] += w
for i in range(3):
for j in range(3):
add(i, j, a[i][j])
add(i-1, j, a[i][j])
add(i+1, j, a[i][j])
add(i, j+1, a[i][j])
add(i, j-1, a[i][j])
for i in range(3):
print ( ''.join( map(str, [ [0,1][b[i][j]%2 ] for j in range(3) ] ) ) )
``` | instruction | 0 | 68,423 | 7 | 136,846 |
Yes | output | 1 | 68,423 | 7 | 136,847 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Lenny is playing a game on a 3 Γ 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on.
Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.
Input
The input consists of three rows. Each row contains three integers each between 0 to 100 inclusive. The j-th number in the i-th row is the number of times the j-th light of the i-th row of the grid is pressed.
Output
Print three lines, each containing three characters. The j-th character of the i-th line is "1" if and only if the corresponding light is switched on, otherwise it's "0".
Examples
Input
1 0 0
0 0 0
0 0 1
Output
001
010
100
Input
1 0 1
8 8 8
2 0 3
Output
010
011
100
Submitted Solution:
```
a,b,c=map(int,input().split())
x,y,z=map(int,input().split())
i,j,k=map(int,input().split())
a1=x+b+a
b1=a+b+c+y
c1=b+z+c
x1=a+x+y+i
y1=b+y+j+x+z
z1=y+z+k+c
i1=x+j+i
j1=i+y+j+k
k1=j+z+k
arr=[a1,b1,c1,x1,y1,z1,i1,j1,k1]
brr=[]
for i in range(len(arr)):
if arr[i]%2==0:
brr.append('1')
else:
brr.append('0')
print(brr[0]+brr[1]+brr[2])
print(brr[3]+brr[4]+brr[5])
print(brr[6]+brr[7]+brr[8])
``` | instruction | 0 | 68,424 | 7 | 136,848 |
Yes | output | 1 | 68,424 | 7 | 136,849 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Lenny is playing a game on a 3 Γ 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on.
Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.
Input
The input consists of three rows. Each row contains three integers each between 0 to 100 inclusive. The j-th number in the i-th row is the number of times the j-th light of the i-th row of the grid is pressed.
Output
Print three lines, each containing three characters. The j-th character of the i-th line is "1" if and only if the corresponding light is switched on, otherwise it's "0".
Examples
Input
1 0 0
0 0 0
0 0 1
Output
001
010
100
Input
1 0 1
8 8 8
2 0 3
Output
010
011
100
Submitted Solution:
```
def change(b):
a=[[True for i in range(3)] for j in range(3)]
for i in range(0,3):
for j in range(0,3):
while (b[i][j]):
a[i][j]=not a[i][j]
a[(i+1)%3][j]=not a[(i+1)%3][j]
a[(i+2)%3][j]=not a[(i+2)%3][j]
a[i][(j+1)%3]=not a[i][(j+1)%3]
a[i][(j+2)%3]=not a[i][(j+2)%3]
b[i][j]=b[i][j]-1
for i in range(0,3):
for j in range(0,3):
if (a[i][j]==True):
a[i][j]='1'
else:
a[i][j]='0'
return a
b=[]
for i in range(0,3):
c=[(int(j)%2) for j in input().split()]
b.append(c)
a=change(b)
for i in range(0,3):
print(''.join(a[i]))
``` | instruction | 0 | 68,425 | 7 | 136,850 |
No | output | 1 | 68,425 | 7 | 136,851 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Lenny is playing a game on a 3 Γ 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on.
Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.
Input
The input consists of three rows. Each row contains three integers each between 0 to 100 inclusive. The j-th number in the i-th row is the number of times the j-th light of the i-th row of the grid is pressed.
Output
Print three lines, each containing three characters. The j-th character of the i-th line is "1" if and only if the corresponding light is switched on, otherwise it's "0".
Examples
Input
1 0 0
0 0 0
0 0 1
Output
001
010
100
Input
1 0 1
8 8 8
2 0 3
Output
010
011
100
Submitted Solution:
```
def dfs(grid, x, y):
if [x, y] == [0, 0]:
toggle(x+1,y)
toggle(x,y+1)
if [x, y] == [0, 1]:
toggle(x,y-1)
toggle(x+1,y)
toggle(x,y+1)
if [x, y] == [0, 2]:
toggle(x,y-1)
toggle(x+1,y)
if [x, y] == [1, 0]:
toggle(x-1,y)
toggle(x+1, y)
toggle(x, y+1)
if [x, y] == [1, 1]:
toggle(x-1, y)
toggle(x, y-1)
toggle(x+1, y)
grid[x][y+1] = toggle(x, y+1)
if [x, y] == [1, 2]:
toggle(x-1, y)
toggle(x, y-1)
toggle(x+1, y)
if [x, y] == [2, 0]:
toggle(x-1 , y)
toggle(x, y+1)
if [x, y] == [2, 1]:
toggle(x-1, y)
toggle(x, y-1)
toggle(x, y+1)
if [x, y] == [2, 2]:
toggle(x-1 , y)
toggle(x , y-1)
toggle(x, y)
def toggle(x, y):
if result[x][y] == 1:
result[x][y] = 0
else:
result[x][y] = 1
grid = []
result = []
for i in range(3):
grid.append([int(x) for x in input().split()])
result.append([1 for x in range(3)])
for row in range(3):
for col in range(3):
if grid[row][col] == 0:
continue
val = grid[row][col]
if val % 2 == 0:
continue
else:
dfs(grid, row, col)
for row in range(3):
for col in range(3):
print(result[row][col], end=" ")
print()
``` | instruction | 0 | 68,426 | 7 | 136,852 |
No | output | 1 | 68,426 | 7 | 136,853 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Lenny is playing a game on a 3 Γ 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on.
Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.
Input
The input consists of three rows. Each row contains three integers each between 0 to 100 inclusive. The j-th number in the i-th row is the number of times the j-th light of the i-th row of the grid is pressed.
Output
Print three lines, each containing three characters. The j-th character of the i-th line is "1" if and only if the corresponding light is switched on, otherwise it's "0".
Examples
Input
1 0 0
0 0 0
0 0 1
Output
001
010
100
Input
1 0 1
8 8 8
2 0 3
Output
010
011
100
Submitted Solution:
```
def arr_inp():
return [int(x) for x in input().split()]
def arr_2d(n, m):
return [[1 for x in range(m)] for i in range(n)]
def print_arr(arr):
print(*arr, sep=' ')
matrix = arr_2d(3, 3)
for i in range(3):
x = arr_inp()
for j in range(3):
if (x[j] % 2):
if (j > 0):
matrix[i][j - 1] = 1 - (matrix[i][j - 1])
if (j < 2):
matrix[i][j + 1] = 1 - (matrix[i][j + 1])
if (i > 0):
matrix[i - 1][j] = 1 - (matrix[i - 1][j])
if (i < 2):
matrix[i + 1][j] = 1 - (matrix[i + 1][j])
matrix[i][j] = 1 - (matrix[i][j])
for i in range(3):
print_arr(matrix[i])
``` | instruction | 0 | 68,427 | 7 | 136,854 |
No | output | 1 | 68,427 | 7 | 136,855 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Lenny is playing a game on a 3 Γ 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on.
Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.
Input
The input consists of three rows. Each row contains three integers each between 0 to 100 inclusive. The j-th number in the i-th row is the number of times the j-th light of the i-th row of the grid is pressed.
Output
Print three lines, each containing three characters. The j-th character of the i-th line is "1" if and only if the corresponding light is switched on, otherwise it's "0".
Examples
Input
1 0 0
0 0 0
0 0 1
Output
001
010
100
Input
1 0 1
8 8 8
2 0 3
Output
010
011
100
Submitted Solution:
```
l = [["1" for x in range(3)] for p in range(3)]
i = [[x for x in map(int, input().split())] for t in range(3)]
for indx1,num in enumerate(i):
for indx2,num1 in enumerate(num):
if num1 % 2 != 0 and num1 != 0:
if l[indx1][indx2] == "1":
l[indx1][indx2] = "O"
else:
l[indx1][indx2] = "1"
if indx2 + 1 in [0,1,2]:
if l[indx1][indx2 + 1] == "1":
l[indx1][indx2 + 1] = "O"
else:
l[indx1][indx2 + 1] = "1"
if indx2 - 1 in [0,1,2]:
if l[indx1][indx2 - 1] == "1":
l[indx1][indx2 - 1] = "O"
else:
l[indx1][indx2 - 1] = "1"
if indx1 + 1 in [0,1,2]:
if l[indx1 + 1][indx2] == "1":
l[indx1 + 1][indx2] = "O"
else:
l[indx1 + 1][indx2] = "1"
if indx1 - 1 in [0,1,2]:
if l[indx1 - 1][indx2] == "1":
l[indx1 - 1][indx2] = "O"
else:
l[indx1 - 1][indx2] = "1"
for t in l:
for tt in t:
print(tt,end='')
print('')
``` | instruction | 0 | 68,428 | 7 | 136,856 |
No | output | 1 | 68,428 | 7 | 136,857 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp has arranged n colored marbles in a row. The color of the i-th marble is a_i. Monocarp likes ordered things, so he wants to rearrange marbles in such a way that all marbles of the same color form a contiguos segment (and there is only one such segment for each color).
In other words, Monocarp wants to rearrange marbles so that, for every color j, if the leftmost marble of color j is l-th in the row, and the rightmost marble of this color has position r in the row, then every marble from l to r has color j.
To achieve his goal, Monocarp can do the following operation any number of times: choose two neighbouring marbles, and swap them.
You have to calculate the minimum number of operations Monocarp has to perform to rearrange the marbles. Note that the order of segments of marbles having equal color does not matter, it is only required that, for every color, all the marbles of this color form exactly one contiguous segment.
Input
The first line contains one integer n (2 β€ n β€ 4 β
10^5) β the number of marbles.
The second line contains an integer sequence a_1, a_2, ..., a_n (1 β€ a_i β€ 20), where a_i is the color of the i-th marble.
Output
Print the minimum number of operations Monocarp has to perform to achieve his goal.
Examples
Input
7
3 4 2 3 4 2 2
Output
3
Input
5
20 1 14 10 2
Output
0
Input
13
5 5 4 4 3 5 7 6 5 4 4 6 5
Output
21
Note
In the first example three operations are enough. Firstly, Monocarp should swap the third and the fourth marbles, so the sequence of colors is [3, 4, 3, 2, 4, 2, 2]. Then Monocarp should swap the second and the third marbles, so the sequence is [3, 3, 4, 2, 4, 2, 2]. And finally, Monocarp should swap the fourth and the fifth marbles, so the sequence is [3, 3, 4, 4, 2, 2, 2].
In the second example there's no need to perform any operations. | instruction | 0 | 69,019 | 7 | 138,038 |
Tags: bitmasks, dp
Correct Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import ceil
def prod(a, mod=10 ** 9 + 7):
ans = 1
for each in a:
ans = (ans * each) % mod
return ans
def gcd(x, y):
while y:
x, y = y, x % y
return x
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
from collections import deque
for _ in range(int(input()) if not True else 1):
n = int(input())
# n, k = map(int, input().split())
# a, b = map(int, input().split())
# c, d = map(int, input().split())
a = list(map(int, input().split()))
indexes = [[] for i in range(21)]
for i in range(n):
indexes[a[i]] += [i]
pos = True
for i in range(1, 21):
if indexes[i]:
if indexes[i] != list(range(indexes[i][0], indexes[i][0] + len(indexes[i]))):
pos = False
break
if pos:
print(0)
continue
n = 0
for i in range(1, 21):
if indexes[i]:
indexes[n] = list(indexes[i])
n += 1
for x in indexes[n-1]:a[x] = n
moves = [[0] * n for i in range(n)]
count = [0.0] * (n + 1)
for i in range(len(a)):
for j in range(1, n+1):
moves[a[i]-1][j-1] += count[j]
count[a[i]] += 1
dp = [float('inf')] * (1 << n)
dp[0] = 0
for mask in range(1 << n):
unsetbits = [i for i in range(n) if not mask & (1 << i)]
for i in unsetbits:
# put color i before other colors
res = mask | (1 << i)
total = sum(moves[i][j] for j in unsetbits) - moves[i][i]
dp[res] = min(dp[res], dp[mask] + total)
print(int(dp[-1]))
``` | output | 1 | 69,019 | 7 | 138,039 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp has arranged n colored marbles in a row. The color of the i-th marble is a_i. Monocarp likes ordered things, so he wants to rearrange marbles in such a way that all marbles of the same color form a contiguos segment (and there is only one such segment for each color).
In other words, Monocarp wants to rearrange marbles so that, for every color j, if the leftmost marble of color j is l-th in the row, and the rightmost marble of this color has position r in the row, then every marble from l to r has color j.
To achieve his goal, Monocarp can do the following operation any number of times: choose two neighbouring marbles, and swap them.
You have to calculate the minimum number of operations Monocarp has to perform to rearrange the marbles. Note that the order of segments of marbles having equal color does not matter, it is only required that, for every color, all the marbles of this color form exactly one contiguous segment.
Input
The first line contains one integer n (2 β€ n β€ 4 β
10^5) β the number of marbles.
The second line contains an integer sequence a_1, a_2, ..., a_n (1 β€ a_i β€ 20), where a_i is the color of the i-th marble.
Output
Print the minimum number of operations Monocarp has to perform to achieve his goal.
Examples
Input
7
3 4 2 3 4 2 2
Output
3
Input
5
20 1 14 10 2
Output
0
Input
13
5 5 4 4 3 5 7 6 5 4 4 6 5
Output
21
Note
In the first example three operations are enough. Firstly, Monocarp should swap the third and the fourth marbles, so the sequence of colors is [3, 4, 3, 2, 4, 2, 2]. Then Monocarp should swap the second and the third marbles, so the sequence is [3, 3, 4, 2, 4, 2, 2]. And finally, Monocarp should swap the fourth and the fifth marbles, so the sequence is [3, 3, 4, 4, 2, 2, 2].
In the second example there's no need to perform any operations. | instruction | 0 | 69,020 | 7 | 138,040 |
Tags: bitmasks, dp
Correct Solution:
```
n = int(input())
a = [int(x) for x in input().split()]
d = {}
for i in range(1, 21):
for j in range(1, 21):
d[(i, j)] = 0
cv = [0 for i in range(21)]
for j in a:
for i in range(1, 21):
d[(i, j)] += cv[i]
cv[j] += 1
s = 0
for i in range(1, 21):
for j in range(i+1, 21):
s += min(d[(i, j)], d[(j, i)])
print(s)
``` | output | 1 | 69,020 | 7 | 138,041 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp has arranged n colored marbles in a row. The color of the i-th marble is a_i. Monocarp likes ordered things, so he wants to rearrange marbles in such a way that all marbles of the same color form a contiguos segment (and there is only one such segment for each color).
In other words, Monocarp wants to rearrange marbles so that, for every color j, if the leftmost marble of color j is l-th in the row, and the rightmost marble of this color has position r in the row, then every marble from l to r has color j.
To achieve his goal, Monocarp can do the following operation any number of times: choose two neighbouring marbles, and swap them.
You have to calculate the minimum number of operations Monocarp has to perform to rearrange the marbles. Note that the order of segments of marbles having equal color does not matter, it is only required that, for every color, all the marbles of this color form exactly one contiguous segment.
Input
The first line contains one integer n (2 β€ n β€ 4 β
10^5) β the number of marbles.
The second line contains an integer sequence a_1, a_2, ..., a_n (1 β€ a_i β€ 20), where a_i is the color of the i-th marble.
Output
Print the minimum number of operations Monocarp has to perform to achieve his goal.
Examples
Input
7
3 4 2 3 4 2 2
Output
3
Input
5
20 1 14 10 2
Output
0
Input
13
5 5 4 4 3 5 7 6 5 4 4 6 5
Output
21
Note
In the first example three operations are enough. Firstly, Monocarp should swap the third and the fourth marbles, so the sequence of colors is [3, 4, 3, 2, 4, 2, 2]. Then Monocarp should swap the second and the third marbles, so the sequence is [3, 3, 4, 2, 4, 2, 2]. And finally, Monocarp should swap the fourth and the fifth marbles, so the sequence is [3, 3, 4, 4, 2, 2, 2].
In the second example there's no need to perform any operations. | instruction | 0 | 69,021 | 7 | 138,042 |
Tags: bitmasks, dp
Correct Solution:
```
import sys
n = int(sys.stdin.readline().strip())
a = list(map(int, sys.stdin.readline().strip().split()))
M = [[0 for i in range (0, 21)] for j in range (0, 21)]
F = [0 for i in range (0, 21)]
for i in range (0, n):
x = int(a[i])
for j in range (0, 21):
if j != x:
M[j][x] = M[j][x] + F[j]
F[x] = F[x] + 1
ans = 0
for i in range (0, 21):
for j in range (0, i):
ans = ans + min(M[i][j], M[j][i])
print(ans)
``` | output | 1 | 69,021 | 7 | 138,043 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp has arranged n colored marbles in a row. The color of the i-th marble is a_i. Monocarp likes ordered things, so he wants to rearrange marbles in such a way that all marbles of the same color form a contiguos segment (and there is only one such segment for each color).
In other words, Monocarp wants to rearrange marbles so that, for every color j, if the leftmost marble of color j is l-th in the row, and the rightmost marble of this color has position r in the row, then every marble from l to r has color j.
To achieve his goal, Monocarp can do the following operation any number of times: choose two neighbouring marbles, and swap them.
You have to calculate the minimum number of operations Monocarp has to perform to rearrange the marbles. Note that the order of segments of marbles having equal color does not matter, it is only required that, for every color, all the marbles of this color form exactly one contiguous segment.
Input
The first line contains one integer n (2 β€ n β€ 4 β
10^5) β the number of marbles.
The second line contains an integer sequence a_1, a_2, ..., a_n (1 β€ a_i β€ 20), where a_i is the color of the i-th marble.
Output
Print the minimum number of operations Monocarp has to perform to achieve his goal.
Examples
Input
7
3 4 2 3 4 2 2
Output
3
Input
5
20 1 14 10 2
Output
0
Input
13
5 5 4 4 3 5 7 6 5 4 4 6 5
Output
21
Note
In the first example three operations are enough. Firstly, Monocarp should swap the third and the fourth marbles, so the sequence of colors is [3, 4, 3, 2, 4, 2, 2]. Then Monocarp should swap the second and the third marbles, so the sequence is [3, 3, 4, 2, 4, 2, 2]. And finally, Monocarp should swap the fourth and the fifth marbles, so the sequence is [3, 3, 4, 4, 2, 2, 2].
In the second example there's no need to perform any operations.
Submitted Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import ceil
def prod(a, mod=10 ** 9 + 7):
ans = 1
for each in a:
ans = (ans * each) % mod
return ans
def gcd(x, y):
while y:
x, y = y, x % y
return x
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
from collections import deque
for _ in range(int(input()) if not True else 1):
n = int(input())
# n, k = map(int, input().split())
# a, b = map(int, input().split())
# c, d = map(int, input().split())
a = list(map(int, input().split()))
indexes = [[] for i in range(21)]
for i in range(n):
indexes[a[i]] += [i]
n = 0
for i in range(1, 21):
if indexes[i]:
indexes[n] = list(indexes[i])
n += 1
moves = [[0] * n for i in range(n)]
for i in range(n):
for j in range(n):
# put i before j
count = 0
p, q = 0, 0
while p != len(indexes[i]):
if q == len(indexes[j]) or indexes[i][p] < indexes[j][q]:
p += 1
count += q
else:
q += 1
moves[i][j] = count
dp = [10**9] * (1 << n)
dp[0] = 0
queue = deque([0])
while queue:
mask = queue.popleft()
for i in range(n):
if not mask & (1 << i):
# put color i before other colors
total = sum(moves[i][j] for j in range(n) if not mask & (1 << j) and i != j)
dp[mask ^ (1 << i)] = min(dp[mask ^ (1 << i)], dp[mask] + total)
queue += [mask ^ (1<< i)]
print(dp[-1])
``` | instruction | 0 | 69,022 | 7 | 138,044 |
No | output | 1 | 69,022 | 7 | 138,045 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have to paint with shades of grey the tiles of an nΓ n wall. The wall has n rows of tiles, each with n tiles.
The tiles on the boundary of the wall (i.e., on the first row, last row, first column and last column) are already painted and you shall not change their color. All the other tiles are not painted. Some of the tiles are broken, you shall not paint those tiles. It is guaranteed that the tiles on the boundary are not broken.
You shall paint all the non-broken tiles that are not already painted. When you paint a tile you can choose from 10^9 shades of grey, indexed from 1 to 10^9. You can paint multiple tiles with the same shade. Formally, painting the wall is equivalent to assigning a shade (an integer between 1 and 10^9) to each non-broken tile that is not already painted.
The contrast between two tiles is the absolute value of the difference between the shades of the two tiles. The total contrast of the wall is the sum of the contrast of all the pairs of adjacent non-broken tiles (two tiles are adjacent if they share a side).
Compute the minimum possible total contrast of the wall.
Input
The first line contains n (3β€ nβ€ 200) β the number of rows and columns.
Then n lines, each containing n integers, follow. The i-th of these lines describe the i-th row of tiles. It contains the n integers a_{ij} (-1β€ a_{ij} β€ 10^9). The value of a_{ij} described the tile on the i-th row and j-th column:
* If a_{ij}=0, then the tile is not painted and shall be painted.
* If a_{ij}=-1, then the tile is broken and shall not be painted.
* If 1β€ a_{ij}β€ 10^9, then the tile is already painted with the shade a_{ij}.
It is guaranteed that the tiles on the boundary are already painted, the tiles not on the boundary are not already painted, and the tiles on the boundary are not broken.
Output
Print a single integer β the minimum possible total contrast of the wall.
Examples
Input
3
1 7 6
4 0 6
1 1 1
Output
26
Input
3
10 100 1
1 -1 100
10 10 10
Output
396
Input
5
6 6 5 4 4
6 0 0 0 4
7 0 0 0 3
8 0 0 0 2
8 8 1 2 2
Output
34
Input
7
315055237 841510063 581663979 148389224 405375301 243686840 882512379
683199716 -1 -1 0 0 0 346177625
496442279 0 0 0 0 0 815993623
223938231 0 0 -1 0 0 16170511
44132173 0 -1 0 0 0 130735659
212201259 0 0 -1 0 0 166102576
123213235 506794677 467013743 410119347 791447348 80193382 142887538
Output
10129482893
Note
Explanation of the first testcase: The initial configuration of the tiles is (tiles to paint are denoted by ?):
1 7 6
4 ? 6
1 1 1
A possible way to paint the tile achieving the minimum possible contrast of 26 is:
1 7 6
4 5 6
1 1 1
Explanation of the second testcase: Since all tiles are either painted or broken, there is nothing to do. The total contrast is 396.
Explanation of the third testcase: The initial configuration of the tiles is (tiles to paint are denoted by ?):
6 6 5 4 4
6 ? ? ? 4
7 ? ? ? 3
8 ? ? ? 2
8 8 1 2 2
A possible way to paint the tiles achieving the minimum possible contrast of 34 is:
6 6 5 4 4
6 6 5 4 4
7 7 5 3 3
8 8 2 2 2
8 8 1 2 2
Submitted Solution:
```
import math as mp
while True :
n=int(input())
if (n>=3) and (n<=200) :
break
y=[]
for i in range(n) :
test=True
while True :
l=input().split(' ')
for m in l :
if (int(m)<(-1)) or (int(m)>(10**9)) :
test=False
if (i==0) or (i==(n-1)):
for s in l :
if int(s)==0 :
test=False
if (i>=1) and (i<=n-2) :
if (int(l[0])==0) or (int(l[n-1]==0)) :
test=False
if test==True :
break
y.append(l)
for t in range(n) :
for k in range(n):
if int(y[t][k])==0 :
y[t][k]=1
v1=abs(int(y[t][k])-int(y[t][k-1]))+abs(int(y[t-1][k])-int(y[t][k]))
while True :
y[t][k]+=1
v2=abs(int(y[t][k])-int(y[t][k-1]))+abs(int(y[t-1][k])-int(y[t][k]))
if (v2<v1) and (y[t][k]<=10**9) :
v1=v2
else:
y[t][k]-=1
break
con=0
for i in range(n):
for j in range(n-1):
if (int(y[i][j])!=-1) and (int(y[i][j+1])!=-1) :
con+=abs(int(y[i][j])-int(y[i][j+1]))
for i in range(n-1):
for j in range(n):
if (int(y[i][j])!=-1) and (int(y[i+1][j])!=-1) :
con+=abs(int(y[i][j])-int(y[i+1][j]))
print(con)
``` | instruction | 0 | 69,152 | 7 | 138,304 |
No | output | 1 | 69,152 | 7 | 138,305 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is an infinite board of square tiles. Initially all tiles are white.
Vova has a red marker and a blue marker. Red marker can color a tiles. Blue marker can color b tiles. If some tile isn't white then you can't use marker of any color on it. Each marker must be drained completely, so at the end there should be exactly a red tiles and exactly b blue tiles across the board.
Vova wants to color such a set of tiles that:
* they would form a rectangle, consisting of exactly a+b colored tiles;
* all tiles of at least one color would also form a rectangle.
Here are some examples of correct colorings:
<image>
Here are some examples of incorrect colorings:
<image>
Among all correct colorings Vova wants to choose the one with the minimal perimeter. What is the minimal perimeter Vova can obtain?
It is guaranteed that there exists at least one correct coloring.
Input
A single line contains two integers a and b (1 β€ a, b β€ 10^{14}) β the number of tiles red marker should color and the number of tiles blue marker should color, respectively.
Output
Print a single integer β the minimal perimeter of a colored rectangle Vova can obtain by coloring exactly a tiles red and exactly b tiles blue.
It is guaranteed that there exists at least one correct coloring.
Examples
Input
4 4
Output
12
Input
3 9
Output
14
Input
9 3
Output
14
Input
3 6
Output
12
Input
506 2708
Output
3218
Note
The first four examples correspond to the first picture of the statement.
Note that for there exist multiple correct colorings for all of the examples.
In the first example you can also make a rectangle with sides 1 and 8, though its perimeter will be 18 which is greater than 8.
In the second example you can make the same resulting rectangle with sides 3 and 4, but red tiles will form the rectangle with sides 1 and 3 and blue tiles will form the rectangle with sides 3 and 3. | instruction | 0 | 69,824 | 7 | 139,648 |
Tags: binary search, brute force, math, number theory
Correct Solution:
```
import math
import time
D = False
def b_search(lst, num, row, col, ab):
H = len(lst) - 1
L = 0
while L <= H:
M = (L + H)//2
if D: print(lst[M], row, ab/lst[M], col)
if D: print("cond:", lst[M] <= row, num/lst[M] <= col)
if lst[M] <= row and num/lst[M] <= col:
return True
if lst[M] > row:
H = M - 1
else:
L = M + 1
return False
def binary_search(lst1, a, lst2, b, row, col, ab):
# we need to know if any rect in lst1 or lst2
# can fix inside the dimensions of row, col
# in this case, row <= col, and
# item in lst are <= their pair
if b_search(lst1, a, row, col, ab):
return True
return b_search(lst2, b, row, col, ab)
def divisors(num):
rtn = []
for i in range(1, math.ceil(math.sqrt(num)) + 1):
if num % i == 0:
rtn.append(i)
return rtn
def sol():
a, b = [int(x) for x in input().split(" ")]
ab = a + b
if D: print("")
if D: print("a, b, ab:", a, b, ab)
div_a = divisors(a)
div_b = divisors(b)
div_ab = divisors(ab)
if D:
print("div_a: " + ", ".join([str(x) for x in div_a]))
print("div_b: " + ", ".join([str(x) for x in div_b]))
print("div_ab: " + ", ".join([str(x) for x in div_ab]))
for i in range(len(div_ab) - 1, -1, -1):
row = div_ab[i]
col = int(ab/row)
if D: print("\n* Trying")
if D: print("row, col:", row, col)
ans = binary_search(div_a, a, div_b, b, row, col, ab)
if ans:
return 2 * (row + col)
if D: start = time.time()
# main
#for t in range(int(input())):
ans = int(sol())
print(ans)
if D:
end = time.time()
print(end - start)
``` | output | 1 | 69,824 | 7 | 139,649 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is an infinite board of square tiles. Initially all tiles are white.
Vova has a red marker and a blue marker. Red marker can color a tiles. Blue marker can color b tiles. If some tile isn't white then you can't use marker of any color on it. Each marker must be drained completely, so at the end there should be exactly a red tiles and exactly b blue tiles across the board.
Vova wants to color such a set of tiles that:
* they would form a rectangle, consisting of exactly a+b colored tiles;
* all tiles of at least one color would also form a rectangle.
Here are some examples of correct colorings:
<image>
Here are some examples of incorrect colorings:
<image>
Among all correct colorings Vova wants to choose the one with the minimal perimeter. What is the minimal perimeter Vova can obtain?
It is guaranteed that there exists at least one correct coloring.
Input
A single line contains two integers a and b (1 β€ a, b β€ 10^{14}) β the number of tiles red marker should color and the number of tiles blue marker should color, respectively.
Output
Print a single integer β the minimal perimeter of a colored rectangle Vova can obtain by coloring exactly a tiles red and exactly b tiles blue.
It is guaranteed that there exists at least one correct coloring.
Examples
Input
4 4
Output
12
Input
3 9
Output
14
Input
9 3
Output
14
Input
3 6
Output
12
Input
506 2708
Output
3218
Note
The first four examples correspond to the first picture of the statement.
Note that for there exist multiple correct colorings for all of the examples.
In the first example you can also make a rectangle with sides 1 and 8, though its perimeter will be 18 which is greater than 8.
In the second example you can make the same resulting rectangle with sides 3 and 4, but red tiles will form the rectangle with sides 1 and 3 and blue tiles will form the rectangle with sides 3 and 3. | instruction | 0 | 69,825 | 7 | 139,650 |
Tags: binary search, brute force, math, number theory
Correct Solution:
```
import sys
from collections import Counter,defaultdict,deque
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def make_divisors(n):
divisors = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n//i)
divisors.sort()
return divisors
a,b = inpl()
st = []
for z in [a,b]:
tmp = make_divisors(z)
for i in range(len(tmp)//2+1):
s = tmp[i]; t = z//s
st.append([s,t])
ttt = make_divisors(a+b)
for i in range(len(ttt)//2+1)[::-1]:
y = ttt[i]
x = (a+b)//y
# print(x,y)
for s,t in st:
if x >= t and y >= s:
print(2*(x+y))
quit()
``` | output | 1 | 69,825 | 7 | 139,651 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.