text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In 20XX AD, a school competition was held. The tournament has finally left only the final competition. You are one of the athletes in the competition.
The competition you participate in is to compete for the time it takes to destroy all the blue objects placed in the space. Athletes are allowed to bring in competition guns. In the space, there are multiple blue objects, the same number of red objects, and multiple obstacles. There is a one-to-one correspondence between the blue object and the red object, and the blue object must be destroyed by shooting a bullet at the blue object from the coordinates where the red object is placed. The obstacles placed in the space are spherical and the composition is slightly different, but if it is a normal bullet, the bullet will stop there when it touches the obstacle.
The bullet used in the competition is a special bullet called Magic Bullet. This bullet can store magical power, and when the bullet touches an obstacle, it automatically consumes the magical power, and the magic that the bullet penetrates is activated. Due to the difference in the composition of obstacles, the amount of magic required to penetrate and the amount of magic power consumed to activate it are different. Therefore, even after the magic for one obstacle is activated, it is necessary to activate another magic in order to penetrate another obstacle. Also, if the bullet touches multiple obstacles at the same time, magic will be activated at the same time. The amount of magical power contained in the bullet decreases with each magic activation.
While the position and size of obstacles and the amount of magical power required to activate the penetrating magic have already been disclosed, the positions of the red and blue objects have not been disclosed. However, the position of the object could be predicted to some extent from the information of the same competition in the past. You want to save as much magical power as you can, because putting magical power into a bullet is very exhausting. Therefore, assuming the position of the red object and the corresponding blue object, the minimum amount of magical power required to be loaded in the bullet at that time, that is, the magical power remaining in the bullet when reaching the blue object is 0. Let's find the amount of magical power that becomes.
Constraints
* 0 β€ N β€ 50
* 1 β€ Q β€ 50
* -500 β€ xi, yi, zi β€ 500
* 1 β€ ri β€ 1,000
* 1 β€ li β€ 1016
* -500 β€ sxj, syj, szj β€ 500
* -500 β€ dxj, dyj, dzj β€ 500
* Obstacles are never stuck in other obstacles
* The coordinates of the object are not inside or on the surface of the obstacle
* Under each assumption, the coordinates of the red object and the blue object do not match.
Input
All inputs are integers. Each number is separated by a single space.
N Q
x1 y1 z1 r1 l1
::
xN yN zN rN lN
sx1 sy1 sz1 dx1 dy1 dz1
::
sxQ syQ szQ dxQ dyQ dzQ
* N is the number of obstacles, and Q is the number of coordinates of the assumed blue and red objects.
* xi, yi, and zi are the x-coordinate, y-coordinate, and z-coordinate that represent the position of the center of the i-th obstacle, respectively.
* ri is the radius of the i-th obstacle.
* li is the amount of magical power consumed by magic to penetrate the i-th obstacle.
* sxj, syj, and szj are the x-coordinate, y-coordinate, and z-coordinate that represent the position of the red object in the jth assumption, respectively.
* dxj, dyj, and dzj are the x-coordinate, y-coordinate, and z-coordinate that represent the position of the blue object in the jth assumption, respectively.
Output
Assuming the position of each pair of red objects and the corresponding blue objects, the amount of magical power to be loaded in the bullet is output on one line, assuming that there are only obstacles, red objects, and one pair of blue objects in space. Let's do it. The bullet is supposed to fly in a straight line from the position of the red object to the position of the blue object, and since the size of the bullet is very small, it is treated as a point.
Examples
Input
5 1
0 10 0 5 2
0 20 0 5 12
0 30 0 5 22
0 40 0 5 32
0 50 0 5 42
0 0 0 0 60 0
Output
110
Input
1 1
10 5 0 5 9
0 0 0 9 12 0
Output
9
Input
5 5
-38 -71 -293 75 1
-158 -38 -405 66 1
-236 -303 157 266 1
316 26 411 190 1
207 -312 -27 196 1
-50 292 -375 -401 389 -389
460 278 409 -329 -303 411
215 -220 -200 309 -474 300
261 -494 -87 -300 123 -463
386 378 486 -443 -64 299
Output
0
2
1
3
0
Submitted Solution:
```
from math import sin, acos
N, Q = map(int, input().split())
obs = [tuple(map(int, input().split())) for _ in range(N)]
def dist(v):
return sum(x ** 2 for x in v)
def cos(v1, v2):
return sum(x * y for x, y in zip(v1, v2)) / pow(dist(v1), 0.5) / pow(dist(v2), 0.5)
for _ in range(Q):
sx, sy, sz, dx, dy, dz = map(int, input().split())
v_oa = (dx - sx, dy - sy, dz - sz)
ans = 0
for x, y, z, r, l in obs:
v_or = (x - sx, y - sy, z - sz)
# print(pow(dist(v_or), 0.5), sin(acos(cos(v_or, v_oa))), abs(pow(dist(v_or), 0.5) * sin(acos(cos(v_or, v_oa)))), r + 1e-9)
if cos(v_or, v_oa) >= 0 and abs(pow(dist(v_or), 0.5) * sin(acos(cos(v_or, v_oa)))) <= r + 1e-9:
ans += l
print(ans)
```
No
| 93,500 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In 20XX AD, a school competition was held. The tournament has finally left only the final competition. You are one of the athletes in the competition.
The competition you participate in is to compete for the time it takes to destroy all the blue objects placed in the space. Athletes are allowed to bring in competition guns. In the space, there are multiple blue objects, the same number of red objects, and multiple obstacles. There is a one-to-one correspondence between the blue object and the red object, and the blue object must be destroyed by shooting a bullet at the blue object from the coordinates where the red object is placed. The obstacles placed in the space are spherical and the composition is slightly different, but if it is a normal bullet, the bullet will stop there when it touches the obstacle.
The bullet used in the competition is a special bullet called Magic Bullet. This bullet can store magical power, and when the bullet touches an obstacle, it automatically consumes the magical power, and the magic that the bullet penetrates is activated. Due to the difference in the composition of obstacles, the amount of magic required to penetrate and the amount of magic power consumed to activate it are different. Therefore, even after the magic for one obstacle is activated, it is necessary to activate another magic in order to penetrate another obstacle. Also, if the bullet touches multiple obstacles at the same time, magic will be activated at the same time. The amount of magical power contained in the bullet decreases with each magic activation.
While the position and size of obstacles and the amount of magical power required to activate the penetrating magic have already been disclosed, the positions of the red and blue objects have not been disclosed. However, the position of the object could be predicted to some extent from the information of the same competition in the past. You want to save as much magical power as you can, because putting magical power into a bullet is very exhausting. Therefore, assuming the position of the red object and the corresponding blue object, the minimum amount of magical power required to be loaded in the bullet at that time, that is, the magical power remaining in the bullet when reaching the blue object is 0. Let's find the amount of magical power that becomes.
Constraints
* 0 β€ N β€ 50
* 1 β€ Q β€ 50
* -500 β€ xi, yi, zi β€ 500
* 1 β€ ri β€ 1,000
* 1 β€ li β€ 1016
* -500 β€ sxj, syj, szj β€ 500
* -500 β€ dxj, dyj, dzj β€ 500
* Obstacles are never stuck in other obstacles
* The coordinates of the object are not inside or on the surface of the obstacle
* Under each assumption, the coordinates of the red object and the blue object do not match.
Input
All inputs are integers. Each number is separated by a single space.
N Q
x1 y1 z1 r1 l1
::
xN yN zN rN lN
sx1 sy1 sz1 dx1 dy1 dz1
::
sxQ syQ szQ dxQ dyQ dzQ
* N is the number of obstacles, and Q is the number of coordinates of the assumed blue and red objects.
* xi, yi, and zi are the x-coordinate, y-coordinate, and z-coordinate that represent the position of the center of the i-th obstacle, respectively.
* ri is the radius of the i-th obstacle.
* li is the amount of magical power consumed by magic to penetrate the i-th obstacle.
* sxj, syj, and szj are the x-coordinate, y-coordinate, and z-coordinate that represent the position of the red object in the jth assumption, respectively.
* dxj, dyj, and dzj are the x-coordinate, y-coordinate, and z-coordinate that represent the position of the blue object in the jth assumption, respectively.
Output
Assuming the position of each pair of red objects and the corresponding blue objects, the amount of magical power to be loaded in the bullet is output on one line, assuming that there are only obstacles, red objects, and one pair of blue objects in space. Let's do it. The bullet is supposed to fly in a straight line from the position of the red object to the position of the blue object, and since the size of the bullet is very small, it is treated as a point.
Examples
Input
5 1
0 10 0 5 2
0 20 0 5 12
0 30 0 5 22
0 40 0 5 32
0 50 0 5 42
0 0 0 0 60 0
Output
110
Input
1 1
10 5 0 5 9
0 0 0 9 12 0
Output
9
Input
5 5
-38 -71 -293 75 1
-158 -38 -405 66 1
-236 -303 157 266 1
316 26 411 190 1
207 -312 -27 196 1
-50 292 -375 -401 389 -389
460 278 409 -329 -303 411
215 -220 -200 309 -474 300
261 -494 -87 -300 123 -463
386 378 486 -443 -64 299
Output
0
2
1
3
0
Submitted Solution:
```
from math import sin, acos
N, Q = map(int, input().split())
obs = [tuple(map(int, input().split())) for _ in range(N)]
def dist(v):
return sum(x ** 2 for x in v)
def cos(v1, v2):
return sum(x * y for x, y in zip(v1, v2)) / pow(dist(v1), 0.5) / pow(dist(v2), 0.5)
for _ in range(Q):
sx, sy, sz, dx, dy, dz = map(int, input().split())
v_oa = (dx - sx, dy - sy, dz - sz)
ans = 0
for x, y, z, r, l in obs:
v_or = (x - sx, y - sy, z - sz)
# print(pow(dist(v_or), 0.5), sin(acos(cos(v_or, v_oa))), abs(pow(dist(v_or), 0.5) * sin(acos(cos(v_or, v_oa)))), r + 1e-9)
if abs(pow(dist(v_or), 0.5) * sin(acos(cos(v_or, v_oa)))) <= r + 1e-9:
ans += l
print(ans)
```
No
| 93,501 |
Provide a correct Python 3 solution for this coding contest problem.
Problem statement
You and AOR Ika are preparing for a graph problem in competitive programming. Generating input cases is AOR Ika-chan's job. The input case for that problem is a directed graph of the $ N $ vertices. The vertices are numbered from $ 1 $ to $ N $. Edges may contain self-loops, but not multiple edges.
However, AOR Ika suddenly lost communication and couldn't get the original graph. All that remains is the following information:
* The number of vertices with degree $ i $ is $ a_i $. That is, the number of vertices ending in $ i $ is $ a_i $.
* The number of vertices with degree $ i $ is $ b_i $. That is, the number of vertices starting from $ i $ is $ b_i $.
Is there a directed graph that is consistent with the information left behind? Judge it, output YES if it exists, and then output one consistent directed graph. If there are more than one, any one may be output. If it does not exist, output NO.
Input constraints
$ 1 \ leq n \ leq 50 $
$ 0 \ leq a_i \ leq n $
$ 0 \ leq b_i \ leq n $
sample
Sample input 1
3
1 2 0 0
1 2 0 0
Sample output 1
YES YES
0 1 0
0 0 1
0 0 0
Sample input 2
1
Ten
Ten
Sample output 2
YES YES
0
Sample input 3
2
0 2 0
0 2 0
Sample output 3
YES YES
0 1
Ten
Sample input 4
Four
1 3 0 0 0
3 0 0 1 0
Sample output 4
YES YES
0 1 1 1
0 0 0 0
0 0 0 0
0 0 0 0
Sample input 5
1
1 1
0 0
Sample output 5
NO
input
$ n $
$ a_0 \ cdots a_n $
$ b_0 \ cdots b_n $
output
If there is a graph that meets the conditions, output it in the following format. $ e_ {ij} $ should be 1 if there is a directed edge from $ i $ to $ j $, or 0 otherwise. Be careful not to print a blank at the end of the line.
YES YES
$ e_ {11} \ e_ {12} \ cdots e_ {1n} $
$ e_ {21} \ e_ {22} \ cdots e_ {2n} $
$ \ vdots $
$ e_ {n1} \ e_ {n2} \ cdots e_ {nn} $
If not, output as follows.
NO
Example
Input
3
1 2 0 0
1 2 0 0
Output
YES
0 1 0
0 0 1
0 0 0
"Correct Solution:
```
from operator import itemgetter
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
cnt_a = 0
cnt_b = 0
for i, (a, b) in enumerate(zip(A, B)):
cnt_a += i*a
cnt_b += i*b
if cnt_a!=cnt_b or not sum(A)==sum(B)==N:
print("NO")
exit()
B_ = []
cumi = 0
for i, b in enumerate(B):
for j in range(b):
B_.append([cumi, i])
cumi += 1
B_.sort(key=itemgetter(1), reverse=True)
Ans = [[0]*N for _ in range(N)]
cumi = 0
for i, a in enumerate(A[1:], 1):
if len(B_) < i:
print("NO")
exit()
for k in range(a):
for j in range(i):
B_[j][1] -= 1
if B_[j][1] < 0:
print("NO")
exit()
Ans[B_[j][0]][cumi] = 1
cumi += 1
B_.sort(key=itemgetter(1), reverse=True)
print("YES")
for ans in Ans:
print(*ans)
```
| 93,502 |
Provide a correct Python 3 solution for this coding contest problem.
A: Information Search
problem
The posting list is a list in which there is a correspondence between the search term and the appearing document ID. For example
* Hokkaido: 1, 2, 4, 9
* Sightseeing: 1, 3, 4, 7
And so on.
From the above posting list, if you search for and, the document with ID 1, 4 will be hit, and if you search for or, ID 1, 2, 3, 4, 7, 9 will be hit.
Here, and search means "listing elements contained in either list", or search means "listing elements contained in at least one of the lists".
Since the posting list is given, output the results of and search and or search respectively.
Input format
n m
a_1 a_2 $ \ ldots $ a_n
b_1 b_2 $ \ ldots $ b_m
All inputs consist of integers.
The first line gives the lengths n and m of the two posting lists to search, separated by spaces.
The second and third lines are given the IDs contained in their respective posting lists, separated by blanks.
Constraint
* 1 \ leq n, m \ leq 2 \ times 10 ^ 5
* a_i <a_j (i <j)
* b_i <b_j (i <j)
* 1 \ leq a_i, b_i \ leq 10 ^ 9
Output format
Let A be the number of hits in the and search, and B be the number of hits in the or search.
Print on the first line in the order A B, separated by blanks.
Output the IDs hit by and search on the following line A in ascending order.
Output the IDs hit by or search on the following B line in ascending order.
Input example 1
4 4
1 2 4 9
1 3 4 7
Output example 1
2 6
1
Four
1
2
3
Four
7
9
Input example 2
4 4
1 3 5 7
2 4 6 8
Output example 2
0 8
1
2
3
Four
Five
6
7
8
Input example 3
3 5
one two Three
1 2 3 4 5
Output example 3
3 5
1
2
3
1
2
3
Four
Five
Example
Input
4 4
1 2 4 9
1 3 4 7
Output
2 6
1
4
1
2
3
4
7
9
"Correct Solution:
```
n,m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
and_list = set(a) & set(b)
or_list = (set(a) ^ set(b)) ^ set(and_list)
print(len(and_list), len(or_list))
for i in sorted(and_list):
print(i)
for i in sorted(or_list):
print(i)
```
| 93,503 |
Provide a correct Python 3 solution for this coding contest problem.
A: Information Search
problem
The posting list is a list in which there is a correspondence between the search term and the appearing document ID. For example
* Hokkaido: 1, 2, 4, 9
* Sightseeing: 1, 3, 4, 7
And so on.
From the above posting list, if you search for and, the document with ID 1, 4 will be hit, and if you search for or, ID 1, 2, 3, 4, 7, 9 will be hit.
Here, and search means "listing elements contained in either list", or search means "listing elements contained in at least one of the lists".
Since the posting list is given, output the results of and search and or search respectively.
Input format
n m
a_1 a_2 $ \ ldots $ a_n
b_1 b_2 $ \ ldots $ b_m
All inputs consist of integers.
The first line gives the lengths n and m of the two posting lists to search, separated by spaces.
The second and third lines are given the IDs contained in their respective posting lists, separated by blanks.
Constraint
* 1 \ leq n, m \ leq 2 \ times 10 ^ 5
* a_i <a_j (i <j)
* b_i <b_j (i <j)
* 1 \ leq a_i, b_i \ leq 10 ^ 9
Output format
Let A be the number of hits in the and search, and B be the number of hits in the or search.
Print on the first line in the order A B, separated by blanks.
Output the IDs hit by and search on the following line A in ascending order.
Output the IDs hit by or search on the following B line in ascending order.
Input example 1
4 4
1 2 4 9
1 3 4 7
Output example 1
2 6
1
Four
1
2
3
Four
7
9
Input example 2
4 4
1 3 5 7
2 4 6 8
Output example 2
0 8
1
2
3
Four
Five
6
7
8
Input example 3
3 5
one two Three
1 2 3 4 5
Output example 3
3 5
1
2
3
1
2
3
Four
Five
Example
Input
4 4
1 2 4 9
1 3 4 7
Output
2 6
1
4
1
2
3
4
7
9
"Correct Solution:
```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
------------------------
author : iiou16
------------------------
'''
def main():
n, m = list(map(int, input().split()))
A = list(map(int, input().split()))
A = set(A)
B = list(map(int, input().split()))
B = set(B)
intersection = A & B
union = A | B
print(len(intersection), len(union))
for i in sorted(list(intersection)):
print(i)
for u in sorted(list(union)):
print(u)
if __name__ == '__main__':
main()
```
| 93,504 |
Provide a correct Python 3 solution for this coding contest problem.
A: Information Search
problem
The posting list is a list in which there is a correspondence between the search term and the appearing document ID. For example
* Hokkaido: 1, 2, 4, 9
* Sightseeing: 1, 3, 4, 7
And so on.
From the above posting list, if you search for and, the document with ID 1, 4 will be hit, and if you search for or, ID 1, 2, 3, 4, 7, 9 will be hit.
Here, and search means "listing elements contained in either list", or search means "listing elements contained in at least one of the lists".
Since the posting list is given, output the results of and search and or search respectively.
Input format
n m
a_1 a_2 $ \ ldots $ a_n
b_1 b_2 $ \ ldots $ b_m
All inputs consist of integers.
The first line gives the lengths n and m of the two posting lists to search, separated by spaces.
The second and third lines are given the IDs contained in their respective posting lists, separated by blanks.
Constraint
* 1 \ leq n, m \ leq 2 \ times 10 ^ 5
* a_i <a_j (i <j)
* b_i <b_j (i <j)
* 1 \ leq a_i, b_i \ leq 10 ^ 9
Output format
Let A be the number of hits in the and search, and B be the number of hits in the or search.
Print on the first line in the order A B, separated by blanks.
Output the IDs hit by and search on the following line A in ascending order.
Output the IDs hit by or search on the following B line in ascending order.
Input example 1
4 4
1 2 4 9
1 3 4 7
Output example 1
2 6
1
Four
1
2
3
Four
7
9
Input example 2
4 4
1 3 5 7
2 4 6 8
Output example 2
0 8
1
2
3
Four
Five
6
7
8
Input example 3
3 5
one two Three
1 2 3 4 5
Output example 3
3 5
1
2
3
1
2
3
Four
Five
Example
Input
4 4
1 2 4 9
1 3 4 7
Output
2 6
1
4
1
2
3
4
7
9
"Correct Solution:
```
n, m = map(int, input().split())
a = set(map(int, input().split()))
b = set(map(int, input().split()))
a_and_b = list(a & b)
a_or_b = list(a | b)
a_and_b.sort()
a_or_b.sort()
print(len(a_and_b), len(a_or_b))
for p in a_and_b:
print(p)
for q in a_or_b:
print(q)
```
| 93,505 |
Provide a correct Python 3 solution for this coding contest problem.
A: Information Search
problem
The posting list is a list in which there is a correspondence between the search term and the appearing document ID. For example
* Hokkaido: 1, 2, 4, 9
* Sightseeing: 1, 3, 4, 7
And so on.
From the above posting list, if you search for and, the document with ID 1, 4 will be hit, and if you search for or, ID 1, 2, 3, 4, 7, 9 will be hit.
Here, and search means "listing elements contained in either list", or search means "listing elements contained in at least one of the lists".
Since the posting list is given, output the results of and search and or search respectively.
Input format
n m
a_1 a_2 $ \ ldots $ a_n
b_1 b_2 $ \ ldots $ b_m
All inputs consist of integers.
The first line gives the lengths n and m of the two posting lists to search, separated by spaces.
The second and third lines are given the IDs contained in their respective posting lists, separated by blanks.
Constraint
* 1 \ leq n, m \ leq 2 \ times 10 ^ 5
* a_i <a_j (i <j)
* b_i <b_j (i <j)
* 1 \ leq a_i, b_i \ leq 10 ^ 9
Output format
Let A be the number of hits in the and search, and B be the number of hits in the or search.
Print on the first line in the order A B, separated by blanks.
Output the IDs hit by and search on the following line A in ascending order.
Output the IDs hit by or search on the following B line in ascending order.
Input example 1
4 4
1 2 4 9
1 3 4 7
Output example 1
2 6
1
Four
1
2
3
Four
7
9
Input example 2
4 4
1 3 5 7
2 4 6 8
Output example 2
0 8
1
2
3
Four
Five
6
7
8
Input example 3
3 5
one two Three
1 2 3 4 5
Output example 3
3 5
1
2
3
1
2
3
Four
Five
Example
Input
4 4
1 2 4 9
1 3 4 7
Output
2 6
1
4
1
2
3
4
7
9
"Correct Solution:
```
#!usr/bin/env python3
from collections import defaultdict
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
l = [None for i in range(n)]
for i in range(n):l[i] = I()
return l
def LIR(n):
l = [None for i in range(n)]
for i in range(n):l[i] = LI()
return l
def SR(n):
l = [None for i in range(n)]
for i in range(n):l[i] = S()
return l
def LSR(n):
l = [None for i in range(n)]
for i in range(n):l[i] = SR()
return l
mod = 1000000007
#A
n,m = LI()
a = LI()
b = LI()
li = list(set(a)|set(b))
li2 = list(set(a)&set(b))
li.sort()
li2.sort()
print(len(li2),len(li))
for i in li2:
print(i)
for i in li:
print(i)
#B
#C
#D
#E
#F
#G
#H
#I
#J
#K
#L
#M
#N
#O
#P
#Q
#R
#S
#T
```
| 93,506 |
Provide a correct Python 3 solution for this coding contest problem.
A: Information Search
problem
The posting list is a list in which there is a correspondence between the search term and the appearing document ID. For example
* Hokkaido: 1, 2, 4, 9
* Sightseeing: 1, 3, 4, 7
And so on.
From the above posting list, if you search for and, the document with ID 1, 4 will be hit, and if you search for or, ID 1, 2, 3, 4, 7, 9 will be hit.
Here, and search means "listing elements contained in either list", or search means "listing elements contained in at least one of the lists".
Since the posting list is given, output the results of and search and or search respectively.
Input format
n m
a_1 a_2 $ \ ldots $ a_n
b_1 b_2 $ \ ldots $ b_m
All inputs consist of integers.
The first line gives the lengths n and m of the two posting lists to search, separated by spaces.
The second and third lines are given the IDs contained in their respective posting lists, separated by blanks.
Constraint
* 1 \ leq n, m \ leq 2 \ times 10 ^ 5
* a_i <a_j (i <j)
* b_i <b_j (i <j)
* 1 \ leq a_i, b_i \ leq 10 ^ 9
Output format
Let A be the number of hits in the and search, and B be the number of hits in the or search.
Print on the first line in the order A B, separated by blanks.
Output the IDs hit by and search on the following line A in ascending order.
Output the IDs hit by or search on the following B line in ascending order.
Input example 1
4 4
1 2 4 9
1 3 4 7
Output example 1
2 6
1
Four
1
2
3
Four
7
9
Input example 2
4 4
1 3 5 7
2 4 6 8
Output example 2
0 8
1
2
3
Four
Five
6
7
8
Input example 3
3 5
one two Three
1 2 3 4 5
Output example 3
3 5
1
2
3
1
2
3
Four
Five
Example
Input
4 4
1 2 4 9
1 3 4 7
Output
2 6
1
4
1
2
3
4
7
9
"Correct Solution:
```
N, M = map(int, input().split())
A = set(map(int, input().split()))
B = set(map(int, input().split()))
AandB = sorted(A & B)
AorB = sorted(A | B)
print(len(AandB), len(AorB))
for x in AandB:
print(x)
for x in AorB:
print(x)
```
| 93,507 |
Provide a correct Python 3 solution for this coding contest problem.
A: Information Search
problem
The posting list is a list in which there is a correspondence between the search term and the appearing document ID. For example
* Hokkaido: 1, 2, 4, 9
* Sightseeing: 1, 3, 4, 7
And so on.
From the above posting list, if you search for and, the document with ID 1, 4 will be hit, and if you search for or, ID 1, 2, 3, 4, 7, 9 will be hit.
Here, and search means "listing elements contained in either list", or search means "listing elements contained in at least one of the lists".
Since the posting list is given, output the results of and search and or search respectively.
Input format
n m
a_1 a_2 $ \ ldots $ a_n
b_1 b_2 $ \ ldots $ b_m
All inputs consist of integers.
The first line gives the lengths n and m of the two posting lists to search, separated by spaces.
The second and third lines are given the IDs contained in their respective posting lists, separated by blanks.
Constraint
* 1 \ leq n, m \ leq 2 \ times 10 ^ 5
* a_i <a_j (i <j)
* b_i <b_j (i <j)
* 1 \ leq a_i, b_i \ leq 10 ^ 9
Output format
Let A be the number of hits in the and search, and B be the number of hits in the or search.
Print on the first line in the order A B, separated by blanks.
Output the IDs hit by and search on the following line A in ascending order.
Output the IDs hit by or search on the following B line in ascending order.
Input example 1
4 4
1 2 4 9
1 3 4 7
Output example 1
2 6
1
Four
1
2
3
Four
7
9
Input example 2
4 4
1 3 5 7
2 4 6 8
Output example 2
0 8
1
2
3
Four
Five
6
7
8
Input example 3
3 5
one two Three
1 2 3 4 5
Output example 3
3 5
1
2
3
1
2
3
Four
Five
Example
Input
4 4
1 2 4 9
1 3 4 7
Output
2 6
1
4
1
2
3
4
7
9
"Correct Solution:
```
n, m = [int(i) for i in input().split()]
a = {int(i) for i in input().split()}
b = {int(i) for i in input().split()}
A = a & b
B = a | b
print('{} {}'.format(len(A),len(B)))
for a in sorted(A):
print(a)
for b in sorted(B):
print(b)
```
| 93,508 |
Provide a correct Python 3 solution for this coding contest problem.
A: Information Search
problem
The posting list is a list in which there is a correspondence between the search term and the appearing document ID. For example
* Hokkaido: 1, 2, 4, 9
* Sightseeing: 1, 3, 4, 7
And so on.
From the above posting list, if you search for and, the document with ID 1, 4 will be hit, and if you search for or, ID 1, 2, 3, 4, 7, 9 will be hit.
Here, and search means "listing elements contained in either list", or search means "listing elements contained in at least one of the lists".
Since the posting list is given, output the results of and search and or search respectively.
Input format
n m
a_1 a_2 $ \ ldots $ a_n
b_1 b_2 $ \ ldots $ b_m
All inputs consist of integers.
The first line gives the lengths n and m of the two posting lists to search, separated by spaces.
The second and third lines are given the IDs contained in their respective posting lists, separated by blanks.
Constraint
* 1 \ leq n, m \ leq 2 \ times 10 ^ 5
* a_i <a_j (i <j)
* b_i <b_j (i <j)
* 1 \ leq a_i, b_i \ leq 10 ^ 9
Output format
Let A be the number of hits in the and search, and B be the number of hits in the or search.
Print on the first line in the order A B, separated by blanks.
Output the IDs hit by and search on the following line A in ascending order.
Output the IDs hit by or search on the following B line in ascending order.
Input example 1
4 4
1 2 4 9
1 3 4 7
Output example 1
2 6
1
Four
1
2
3
Four
7
9
Input example 2
4 4
1 3 5 7
2 4 6 8
Output example 2
0 8
1
2
3
Four
Five
6
7
8
Input example 3
3 5
one two Three
1 2 3 4 5
Output example 3
3 5
1
2
3
1
2
3
Four
Five
Example
Input
4 4
1 2 4 9
1 3 4 7
Output
2 6
1
4
1
2
3
4
7
9
"Correct Solution:
```
n,m=map(int,input().split())
a = list(map(int,input().split()))+[1000000001]
b = list(map(int,input().split()))+[1000000001]
andlis=[]
orlis=[]
cura=0
curb=0
for _ in range(n+m):
if a[cura]>b[curb]:
orlis.append(b[curb])
curb+=1
elif a[cura]==b[curb]:
andlis.append(a[cura])
cura+=1
elif a[cura]<b[curb]:
orlis.append(a[cura])
cura+=1
print(len(andlis),len(orlis))
for i in andlis:
print(i)
for i in orlis:
print(i)
```
| 93,509 |
Provide a correct Python 3 solution for this coding contest problem.
A: Information Search
problem
The posting list is a list in which there is a correspondence between the search term and the appearing document ID. For example
* Hokkaido: 1, 2, 4, 9
* Sightseeing: 1, 3, 4, 7
And so on.
From the above posting list, if you search for and, the document with ID 1, 4 will be hit, and if you search for or, ID 1, 2, 3, 4, 7, 9 will be hit.
Here, and search means "listing elements contained in either list", or search means "listing elements contained in at least one of the lists".
Since the posting list is given, output the results of and search and or search respectively.
Input format
n m
a_1 a_2 $ \ ldots $ a_n
b_1 b_2 $ \ ldots $ b_m
All inputs consist of integers.
The first line gives the lengths n and m of the two posting lists to search, separated by spaces.
The second and third lines are given the IDs contained in their respective posting lists, separated by blanks.
Constraint
* 1 \ leq n, m \ leq 2 \ times 10 ^ 5
* a_i <a_j (i <j)
* b_i <b_j (i <j)
* 1 \ leq a_i, b_i \ leq 10 ^ 9
Output format
Let A be the number of hits in the and search, and B be the number of hits in the or search.
Print on the first line in the order A B, separated by blanks.
Output the IDs hit by and search on the following line A in ascending order.
Output the IDs hit by or search on the following B line in ascending order.
Input example 1
4 4
1 2 4 9
1 3 4 7
Output example 1
2 6
1
Four
1
2
3
Four
7
9
Input example 2
4 4
1 3 5 7
2 4 6 8
Output example 2
0 8
1
2
3
Four
Five
6
7
8
Input example 3
3 5
one two Three
1 2 3 4 5
Output example 3
3 5
1
2
3
1
2
3
Four
Five
Example
Input
4 4
1 2 4 9
1 3 4 7
Output
2 6
1
4
1
2
3
4
7
9
"Correct Solution:
```
import sys
sys.setrecursionlimit(int(1e7))
from collections import deque
def inpl(): return list(map(int, input().split()))
input()
A = set(inpl())
B = set(inpl())
ands = sorted(A&B)
ors = sorted(A|B)
print(len(ands), len(ors))
if len(ands):
print(*ands,sep="\n")
if len(ors):
print(*ors, sep="\n")
```
| 93,510 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A: Information Search
problem
The posting list is a list in which there is a correspondence between the search term and the appearing document ID. For example
* Hokkaido: 1, 2, 4, 9
* Sightseeing: 1, 3, 4, 7
And so on.
From the above posting list, if you search for and, the document with ID 1, 4 will be hit, and if you search for or, ID 1, 2, 3, 4, 7, 9 will be hit.
Here, and search means "listing elements contained in either list", or search means "listing elements contained in at least one of the lists".
Since the posting list is given, output the results of and search and or search respectively.
Input format
n m
a_1 a_2 $ \ ldots $ a_n
b_1 b_2 $ \ ldots $ b_m
All inputs consist of integers.
The first line gives the lengths n and m of the two posting lists to search, separated by spaces.
The second and third lines are given the IDs contained in their respective posting lists, separated by blanks.
Constraint
* 1 \ leq n, m \ leq 2 \ times 10 ^ 5
* a_i <a_j (i <j)
* b_i <b_j (i <j)
* 1 \ leq a_i, b_i \ leq 10 ^ 9
Output format
Let A be the number of hits in the and search, and B be the number of hits in the or search.
Print on the first line in the order A B, separated by blanks.
Output the IDs hit by and search on the following line A in ascending order.
Output the IDs hit by or search on the following B line in ascending order.
Input example 1
4 4
1 2 4 9
1 3 4 7
Output example 1
2 6
1
Four
1
2
3
Four
7
9
Input example 2
4 4
1 3 5 7
2 4 6 8
Output example 2
0 8
1
2
3
Four
Five
6
7
8
Input example 3
3 5
one two Three
1 2 3 4 5
Output example 3
3 5
1
2
3
1
2
3
Four
Five
Example
Input
4 4
1 2 4 9
1 3 4 7
Output
2 6
1
4
1
2
3
4
7
9
Submitted Solution:
```
n,m = map(int,input().split())
a = set(map(int,input().split()))
b = set(map(int,input().split()))
i = sorted(a&b)
u = sorted(a|b)
print(len(i),len(u))
for x in i:
print(x)
for x in u:
print(x)
```
Yes
| 93,511 |
Provide a correct Python 3 solution for this coding contest problem.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$.
* get($key$): Print the value with the specified $key$. Print 0 if there is no such element.
* delete($key$): Delete the element with the specified $key$.
* dump($L$, $R$): Print all elements formed by a pair of the key and the value such that the key is greater than or equal to $L$ and less than or equal to $R$ in lexicographic order.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consists of lower-case letters
* $L \leq R$ in lexicographic order
* The total number of elements printed by dump operations does not exceed $1,000,000$
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
or
2 $key$
or
3 $L$ $R$
where the first digits 0, 1, 2 and 3 represent insert, get, delete and dump operations.
Output
For each get operation, print the corresponding value.
For each dump operation, print the corresponding elements formed by a pair of the key and the value. For the dump operation, print the elements (a pair of key and value separated by a space character) in ascending order of the keys.
Example
Input
9
0 blue 4
0 red 1
0 white 5
1 red
1 blue
2 red
1 black
1 red
3 w z
Output
1
4
0
0
white 5
"Correct Solution:
```
# -*- coding: utf-8 -*-
"""
Dictionary - Map: Range Search
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP2_8_C&lang=jp
"""
from bisect import insort, bisect_right, bisect_left
class Range_map:
def __init__(self):
self.rm = dict()
self.lr = []
def insert(self, x, y):
if x not in self.rm:
insort(self.lr, x)
self.rm[x] = y
def get(self, x):
print(self.rm.get(x, 0))
def delete(self, x):
if x in self.rm:
self.rm[x] = 0
def dump(self, l, r):
lb = bisect_left(self.lr, l)
ub = bisect_right(self.lr, r)
for i in range(lb, ub):
k = self.lr[i]
if k in self.rm and self.rm[k] != 0:
print(f'{k} {self.rm[k]}')
rm = Range_map()
for _ in range(int(input())):
op, x, y = (input() + ' 1').split()[:3]
if op == '0':
rm.insert(x, int(y))
elif op == '1':
rm.get(x)
elif op == '2':
rm.delete(x)
else:
rm.dump(x, y)
```
| 93,512 |
Provide a correct Python 3 solution for this coding contest problem.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$.
* get($key$): Print the value with the specified $key$. Print 0 if there is no such element.
* delete($key$): Delete the element with the specified $key$.
* dump($L$, $R$): Print all elements formed by a pair of the key and the value such that the key is greater than or equal to $L$ and less than or equal to $R$ in lexicographic order.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consists of lower-case letters
* $L \leq R$ in lexicographic order
* The total number of elements printed by dump operations does not exceed $1,000,000$
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
or
2 $key$
or
3 $L$ $R$
where the first digits 0, 1, 2 and 3 represent insert, get, delete and dump operations.
Output
For each get operation, print the corresponding value.
For each dump operation, print the corresponding elements formed by a pair of the key and the value. For the dump operation, print the elements (a pair of key and value separated by a space character) in ascending order of the keys.
Example
Input
9
0 blue 4
0 red 1
0 white 5
1 red
1 blue
2 red
1 black
1 red
3 w z
Output
1
4
0
0
white 5
"Correct Solution:
```
import bisect
keys=[]
q=int(input())
d={}
def find(x):
index=bisect.bisect_left(keys,x)
if index==len(keys):
return -1
if keys[index]==x:
return index
else:
return -1
for _ in range(q):
query=input().split(" ")
if query[0]=="0":
if find(query[1])!=-1:
pass
else:
bisect.insort_left(keys, query[1])
d[query[1]]=query[2]
elif query[0]=="1":
if find(query[1])!=-1:
print(d[query[1]])
else:
print(0)
elif query[0]=="2":
while find(query[1])>=0:
keys.pop(find(query[1]))
else:
L,R=query[1],query[2]
indL=bisect.bisect_left(keys,L)
indR=bisect.bisect_right(keys,R)
for s in keys[indL:indR]:
print(s,d[s])
```
| 93,513 |
Provide a correct Python 3 solution for this coding contest problem.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$.
* get($key$): Print the value with the specified $key$. Print 0 if there is no such element.
* delete($key$): Delete the element with the specified $key$.
* dump($L$, $R$): Print all elements formed by a pair of the key and the value such that the key is greater than or equal to $L$ and less than or equal to $R$ in lexicographic order.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consists of lower-case letters
* $L \leq R$ in lexicographic order
* The total number of elements printed by dump operations does not exceed $1,000,000$
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
or
2 $key$
or
3 $L$ $R$
where the first digits 0, 1, 2 and 3 represent insert, get, delete and dump operations.
Output
For each get operation, print the corresponding value.
For each dump operation, print the corresponding elements formed by a pair of the key and the value. For the dump operation, print the elements (a pair of key and value separated by a space character) in ascending order of the keys.
Example
Input
9
0 blue 4
0 red 1
0 white 5
1 red
1 blue
2 red
1 black
1 red
3 w z
Output
1
4
0
0
white 5
"Correct Solution:
```
# AOJ ITP2_8_C: Map: Range Search
# Python3 2018.6.24 bal4u
from bisect import bisect_left, bisect_right, insort_left
dict = {}
keytbl = []
q = int(input())
for i in range(q):
a = list(input().split())
ki = a[1]
if a[0] == '0':
if ki not in dict:
insort_left(keytbl, ki)
dict[ki] = int(a[2])
elif a[0] == '1':
print(dict[ki] if ki in dict else 0)
elif a[0] == '2':
if ki in dict: dict[ki] = 0
else:
L = bisect_left (keytbl, a[1])
R = bisect_right(keytbl, a[2], L)
for j in range(L, R):
if dict[keytbl[j]] > 0: print(keytbl[j], dict[keytbl[j]])
```
| 93,514 |
Provide a correct Python 3 solution for this coding contest problem.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$.
* get($key$): Print the value with the specified $key$. Print 0 if there is no such element.
* delete($key$): Delete the element with the specified $key$.
* dump($L$, $R$): Print all elements formed by a pair of the key and the value such that the key is greater than or equal to $L$ and less than or equal to $R$ in lexicographic order.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consists of lower-case letters
* $L \leq R$ in lexicographic order
* The total number of elements printed by dump operations does not exceed $1,000,000$
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
or
2 $key$
or
3 $L$ $R$
where the first digits 0, 1, 2 and 3 represent insert, get, delete and dump operations.
Output
For each get operation, print the corresponding value.
For each dump operation, print the corresponding elements formed by a pair of the key and the value. For the dump operation, print the elements (a pair of key and value separated by a space character) in ascending order of the keys.
Example
Input
9
0 blue 4
0 red 1
0 white 5
1 red
1 blue
2 red
1 black
1 red
3 w z
Output
1
4
0
0
white 5
"Correct Solution:
```
from bisect import *
import sys
n = int(input())
dic = {}
dic2 = {}
box = []
for i in range(n):
a, b, *c = sys.stdin.readline().split()
if a == '0':
insort_left(box, b)
dic[b] = int(c[0])
elif a == '1':
print(dic[b] if b in dic else 0)
elif a == '2':
if b in dic:
del dic[b]
else:
L = bisect_left(box,b)
R = bisect_right(box, c[0])
while L<R:
if box[L] in dic:
print(box[L], dic[box[L]])
L = bisect_right(box, box[L])
```
| 93,515 |
Provide a correct Python 3 solution for this coding contest problem.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$.
* get($key$): Print the value with the specified $key$. Print 0 if there is no such element.
* delete($key$): Delete the element with the specified $key$.
* dump($L$, $R$): Print all elements formed by a pair of the key and the value such that the key is greater than or equal to $L$ and less than or equal to $R$ in lexicographic order.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consists of lower-case letters
* $L \leq R$ in lexicographic order
* The total number of elements printed by dump operations does not exceed $1,000,000$
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
or
2 $key$
or
3 $L$ $R$
where the first digits 0, 1, 2 and 3 represent insert, get, delete and dump operations.
Output
For each get operation, print the corresponding value.
For each dump operation, print the corresponding elements formed by a pair of the key and the value. For the dump operation, print the elements (a pair of key and value separated by a space character) in ascending order of the keys.
Example
Input
9
0 blue 4
0 red 1
0 white 5
1 red
1 blue
2 red
1 black
1 red
3 w z
Output
1
4
0
0
white 5
"Correct Solution:
```
def resolve():
import sys
import bisect
input = sys.stdin.readline
n = int(input())
ans = dict()
need_sort = True
sorted_keys = None
for _ in range(n):
q, key, *x = input().split()
if q == "0":
if key in ans:
ans[key] = x[0]
else:
ans[key] = x[0]
need_sort = True
elif q == "1":
if key in ans:
print(ans[key])
else:
print(0)
elif q == "2":
ans[key] = "0"
else:
if sorted_keys is None:
sorted_keys = sorted(ans.keys())
if need_sort:
sorted_keys = sorted(ans.keys())
need_sort = False
l, r = key, x[0]
fr = bisect.bisect_left(sorted_keys, l)
to = bisect.bisect_right(sorted_keys, r)
for i in range(fr, to):
if ans[sorted_keys[i]] != "0":
print(sorted_keys[i], ans[sorted_keys[i]])
resolve()
```
| 93,516 |
Provide a correct Python 3 solution for this coding contest problem.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$.
* get($key$): Print the value with the specified $key$. Print 0 if there is no such element.
* delete($key$): Delete the element with the specified $key$.
* dump($L$, $R$): Print all elements formed by a pair of the key and the value such that the key is greater than or equal to $L$ and less than or equal to $R$ in lexicographic order.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consists of lower-case letters
* $L \leq R$ in lexicographic order
* The total number of elements printed by dump operations does not exceed $1,000,000$
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
or
2 $key$
or
3 $L$ $R$
where the first digits 0, 1, 2 and 3 represent insert, get, delete and dump operations.
Output
For each get operation, print the corresponding value.
For each dump operation, print the corresponding elements formed by a pair of the key and the value. For the dump operation, print the elements (a pair of key and value separated by a space character) in ascending order of the keys.
Example
Input
9
0 blue 4
0 red 1
0 white 5
1 red
1 blue
2 red
1 black
1 red
3 w z
Output
1
4
0
0
white 5
"Correct Solution:
```
import sys
import bisect
n = int(input())
arr = []
lines = sys.stdin.readlines()
ans = [None] * n
d = {}
for i in range(n):
q, *arg = lines[i].split()
key = arg[0]
idx = bisect.bisect_left(arr, arg[0])
if q == '0': # insert
if idx == len(arr) or arr[idx] != key:
arr.insert(idx, key)
d[key] = arg[1]
elif q == '1': # get
ans[i] = d[key] if idx != len(arr) and arr[idx] == key else '0'
elif q == '2': # delete
if idx < len(arr) and arr[idx] == key:
del arr[idx]
del d[key]
elif q == '3': # dump L R
r_idx = bisect.bisect_right(arr, arg[1])
ans[i] = '\n'.join([f'{key_} {d[key_]}' for key_ in arr[idx:r_idx]]) if (r_idx - idx) != 0 else None
[print(x) for x in ans if x is not None]
```
| 93,517 |
Provide a correct Python 3 solution for this coding contest problem.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$.
* get($key$): Print the value with the specified $key$. Print 0 if there is no such element.
* delete($key$): Delete the element with the specified $key$.
* dump($L$, $R$): Print all elements formed by a pair of the key and the value such that the key is greater than or equal to $L$ and less than or equal to $R$ in lexicographic order.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consists of lower-case letters
* $L \leq R$ in lexicographic order
* The total number of elements printed by dump operations does not exceed $1,000,000$
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
or
2 $key$
or
3 $L$ $R$
where the first digits 0, 1, 2 and 3 represent insert, get, delete and dump operations.
Output
For each get operation, print the corresponding value.
For each dump operation, print the corresponding elements formed by a pair of the key and the value. For the dump operation, print the elements (a pair of key and value separated by a space character) in ascending order of the keys.
Example
Input
9
0 blue 4
0 red 1
0 white 5
1 red
1 blue
2 red
1 black
1 red
3 w z
Output
1
4
0
0
white 5
"Correct Solution:
```
from bisect import bisect_left, bisect_right, insort_left
dict = {}
keytbl = []
q = int(input())
for i in range(q):
a = list(input().split())
ki = a[1]
if a[0] == '0':
if ki not in dict:
insort_left(keytbl, ki)
dict[ki] = int(a[2])
elif a[0] == '1':
print(dict[ki] if ki in dict else 0)
elif a[0] == '2':
if ki in dict: dict[ki] = 0
else:
L = bisect_left (keytbl, a[1])
R = bisect_right(keytbl, a[2], L)
for j in range(L, R):
if dict[keytbl[j]] > 0: print(keytbl[j], dict[keytbl[j]])
```
| 93,518 |
Provide a correct Python 3 solution for this coding contest problem.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$.
* get($key$): Print the value with the specified $key$. Print 0 if there is no such element.
* delete($key$): Delete the element with the specified $key$.
* dump($L$, $R$): Print all elements formed by a pair of the key and the value such that the key is greater than or equal to $L$ and less than or equal to $R$ in lexicographic order.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consists of lower-case letters
* $L \leq R$ in lexicographic order
* The total number of elements printed by dump operations does not exceed $1,000,000$
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
or
2 $key$
or
3 $L$ $R$
where the first digits 0, 1, 2 and 3 represent insert, get, delete and dump operations.
Output
For each get operation, print the corresponding value.
For each dump operation, print the corresponding elements formed by a pair of the key and the value. For the dump operation, print the elements (a pair of key and value separated by a space character) in ascending order of the keys.
Example
Input
9
0 blue 4
0 red 1
0 white 5
1 red
1 blue
2 red
1 black
1 red
3 w z
Output
1
4
0
0
white 5
"Correct Solution:
```
from bisect import bisect,bisect_left,insort
dic = {}
l = []
for i in range(int(input())):
order = list(input().split())
if order[0] == "0":
if order[1] in dic:
dic[order[1]] = int(order[2])
else:
dic[order[1]] = int(order[2])
insort(l,order[1])
elif order[0] == "1":
if order[1] in dic:
print(dic[order[1]])
else:
print(0)
elif order[0] == "2":
if order[1] in dic:
dic[order[1]] = 0
elif order[0] == "3":
L = bisect_left(l,order[1])
R = bisect(l,order[2])
for i in range(L,R):
if dic[l[i]]:
print(l[i],dic[l[i]])
```
| 93,519 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$.
* get($key$): Print the value with the specified $key$. Print 0 if there is no such element.
* delete($key$): Delete the element with the specified $key$.
* dump($L$, $R$): Print all elements formed by a pair of the key and the value such that the key is greater than or equal to $L$ and less than or equal to $R$ in lexicographic order.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consists of lower-case letters
* $L \leq R$ in lexicographic order
* The total number of elements printed by dump operations does not exceed $1,000,000$
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
or
2 $key$
or
3 $L$ $R$
where the first digits 0, 1, 2 and 3 represent insert, get, delete and dump operations.
Output
For each get operation, print the corresponding value.
For each dump operation, print the corresponding elements formed by a pair of the key and the value. For the dump operation, print the elements (a pair of key and value separated by a space character) in ascending order of the keys.
Example
Input
9
0 blue 4
0 red 1
0 white 5
1 red
1 blue
2 red
1 black
1 red
3 w z
Output
1
4
0
0
white 5
Submitted Solution:
```
import bisect
q = int(input())
M = {}
sortedList = []
for i in range(q):
query, *inp = input().split()
key = inp[0]
# insert
if query == "0":
x = int(inp[1])
if key not in M:
bisect.insort_left(sortedList, key)
M[key] = x
# get
elif query == "1":
if key in M:
if M[key] != None:
print(M[key])
else:
print(0)
else:
print(0)
# delete
elif query == "2":
if key in M:
M[key] = None
# dump
else:
L = inp[0]
R = inp[1]
index_left = bisect.bisect_left(sortedList, L)
index_right = bisect.bisect_right(sortedList, R)
for i in range(index_left, index_right):
key_ans = sortedList[i]
if M[key_ans] != None:
print(key_ans, M[key_ans])
```
Yes
| 93,520 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$.
* get($key$): Print the value with the specified $key$. Print 0 if there is no such element.
* delete($key$): Delete the element with the specified $key$.
* dump($L$, $R$): Print all elements formed by a pair of the key and the value such that the key is greater than or equal to $L$ and less than or equal to $R$ in lexicographic order.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consists of lower-case letters
* $L \leq R$ in lexicographic order
* The total number of elements printed by dump operations does not exceed $1,000,000$
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
or
2 $key$
or
3 $L$ $R$
where the first digits 0, 1, 2 and 3 represent insert, get, delete and dump operations.
Output
For each get operation, print the corresponding value.
For each dump operation, print the corresponding elements formed by a pair of the key and the value. For the dump operation, print the elements (a pair of key and value separated by a space character) in ascending order of the keys.
Example
Input
9
0 blue 4
0 red 1
0 white 5
1 red
1 blue
2 red
1 black
1 red
3 w z
Output
1
4
0
0
white 5
Submitted Solution:
```
import bisect
q = int(input())
M = {}
list_key_sorted = []
for _ in range(q):
command, *list_num = input().split()
if command == "0":
# insert(key, x)
key = list_num[0]
x = int(list_num[1])
if key not in M:
bisect.insort_left(list_key_sorted, key)
M[key] = x
elif command == "1":
# get(key)
key = list_num[0]
if key in M:
if M[key] == None:
print(0)
else:
print(M[key])
else:
print(0)
elif command == "2":
# delete(key)
key = list_num[0]
if key in M:
M[key] = None
elif command == "3":
# dump(L, R)
L = list_num[0]
R = list_num[1]
index_left = bisect.bisect_left(list_key_sorted, L)
index_right = bisect.bisect_right(list_key_sorted, R)
for index in range(index_left, index_right):
key_ans = list_key_sorted[index]
if M[key_ans] != None:
print(key_ans, M[key_ans])
else:
raise
```
Yes
| 93,521 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$.
* get($key$): Print the value with the specified $key$. Print 0 if there is no such element.
* delete($key$): Delete the element with the specified $key$.
* dump($L$, $R$): Print all elements formed by a pair of the key and the value such that the key is greater than or equal to $L$ and less than or equal to $R$ in lexicographic order.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consists of lower-case letters
* $L \leq R$ in lexicographic order
* The total number of elements printed by dump operations does not exceed $1,000,000$
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
or
2 $key$
or
3 $L$ $R$
where the first digits 0, 1, 2 and 3 represent insert, get, delete and dump operations.
Output
For each get operation, print the corresponding value.
For each dump operation, print the corresponding elements formed by a pair of the key and the value. For the dump operation, print the elements (a pair of key and value separated by a space character) in ascending order of the keys.
Example
Input
9
0 blue 4
0 red 1
0 white 5
1 red
1 blue
2 red
1 black
1 red
3 w z
Output
1
4
0
0
white 5
Submitted Solution:
```
from enum import Enum
class Color(Enum):
BLACK = 0
RED = 1
@staticmethod
def flip(c):
return [Color.RED, Color.BLACK][c.value]
class Node:
__slots__ = ('key', 'left', 'right', 'size', 'color', 'value')
def __init__(self, key, value):
self.key = key
self.value = value
self.left = Leaf
self.right = Leaf
self.size = 1
self.color = Color.RED
def is_red(self):
return self.color == Color.RED
def is_black(self):
return self.color == Color.BLACK
def __str__(self):
if self.color == Color.RED:
key = '*{}'.format(self.key)
else:
key = '{}'.format(self.key)
return "{}[{}] ({}, {})".format(key, self.size,
self.left, self.right)
class LeafNode(Node):
def __init__(self):
self.key = None
self.value = None
self.left = None
self.right = None
self.size = 0
self.color = None
def is_red(self):
return False
def is_black(self):
return False
def __str__(self):
return '-'
Leaf = LeafNode()
class RedBlackBinarySearchTree:
"""Red Black Binary Search Tree with range, min, max.
Originally impremented in the textbook
Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
"""
def __init__(self):
self.root = Leaf
def put(self, key, value=None):
def _put(node):
if node is Leaf:
node = Node(key, value)
if node.key > key:
node.left = _put(node.left)
elif node.key < key:
node.right = _put(node.right)
else:
node.value = value
node = self._restore(node)
node.size = node.left.size + node.right.size + 1
return node
self.root = _put(self.root)
self.root.color = Color.BLACK
def _rotate_left(self, node):
x = node.right
node.right = x.left
x.left = node
x.color = node.color
node.color = Color.RED
node.size = node.left.size + node.right.size + 1
return x
def _rotate_right(self, node):
x = node.left
node.left = x.right
x.right = node
x.color = node.color
node.color = Color.RED
node.size = node.left.size + node.right.size + 1
return x
def _flip_colors(self, node):
node.color = Color.flip(node.color)
node.left.color = Color.flip(node.left.color)
node.right.color = Color.flip(node.right.color)
return node
def __contains__(self, key):
def _contains(node):
if node is Leaf:
return False
if node.key > key:
return _contains(node.left)
elif node.key < key:
return _contains(node.right)
else:
return True
return _contains(self.root)
def get(self, key):
def _get(node):
if node is Leaf:
return None
if node.key > key:
return _get(node.left)
elif node.key < key:
return _get(node.right)
else:
return node.value
return _get(self.root)
def delete(self, key):
def _delete(node):
if node is Leaf:
return Leaf
if node.key > key:
if node.left is Leaf:
return self._balance(node)
if not self._is_red_left(node):
node = self._red_left(node)
node.left = _delete(node.left)
else:
if node.left.is_red():
node = self._rotate_right(node)
if node.key == key and node.right is Leaf:
return Leaf
elif node.right is Leaf:
return self._balance(node)
if not self._is_red_right(node):
node = self._red_right(node)
if node.key == key:
x = self._find_min(node.right)
node.key = x.key
node.value = x.value
node.right = self._delete_min(node.right)
else:
node.right = _delete(node.right)
return self._balance(node)
if self.is_empty():
raise ValueError('delete on empty tree')
if not self.root.left.is_red() and not self.root.right.is_red():
self.root.color = Color.RED
self.root = _delete(self.root)
if not self.is_empty():
self.root.color = Color.BLACK
def delete_max(self):
if self.is_empty():
raise ValueError('delete max on empty tree')
if not self.root.left.is_red() and not self.root.right.is_red():
self.root.color = Color.RED
self.root = self._delete_max(self.root)
if not self.is_empty():
self.root.color = Color.BLACK
def _delete_max(self, node):
if node.left.is_red():
node = self._rotate_right(node)
if node.right is Leaf:
return Leaf
if not self._is_red_right(node):
node = self._red_right(node)
node.right = self._delete_max(node.right)
return self._balance(node)
def _red_right(self, node):
node = self._flip_colors(node)
if node.left.left.is_red():
node = self._rotate_right(node)
return node
def _is_red_right(self, node):
return (node.right.is_red() or
(node.right.is_black() and node.right.left.is_red()))
def delete_min(self):
if self.is_empty():
raise ValueError('delete min on empty tree')
if not self.root.left.is_red() and not self.root.right.is_red():
self.root.color = Color.RED
self.root = self._delete_min(self.root)
if not self.is_empty():
self.root.color = Color.BLACK
def _delete_min(self, node):
if node.left is Leaf:
return Leaf
if not self._is_red_left(node):
node = self._red_left(node)
node.left = self._delete_min(node.left)
return self._balance(node)
def _red_left(self, node):
node = self._flip_colors(node)
if node.right.left.is_red():
node.right = self._rotate_right(node.right)
node = self._rotate_left(node)
return node
def _is_red_left(self, node):
return (node.left.is_red() or
(node.left.is_black() and node.left.left.is_red()))
def _balance(self, node):
if node.right.is_red():
node = self._rotate_left(node)
return self._restore(node)
def _restore(self, node):
if node.right.is_red() and not node.left.is_red():
node = self._rotate_left(node)
if node.left.is_red() and node.left.left.is_red():
node = self._rotate_right(node)
if node.left.is_red() and node.right.is_red():
node = self._flip_colors(node)
node.size = node.left.size + node.right.size + 1
return node
def is_empty(self):
return self.root is Leaf
def is_balanced(self):
if self.is_empty():
return True
try:
left = self._depth(self.root.left)
right = self._depth(self.root.right)
return left == right
except Exception:
return False
@property
def depth(self):
return self._depth(self.root)
def _depth(self, node):
if node is Leaf:
return 0
if node.right.is_red():
raise Exception('right red')
left = self._depth(node.left)
right = self._depth(node.right)
if left != right:
raise Exception('unbalanced')
if node.is_red():
return left
else:
return 1 + left
def __len__(self):
return self.root.size
@property
def max(self):
if self.is_empty():
raise ValueError('max on empty tree')
return self._max(self.root)
def _max(self, node):
x = self._find_max(node)
return x.key
def _find_max(self, node):
if node.right is Leaf:
return node
else:
return self._find_max(node.right)
@property
def min(self):
if self.is_empty():
raise ValueError('min on empty tree')
return self._min(self.root)
def _min(self, node):
x = self._find_min(node)
return x.key
def _find_min(self, node):
if node.left is Leaf:
return node
else:
return self._find_min(node.left)
def __iter__(self):
def inorder(node):
if node is Leaf:
return
yield from inorder(node.left)
yield node.value
yield from inorder(node.right)
yield from inorder(self.root)
def range(self, min_, max_):
def _range(node):
if node is Leaf:
return
if node.key > max_:
yield from _range(node.left)
elif node.key < min_:
yield from _range(node.right)
else:
yield from _range(node.left)
yield (node.key, node.value)
yield from _range(node.right)
if min_ > max_:
return
yield from _range(self.root)
class Map:
def __init__(self):
self.tree = RedBlackBinarySearchTree()
def __getitem__(self, key):
if key in self.tree:
return self.tree.get(key)
else:
raise IndexError('key {} not found in map'.format(key))
def __setitem__(self, key, value):
self.tree.put(key, value)
def __delitem__(self, key):
if key in self.tree:
self.tree.delete(key)
else:
raise IndexError('key {} not found in map'.format(key))
def __len__(self):
return len(self.tree)
def items(self):
for k, v in self.tree:
yield (k, v)
def range(self, min_, max_):
for k, v in self.tree.range(min_, max_):
yield (k, v)
def run():
q = int(input())
m = Map()
for _ in range(q):
command, *args = input().split()
if command == '0':
key = args[0]
value = int(args[1])
m[key] = value
elif command == '1':
key = args[0]
try:
print(m[key])
except IndexError:
print(0)
elif command == '2':
key = args[0]
try:
del m[key]
except IndexError:
pass
elif command == '3':
low, hi = args
for k, v in m.range(low, hi):
print(k, v)
else:
raise ValueError('invalid command')
if __name__ == '__main__':
run()
```
Yes
| 93,522 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$.
* get($key$): Print the value with the specified $key$. Print 0 if there is no such element.
* delete($key$): Delete the element with the specified $key$.
* dump($L$, $R$): Print all elements formed by a pair of the key and the value such that the key is greater than or equal to $L$ and less than or equal to $R$ in lexicographic order.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consists of lower-case letters
* $L \leq R$ in lexicographic order
* The total number of elements printed by dump operations does not exceed $1,000,000$
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
or
2 $key$
or
3 $L$ $R$
where the first digits 0, 1, 2 and 3 represent insert, get, delete and dump operations.
Output
For each get operation, print the corresponding value.
For each dump operation, print the corresponding elements formed by a pair of the key and the value. For the dump operation, print the elements (a pair of key and value separated by a space character) in ascending order of the keys.
Example
Input
9
0 blue 4
0 red 1
0 white 5
1 red
1 blue
2 red
1 black
1 red
3 w z
Output
1
4
0
0
white 5
Submitted Solution:
```
from bisect import bisect_left, bisect_right, insort_left
q = int(input())
M = {}
tbl = []
for i in range(q):
query, *x = input().split()
if query == "0":
x[1] = int(x[1])
if x[0] not in M:
insort_left(tbl, x[0])
M[x[0]] = x[1]
elif query == "1":
print(M[x[0]] if x[0] in M and M[x[0]] != 0 else 0)
elif query == "2":
M[x[0]] = 0
else:
L = bisect_left( tbl, x[0])
R = bisect_right(tbl, x[1])
for i in range(L, R):
if M[tbl[i]] != 0:
print(tbl[i], M[tbl[i]])
```
Yes
| 93,523 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$.
* get($key$): Print the value with the specified $key$. Print 0 if there is no such element.
* delete($key$): Delete the element with the specified $key$.
* dump($L$, $R$): Print all elements formed by a pair of the key and the value such that the key is greater than or equal to $L$ and less than or equal to $R$ in lexicographic order.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consists of lower-case letters
* $L \leq R$ in lexicographic order
* The total number of elements printed by dump operations does not exceed $1,000,000$
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
or
2 $key$
or
3 $L$ $R$
where the first digits 0, 1, 2 and 3 represent insert, get, delete and dump operations.
Output
For each get operation, print the corresponding value.
For each dump operation, print the corresponding elements formed by a pair of the key and the value. For the dump operation, print the elements (a pair of key and value separated by a space character) in ascending order of the keys.
Example
Input
9
0 blue 4
0 red 1
0 white 5
1 red
1 blue
2 red
1 black
1 red
3 w z
Output
1
4
0
0
white 5
Submitted Solution:
```
from enum import Enum
class Color(Enum):
BLACK = 0
RED = 1
@staticmethod
def flip(c):
return [Color.RED, Color.BLACK][c.value]
class Node:
__slots__ = ('key', 'left', 'right', 'size', 'color', 'value')
def __init__(self, key, value):
self.key = key
self.value = value
self.left = Leaf
self.right = Leaf
self.size = 1
self.color = Color.RED
def is_red(self):
return self.color == Color.RED
def is_black(self):
return self.color == Color.BLACK
def __str__(self):
if self.color == Color.RED:
key = '*{}'.format(self.key)
else:
key = '{}'.format(self.key)
return "{}[{}] ({}, {})".format(key, self.size,
self.left, self.right)
class LeafNode(Node):
def __init__(self):
self.key = None
self.value = None
self.left = None
self.right = None
self.size = 0
self.color = None
def is_red(self):
return False
def is_black(self):
return False
def __str__(self):
return '-'
Leaf = LeafNode()
class RedBlackBinarySearchTree:
"""Red Black Binary Search Tree with range, min, max.
Originally impremented in the textbook
Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
"""
def __init__(self):
self.root = Leaf
def put(self, key, value=None):
def _put(node):
if node is Leaf:
node = Node(key, value)
if node.key > key:
node.left = _put(node.left)
elif node.key < key:
node.right = _put(node.right)
else:
node.value = value
node = self._restore(node)
node.size = node.left.size + node.right.size + 1
return node
self.root = _put(self.root)
self.root.color = Color.BLACK
def _rotate_left(self, node):
assert node.right.is_red()
x = node.right
node.right = x.left
x.left = node
x.color = node.color
node.color = Color.RED
node.size = node.left.size + node.right.size + 1
return x
def _rotate_right(self, node):
assert node.left.is_red()
x = node.left
node.left = x.right
x.right = node
x.color = node.color
node.color = Color.RED
node.size = node.left.size + node.right.size + 1
return x
def _flip_colors(self, node):
node.color = Color.flip(node.color)
node.left.color = Color.flip(node.left.color)
node.right.color = Color.flip(node.right.color)
return node
def __contains__(self, key):
def _contains(node):
if node is Leaf:
return False
if node.key > key:
return _contains(node.left)
elif node.key < key:
return _contains(node.right)
else:
return True
return _contains(self.root)
def get(self, key):
def _get(node):
if node is Leaf:
return None
if node.key > key:
return _get(node.left)
elif node.key < key:
return _get(node.right)
else:
return node.value
return _get(self.root)
def delete(self, key):
def _delete(node):
if node is Leaf:
return Leaf
if node.key > key:
if node.left is Leaf:
return self._balance(node)
if not self._is_red_left(node):
node = self._red_left(node)
node.left = _delete(node.left)
else:
if node.left.is_red():
node = self._rotate_right(node)
if node.key == key and node.right is Leaf:
return Leaf
elif node.right is Leaf:
return self._balance(node)
if not self._is_red_right(node):
node = self._red_right(node)
if node.key == key:
x = self._find_min(node.right)
node.key = x.key
node.value = x.value
node.right = self._delete_min(node.right)
else:
node.right = _delete(node.right)
if self.is_empty():
raise ValueError('delete on empty tree')
if not self.root.left.is_red() and not self.root.right.is_red():
self.root.color = Color.RED
self.root = _delete(self.root)
if not self.is_empty():
self.root.color = Color.BLACK
def delete_max(self):
if self.is_empty():
raise ValueError('delete max on empty tree')
if not self.root.left.is_red() and not self.root.right.is_red():
self.root.color = Color.RED
self.root = self._delete_max(self.root)
if not self.is_empty():
self.root.color = Color.BLACK
def _delete_max(self, node):
if node.left.is_red():
node = self._rotate_right(node)
if node.right is Leaf:
return Leaf
if not self._is_red_right(node):
node = self._red_right(node)
node.right = self._delete_max(node.right)
def _red_right(self, node):
node = self._flip_colors(node)
if node.left.left.is_red():
node = self._rotate_right(node)
return node
def _is_red_right(self, node):
return (node.right.is_red() or
(node.right.is_black() and node.right.left.is_red()))
def delete_min(self):
if self.is_empty():
raise ValueError('delete min on empty tree')
if not self.root.left.is_red() and not self.root.right.is_red():
self.root.color = Color.RED
self.root = self._delete_min(self.root)
if not self.is_empty():
self.root.color = Color.BLACK
def _delete_min(self, node):
if node.left is Leaf:
return Leaf
if not self._is_red_left(node):
node = self._red_left(node)
node.left = self._delete_min(node.left)
return self._balance(node)
def _red_left(self, node):
node = self._flip_colors(node)
if node.right.left.is_red():
node.right = self._rotate_right(node.right)
node = self._rotate_left(node)
return node
def _is_red_left(self, node):
return (node.left.is_red() or
(node.left.is_black() and node.left.left.is_red()))
def _balance(self, node):
if node.right.is_red():
node = self._rotate_left(node)
return self._restore(node)
def _restore(self, node):
if node.right.is_red() and not node.left.is_red():
node = self._rotate_left(node)
if node.left.is_red() and node.left.left.is_red():
node = self._rotate_right(node)
if node.left.is_red() and node.right.is_red():
node = self._flip_colors(node)
node.size = node.left.size + node.right.size + 1
return node
def is_empty(self):
return self.root is Leaf
def is_balanced(self):
if self.is_empty():
return True
try:
left = self._depth(self.root.left)
right = self._depth(self.root.right)
return left == right
except Exception:
return False
@property
def depth(self):
return self._depth(self.root)
def _depth(self, node):
if node is Leaf:
return 0
if node.right.is_red():
raise Exception('right red')
left = self._depth(node.left)
right = self._depth(node.right)
if left != right:
raise Exception('unbalanced')
if node.is_red():
return left
else:
return 1 + left
def __len__(self):
return self.root.size
@property
def max(self):
if self.is_empty():
raise ValueError('max on empty tree')
return self._max(self.root)
def _max(self, node):
x = self._find_max(node)
return x.key
def _find_max(self, node):
if node.right is Leaf:
return node
else:
return self._find_max(node.right)
@property
def min(self):
if self.is_empty():
raise ValueError('min on empty tree')
return self._min(self.root)
def _min(self, node):
x = self._find_min(node)
return x.key
def _find_min(self, node):
if node.left is Leaf:
return node
else:
return self._find_min(node.left)
def __iter__(self):
def inorder(node):
if node is Leaf:
return
yield from inorder(node.left)
yield node.value
yield from inorder(node.right)
yield from inorder(self.root)
def range(self, min_, max_):
def _range(node):
if node is Leaf:
return
if node.key > max_:
yield from _range(node.left)
elif node.key < min_:
yield from _range(node.right)
else:
yield from _range(node.left)
yield (node.key, node.value)
yield from _range(node.right)
if min_ > max_:
return
yield from _range(self.root)
class Map:
def __init__(self):
self.tree = RedBlackBinarySearchTree()
def __getitem__(self, key):
if key in self.tree:
return self.tree.get(key)
else:
raise IndexError('key {} not found in map'.format(key))
def __setitem__(self, key, value):
self.tree.put(key, value)
def __delitem__(self, key):
if key in self.tree:
self.tree.delete(key)
else:
raise IndexError('key {} not found in map'.format(key))
def __len__(self):
return len(self.tree)
def items(self):
for k, v in self.tree:
yield (k, v)
def range(self, min_, max_):
for k, v in self.tree.range(min_, max_):
yield (k, v)
def run():
q = int(input())
m = Map()
for _ in range(q):
command, *args = input().split()
if command == '0':
key = args[0]
value = int(args[1])
m[key] = value
elif command == '1':
key = args[0]
try:
print(m[key])
except IndexError:
print(0)
elif command == '2':
key = args[0]
try:
del m[key]
except IndexError:
pass
elif command == '3':
low, hi = args
for k, v in m.range(low, hi):
print(k, v)
else:
raise ValueError('invalid command')
if __name__ == '__main__':
run()
```
No
| 93,524 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$.
* get($key$): Print the value with the specified $key$. Print 0 if there is no such element.
* delete($key$): Delete the element with the specified $key$.
* dump($L$, $R$): Print all elements formed by a pair of the key and the value such that the key is greater than or equal to $L$ and less than or equal to $R$ in lexicographic order.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consists of lower-case letters
* $L \leq R$ in lexicographic order
* The total number of elements printed by dump operations does not exceed $1,000,000$
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
or
2 $key$
or
3 $L$ $R$
where the first digits 0, 1, 2 and 3 represent insert, get, delete and dump operations.
Output
For each get operation, print the corresponding value.
For each dump operation, print the corresponding elements formed by a pair of the key and the value. For the dump operation, print the elements (a pair of key and value separated by a space character) in ascending order of the keys.
Example
Input
9
0 blue 4
0 red 1
0 white 5
1 red
1 blue
2 red
1 black
1 red
3 w z
Output
1
4
0
0
white 5
Submitted Solution:
```
from collections import OrderedDict
dict = OrderedDict()
q = int(input())
for i in range(q):
query, *val = input().split(' ')
if query == '0':
dict[val[0]] = int(val[1])
elif query == '1':
print(dict.get(val[0], 0))
elif query == '2':
if val[0] in dict:
dict.pop(val[0])
else:
ans = ''
for k, v in dict.items():
if val[0] <= k and k <= val[1]:
ans += str(k) + ' ' + str(v) + ' '
print(ans.strip())
```
No
| 93,525 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$.
* get($key$): Print the value with the specified $key$. Print 0 if there is no such element.
* delete($key$): Delete the element with the specified $key$.
* dump($L$, $R$): Print all elements formed by a pair of the key and the value such that the key is greater than or equal to $L$ and less than or equal to $R$ in lexicographic order.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consists of lower-case letters
* $L \leq R$ in lexicographic order
* The total number of elements printed by dump operations does not exceed $1,000,000$
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
or
2 $key$
or
3 $L$ $R$
where the first digits 0, 1, 2 and 3 represent insert, get, delete and dump operations.
Output
For each get operation, print the corresponding value.
For each dump operation, print the corresponding elements formed by a pair of the key and the value. For the dump operation, print the elements (a pair of key and value separated by a space character) in ascending order of the keys.
Example
Input
9
0 blue 4
0 red 1
0 white 5
1 red
1 blue
2 red
1 black
1 red
3 w z
Output
1
4
0
0
white 5
Submitted Solution:
```
from enum import Enum
class Color(Enum):
BLACK = 0
RED = 1
@staticmethod
def flip(c):
return [Color.RED, Color.BLACK][c.value]
class Node:
__slots__ = ('key', 'left', 'right', 'size', 'color', 'value')
def __init__(self, key, value):
self.key = key
self.value = value
self.left = Leaf
self.right = Leaf
self.size = 1
self.color = Color.RED
def is_red(self):
return self.color == Color.RED
def is_black(self):
return self.color == Color.BLACK
def __str__(self):
if self.color == Color.RED:
key = '*{}'.format(self.key)
else:
key = '{}'.format(self.key)
return "{}[{}] ({}, {})".format(key, self.size,
self.left, self.right)
class LeafNode(Node):
def __init__(self):
self.key = None
self.value = None
self.left = None
self.right = None
self.size = 0
self.color = None
def is_red(self):
return False
def is_black(self):
return False
def __str__(self):
return '-'
Leaf = LeafNode()
class RedBlackBinarySearchTree:
"""Red Black Binary Search Tree with range, min, max.
Originally impremented in the textbook
Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
"""
def __init__(self):
self.root = Leaf
def put(self, key, value=None):
def _put(node):
if node is Leaf:
node = Node(key, value)
if node.key > key:
node.left = _put(node.left)
elif node.key < key:
node.right = _put(node.right)
else:
node.value = value
node = self._restore(node)
node.size = node.left.size + node.right.size + 1
return node
self.root = _put(self.root)
self.root.color = Color.BLACK
def _rotate_left(self, node):
assert node.right.is_red()
x = node.right
node.right = x.left
x.left = node
x.color = node.color
node.color = Color.RED
node.size = node.left.size + node.right.size + 1
return x
def _rotate_right(self, node):
assert node.left.is_red()
x = node.left
node.left = x.right
x.right = node
x.color = node.color
node.color = Color.RED
node.size = node.left.size + node.right.size + 1
return x
def _flip_colors(self, node):
node.color = Color.flip(node.color)
node.left.color = Color.flip(node.left.color)
node.right.color = Color.flip(node.right.color)
return node
def __contains__(self, key):
def _contains(node):
if node is Leaf:
return False
if node.key > key:
return _contains(node.left)
elif node.key < key:
return _contains(node.right)
else:
return True
return _contains(self.root)
def get(self, key):
def _get(node):
if node is Leaf:
return None
if node.key > key:
return _get(node.left)
elif node.key < key:
return _get(node.right)
else:
return node.value
return _get(self.root)
def delete(self, key):
def _delete(node):
if node is Leaf:
return Leaf
if node.key > key:
if node.left is Leaf:
return self._balance(node)
if not self._is_red_left(node):
node = self._red_left(node)
node.left = _delete(node.left)
else:
if node.left.is_red():
node = self._rotate_right(node)
if node.key == key and node.right is Leaf:
return Leaf
elif node.right is Leaf:
return self._balance(node)
if not self._is_red_right(node):
node = self._red_right(node)
if node.key == key:
x = self._find_min(node.right)
node.key = x.key
node.value = x.value
node.right = self._delete_min(node.right)
else:
node.right = _delete(node.right)
return self._balance(node)
if self.is_empty():
raise ValueError('delete on empty tree')
if not self.root.left.is_red() and not self.root.right.is_red():
self.root.color = Color.RED
self.root = _delete(self.root)
if not self.is_empty():
self.root.color = Color.BLACK
assert self.is_balanced()
def delete_max(self):
if self.is_empty():
raise ValueError('delete max on empty tree')
if not self.root.left.is_red() and not self.root.right.is_red():
self.root.color = Color.RED
self.root = self._delete_max(self.root)
if not self.is_empty():
self.root.color = Color.BLACK
assert self.is_balanced()
def _delete_max(self, node):
if node.left.is_red():
node = self._rotate_right(node)
if node.right is Leaf:
return Leaf
if not self._is_red_right(node):
node = self._red_right(node)
node.right = self._delete_max(node.right)
return self._balance(node)
def _red_right(self, node):
node = self._flip_colors(node)
if node.left.left.is_red():
node = self._rotate_right(node)
return node
def _is_red_right(self, node):
return (node.right.is_red() or
(node.right.is_black() and node.right.left.is_red()))
def delete_min(self):
if self.is_empty():
raise ValueError('delete min on empty tree')
if not self.root.left.is_red() and not self.root.right.is_red():
self.root.color = Color.RED
self.root = self._delete_min(self.root)
if not self.is_empty():
self.root.color = Color.BLACK
assert self.is_balanced()
def _delete_min(self, node):
if node.left is Leaf:
return Leaf
if not self._is_red_left(node):
node = self._red_left(node)
node.left = self._delete_min(node.left)
return self._balance(node)
def _red_left(self, node):
node = self._flip_colors(node)
if node.right.left.is_red():
node.right = self._rotate_right(node.right)
node = self._rotate_left(node)
return node
def _is_red_left(self, node):
return (node.left.is_red() or
(node.left.is_black() and node.left.left.is_red()))
def _balance(self, node):
if node.right.is_red():
node = self._rotate_left(node)
return self._restore(node)
def _restore(self, node):
if node.right.is_red() and not node.left.is_red():
node = self._rotate_left(node)
if node.left.is_red() and node.left.left.is_red():
node = self._rotate_right(node)
if node.left.is_red() and node.right.is_red():
node = self._flip_colors(node)
node.size = node.left.size + node.right.size + 1
return node
def is_empty(self):
return self.root is Leaf
def is_balanced(self):
if self.is_empty():
return True
try:
left = self._depth(self.root.left)
right = self._depth(self.root.right)
return left == right
except Exception:
return False
@property
def depth(self):
return self._depth(self.root)
def _depth(self, node):
if node is Leaf:
return 0
if node.right.is_red():
raise Exception('right red')
left = self._depth(node.left)
right = self._depth(node.right)
if left != right:
raise Exception('unbalanced')
if node.is_red():
return left
else:
return 1 + left
def __len__(self):
return self.root.size
@property
def max(self):
if self.is_empty():
raise ValueError('max on empty tree')
return self._max(self.root)
def _max(self, node):
x = self._find_max(node)
return x.key
def _find_max(self, node):
if node.right is Leaf:
return node
else:
return self._find_max(node.right)
@property
def min(self):
if self.is_empty():
raise ValueError('min on empty tree')
return self._min(self.root)
def _min(self, node):
x = self._find_min(node)
return x.key
def _find_min(self, node):
if node.left is Leaf:
return node
else:
return self._find_min(node.left)
def __iter__(self):
def inorder(node):
if node is Leaf:
return
yield from inorder(node.left)
yield node.value
yield from inorder(node.right)
yield from inorder(self.root)
def range(self, min_, max_):
def _range(node):
if node is Leaf:
return
if node.key > max_:
yield from _range(node.left)
elif node.key < min_:
yield from _range(node.right)
else:
yield from _range(node.left)
yield (node.key, node.value)
yield from _range(node.right)
if min_ > max_:
return
yield from _range(self.root)
class Map:
def __init__(self):
self.tree = RedBlackBinarySearchTree()
def __getitem__(self, key):
if key in self.tree:
return self.tree.get(key)
else:
raise IndexError('key {} not found in map'.format(key))
def __setitem__(self, key, value):
self.tree.put(key, value)
def __delitem__(self, key):
if key in self.tree:
self.tree.delete(key)
else:
raise IndexError('key {} not found in map'.format(key))
def __len__(self):
return len(self.tree)
def items(self):
for k, v in self.tree:
yield (k, v)
def range(self, min_, max_):
for k, v in self.tree.range(min_, max_):
yield (k, v)
def run():
q = int(input())
m = Map()
for _ in range(q):
command, *args = input().split()
if command == '0':
key = args[0]
value = int(args[1])
m[key] = value
elif command == '1':
key = args[0]
try:
print(m[key])
except IndexError:
print(0)
elif command == '2':
key = args[0]
try:
del m[key]
except IndexError:
pass
elif command == '3':
low, hi = args
for k, v in m.range(low, hi):
print(k, v)
else:
raise ValueError('invalid command')
if __name__ == '__main__':
run()
```
No
| 93,526 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$.
* get($key$): Print the value with the specified $key$. Print 0 if there is no such element.
* delete($key$): Delete the element with the specified $key$.
* dump($L$, $R$): Print all elements formed by a pair of the key and the value such that the key is greater than or equal to $L$ and less than or equal to $R$ in lexicographic order.
Constraints
* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consists of lower-case letters
* $L \leq R$ in lexicographic order
* The total number of elements printed by dump operations does not exceed $1,000,000$
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $key$ $x$
or
1 $key$
or
2 $key$
or
3 $L$ $R$
where the first digits 0, 1, 2 and 3 represent insert, get, delete and dump operations.
Output
For each get operation, print the corresponding value.
For each dump operation, print the corresponding elements formed by a pair of the key and the value. For the dump operation, print the elements (a pair of key and value separated by a space character) in ascending order of the keys.
Example
Input
9
0 blue 4
0 red 1
0 white 5
1 red
1 blue
2 red
1 black
1 red
3 w z
Output
1
4
0
0
white 5
Submitted Solution:
```
from collections import OrderedDict
dict = OrderedDict()
q = int(input())
for i in range(q):
query, *val = input().split(' ')
if query == '0':
dict[val[0]] = int(val[1])
elif query == '1':
print(dict.get(val[0], 0))
elif query == '2':
if val[0] in dict:
dict.pop(val[0])
else:
ans = []
for k, v in dict.items():
if val[0] <= k and k <= val[1]:
print(k, v, end=' ')
print()
```
No
| 93,527 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Since Sonya has just learned the basics of matrices, she decided to play with them a little bit.
Sonya imagined a new type of matrices that she called rhombic matrices. These matrices have exactly one zero, while all other cells have the Manhattan distance to the cell containing the zero. The cells with equal numbers have the form of a rhombus, that is why Sonya called this type so.
The Manhattan distance between two cells (x_1, y_1) and (x_2, y_2) is defined as |x_1 - x_2| + |y_1 - y_2|. For example, the Manhattan distance between the cells (5, 2) and (7, 1) equals to |5-7|+|2-1|=3.
<image> Example of a rhombic matrix.
Note that rhombic matrices are uniquely defined by n, m, and the coordinates of the cell containing the zero.
She drew a nΓ m rhombic matrix. She believes that you can not recreate the matrix if she gives you only the elements of this matrix in some arbitrary order (i.e., the sequence of nβ
m numbers). Note that Sonya will not give you n and m, so only the sequence of numbers in this matrix will be at your disposal.
Write a program that finds such an nΓ m rhombic matrix whose elements are the same as the elements in the sequence in some order.
Input
The first line contains a single integer t (1β€ tβ€ 10^6) β the number of cells in the matrix.
The second line contains t integers a_1, a_2, β¦, a_t (0β€ a_i< t) β the values in the cells in arbitrary order.
Output
In the first line, print two positive integers n and m (n Γ m = t) β the size of the matrix.
In the second line, print two integers x and y (1β€ xβ€ n, 1β€ yβ€ m) β the row number and the column number where the cell with 0 is located.
If there are multiple possible answers, print any of them. If there is no solution, print the single integer -1.
Examples
Input
20
1 0 2 3 5 3 2 1 3 2 3 1 4 2 1 4 2 3 2 4
Output
4 5
2 2
Input
18
2 2 3 2 4 3 3 3 0 2 4 2 1 3 2 1 1 1
Output
3 6
2 3
Input
6
2 1 0 2 1 2
Output
-1
Note
You can see the solution to the first example in the legend. You also can choose the cell (2, 2) for the cell where 0 is located. You also can choose a 5Γ 4 matrix with zero at (4, 2).
In the second example, there is a 3Γ 6 matrix, where the zero is located at (2, 3) there.
In the third example, a solution does not exist.
Tags: brute force, constructive algorithms, implementation
Correct Solution:
```
import math
t = int(input())
L = [int(x) for x in input().split()]
L.sort()
ma = max(L)
S = 2*sum(L)
Div = []
for i in range(1,int(math.sqrt(t))+1):
if t%i == 0:
Div.append(i)
Div.append(t//i)
if len(Div) >= 2:
if Div[-1] == Div[-2]:
Div.pop()
Div.sort()
D = {}
for i in L:
if i in D:
D[i] += 1
else:
D[i] = 1
Candidates = []
for i in range(len(Div)):
n = Div[i]
m = Div[-i-1]
for j in range(ma,ma-m,-1):
if D.get(j,-1) > ma-j+1:
break
else:
j -= 1
good = ma-j
y = 1+(m-good)//2
x = m+n-ma-y
T = x+y
if y >= 1:
if y <= (m+1)//2:
if x <= (n+1)//2:
if m*(x*(x-1)+(n-x)*(n-x+1))+n*((T-x)*(T-x-1)+(m-T+x)*(m-T+x+1)) == S:
temp = []
for j in range(m*n):
temp.append(abs(1+(j%n)-x)+abs(1+(j//n)-y))
temp.sort()
if temp == L:
print(n,m)
print(x,y)
break
else:
print(-1)
```
| 93,528 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Since Sonya has just learned the basics of matrices, she decided to play with them a little bit.
Sonya imagined a new type of matrices that she called rhombic matrices. These matrices have exactly one zero, while all other cells have the Manhattan distance to the cell containing the zero. The cells with equal numbers have the form of a rhombus, that is why Sonya called this type so.
The Manhattan distance between two cells (x_1, y_1) and (x_2, y_2) is defined as |x_1 - x_2| + |y_1 - y_2|. For example, the Manhattan distance between the cells (5, 2) and (7, 1) equals to |5-7|+|2-1|=3.
<image> Example of a rhombic matrix.
Note that rhombic matrices are uniquely defined by n, m, and the coordinates of the cell containing the zero.
She drew a nΓ m rhombic matrix. She believes that you can not recreate the matrix if she gives you only the elements of this matrix in some arbitrary order (i.e., the sequence of nβ
m numbers). Note that Sonya will not give you n and m, so only the sequence of numbers in this matrix will be at your disposal.
Write a program that finds such an nΓ m rhombic matrix whose elements are the same as the elements in the sequence in some order.
Input
The first line contains a single integer t (1β€ tβ€ 10^6) β the number of cells in the matrix.
The second line contains t integers a_1, a_2, β¦, a_t (0β€ a_i< t) β the values in the cells in arbitrary order.
Output
In the first line, print two positive integers n and m (n Γ m = t) β the size of the matrix.
In the second line, print two integers x and y (1β€ xβ€ n, 1β€ yβ€ m) β the row number and the column number where the cell with 0 is located.
If there are multiple possible answers, print any of them. If there is no solution, print the single integer -1.
Examples
Input
20
1 0 2 3 5 3 2 1 3 2 3 1 4 2 1 4 2 3 2 4
Output
4 5
2 2
Input
18
2 2 3 2 4 3 3 3 0 2 4 2 1 3 2 1 1 1
Output
3 6
2 3
Input
6
2 1 0 2 1 2
Output
-1
Note
You can see the solution to the first example in the legend. You also can choose the cell (2, 2) for the cell where 0 is located. You also can choose a 5Γ 4 matrix with zero at (4, 2).
In the second example, there is a 3Γ 6 matrix, where the zero is located at (2, 3) there.
In the third example, a solution does not exist.
Tags: brute force, constructive algorithms, implementation
Correct Solution:
```
import functools
import time
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
stime = time.perf_counter()
res = func(*args, **kwargs)
elapsed = time.perf_counter() - stime
print(f"{func.__name__} in {elapsed:.4f} secs")
return res
return wrapper
class solver:
# @timer
def __init__(self):
t = int(input())
a = list(map(int, input().strip().split()))
def build(n, m, r, c):
if not (0 <= r and r < n and 0 <= c and c < m):
return []
ret = [0] * t
for i in range (n):
for j in range(m):
ret[abs(r - i) + abs(c - j)] += 1
return ret
a.sort()
h = [0] * t
amax = 0
for ai in a:
h[ai] += 1
amax = max(amax, ai)
r = 0
while r + 1 < t and h[r + 1] == (r + 1) * 4:
r += 1
n = 1
while n * n <= t:
for transposed in [False, True]:
if t % n == 0:
m = t // n
c = (n - 1 - r) + (m - 1 - amax)
f = build(n, m, r, c) if not transposed else build(n, m, c, r)
if h == f:
print(f"{n} {m}")
if not transposed:
print(f"{r + 1} {c + 1}")
else:
print(f"{c + 1} {r + 1}")
exit(0)
n += 1
print('-1')
solver()
```
| 93,529 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Since Sonya has just learned the basics of matrices, she decided to play with them a little bit.
Sonya imagined a new type of matrices that she called rhombic matrices. These matrices have exactly one zero, while all other cells have the Manhattan distance to the cell containing the zero. The cells with equal numbers have the form of a rhombus, that is why Sonya called this type so.
The Manhattan distance between two cells (x_1, y_1) and (x_2, y_2) is defined as |x_1 - x_2| + |y_1 - y_2|. For example, the Manhattan distance between the cells (5, 2) and (7, 1) equals to |5-7|+|2-1|=3.
<image> Example of a rhombic matrix.
Note that rhombic matrices are uniquely defined by n, m, and the coordinates of the cell containing the zero.
She drew a nΓ m rhombic matrix. She believes that you can not recreate the matrix if she gives you only the elements of this matrix in some arbitrary order (i.e., the sequence of nβ
m numbers). Note that Sonya will not give you n and m, so only the sequence of numbers in this matrix will be at your disposal.
Write a program that finds such an nΓ m rhombic matrix whose elements are the same as the elements in the sequence in some order.
Input
The first line contains a single integer t (1β€ tβ€ 10^6) β the number of cells in the matrix.
The second line contains t integers a_1, a_2, β¦, a_t (0β€ a_i< t) β the values in the cells in arbitrary order.
Output
In the first line, print two positive integers n and m (n Γ m = t) β the size of the matrix.
In the second line, print two integers x and y (1β€ xβ€ n, 1β€ yβ€ m) β the row number and the column number where the cell with 0 is located.
If there are multiple possible answers, print any of them. If there is no solution, print the single integer -1.
Examples
Input
20
1 0 2 3 5 3 2 1 3 2 3 1 4 2 1 4 2 3 2 4
Output
4 5
2 2
Input
18
2 2 3 2 4 3 3 3 0 2 4 2 1 3 2 1 1 1
Output
3 6
2 3
Input
6
2 1 0 2 1 2
Output
-1
Note
You can see the solution to the first example in the legend. You also can choose the cell (2, 2) for the cell where 0 is located. You also can choose a 5Γ 4 matrix with zero at (4, 2).
In the second example, there is a 3Γ 6 matrix, where the zero is located at (2, 3) there.
In the third example, a solution does not exist.
Tags: brute force, constructive algorithms, implementation
Correct Solution:
```
from collections import Counter as c
def maker(m, n, x, y, a):
small, larg = min(x, y), max(x, y)
k1 = [i + 1 for i in range(small)] + [small for i in range(small, larg)] + [small + larg - i - 1 for i in range(larg, small + larg)] + [0 for i in range(small + larg, a + 1)]
small, larg = min(x, n - y + 1), max(x, n - y + 1)
k2 = [i + 1 for i in range(small)] + [small for i in range(small, larg)] + [small + larg - i - 1 for i in range(larg, small + larg)] + [0 for i in range(small + larg, a + 1)]
small, larg = min(m - x + 1, n - y + 1), max(m - x + 1, n - y + 1)
k3 = [i + 1 for i in range(small)] + [small for i in range(small, larg)] + [small + larg - i - 1 for i in range(larg, small + larg)] + [0 for i in range(small + larg, a + 1)]
small, larg = m - x + 1, y
k4 = [i + 1 for i in range(small)] + [small for i in range(small, larg)] + [small + larg - i - 1 for i in range(larg, small + larg)] + [0 for i in range(small + larg, a + 1)]
k = [k1[i] + k2[i] + k3[i] + k4[i] for i in range(a + 1)]
for i in range(x):k[i] -= 1
for i in range(y):k[i] -= 1
for i in range(m - x + 1):k[i] -= 1
for i in range(n - y + 1):k[i] -= 1
k[0] = 1
return k
t, d = int(input()), dict(c(map(int, input().split())))
if t == 1:
if 0 in d:
print(1, 1)
print(1, 1)
else:
print(-1)
else:
if any([i not in d for i in range(max(d))]):
print(-1)
else:
n, a, l, flag = int(t ** .5) + 1, max(d), [], False
d = [d[i] for i in range(a + 1)]
if d[0] != 1:
print(-1)
flag = True
if not flag:
for index in range(1, a + 1):
if d[index] > 4 * index:
print(-1)
flag = True
if d[index] < index * 4:
break
if not flag:
for m in range(2 * index - 1, n):
if not t % m:
n = t // m
if (m + n) // 2 <= a <= m + n - 2 and 2 * index - 1 <= n:
l.append((m, n))
for m, n in l:
t = [(m - index + 1, a + index + 1 - m), (a + index + 1 - n, n - index + 1)]
for x, y in t:
if m // 2 < x <= m and n // 2 < y <= n:
if d == maker(m, n, x, y, a):
print(m, n)
print(x, y)
flag = True
break
if flag:break
else:
print(-1)
```
| 93,530 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Since Sonya has just learned the basics of matrices, she decided to play with them a little bit.
Sonya imagined a new type of matrices that she called rhombic matrices. These matrices have exactly one zero, while all other cells have the Manhattan distance to the cell containing the zero. The cells with equal numbers have the form of a rhombus, that is why Sonya called this type so.
The Manhattan distance between two cells (x_1, y_1) and (x_2, y_2) is defined as |x_1 - x_2| + |y_1 - y_2|. For example, the Manhattan distance between the cells (5, 2) and (7, 1) equals to |5-7|+|2-1|=3.
<image> Example of a rhombic matrix.
Note that rhombic matrices are uniquely defined by n, m, and the coordinates of the cell containing the zero.
She drew a nΓ m rhombic matrix. She believes that you can not recreate the matrix if she gives you only the elements of this matrix in some arbitrary order (i.e., the sequence of nβ
m numbers). Note that Sonya will not give you n and m, so only the sequence of numbers in this matrix will be at your disposal.
Write a program that finds such an nΓ m rhombic matrix whose elements are the same as the elements in the sequence in some order.
Input
The first line contains a single integer t (1β€ tβ€ 10^6) β the number of cells in the matrix.
The second line contains t integers a_1, a_2, β¦, a_t (0β€ a_i< t) β the values in the cells in arbitrary order.
Output
In the first line, print two positive integers n and m (n Γ m = t) β the size of the matrix.
In the second line, print two integers x and y (1β€ xβ€ n, 1β€ yβ€ m) β the row number and the column number where the cell with 0 is located.
If there are multiple possible answers, print any of them. If there is no solution, print the single integer -1.
Examples
Input
20
1 0 2 3 5 3 2 1 3 2 3 1 4 2 1 4 2 3 2 4
Output
4 5
2 2
Input
18
2 2 3 2 4 3 3 3 0 2 4 2 1 3 2 1 1 1
Output
3 6
2 3
Input
6
2 1 0 2 1 2
Output
-1
Note
You can see the solution to the first example in the legend. You also can choose the cell (2, 2) for the cell where 0 is located. You also can choose a 5Γ 4 matrix with zero at (4, 2).
In the second example, there is a 3Γ 6 matrix, where the zero is located at (2, 3) there.
In the third example, a solution does not exist.
Tags: brute force, constructive algorithms, implementation
Correct Solution:
```
def get(n,m,a,b,t):
freq=[0]*(t+1)
for i in range(n):
for j in range(m):
val=abs(i-a)+abs(j-b)
freq[val]+=1
return freq
t=int(input())
a=list(map(int,input().split()))
mx=max(a)
f=[0]*(t+1)
for i in a:
f[i]+=1
b=1
for i in range(1,mx+1):
if f[i]!=4*i:
b=i
break
n=1
a=-1
x=0
y=0
mila=False
while n*n<=t:
if t%n==0:
m=t//n
a=n+m-mx-b
x,y=n,m
if a>0 and a<=n and b>0 and b<=m and f==get(n,m,a-1,b-1,t):
mila=True
break
if a>0 and a<=m and b>0 and b<=n and f==get(n,m,b-1,a-1,t):
mila=True
a,b=b,a
break
n+=1
if not mila:
print(-1)
else:
print(x,y)
print(a,b)
```
| 93,531 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Since Sonya has just learned the basics of matrices, she decided to play with them a little bit.
Sonya imagined a new type of matrices that she called rhombic matrices. These matrices have exactly one zero, while all other cells have the Manhattan distance to the cell containing the zero. The cells with equal numbers have the form of a rhombus, that is why Sonya called this type so.
The Manhattan distance between two cells (x_1, y_1) and (x_2, y_2) is defined as |x_1 - x_2| + |y_1 - y_2|. For example, the Manhattan distance between the cells (5, 2) and (7, 1) equals to |5-7|+|2-1|=3.
<image> Example of a rhombic matrix.
Note that rhombic matrices are uniquely defined by n, m, and the coordinates of the cell containing the zero.
She drew a nΓ m rhombic matrix. She believes that you can not recreate the matrix if she gives you only the elements of this matrix in some arbitrary order (i.e., the sequence of nβ
m numbers). Note that Sonya will not give you n and m, so only the sequence of numbers in this matrix will be at your disposal.
Write a program that finds such an nΓ m rhombic matrix whose elements are the same as the elements in the sequence in some order.
Input
The first line contains a single integer t (1β€ tβ€ 10^6) β the number of cells in the matrix.
The second line contains t integers a_1, a_2, β¦, a_t (0β€ a_i< t) β the values in the cells in arbitrary order.
Output
In the first line, print two positive integers n and m (n Γ m = t) β the size of the matrix.
In the second line, print two integers x and y (1β€ xβ€ n, 1β€ yβ€ m) β the row number and the column number where the cell with 0 is located.
If there are multiple possible answers, print any of them. If there is no solution, print the single integer -1.
Examples
Input
20
1 0 2 3 5 3 2 1 3 2 3 1 4 2 1 4 2 3 2 4
Output
4 5
2 2
Input
18
2 2 3 2 4 3 3 3 0 2 4 2 1 3 2 1 1 1
Output
3 6
2 3
Input
6
2 1 0 2 1 2
Output
-1
Note
You can see the solution to the first example in the legend. You also can choose the cell (2, 2) for the cell where 0 is located. You also can choose a 5Γ 4 matrix with zero at (4, 2).
In the second example, there is a 3Γ 6 matrix, where the zero is located at (2, 3) there.
In the third example, a solution does not exist.
Tags: brute force, constructive algorithms, implementation
Correct Solution:
```
from math import sqrt
from collections import Counter
def f(h, w, y, x):
return h * w * (h + w - (x + y + 1) * 2) // 2 + h * x * (x + 1) + w * y * (y + 1)
def check(h, w, y, x, cnt):
for i in range(1, y + 1):
for j in range(i + 1, i + x + 1):
cnt[j] -= 1
for j in range(i, i + w - x):
cnt[j] -= 1
for i in range(h - y):
for j in range(i + 1, i + x + 1):
cnt[j] -= 1
for j in range(i, i + w - x):
cnt[j] -= 1
if any(cnt.values()):
return
print(f'{h} {w}\n{y+1} {int(x)+1}')
raise TabError
def getyx(h, w, tot, cnt):
b = (w - 1) * .5
c = h * (tot - h * (w * w - 2 * w * (1 - h) - 1) * .25)
for y in range((h + 3) // 2):
d = (c - h * y * (w * y - h * w + w))
if d >= 0:
x = b - sqrt(d) / h
if x.is_integer() and x >= 0.:
check(h, w, y, int(x), cnt.copy())
def main():
n, l = int(input()), list(map(int, input().split()))
cnt, r, R, tot = Counter(l), 1, max(l), sum(l)
for r in range(1, R + 1):
if cnt[r] < r * 4:
break
try:
for h in range(r * 2 - 1, int(sqrt(n)) + 1):
if not n % h:
w = n // h
if f(h, w, h // 2, w // 2) <= tot <= f(h, w, 0, 0):
getyx(h, w, tot, cnt)
except TabError:
return
print(-1)
if __name__ == '__main__':
main()
```
| 93,532 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Since Sonya has just learned the basics of matrices, she decided to play with them a little bit.
Sonya imagined a new type of matrices that she called rhombic matrices. These matrices have exactly one zero, while all other cells have the Manhattan distance to the cell containing the zero. The cells with equal numbers have the form of a rhombus, that is why Sonya called this type so.
The Manhattan distance between two cells (x_1, y_1) and (x_2, y_2) is defined as |x_1 - x_2| + |y_1 - y_2|. For example, the Manhattan distance between the cells (5, 2) and (7, 1) equals to |5-7|+|2-1|=3.
<image> Example of a rhombic matrix.
Note that rhombic matrices are uniquely defined by n, m, and the coordinates of the cell containing the zero.
She drew a nΓ m rhombic matrix. She believes that you can not recreate the matrix if she gives you only the elements of this matrix in some arbitrary order (i.e., the sequence of nβ
m numbers). Note that Sonya will not give you n and m, so only the sequence of numbers in this matrix will be at your disposal.
Write a program that finds such an nΓ m rhombic matrix whose elements are the same as the elements in the sequence in some order.
Input
The first line contains a single integer t (1β€ tβ€ 10^6) β the number of cells in the matrix.
The second line contains t integers a_1, a_2, β¦, a_t (0β€ a_i< t) β the values in the cells in arbitrary order.
Output
In the first line, print two positive integers n and m (n Γ m = t) β the size of the matrix.
In the second line, print two integers x and y (1β€ xβ€ n, 1β€ yβ€ m) β the row number and the column number where the cell with 0 is located.
If there are multiple possible answers, print any of them. If there is no solution, print the single integer -1.
Examples
Input
20
1 0 2 3 5 3 2 1 3 2 3 1 4 2 1 4 2 3 2 4
Output
4 5
2 2
Input
18
2 2 3 2 4 3 3 3 0 2 4 2 1 3 2 1 1 1
Output
3 6
2 3
Input
6
2 1 0 2 1 2
Output
-1
Note
You can see the solution to the first example in the legend. You also can choose the cell (2, 2) for the cell where 0 is located. You also can choose a 5Γ 4 matrix with zero at (4, 2).
In the second example, there is a 3Γ 6 matrix, where the zero is located at (2, 3) there.
In the third example, a solution does not exist.
Tags: brute force, constructive algorithms, implementation
Correct Solution:
```
import sys
from collections import Counter
from itertools import chain
def i_ints():
return map(int, sys.stdin.readline().split())
def check(w, h, x, y, c):
counts = Counter(chain.from_iterable(range(abs(i-x), abs(i-x)+y) for i in range(1, w+1)))
counts += Counter(chain.from_iterable(range(abs(i-x)+1, abs(i-x)+1+(h-y)) for i in range(1, w+1)))
return c == counts
t, = i_ints()
a = Counter(i_ints())
i = 0
for i in range(1, t+1):
if a[i] != 4 * i:
break
x = i
B = max(a)
def main():
for w in range(2*x-1, int(t**0.5)+2):
if t % w:
continue
h = t // w
y = w + h - B - x
if y >= x and h >= 2*y-1 and check(w, h, x, y, a):
return "%s %s\n%s %s" % (w, h, x, y)
w, h = h, w
y = w + h - B - x
if y >= x and h >= 2*y-1 and check(w, h, x, y, a):
return "%s %s\n%s %s" % (w, h, x, y)
return -1
print(main())
```
| 93,533 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Since Sonya has just learned the basics of matrices, she decided to play with them a little bit.
Sonya imagined a new type of matrices that she called rhombic matrices. These matrices have exactly one zero, while all other cells have the Manhattan distance to the cell containing the zero. The cells with equal numbers have the form of a rhombus, that is why Sonya called this type so.
The Manhattan distance between two cells (x_1, y_1) and (x_2, y_2) is defined as |x_1 - x_2| + |y_1 - y_2|. For example, the Manhattan distance between the cells (5, 2) and (7, 1) equals to |5-7|+|2-1|=3.
<image> Example of a rhombic matrix.
Note that rhombic matrices are uniquely defined by n, m, and the coordinates of the cell containing the zero.
She drew a nΓ m rhombic matrix. She believes that you can not recreate the matrix if she gives you only the elements of this matrix in some arbitrary order (i.e., the sequence of nβ
m numbers). Note that Sonya will not give you n and m, so only the sequence of numbers in this matrix will be at your disposal.
Write a program that finds such an nΓ m rhombic matrix whose elements are the same as the elements in the sequence in some order.
Input
The first line contains a single integer t (1β€ tβ€ 10^6) β the number of cells in the matrix.
The second line contains t integers a_1, a_2, β¦, a_t (0β€ a_i< t) β the values in the cells in arbitrary order.
Output
In the first line, print two positive integers n and m (n Γ m = t) β the size of the matrix.
In the second line, print two integers x and y (1β€ xβ€ n, 1β€ yβ€ m) β the row number and the column number where the cell with 0 is located.
If there are multiple possible answers, print any of them. If there is no solution, print the single integer -1.
Examples
Input
20
1 0 2 3 5 3 2 1 3 2 3 1 4 2 1 4 2 3 2 4
Output
4 5
2 2
Input
18
2 2 3 2 4 3 3 3 0 2 4 2 1 3 2 1 1 1
Output
3 6
2 3
Input
6
2 1 0 2 1 2
Output
-1
Note
You can see the solution to the first example in the legend. You also can choose the cell (2, 2) for the cell where 0 is located. You also can choose a 5Γ 4 matrix with zero at (4, 2).
In the second example, there is a 3Γ 6 matrix, where the zero is located at (2, 3) there.
In the third example, a solution does not exist.
Submitted Solution:
```
from collections import Counter as c
def xsum(h, w, x, y):
return h * w * (h + w - (x + y + 1) * 2) // 2 + w * x * (x + 1) + h * y * (y + 1)
def maker(m, n, x, y, a):
small, larg = min(x, y), max(x, y)
k1 = [i + 1 for i in range(small)] + [small for i in range(small, larg)] + [small + larg - i - 1 for i in range(larg, small + larg)] + [0 for i in range(small + larg, a + 1)]
small, larg = min(x, n - y + 1), max(x, n - y + 1)
k2 = [i + 1 for i in range(small)] + [small for i in range(small, larg)] + [small + larg - i - 1 for i in range(larg, small + larg)] + [0 for i in range(small + larg, a + 1)]
small, larg = min(m - x + 1, n - y + 1), max(m - x + 1, n - y + 1)
k3 = [i + 1 for i in range(small)] + [small for i in range(small, larg)] + [small + larg - i - 1 for i in range(larg, small + larg)] + [0 for i in range(small + larg, a + 1)]
small, larg = m - x + 1, y
k4 = [i + 1 for i in range(small)] + [small for i in range(small, larg)] + [small + larg - i - 1 for i in range(larg, small + larg)] + [0 for i in range(small + larg, a + 1)]
k = [k1[i] + k2[i] + k3[i] + k4[i] for i in range(a + 1)]
for i in range(x):k[i] -= 1
for i in range(y):k[i] -= 1
for i in range(a-x+1):k[i] -= 1
for i in range(b-y+1):k[i] -= 1
k[0] = 0
return k
t, d = int(input()), dict(c(map(int, input().split())))
n, a, l = int(t ** .5) + 1, max(d), []
d = [d[i] for i in range(a + 1)]
tot = sum([i * d[i] for i in range(a + 1)])
if d[0] != 1:
print(-1)
exit()
for index in range(1, a + 1):
if d[index] > 4 * index:
print(-1)
exit()
if d[index] < index * 4:
break
for m in range(2 * index - 1, n):
if not t % m:
n = t // m
if (m + n) // 2 <= a <= m + n - 2 and 2 * index - 1 <= n and xsum(m, n, m // 2, n // 2) <= tot <= xsum(m, n, 0, 0):
l.append((m, n))
for m, n in l:
t = [(m - index + 1, a + index + 1 - m), (a + index + 1 - n, n - index + 1)]
for x, y in t:
if m // 2 < x <= m and n // 2 < y <= n and xsum(m, n, x, y) == tot:
if d == maker(m, n, x, y, a):
print(m, n)
print(x, y)
exit()
else:
print(-1)
```
No
| 93,534 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Since Sonya has just learned the basics of matrices, she decided to play with them a little bit.
Sonya imagined a new type of matrices that she called rhombic matrices. These matrices have exactly one zero, while all other cells have the Manhattan distance to the cell containing the zero. The cells with equal numbers have the form of a rhombus, that is why Sonya called this type so.
The Manhattan distance between two cells (x_1, y_1) and (x_2, y_2) is defined as |x_1 - x_2| + |y_1 - y_2|. For example, the Manhattan distance between the cells (5, 2) and (7, 1) equals to |5-7|+|2-1|=3.
<image> Example of a rhombic matrix.
Note that rhombic matrices are uniquely defined by n, m, and the coordinates of the cell containing the zero.
She drew a nΓ m rhombic matrix. She believes that you can not recreate the matrix if she gives you only the elements of this matrix in some arbitrary order (i.e., the sequence of nβ
m numbers). Note that Sonya will not give you n and m, so only the sequence of numbers in this matrix will be at your disposal.
Write a program that finds such an nΓ m rhombic matrix whose elements are the same as the elements in the sequence in some order.
Input
The first line contains a single integer t (1β€ tβ€ 10^6) β the number of cells in the matrix.
The second line contains t integers a_1, a_2, β¦, a_t (0β€ a_i< t) β the values in the cells in arbitrary order.
Output
In the first line, print two positive integers n and m (n Γ m = t) β the size of the matrix.
In the second line, print two integers x and y (1β€ xβ€ n, 1β€ yβ€ m) β the row number and the column number where the cell with 0 is located.
If there are multiple possible answers, print any of them. If there is no solution, print the single integer -1.
Examples
Input
20
1 0 2 3 5 3 2 1 3 2 3 1 4 2 1 4 2 3 2 4
Output
4 5
2 2
Input
18
2 2 3 2 4 3 3 3 0 2 4 2 1 3 2 1 1 1
Output
3 6
2 3
Input
6
2 1 0 2 1 2
Output
-1
Note
You can see the solution to the first example in the legend. You also can choose the cell (2, 2) for the cell where 0 is located. You also can choose a 5Γ 4 matrix with zero at (4, 2).
In the second example, there is a 3Γ 6 matrix, where the zero is located at (2, 3) there.
In the third example, a solution does not exist.
Submitted Solution:
```
from collections import Counter as c
def area(h, w, x, y):
return h * w * (h + w - (x + y + 1) * 2) // 2 + w * x * (x + 1) + h * y * (y + 1)
t, d = int(input()), dict(c(map(int, input().split())))
n, a, l, flag = int(t ** .5) + 1, max(d), [], False
d = [d[i] for i in range(a + 1)]
tot = sum([i * d[i] for i in range(a + 1)])
if d[0] != 1:
print(-1)
exit()
for i in range(1, a + 1):
if d[i] > 4 * i:
print(-1)
exit()
for index in range(1, a + 1):
if d[index] < index * 4:
break
for m in range(2 * index - 1, n):
if t % m == 0:
n = t // m
if (m + n) // 2 <= a <= m + n - 2 and 2 * index - 1 <= n and area(m, n, m // 2, n // 2) <= tot <= area(m, n, 0, 0):
l.append((m, n))
for m, n in l:
t = [(m - index + 1, a + index + 1 - m), (a + index + 1 - n, n - index + 1)]
for x, y in t:
if m // 2 < x <= m and n // 2 < y <= n and area(m, n, x, y) == tot:
for i in range(1, m + 1):
for j in range(1, n + 1):
d[abs(i - x) + abs(j - y)] -= 1
if set(d) == {0}:
print(m, n)
print(x, y)
flag = True
break
for i in range(1, m + 1):
for j in range(1, n + 1):
d[abs(i - x) + abs(j - y)] += 1
if flag:break
else:
print(-1)
```
No
| 93,535 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Since Sonya has just learned the basics of matrices, she decided to play with them a little bit.
Sonya imagined a new type of matrices that she called rhombic matrices. These matrices have exactly one zero, while all other cells have the Manhattan distance to the cell containing the zero. The cells with equal numbers have the form of a rhombus, that is why Sonya called this type so.
The Manhattan distance between two cells (x_1, y_1) and (x_2, y_2) is defined as |x_1 - x_2| + |y_1 - y_2|. For example, the Manhattan distance between the cells (5, 2) and (7, 1) equals to |5-7|+|2-1|=3.
<image> Example of a rhombic matrix.
Note that rhombic matrices are uniquely defined by n, m, and the coordinates of the cell containing the zero.
She drew a nΓ m rhombic matrix. She believes that you can not recreate the matrix if she gives you only the elements of this matrix in some arbitrary order (i.e., the sequence of nβ
m numbers). Note that Sonya will not give you n and m, so only the sequence of numbers in this matrix will be at your disposal.
Write a program that finds such an nΓ m rhombic matrix whose elements are the same as the elements in the sequence in some order.
Input
The first line contains a single integer t (1β€ tβ€ 10^6) β the number of cells in the matrix.
The second line contains t integers a_1, a_2, β¦, a_t (0β€ a_i< t) β the values in the cells in arbitrary order.
Output
In the first line, print two positive integers n and m (n Γ m = t) β the size of the matrix.
In the second line, print two integers x and y (1β€ xβ€ n, 1β€ yβ€ m) β the row number and the column number where the cell with 0 is located.
If there are multiple possible answers, print any of them. If there is no solution, print the single integer -1.
Examples
Input
20
1 0 2 3 5 3 2 1 3 2 3 1 4 2 1 4 2 3 2 4
Output
4 5
2 2
Input
18
2 2 3 2 4 3 3 3 0 2 4 2 1 3 2 1 1 1
Output
3 6
2 3
Input
6
2 1 0 2 1 2
Output
-1
Note
You can see the solution to the first example in the legend. You also can choose the cell (2, 2) for the cell where 0 is located. You also can choose a 5Γ 4 matrix with zero at (4, 2).
In the second example, there is a 3Γ 6 matrix, where the zero is located at (2, 3) there.
In the third example, a solution does not exist.
Submitted Solution:
```
from collections import defaultdict
import math
s = int(input())
ls = [int(i) for i in input().split()]
cnt = defaultdict(int)
for i in ls:
cnt[i] += 1
b = max(ls)
y, n, m = -1, -1, -1
x = 1
while cnt[x] == 4 * x:
x += 1
f = int(math.sqrt(s))
for i in range(x, s+1):
if i > f:
break
if s % i != 0:
continue
n, m = i, s // i
# if n + m - b - x < m:
# continue
y = n + m - b - x
if x - 1 + y - 1 != x:
y = -1
continue
break
if y == -1:
exit(print(-1))
print(n, ' ', m)
print(x, ' ', y)
```
No
| 93,536 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Since Sonya has just learned the basics of matrices, she decided to play with them a little bit.
Sonya imagined a new type of matrices that she called rhombic matrices. These matrices have exactly one zero, while all other cells have the Manhattan distance to the cell containing the zero. The cells with equal numbers have the form of a rhombus, that is why Sonya called this type so.
The Manhattan distance between two cells (x_1, y_1) and (x_2, y_2) is defined as |x_1 - x_2| + |y_1 - y_2|. For example, the Manhattan distance between the cells (5, 2) and (7, 1) equals to |5-7|+|2-1|=3.
<image> Example of a rhombic matrix.
Note that rhombic matrices are uniquely defined by n, m, and the coordinates of the cell containing the zero.
She drew a nΓ m rhombic matrix. She believes that you can not recreate the matrix if she gives you only the elements of this matrix in some arbitrary order (i.e., the sequence of nβ
m numbers). Note that Sonya will not give you n and m, so only the sequence of numbers in this matrix will be at your disposal.
Write a program that finds such an nΓ m rhombic matrix whose elements are the same as the elements in the sequence in some order.
Input
The first line contains a single integer t (1β€ tβ€ 10^6) β the number of cells in the matrix.
The second line contains t integers a_1, a_2, β¦, a_t (0β€ a_i< t) β the values in the cells in arbitrary order.
Output
In the first line, print two positive integers n and m (n Γ m = t) β the size of the matrix.
In the second line, print two integers x and y (1β€ xβ€ n, 1β€ yβ€ m) β the row number and the column number where the cell with 0 is located.
If there are multiple possible answers, print any of them. If there is no solution, print the single integer -1.
Examples
Input
20
1 0 2 3 5 3 2 1 3 2 3 1 4 2 1 4 2 3 2 4
Output
4 5
2 2
Input
18
2 2 3 2 4 3 3 3 0 2 4 2 1 3 2 1 1 1
Output
3 6
2 3
Input
6
2 1 0 2 1 2
Output
-1
Note
You can see the solution to the first example in the legend. You also can choose the cell (2, 2) for the cell where 0 is located. You also can choose a 5Γ 4 matrix with zero at (4, 2).
In the second example, there is a 3Γ 6 matrix, where the zero is located at (2, 3) there.
In the third example, a solution does not exist.
Submitted Solution:
```
def get(n,m,a,b,t):
freq=[0]*(t+1)
for i in range(n):
for j in range(m):
val=abs(i-a)+abs(j-b)
freq[val]+=1
return freq
t=int(input())
a=list(map(int,input().split()))
mx=max(a)
f=[0]*(t+1)
for i in a:
f[i]+=1
b=-1
for i in range(1,mx+1):
if f[i]!=4*i:
b=i
break
n=1
a=-1
x=0
y=0
mila=False
while n*n<=t:
if t%n==0:
m=t//n
a=n+m-mx-b-2
x,y=n,m
if a>=0 and a<n and b>=0 and b<m and f==get(n,m,a,b,t):
mila=True
break
if a>=0 and a<m and b>=0 and b<n and f==get(n,m,b,a,t):
mila=True
a,b=b,a
break
n+=1
if not mila:
print(-1)
else:
print(x,y)
print(a+1,b+1)
```
No
| 93,537 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price.
At every moment of time, every SELL offer has higher price than every BUY offer.
In this problem no two ever existed orders will have the same price.
The lowest-price SELL order and the highest-price BUY order are called the best offers, marked with black frames on the picture below.
<image> The presented order book says that someone wants to sell the product at price 12 and it's the best SELL offer because the other two have higher prices. The best BUY offer has price 10.
There are two possible actions in this orderbook:
1. Somebody adds a new order of some direction with some price.
2. Somebody accepts the best possible SELL or BUY offer (makes a deal). It's impossible to accept not the best SELL or BUY offer (to make a deal at worse price). After someone accepts the offer, it is removed from the orderbook forever.
It is allowed to add new BUY order only with prices less than the best SELL offer (if you want to buy stock for higher price, then instead of adding an order you should accept the best SELL offer). Similarly, one couldn't add a new SELL order with price less or equal to the best BUY offer. For example, you can't add a new offer "SELL 20" if there is already an offer "BUY 20" or "BUY 25" β in this case you just accept the best BUY offer.
You have a damaged order book log (in the beginning the are no orders in book). Every action has one of the two types:
1. "ADD p" denotes adding a new order with price p and unknown direction. The order must not contradict with orders still not removed from the order book.
2. "ACCEPT p" denotes accepting an existing best offer with price p and unknown direction.
The directions of all actions are lost. Information from the log isn't always enough to determine these directions. Count the number of ways to correctly restore all ADD action directions so that all the described conditions are satisfied at any moment. Since the answer could be large, output it modulo 10^9 + 7. If it is impossible to correctly restore directions, then output 0.
Input
The first line contains an integer n (1 β€ n β€ 363 304) β the number of actions in the log.
Each of the next n lines contains a string "ACCEPT" or "ADD" and an integer p (1 β€ p β€ 308 983 066), describing an action type and price.
All ADD actions have different prices. For ACCEPT action it is guaranteed that the order with the same price has already been added but has not been accepted yet.
Output
Output the number of ways to restore directions of ADD actions modulo 10^9 + 7.
Examples
Input
6
ADD 1
ACCEPT 1
ADD 2
ACCEPT 2
ADD 3
ACCEPT 3
Output
8
Input
4
ADD 1
ADD 2
ADD 3
ACCEPT 2
Output
2
Input
7
ADD 1
ADD 2
ADD 3
ADD 4
ADD 5
ACCEPT 3
ACCEPT 5
Output
0
Note
In the first example each of orders may be BUY or SELL.
In the second example the order with price 1 has to be BUY order, the order with the price 3 has to be SELL order.
Tags: combinatorics, data structures, greedy
Correct Solution:
```
import heapq
n = int(input())
buy = [] # negative
sell = []
unknown = []
res = 1
for i in range(n):
cmd, amount = input().strip().split()
amount = int(amount)
if cmd == 'ADD':
if sell and sell[0] < amount:
heapq.heappush(sell, amount)
elif buy and -buy[0] > amount:
heapq.heappush(buy, -amount)
else:
unknown.append(amount)
else:
if (sell and amount > sell[0]) or (buy and amount < -buy[0]):
print(0)
exit(0)
if sell and amount == sell[0]:
heapq.heappop(sell)
elif buy and amount == -buy[0]:
heapq.heappop(buy)
else:
res = res * 2 % 1000000007
for x in unknown:
if x < amount:
heapq.heappush(buy, -x)
elif x > amount:
heapq.heappush(sell, x)
unknown = []
res = res * (len(unknown) + 1) % 1000000007
print(res)
```
| 93,538 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price.
At every moment of time, every SELL offer has higher price than every BUY offer.
In this problem no two ever existed orders will have the same price.
The lowest-price SELL order and the highest-price BUY order are called the best offers, marked with black frames on the picture below.
<image> The presented order book says that someone wants to sell the product at price 12 and it's the best SELL offer because the other two have higher prices. The best BUY offer has price 10.
There are two possible actions in this orderbook:
1. Somebody adds a new order of some direction with some price.
2. Somebody accepts the best possible SELL or BUY offer (makes a deal). It's impossible to accept not the best SELL or BUY offer (to make a deal at worse price). After someone accepts the offer, it is removed from the orderbook forever.
It is allowed to add new BUY order only with prices less than the best SELL offer (if you want to buy stock for higher price, then instead of adding an order you should accept the best SELL offer). Similarly, one couldn't add a new SELL order with price less or equal to the best BUY offer. For example, you can't add a new offer "SELL 20" if there is already an offer "BUY 20" or "BUY 25" β in this case you just accept the best BUY offer.
You have a damaged order book log (in the beginning the are no orders in book). Every action has one of the two types:
1. "ADD p" denotes adding a new order with price p and unknown direction. The order must not contradict with orders still not removed from the order book.
2. "ACCEPT p" denotes accepting an existing best offer with price p and unknown direction.
The directions of all actions are lost. Information from the log isn't always enough to determine these directions. Count the number of ways to correctly restore all ADD action directions so that all the described conditions are satisfied at any moment. Since the answer could be large, output it modulo 10^9 + 7. If it is impossible to correctly restore directions, then output 0.
Input
The first line contains an integer n (1 β€ n β€ 363 304) β the number of actions in the log.
Each of the next n lines contains a string "ACCEPT" or "ADD" and an integer p (1 β€ p β€ 308 983 066), describing an action type and price.
All ADD actions have different prices. For ACCEPT action it is guaranteed that the order with the same price has already been added but has not been accepted yet.
Output
Output the number of ways to restore directions of ADD actions modulo 10^9 + 7.
Examples
Input
6
ADD 1
ACCEPT 1
ADD 2
ACCEPT 2
ADD 3
ACCEPT 3
Output
8
Input
4
ADD 1
ADD 2
ADD 3
ACCEPT 2
Output
2
Input
7
ADD 1
ADD 2
ADD 3
ADD 4
ADD 5
ACCEPT 3
ACCEPT 5
Output
0
Note
In the first example each of orders may be BUY or SELL.
In the second example the order with price 1 has to be BUY order, the order with the price 3 has to be SELL order.
Tags: combinatorics, data structures, greedy
Correct Solution:
```
import heapq
n = int(input())
ans = 1
mod = 10**9 + 7
buy, undefined, sell = [], [], []
for i in range(n):
cmd, str_p = input().split()
p = int(str_p)
if cmd == 'ADD':
if buy and p < -buy[0]:
heapq.heappush(buy, -p)
elif sell and p > sell[0]:
heapq.heappush(sell, p)
else:
undefined.append(p)
else:
if (buy and p < -buy[0]) or (sell and p > sell[0]):
ans = 0
break
elif buy and p == -buy[0]:
heapq.heappop(buy)
elif sell and p == sell[0]:
heapq.heappop(sell)
else:
ans = (ans << 1) % mod
for x in undefined:
if x < p:
heapq.heappush(buy, -x)
elif x > p:
heapq.heappush(sell, x)
undefined = []
ans = ans * (len(undefined) + 1) % mod
print(ans)
```
| 93,539 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price.
At every moment of time, every SELL offer has higher price than every BUY offer.
In this problem no two ever existed orders will have the same price.
The lowest-price SELL order and the highest-price BUY order are called the best offers, marked with black frames on the picture below.
<image> The presented order book says that someone wants to sell the product at price 12 and it's the best SELL offer because the other two have higher prices. The best BUY offer has price 10.
There are two possible actions in this orderbook:
1. Somebody adds a new order of some direction with some price.
2. Somebody accepts the best possible SELL or BUY offer (makes a deal). It's impossible to accept not the best SELL or BUY offer (to make a deal at worse price). After someone accepts the offer, it is removed from the orderbook forever.
It is allowed to add new BUY order only with prices less than the best SELL offer (if you want to buy stock for higher price, then instead of adding an order you should accept the best SELL offer). Similarly, one couldn't add a new SELL order with price less or equal to the best BUY offer. For example, you can't add a new offer "SELL 20" if there is already an offer "BUY 20" or "BUY 25" β in this case you just accept the best BUY offer.
You have a damaged order book log (in the beginning the are no orders in book). Every action has one of the two types:
1. "ADD p" denotes adding a new order with price p and unknown direction. The order must not contradict with orders still not removed from the order book.
2. "ACCEPT p" denotes accepting an existing best offer with price p and unknown direction.
The directions of all actions are lost. Information from the log isn't always enough to determine these directions. Count the number of ways to correctly restore all ADD action directions so that all the described conditions are satisfied at any moment. Since the answer could be large, output it modulo 10^9 + 7. If it is impossible to correctly restore directions, then output 0.
Input
The first line contains an integer n (1 β€ n β€ 363 304) β the number of actions in the log.
Each of the next n lines contains a string "ACCEPT" or "ADD" and an integer p (1 β€ p β€ 308 983 066), describing an action type and price.
All ADD actions have different prices. For ACCEPT action it is guaranteed that the order with the same price has already been added but has not been accepted yet.
Output
Output the number of ways to restore directions of ADD actions modulo 10^9 + 7.
Examples
Input
6
ADD 1
ACCEPT 1
ADD 2
ACCEPT 2
ADD 3
ACCEPT 3
Output
8
Input
4
ADD 1
ADD 2
ADD 3
ACCEPT 2
Output
2
Input
7
ADD 1
ADD 2
ADD 3
ADD 4
ADD 5
ACCEPT 3
ACCEPT 5
Output
0
Note
In the first example each of orders may be BUY or SELL.
In the second example the order with price 1 has to be BUY order, the order with the price 3 has to be SELL order.
Tags: combinatorics, data structures, greedy
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
#import threading
from collections import defaultdict
#threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
#sys.setrecursionlimit(300000)
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")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
class SegmentTree2:
def __init__(self, data, default=3000006, func=lambda a, b: min(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=10**10, func=lambda a, b: min(a , b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b:a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] <key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] > k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.isEndOfWord = False
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def _charToIndex(self, ch):
return ord(ch) - ord('a')
def insert(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
pCrawl.children[index] = self.getNode()
pCrawl = pCrawl.children[index]
pCrawl.isEndOfWord = True
def search(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
return False
pCrawl = pCrawl.children[index]
return pCrawl != None and pCrawl.isEndOfWord
#-----------------------------------------trie---------------------------------
class Node:
def __init__(self, data):
self.data = data
self.count=0
self.left = None # left node for 0
self.right = None # right node for 1
class BinaryTrie:
def __init__(self):
self.root = Node(0)
def insert(self, pre_xor,t):
self.temp = self.root
for i in range(31, -1, -1):
val = pre_xor & (1 << i)
if val:
if not self.temp.right:
self.temp.right = Node(0)
self.temp = self.temp.right
self.temp.count+=t
if not val:
if not self.temp.left:
self.temp.left = Node(0)
self.temp = self.temp.left
self.temp.count += t
self.temp.data = pre_xor
def query(self, p,l):
ans=0
self.temp = self.root
for i in range(31, -1, -1):
val = p & (1 << i)
val1= l & (1<<i)
if val1==0:
if val==0:
if self.temp.left and self.temp.left.count>0:
self.temp = self.temp.left
else:
return ans
else:
if self.temp.right and self.temp.right.count>0:
self.temp = self.temp.right
else:
return ans
else:
if val !=0 :
if self.temp.right:
ans+=self.temp.right.count
if self.temp.left and self.temp.left.count > 0:
self.temp = self.temp.left
else:
return ans
else:
if self.temp.left:
ans += self.temp.left.count
if self.temp.right and self.temp.right.count > 0:
self.temp = self.temp.right
else:
return ans
return ans
#-------------------------bin trie-------------------------------------------
n=int(input())
l=[]
w=[]
for i in range(n):
typ,a=map(str,input().split())
l.append((typ,a))
w.append(a)
w.sort()
ind=defaultdict(int)
for i in range(len(w)):
ind[w[i]]=i
nex=-1
ne=[-1]*n
for i in range(n-1,-1,-1):
typ,a=l[i]
if typ=="ACCEPT":
nex=int(a)
else:
ne[i]=nex
ans=1
buy=[]
sell=[]
heapq.heapify(buy)
heapq.heapify(sell)
t=0
for i in range(n):
typ,a=l[i]
a=int(a)
nex=ne[i]
if typ=="ADD":
if nex==-1:
if len(buy) > 0 and buy[0] * (-1) > a:
heapq.heappush(buy, -a)
elif len(sell) > 0 and sell[0] < a:
heapq.heappush(sell, a)
else:
t+=1
continue
if nex>a:
heapq.heappush(buy,-a)
elif nex<a:
heapq.heappush(sell,a)
else:
if len(buy)>0 and buy[0]*(-1)>a:
heapq.heappush(buy, -a)
elif len(sell)>0 and sell[0]<a:
heapq.heappush(sell, a)
else:
heapq.heappush(buy, -a)
heapq.heappush(sell, a)
ans*=2
ans%=mod
else:
w=0
w1=308983067
if len(buy)>0:
w=heapq.heappop(buy)
if len(sell)>0:
w1=heapq.heappop(sell)
w*=-1
if a!=w and a!=w1:
ans=0
break
else:
if a!=w and w!=0:
heapq.heappush(buy,-w)
if a!=w1 and w1!=308983067:
heapq.heappush(sell,w1)
#print(ans)
ans*=(t+1)
ans%=mod
print(ans)
```
| 93,540 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price.
At every moment of time, every SELL offer has higher price than every BUY offer.
In this problem no two ever existed orders will have the same price.
The lowest-price SELL order and the highest-price BUY order are called the best offers, marked with black frames on the picture below.
<image> The presented order book says that someone wants to sell the product at price 12 and it's the best SELL offer because the other two have higher prices. The best BUY offer has price 10.
There are two possible actions in this orderbook:
1. Somebody adds a new order of some direction with some price.
2. Somebody accepts the best possible SELL or BUY offer (makes a deal). It's impossible to accept not the best SELL or BUY offer (to make a deal at worse price). After someone accepts the offer, it is removed from the orderbook forever.
It is allowed to add new BUY order only with prices less than the best SELL offer (if you want to buy stock for higher price, then instead of adding an order you should accept the best SELL offer). Similarly, one couldn't add a new SELL order with price less or equal to the best BUY offer. For example, you can't add a new offer "SELL 20" if there is already an offer "BUY 20" or "BUY 25" β in this case you just accept the best BUY offer.
You have a damaged order book log (in the beginning the are no orders in book). Every action has one of the two types:
1. "ADD p" denotes adding a new order with price p and unknown direction. The order must not contradict with orders still not removed from the order book.
2. "ACCEPT p" denotes accepting an existing best offer with price p and unknown direction.
The directions of all actions are lost. Information from the log isn't always enough to determine these directions. Count the number of ways to correctly restore all ADD action directions so that all the described conditions are satisfied at any moment. Since the answer could be large, output it modulo 10^9 + 7. If it is impossible to correctly restore directions, then output 0.
Input
The first line contains an integer n (1 β€ n β€ 363 304) β the number of actions in the log.
Each of the next n lines contains a string "ACCEPT" or "ADD" and an integer p (1 β€ p β€ 308 983 066), describing an action type and price.
All ADD actions have different prices. For ACCEPT action it is guaranteed that the order with the same price has already been added but has not been accepted yet.
Output
Output the number of ways to restore directions of ADD actions modulo 10^9 + 7.
Examples
Input
6
ADD 1
ACCEPT 1
ADD 2
ACCEPT 2
ADD 3
ACCEPT 3
Output
8
Input
4
ADD 1
ADD 2
ADD 3
ACCEPT 2
Output
2
Input
7
ADD 1
ADD 2
ADD 3
ADD 4
ADD 5
ACCEPT 3
ACCEPT 5
Output
0
Note
In the first example each of orders may be BUY or SELL.
In the second example the order with price 1 has to be BUY order, the order with the price 3 has to be SELL order.
Tags: combinatorics, data structures, greedy
Correct Solution:
```
from sys import stdin
import heapq
MOD = pow(10, 9) + 7
n=int(stdin.readline())
a=[]
for i in range(n):
x=stdin.readline().split()
if x[0]=='ADD':
a.append((0,int(x[1])))
else:
a.append((1,int(x[1])))
next_accept=[-1]*n
accept = -1
for i in range(n-1, -1, -1):
if a[i][0]== 1:
accept=i
next_accept[i] = accept
top = []
bottom = []
buysell_n = 0
last_n=0
invalid = False
for i in range(n):
if a[i][0] == 0:
if next_accept[i] != -1:
if a[i][1] > a[next_accept[i]][1]:
heapq.heappush(top, a[i][1])
elif a[i][1] < a[next_accept[i]][1]:
heapq.heappush(bottom, -a[i][1])
elif (len(top) == 0 or a[i][1] < top[0]) and (len(bottom) == 0 or a[i][1] > -bottom[0]):
last_n += 1
else:
if len(top) > 0 and a[i][1] == top[0]:
heapq.heappop(top)
elif len(bottom) > 0 and a[i][1] == -bottom[0]:
heapq.heappop(bottom)
else:
if len(top) > 0 and a[i][1] > top[0] or len(bottom) > 0 and a[i][1] < -bottom[0]:
invalid = True
break
buysell_n += 1
if invalid:
ans = 0
else:
ans = (pow(2, buysell_n, MOD)*(last_n+1))%MOD
print(ans)
```
| 93,541 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price.
At every moment of time, every SELL offer has higher price than every BUY offer.
In this problem no two ever existed orders will have the same price.
The lowest-price SELL order and the highest-price BUY order are called the best offers, marked with black frames on the picture below.
<image> The presented order book says that someone wants to sell the product at price 12 and it's the best SELL offer because the other two have higher prices. The best BUY offer has price 10.
There are two possible actions in this orderbook:
1. Somebody adds a new order of some direction with some price.
2. Somebody accepts the best possible SELL or BUY offer (makes a deal). It's impossible to accept not the best SELL or BUY offer (to make a deal at worse price). After someone accepts the offer, it is removed from the orderbook forever.
It is allowed to add new BUY order only with prices less than the best SELL offer (if you want to buy stock for higher price, then instead of adding an order you should accept the best SELL offer). Similarly, one couldn't add a new SELL order with price less or equal to the best BUY offer. For example, you can't add a new offer "SELL 20" if there is already an offer "BUY 20" or "BUY 25" β in this case you just accept the best BUY offer.
You have a damaged order book log (in the beginning the are no orders in book). Every action has one of the two types:
1. "ADD p" denotes adding a new order with price p and unknown direction. The order must not contradict with orders still not removed from the order book.
2. "ACCEPT p" denotes accepting an existing best offer with price p and unknown direction.
The directions of all actions are lost. Information from the log isn't always enough to determine these directions. Count the number of ways to correctly restore all ADD action directions so that all the described conditions are satisfied at any moment. Since the answer could be large, output it modulo 10^9 + 7. If it is impossible to correctly restore directions, then output 0.
Input
The first line contains an integer n (1 β€ n β€ 363 304) β the number of actions in the log.
Each of the next n lines contains a string "ACCEPT" or "ADD" and an integer p (1 β€ p β€ 308 983 066), describing an action type and price.
All ADD actions have different prices. For ACCEPT action it is guaranteed that the order with the same price has already been added but has not been accepted yet.
Output
Output the number of ways to restore directions of ADD actions modulo 10^9 + 7.
Examples
Input
6
ADD 1
ACCEPT 1
ADD 2
ACCEPT 2
ADD 3
ACCEPT 3
Output
8
Input
4
ADD 1
ADD 2
ADD 3
ACCEPT 2
Output
2
Input
7
ADD 1
ADD 2
ADD 3
ADD 4
ADD 5
ACCEPT 3
ACCEPT 5
Output
0
Note
In the first example each of orders may be BUY or SELL.
In the second example the order with price 1 has to be BUY order, the order with the price 3 has to be SELL order.
Tags: combinatorics, data structures, greedy
Correct Solution:
```
from sys import exit
from heapq import heapify,heappush,heappop
n=int(input())
low=[]
high=[]
pos=0
mid=set()
for i in range(n):
#print(high,low,mid)
s=input().split()
#print(s)
x=int(s[1])
s=s[0]
#print(s[0],s[0]=='ADD')
if(s=='ADD'):
if(len(low) and x<-1*low[0]):
heappush(low,(-x))
elif(len(high) and x>high[0]):
heappush(high,x)
else:
mid.add(x)
else:
if(len(low) and x==-low[0]):
heappop(low)
elif(len(high) and x==high[0]):
heappop(high)
elif(x in mid):
pos+=1
else:
print(0)
exit()
for j in mid:
if(j>x):
heappush(high,j)
elif(j<x):
heappush(low,-j)
mid=set()
mod=int(1e9+7)
print((pow(2,pos,mod)*(len(mid)+1))%mod)
```
| 93,542 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price.
At every moment of time, every SELL offer has higher price than every BUY offer.
In this problem no two ever existed orders will have the same price.
The lowest-price SELL order and the highest-price BUY order are called the best offers, marked with black frames on the picture below.
<image> The presented order book says that someone wants to sell the product at price 12 and it's the best SELL offer because the other two have higher prices. The best BUY offer has price 10.
There are two possible actions in this orderbook:
1. Somebody adds a new order of some direction with some price.
2. Somebody accepts the best possible SELL or BUY offer (makes a deal). It's impossible to accept not the best SELL or BUY offer (to make a deal at worse price). After someone accepts the offer, it is removed from the orderbook forever.
It is allowed to add new BUY order only with prices less than the best SELL offer (if you want to buy stock for higher price, then instead of adding an order you should accept the best SELL offer). Similarly, one couldn't add a new SELL order with price less or equal to the best BUY offer. For example, you can't add a new offer "SELL 20" if there is already an offer "BUY 20" or "BUY 25" β in this case you just accept the best BUY offer.
You have a damaged order book log (in the beginning the are no orders in book). Every action has one of the two types:
1. "ADD p" denotes adding a new order with price p and unknown direction. The order must not contradict with orders still not removed from the order book.
2. "ACCEPT p" denotes accepting an existing best offer with price p and unknown direction.
The directions of all actions are lost. Information from the log isn't always enough to determine these directions. Count the number of ways to correctly restore all ADD action directions so that all the described conditions are satisfied at any moment. Since the answer could be large, output it modulo 10^9 + 7. If it is impossible to correctly restore directions, then output 0.
Input
The first line contains an integer n (1 β€ n β€ 363 304) β the number of actions in the log.
Each of the next n lines contains a string "ACCEPT" or "ADD" and an integer p (1 β€ p β€ 308 983 066), describing an action type and price.
All ADD actions have different prices. For ACCEPT action it is guaranteed that the order with the same price has already been added but has not been accepted yet.
Output
Output the number of ways to restore directions of ADD actions modulo 10^9 + 7.
Examples
Input
6
ADD 1
ACCEPT 1
ADD 2
ACCEPT 2
ADD 3
ACCEPT 3
Output
8
Input
4
ADD 1
ADD 2
ADD 3
ACCEPT 2
Output
2
Input
7
ADD 1
ADD 2
ADD 3
ADD 4
ADD 5
ACCEPT 3
ACCEPT 5
Output
0
Note
In the first example each of orders may be BUY or SELL.
In the second example the order with price 1 has to be BUY order, the order with the price 3 has to be SELL order.
Tags: combinatorics, data structures, greedy
Correct Solution:
```
from sys import stdin
from heapq import heappush, heappop
def main():
n, r, m = int(input()), 0, 1000000007
bb, ss, bs = [0], [m], []
for s in stdin.read().splitlines():
if s[1] == 'D':
p = int(s[4:])
if ss and ss[0] < p:
heappush(ss, p)
elif bb and -bb[0] > p:
heappush(bb, -p)
else:
bs.append(p)
else:
p = int(s[7:])
if -bb[0] < p < ss[0]:
r += 1
elif p == ss[0]:
heappop(ss)
elif p == -bb[0]:
heappop(bb)
else:
print(0)
return
for x in bs:
if x < p:
heappush(bb, -x)
elif x > p:
heappush(ss, x)
bs = []
print((len(bs) + 1) * pow(2, r, m) % m)
if __name__ == '__main__':
main()
```
| 93,543 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price.
At every moment of time, every SELL offer has higher price than every BUY offer.
In this problem no two ever existed orders will have the same price.
The lowest-price SELL order and the highest-price BUY order are called the best offers, marked with black frames on the picture below.
<image> The presented order book says that someone wants to sell the product at price 12 and it's the best SELL offer because the other two have higher prices. The best BUY offer has price 10.
There are two possible actions in this orderbook:
1. Somebody adds a new order of some direction with some price.
2. Somebody accepts the best possible SELL or BUY offer (makes a deal). It's impossible to accept not the best SELL or BUY offer (to make a deal at worse price). After someone accepts the offer, it is removed from the orderbook forever.
It is allowed to add new BUY order only with prices less than the best SELL offer (if you want to buy stock for higher price, then instead of adding an order you should accept the best SELL offer). Similarly, one couldn't add a new SELL order with price less or equal to the best BUY offer. For example, you can't add a new offer "SELL 20" if there is already an offer "BUY 20" or "BUY 25" β in this case you just accept the best BUY offer.
You have a damaged order book log (in the beginning the are no orders in book). Every action has one of the two types:
1. "ADD p" denotes adding a new order with price p and unknown direction. The order must not contradict with orders still not removed from the order book.
2. "ACCEPT p" denotes accepting an existing best offer with price p and unknown direction.
The directions of all actions are lost. Information from the log isn't always enough to determine these directions. Count the number of ways to correctly restore all ADD action directions so that all the described conditions are satisfied at any moment. Since the answer could be large, output it modulo 10^9 + 7. If it is impossible to correctly restore directions, then output 0.
Input
The first line contains an integer n (1 β€ n β€ 363 304) β the number of actions in the log.
Each of the next n lines contains a string "ACCEPT" or "ADD" and an integer p (1 β€ p β€ 308 983 066), describing an action type and price.
All ADD actions have different prices. For ACCEPT action it is guaranteed that the order with the same price has already been added but has not been accepted yet.
Output
Output the number of ways to restore directions of ADD actions modulo 10^9 + 7.
Examples
Input
6
ADD 1
ACCEPT 1
ADD 2
ACCEPT 2
ADD 3
ACCEPT 3
Output
8
Input
4
ADD 1
ADD 2
ADD 3
ACCEPT 2
Output
2
Input
7
ADD 1
ADD 2
ADD 3
ADD 4
ADD 5
ACCEPT 3
ACCEPT 5
Output
0
Note
In the first example each of orders may be BUY or SELL.
In the second example the order with price 1 has to be BUY order, the order with the price 3 has to be SELL order.
Submitted Solution:
```
MOD = 10 ** 9 + 7
n = int(input())
order = []
new_comer = []
ans = 1
def cand_search(ac):
buy_max = 0
sell_min = float("inf")
needed_order = candidate + new_comer
for o in needed_order:
if o < ac and o > buy_max:
buy_max = o
elif o > ac and o < sell_min:
sell_min = o
return [buy_max, sell_min]
candidate = [0, float("inf")]
for _ in range(n):
I = input().split()
i = int(I[1])
if I[0] == "ADD":
order.append(i)
if candidate[0] < i < candidate[1]:
new_comer.append(i)
elif I[0] == "ACCEPT":
ans = ans * 2 % MOD
if i < candidate[0] or i > candidate[1]:
ans *= 0
break
candidate = cand_search(i)
new_comer = []
ans = ans * (2 ** len(new_comer)) % MOD
print(ans)
```
No
| 93,544 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price.
At every moment of time, every SELL offer has higher price than every BUY offer.
In this problem no two ever existed orders will have the same price.
The lowest-price SELL order and the highest-price BUY order are called the best offers, marked with black frames on the picture below.
<image> The presented order book says that someone wants to sell the product at price 12 and it's the best SELL offer because the other two have higher prices. The best BUY offer has price 10.
There are two possible actions in this orderbook:
1. Somebody adds a new order of some direction with some price.
2. Somebody accepts the best possible SELL or BUY offer (makes a deal). It's impossible to accept not the best SELL or BUY offer (to make a deal at worse price). After someone accepts the offer, it is removed from the orderbook forever.
It is allowed to add new BUY order only with prices less than the best SELL offer (if you want to buy stock for higher price, then instead of adding an order you should accept the best SELL offer). Similarly, one couldn't add a new SELL order with price less or equal to the best BUY offer. For example, you can't add a new offer "SELL 20" if there is already an offer "BUY 20" or "BUY 25" β in this case you just accept the best BUY offer.
You have a damaged order book log (in the beginning the are no orders in book). Every action has one of the two types:
1. "ADD p" denotes adding a new order with price p and unknown direction. The order must not contradict with orders still not removed from the order book.
2. "ACCEPT p" denotes accepting an existing best offer with price p and unknown direction.
The directions of all actions are lost. Information from the log isn't always enough to determine these directions. Count the number of ways to correctly restore all ADD action directions so that all the described conditions are satisfied at any moment. Since the answer could be large, output it modulo 10^9 + 7. If it is impossible to correctly restore directions, then output 0.
Input
The first line contains an integer n (1 β€ n β€ 363 304) β the number of actions in the log.
Each of the next n lines contains a string "ACCEPT" or "ADD" and an integer p (1 β€ p β€ 308 983 066), describing an action type and price.
All ADD actions have different prices. For ACCEPT action it is guaranteed that the order with the same price has already been added but has not been accepted yet.
Output
Output the number of ways to restore directions of ADD actions modulo 10^9 + 7.
Examples
Input
6
ADD 1
ACCEPT 1
ADD 2
ACCEPT 2
ADD 3
ACCEPT 3
Output
8
Input
4
ADD 1
ADD 2
ADD 3
ACCEPT 2
Output
2
Input
7
ADD 1
ADD 2
ADD 3
ADD 4
ADD 5
ACCEPT 3
ACCEPT 5
Output
0
Note
In the first example each of orders may be BUY or SELL.
In the second example the order with price 1 has to be BUY order, the order with the price 3 has to be SELL order.
Submitted Solution:
```
import heapq
def decode(line):
args = line.split()
num = int(args[1])
return args[0], num
def main():
mod = 10e9+7
n = int(input())
events = [decode(input()) for i in range(n)]
unknown = []
buy = []
sell = []
ans = 1
for event in events:
if event[0] == 'ADD':
if len(buy) > 0 and buy[0] > event[1]:
heapq.heappush(buy, event[1])
elif len(sell) > 0 and sell[0] < event[1]:
heapq.heappush(sell, event[1])
else:
unknown.append(event[1])
else:
if (
len(buy) > 0 and buy[0] > event[1]
) or (
len(sell) > 0 and sell[0] < event[1]
):
print(0)
return
if len(buy) > 0 and buy[0] == event[1]:
heapq.heappop(buy)
elif len(sell) > 0 and sell[0] == event[1]:
heapq.heappop(sell)
else:
ans *= 2
ans = int(ans % mod)
for num in unknown:
if num < event[1]:
heapq.heappush(buy, num)
elif num > event[1]:
heapq.heappush(sell, num)
unknown.clear()
ans *= len(unknown)+1
ans = int(ans % mod)
print(ans)
try:
main()
except Exception as e:
print(e)
```
No
| 93,545 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price.
At every moment of time, every SELL offer has higher price than every BUY offer.
In this problem no two ever existed orders will have the same price.
The lowest-price SELL order and the highest-price BUY order are called the best offers, marked with black frames on the picture below.
<image> The presented order book says that someone wants to sell the product at price 12 and it's the best SELL offer because the other two have higher prices. The best BUY offer has price 10.
There are two possible actions in this orderbook:
1. Somebody adds a new order of some direction with some price.
2. Somebody accepts the best possible SELL or BUY offer (makes a deal). It's impossible to accept not the best SELL or BUY offer (to make a deal at worse price). After someone accepts the offer, it is removed from the orderbook forever.
It is allowed to add new BUY order only with prices less than the best SELL offer (if you want to buy stock for higher price, then instead of adding an order you should accept the best SELL offer). Similarly, one couldn't add a new SELL order with price less or equal to the best BUY offer. For example, you can't add a new offer "SELL 20" if there is already an offer "BUY 20" or "BUY 25" β in this case you just accept the best BUY offer.
You have a damaged order book log (in the beginning the are no orders in book). Every action has one of the two types:
1. "ADD p" denotes adding a new order with price p and unknown direction. The order must not contradict with orders still not removed from the order book.
2. "ACCEPT p" denotes accepting an existing best offer with price p and unknown direction.
The directions of all actions are lost. Information from the log isn't always enough to determine these directions. Count the number of ways to correctly restore all ADD action directions so that all the described conditions are satisfied at any moment. Since the answer could be large, output it modulo 10^9 + 7. If it is impossible to correctly restore directions, then output 0.
Input
The first line contains an integer n (1 β€ n β€ 363 304) β the number of actions in the log.
Each of the next n lines contains a string "ACCEPT" or "ADD" and an integer p (1 β€ p β€ 308 983 066), describing an action type and price.
All ADD actions have different prices. For ACCEPT action it is guaranteed that the order with the same price has already been added but has not been accepted yet.
Output
Output the number of ways to restore directions of ADD actions modulo 10^9 + 7.
Examples
Input
6
ADD 1
ACCEPT 1
ADD 2
ACCEPT 2
ADD 3
ACCEPT 3
Output
8
Input
4
ADD 1
ADD 2
ADD 3
ACCEPT 2
Output
2
Input
7
ADD 1
ADD 2
ADD 3
ADD 4
ADD 5
ACCEPT 3
ACCEPT 5
Output
0
Note
In the first example each of orders may be BUY or SELL.
In the second example the order with price 1 has to be BUY order, the order with the price 3 has to be SELL order.
Submitted Solution:
```
from sys import exit
from heapq import heapify,heappush,heappop
n=int(input())
first=False
low=[]
high=[]
a=[]
pos=1
mid=set()
for i in range(n):
#print(high,low,mid,first)
s=input().split()
#print(s)
x=int(s[1])
s=s[0]
#print(s[0],s[0]=='ADD')
if(s=='ADD'):
#print('in add',x)
if(not first):
a.append(x)
continue
if(len(low) and x<-1*low[0]):
heappush(low,(-x))
elif(len(high) and x>high[0]):
heappush(high,x)
else:
mid.add(x)
else:
if(not first):
first=True
for j in range(i):
if(a[j]<x):
low.append(-a[j])
elif(a[j]>x):
high.append(a[j])
heapify(low)
heapify(high)
continue
if(len(low) and x==-low[0]):
heappop(low)
elif(len(high) and x==high[0]):
heppop(high)
elif(x in mid):
for j in mid:
if(j>x):
heappush(high,j)
else:
heappush(low,-j)
pos+=1
else:
print(0)
exit()
mod=int(1e9+7)
if(not first):
print(n+1)
else:
print(pow(2,pos,mod))
```
No
| 93,546 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price.
At every moment of time, every SELL offer has higher price than every BUY offer.
In this problem no two ever existed orders will have the same price.
The lowest-price SELL order and the highest-price BUY order are called the best offers, marked with black frames on the picture below.
<image> The presented order book says that someone wants to sell the product at price 12 and it's the best SELL offer because the other two have higher prices. The best BUY offer has price 10.
There are two possible actions in this orderbook:
1. Somebody adds a new order of some direction with some price.
2. Somebody accepts the best possible SELL or BUY offer (makes a deal). It's impossible to accept not the best SELL or BUY offer (to make a deal at worse price). After someone accepts the offer, it is removed from the orderbook forever.
It is allowed to add new BUY order only with prices less than the best SELL offer (if you want to buy stock for higher price, then instead of adding an order you should accept the best SELL offer). Similarly, one couldn't add a new SELL order with price less or equal to the best BUY offer. For example, you can't add a new offer "SELL 20" if there is already an offer "BUY 20" or "BUY 25" β in this case you just accept the best BUY offer.
You have a damaged order book log (in the beginning the are no orders in book). Every action has one of the two types:
1. "ADD p" denotes adding a new order with price p and unknown direction. The order must not contradict with orders still not removed from the order book.
2. "ACCEPT p" denotes accepting an existing best offer with price p and unknown direction.
The directions of all actions are lost. Information from the log isn't always enough to determine these directions. Count the number of ways to correctly restore all ADD action directions so that all the described conditions are satisfied at any moment. Since the answer could be large, output it modulo 10^9 + 7. If it is impossible to correctly restore directions, then output 0.
Input
The first line contains an integer n (1 β€ n β€ 363 304) β the number of actions in the log.
Each of the next n lines contains a string "ACCEPT" or "ADD" and an integer p (1 β€ p β€ 308 983 066), describing an action type and price.
All ADD actions have different prices. For ACCEPT action it is guaranteed that the order with the same price has already been added but has not been accepted yet.
Output
Output the number of ways to restore directions of ADD actions modulo 10^9 + 7.
Examples
Input
6
ADD 1
ACCEPT 1
ADD 2
ACCEPT 2
ADD 3
ACCEPT 3
Output
8
Input
4
ADD 1
ADD 2
ADD 3
ACCEPT 2
Output
2
Input
7
ADD 1
ADD 2
ADD 3
ADD 4
ADD 5
ACCEPT 3
ACCEPT 5
Output
0
Note
In the first example each of orders may be BUY or SELL.
In the second example the order with price 1 has to be BUY order, the order with the price 3 has to be SELL order.
Submitted Solution:
```
from bisect import bisect_left
num_actions = int(input())
buy = list()
sell = list()
undefined = list()
num_solutions = 1
best_buy = None
best_sell = None
for _ in range(num_actions):
instruction, price = input().split()
price = int(price)
if instruction == 'ADD':
if best_buy is not None and price <= best_buy:
buy.append(price)
elif best_sell is not None and price >= best_sell:
sell.append(price)
else:
undefined.append(price)
else: # Accept
buy.sort()
sell.sort()
undefined.sort()
if (buy and price < buy[-1]) or (sell and price > sell[0]):
num_solutions = 0
break
elif buy and price == buy[-1]: # sell to best offer
del buy[-1]
elif sell and price == sell[0]: # buy to best offer
del sell[0]
else:
pos = bisect_left(undefined, price)
buy.extend(undefined[:pos])
sell.extend(undefined[pos + 1:])
sell.sort()
if buy:
best_buy = buy[-1]
if sell:
best_sell = sell[0]
num_solutions = (num_solutions * 2) % 1000000007
print(num_solutions)
```
No
| 93,547 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.
The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th part of the wall.
Vova can only use 2 Γ 1 bricks to put in the wall (he has infinite supply of them, however).
Vova can put bricks only horizontally on the neighbouring parts of the wall of equal height. It means that if for some i the current height of part i is the same as for part i + 1, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part 1 of the wall or to the right of part n of it).
Note that Vova can't put bricks vertically.
Vova is a perfectionist, so he considers the wall completed when:
* all parts of the wall has the same height;
* the wall has no empty spaces inside it.
Can Vova complete the wall using any amount of bricks (possibly zero)?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of parts in the wall.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β the initial heights of the parts of the wall.
Output
Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero).
Print "NO" otherwise.
Examples
Input
5
2 1 1 2 5
Output
YES
Input
3
4 5 3
Output
NO
Input
2
10 10
Output
YES
Note
In the first example Vova can put a brick on parts 2 and 3 to make the wall [2, 2, 2, 2, 5] and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it [5, 5, 5, 5, 5].
In the second example Vova can put no bricks in the wall.
In the third example the wall is already complete.
Tags: data structures, implementation
Correct Solution:
```
n = int(input())
a = list(map(int,input().split()))
s = []
flag = 1
for i in range(0,n):
if len(s) and s[-1] == a[i]:
s.pop()
elif len(s) == 0 or s[-1] > a[i]:
s.append(a[i])
else:
print("NO")
flag = 0
break
if(flag == 1):
if len(s) == 0 or len(s) == 1 and s[-1] == max(a):
print("YES")
else:
print("NO")
```
| 93,548 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.
The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th part of the wall.
Vova can only use 2 Γ 1 bricks to put in the wall (he has infinite supply of them, however).
Vova can put bricks only horizontally on the neighbouring parts of the wall of equal height. It means that if for some i the current height of part i is the same as for part i + 1, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part 1 of the wall or to the right of part n of it).
Note that Vova can't put bricks vertically.
Vova is a perfectionist, so he considers the wall completed when:
* all parts of the wall has the same height;
* the wall has no empty spaces inside it.
Can Vova complete the wall using any amount of bricks (possibly zero)?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of parts in the wall.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β the initial heights of the parts of the wall.
Output
Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero).
Print "NO" otherwise.
Examples
Input
5
2 1 1 2 5
Output
YES
Input
3
4 5 3
Output
NO
Input
2
10 10
Output
YES
Note
In the first example Vova can put a brick on parts 2 and 3 to make the wall [2, 2, 2, 2, 5] and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it [5, 5, 5, 5, 5].
In the second example Vova can put no bricks in the wall.
In the third example the wall is already complete.
Tags: data structures, implementation
Correct Solution:
```
n=int(input())
a=list(map(int,input().split()))
down=[]
good=True
for guy in a:
if len(down)==0:
down.append(guy)
elif down[-1]>guy:
down.append(guy)
elif down[-1]==guy:
down.pop()
else:
good=False
break
if not good:
print("NO")
elif len(down)>1:
print("NO")
elif len(down)==1 and down[0]!=max(a):
print("NO")
else:
print("YES")
```
| 93,549 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.
The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th part of the wall.
Vova can only use 2 Γ 1 bricks to put in the wall (he has infinite supply of them, however).
Vova can put bricks only horizontally on the neighbouring parts of the wall of equal height. It means that if for some i the current height of part i is the same as for part i + 1, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part 1 of the wall or to the right of part n of it).
Note that Vova can't put bricks vertically.
Vova is a perfectionist, so he considers the wall completed when:
* all parts of the wall has the same height;
* the wall has no empty spaces inside it.
Can Vova complete the wall using any amount of bricks (possibly zero)?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of parts in the wall.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β the initial heights of the parts of the wall.
Output
Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero).
Print "NO" otherwise.
Examples
Input
5
2 1 1 2 5
Output
YES
Input
3
4 5 3
Output
NO
Input
2
10 10
Output
YES
Note
In the first example Vova can put a brick on parts 2 and 3 to make the wall [2, 2, 2, 2, 5] and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it [5, 5, 5, 5, 5].
In the second example Vova can put no bricks in the wall.
In the third example the wall is already complete.
Tags: data structures, implementation
Correct Solution:
```
i,p,l,j=input,print,len,int
n,m,q=j(i()),0,[]
f=q.append
for a in map(j,i().split()):
if q:
if a==q[-1]:q.pop()
elif a>q[-1]:f(a);break
else:f(a)
else:f(a)
m=max(m,a)
if l(q)==0 or l(q)==1 and q[0]==m:p('YES')
else:p('NO')
```
| 93,550 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.
The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th part of the wall.
Vova can only use 2 Γ 1 bricks to put in the wall (he has infinite supply of them, however).
Vova can put bricks only horizontally on the neighbouring parts of the wall of equal height. It means that if for some i the current height of part i is the same as for part i + 1, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part 1 of the wall or to the right of part n of it).
Note that Vova can't put bricks vertically.
Vova is a perfectionist, so he considers the wall completed when:
* all parts of the wall has the same height;
* the wall has no empty spaces inside it.
Can Vova complete the wall using any amount of bricks (possibly zero)?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of parts in the wall.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β the initial heights of the parts of the wall.
Output
Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero).
Print "NO" otherwise.
Examples
Input
5
2 1 1 2 5
Output
YES
Input
3
4 5 3
Output
NO
Input
2
10 10
Output
YES
Note
In the first example Vova can put a brick on parts 2 and 3 to make the wall [2, 2, 2, 2, 5] and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it [5, 5, 5, 5, 5].
In the second example Vova can put no bricks in the wall.
In the third example the wall is already complete.
Tags: data structures, implementation
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
b = [[a[0], 1]]
fl = False
for i in range(1, n):
if fl:
break
if a[i] == b[-1][0]:
b[-1][1] += 1
elif a[i] < b[-1][0]:
b.append([a[i], 1])
else:
while len(b) != 0 and a[i] > b[-1][0]:
if b[-1][1] % 2 != 0:
print("NO")
fl = True
break
b.pop()
if len(b) == 0 or a[i] < b[-1][0]:
b.append([a[i], 1])
else:
b[-1][1] += 1
if not fl:
i = len(b) - 1
while i != 0:
if b[i][1] % 2 != 0:
fl = True
break
i -= 1
if fl:
print("NO")
else:
print("YES")
```
| 93,551 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.
The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th part of the wall.
Vova can only use 2 Γ 1 bricks to put in the wall (he has infinite supply of them, however).
Vova can put bricks only horizontally on the neighbouring parts of the wall of equal height. It means that if for some i the current height of part i is the same as for part i + 1, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part 1 of the wall or to the right of part n of it).
Note that Vova can't put bricks vertically.
Vova is a perfectionist, so he considers the wall completed when:
* all parts of the wall has the same height;
* the wall has no empty spaces inside it.
Can Vova complete the wall using any amount of bricks (possibly zero)?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of parts in the wall.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β the initial heights of the parts of the wall.
Output
Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero).
Print "NO" otherwise.
Examples
Input
5
2 1 1 2 5
Output
YES
Input
3
4 5 3
Output
NO
Input
2
10 10
Output
YES
Note
In the first example Vova can put a brick on parts 2 and 3 to make the wall [2, 2, 2, 2, 5] and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it [5, 5, 5, 5, 5].
In the second example Vova can put no bricks in the wall.
In the third example the wall is already complete.
Tags: data structures, implementation
Correct Solution:
```
i = int(input())
s = input().split()
m = max (list(map(int,s)))
l = []
for j in s:
if not l or int(j) < l[-1] :
l.append(int(j))
elif int(j) == l[-1]:
l.pop()
else:
print('NO')
exit()
if (len(l) ==1 and l[0] >= m) or len(l) == 0 :
print('YES')
else:
print('NO')
```
| 93,552 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.
The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th part of the wall.
Vova can only use 2 Γ 1 bricks to put in the wall (he has infinite supply of them, however).
Vova can put bricks only horizontally on the neighbouring parts of the wall of equal height. It means that if for some i the current height of part i is the same as for part i + 1, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part 1 of the wall or to the right of part n of it).
Note that Vova can't put bricks vertically.
Vova is a perfectionist, so he considers the wall completed when:
* all parts of the wall has the same height;
* the wall has no empty spaces inside it.
Can Vova complete the wall using any amount of bricks (possibly zero)?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of parts in the wall.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β the initial heights of the parts of the wall.
Output
Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero).
Print "NO" otherwise.
Examples
Input
5
2 1 1 2 5
Output
YES
Input
3
4 5 3
Output
NO
Input
2
10 10
Output
YES
Note
In the first example Vova can put a brick on parts 2 and 3 to make the wall [2, 2, 2, 2, 5] and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it [5, 5, 5, 5, 5].
In the second example Vova can put no bricks in the wall.
In the third example the wall is already complete.
Tags: data structures, implementation
Correct Solution:
```
i,p=input,print;n,m,q=int(i()),0,[];f=q.append
for a in map(int,i().split()):
if q:
if a==q[-1]:q.pop()
elif a>q[-1]:f(a);break
else:f(a)
else:f(a)
m=max(m,a)
p('YES'if len(q)==0 or len(q)==1 and q[0]==m else'NO')
```
| 93,553 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.
The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th part of the wall.
Vova can only use 2 Γ 1 bricks to put in the wall (he has infinite supply of them, however).
Vova can put bricks only horizontally on the neighbouring parts of the wall of equal height. It means that if for some i the current height of part i is the same as for part i + 1, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part 1 of the wall or to the right of part n of it).
Note that Vova can't put bricks vertically.
Vova is a perfectionist, so he considers the wall completed when:
* all parts of the wall has the same height;
* the wall has no empty spaces inside it.
Can Vova complete the wall using any amount of bricks (possibly zero)?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of parts in the wall.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β the initial heights of the parts of the wall.
Output
Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero).
Print "NO" otherwise.
Examples
Input
5
2 1 1 2 5
Output
YES
Input
3
4 5 3
Output
NO
Input
2
10 10
Output
YES
Note
In the first example Vova can put a brick on parts 2 and 3 to make the wall [2, 2, 2, 2, 5] and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it [5, 5, 5, 5, 5].
In the second example Vova can put no bricks in the wall.
In the third example the wall is already complete.
Tags: data structures, implementation
Correct Solution:
```
n=int(input())
a=list(map(int,input().split()))
b=[0]*1000000
sp=-1
max=0
f=True;
for i in range(n):
sp=sp+1
b[sp]=a[i]
if b[sp]>max:
max=b[sp]
if sp>0:
if b[sp]>b[sp-1]:
f=False
if b[sp]==b[sp-1]:
sp=sp-2
if f==True :
if sp==0:
if b[sp]>=max:
print("YES")
else:
print("NO")
elif sp<0:
print("YES")
else:
print("NO")
else:
print("NO")
```
| 93,554 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.
The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th part of the wall.
Vova can only use 2 Γ 1 bricks to put in the wall (he has infinite supply of them, however).
Vova can put bricks only horizontally on the neighbouring parts of the wall of equal height. It means that if for some i the current height of part i is the same as for part i + 1, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part 1 of the wall or to the right of part n of it).
Note that Vova can't put bricks vertically.
Vova is a perfectionist, so he considers the wall completed when:
* all parts of the wall has the same height;
* the wall has no empty spaces inside it.
Can Vova complete the wall using any amount of bricks (possibly zero)?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of parts in the wall.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β the initial heights of the parts of the wall.
Output
Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero).
Print "NO" otherwise.
Examples
Input
5
2 1 1 2 5
Output
YES
Input
3
4 5 3
Output
NO
Input
2
10 10
Output
YES
Note
In the first example Vova can put a brick on parts 2 and 3 to make the wall [2, 2, 2, 2, 5] and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it [5, 5, 5, 5, 5].
In the second example Vova can put no bricks in the wall.
In the third example the wall is already complete.
Tags: data structures, implementation
Correct Solution:
```
n=int(input())
l=[int(x) for x in input().split()]
st=[]
for i in l:
d=i
if len(st) and st[-1]==d:
st.pop()
elif len(st)==0 or st[-1]>d:
st.append(d)
else:
print("NO")
break
else:
if len(st)==0 or len(st)==1 and st[-1]==max(l):
print("YES")
else:
print("NO")
```
| 93,555 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.
The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th part of the wall.
Vova can only use 2 Γ 1 bricks to put in the wall (he has infinite supply of them, however).
Vova can put bricks only horizontally on the neighbouring parts of the wall of equal height. It means that if for some i the current height of part i is the same as for part i + 1, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part 1 of the wall or to the right of part n of it).
Note that Vova can't put bricks vertically.
Vova is a perfectionist, so he considers the wall completed when:
* all parts of the wall has the same height;
* the wall has no empty spaces inside it.
Can Vova complete the wall using any amount of bricks (possibly zero)?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of parts in the wall.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β the initial heights of the parts of the wall.
Output
Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero).
Print "NO" otherwise.
Examples
Input
5
2 1 1 2 5
Output
YES
Input
3
4 5 3
Output
NO
Input
2
10 10
Output
YES
Note
In the first example Vova can put a brick on parts 2 and 3 to make the wall [2, 2, 2, 2, 5] and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it [5, 5, 5, 5, 5].
In the second example Vova can put no bricks in the wall.
In the third example the wall is already complete.
Submitted Solution:
```
import sys
n = int(sys.stdin.readline())
cur_str = ((sys.stdin.readline()).strip()).split()
array = [int(elem) for elem in cur_str]
i = 0
stack = []
ans = True
maximum = -1
while i<len(array):
maximum = max(maximum,array[i])
if not stack or array[i] < stack[-1]: stack.append(array[i])
else:
if stack[-1] < array[i]:
ans = False
break
elif stack[-1] == array[i]: stack.pop()
i+=1
for i in range(1,len(stack)):
if stack[i]!=stack[i-1]:
ans = False
break
if stack and min(stack) < maximum: ans = False
if ans == True or n==1: print("YES")
else: print("NO")
```
Yes
| 93,556 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.
The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th part of the wall.
Vova can only use 2 Γ 1 bricks to put in the wall (he has infinite supply of them, however).
Vova can put bricks only horizontally on the neighbouring parts of the wall of equal height. It means that if for some i the current height of part i is the same as for part i + 1, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part 1 of the wall or to the right of part n of it).
Note that Vova can't put bricks vertically.
Vova is a perfectionist, so he considers the wall completed when:
* all parts of the wall has the same height;
* the wall has no empty spaces inside it.
Can Vova complete the wall using any amount of bricks (possibly zero)?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of parts in the wall.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β the initial heights of the parts of the wall.
Output
Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero).
Print "NO" otherwise.
Examples
Input
5
2 1 1 2 5
Output
YES
Input
3
4 5 3
Output
NO
Input
2
10 10
Output
YES
Note
In the first example Vova can put a brick on parts 2 and 3 to make the wall [2, 2, 2, 2, 5] and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it [5, 5, 5, 5, 5].
In the second example Vova can put no bricks in the wall.
In the third example the wall is already complete.
Submitted Solution:
```
from bisect import bisect_right as br
from bisect import bisect_left as bl
from collections import defaultdict
from itertools import combinations
import functools
import sys
import math
MAX = sys.maxsize
MAXN = 10**6+10
MOD = 998244353
def isprime(n):
n = abs(int(n))
if n < 2:
return False
if n == 2:
return True
if not n & 1:
return False
for x in range(3, int(n**0.5) + 1, 2):
if n % x == 0:
return False
return True
def mhd(a,b,x,y):
return abs(a-x)+abs(b-y)
def numIN():
return(map(int,sys.stdin.readline().strip().split()))
def charIN():
return(sys.stdin.readline().strip().split())
t = [(-1,-1)]*1000010
def create(a):
global t,n
for i in range(n,2*n):
t[i] = (a[i-n],i-n)
for i in range(n-1,0,-1):
x = [t[2*i],t[2*i+1]]
x.sort(key = lambda x:x[0])
t[i] = x[1]
def update(idx,value):
global t,n
idx = idx+n
t[idx] = value
while(idx>1):
idx = idx//2
x = [t[2*idx],t[2*idx+1]]
x.sort(key = lambda x:x[0])
t[idx] = x[1]
def dis(a,b,k):
ans = 0
for i in range(k):
ans+=abs(a[i]-b[i])
return ans
def cal(n,k):
res = 1
c = [0]*(k+1)
c[0]=1
for i in range(1,n+1):
for j in range(min(i,k),0,-1):
c[j] = (c[j]+c[j-1])%MOD
return c[k]
n = int(input())
l = list(numIN())
x = []
for i in range(n):
if x and x[-1]==l[i]:
x.pop()
continue
if x and x[-1]<l[i]:
print('NO')
exit(0)
x.append(l[i])
if x and x[-1]!=max(l):
print('NO')
else:
print('YES')
```
Yes
| 93,557 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.
The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th part of the wall.
Vova can only use 2 Γ 1 bricks to put in the wall (he has infinite supply of them, however).
Vova can put bricks only horizontally on the neighbouring parts of the wall of equal height. It means that if for some i the current height of part i is the same as for part i + 1, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part 1 of the wall or to the right of part n of it).
Note that Vova can't put bricks vertically.
Vova is a perfectionist, so he considers the wall completed when:
* all parts of the wall has the same height;
* the wall has no empty spaces inside it.
Can Vova complete the wall using any amount of bricks (possibly zero)?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of parts in the wall.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β the initial heights of the parts of the wall.
Output
Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero).
Print "NO" otherwise.
Examples
Input
5
2 1 1 2 5
Output
YES
Input
3
4 5 3
Output
NO
Input
2
10 10
Output
YES
Note
In the first example Vova can put a brick on parts 2 and 3 to make the wall [2, 2, 2, 2, 5] and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it [5, 5, 5, 5, 5].
In the second example Vova can put no bricks in the wall.
In the third example the wall is already complete.
Submitted Solution:
```
import sys
input = sys.stdin.readline
from collections import deque
n=int(input())
A=list(map(int,input().split()))
AX=[(A[i],i) for i in range(n)]
QUE = deque()
for i in range(n):
QUE.append(AX[i])
while len(QUE)>=2 and QUE[-1][0]==QUE[-2][0] and A[QUE[-2][1]]>=A[QUE[-2][1]+1]:
QUE.pop()
QUE.pop()
if len(QUE)>=2:
print("NO")
elif len(QUE)==1:
if QUE[0][0]==max(A):
print("YES")
else:
print("NO")
else:
print("YES")
```
Yes
| 93,558 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.
The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th part of the wall.
Vova can only use 2 Γ 1 bricks to put in the wall (he has infinite supply of them, however).
Vova can put bricks only horizontally on the neighbouring parts of the wall of equal height. It means that if for some i the current height of part i is the same as for part i + 1, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part 1 of the wall or to the right of part n of it).
Note that Vova can't put bricks vertically.
Vova is a perfectionist, so he considers the wall completed when:
* all parts of the wall has the same height;
* the wall has no empty spaces inside it.
Can Vova complete the wall using any amount of bricks (possibly zero)?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of parts in the wall.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β the initial heights of the parts of the wall.
Output
Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero).
Print "NO" otherwise.
Examples
Input
5
2 1 1 2 5
Output
YES
Input
3
4 5 3
Output
NO
Input
2
10 10
Output
YES
Note
In the first example Vova can put a brick on parts 2 and 3 to make the wall [2, 2, 2, 2, 5] and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it [5, 5, 5, 5, 5].
In the second example Vova can put no bricks in the wall.
In the third example the wall is already complete.
Submitted Solution:
```
def main():
n = int(input())
m = 0
stack = []
for val in map(int, input().split()):
if stack:
if val == stack[-1]:
stack.pop()
elif val > stack[-1]:
stack.append(val)
break
else:
stack.append(val)
else:
stack.append(val)
m = max(m, val)
print('YES' if len(stack) == 0 or len(stack) == 1 and stack[0] == m else 'NO')
if __name__ == '__main__':
main()
```
Yes
| 93,559 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.
The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th part of the wall.
Vova can only use 2 Γ 1 bricks to put in the wall (he has infinite supply of them, however).
Vova can put bricks only horizontally on the neighbouring parts of the wall of equal height. It means that if for some i the current height of part i is the same as for part i + 1, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part 1 of the wall or to the right of part n of it).
Note that Vova can't put bricks vertically.
Vova is a perfectionist, so he considers the wall completed when:
* all parts of the wall has the same height;
* the wall has no empty spaces inside it.
Can Vova complete the wall using any amount of bricks (possibly zero)?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of parts in the wall.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β the initial heights of the parts of the wall.
Output
Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero).
Print "NO" otherwise.
Examples
Input
5
2 1 1 2 5
Output
YES
Input
3
4 5 3
Output
NO
Input
2
10 10
Output
YES
Note
In the first example Vova can put a brick on parts 2 and 3 to make the wall [2, 2, 2, 2, 5] and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it [5, 5, 5, 5, 5].
In the second example Vova can put no bricks in the wall.
In the third example the wall is already complete.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
b=[0]*10000
sp=0
for i in range(n):
b[sp]=a[i]
sp=sp+1
if sp>0:
if b[sp-1]==b[sp-2]:
sp=sp-2
if sp<=1:
print("YES")
else:
print("NO")
```
No
| 93,560 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.
The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th part of the wall.
Vova can only use 2 Γ 1 bricks to put in the wall (he has infinite supply of them, however).
Vova can put bricks only horizontally on the neighbouring parts of the wall of equal height. It means that if for some i the current height of part i is the same as for part i + 1, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part 1 of the wall or to the right of part n of it).
Note that Vova can't put bricks vertically.
Vova is a perfectionist, so he considers the wall completed when:
* all parts of the wall has the same height;
* the wall has no empty spaces inside it.
Can Vova complete the wall using any amount of bricks (possibly zero)?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of parts in the wall.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β the initial heights of the parts of the wall.
Output
Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero).
Print "NO" otherwise.
Examples
Input
5
2 1 1 2 5
Output
YES
Input
3
4 5 3
Output
NO
Input
2
10 10
Output
YES
Note
In the first example Vova can put a brick on parts 2 and 3 to make the wall [2, 2, 2, 2, 5] and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it [5, 5, 5, 5, 5].
In the second example Vova can put no bricks in the wall.
In the third example the wall is already complete.
Submitted Solution:
```
#!/usr/bin/env python3
import sys
def rint():
return map(int, sys.stdin.readline().split())
#lines = stdin.readlines()
n = int(input())
a = list(rint())
stack = [a[0]]
for i in range(1, n):
if len(stack) == 0:
stack.append(a[i])
if a[i] == stack[-1]:
stack.pop()
else:
stack.append(a[i])
if len(stack) > 1:
print("NO")
else:
print("YES")
```
No
| 93,561 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.
The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th part of the wall.
Vova can only use 2 Γ 1 bricks to put in the wall (he has infinite supply of them, however).
Vova can put bricks only horizontally on the neighbouring parts of the wall of equal height. It means that if for some i the current height of part i is the same as for part i + 1, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part 1 of the wall or to the right of part n of it).
Note that Vova can't put bricks vertically.
Vova is a perfectionist, so he considers the wall completed when:
* all parts of the wall has the same height;
* the wall has no empty spaces inside it.
Can Vova complete the wall using any amount of bricks (possibly zero)?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of parts in the wall.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β the initial heights of the parts of the wall.
Output
Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero).
Print "NO" otherwise.
Examples
Input
5
2 1 1 2 5
Output
YES
Input
3
4 5 3
Output
NO
Input
2
10 10
Output
YES
Note
In the first example Vova can put a brick on parts 2 and 3 to make the wall [2, 2, 2, 2, 5] and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it [5, 5, 5, 5, 5].
In the second example Vova can put no bricks in the wall.
In the third example the wall is already complete.
Submitted Solution:
```
n=int(input())
l=[int(x) for x in input().split()]
st=[]
for i in l:
d=i
if len(st) and st[-1]==d:
st.pop()
else:
st.append(d)
if len(st)<2:
print("YES")
else:
print("NO")
```
No
| 93,562 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.
The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th part of the wall.
Vova can only use 2 Γ 1 bricks to put in the wall (he has infinite supply of them, however).
Vova can put bricks only horizontally on the neighbouring parts of the wall of equal height. It means that if for some i the current height of part i is the same as for part i + 1, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part 1 of the wall or to the right of part n of it).
Note that Vova can't put bricks vertically.
Vova is a perfectionist, so he considers the wall completed when:
* all parts of the wall has the same height;
* the wall has no empty spaces inside it.
Can Vova complete the wall using any amount of bricks (possibly zero)?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of parts in the wall.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β the initial heights of the parts of the wall.
Output
Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero).
Print "NO" otherwise.
Examples
Input
5
2 1 1 2 5
Output
YES
Input
3
4 5 3
Output
NO
Input
2
10 10
Output
YES
Note
In the first example Vova can put a brick on parts 2 and 3 to make the wall [2, 2, 2, 2, 5] and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it [5, 5, 5, 5, 5].
In the second example Vova can put no bricks in the wall.
In the third example the wall is already complete.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
b=[0]*100001
sp=-1
max=0
f=True;
for i in range(n):
sp=sp+1
b[sp]=a[i]
if b[sp]>max:
max=b[sp]
if sp>0:
if b[sp]>b[sp-1]:
f=False
if b[sp]==b[sp-1]:
sp=sp-2
if f==True :
if sp==0:
if b[sp]>max:
print("YES")
else:
print("NO")
elif sp<0:
print("YES")
else:
print("NO")
```
No
| 93,563 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.
Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following:
* if the current length is at least 2, divide the base into 2 equal halves and destroy them separately, or
* burn the current base. If it contains no avenger in it, it takes A amount of power, otherwise it takes his B β
n_a β
l amount of power, where n_a is the number of avengers and l is the length of the current base.
Output the minimum power needed by Thanos to destroy the avengers' base.
Input
The first line contains four integers n, k, A and B (1 β€ n β€ 30, 1 β€ k β€ 10^5, 1 β€ A,B β€ 10^4), where 2^n is the length of the base, k is the number of avengers and A and B are the constants explained in the question.
The second line contains k integers a_{1}, a_{2}, a_{3}, β¦, a_{k} (1 β€ a_{i} β€ 2^n), where a_{i} represents the position of avenger in the base.
Output
Output one integer β the minimum power needed to destroy the avengers base.
Examples
Input
2 2 1 2
1 3
Output
6
Input
3 2 1 2
1 7
Output
8
Note
Consider the first example.
One option for Thanos is to burn the whole base 1-4 with power 2 β
2 β
4 = 16.
Otherwise he can divide the base into two parts 1-2 and 3-4.
For base 1-2, he can either burn it with power 2 β
1 β
2 = 4 or divide it into 2 parts 1-1 and 2-2.
For base 1-1, he can burn it with power 2 β
1 β
1 = 2. For 2-2, he can destroy it with power 1, as there are no avengers. So, the total power for destroying 1-2 is 2 + 1 = 3, which is less than 4.
Similarly, he needs 3 power to destroy 3-4. The total minimum power needed is 6.
Tags: binary search, brute force, divide and conquer, math
Correct Solution:
```
from bisect import bisect_left, bisect_right
import sys
def input():
return sys.stdin.readline().rstrip()
def slv():
n, k, A, B = map(int, input().split())
avengers = list(map(int, input().split()))
avengers.sort()
def get_count(l, r):
"""
return the number of hero in range[l,r).
"""
if l >= r:
return 0
return bisect_right(avengers, r - 1) - bisect_right(avengers, l - 1)
def query(L, R):
assert L <= R
if L == R:
cnt = get_count(L, R + 1)
if cnt:
return B * cnt
return A
else:
med = (R + L + 1)//2
#[L,R] -> [L,med] [med,R]
cnt = get_count(L, R + 1)
if cnt:
res = B * cnt * (R - L + 1)
else:
res = A
return res
return min(query(L, med - 1) + query(med, R), res)
ans = query(1, (1 << n))
print(ans)
return
def main():
t = 1
for i in range(t):
slv()
return
if __name__ == "__main__":
main()
```
| 93,564 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.
Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following:
* if the current length is at least 2, divide the base into 2 equal halves and destroy them separately, or
* burn the current base. If it contains no avenger in it, it takes A amount of power, otherwise it takes his B β
n_a β
l amount of power, where n_a is the number of avengers and l is the length of the current base.
Output the minimum power needed by Thanos to destroy the avengers' base.
Input
The first line contains four integers n, k, A and B (1 β€ n β€ 30, 1 β€ k β€ 10^5, 1 β€ A,B β€ 10^4), where 2^n is the length of the base, k is the number of avengers and A and B are the constants explained in the question.
The second line contains k integers a_{1}, a_{2}, a_{3}, β¦, a_{k} (1 β€ a_{i} β€ 2^n), where a_{i} represents the position of avenger in the base.
Output
Output one integer β the minimum power needed to destroy the avengers base.
Examples
Input
2 2 1 2
1 3
Output
6
Input
3 2 1 2
1 7
Output
8
Note
Consider the first example.
One option for Thanos is to burn the whole base 1-4 with power 2 β
2 β
4 = 16.
Otherwise he can divide the base into two parts 1-2 and 3-4.
For base 1-2, he can either burn it with power 2 β
1 β
2 = 4 or divide it into 2 parts 1-1 and 2-2.
For base 1-1, he can burn it with power 2 β
1 β
1 = 2. For 2-2, he can destroy it with power 1, as there are no avengers. So, the total power for destroying 1-2 is 2 + 1 = 3, which is less than 4.
Similarly, he needs 3 power to destroy 3-4. The total minimum power needed is 6.
Tags: binary search, brute force, divide and conquer, math
Correct Solution:
```
import sys
from bisect import bisect_left as bl, bisect_right as br
def min_cost(l, r):
cnt = br(pos, r) - bl(pos, l)
if cnt == 0:
return a
curr = b * cnt
if l == r:
return curr
m = (l + r) // 2
return min(curr * (r - l + 1), min_cost(l, m) + min_cost(m + 1, r))
n, k, a, b = map(int, input().split())
pos = [int(x) for x in input().split()]
pos.sort()
print(min_cost(1, 2 ** n))
```
| 93,565 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.
Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following:
* if the current length is at least 2, divide the base into 2 equal halves and destroy them separately, or
* burn the current base. If it contains no avenger in it, it takes A amount of power, otherwise it takes his B β
n_a β
l amount of power, where n_a is the number of avengers and l is the length of the current base.
Output the minimum power needed by Thanos to destroy the avengers' base.
Input
The first line contains four integers n, k, A and B (1 β€ n β€ 30, 1 β€ k β€ 10^5, 1 β€ A,B β€ 10^4), where 2^n is the length of the base, k is the number of avengers and A and B are the constants explained in the question.
The second line contains k integers a_{1}, a_{2}, a_{3}, β¦, a_{k} (1 β€ a_{i} β€ 2^n), where a_{i} represents the position of avenger in the base.
Output
Output one integer β the minimum power needed to destroy the avengers base.
Examples
Input
2 2 1 2
1 3
Output
6
Input
3 2 1 2
1 7
Output
8
Note
Consider the first example.
One option for Thanos is to burn the whole base 1-4 with power 2 β
2 β
4 = 16.
Otherwise he can divide the base into two parts 1-2 and 3-4.
For base 1-2, he can either burn it with power 2 β
1 β
2 = 4 or divide it into 2 parts 1-1 and 2-2.
For base 1-1, he can burn it with power 2 β
1 β
1 = 2. For 2-2, he can destroy it with power 1, as there are no avengers. So, the total power for destroying 1-2 is 2 + 1 = 3, which is less than 4.
Similarly, he needs 3 power to destroy 3-4. The total minimum power needed is 6.
Tags: binary search, brute force, divide and conquer, math
Correct Solution:
```
from bisect import bisect_left as lb, bisect_right as ub
n, k, A, B = map(int, input().split(' '))
a = sorted(map(int, input().split(' ')))
def heihei(l, r):
cnt = ub(a, r) - lb(a, l)
if cnt == 0:
return A
if l == r:
return A if cnt == 0 else B * cnt
mid = (l + r) >> 1
lr, rr = heihei(l, mid), heihei(mid + 1, r)
return min(B * cnt * (r - l + 1), lr + rr)
print(heihei(1, 2 ** n))
```
| 93,566 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.
Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following:
* if the current length is at least 2, divide the base into 2 equal halves and destroy them separately, or
* burn the current base. If it contains no avenger in it, it takes A amount of power, otherwise it takes his B β
n_a β
l amount of power, where n_a is the number of avengers and l is the length of the current base.
Output the minimum power needed by Thanos to destroy the avengers' base.
Input
The first line contains four integers n, k, A and B (1 β€ n β€ 30, 1 β€ k β€ 10^5, 1 β€ A,B β€ 10^4), where 2^n is the length of the base, k is the number of avengers and A and B are the constants explained in the question.
The second line contains k integers a_{1}, a_{2}, a_{3}, β¦, a_{k} (1 β€ a_{i} β€ 2^n), where a_{i} represents the position of avenger in the base.
Output
Output one integer β the minimum power needed to destroy the avengers base.
Examples
Input
2 2 1 2
1 3
Output
6
Input
3 2 1 2
1 7
Output
8
Note
Consider the first example.
One option for Thanos is to burn the whole base 1-4 with power 2 β
2 β
4 = 16.
Otherwise he can divide the base into two parts 1-2 and 3-4.
For base 1-2, he can either burn it with power 2 β
1 β
2 = 4 or divide it into 2 parts 1-1 and 2-2.
For base 1-1, he can burn it with power 2 β
1 β
1 = 2. For 2-2, he can destroy it with power 1, as there are no avengers. So, the total power for destroying 1-2 is 2 + 1 = 3, which is less than 4.
Similarly, he needs 3 power to destroy 3-4. The total minimum power needed is 6.
Tags: binary search, brute force, divide and conquer, math
Correct Solution:
```
# -*- coding:utf-8 -*-
"""
created by shuangquan.huang at 2/11/19
"""
import collections
import time
import os
import sys
import bisect
import heapq
N, K, A, B = map(int, input().split())
positions = [int(x) for x in input().split()]
positions.sort()
def count(l, r):
a = bisect.bisect_left(positions, l)
b = bisect.bisect_right(positions, r)
return b-a
def solve(l, r):
a, b = bisect.bisect_left(positions, l), bisect.bisect_right(positions, r)
x = b - a
ans = 0
if x == 0:
ans = A
else:
ans = B * x * (r-l+1)
if l == r or x == 0:
return ans
m = (l+r) // 2
ans = min(ans, solve(l, m) + solve(m+1, r))
return ans
print(solve(1, 1 << N))
```
| 93,567 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.
Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following:
* if the current length is at least 2, divide the base into 2 equal halves and destroy them separately, or
* burn the current base. If it contains no avenger in it, it takes A amount of power, otherwise it takes his B β
n_a β
l amount of power, where n_a is the number of avengers and l is the length of the current base.
Output the minimum power needed by Thanos to destroy the avengers' base.
Input
The first line contains four integers n, k, A and B (1 β€ n β€ 30, 1 β€ k β€ 10^5, 1 β€ A,B β€ 10^4), where 2^n is the length of the base, k is the number of avengers and A and B are the constants explained in the question.
The second line contains k integers a_{1}, a_{2}, a_{3}, β¦, a_{k} (1 β€ a_{i} β€ 2^n), where a_{i} represents the position of avenger in the base.
Output
Output one integer β the minimum power needed to destroy the avengers base.
Examples
Input
2 2 1 2
1 3
Output
6
Input
3 2 1 2
1 7
Output
8
Note
Consider the first example.
One option for Thanos is to burn the whole base 1-4 with power 2 β
2 β
4 = 16.
Otherwise he can divide the base into two parts 1-2 and 3-4.
For base 1-2, he can either burn it with power 2 β
1 β
2 = 4 or divide it into 2 parts 1-1 and 2-2.
For base 1-1, he can burn it with power 2 β
1 β
1 = 2. For 2-2, he can destroy it with power 1, as there are no avengers. So, the total power for destroying 1-2 is 2 + 1 = 3, which is less than 4.
Similarly, he needs 3 power to destroy 3-4. The total minimum power needed is 6.
Tags: binary search, brute force, divide and conquer, math
Correct Solution:
```
import bisect
n, k, A, B = map(int, input().split())
X = sorted([int(a)-1 for a in input().split()])
def calc(l, r):
def cnt(a, b):
return bisect.bisect_left(X, b) - bisect.bisect_left(X, a)
c = cnt(l, r)
if c == 0:
ret = A
elif r-l == 1:
ret = B * c
else:
m = (l+r) // 2
a = cnt(l, m)
b = c - a
if a == 0:
ret = min(A + calc(m, r), B * c * (r - l))
elif b == 0:
ret = min(A + calc(l, m), B * c * (r - l))
else:
ret = calc(l, m) + calc(m, r)
return ret
print(calc(0, 2**n))
```
| 93,568 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.
Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following:
* if the current length is at least 2, divide the base into 2 equal halves and destroy them separately, or
* burn the current base. If it contains no avenger in it, it takes A amount of power, otherwise it takes his B β
n_a β
l amount of power, where n_a is the number of avengers and l is the length of the current base.
Output the minimum power needed by Thanos to destroy the avengers' base.
Input
The first line contains four integers n, k, A and B (1 β€ n β€ 30, 1 β€ k β€ 10^5, 1 β€ A,B β€ 10^4), where 2^n is the length of the base, k is the number of avengers and A and B are the constants explained in the question.
The second line contains k integers a_{1}, a_{2}, a_{3}, β¦, a_{k} (1 β€ a_{i} β€ 2^n), where a_{i} represents the position of avenger in the base.
Output
Output one integer β the minimum power needed to destroy the avengers base.
Examples
Input
2 2 1 2
1 3
Output
6
Input
3 2 1 2
1 7
Output
8
Note
Consider the first example.
One option for Thanos is to burn the whole base 1-4 with power 2 β
2 β
4 = 16.
Otherwise he can divide the base into two parts 1-2 and 3-4.
For base 1-2, he can either burn it with power 2 β
1 β
2 = 4 or divide it into 2 parts 1-1 and 2-2.
For base 1-1, he can burn it with power 2 β
1 β
1 = 2. For 2-2, he can destroy it with power 1, as there are no avengers. So, the total power for destroying 1-2 is 2 + 1 = 3, which is less than 4.
Similarly, he needs 3 power to destroy 3-4. The total minimum power needed is 6.
Tags: binary search, brute force, divide and conquer, math
Correct Solution:
```
n, k, A, B = map(int, input().split())
X = sorted([int(a)-1 for a in input().split()])
def calc(l, r, S):
if len(S) == 0:
ret = A
elif r-l == 1:
ret = B * len(S)
else:
m = (l+r) // 2
SL = []
SR = []
for s in S:
if s < m:
SL.append(s)
else:
SR.append(s)
ret = min(B * len(S) * (r - l), calc(l, m, SL) + calc(m, r, SR))
return ret
print(calc(0, 2**n, X))
```
| 93,569 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.
Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following:
* if the current length is at least 2, divide the base into 2 equal halves and destroy them separately, or
* burn the current base. If it contains no avenger in it, it takes A amount of power, otherwise it takes his B β
n_a β
l amount of power, where n_a is the number of avengers and l is the length of the current base.
Output the minimum power needed by Thanos to destroy the avengers' base.
Input
The first line contains four integers n, k, A and B (1 β€ n β€ 30, 1 β€ k β€ 10^5, 1 β€ A,B β€ 10^4), where 2^n is the length of the base, k is the number of avengers and A and B are the constants explained in the question.
The second line contains k integers a_{1}, a_{2}, a_{3}, β¦, a_{k} (1 β€ a_{i} β€ 2^n), where a_{i} represents the position of avenger in the base.
Output
Output one integer β the minimum power needed to destroy the avengers base.
Examples
Input
2 2 1 2
1 3
Output
6
Input
3 2 1 2
1 7
Output
8
Note
Consider the first example.
One option for Thanos is to burn the whole base 1-4 with power 2 β
2 β
4 = 16.
Otherwise he can divide the base into two parts 1-2 and 3-4.
For base 1-2, he can either burn it with power 2 β
1 β
2 = 4 or divide it into 2 parts 1-1 and 2-2.
For base 1-1, he can burn it with power 2 β
1 β
1 = 2. For 2-2, he can destroy it with power 1, as there are no avengers. So, the total power for destroying 1-2 is 2 + 1 = 3, which is less than 4.
Similarly, he needs 3 power to destroy 3-4. The total minimum power needed is 6.
Tags: binary search, brute force, divide and conquer, math
Correct Solution:
```
def I(): return(list(map(int,input().split())))
def rec(l,r):
numavens=getnums(l,r)
# print(numavens,l,r)
if numavens==0:return a
if l==r:return b*numavens
mid=(r-l)//2+l
return min(((r-l)+1)*numavens*b,rec(l,mid)+rec(mid+1,r))
def getnums(l,r):
if l==0:return get(r)
return get(r)-get(l-1)
def get(t):
l=0
r=k-1
# print(x)
while(l<=r):
mid=(r-l)//2+l
if x[mid]<=t:l=mid+1
else: r=mid-1
# print(l,t)
return l
n,k,a,b=I()
x=I()
x.sort()
l=1
r=2**n
print(rec(l,r))
```
| 93,570 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.
Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following:
* if the current length is at least 2, divide the base into 2 equal halves and destroy them separately, or
* burn the current base. If it contains no avenger in it, it takes A amount of power, otherwise it takes his B β
n_a β
l amount of power, where n_a is the number of avengers and l is the length of the current base.
Output the minimum power needed by Thanos to destroy the avengers' base.
Input
The first line contains four integers n, k, A and B (1 β€ n β€ 30, 1 β€ k β€ 10^5, 1 β€ A,B β€ 10^4), where 2^n is the length of the base, k is the number of avengers and A and B are the constants explained in the question.
The second line contains k integers a_{1}, a_{2}, a_{3}, β¦, a_{k} (1 β€ a_{i} β€ 2^n), where a_{i} represents the position of avenger in the base.
Output
Output one integer β the minimum power needed to destroy the avengers base.
Examples
Input
2 2 1 2
1 3
Output
6
Input
3 2 1 2
1 7
Output
8
Note
Consider the first example.
One option for Thanos is to burn the whole base 1-4 with power 2 β
2 β
4 = 16.
Otherwise he can divide the base into two parts 1-2 and 3-4.
For base 1-2, he can either burn it with power 2 β
1 β
2 = 4 or divide it into 2 parts 1-1 and 2-2.
For base 1-1, he can burn it with power 2 β
1 β
1 = 2. For 2-2, he can destroy it with power 1, as there are no avengers. So, the total power for destroying 1-2 is 2 + 1 = 3, which is less than 4.
Similarly, he needs 3 power to destroy 3-4. The total minimum power needed is 6.
Tags: binary search, brute force, divide and conquer, math
Correct Solution:
```
import bisect
n, k, A, B = map(int, input().split())
X = sorted([int(a)-1 for a in input().split()])
def calc(l, r, S):
cl = bisect.bisect_left(S, l)
cr = bisect.bisect_left(S, r)
c = cr - cl
if c == 0:
ret = A
elif r-l == 1:
ret = B * c
else:
m = (l+r) // 2
cm = bisect.bisect_left(S, m)
a = cm - cl
b = cr - cm
SL = []
SR = []
for s in S:
if s < m:
SL.append(s)
else:
SR.append(s)
if a == 0:
ret = min(A + calc(m, r, SR), B * c * (r - l))
elif b == 0:
ret = min(A + calc(l, m, SL), B * c * (r - l))
else:
ret = calc(l, m, SL) + calc(m, r, SR)
return ret
print(calc(0, 2**n, X))
```
| 93,571 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.
Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following:
* if the current length is at least 2, divide the base into 2 equal halves and destroy them separately, or
* burn the current base. If it contains no avenger in it, it takes A amount of power, otherwise it takes his B β
n_a β
l amount of power, where n_a is the number of avengers and l is the length of the current base.
Output the minimum power needed by Thanos to destroy the avengers' base.
Input
The first line contains four integers n, k, A and B (1 β€ n β€ 30, 1 β€ k β€ 10^5, 1 β€ A,B β€ 10^4), where 2^n is the length of the base, k is the number of avengers and A and B are the constants explained in the question.
The second line contains k integers a_{1}, a_{2}, a_{3}, β¦, a_{k} (1 β€ a_{i} β€ 2^n), where a_{i} represents the position of avenger in the base.
Output
Output one integer β the minimum power needed to destroy the avengers base.
Examples
Input
2 2 1 2
1 3
Output
6
Input
3 2 1 2
1 7
Output
8
Note
Consider the first example.
One option for Thanos is to burn the whole base 1-4 with power 2 β
2 β
4 = 16.
Otherwise he can divide the base into two parts 1-2 and 3-4.
For base 1-2, he can either burn it with power 2 β
1 β
2 = 4 or divide it into 2 parts 1-1 and 2-2.
For base 1-1, he can burn it with power 2 β
1 β
1 = 2. For 2-2, he can destroy it with power 1, as there are no avengers. So, the total power for destroying 1-2 is 2 + 1 = 3, which is less than 4.
Similarly, he needs 3 power to destroy 3-4. The total minimum power needed is 6.
Submitted Solution:
```
n,k,A,B = map(int,input().split())
f = list(sorted(list(map(int, input().split()))))
def min_cost(l, r, full):
if len(full) == 0:
return A
elif l == r:
return B * len(full)
else:
mid = (l + r) // 2
left = []
right = []
for i in full:
if i <= mid:
left.append(i)
else:
right.append(i)
return min(len(full) * (r - l + 1) * B, min_cost(l, mid, left) + min_cost(mid + 1, r, right))
print(min_cost(1, 2 ** n, f))
```
Yes
| 93,572 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.
Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following:
* if the current length is at least 2, divide the base into 2 equal halves and destroy them separately, or
* burn the current base. If it contains no avenger in it, it takes A amount of power, otherwise it takes his B β
n_a β
l amount of power, where n_a is the number of avengers and l is the length of the current base.
Output the minimum power needed by Thanos to destroy the avengers' base.
Input
The first line contains four integers n, k, A and B (1 β€ n β€ 30, 1 β€ k β€ 10^5, 1 β€ A,B β€ 10^4), where 2^n is the length of the base, k is the number of avengers and A and B are the constants explained in the question.
The second line contains k integers a_{1}, a_{2}, a_{3}, β¦, a_{k} (1 β€ a_{i} β€ 2^n), where a_{i} represents the position of avenger in the base.
Output
Output one integer β the minimum power needed to destroy the avengers base.
Examples
Input
2 2 1 2
1 3
Output
6
Input
3 2 1 2
1 7
Output
8
Note
Consider the first example.
One option for Thanos is to burn the whole base 1-4 with power 2 β
2 β
4 = 16.
Otherwise he can divide the base into two parts 1-2 and 3-4.
For base 1-2, he can either burn it with power 2 β
1 β
2 = 4 or divide it into 2 parts 1-1 and 2-2.
For base 1-1, he can burn it with power 2 β
1 β
1 = 2. For 2-2, he can destroy it with power 1, as there are no avengers. So, the total power for destroying 1-2 is 2 + 1 = 3, which is less than 4.
Similarly, he needs 3 power to destroy 3-4. The total minimum power needed is 6.
Submitted Solution:
```
n,k,A,B = map(int,input().split())
avg = [int(i) for i in input().split()]
avg.sort()
def get(l,h,a):
if len(a) == 0: return A
elif l==h: return B * len(a)
else:
mid = (l+h)//2
left = []
right = []
for i in a:
if i <= mid: left.append(i)
else: right.append(i)
pow_a = len(a)*(h-l+1)*B
pow_b = get(l,mid,left) + get(mid+1,h,right)
return min(pow_a,pow_b)
print(get(1,2**n,avg))
```
Yes
| 93,573 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.
Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following:
* if the current length is at least 2, divide the base into 2 equal halves and destroy them separately, or
* burn the current base. If it contains no avenger in it, it takes A amount of power, otherwise it takes his B β
n_a β
l amount of power, where n_a is the number of avengers and l is the length of the current base.
Output the minimum power needed by Thanos to destroy the avengers' base.
Input
The first line contains four integers n, k, A and B (1 β€ n β€ 30, 1 β€ k β€ 10^5, 1 β€ A,B β€ 10^4), where 2^n is the length of the base, k is the number of avengers and A and B are the constants explained in the question.
The second line contains k integers a_{1}, a_{2}, a_{3}, β¦, a_{k} (1 β€ a_{i} β€ 2^n), where a_{i} represents the position of avenger in the base.
Output
Output one integer β the minimum power needed to destroy the avengers base.
Examples
Input
2 2 1 2
1 3
Output
6
Input
3 2 1 2
1 7
Output
8
Note
Consider the first example.
One option for Thanos is to burn the whole base 1-4 with power 2 β
2 β
4 = 16.
Otherwise he can divide the base into two parts 1-2 and 3-4.
For base 1-2, he can either burn it with power 2 β
1 β
2 = 4 or divide it into 2 parts 1-1 and 2-2.
For base 1-1, he can burn it with power 2 β
1 β
1 = 2. For 2-2, he can destroy it with power 1, as there are no avengers. So, the total power for destroying 1-2 is 2 + 1 = 3, which is less than 4.
Similarly, he needs 3 power to destroy 3-4. The total minimum power needed is 6.
Submitted Solution:
```
n,k,a,b=map(int,input().split())
from bisect import bisect_right as br
from bisect import bisect_left as bl
p=list(map(int,input().split()))
p.sort()
def dp(i,j,nb):
if i==j:
if nb==0:return(a)
return(nb*b)
if nb==0:c=a;return(c)
else:c=b*nb*(j-i+1)
r=i+(j-i)//2
l=r+1
nbl=br(p,r)-bl(p,i)
nbr=nb-nbl
return(min(c,dp(i,r,nbl)+dp(l,j,nbr)))
print(dp(1,2**n,k))
```
Yes
| 93,574 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.
Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following:
* if the current length is at least 2, divide the base into 2 equal halves and destroy them separately, or
* burn the current base. If it contains no avenger in it, it takes A amount of power, otherwise it takes his B β
n_a β
l amount of power, where n_a is the number of avengers and l is the length of the current base.
Output the minimum power needed by Thanos to destroy the avengers' base.
Input
The first line contains four integers n, k, A and B (1 β€ n β€ 30, 1 β€ k β€ 10^5, 1 β€ A,B β€ 10^4), where 2^n is the length of the base, k is the number of avengers and A and B are the constants explained in the question.
The second line contains k integers a_{1}, a_{2}, a_{3}, β¦, a_{k} (1 β€ a_{i} β€ 2^n), where a_{i} represents the position of avenger in the base.
Output
Output one integer β the minimum power needed to destroy the avengers base.
Examples
Input
2 2 1 2
1 3
Output
6
Input
3 2 1 2
1 7
Output
8
Note
Consider the first example.
One option for Thanos is to burn the whole base 1-4 with power 2 β
2 β
4 = 16.
Otherwise he can divide the base into two parts 1-2 and 3-4.
For base 1-2, he can either burn it with power 2 β
1 β
2 = 4 or divide it into 2 parts 1-1 and 2-2.
For base 1-1, he can burn it with power 2 β
1 β
1 = 2. For 2-2, he can destroy it with power 1, as there are no avengers. So, the total power for destroying 1-2 is 2 + 1 = 3, which is less than 4.
Similarly, he needs 3 power to destroy 3-4. The total minimum power needed is 6.
Submitted Solution:
```
import bisect
# Turn list(str) into list(int)
def getIntList(lst):
assert type(lst) is list
rep = []
for i in lst:rep.append(int(i))
return rep
n,k,A,B = getIntList(input().split())
pos = getIntList(input().split())
def calc(l,r,heros):
assert type(heros) is list
if len(heros) == 0: return A
if r-l == 0: return B*len(heros)
mid = bisect.bisect_right(heros,(l+r)//2)
tans = min(
calc(l,(l+r)//2,heros[:mid])+calc((l+r)//2+1,r,heros[mid:]),
B*len(heros)*(r-l+1)
)
return tans
pos.sort()
ans = calc(1,2**n,pos)
print(ans)
```
Yes
| 93,575 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.
Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following:
* if the current length is at least 2, divide the base into 2 equal halves and destroy them separately, or
* burn the current base. If it contains no avenger in it, it takes A amount of power, otherwise it takes his B β
n_a β
l amount of power, where n_a is the number of avengers and l is the length of the current base.
Output the minimum power needed by Thanos to destroy the avengers' base.
Input
The first line contains four integers n, k, A and B (1 β€ n β€ 30, 1 β€ k β€ 10^5, 1 β€ A,B β€ 10^4), where 2^n is the length of the base, k is the number of avengers and A and B are the constants explained in the question.
The second line contains k integers a_{1}, a_{2}, a_{3}, β¦, a_{k} (1 β€ a_{i} β€ 2^n), where a_{i} represents the position of avenger in the base.
Output
Output one integer β the minimum power needed to destroy the avengers base.
Examples
Input
2 2 1 2
1 3
Output
6
Input
3 2 1 2
1 7
Output
8
Note
Consider the first example.
One option for Thanos is to burn the whole base 1-4 with power 2 β
2 β
4 = 16.
Otherwise he can divide the base into two parts 1-2 and 3-4.
For base 1-2, he can either burn it with power 2 β
1 β
2 = 4 or divide it into 2 parts 1-1 and 2-2.
For base 1-1, he can burn it with power 2 β
1 β
1 = 2. For 2-2, he can destroy it with power 1, as there are no avengers. So, the total power for destroying 1-2 is 2 + 1 = 3, which is less than 4.
Similarly, he needs 3 power to destroy 3-4. The total minimum power needed is 6.
Submitted Solution:
```
n, k, A, B = list(map(int, input().split()))
n = 2 ** n
a = sorted(list(map(int, input().split())))
def recurs(start, end, sum_all, array):
if sum_all == 0:
return A
else:
energy = B*(end - start)*sum_all
if end - start == 1:
return energy
c, d = [], []
for x in array:
if x < ((start + end)//2):
c += [x]
else:
d += [x]
first = sum(c)
second = sum_all - first
tmp = recurs(start, (start + end)//2, first, c)
tmp += recurs((start + end)//2, end, second, d)
return (energy < tmp) * energy + (1 - (energy < tmp))*tmp
print (recurs(0, n, k, a))
# import numpy as np
# print('ΠΠ²Π΅Π΄ΠΈΡΠ΅ ΠΊΠΎΠ»ΠΈΡΠ΅ΡΡΠ²ΠΎ ΡΡΠ°Π²Π½Π΅Π½ΠΈΠΉ:')
# n = int(input())
# print('ΠΠ²Π΅Π΄ΠΈΡΠ΅ Π»ΠΈΠ½Π΅ΠΉΠ½ΡΠ΅ ΠΊΠΎΡΡΠΈΡΠΈΠ΅Π½ΡΡ:')
# a = np.array([list(float(t) for t in input().split()) for i in range(n)])
# print(a.shape)
```
No
| 93,576 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.
Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following:
* if the current length is at least 2, divide the base into 2 equal halves and destroy them separately, or
* burn the current base. If it contains no avenger in it, it takes A amount of power, otherwise it takes his B β
n_a β
l amount of power, where n_a is the number of avengers and l is the length of the current base.
Output the minimum power needed by Thanos to destroy the avengers' base.
Input
The first line contains four integers n, k, A and B (1 β€ n β€ 30, 1 β€ k β€ 10^5, 1 β€ A,B β€ 10^4), where 2^n is the length of the base, k is the number of avengers and A and B are the constants explained in the question.
The second line contains k integers a_{1}, a_{2}, a_{3}, β¦, a_{k} (1 β€ a_{i} β€ 2^n), where a_{i} represents the position of avenger in the base.
Output
Output one integer β the minimum power needed to destroy the avengers base.
Examples
Input
2 2 1 2
1 3
Output
6
Input
3 2 1 2
1 7
Output
8
Note
Consider the first example.
One option for Thanos is to burn the whole base 1-4 with power 2 β
2 β
4 = 16.
Otherwise he can divide the base into two parts 1-2 and 3-4.
For base 1-2, he can either burn it with power 2 β
1 β
2 = 4 or divide it into 2 parts 1-1 and 2-2.
For base 1-1, he can burn it with power 2 β
1 β
1 = 2. For 2-2, he can destroy it with power 1, as there are no avengers. So, the total power for destroying 1-2 is 2 + 1 = 3, which is less than 4.
Similarly, he needs 3 power to destroy 3-4. The total minimum power needed is 6.
Submitted Solution:
```
def get(tl, tr, a):
global A, B
if len(a) == 0:
return A
if tl == tr:
return B
tm = (tl + tr) // 2
c, d = [], []
for x in a:
if x <= tm:
c += [x]
else:
d += [x]
return min(B * len(a) * (tr - tl + 1), get(tl, tm, c) + get(tm + 1, tr, d))
n, k, A, B = map(int, input().split())
a = list(sorted(list(map(int, input().split()))))
print(get(1, 1 << n, a))
```
No
| 93,577 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.
Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following:
* if the current length is at least 2, divide the base into 2 equal halves and destroy them separately, or
* burn the current base. If it contains no avenger in it, it takes A amount of power, otherwise it takes his B β
n_a β
l amount of power, where n_a is the number of avengers and l is the length of the current base.
Output the minimum power needed by Thanos to destroy the avengers' base.
Input
The first line contains four integers n, k, A and B (1 β€ n β€ 30, 1 β€ k β€ 10^5, 1 β€ A,B β€ 10^4), where 2^n is the length of the base, k is the number of avengers and A and B are the constants explained in the question.
The second line contains k integers a_{1}, a_{2}, a_{3}, β¦, a_{k} (1 β€ a_{i} β€ 2^n), where a_{i} represents the position of avenger in the base.
Output
Output one integer β the minimum power needed to destroy the avengers base.
Examples
Input
2 2 1 2
1 3
Output
6
Input
3 2 1 2
1 7
Output
8
Note
Consider the first example.
One option for Thanos is to burn the whole base 1-4 with power 2 β
2 β
4 = 16.
Otherwise he can divide the base into two parts 1-2 and 3-4.
For base 1-2, he can either burn it with power 2 β
1 β
2 = 4 or divide it into 2 parts 1-1 and 2-2.
For base 1-1, he can burn it with power 2 β
1 β
1 = 2. For 2-2, he can destroy it with power 1, as there are no avengers. So, the total power for destroying 1-2 is 2 + 1 = 3, which is less than 4.
Similarly, he needs 3 power to destroy 3-4. The total minimum power needed is 6.
Submitted Solution:
```
nkAB=list(map(int,input().split()))
K=list(map(int,input().split()))
n=nkAB[0]
k=nkAB[1]
A=nkAB[2]
B=nkAB[3]
posn_avn=[]
for i in range(pow(2,n)):
posn_avn.append(0)
for i in K:
posn_avn[i-1]=1
def result(l,a,b):
m=0
if(l.count(0)==len(l))and(len(l)>=1):
m+=a
if(len(l)==1)and(l[0]==1):
m+=b
else:
if(len(l)>1)and(l.count(0)!=len(l)):
l1=l[0:int(len(l)/2)]
l2=l[int(len(l)/2):len(l)]
m+=result(l1,a,b)
m+=result(l2,a,b)
return m
print(result(posn_avn,A,B))
```
No
| 93,578 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.
Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following:
* if the current length is at least 2, divide the base into 2 equal halves and destroy them separately, or
* burn the current base. If it contains no avenger in it, it takes A amount of power, otherwise it takes his B β
n_a β
l amount of power, where n_a is the number of avengers and l is the length of the current base.
Output the minimum power needed by Thanos to destroy the avengers' base.
Input
The first line contains four integers n, k, A and B (1 β€ n β€ 30, 1 β€ k β€ 10^5, 1 β€ A,B β€ 10^4), where 2^n is the length of the base, k is the number of avengers and A and B are the constants explained in the question.
The second line contains k integers a_{1}, a_{2}, a_{3}, β¦, a_{k} (1 β€ a_{i} β€ 2^n), where a_{i} represents the position of avenger in the base.
Output
Output one integer β the minimum power needed to destroy the avengers base.
Examples
Input
2 2 1 2
1 3
Output
6
Input
3 2 1 2
1 7
Output
8
Note
Consider the first example.
One option for Thanos is to burn the whole base 1-4 with power 2 β
2 β
4 = 16.
Otherwise he can divide the base into two parts 1-2 and 3-4.
For base 1-2, he can either burn it with power 2 β
1 β
2 = 4 or divide it into 2 parts 1-1 and 2-2.
For base 1-1, he can burn it with power 2 β
1 β
1 = 2. For 2-2, he can destroy it with power 1, as there are no avengers. So, the total power for destroying 1-2 is 2 + 1 = 3, which is less than 4.
Similarly, he needs 3 power to destroy 3-4. The total minimum power needed is 6.
Submitted Solution:
```
def explosion(a, x, y, q, l, r):
if r - l == 1:
q1 = q
while q1 < len(a) and a[q1] < r:
q1 += 1
if q1 == q:
return x
else:
return (q1-q)*y
q1 = q
while q1 < len(a) and a[q1] < (l+r)//2:
q1 += 1
q2 = q1
while q2 < len(a) and a[q2] < r:
q2 += 1
if q1-q == 0 and q2-q1 == 0:
return x
if q2-q1 != 0 and q1-q != 0:
return explosion(a, x, y, q, l, (l+r)//2)+explosion(a, x, y, q1, (l+r)//2, r)
if q1 != q:
d = explosion(a, x, y, q, l, (l+r)//2)
if d > x:
return x+explosion(a, x, y, q, l, (l+r)//2)
else:
return (r-l)*(q1-q)*y
else:
d = explosion(a, x, y, q1, (l+r)//2, r)
if d > x:
return x+explosion(a, x, y, q1, (l+r)//2, r)
else:
return (r-l)*(q2-q1)*y
n, k, x, y = map(int, input().split())
a = sorted(list(map(int, input().split())))
print(explosion(a, x, y, 0, 0, 2**n))
```
No
| 93,579 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.
Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.
It is easy to prove that any way to transform n to m contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).
Input
The only line of the input contains two integers n and m (1 β€ n β€ m β€ 5β
10^8).
Output
Print the number of moves to transform n to m, or -1 if there is no solution.
Examples
Input
120 51840
Output
7
Input
42 42
Output
0
Input
48 72
Output
-1
Note
In the first example, the possible sequence of moves is: 120 β 240 β 720 β 1440 β 4320 β 12960 β 25920 β 51840. The are 7 steps in total.
In the second example, no moves are needed. Thus, the answer is 0.
In the third example, it is impossible to transform 48 to 72.
Tags: implementation, math
Correct Solution:
```
n, m = map(int, input().split())
if m % n != 0:
print(-1)
else:
x = m / n
two = 0
three = 0
while (x % 2 == 0):
two += 1
x = x // 2
while (x % 3 == 0):
three += 1
x = x // 3
if x != 1:
print(-1)
else:
print(two + three)
```
| 93,580 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.
Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.
It is easy to prove that any way to transform n to m contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).
Input
The only line of the input contains two integers n and m (1 β€ n β€ m β€ 5β
10^8).
Output
Print the number of moves to transform n to m, or -1 if there is no solution.
Examples
Input
120 51840
Output
7
Input
42 42
Output
0
Input
48 72
Output
-1
Note
In the first example, the possible sequence of moves is: 120 β 240 β 720 β 1440 β 4320 β 12960 β 25920 β 51840. The are 7 steps in total.
In the second example, no moves are needed. Thus, the answer is 0.
In the third example, it is impossible to transform 48 to 72.
Tags: implementation, math
Correct Solution:
```
import math
x, y = map(int, input().split())
v, c = y / x, 0
while v % 3 == 0:
v /= 3
c += 1
while v % 2 == 0:
v /= 2
c += 1
if v > 1:
print(-1)
else:
print(c)
```
| 93,581 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.
Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.
It is easy to prove that any way to transform n to m contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).
Input
The only line of the input contains two integers n and m (1 β€ n β€ m β€ 5β
10^8).
Output
Print the number of moves to transform n to m, or -1 if there is no solution.
Examples
Input
120 51840
Output
7
Input
42 42
Output
0
Input
48 72
Output
-1
Note
In the first example, the possible sequence of moves is: 120 β 240 β 720 β 1440 β 4320 β 12960 β 25920 β 51840. The are 7 steps in total.
In the second example, no moves are needed. Thus, the answer is 0.
In the third example, it is impossible to transform 48 to 72.
Tags: implementation, math
Correct Solution:
```
n,m=map(int,input().split())
if(m%n):
print(-1)
exit()
ans=0
m=m//n
while(m>1):
if(m%3==0):
ans+=1
m=m//3
if(m%2==0):
ans+=1
m=m//2
if(m>1 and m%2 and m%3):
print(-1)
exit()
print(ans)
```
| 93,582 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.
Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.
It is easy to prove that any way to transform n to m contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).
Input
The only line of the input contains two integers n and m (1 β€ n β€ m β€ 5β
10^8).
Output
Print the number of moves to transform n to m, or -1 if there is no solution.
Examples
Input
120 51840
Output
7
Input
42 42
Output
0
Input
48 72
Output
-1
Note
In the first example, the possible sequence of moves is: 120 β 240 β 720 β 1440 β 4320 β 12960 β 25920 β 51840. The are 7 steps in total.
In the second example, no moves are needed. Thus, the answer is 0.
In the third example, it is impossible to transform 48 to 72.
Tags: implementation, math
Correct Solution:
```
n, m = map(int, input().split())
if m % n:
print(-1)
exit(0)
m //= n
a = 0
while m % 2 == 0:
m//=2
a+=1
while m % 3 == 0:
m//=3
a+=1
if m==1:
print(a)
else:
print(-1)
```
| 93,583 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.
Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.
It is easy to prove that any way to transform n to m contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).
Input
The only line of the input contains two integers n and m (1 β€ n β€ m β€ 5β
10^8).
Output
Print the number of moves to transform n to m, or -1 if there is no solution.
Examples
Input
120 51840
Output
7
Input
42 42
Output
0
Input
48 72
Output
-1
Note
In the first example, the possible sequence of moves is: 120 β 240 β 720 β 1440 β 4320 β 12960 β 25920 β 51840. The are 7 steps in total.
In the second example, no moves are needed. Thus, the answer is 0.
In the third example, it is impossible to transform 48 to 72.
Tags: implementation, math
Correct Solution:
```
n,m = list(map(int,input().split()))
if m%n == 0:
d = m//n
if d > 1:
count = 0
while d%2 == 0:
count += 1
d = d//2
while d%3 == 0:
count += 1
d = d//3
if d == 1:
print(count)
else:
print(-1)
else:
print(0)
else:
print(-1)
```
| 93,584 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.
Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.
It is easy to prove that any way to transform n to m contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).
Input
The only line of the input contains two integers n and m (1 β€ n β€ m β€ 5β
10^8).
Output
Print the number of moves to transform n to m, or -1 if there is no solution.
Examples
Input
120 51840
Output
7
Input
42 42
Output
0
Input
48 72
Output
-1
Note
In the first example, the possible sequence of moves is: 120 β 240 β 720 β 1440 β 4320 β 12960 β 25920 β 51840. The are 7 steps in total.
In the second example, no moves are needed. Thus, the answer is 0.
In the third example, it is impossible to transform 48 to 72.
Tags: implementation, math
Correct Solution:
```
a,b=map(int,input().split())
i=0
if b%a==0:
b=b//a
while b!=1:
if b%2==0:
b=b//2
i=i+1
elif b%3==0:
b=b//3
i=i+1
elif b%2!=0 and b%3!=0 and b>1:
b=1
i=-1
elif b<1:
b=1
i=-1
print(i)
else:
print(-1)
```
| 93,585 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.
Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.
It is easy to prove that any way to transform n to m contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).
Input
The only line of the input contains two integers n and m (1 β€ n β€ m β€ 5β
10^8).
Output
Print the number of moves to transform n to m, or -1 if there is no solution.
Examples
Input
120 51840
Output
7
Input
42 42
Output
0
Input
48 72
Output
-1
Note
In the first example, the possible sequence of moves is: 120 β 240 β 720 β 1440 β 4320 β 12960 β 25920 β 51840. The are 7 steps in total.
In the second example, no moves are needed. Thus, the answer is 0.
In the third example, it is impossible to transform 48 to 72.
Tags: implementation, math
Correct Solution:
```
n, m = map(int, input().split())
if m % n:
print(-1)
else:
m //= n
k = 0
for d in (2,3):
while m % d == 0:
m //= d
k += 1
print(k if m < 2 else -1)
```
| 93,586 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.
Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.
It is easy to prove that any way to transform n to m contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).
Input
The only line of the input contains two integers n and m (1 β€ n β€ m β€ 5β
10^8).
Output
Print the number of moves to transform n to m, or -1 if there is no solution.
Examples
Input
120 51840
Output
7
Input
42 42
Output
0
Input
48 72
Output
-1
Note
In the first example, the possible sequence of moves is: 120 β 240 β 720 β 1440 β 4320 β 12960 β 25920 β 51840. The are 7 steps in total.
In the second example, no moves are needed. Thus, the answer is 0.
In the third example, it is impossible to transform 48 to 72.
Tags: implementation, math
Correct Solution:
```
x,y=map(int,input().split())
s=0
if y/x==1:
print(0)
elif int(y/x)!=y/x:
print(-1)
else:
d=y/x
while d!=1:
if int(d/2)!=d/2 and int(d/3)!=d/3:
print(-1)
exit()
for i in [2,3]:
if int(d/i)!=d/i:
d=d
else:
d=d/i
s=s+1
print(s)
```
| 93,587 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.
Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.
It is easy to prove that any way to transform n to m contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).
Input
The only line of the input contains two integers n and m (1 β€ n β€ m β€ 5β
10^8).
Output
Print the number of moves to transform n to m, or -1 if there is no solution.
Examples
Input
120 51840
Output
7
Input
42 42
Output
0
Input
48 72
Output
-1
Note
In the first example, the possible sequence of moves is: 120 β 240 β 720 β 1440 β 4320 β 12960 β 25920 β 51840. The are 7 steps in total.
In the second example, no moves are needed. Thus, the answer is 0.
In the third example, it is impossible to transform 48 to 72.
Submitted Solution:
```
# print("Input n and m")
n,m = [int(x) for x in input().split()]
if m%n != 0:
print(-1)
else:
answer = 0
qu = m//n
while qu%2==0:
qu = qu // 2
answer += 1
while qu%3==0:
qu = qu // 3
answer += 1
if qu == 1:
print(str(answer))
else:
print(-1)
```
Yes
| 93,588 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.
Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.
It is easy to prove that any way to transform n to m contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).
Input
The only line of the input contains two integers n and m (1 β€ n β€ m β€ 5β
10^8).
Output
Print the number of moves to transform n to m, or -1 if there is no solution.
Examples
Input
120 51840
Output
7
Input
42 42
Output
0
Input
48 72
Output
-1
Note
In the first example, the possible sequence of moves is: 120 β 240 β 720 β 1440 β 4320 β 12960 β 25920 β 51840. The are 7 steps in total.
In the second example, no moves are needed. Thus, the answer is 0.
In the third example, it is impossible to transform 48 to 72.
Submitted Solution:
```
x,y=map(int,input().split())
k=-1
if y%x==0:
k=0
p=y/x
while p%2==0:
p/=2
k+=1
while p%3==0:
p/=3
k+=1
if p!=1:k=-1
print(k)
```
Yes
| 93,589 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.
Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.
It is easy to prove that any way to transform n to m contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).
Input
The only line of the input contains two integers n and m (1 β€ n β€ m β€ 5β
10^8).
Output
Print the number of moves to transform n to m, or -1 if there is no solution.
Examples
Input
120 51840
Output
7
Input
42 42
Output
0
Input
48 72
Output
-1
Note
In the first example, the possible sequence of moves is: 120 β 240 β 720 β 1440 β 4320 β 12960 β 25920 β 51840. The are 7 steps in total.
In the second example, no moves are needed. Thus, the answer is 0.
In the third example, it is impossible to transform 48 to 72.
Submitted Solution:
```
n,m=map(int,input().split())
r=-1
if m%n==0:
m//=n;r=0
for d in 2,3:
while m%d==0:m//=d;r+=1
if m>1:r=-1
print(r)
```
Yes
| 93,590 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.
Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.
It is easy to prove that any way to transform n to m contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).
Input
The only line of the input contains two integers n and m (1 β€ n β€ m β€ 5β
10^8).
Output
Print the number of moves to transform n to m, or -1 if there is no solution.
Examples
Input
120 51840
Output
7
Input
42 42
Output
0
Input
48 72
Output
-1
Note
In the first example, the possible sequence of moves is: 120 β 240 β 720 β 1440 β 4320 β 12960 β 25920 β 51840. The are 7 steps in total.
In the second example, no moves are needed. Thus, the answer is 0.
In the third example, it is impossible to transform 48 to 72.
Submitted Solution:
```
n, m = map(int, input().split())
if m % n:
print(-1)
else:
d = m // n
c = 0
while d % 2 == 0:
d //= 2
c += 1
while d % 3 == 0:
d //= 3
c += 1
if d == 1:
print(c)
else:
print(-1)
```
Yes
| 93,591 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.
Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.
It is easy to prove that any way to transform n to m contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).
Input
The only line of the input contains two integers n and m (1 β€ n β€ m β€ 5β
10^8).
Output
Print the number of moves to transform n to m, or -1 if there is no solution.
Examples
Input
120 51840
Output
7
Input
42 42
Output
0
Input
48 72
Output
-1
Note
In the first example, the possible sequence of moves is: 120 β 240 β 720 β 1440 β 4320 β 12960 β 25920 β 51840. The are 7 steps in total.
In the second example, no moves are needed. Thus, the answer is 0.
In the third example, it is impossible to transform 48 to 72.
Submitted Solution:
```
n,m=map(int,input().split())
p=m/n
sum1=0
if m%n!=0: print(-1)
else:
while(p%2==0):
p/=2
sum1+=1
while(p%3==0):
p/=3
sum1+=1
print(sum1)
```
No
| 93,592 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.
Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.
It is easy to prove that any way to transform n to m contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).
Input
The only line of the input contains two integers n and m (1 β€ n β€ m β€ 5β
10^8).
Output
Print the number of moves to transform n to m, or -1 if there is no solution.
Examples
Input
120 51840
Output
7
Input
42 42
Output
0
Input
48 72
Output
-1
Note
In the first example, the possible sequence of moves is: 120 β 240 β 720 β 1440 β 4320 β 12960 β 25920 β 51840. The are 7 steps in total.
In the second example, no moves are needed. Thus, the answer is 0.
In the third example, it is impossible to transform 48 to 72.
Submitted Solution:
```
n,m=map(int,input().split())
count =0
if not((m//n)%2 == 0 or (m//n)%3==0 or m==n):
print(-1)
else:
if (m//n)%2 == 0 or (m//n)%3==0 or m==n:
while m>n :
if (m//n)%2 == 0 or (m//n)%3==0 or m==n:
if m%2 == 0 and m!=n:
m/=2
count +=1
if m%3 == 0 and m!=n:
m/=3
count +=1
print(int(count))
```
No
| 93,593 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.
Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.
It is easy to prove that any way to transform n to m contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).
Input
The only line of the input contains two integers n and m (1 β€ n β€ m β€ 5β
10^8).
Output
Print the number of moves to transform n to m, or -1 if there is no solution.
Examples
Input
120 51840
Output
7
Input
42 42
Output
0
Input
48 72
Output
-1
Note
In the first example, the possible sequence of moves is: 120 β 240 β 720 β 1440 β 4320 β 12960 β 25920 β 51840. The are 7 steps in total.
In the second example, no moves are needed. Thus, the answer is 0.
In the third example, it is impossible to transform 48 to 72.
Submitted Solution:
```
import math
def primeFactors(n):
c=[]
# Print the number of two's that divide n
while n % 2 == 0:
c.append(2)
n = n // 2
# n must be odd at this point
# so a skip of 2 ( i = i + 2) can be used
for i in range(3,int(math.sqrt(n))+1,2):
# while i divides n , print i ad divide n
while n % i== 0:
c.append(i)
n = n // i
# Condition if n is a prime
# number greater than 2
if n > 2:
c.append(n)
return c
n,m = map(int,input().split())
k = m//n
l = m%n
if(l!=0 or (k%3!=0 and k%2!=0)):
if(n==m):
print(0)
else:
print(-1)
else:
print(len(primeFactors(k)))
```
No
| 93,594 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.
Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.
It is easy to prove that any way to transform n to m contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).
Input
The only line of the input contains two integers n and m (1 β€ n β€ m β€ 5β
10^8).
Output
Print the number of moves to transform n to m, or -1 if there is no solution.
Examples
Input
120 51840
Output
7
Input
42 42
Output
0
Input
48 72
Output
-1
Note
In the first example, the possible sequence of moves is: 120 β 240 β 720 β 1440 β 4320 β 12960 β 25920 β 51840. The are 7 steps in total.
In the second example, no moves are needed. Thus, the answer is 0.
In the third example, it is impossible to transform 48 to 72.
Submitted Solution:
```
a=input()
b=[int(x)for x in a.split()]
def func3(number, rezdel):
for i in range(number):
if ((2**i)*(3**(number-i)))==rezdel:
return False
return True
def func (razdel):
for i in range(razdel):
if(3**i==razdel):
return i
def func2(razdel):
for i in range(razdel):
if(2**i==razdel):
return i
count=1
if b[1]%b[0]==0:
if(b[1]==b[0]):
print(0)
if(b[1]/b[0])%6==0:
while(func3(count,(int(b[1]/b[0])))):
count+=1
print(count)
elif(b[1]/b[0])%3==0:
print(func(int(b[1]/b[0])))
elif (b[1]/b[0])%2==0:
print(str(func2(int(b[1]/b[0]))))
else:
print(-1)
```
No
| 93,595 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a binary string s (recall that a string is binary if each character is either 0 or 1).
Let f(t) be the decimal representation of integer t written in binary form (possibly with leading zeroes). For example f(011) = 3, f(00101) = 5, f(00001) = 1, f(10) = 2, f(000) = 0 and f(000100) = 4.
The substring s_{l}, s_{l+1}, ... , s_{r} is good if r - l + 1 = f(s_l ... s_r).
For example string s = 1011 has 5 good substrings: s_1 ... s_1 = 1, s_3 ... s_3 = 1, s_4 ... s_4 = 1, s_1 ... s_2 = 10 and s_2 ... s_4 = 011.
Your task is to calculate the number of good substrings of string s.
You have to answer t independent queries.
Input
The first line contains one integer t (1 β€ t β€ 1000) β the number of queries.
The only line of each query contains string s (1 β€ |s| β€ 2 β
10^5), consisting of only digits 0 and 1.
It is guaranteed that β_{i=1}^{t} |s_i| β€ 2 β
10^5.
Output
For each query print one integer β the number of good substrings of string s.
Example
Input
4
0110
0101
00001000
0001000
Output
4
3
4
3
Tags: binary search, bitmasks, brute force
Correct Solution:
```
import sys
from bisect import *
zz=1
sys.setrecursionlimit(10**5)
if zz:
input=sys.stdin.readline
else:
sys.stdin=open('input.txt', 'r')
sys.stdout=open('all.txt','w')
di=[[-1,0],[1,0],[0,1],[0,-1]]
def fori(n):
return [fi() for i in range(n)]
def inc(d,c,x=1):
d[c]=d[c]+x if c in d else x
def ii():
return input().rstrip()
def li():
return [int(xx) for xx in input().split()]
def fli():
return [float(x) for x in input().split()]
def comp(a,b):
if(a>b):
return 2
return 2 if a==b else 0
def gi():
return [xx for xx in input().split()]
def gtc(tc,ans):
print("Case #"+str(tc)+":",ans)
def cil(n,m):
return n//m+int(n%m>0)
def fi():
return int(input())
def pro(a):
return reduce(lambda a,b:a*b,a)
def swap(a,i,j):
a[i],a[j]=a[j],a[i]
def si():
return list(input().rstrip())
def mi():
return map(int,input().split())
def gh():
sys.stdout.flush()
def isvalid(i,j,n,m):
return 0<=i<n and 0<=j<m
def bo(i):
return ord(i)-ord('a')
def graph(n,m):
for i in range(m):
x,y=mi()
a[x].append(y)
a[y].append(x)
t=fi()
uu=t
while t>0:
t-=1
s=ii()
n=len(s)
a=[]
for i in range(n):
if s[i]=='1':
a.append(i)
ans=0
for i in range(n-1,-1,-1):
c=0
for j in range(i,max(-1,i-21),-1):
c+=int(s[j])*2**(i-j)
if i+1<c:
break
if s[j]=='1' :
w=bisect_left(a,i-c+1)
if a[w]==j:
ans+=1
print(ans)
```
| 93,596 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a binary string s (recall that a string is binary if each character is either 0 or 1).
Let f(t) be the decimal representation of integer t written in binary form (possibly with leading zeroes). For example f(011) = 3, f(00101) = 5, f(00001) = 1, f(10) = 2, f(000) = 0 and f(000100) = 4.
The substring s_{l}, s_{l+1}, ... , s_{r} is good if r - l + 1 = f(s_l ... s_r).
For example string s = 1011 has 5 good substrings: s_1 ... s_1 = 1, s_3 ... s_3 = 1, s_4 ... s_4 = 1, s_1 ... s_2 = 10 and s_2 ... s_4 = 011.
Your task is to calculate the number of good substrings of string s.
You have to answer t independent queries.
Input
The first line contains one integer t (1 β€ t β€ 1000) β the number of queries.
The only line of each query contains string s (1 β€ |s| β€ 2 β
10^5), consisting of only digits 0 and 1.
It is guaranteed that β_{i=1}^{t} |s_i| β€ 2 β
10^5.
Output
For each query print one integer β the number of good substrings of string s.
Example
Input
4
0110
0101
00001000
0001000
Output
4
3
4
3
Tags: binary search, bitmasks, brute force
Correct Solution:
```
import math
import sys
from collections import defaultdict
# input = sys.stdin.readline
rt = lambda: map(int, input().split())
ri = lambda: int(input())
rl = lambda: list(map(int, input().split()))
def solve(a):
n = len(a)
pref0 = [0] * n
for i in range(n):
if i == 0:
pref0[i] = 0
else:
pref0[i] = pref0[i-1] + 1 if a[i-1] == 0 else 0
res = 0
for i, val in enumerate(a):
if val == 1:
j = i
curr = 0
while j < n:
curr = 2*curr + a[j]
curr_len = j - i + 1
zpref = curr - curr_len
if zpref > i or zpref > pref0[i]:
break
res += 1
j += 1
return res
def main():
T = ri()
for _ in range(T):
print(solve(list(map(int, input()))))
if __name__ == '__main__':
main()
```
| 93,597 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a binary string s (recall that a string is binary if each character is either 0 or 1).
Let f(t) be the decimal representation of integer t written in binary form (possibly with leading zeroes). For example f(011) = 3, f(00101) = 5, f(00001) = 1, f(10) = 2, f(000) = 0 and f(000100) = 4.
The substring s_{l}, s_{l+1}, ... , s_{r} is good if r - l + 1 = f(s_l ... s_r).
For example string s = 1011 has 5 good substrings: s_1 ... s_1 = 1, s_3 ... s_3 = 1, s_4 ... s_4 = 1, s_1 ... s_2 = 10 and s_2 ... s_4 = 011.
Your task is to calculate the number of good substrings of string s.
You have to answer t independent queries.
Input
The first line contains one integer t (1 β€ t β€ 1000) β the number of queries.
The only line of each query contains string s (1 β€ |s| β€ 2 β
10^5), consisting of only digits 0 and 1.
It is guaranteed that β_{i=1}^{t} |s_i| β€ 2 β
10^5.
Output
For each query print one integer β the number of good substrings of string s.
Example
Input
4
0110
0101
00001000
0001000
Output
4
3
4
3
Tags: binary search, bitmasks, brute force
Correct Solution:
```
# import sys
# input = sys.stdin.readline
def calc(s):
return int(s,2)
for nt in range(int(input())):
s=input()
n=len(s)
pref=[-1]*(n)
for i in range(n):
if s[i]=="1":
pref[i]=i
else:
pref[i]=pref[i-1]
ans=0
for i in range(18):
for j in range(n-1,i-1,-1):
temp=s[j-i:j+1]
# print (temp,i,j,calc(temp),ans,j-pref[j-i-1])
if calc(temp)==i+1 and temp[0]=="1":
ans+=1
elif s[j-i]=="1" and j-i-1>=0 and calc(temp)>i+1 and calc(temp)<=(j-pref[j-i-1]):
ans+=1
print (ans)
```
| 93,598 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a binary string s (recall that a string is binary if each character is either 0 or 1).
Let f(t) be the decimal representation of integer t written in binary form (possibly with leading zeroes). For example f(011) = 3, f(00101) = 5, f(00001) = 1, f(10) = 2, f(000) = 0 and f(000100) = 4.
The substring s_{l}, s_{l+1}, ... , s_{r} is good if r - l + 1 = f(s_l ... s_r).
For example string s = 1011 has 5 good substrings: s_1 ... s_1 = 1, s_3 ... s_3 = 1, s_4 ... s_4 = 1, s_1 ... s_2 = 10 and s_2 ... s_4 = 011.
Your task is to calculate the number of good substrings of string s.
You have to answer t independent queries.
Input
The first line contains one integer t (1 β€ t β€ 1000) β the number of queries.
The only line of each query contains string s (1 β€ |s| β€ 2 β
10^5), consisting of only digits 0 and 1.
It is guaranteed that β_{i=1}^{t} |s_i| β€ 2 β
10^5.
Output
For each query print one integer β the number of good substrings of string s.
Example
Input
4
0110
0101
00001000
0001000
Output
4
3
4
3
Tags: binary search, bitmasks, brute force
Correct Solution:
```
'''
Auther: ghoshashis545 Ashis Ghosh
College: jalpaiguri Govt Enggineering College
'''
from os import path
from io import BytesIO, IOBase
import sys
from heapq import heappush,heappop
from functools import cmp_to_key as ctk
from collections import deque,Counter,defaultdict as dd
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input().rstrip()
def mi():return map(int,input().split())
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
# mod=1000000007
mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]
def bo(i):
return ord(i)-ord('0')
file = 1
def ceil(a,b):
return (a+b-1)//b
# write fastio for getting fastio template.
def solve():
for _ in range(ii()):
s = si()
n = len(s)
ans = 0
c = 0
for i in range(n):
if s[i] == '1':
x = 1
ans +=1
for j in range(min(c+1,n-i-1)):
x *= 2
if s[i+j+1]=='1':
x += 1
if (j+2+c) >= x:
ans += 1
else:
break
c = 0
else:
c +=1
print(ans)
if __name__ =="__main__":
if(file):
if path.exists('input.txt'):
sys.stdin=open('input.txt', 'r')
sys.stdout=open('output.txt','w')
else:
input=sys.stdin.readline
solve()
```
| 93,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.