message stringlengths 2 44.5k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 276 109k | cluster float64 23 23 | __index_level_0__ int64 552 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the length of any stick.
Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them.
Input
The single line contains 4 integers a, b, c, l (1 ≤ a, b, c ≤ 3·105, 0 ≤ l ≤ 3·105).
Output
Print a single integer — the number of ways to increase the sizes of the sticks by the total of at most l centimeters, so that you can make a non-degenerate triangle from it.
Examples
Input
1 1 1 2
Output
4
Input
1 2 3 1
Output
2
Input
10 2 1 7
Output
0
Note
In the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter.
In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions.
Submitted Solution:
```
from math import ceil
a, b, c, l = list(map(int, input().split()))
ans = 0
for i in range(l + 1):
a1 = a + i
lmin = max(a1 - (b + c) + 1, 0)
lmax = l - i
diffmax = a1 + b - c - 1
diffmin = b - c - a1 + 1
ans += max(0, (max(diffmax - diffmin + 1, 0)) * ((lmax + diffmin) // 2 - max(diffmax, ceil((lmin + diffmax) / 2))))
ans += (lmax - max(ceil((lmin + diffmax) / 2), ceil((lmax + diffmin) / 2))) * (max(0, lmax - lmin + 1))
#for lc in range(lmax + 1):
# ans += max(-1, min(lmax - lc, lc - diffmin) - max(lc - diffmax, lmin-lc, 0)) + 1
print(ans)
``` | instruction | 0 | 89,711 | 23 | 179,422 |
No | output | 1 | 89,711 | 23 | 179,423 |
Provide a correct Python 3 solution for this coding contest problem.
Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm.
........#
........#
........#
........#
Constraints
* 3 ≤ H ≤ 300
* 3 ≤ W ≤ 300
Input
The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.
The input ends with two 0 (when both H and W are zero).
Output
For each dataset, print the frame made of '#' and '.'.
Print a blank line after each dataset.
Example
Input
3 4
5 6
3 3
0 0
Output
####
#..#
####
######
#....#
#....#
#....#
######
###
#.#
### | instruction | 0 | 90,082 | 23 | 180,164 |
"Correct Solution:
```
while True:
h,w = map(int, input().split())
if (w + h) == 0:
break
print("#"*w)
for i in range(h-2):
print("#"+"."*(w-2)+"#")
print("#"*w)
print("")
``` | output | 1 | 90,082 | 23 | 180,165 |
Provide a correct Python 3 solution for this coding contest problem.
Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm.
........#
........#
........#
........#
Constraints
* 3 ≤ H ≤ 300
* 3 ≤ W ≤ 300
Input
The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.
The input ends with two 0 (when both H and W are zero).
Output
For each dataset, print the frame made of '#' and '.'.
Print a blank line after each dataset.
Example
Input
3 4
5 6
3 3
0 0
Output
####
#..#
####
######
#....#
#....#
#....#
######
###
#.#
### | instruction | 0 | 90,083 | 23 | 180,166 |
"Correct Solution:
```
while True:
y,x = map(int,input().split())
if y == 0 and x == 0:
break
print("#"*x)
for j in range(y-2):
print("#"+"."*(x-2)+"#")
print("#"*x)
print()
``` | output | 1 | 90,083 | 23 | 180,167 |
Provide a correct Python 3 solution for this coding contest problem.
Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm.
........#
........#
........#
........#
Constraints
* 3 ≤ H ≤ 300
* 3 ≤ W ≤ 300
Input
The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.
The input ends with two 0 (when both H and W are zero).
Output
For each dataset, print the frame made of '#' and '.'.
Print a blank line after each dataset.
Example
Input
3 4
5 6
3 3
0 0
Output
####
#..#
####
######
#....#
#....#
#....#
######
###
#.#
### | instruction | 0 | 90,084 | 23 | 180,168 |
"Correct Solution:
```
while True:
h, w = map(int, input().split())
if(h==0):
break
print('#'*w)
[print('#'+'.'*(w-2)+'#') for i in range(h-2)]
print('#'*w)
print()
``` | output | 1 | 90,084 | 23 | 180,169 |
Provide a correct Python 3 solution for this coding contest problem.
Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm.
........#
........#
........#
........#
Constraints
* 3 ≤ H ≤ 300
* 3 ≤ W ≤ 300
Input
The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.
The input ends with two 0 (when both H and W are zero).
Output
For each dataset, print the frame made of '#' and '.'.
Print a blank line after each dataset.
Example
Input
3 4
5 6
3 3
0 0
Output
####
#..#
####
######
#....#
#....#
#....#
######
###
#.#
### | instruction | 0 | 90,085 | 23 | 180,170 |
"Correct Solution:
```
while True:
H,W = map(int,input().split())
if H==0 and W==0:
break
print("#"*W)
for i in range(H-2):
print("#","."*(W-2),"#",sep='')
print("#"*W)
print()
``` | output | 1 | 90,085 | 23 | 180,171 |
Provide a correct Python 3 solution for this coding contest problem.
Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm.
........#
........#
........#
........#
Constraints
* 3 ≤ H ≤ 300
* 3 ≤ W ≤ 300
Input
The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.
The input ends with two 0 (when both H and W are zero).
Output
For each dataset, print the frame made of '#' and '.'.
Print a blank line after each dataset.
Example
Input
3 4
5 6
3 3
0 0
Output
####
#..#
####
######
#....#
#....#
#....#
######
###
#.#
### | instruction | 0 | 90,086 | 23 | 180,172 |
"Correct Solution:
```
for i in range(100000):
h,w = map(int,input().split(" "))
if h + w == 0:
break
print("#"*w)
for j in range(h-2):
print("#" + "."*(w-2) + "#")
print("#"*w)
print("")
``` | output | 1 | 90,086 | 23 | 180,173 |
Provide a correct Python 3 solution for this coding contest problem.
Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm.
........#
........#
........#
........#
Constraints
* 3 ≤ H ≤ 300
* 3 ≤ W ≤ 300
Input
The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.
The input ends with two 0 (when both H and W are zero).
Output
For each dataset, print the frame made of '#' and '.'.
Print a blank line after each dataset.
Example
Input
3 4
5 6
3 3
0 0
Output
####
#..#
####
######
#....#
#....#
#....#
######
###
#.#
### | instruction | 0 | 90,087 | 23 | 180,174 |
"Correct Solution:
```
while True :
H,W=map(int,input().split())
if H==0 and W==0 :
break
print("#"*W)
for i in range (H-2):
print("{}{}{}".format("#",(".")*(W-2),"#"))
print("#"*W)
print()
``` | output | 1 | 90,087 | 23 | 180,175 |
Provide a correct Python 3 solution for this coding contest problem.
Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm.
........#
........#
........#
........#
Constraints
* 3 ≤ H ≤ 300
* 3 ≤ W ≤ 300
Input
The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.
The input ends with two 0 (when both H and W are zero).
Output
For each dataset, print the frame made of '#' and '.'.
Print a blank line after each dataset.
Example
Input
3 4
5 6
3 3
0 0
Output
####
#..#
####
######
#....#
#....#
#....#
######
###
#.#
### | instruction | 0 | 90,088 | 23 | 180,176 |
"Correct Solution:
```
while True:
H,W = map(int,input().split(' '))
if not(H or W):break
print('#'*W)
for h in range(H-2):
print(f'#{"."*(W-2)}#')
print('#'*W)
print()
``` | output | 1 | 90,088 | 23 | 180,177 |
Provide a correct Python 3 solution for this coding contest problem.
Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm.
........#
........#
........#
........#
Constraints
* 3 ≤ H ≤ 300
* 3 ≤ W ≤ 300
Input
The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.
The input ends with two 0 (when both H and W are zero).
Output
For each dataset, print the frame made of '#' and '.'.
Print a blank line after each dataset.
Example
Input
3 4
5 6
3 3
0 0
Output
####
#..#
####
######
#....#
#....#
#....#
######
###
#.#
### | instruction | 0 | 90,089 | 23 | 180,178 |
"Correct Solution:
```
while True:
h, w = [int(i) for i in input().split()]
if w == h == 0:
break
print("#" * w, end="")
print(("\n#" + "." * (w - 2) + "#") * (h - 2))
print("#" * w, end="\n\n")
``` | output | 1 | 90,089 | 23 | 180,179 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm.
........#
........#
........#
........#
Constraints
* 3 ≤ H ≤ 300
* 3 ≤ W ≤ 300
Input
The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.
The input ends with two 0 (when both H and W are zero).
Output
For each dataset, print the frame made of '#' and '.'.
Print a blank line after each dataset.
Example
Input
3 4
5 6
3 3
0 0
Output
####
#..#
####
######
#....#
#....#
#....#
######
###
#.#
###
Submitted Solution:
```
while True:
H,W = map(int,input().split())
if H==W==0:
break;
print("#"*W)
for i in range(0,H-2):
print("#"+"."*(W-2)+"#")
print("#"*W)
print()
``` | instruction | 0 | 90,090 | 23 | 180,180 |
Yes | output | 1 | 90,090 | 23 | 180,181 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm.
........#
........#
........#
........#
Constraints
* 3 ≤ H ≤ 300
* 3 ≤ W ≤ 300
Input
The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.
The input ends with two 0 (when both H and W are zero).
Output
For each dataset, print the frame made of '#' and '.'.
Print a blank line after each dataset.
Example
Input
3 4
5 6
3 3
0 0
Output
####
#..#
####
######
#....#
#....#
#....#
######
###
#.#
###
Submitted Solution:
```
while(1):
h,w = [int(i) for i in input().split()]
if h == 0 and w == 0:
break
print("#"*w)
for i in range(h-2):
print("#"+"."*(w-2)+"#")
print("#"*w)
print("")
``` | instruction | 0 | 90,091 | 23 | 180,182 |
Yes | output | 1 | 90,091 | 23 | 180,183 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm.
........#
........#
........#
........#
Constraints
* 3 ≤ H ≤ 300
* 3 ≤ W ≤ 300
Input
The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.
The input ends with two 0 (when both H and W are zero).
Output
For each dataset, print the frame made of '#' and '.'.
Print a blank line after each dataset.
Example
Input
3 4
5 6
3 3
0 0
Output
####
#..#
####
######
#....#
#....#
#....#
######
###
#.#
###
Submitted Solution:
```
while True:
h, w = map(int, input().split())
if h == w == 0: break
print('#' * w)
for _ in range(h - 2):
print('#' + '.'*(w-2) + '#')
print('#' * w)
print()
``` | instruction | 0 | 90,092 | 23 | 180,184 |
Yes | output | 1 | 90,092 | 23 | 180,185 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm.
........#
........#
........#
........#
Constraints
* 3 ≤ H ≤ 300
* 3 ≤ W ≤ 300
Input
The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.
The input ends with two 0 (when both H and W are zero).
Output
For each dataset, print the frame made of '#' and '.'.
Print a blank line after each dataset.
Example
Input
3 4
5 6
3 3
0 0
Output
####
#..#
####
######
#....#
#....#
#....#
######
###
#.#
###
Submitted Solution:
```
while True:
h, w = map(int, input().strip().split())
if h == w == 0: break
print('#'*w)
for i in range(h - 2):
print('#'+'.'*(w-2)+'#')
print('#'*w)
print()
``` | instruction | 0 | 90,093 | 23 | 180,186 |
Yes | output | 1 | 90,093 | 23 | 180,187 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm.
........#
........#
........#
........#
Constraints
* 3 ≤ H ≤ 300
* 3 ≤ W ≤ 300
Input
The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.
The input ends with two 0 (when both H and W are zero).
Output
For each dataset, print the frame made of '#' and '.'.
Print a blank line after each dataset.
Example
Input
3 4
5 6
3 3
0 0
Output
####
#..#
####
######
#....#
#....#
#....#
######
###
#.#
###
Submitted Solution:
```
while True:
a,b=map(int,input().split())
if a==0 and b==0:break
f=[[0 for i in range(a)]for j in range(b)]
for i in range(a):
for j in range(b):
if i==0 or i==a-1 or j==0 or j==b-1:
f[i][j]=1
for i in range(a):
for j in range(b):
if f[i][j]==1:
print('#')
else :
print('.')
print()
print()
``` | instruction | 0 | 90,094 | 23 | 180,188 |
No | output | 1 | 90,094 | 23 | 180,189 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm.
........#
........#
........#
........#
Constraints
* 3 ≤ H ≤ 300
* 3 ≤ W ≤ 300
Input
The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.
The input ends with two 0 (when both H and W are zero).
Output
For each dataset, print the frame made of '#' and '.'.
Print a blank line after each dataset.
Example
Input
3 4
5 6
3 3
0 0
Output
####
#..#
####
######
#....#
#....#
#....#
######
###
#.#
###
Submitted Solution:
```
while True:
H, W = [int(x) for x in input().split(" ")]
if H == W == 0:
break
for i in range(H):
if i == 0 or i == (H - 1):
print("#" * W)
else:
print("#" + "." * (W - 2) + "#")
print("\n")
``` | instruction | 0 | 90,095 | 23 | 180,190 |
No | output | 1 | 90,095 | 23 | 180,191 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm.
........#
........#
........#
........#
Constraints
* 3 ≤ H ≤ 300
* 3 ≤ W ≤ 300
Input
The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.
The input ends with two 0 (when both H and W are zero).
Output
For each dataset, print the frame made of '#' and '.'.
Print a blank line after each dataset.
Example
Input
3 4
5 6
3 3
0 0
Output
####
#..#
####
######
#....#
#....#
#....#
######
###
#.#
###
Submitted Solution:
```
while True:
a,b = map(int, input().split())
if a ==0 and b == 0:
break
for i in range(a):
if i ==0 or i == (a-1):
print("#", end = "")
print("#"*(a-2), end = "")
print("#")
else:
print("#"*b, end = "")
print()
print()
``` | instruction | 0 | 90,096 | 23 | 180,192 |
No | output | 1 | 90,096 | 23 | 180,193 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm.
........#
........#
........#
........#
Constraints
* 3 ≤ H ≤ 300
* 3 ≤ W ≤ 300
Input
The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.
The input ends with two 0 (when both H and W are zero).
Output
For each dataset, print the frame made of '#' and '.'.
Print a blank line after each dataset.
Example
Input
3 4
5 6
3 3
0 0
Output
####
#..#
####
######
#....#
#....#
#....#
######
###
#.#
###
Submitted Solution:
```
h,w = map(int,input().split())
print('#'*w)
print(('#' + '.'*(w-2) + '#\n')*(h-2),end ='')
print('#'*w + '\n')
``` | instruction | 0 | 90,097 | 23 | 180,194 |
No | output | 1 | 90,097 | 23 | 180,195 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n points on the plane. The polygon formed from all the n points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from 1 to n, in clockwise order.
We define the distance between two points p_1 = (x_1, y_1) and p_2 = (x_2, y_2) as their Manhattan distance: $$$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.$$$
Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as p_1, p_2, …, p_k (k ≥ 3), then the perimeter of the polygon is d(p_1, p_2) + d(p_2, p_3) + … + d(p_k, p_1).
For some parameter k, let's consider all the polygons that can be formed from the given set of points, having any k vertices, such that the polygon is not self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define f(k) to be the maximal perimeter.
Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures:
<image>
In the middle polygon, the order of points (p_1, p_3, p_2, p_4) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is (p_1, p_2, p_3, p_4), which is the left polygon.
Your task is to compute f(3), f(4), …, f(n). In other words, find the maximum possible perimeter for each possible number of points (i.e. 3 to n).
Input
The first line contains a single integer n (3 ≤ n ≤ 3⋅ 10^5) — the number of points.
Each of the next n lines contains two integers x_i and y_i (-10^8 ≤ x_i, y_i ≤ 10^8) — the coordinates of point p_i.
The set of points is guaranteed to be convex, all points are distinct, the points are ordered in clockwise order, and there will be no three collinear points.
Output
For each i (3≤ i≤ n), output f(i).
Examples
Input
4
2 4
4 3
3 0
1 3
Output
12 14
Input
3
0 0
0 2
2 0
Output
8
Note
In the first example, for f(3), we consider four possible polygons:
* (p_1, p_2, p_3), with perimeter 12.
* (p_1, p_2, p_4), with perimeter 8.
* (p_1, p_3, p_4), with perimeter 12.
* (p_2, p_3, p_4), with perimeter 12.
For f(4), there is only one option, taking all the given points. Its perimeter 14.
In the second example, there is only one possible polygon. Its perimeter is 8. | instruction | 0 | 90,114 | 23 | 180,228 |
Tags: dp, geometry
Correct Solution:
```
n=int(input())
tl=tr=bl=br=top=bot=left=right=-200000000
for i in range(n):
a,b=map(int,input().split())
top=max(top,b)
bot=max(bot,-b)
right=max(right,a)
left=max(left,-a)
tr=max(tr,a+b)
tl=max(tl,b-a)
br=max(br,a-b)
bl=max(bl,-a-b)
print(str(2*max(top+left+br,top+right+bl,bot+left+tr,bot+right+tl))+(n-3)*(" "+str(2*(top+bot+left+right))))
``` | output | 1 | 90,114 | 23 | 180,229 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n points on the plane. The polygon formed from all the n points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from 1 to n, in clockwise order.
We define the distance between two points p_1 = (x_1, y_1) and p_2 = (x_2, y_2) as their Manhattan distance: $$$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.$$$
Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as p_1, p_2, …, p_k (k ≥ 3), then the perimeter of the polygon is d(p_1, p_2) + d(p_2, p_3) + … + d(p_k, p_1).
For some parameter k, let's consider all the polygons that can be formed from the given set of points, having any k vertices, such that the polygon is not self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define f(k) to be the maximal perimeter.
Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures:
<image>
In the middle polygon, the order of points (p_1, p_3, p_2, p_4) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is (p_1, p_2, p_3, p_4), which is the left polygon.
Your task is to compute f(3), f(4), …, f(n). In other words, find the maximum possible perimeter for each possible number of points (i.e. 3 to n).
Input
The first line contains a single integer n (3 ≤ n ≤ 3⋅ 10^5) — the number of points.
Each of the next n lines contains two integers x_i and y_i (-10^8 ≤ x_i, y_i ≤ 10^8) — the coordinates of point p_i.
The set of points is guaranteed to be convex, all points are distinct, the points are ordered in clockwise order, and there will be no three collinear points.
Output
For each i (3≤ i≤ n), output f(i).
Examples
Input
4
2 4
4 3
3 0
1 3
Output
12 14
Input
3
0 0
0 2
2 0
Output
8
Note
In the first example, for f(3), we consider four possible polygons:
* (p_1, p_2, p_3), with perimeter 12.
* (p_1, p_2, p_4), with perimeter 8.
* (p_1, p_3, p_4), with perimeter 12.
* (p_2, p_3, p_4), with perimeter 12.
For f(4), there is only one option, taking all the given points. Its perimeter 14.
In the second example, there is only one possible polygon. Its perimeter is 8. | instruction | 0 | 90,115 | 23 | 180,230 |
Tags: dp, geometry
Correct Solution:
```
n = int(input())
north = -100000000
south = 100000000
east = -100000000
west = 100000000
ne = -200000000
nw = -200000000
se = -200000000
sw = -200000000
for i in range(n):
x,y = map(int,input().split())
north = max(north,y)
east = max(east,x)
south = min(south,y)
west = min(west,x)
ne = max(ne,x+y)
nw = max(nw,y-x)
se = max(se,x-y)
sw = max(sw,-1*x-y)
best = 2*(ne-south-west)
best = max(best,2*(nw-south+east))
best = max(best,2*(se+north-west))
best = max(best,2*(sw+north+east))
ans = str(best)
peri = 2*(north-south+east-west)
ans += (" "+str(peri))*(n-3)
print(ans)
``` | output | 1 | 90,115 | 23 | 180,231 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n points on the plane. The polygon formed from all the n points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from 1 to n, in clockwise order.
We define the distance between two points p_1 = (x_1, y_1) and p_2 = (x_2, y_2) as their Manhattan distance: $$$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.$$$
Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as p_1, p_2, …, p_k (k ≥ 3), then the perimeter of the polygon is d(p_1, p_2) + d(p_2, p_3) + … + d(p_k, p_1).
For some parameter k, let's consider all the polygons that can be formed from the given set of points, having any k vertices, such that the polygon is not self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define f(k) to be the maximal perimeter.
Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures:
<image>
In the middle polygon, the order of points (p_1, p_3, p_2, p_4) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is (p_1, p_2, p_3, p_4), which is the left polygon.
Your task is to compute f(3), f(4), …, f(n). In other words, find the maximum possible perimeter for each possible number of points (i.e. 3 to n).
Input
The first line contains a single integer n (3 ≤ n ≤ 3⋅ 10^5) — the number of points.
Each of the next n lines contains two integers x_i and y_i (-10^8 ≤ x_i, y_i ≤ 10^8) — the coordinates of point p_i.
The set of points is guaranteed to be convex, all points are distinct, the points are ordered in clockwise order, and there will be no three collinear points.
Output
For each i (3≤ i≤ n), output f(i).
Examples
Input
4
2 4
4 3
3 0
1 3
Output
12 14
Input
3
0 0
0 2
2 0
Output
8
Note
In the first example, for f(3), we consider four possible polygons:
* (p_1, p_2, p_3), with perimeter 12.
* (p_1, p_2, p_4), with perimeter 8.
* (p_1, p_3, p_4), with perimeter 12.
* (p_2, p_3, p_4), with perimeter 12.
For f(4), there is only one option, taking all the given points. Its perimeter 14.
In the second example, there is only one possible polygon. Its perimeter is 8. | instruction | 0 | 90,116 | 23 | 180,232 |
Tags: dp, geometry
Correct Solution:
```
import itertools
n = int(input())
xys = [tuple(map(int, input().split())) for _ in range(n)]
h = min(xy[0] for xy in xys)
j = min(xy[1] for xy in xys)
k = max(xy[1] for xy in xys)
l = max(xy[0] for xy in xys)
ans3 = max(
max(
abs(x - h) + abs(y - j),
abs(x - l) + abs(y - j),
abs(x - h) + abs(y - k),
abs(x - l) + abs(y - k),
) for x, y in xys)
ans = sum(abs(x1 - x2) + abs(y1 - y2) for (x1, y1), (x2, y2) in zip(xys, [*xys[1:], xys[0]]))
print(' '.join(itertools.chain((str(ans3 * 2),), itertools.repeat(str(ans), n - 3))))
``` | output | 1 | 90,116 | 23 | 180,233 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n points on the plane. The polygon formed from all the n points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from 1 to n, in clockwise order.
We define the distance between two points p_1 = (x_1, y_1) and p_2 = (x_2, y_2) as their Manhattan distance: $$$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.$$$
Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as p_1, p_2, …, p_k (k ≥ 3), then the perimeter of the polygon is d(p_1, p_2) + d(p_2, p_3) + … + d(p_k, p_1).
For some parameter k, let's consider all the polygons that can be formed from the given set of points, having any k vertices, such that the polygon is not self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define f(k) to be the maximal perimeter.
Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures:
<image>
In the middle polygon, the order of points (p_1, p_3, p_2, p_4) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is (p_1, p_2, p_3, p_4), which is the left polygon.
Your task is to compute f(3), f(4), …, f(n). In other words, find the maximum possible perimeter for each possible number of points (i.e. 3 to n).
Input
The first line contains a single integer n (3 ≤ n ≤ 3⋅ 10^5) — the number of points.
Each of the next n lines contains two integers x_i and y_i (-10^8 ≤ x_i, y_i ≤ 10^8) — the coordinates of point p_i.
The set of points is guaranteed to be convex, all points are distinct, the points are ordered in clockwise order, and there will be no three collinear points.
Output
For each i (3≤ i≤ n), output f(i).
Examples
Input
4
2 4
4 3
3 0
1 3
Output
12 14
Input
3
0 0
0 2
2 0
Output
8
Note
In the first example, for f(3), we consider four possible polygons:
* (p_1, p_2, p_3), with perimeter 12.
* (p_1, p_2, p_4), with perimeter 8.
* (p_1, p_3, p_4), with perimeter 12.
* (p_2, p_3, p_4), with perimeter 12.
For f(4), there is only one option, taking all the given points. Its perimeter 14.
In the second example, there is only one possible polygon. Its perimeter is 8. | instruction | 0 | 90,117 | 23 | 180,234 |
Tags: dp, geometry
Correct Solution:
```
from collections import namedtuple
import sys
XY = namedtuple('XY', 'x y')
n = int(input())
pg = [XY(*[int(w) for w in input().split()]) for _ in range(n)]
minx = min(p.x for p in pg)
miny = min(p.y for p in pg)
maxx = max(p.x for p in pg)
maxy = max(p.y for p in pg)
p4 = 2 * ((maxx - minx) + (maxy - miny))
p3 = p4 - 2 * min([min(p.x - minx, maxx - p.x) + min(p.y - miny, maxy - p.y) for p in pg])
print(p3, *([p4] * (n-3)))
``` | output | 1 | 90,117 | 23 | 180,235 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n points on the plane. The polygon formed from all the n points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from 1 to n, in clockwise order.
We define the distance between two points p_1 = (x_1, y_1) and p_2 = (x_2, y_2) as their Manhattan distance: $$$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.$$$
Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as p_1, p_2, …, p_k (k ≥ 3), then the perimeter of the polygon is d(p_1, p_2) + d(p_2, p_3) + … + d(p_k, p_1).
For some parameter k, let's consider all the polygons that can be formed from the given set of points, having any k vertices, such that the polygon is not self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define f(k) to be the maximal perimeter.
Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures:
<image>
In the middle polygon, the order of points (p_1, p_3, p_2, p_4) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is (p_1, p_2, p_3, p_4), which is the left polygon.
Your task is to compute f(3), f(4), …, f(n). In other words, find the maximum possible perimeter for each possible number of points (i.e. 3 to n).
Input
The first line contains a single integer n (3 ≤ n ≤ 3⋅ 10^5) — the number of points.
Each of the next n lines contains two integers x_i and y_i (-10^8 ≤ x_i, y_i ≤ 10^8) — the coordinates of point p_i.
The set of points is guaranteed to be convex, all points are distinct, the points are ordered in clockwise order, and there will be no three collinear points.
Output
For each i (3≤ i≤ n), output f(i).
Examples
Input
4
2 4
4 3
3 0
1 3
Output
12 14
Input
3
0 0
0 2
2 0
Output
8
Note
In the first example, for f(3), we consider four possible polygons:
* (p_1, p_2, p_3), with perimeter 12.
* (p_1, p_2, p_4), with perimeter 8.
* (p_1, p_3, p_4), with perimeter 12.
* (p_2, p_3, p_4), with perimeter 12.
For f(4), there is only one option, taking all the given points. Its perimeter 14.
In the second example, there is only one possible polygon. Its perimeter is 8.
Submitted Solution:
```
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
n = int(input())
pts = [Point(*map(int, input().split())) for _ in range(n)]
min_x_idx = min(range(n), key=lambda i : pts[i].x)
max_x_idx = max(range(n), key=lambda i : pts[i].x)
min_y_idx = min(range(n), key=lambda i : pts[i].y)
max_y_idx = max(range(n), key=lambda i : pts[i].y)
extremities = sorted([(min_x_idx, 'x'),
(min_y_idx, 'y'),
(max_x_idx, 'x'),
(max_y_idx, 'y')])
# print(extremities)
# print(*[tuple(pts[i]) for i, _ in extremities])
loop_extremities = extremities + extremities
def interpolate_corner(pts, shift_x, shift_y, idx1, idx2):
i = idx1
max_dist = 0
while i != idx2:
# print(idx1, i, idx2)
max_dist = max(abs(pts[i].x - shift_x) + abs(pts[i].y - shift_y), max_dist)
# print(abs(pts[i].x - shift_x) , abs(pts[i].y - shift_y))
i = (i + 1) % len(pts)
return 2 * max_dist
quad_perimeter = 2 * ( max(pt.x for pt in pts) + max(pt.y for pt in pts) - min(pt.x for pt in pts) - min(pt.y for pt in pts) )
tri_perimeter = -1
if n >= 4:
for i in range(4):
(to_use_1, u1_label), (to_use_2, u2_label) = loop_extremities[i:i+2]
(to_merge_1, m1_label), (to_merge_2, m2_label) = loop_extremities[i+2:i+4]
if u1_label == 'x':
shift_x = pts[to_use_1].x
shift_y = pts[to_use_2].y
else:
shift_x = pts[to_use_2].x
shift_y = pts[to_use_1].y
tri_perimeter = max(interpolate_corner(pts, shift_x, shift_y, to_merge_1, to_merge_2), tri_perimeter)
# print(*[tuple(pts[i]) for i, _ in loop_extremities[i:i+4]])
# print(tri_perimeter)
else:
tri_perimeter = quad_perimeter
print(tri_perimeter, end=' ')
print(*(quad_perimeter for _ in range(n-3)))
``` | instruction | 0 | 90,118 | 23 | 180,236 |
No | output | 1 | 90,118 | 23 | 180,237 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n points on the plane. The polygon formed from all the n points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from 1 to n, in clockwise order.
We define the distance between two points p_1 = (x_1, y_1) and p_2 = (x_2, y_2) as their Manhattan distance: $$$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.$$$
Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as p_1, p_2, …, p_k (k ≥ 3), then the perimeter of the polygon is d(p_1, p_2) + d(p_2, p_3) + … + d(p_k, p_1).
For some parameter k, let's consider all the polygons that can be formed from the given set of points, having any k vertices, such that the polygon is not self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define f(k) to be the maximal perimeter.
Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures:
<image>
In the middle polygon, the order of points (p_1, p_3, p_2, p_4) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is (p_1, p_2, p_3, p_4), which is the left polygon.
Your task is to compute f(3), f(4), …, f(n). In other words, find the maximum possible perimeter for each possible number of points (i.e. 3 to n).
Input
The first line contains a single integer n (3 ≤ n ≤ 3⋅ 10^5) — the number of points.
Each of the next n lines contains two integers x_i and y_i (-10^8 ≤ x_i, y_i ≤ 10^8) — the coordinates of point p_i.
The set of points is guaranteed to be convex, all points are distinct, the points are ordered in clockwise order, and there will be no three collinear points.
Output
For each i (3≤ i≤ n), output f(i).
Examples
Input
4
2 4
4 3
3 0
1 3
Output
12 14
Input
3
0 0
0 2
2 0
Output
8
Note
In the first example, for f(3), we consider four possible polygons:
* (p_1, p_2, p_3), with perimeter 12.
* (p_1, p_2, p_4), with perimeter 8.
* (p_1, p_3, p_4), with perimeter 12.
* (p_2, p_3, p_4), with perimeter 12.
For f(4), there is only one option, taking all the given points. Its perimeter 14.
In the second example, there is only one possible polygon. Its perimeter is 8.
Submitted Solution:
```
n=int(input())
#n,m=map(int,input().split())
xy=[]
for i in range(n):
x,y=map(int,input().split())
xy.append([x,y])
kr=[0]*4
maxx=-1000000000
minx=1000000000
maxy=-1000000000
miny=1000000000
for i in range(n):
x=xy[i][0]
y=xy[i][1]
if x<=xy[kr[3]][0]: kr[3]=i
if x>=xy[kr[1]][0]: kr[1]=i
if y<=xy[kr[2]][1]: kr[2]=i
if y>=xy[kr[0]][1]: kr[0]=i
def diss(xy,i1,i2):
return abs(xy[i1][0]-xy[i2][0])+abs(xy[i1][1]-xy[i2][1])
a1=diss(xy,kr[0],kr[1])+diss(xy,kr[1],kr[2])+diss(xy,kr[2],kr[0])
a2=diss(xy,kr[0],kr[1])+diss(xy,kr[1],kr[3])+diss(xy,kr[3],kr[0])
a3=diss(xy,kr[0],kr[2])+diss(xy,kr[2],kr[3])+diss(xy,kr[3],kr[0])
a4=diss(xy,kr[1],kr[2])+diss(xy,kr[2],kr[3])+diss(xy,kr[3],kr[1])
print(max(a1,a2,a3,a4),end=' ')
ans=diss(xy,kr[0],kr[1])+diss(xy,kr[1],kr[2])+diss(xy,kr[2],kr[3])+diss(xy,kr[3],kr[0])
for i in range(n-3):
print(ans,end=' ')
``` | instruction | 0 | 90,119 | 23 | 180,238 |
No | output | 1 | 90,119 | 23 | 180,239 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n points on the plane. The polygon formed from all the n points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from 1 to n, in clockwise order.
We define the distance between two points p_1 = (x_1, y_1) and p_2 = (x_2, y_2) as their Manhattan distance: $$$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.$$$
Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as p_1, p_2, …, p_k (k ≥ 3), then the perimeter of the polygon is d(p_1, p_2) + d(p_2, p_3) + … + d(p_k, p_1).
For some parameter k, let's consider all the polygons that can be formed from the given set of points, having any k vertices, such that the polygon is not self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define f(k) to be the maximal perimeter.
Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures:
<image>
In the middle polygon, the order of points (p_1, p_3, p_2, p_4) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is (p_1, p_2, p_3, p_4), which is the left polygon.
Your task is to compute f(3), f(4), …, f(n). In other words, find the maximum possible perimeter for each possible number of points (i.e. 3 to n).
Input
The first line contains a single integer n (3 ≤ n ≤ 3⋅ 10^5) — the number of points.
Each of the next n lines contains two integers x_i and y_i (-10^8 ≤ x_i, y_i ≤ 10^8) — the coordinates of point p_i.
The set of points is guaranteed to be convex, all points are distinct, the points are ordered in clockwise order, and there will be no three collinear points.
Output
For each i (3≤ i≤ n), output f(i).
Examples
Input
4
2 4
4 3
3 0
1 3
Output
12 14
Input
3
0 0
0 2
2 0
Output
8
Note
In the first example, for f(3), we consider four possible polygons:
* (p_1, p_2, p_3), with perimeter 12.
* (p_1, p_2, p_4), with perimeter 8.
* (p_1, p_3, p_4), with perimeter 12.
* (p_2, p_3, p_4), with perimeter 12.
For f(4), there is only one option, taking all the given points. Its perimeter 14.
In the second example, there is only one possible polygon. Its perimeter is 8.
Submitted Solution:
```
from itertools import combinations
n = int(input())
dots = [list(map(int, input().split())) for i in range(n)]
minx = min([x for x, y in dots])
maxx = max([x for x, y in dots])
miny = min([y for x, y in dots])
maxy = max([y for x, y in dots])
ans_gt3 = 2 * (maxx - minx) + 2 * (maxy - miny)
def get_perimeter(a, b, c):
ax, ay = a
bx, by = b
cx, cy = c
xmin, _, xmax = list(sorted([ax, bx, cx]))
ymin, _, ymax = list(sorted([ay, by, cy]))
return 2 * (xmax - xmin) + 2 * (ymax - ymin)
a1 = get_perimeter((minx, min([y for x, y in dots if x == minx])), (max([x for x, y in dots if y == maxy]), maxy), (max([x for x, y in dots if y == miny]), miny))
a2 = get_perimeter((max([x for x, y in dots if y == maxy]), maxy), (maxx, min([y for x, y in dots if x == maxx])), (minx, min([y for x, y in dots if x == minx])))
a3 = get_perimeter((maxx, min([y for x, y in dots if x == maxx])), (min([x for x, y in dots if y == miny]), miny), (min([x for x, y in dots if y == maxy]), maxy))
a4 = get_perimeter((max([x for x, y in dots if y == miny]), miny), (minx, max([y for x, y in dots if x == minx])), (maxx, max([y for x, y in dots if x == maxx])))
ans_3 = max(a1, a2, a3, a4)
if n == 3:
print(ans_3)
else:
ans = [ans_3] + ([ans_gt3] * (n - 3))
ans = list(map(str, ans))
print(' '.join(ans))
``` | instruction | 0 | 90,120 | 23 | 180,240 |
No | output | 1 | 90,120 | 23 | 180,241 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n points on the plane. The polygon formed from all the n points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from 1 to n, in clockwise order.
We define the distance between two points p_1 = (x_1, y_1) and p_2 = (x_2, y_2) as their Manhattan distance: $$$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.$$$
Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as p_1, p_2, …, p_k (k ≥ 3), then the perimeter of the polygon is d(p_1, p_2) + d(p_2, p_3) + … + d(p_k, p_1).
For some parameter k, let's consider all the polygons that can be formed from the given set of points, having any k vertices, such that the polygon is not self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define f(k) to be the maximal perimeter.
Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures:
<image>
In the middle polygon, the order of points (p_1, p_3, p_2, p_4) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is (p_1, p_2, p_3, p_4), which is the left polygon.
Your task is to compute f(3), f(4), …, f(n). In other words, find the maximum possible perimeter for each possible number of points (i.e. 3 to n).
Input
The first line contains a single integer n (3 ≤ n ≤ 3⋅ 10^5) — the number of points.
Each of the next n lines contains two integers x_i and y_i (-10^8 ≤ x_i, y_i ≤ 10^8) — the coordinates of point p_i.
The set of points is guaranteed to be convex, all points are distinct, the points are ordered in clockwise order, and there will be no three collinear points.
Output
For each i (3≤ i≤ n), output f(i).
Examples
Input
4
2 4
4 3
3 0
1 3
Output
12 14
Input
3
0 0
0 2
2 0
Output
8
Note
In the first example, for f(3), we consider four possible polygons:
* (p_1, p_2, p_3), with perimeter 12.
* (p_1, p_2, p_4), with perimeter 8.
* (p_1, p_3, p_4), with perimeter 12.
* (p_2, p_3, p_4), with perimeter 12.
For f(4), there is only one option, taking all the given points. Its perimeter 14.
In the second example, there is only one possible polygon. Its perimeter is 8.
Submitted Solution:
```
from itertools import combinations
n = int(input())
dots = [list(map(int, input().split())) for i in range(n)]
minx = min([x for x, y in dots])
maxx = max([x for x, y in dots])
miny = min([y for x, y in dots])
maxy = max([y for x, y in dots])
lx, ly = dots[0]
for x, y in dots:
if x < lx:
lx, ly = x, y
rx, ry = dots[0]
for x, y in dots:
if x > rx:
rx, ry = x, y
ux, uy = dots[0]
for x, y in dots:
if y > uy:
ux, uy = x, y
dx, dy = dots[0]
for x, y in dots:
if y < dy:
dx, dy = x, y
ans_gt3 = 2 * (rx - lx) + 2 * (uy - dy)
def get_perimeter(a, b, c):
ax, ay = a
bx, by = b
cx, cy = c
return abs(ax - bx) + abs(ay - by) + \
abs(bx - cx) + abs(by - cy) + \
abs(cx - ax) + abs(cy - ay)
a1 = get_perimeter((lx, ly), (max([x for x, y in dots if y == maxy]), maxy), (max([x for x, y in dots if y == miny]), miny))
a2 = get_perimeter((ux, uy), (maxx, min([y for x, y in dots if x == maxx])), (minx, min([y for x, y in dots if x == minx])))
a3 = get_perimeter((rx, ry), (min([x for x, y in dots if y == miny]), miny), (min([x for x, y in dots if y == maxy]), maxy))
a4 = get_perimeter((dx, dy), (minx, max([y for x, y in dots if x == minx])), (maxx, max([y for x, y in dots if x == maxx])))
ans_3 = max(a1, a2, a3, a4)
if n == 3:
print(ans_3)
else:
ans = [ans_3] + ([ans_gt3] * (n - 3))
ans = list(map(str, ans))
print(' '.join(ans))
``` | instruction | 0 | 90,121 | 23 | 180,242 |
No | output | 1 | 90,121 | 23 | 180,243 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version, n ≤ 50 000.
There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even.
You'd like to remove all n points using a sequence of n/2 snaps. In one snap, you can remove any two points a and b that have not been removed yet and form a perfectly balanced pair. A pair of points a and b is perfectly balanced if no other point c (that has not been removed yet) lies within the axis-aligned minimum bounding box of points a and b.
Formally, point c lies within the axis-aligned minimum bounding box of points a and b if and only if min(x_a, x_b) ≤ x_c ≤ max(x_a, x_b), min(y_a, y_b) ≤ y_c ≤ max(y_a, y_b), and min(z_a, z_b) ≤ z_c ≤ max(z_a, z_b). Note that the bounding box might be degenerate.
Find a way to remove all points in n/2 snaps.
Input
The first line contains a single integer n (2 ≤ n ≤ 50 000; n is even), denoting the number of points.
Each of the next n lines contains three integers x_i, y_i, z_i (-10^8 ≤ x_i, y_i, z_i ≤ 10^8), denoting the coordinates of the i-th point.
No two points coincide.
Output
Output n/2 pairs of integers a_i, b_i (1 ≤ a_i, b_i ≤ n), denoting the indices of points removed on snap i. Every integer between 1 and n, inclusive, must appear in your output exactly once.
We can show that it is always possible to remove all points. If there are many solutions, output any of them.
Examples
Input
6
3 1 0
0 3 0
2 2 0
1 0 0
1 3 0
0 1 0
Output
3 6
5 1
2 4
Input
8
0 1 1
1 0 1
1 1 0
1 1 1
2 2 2
3 2 2
2 3 2
2 2 3
Output
4 5
1 6
2 7
3 8
Note
In the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on z = 0 plane). Note that order of removing matters: for example, points 5 and 1 don't form a perfectly balanced pair initially, but they do after point 3 is removed.
<image> | instruction | 0 | 90,226 | 23 | 180,452 |
Tags: binary search, constructive algorithms, divide and conquer, greedy, implementation, sortings
Correct Solution:
```
def main():
n = int(input())
lkz = {}
lky = {}
for i in range(n):
px, py, pz = map(int, input().split())
if pz not in lkz:
lkz[pz] = set()
lkz[pz].add(py)
lky[(pz, py)] = [(pz, py, px, i + 1)]
else:
lkz[pz].add(py)
if (pz, py) not in lky:
lky[(pz, py)] = [(pz, py, px, i + 1)]
else:
lky[(pz, py)].append((pz, py, px, i + 1))
ans = []
final_list = []
for pz in lkz:
curr_list = []
for py in lkz[pz]:
if len(lky[(pz, py)]) > 1:
lky[(pz, py)].sort()
for i in range(0, len(lky[pz, py]) // 2):
p1 = lky[(pz, py)][2 *i]
p2 = lky[(pz, py)][2 * i + 1]
ans.append((p1[3], p2[3]))
if len(lky[(pz, py)]) % 2 == 1:
curr_list.append(lky[(pz, py)][-1])
if len(curr_list) > 1:
curr_list.sort()
for i in range(0, len(curr_list) // 2):
ans.append((curr_list[2 * i][3], curr_list[2 * i + 1][3]))
if len(curr_list) % 2 == 1:
final_list.append(curr_list[-1])
final_list.sort()
for i in range(0, len(final_list) // 2):
ans.append((final_list[2 * i][3], final_list[2 * i + 1][3]))
for pair in ans:
print(*pair)
if __name__ == '__main__':
main()
``` | output | 1 | 90,226 | 23 | 180,453 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version, n ≤ 50 000.
There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even.
You'd like to remove all n points using a sequence of n/2 snaps. In one snap, you can remove any two points a and b that have not been removed yet and form a perfectly balanced pair. A pair of points a and b is perfectly balanced if no other point c (that has not been removed yet) lies within the axis-aligned minimum bounding box of points a and b.
Formally, point c lies within the axis-aligned minimum bounding box of points a and b if and only if min(x_a, x_b) ≤ x_c ≤ max(x_a, x_b), min(y_a, y_b) ≤ y_c ≤ max(y_a, y_b), and min(z_a, z_b) ≤ z_c ≤ max(z_a, z_b). Note that the bounding box might be degenerate.
Find a way to remove all points in n/2 snaps.
Input
The first line contains a single integer n (2 ≤ n ≤ 50 000; n is even), denoting the number of points.
Each of the next n lines contains three integers x_i, y_i, z_i (-10^8 ≤ x_i, y_i, z_i ≤ 10^8), denoting the coordinates of the i-th point.
No two points coincide.
Output
Output n/2 pairs of integers a_i, b_i (1 ≤ a_i, b_i ≤ n), denoting the indices of points removed on snap i. Every integer between 1 and n, inclusive, must appear in your output exactly once.
We can show that it is always possible to remove all points. If there are many solutions, output any of them.
Examples
Input
6
3 1 0
0 3 0
2 2 0
1 0 0
1 3 0
0 1 0
Output
3 6
5 1
2 4
Input
8
0 1 1
1 0 1
1 1 0
1 1 1
2 2 2
3 2 2
2 3 2
2 2 3
Output
4 5
1 6
2 7
3 8
Note
In the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on z = 0 plane). Note that order of removing matters: for example, points 5 and 1 don't form a perfectly balanced pair initially, but they do after point 3 is removed.
<image> | instruction | 0 | 90,227 | 23 | 180,454 |
Tags: binary search, constructive algorithms, divide and conquer, greedy, implementation, sortings
Correct Solution:
```
from bisect import bisect
def solve(points):
def it():
Z = sorted(set(z for x,y,z in points))
z_bin = [[] for _ in range(len(Z))]
for i,(x,y,z) in enumerate(points):
z_bin[bisect(Z,z)-1].append(i)
last_z = -1
for zi,plane in enumerate(z_bin):
Y = sorted(set(points[i][1] for i in plane))
y_bin = [[] for _ in range(len(Y))]
for i in plane:
x,y,z = points[i]
y_bin[bisect(Y,y)-1].append(i)
last_y = -1
for yi,line in enumerate(y_bin):
line.sort(key=lambda i:points[i][0])
m = iter(line)
for a,b in zip(m,m):
yield a,b
if len(line) % 2:
if last_y < 0:
last_y = line[-1]
else:
yield last_y,line[-1]
last_y = -1
if last_y >= 0:
if last_z < 0:
last_z = last_y
else:
yield last_z,last_y
last_z = -1
return it()
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
if __name__ == '__main__':
N = int(readline())
m = map(int,read().split())
res = solve(tuple(zip(m,m,m)))
print('\n'.join(f'{a+1} {b+1}' for a,b in res))
``` | output | 1 | 90,227 | 23 | 180,455 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version, n ≤ 50 000.
There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even.
You'd like to remove all n points using a sequence of n/2 snaps. In one snap, you can remove any two points a and b that have not been removed yet and form a perfectly balanced pair. A pair of points a and b is perfectly balanced if no other point c (that has not been removed yet) lies within the axis-aligned minimum bounding box of points a and b.
Formally, point c lies within the axis-aligned minimum bounding box of points a and b if and only if min(x_a, x_b) ≤ x_c ≤ max(x_a, x_b), min(y_a, y_b) ≤ y_c ≤ max(y_a, y_b), and min(z_a, z_b) ≤ z_c ≤ max(z_a, z_b). Note that the bounding box might be degenerate.
Find a way to remove all points in n/2 snaps.
Input
The first line contains a single integer n (2 ≤ n ≤ 50 000; n is even), denoting the number of points.
Each of the next n lines contains three integers x_i, y_i, z_i (-10^8 ≤ x_i, y_i, z_i ≤ 10^8), denoting the coordinates of the i-th point.
No two points coincide.
Output
Output n/2 pairs of integers a_i, b_i (1 ≤ a_i, b_i ≤ n), denoting the indices of points removed on snap i. Every integer between 1 and n, inclusive, must appear in your output exactly once.
We can show that it is always possible to remove all points. If there are many solutions, output any of them.
Examples
Input
6
3 1 0
0 3 0
2 2 0
1 0 0
1 3 0
0 1 0
Output
3 6
5 1
2 4
Input
8
0 1 1
1 0 1
1 1 0
1 1 1
2 2 2
3 2 2
2 3 2
2 2 3
Output
4 5
1 6
2 7
3 8
Note
In the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on z = 0 plane). Note that order of removing matters: for example, points 5 and 1 don't form a perfectly balanced pair initially, but they do after point 3 is removed.
<image> | instruction | 0 | 90,228 | 23 | 180,456 |
Tags: binary search, constructive algorithms, divide and conquer, greedy, implementation, sortings
Correct Solution:
```
import sys
from collections import defaultdict
readline = sys.stdin.readline
N = int(readline())
XYZ = [tuple(map(int, readline().split())) for _ in range(N) ]
XYZI = [(x, y, z, i) for i, (x, y, z) in enumerate(XYZ, 1)]
XYZI.sort()
X, Y, Z, IDX = map(list, zip(*XYZI))
Di = defaultdict(list)
for i in range(N):
x, y, z, idx = X[i], Y[i], Z[i], IDX[i]
Di[x].append((y, z, idx))
Ans = []
Ama = []
for L in Di.values():
D2 = defaultdict(int)
for y, _, _ in L:
D2[y] += 1
pre = None
st = None
for y, z, i in L:
if st is None and D2[y] == 1:
if pre is not None:
Ans.append((pre, i))
pre = None
else:
pre = i
else:
if st is not None:
Ans.append((st, i))
st = None
else:
st = i
D2[y] -= 1
if st:
Ama.append(st)
if pre:
Ama.append(pre)
Le = len(Ama)
for i in range(Le//2):
Ans.append((Ama[2*i], Ama[2*i+1]))
for a in Ans:
sys.stdout.write('{} {}\n'.format(*a))
``` | output | 1 | 90,228 | 23 | 180,457 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version, n ≤ 50 000.
There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even.
You'd like to remove all n points using a sequence of n/2 snaps. In one snap, you can remove any two points a and b that have not been removed yet and form a perfectly balanced pair. A pair of points a and b is perfectly balanced if no other point c (that has not been removed yet) lies within the axis-aligned minimum bounding box of points a and b.
Formally, point c lies within the axis-aligned minimum bounding box of points a and b if and only if min(x_a, x_b) ≤ x_c ≤ max(x_a, x_b), min(y_a, y_b) ≤ y_c ≤ max(y_a, y_b), and min(z_a, z_b) ≤ z_c ≤ max(z_a, z_b). Note that the bounding box might be degenerate.
Find a way to remove all points in n/2 snaps.
Input
The first line contains a single integer n (2 ≤ n ≤ 50 000; n is even), denoting the number of points.
Each of the next n lines contains three integers x_i, y_i, z_i (-10^8 ≤ x_i, y_i, z_i ≤ 10^8), denoting the coordinates of the i-th point.
No two points coincide.
Output
Output n/2 pairs of integers a_i, b_i (1 ≤ a_i, b_i ≤ n), denoting the indices of points removed on snap i. Every integer between 1 and n, inclusive, must appear in your output exactly once.
We can show that it is always possible to remove all points. If there are many solutions, output any of them.
Examples
Input
6
3 1 0
0 3 0
2 2 0
1 0 0
1 3 0
0 1 0
Output
3 6
5 1
2 4
Input
8
0 1 1
1 0 1
1 1 0
1 1 1
2 2 2
3 2 2
2 3 2
2 2 3
Output
4 5
1 6
2 7
3 8
Note
In the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on z = 0 plane). Note that order of removing matters: for example, points 5 and 1 don't form a perfectly balanced pair initially, but they do after point 3 is removed.
<image> | instruction | 0 | 90,229 | 23 | 180,458 |
Tags: binary search, constructive algorithms, divide and conquer, greedy, implementation, sortings
Correct Solution:
```
from collections import defaultdict
def filterOut(ans,removed,mapp): # filters adjacent pairs in map values. same line
# mapp is like {(x,y):[[z1,idx1],[z2,idx2],...]}
for v in mapp.values():
arr=list(v)
n=len(arr)
arr.sort() # sort by 0th index asc
i=0
while i+1<n:
idx1,idx2=arr[i][1],arr[i+1][1]
ans.append([idx1,idx2])
removed[idx1]=removed[idx2]=True
i+=2
return
def filterOut2(ans,removed,mapp): # filters adjacent pairs in map values. same plane
# mapp is like {x:[[y1,z1,idx1],[y2,z2,idx2],...]}
for v in mapp.values():
arr=list(v)
n=len(arr)
arr.sort() # sort by 0th index asc, then 1st index asc
i=0
while i+1<n:
idx1,idx2=arr[i][2],arr[i+1][2]
ans.append([idx1,idx2])
removed[idx1]=removed[idx2]=True
i+=2
return
def main():
n=int(input())
coords=[] # [x,y,z,i]
for i in range(1,n+1):
x,y,z=readIntArr()
coords.append([x,y,z,i])
ans=[]
removed=[False for _ in range(n+1)]
# first identify points on the same lines
# same (x,y)
xyMap=defaultdict(lambda:[]) # {(x,y):[[z1,idx1],[z2,idx2],...]}
for i in range(n):
x,y,z,idx=coords[i]
xyMap[(x,y)].append([z,idx])
filterOut(ans,removed,xyMap)
#update coords and n
coords2=[]
for i in range(n):
if not removed[coords[i][3]]:
coords2.append(coords[i])
coords=coords2
n=len(coords)
# same (y,z)
yzMap=defaultdict(lambda:[])
for i in range(n):
x,y,z,idx=coords[i]
yzMap[(y,z)].append([x,idx])
filterOut(ans,removed,yzMap)
#update coords and n
coords2=[]
for i in range(n):
if not removed[coords[i][3]]:
coords2.append(coords[i])
coords=coords2
n=len(coords)
# same (z,x)
zxMap=defaultdict(lambda:[])
for i in range(n):
x,y,z,idx=coords[i]
zxMap[(z,x)].append([y,idx])
filterOut(ans,removed,zxMap)
#update coords and n
coords2=[]
for i in range(n):
if not removed[coords[i][3]]:
coords2.append(coords[i])
coords=coords2
n=len(coords)
# first identify points on the same planes
# same x
xMap=defaultdict(lambda:[]) # {x:[[y1,z1,idx1],[y2,z2,idx2],...]}
for i in range(n):
x,y,z,idx=coords[i]
xMap[x].append([y,z,idx])
filterOut2(ans,removed,xMap)
#update coords and n
coords2=[]
for i in range(n):
if not removed[coords[i][3]]:
coords2.append(coords[i])
coords=coords2
n=len(coords)
# same y
yMap=defaultdict(lambda:[])
for i in range(n):
x,y,z,idx=coords[i]
yMap[y].append([x,z,idx])
filterOut2(ans,removed,yMap)
#update coords and n
coords2=[]
for i in range(n):
if not removed[coords[i][3]]:
coords2.append(coords[i])
coords=coords2
n=len(coords)
# same z
zMap=defaultdict(lambda:[])
for i in range(n):
x,y,z,idx=coords[i]
zMap[x].append([y,z,idx])
filterOut2(ans,removed,zMap)
#update coords and n
coords2=[]
for i in range(n):
if not removed[coords[i][3]]:
coords2.append(coords[i])
coords=coords2
n=len(coords)
# remaining coordinates that don't share x,y,z
coords.sort() # sort by x,y,z asc
for i in range(0,n,2):
ans.append([coords[i][3],coords[i+1][3]])
multiLineArrayOfArraysPrint(ans)
return
import sys
# input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(i,j):
print('? {} {}'.format(i,j))
sys.stdout.flush()
return int(input())
def answerInteractive(ans):
print('! {}'.format(' '.join([str(x) for x in ans])))
sys.stdout.flush()
inf=float('inf')
MOD=10**9+7
# MOD=998244353
for _abc in range(1):
main()
``` | output | 1 | 90,229 | 23 | 180,459 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version, n ≤ 50 000.
There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even.
You'd like to remove all n points using a sequence of n/2 snaps. In one snap, you can remove any two points a and b that have not been removed yet and form a perfectly balanced pair. A pair of points a and b is perfectly balanced if no other point c (that has not been removed yet) lies within the axis-aligned minimum bounding box of points a and b.
Formally, point c lies within the axis-aligned minimum bounding box of points a and b if and only if min(x_a, x_b) ≤ x_c ≤ max(x_a, x_b), min(y_a, y_b) ≤ y_c ≤ max(y_a, y_b), and min(z_a, z_b) ≤ z_c ≤ max(z_a, z_b). Note that the bounding box might be degenerate.
Find a way to remove all points in n/2 snaps.
Input
The first line contains a single integer n (2 ≤ n ≤ 50 000; n is even), denoting the number of points.
Each of the next n lines contains three integers x_i, y_i, z_i (-10^8 ≤ x_i, y_i, z_i ≤ 10^8), denoting the coordinates of the i-th point.
No two points coincide.
Output
Output n/2 pairs of integers a_i, b_i (1 ≤ a_i, b_i ≤ n), denoting the indices of points removed on snap i. Every integer between 1 and n, inclusive, must appear in your output exactly once.
We can show that it is always possible to remove all points. If there are many solutions, output any of them.
Examples
Input
6
3 1 0
0 3 0
2 2 0
1 0 0
1 3 0
0 1 0
Output
3 6
5 1
2 4
Input
8
0 1 1
1 0 1
1 1 0
1 1 1
2 2 2
3 2 2
2 3 2
2 2 3
Output
4 5
1 6
2 7
3 8
Note
In the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on z = 0 plane). Note that order of removing matters: for example, points 5 and 1 don't form a perfectly balanced pair initially, but they do after point 3 is removed.
<image> | instruction | 0 | 90,230 | 23 | 180,460 |
Tags: binary search, constructive algorithms, divide and conquer, greedy, implementation, sortings
Correct Solution:
```
n = int(input())
coords = n*[-1]
coordsy = list()
coordsz = list()
for i in range(n):
coords[i] = [int(i) for i in input().split()] + [i]
coords.sort()
i = 0
while i < len(coords) - 1:
if coords[i][:2] == coords[i + 1][:2]:
print(coords[i][3] + 1, coords[i + 1][3] + 1)
# coords.pop(i)
# coords.pop(i)
i += 1
else:
coordsy.append(coords[i])
i += 1
if i == len(coords) - 1:
coordsy.append(coords[i])
i = 0
while i < len(coordsy) - 1:
if coordsy[i][:1] == coordsy[i + 1][:1]:
print(coordsy[i][3] + 1, coordsy[i + 1][3] + 1)
# coords.pop(i)
# coords.pop(i)
i += 1
else:
coordsz.append(coordsy[i])
i += 1
if i == len(coordsy) - 1:
coordsz.append(coordsy[i])
for i in range(0, len(coordsz), 2):
print(coordsz[i][3] + 1, coordsz[i + 1][3] + 1)
``` | output | 1 | 90,230 | 23 | 180,461 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version, n ≤ 50 000.
There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even.
You'd like to remove all n points using a sequence of n/2 snaps. In one snap, you can remove any two points a and b that have not been removed yet and form a perfectly balanced pair. A pair of points a and b is perfectly balanced if no other point c (that has not been removed yet) lies within the axis-aligned minimum bounding box of points a and b.
Formally, point c lies within the axis-aligned minimum bounding box of points a and b if and only if min(x_a, x_b) ≤ x_c ≤ max(x_a, x_b), min(y_a, y_b) ≤ y_c ≤ max(y_a, y_b), and min(z_a, z_b) ≤ z_c ≤ max(z_a, z_b). Note that the bounding box might be degenerate.
Find a way to remove all points in n/2 snaps.
Input
The first line contains a single integer n (2 ≤ n ≤ 50 000; n is even), denoting the number of points.
Each of the next n lines contains three integers x_i, y_i, z_i (-10^8 ≤ x_i, y_i, z_i ≤ 10^8), denoting the coordinates of the i-th point.
No two points coincide.
Output
Output n/2 pairs of integers a_i, b_i (1 ≤ a_i, b_i ≤ n), denoting the indices of points removed on snap i. Every integer between 1 and n, inclusive, must appear in your output exactly once.
We can show that it is always possible to remove all points. If there are many solutions, output any of them.
Examples
Input
6
3 1 0
0 3 0
2 2 0
1 0 0
1 3 0
0 1 0
Output
3 6
5 1
2 4
Input
8
0 1 1
1 0 1
1 1 0
1 1 1
2 2 2
3 2 2
2 3 2
2 2 3
Output
4 5
1 6
2 7
3 8
Note
In the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on z = 0 plane). Note that order of removing matters: for example, points 5 and 1 don't form a perfectly balanced pair initially, but they do after point 3 is removed.
<image> | instruction | 0 | 90,231 | 23 | 180,462 |
Tags: binary search, constructive algorithms, divide and conquer, greedy, implementation, sortings
Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
N = int(input())
D = {}
ans = []
for i in range(N):
x, y, z = map(int, input().split())
if z in D:
if y in D[z]:
D[z][y].append((x, i))
else:
D[z][y] = [(x, i)]
else:
D[z] = {y: [(x, i)]}
E = {}
for z in D:
for y in D[z]:
D[z][y] = sorted(D[z][y])
while len(D[z][y]) >= 2:
a, b = D[z][y].pop(), D[z][y].pop()
ans.append((a[1], b[1]))
if len(D[z][y]):
if z in E:
E[z].append((y, D[z][y][0][1]))
else:
E[z] = [(y, D[z][y][0][1])]
F = []
for z in E:
E[z] = sorted(E[z])
while len(E[z]) >= 2:
a, b = E[z].pop(), E[z].pop()
ans.append((a[1], b[1]))
if len(E[z]):
F.append((z, E[z][0][1]))
F = sorted(F)
while len(F) >= 2:
a, b = F.pop(), F.pop()
ans.append((a[1], b[1]))
ans = [(a[0]+1, a[1]+1) for a in ans]
sans = [" ".join(map(str, a)) for a in ans]
print("\n".join(sans))
``` | output | 1 | 90,231 | 23 | 180,463 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version, n ≤ 50 000.
There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even.
You'd like to remove all n points using a sequence of n/2 snaps. In one snap, you can remove any two points a and b that have not been removed yet and form a perfectly balanced pair. A pair of points a and b is perfectly balanced if no other point c (that has not been removed yet) lies within the axis-aligned minimum bounding box of points a and b.
Formally, point c lies within the axis-aligned minimum bounding box of points a and b if and only if min(x_a, x_b) ≤ x_c ≤ max(x_a, x_b), min(y_a, y_b) ≤ y_c ≤ max(y_a, y_b), and min(z_a, z_b) ≤ z_c ≤ max(z_a, z_b). Note that the bounding box might be degenerate.
Find a way to remove all points in n/2 snaps.
Input
The first line contains a single integer n (2 ≤ n ≤ 50 000; n is even), denoting the number of points.
Each of the next n lines contains three integers x_i, y_i, z_i (-10^8 ≤ x_i, y_i, z_i ≤ 10^8), denoting the coordinates of the i-th point.
No two points coincide.
Output
Output n/2 pairs of integers a_i, b_i (1 ≤ a_i, b_i ≤ n), denoting the indices of points removed on snap i. Every integer between 1 and n, inclusive, must appear in your output exactly once.
We can show that it is always possible to remove all points. If there are many solutions, output any of them.
Examples
Input
6
3 1 0
0 3 0
2 2 0
1 0 0
1 3 0
0 1 0
Output
3 6
5 1
2 4
Input
8
0 1 1
1 0 1
1 1 0
1 1 1
2 2 2
3 2 2
2 3 2
2 2 3
Output
4 5
1 6
2 7
3 8
Note
In the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on z = 0 plane). Note that order of removing matters: for example, points 5 and 1 don't form a perfectly balanced pair initially, but they do after point 3 is removed.
<image> | instruction | 0 | 90,232 | 23 | 180,464 |
Tags: binary search, constructive algorithms, divide and conquer, greedy, implementation, sortings
Correct Solution:
```
"""
> File Name: c.py
> Author: Code_Bear
> Mail: secret
> Created Time: Thu Oct 17 16:34:03 2019
"""
from collections import OrderedDict
def SortPoint(p, ids, k, D):
if k == D:
return ids[0]
maps = OrderedDict()
for i in ids:
if p[i][k] not in maps:
maps[p[i][k]] = []
maps[p[i][k]].append(i)
a = []
for i in sorted(maps.keys()):
cnt = SortPoint(p, maps[i], k + 1, D)
if cnt != -1: a.append(cnt)
for i in range(0, len(a), 2):
if i + 1 < len(a):
print(a[i] + 1, a[i + 1] + 1)
return -1 if len(a) % 2 == 0 else a[-1]
def solver():
n = int(input())
p = []
ids = [i for i in range(n)]
for i in range(n):
point = list(map(int, input().split()))
p.append(point)
SortPoint(p, ids, 0, 3)
def main():
while 1:
try:
solver()
except EOFError:
break
if __name__ == '__main__':
main()
``` | output | 1 | 90,232 | 23 | 180,465 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version, n ≤ 50 000.
There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even.
You'd like to remove all n points using a sequence of n/2 snaps. In one snap, you can remove any two points a and b that have not been removed yet and form a perfectly balanced pair. A pair of points a and b is perfectly balanced if no other point c (that has not been removed yet) lies within the axis-aligned minimum bounding box of points a and b.
Formally, point c lies within the axis-aligned minimum bounding box of points a and b if and only if min(x_a, x_b) ≤ x_c ≤ max(x_a, x_b), min(y_a, y_b) ≤ y_c ≤ max(y_a, y_b), and min(z_a, z_b) ≤ z_c ≤ max(z_a, z_b). Note that the bounding box might be degenerate.
Find a way to remove all points in n/2 snaps.
Input
The first line contains a single integer n (2 ≤ n ≤ 50 000; n is even), denoting the number of points.
Each of the next n lines contains three integers x_i, y_i, z_i (-10^8 ≤ x_i, y_i, z_i ≤ 10^8), denoting the coordinates of the i-th point.
No two points coincide.
Output
Output n/2 pairs of integers a_i, b_i (1 ≤ a_i, b_i ≤ n), denoting the indices of points removed on snap i. Every integer between 1 and n, inclusive, must appear in your output exactly once.
We can show that it is always possible to remove all points. If there are many solutions, output any of them.
Examples
Input
6
3 1 0
0 3 0
2 2 0
1 0 0
1 3 0
0 1 0
Output
3 6
5 1
2 4
Input
8
0 1 1
1 0 1
1 1 0
1 1 1
2 2 2
3 2 2
2 3 2
2 2 3
Output
4 5
1 6
2 7
3 8
Note
In the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on z = 0 plane). Note that order of removing matters: for example, points 5 and 1 don't form a perfectly balanced pair initially, but they do after point 3 is removed.
<image> | instruction | 0 | 90,233 | 23 | 180,466 |
Tags: binary search, constructive algorithms, divide and conquer, greedy, implementation, sortings
Correct Solution:
```
n = int(input())
arr = []
for _ in range(n):
a, b, c = map(int, input().split())
arr.append([a, b, c] + [_ + 1])
arr.sort()
ans = []
for i in range(2, -1, -1):
st = []
for x in arr:
if st and all(st[-1][itr] <= x[itr] for itr in range(i+1)):
ans.append((st.pop()[-1], x[-1]))
else:
st.append(x)
arr = st
for i in ans:
print(i[0], i[1])
``` | output | 1 | 90,233 | 23 | 180,467 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version, n ≤ 50 000.
There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even.
You'd like to remove all n points using a sequence of n/2 snaps. In one snap, you can remove any two points a and b that have not been removed yet and form a perfectly balanced pair. A pair of points a and b is perfectly balanced if no other point c (that has not been removed yet) lies within the axis-aligned minimum bounding box of points a and b.
Formally, point c lies within the axis-aligned minimum bounding box of points a and b if and only if min(x_a, x_b) ≤ x_c ≤ max(x_a, x_b), min(y_a, y_b) ≤ y_c ≤ max(y_a, y_b), and min(z_a, z_b) ≤ z_c ≤ max(z_a, z_b). Note that the bounding box might be degenerate.
Find a way to remove all points in n/2 snaps.
Input
The first line contains a single integer n (2 ≤ n ≤ 50 000; n is even), denoting the number of points.
Each of the next n lines contains three integers x_i, y_i, z_i (-10^8 ≤ x_i, y_i, z_i ≤ 10^8), denoting the coordinates of the i-th point.
No two points coincide.
Output
Output n/2 pairs of integers a_i, b_i (1 ≤ a_i, b_i ≤ n), denoting the indices of points removed on snap i. Every integer between 1 and n, inclusive, must appear in your output exactly once.
We can show that it is always possible to remove all points. If there are many solutions, output any of them.
Examples
Input
6
3 1 0
0 3 0
2 2 0
1 0 0
1 3 0
0 1 0
Output
3 6
5 1
2 4
Input
8
0 1 1
1 0 1
1 1 0
1 1 1
2 2 2
3 2 2
2 3 2
2 2 3
Output
4 5
1 6
2 7
3 8
Note
In the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on z = 0 plane). Note that order of removing matters: for example, points 5 and 1 don't form a perfectly balanced pair initially, but they do after point 3 is removed.
<image>
Submitted Solution:
```
from math import *
#from bisect import *
#from collections import *
#from random import *
#from decimal import *"""
#from heapq import *
#from random import *
import sys
input=sys.stdin.readline
#sys.setrecursionlimit(3*(10**5))
global flag
def inp():
return int(input())
def st():
return input().rstrip('\n')
def lis():
return list(map(int,input().split()))
def ma1():
return map(int,input().split())
t=1
while(t):
t-=1
n=inp()
r=[]
di={}
for i in range(n):
a=lis()
a+=[i]
r.append(a)
try:
di[a[-2]].append(a)
except:
di[a[-2]]=[a]
ydi={}
extra=[]
#print(di)
for i in di.keys():
extray=[]
for j in di[i]:
try:
ydi[j[-3]].append(j)
except:
ydi[j[-3]]=[j]
for j in ydi.keys():
ydi[j].sort()
for j in ydi.keys():
for k in range(0,len(ydi[j])-(len(ydi[j])%2),2):
print(ydi[j][k][-1]+1,ydi[j][k+1][-1]+1)
if(len(ydi[j])%2):
has=ydi[j][-1]
has1=[has[-3],has[-4],has[-2],has[-1]]
extray.append(has1)
extray.sort()
for j in range(0,len(extray)-len(extray)%2,2):
print(extray[j][-1]+1,extray[j+1][-1]+1)
if(len(extray)%2):
has=[extray[-1][-2],extray[-1][-3],extray[-1][-4],extray[-1][-1]]
extra.append(has)
ydi={}
extray=[]
extra.sort()
#print(extra)
for i in range(0,len(extra),2):
print(extra[i][-1]+1,extra[i+1][-1]+1)
``` | instruction | 0 | 90,234 | 23 | 180,468 |
Yes | output | 1 | 90,234 | 23 | 180,469 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version, n ≤ 50 000.
There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even.
You'd like to remove all n points using a sequence of n/2 snaps. In one snap, you can remove any two points a and b that have not been removed yet and form a perfectly balanced pair. A pair of points a and b is perfectly balanced if no other point c (that has not been removed yet) lies within the axis-aligned minimum bounding box of points a and b.
Formally, point c lies within the axis-aligned minimum bounding box of points a and b if and only if min(x_a, x_b) ≤ x_c ≤ max(x_a, x_b), min(y_a, y_b) ≤ y_c ≤ max(y_a, y_b), and min(z_a, z_b) ≤ z_c ≤ max(z_a, z_b). Note that the bounding box might be degenerate.
Find a way to remove all points in n/2 snaps.
Input
The first line contains a single integer n (2 ≤ n ≤ 50 000; n is even), denoting the number of points.
Each of the next n lines contains three integers x_i, y_i, z_i (-10^8 ≤ x_i, y_i, z_i ≤ 10^8), denoting the coordinates of the i-th point.
No two points coincide.
Output
Output n/2 pairs of integers a_i, b_i (1 ≤ a_i, b_i ≤ n), denoting the indices of points removed on snap i. Every integer between 1 and n, inclusive, must appear in your output exactly once.
We can show that it is always possible to remove all points. If there are many solutions, output any of them.
Examples
Input
6
3 1 0
0 3 0
2 2 0
1 0 0
1 3 0
0 1 0
Output
3 6
5 1
2 4
Input
8
0 1 1
1 0 1
1 1 0
1 1 1
2 2 2
3 2 2
2 3 2
2 2 3
Output
4 5
1 6
2 7
3 8
Note
In the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on z = 0 plane). Note that order of removing matters: for example, points 5 and 1 don't form a perfectly balanced pair initially, but they do after point 3 is removed.
<image>
Submitted Solution:
```
n = int(input())
sentinel = [(10**9, 10**9, 10**9)]
points = sorted(tuple(map(int, input().split())) + (i,) for i in range(1, n+1)) + sentinel
ans = []
rem = []
i = 0
while i < n:
if points[i][:2] == points[i+1][:2]:
ans.append(f'{points[i][-1]} {points[i+1][-1]}')
i += 2
else:
rem.append(i)
i += 1
rem += [n]
rem2 = []
n = len(rem)
i = 0
while i < n-1:
if points[rem[i]][0] == points[rem[i+1]][0]:
ans.append(f'{points[rem[i]][-1]} {points[rem[i+1]][-1]}')
i += 2
else:
rem2.append(points[rem[i]][-1])
i += 1
print(*ans, sep='\n')
for i in range(0, len(rem2), 2):
print(rem2[i], rem2[i+1])
``` | instruction | 0 | 90,235 | 23 | 180,470 |
Yes | output | 1 | 90,235 | 23 | 180,471 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version, n ≤ 50 000.
There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even.
You'd like to remove all n points using a sequence of n/2 snaps. In one snap, you can remove any two points a and b that have not been removed yet and form a perfectly balanced pair. A pair of points a and b is perfectly balanced if no other point c (that has not been removed yet) lies within the axis-aligned minimum bounding box of points a and b.
Formally, point c lies within the axis-aligned minimum bounding box of points a and b if and only if min(x_a, x_b) ≤ x_c ≤ max(x_a, x_b), min(y_a, y_b) ≤ y_c ≤ max(y_a, y_b), and min(z_a, z_b) ≤ z_c ≤ max(z_a, z_b). Note that the bounding box might be degenerate.
Find a way to remove all points in n/2 snaps.
Input
The first line contains a single integer n (2 ≤ n ≤ 50 000; n is even), denoting the number of points.
Each of the next n lines contains three integers x_i, y_i, z_i (-10^8 ≤ x_i, y_i, z_i ≤ 10^8), denoting the coordinates of the i-th point.
No two points coincide.
Output
Output n/2 pairs of integers a_i, b_i (1 ≤ a_i, b_i ≤ n), denoting the indices of points removed on snap i. Every integer between 1 and n, inclusive, must appear in your output exactly once.
We can show that it is always possible to remove all points. If there are many solutions, output any of them.
Examples
Input
6
3 1 0
0 3 0
2 2 0
1 0 0
1 3 0
0 1 0
Output
3 6
5 1
2 4
Input
8
0 1 1
1 0 1
1 1 0
1 1 1
2 2 2
3 2 2
2 3 2
2 2 3
Output
4 5
1 6
2 7
3 8
Note
In the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on z = 0 plane). Note that order of removing matters: for example, points 5 and 1 don't form a perfectly balanced pair initially, but they do after point 3 is removed.
<image>
Submitted 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
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**51, 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)
# -------------------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------------------------------------
n=int(input())
d=defaultdict(list)
def solve(e):
e.sort()
#print(e)
for i in range(len(e) // 2):
print(e[2 * i][3], e[2 * i + 1][3])
if len(e) % 2 == 1:
return e[-1]
else:
return -1
def solve2(l):
de=defaultdict(list)
for i in range(len(l)):
de[l[i][1]].append((l[i][0],l[i][1],l[i][2],l[i][3]))
e=[]
for i in de:
r=solve(de[i])
if r!=-1:
e.append(r)
e.sort()
for i in range(len(e) // 2):
print(e[2 * i][3], e[2 * i + 1][3])
if len(e)%2==1:
return e[-1]
else:
return -1
for i in range(n):
a,b,c=map(int,input().split())
d[a].append((a,b,c,i+1))
e=[]
for i in d:
r = solve2(d[i])
if r != -1:
e.append(r)
e.sort()
for i in range(len(e)//2):
print(e[2*i][3],e[2*i+1][3])
``` | instruction | 0 | 90,236 | 23 | 180,472 |
Yes | output | 1 | 90,236 | 23 | 180,473 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version, n ≤ 50 000.
There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even.
You'd like to remove all n points using a sequence of n/2 snaps. In one snap, you can remove any two points a and b that have not been removed yet and form a perfectly balanced pair. A pair of points a and b is perfectly balanced if no other point c (that has not been removed yet) lies within the axis-aligned minimum bounding box of points a and b.
Formally, point c lies within the axis-aligned minimum bounding box of points a and b if and only if min(x_a, x_b) ≤ x_c ≤ max(x_a, x_b), min(y_a, y_b) ≤ y_c ≤ max(y_a, y_b), and min(z_a, z_b) ≤ z_c ≤ max(z_a, z_b). Note that the bounding box might be degenerate.
Find a way to remove all points in n/2 snaps.
Input
The first line contains a single integer n (2 ≤ n ≤ 50 000; n is even), denoting the number of points.
Each of the next n lines contains three integers x_i, y_i, z_i (-10^8 ≤ x_i, y_i, z_i ≤ 10^8), denoting the coordinates of the i-th point.
No two points coincide.
Output
Output n/2 pairs of integers a_i, b_i (1 ≤ a_i, b_i ≤ n), denoting the indices of points removed on snap i. Every integer between 1 and n, inclusive, must appear in your output exactly once.
We can show that it is always possible to remove all points. If there are many solutions, output any of them.
Examples
Input
6
3 1 0
0 3 0
2 2 0
1 0 0
1 3 0
0 1 0
Output
3 6
5 1
2 4
Input
8
0 1 1
1 0 1
1 1 0
1 1 1
2 2 2
3 2 2
2 3 2
2 2 3
Output
4 5
1 6
2 7
3 8
Note
In the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on z = 0 plane). Note that order of removing matters: for example, points 5 and 1 don't form a perfectly balanced pair initially, but they do after point 3 is removed.
<image>
Submitted Solution:
```
def solve(points,ans,coords,x):
arr = []
curr = []
y = points[0][0]
for p in points:
if p[0] == y:
curr.append((y,p[1],p[2]))
else:
arr.append(curr)
y = p[0]
curr = [(y,p[1],p[2])]
arr.append(curr)
arr1 = []
for i in arr:
while len(i) >= 2:
ans.append((i.pop(0)[2],i.pop(0)[2]))
if len(i) == 1:
arr1.append((i[0][0],i[0][1],i[0][2]))
while len(arr1) >= 2:
ans.append((arr1.pop(0)[2],arr1.pop(0)[2]))
coords[x] = arr1[:]
def main():
n = int(input())
points = []
coords = {}
for i in range(n):
x,y,z = map(int,input().split())
if x not in coords.keys():
coords[x] = [(y,z,i+1)]
else:
coords[x].append((y,z,i+1))
ans = []
for i in coords.keys():
coords[i].sort()
if len(coords[i]) > 1:
solve(coords[i],ans,coords,i)
if len(coords[i]) == 1:
points.append((i,coords[i][0][0],coords[i][0][1],coords[i][0][2]))
points.sort()
for i in range(0,len(points),2):
a,b = points[i][3],points[i+1][3]
ans.append((a,b))
for i in ans:
print(i[0],i[1])
main()
``` | instruction | 0 | 90,237 | 23 | 180,474 |
Yes | output | 1 | 90,237 | 23 | 180,475 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version, n ≤ 50 000.
There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even.
You'd like to remove all n points using a sequence of n/2 snaps. In one snap, you can remove any two points a and b that have not been removed yet and form a perfectly balanced pair. A pair of points a and b is perfectly balanced if no other point c (that has not been removed yet) lies within the axis-aligned minimum bounding box of points a and b.
Formally, point c lies within the axis-aligned minimum bounding box of points a and b if and only if min(x_a, x_b) ≤ x_c ≤ max(x_a, x_b), min(y_a, y_b) ≤ y_c ≤ max(y_a, y_b), and min(z_a, z_b) ≤ z_c ≤ max(z_a, z_b). Note that the bounding box might be degenerate.
Find a way to remove all points in n/2 snaps.
Input
The first line contains a single integer n (2 ≤ n ≤ 50 000; n is even), denoting the number of points.
Each of the next n lines contains three integers x_i, y_i, z_i (-10^8 ≤ x_i, y_i, z_i ≤ 10^8), denoting the coordinates of the i-th point.
No two points coincide.
Output
Output n/2 pairs of integers a_i, b_i (1 ≤ a_i, b_i ≤ n), denoting the indices of points removed on snap i. Every integer between 1 and n, inclusive, must appear in your output exactly once.
We can show that it is always possible to remove all points. If there are many solutions, output any of them.
Examples
Input
6
3 1 0
0 3 0
2 2 0
1 0 0
1 3 0
0 1 0
Output
3 6
5 1
2 4
Input
8
0 1 1
1 0 1
1 1 0
1 1 1
2 2 2
3 2 2
2 3 2
2 2 3
Output
4 5
1 6
2 7
3 8
Note
In the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on z = 0 plane). Note that order of removing matters: for example, points 5 and 1 don't form a perfectly balanced pair initially, but they do after point 3 is removed.
<image>
Submitted 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
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**51, 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)
# -------------------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------------------------------------
n=int(input())
d=defaultdict(deque)
for i in range(n):
a,b,c=map(int,input().split())
d[a].append((b,c,i+1))
for i in d:
d[i]=list(d[i])
d[i].sort()
d[i]=deque(d[i])
for j in range(len(d[i])//2):
print(d[i][2*j][2],d[i][2*j+1][2])
d[i].popleft()
d[i].popleft()
l=[]
for i in d:
if len(d[i])!=0:
l.append(i)
l.sort()
for i in range(len(l)//2):
print(d[l[2*i]][0][2],d[l[2*i+1]][0][2])
``` | instruction | 0 | 90,238 | 23 | 180,476 |
No | output | 1 | 90,238 | 23 | 180,477 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version, n ≤ 50 000.
There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even.
You'd like to remove all n points using a sequence of n/2 snaps. In one snap, you can remove any two points a and b that have not been removed yet and form a perfectly balanced pair. A pair of points a and b is perfectly balanced if no other point c (that has not been removed yet) lies within the axis-aligned minimum bounding box of points a and b.
Formally, point c lies within the axis-aligned minimum bounding box of points a and b if and only if min(x_a, x_b) ≤ x_c ≤ max(x_a, x_b), min(y_a, y_b) ≤ y_c ≤ max(y_a, y_b), and min(z_a, z_b) ≤ z_c ≤ max(z_a, z_b). Note that the bounding box might be degenerate.
Find a way to remove all points in n/2 snaps.
Input
The first line contains a single integer n (2 ≤ n ≤ 50 000; n is even), denoting the number of points.
Each of the next n lines contains three integers x_i, y_i, z_i (-10^8 ≤ x_i, y_i, z_i ≤ 10^8), denoting the coordinates of the i-th point.
No two points coincide.
Output
Output n/2 pairs of integers a_i, b_i (1 ≤ a_i, b_i ≤ n), denoting the indices of points removed on snap i. Every integer between 1 and n, inclusive, must appear in your output exactly once.
We can show that it is always possible to remove all points. If there are many solutions, output any of them.
Examples
Input
6
3 1 0
0 3 0
2 2 0
1 0 0
1 3 0
0 1 0
Output
3 6
5 1
2 4
Input
8
0 1 1
1 0 1
1 1 0
1 1 1
2 2 2
3 2 2
2 3 2
2 2 3
Output
4 5
1 6
2 7
3 8
Note
In the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on z = 0 plane). Note that order of removing matters: for example, points 5 and 1 don't form a perfectly balanced pair initially, but they do after point 3 is removed.
<image>
Submitted Solution:
```
from sys import stdin,stdout
n=int(stdin.readline())
l=[]
for i in range(n):
x=list(map(int,stdin.readline().split()))
l.append([x,i+1])
l.sort()
for i in range(0,n,2):
print(l[i][1],l[i+1][1])
``` | instruction | 0 | 90,239 | 23 | 180,478 |
No | output | 1 | 90,239 | 23 | 180,479 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version, n ≤ 50 000.
There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even.
You'd like to remove all n points using a sequence of n/2 snaps. In one snap, you can remove any two points a and b that have not been removed yet and form a perfectly balanced pair. A pair of points a and b is perfectly balanced if no other point c (that has not been removed yet) lies within the axis-aligned minimum bounding box of points a and b.
Formally, point c lies within the axis-aligned minimum bounding box of points a and b if and only if min(x_a, x_b) ≤ x_c ≤ max(x_a, x_b), min(y_a, y_b) ≤ y_c ≤ max(y_a, y_b), and min(z_a, z_b) ≤ z_c ≤ max(z_a, z_b). Note that the bounding box might be degenerate.
Find a way to remove all points in n/2 snaps.
Input
The first line contains a single integer n (2 ≤ n ≤ 50 000; n is even), denoting the number of points.
Each of the next n lines contains three integers x_i, y_i, z_i (-10^8 ≤ x_i, y_i, z_i ≤ 10^8), denoting the coordinates of the i-th point.
No two points coincide.
Output
Output n/2 pairs of integers a_i, b_i (1 ≤ a_i, b_i ≤ n), denoting the indices of points removed on snap i. Every integer between 1 and n, inclusive, must appear in your output exactly once.
We can show that it is always possible to remove all points. If there are many solutions, output any of them.
Examples
Input
6
3 1 0
0 3 0
2 2 0
1 0 0
1 3 0
0 1 0
Output
3 6
5 1
2 4
Input
8
0 1 1
1 0 1
1 1 0
1 1 1
2 2 2
3 2 2
2 3 2
2 2 3
Output
4 5
1 6
2 7
3 8
Note
In the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on z = 0 plane). Note that order of removing matters: for example, points 5 and 1 don't form a perfectly balanced pair initially, but they do after point 3 is removed.
<image>
Submitted Solution:
```
"""
NTC here
"""
from sys import stdin, setrecursionlimit
setrecursionlimit(10**7)
def iin(): return int(stdin.readline())
def lin(): return list(map(int, stdin.readline().split()))
# range = xrange
# input = raw_input
def main():
from collections import defaultdict
n=iin()
point=[lin()+[i] for i in range(n)]
point.sort()
ans=[]
# remove same points
done=set()
for i in range(n-1):
if i in done:continue
ch=0
for j in range(3):
if point[i][j]==point[i+1][j]:
ch+=1
if ch==3:
done.add(i+1)
done.add(i)
ans.append([point[i][3]+1,point[i+1][3]+1])
point=[point[i] for i in range(n) if i not in done]
# print('A',point,ans)
#remove 2 commons
done= set()
p1,p2,p3=sorted(point,key=lambda x: [x[0],x[1],x[2]]),sorted(point,key=lambda x: [x[0],x[2],x[1]]),sorted(point,key=lambda x: [x[1],x[2],x[0]])
l=len(point)
for i in range(l-1):
if p1[i][3] in done or p1[i+1][3] in done:continue
ch=0
for j in range(3):
if p1[i][j]==p1[i+1][j]:
ch+=1
if ch>=2:
ans.append([p1[i][3]+1,p1[i+1][3]+1])
done.add(p1[i][3])
done.add(p1[i+1][3])
for i in range(l-1):
if p2[i][3] in done or p2[i+1][3] in done:continue
ch=0
for j in range(3):
if p2[i][j]==p2[i+1][j]:
ch+=1
if ch>=2:
ans.append([p2[i][3]+1,p2[i+1][3]+1])
done.add(p2[i][3])
done.add(p2[i+1][3])
for i in range(l-1):
if p3[i][3] in done or p3[i+1][3] in done:continue
ch=0
for j in range(3):
if p3[i][j]==p3[i+1][j]:
ch+=1
if ch>=2:
ans.append([p3[i][3]+1,p3[i+1][3]+1])
done.add(p3[i][3])
done.add(p3[i+1][3])
point=[point[i] for i in range(l) if point[i][3] not in done]
# print('B',point,ans)
#left out
point.sort()
l=len(point)
done=set()
for i in range(l-1):
if i in done:continue
ans.append([point[i][3]+1,point[i+1][3]+1])
done.add(i+1)
for i,j in ans:
print(i,j)
main()
# try:
# main()
# except Exception as e: print(e)
``` | instruction | 0 | 90,240 | 23 | 180,480 |
No | output | 1 | 90,240 | 23 | 180,481 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version, n ≤ 50 000.
There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even.
You'd like to remove all n points using a sequence of n/2 snaps. In one snap, you can remove any two points a and b that have not been removed yet and form a perfectly balanced pair. A pair of points a and b is perfectly balanced if no other point c (that has not been removed yet) lies within the axis-aligned minimum bounding box of points a and b.
Formally, point c lies within the axis-aligned minimum bounding box of points a and b if and only if min(x_a, x_b) ≤ x_c ≤ max(x_a, x_b), min(y_a, y_b) ≤ y_c ≤ max(y_a, y_b), and min(z_a, z_b) ≤ z_c ≤ max(z_a, z_b). Note that the bounding box might be degenerate.
Find a way to remove all points in n/2 snaps.
Input
The first line contains a single integer n (2 ≤ n ≤ 50 000; n is even), denoting the number of points.
Each of the next n lines contains three integers x_i, y_i, z_i (-10^8 ≤ x_i, y_i, z_i ≤ 10^8), denoting the coordinates of the i-th point.
No two points coincide.
Output
Output n/2 pairs of integers a_i, b_i (1 ≤ a_i, b_i ≤ n), denoting the indices of points removed on snap i. Every integer between 1 and n, inclusive, must appear in your output exactly once.
We can show that it is always possible to remove all points. If there are many solutions, output any of them.
Examples
Input
6
3 1 0
0 3 0
2 2 0
1 0 0
1 3 0
0 1 0
Output
3 6
5 1
2 4
Input
8
0 1 1
1 0 1
1 1 0
1 1 1
2 2 2
3 2 2
2 3 2
2 2 3
Output
4 5
1 6
2 7
3 8
Note
In the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on z = 0 plane). Note that order of removing matters: for example, points 5 and 1 don't form a perfectly balanced pair initially, but they do after point 3 is removed.
<image>
Submitted Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------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
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default='z', 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------------------------------------
n=int(input())
ind=[i+1 for i in range(n)]
l=[]
for i in range(n):
a,b,c=map(int,input().split())
l.append((a,b,c))
ind=sort_list(ind,l)
l.sort()
for i in range(n//2):
print(ind[2*i],ind[2*i+1])
``` | instruction | 0 | 90,241 | 23 | 180,482 |
No | output | 1 | 90,241 | 23 | 180,483 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image> | instruction | 0 | 90,508 | 23 | 181,016 |
Tags: binary search, data structures, implementation
Correct Solution:
```
# import itertools
# import bisect
# import math
from collections import defaultdict, Counter
import os
import sys
from io import BytesIO, IOBase
# sys.setrecursionlimit(10 ** 5)
ii = lambda: int(input())
lmii = lambda: list(map(int, input().split()))
slmii = lambda: sorted(map(int, input().split()))
li = lambda: list(input())
mii = lambda: map(int, input().split())
msi = lambda: map(str, input().split())
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
def gcd(a, b):
if b == 0: return a
return gcd(b, a % b)
def lcm(a, b): return (a * b) // gcd(a, b)
def main():
# for _ in " " * int(input()):
w, h, n = mii()
ws, dws, hs, dhs, hsm, wsm = SortedList([]), defaultdict(int), SortedList([]), defaultdict(int), SortedList(
[]), SortedList([])
hsm.add(h);
wsm.add(w);
hs.add(0);
ws.add(0);
hs.add(h);
ws.add(w);
dhs[h] = 1;
dhs[0] = 1;
dws[0] = 1;
dws[w] = 1
for i in range(n):
t, p = map(str, input().split())
p = int(p)
if t == "H":
if dhs[p] == 0:
hs.add(p)
dhs[p] = 1
ind = hs.bisect_left(p)
pre, nex = hs[ind - 1], hs[ind + 1]
hsm.__delitem__(hsm.bisect_left(nex - pre));
hsm.add(p - pre);
hsm.add(nex - p)
else:
if dws[p] == 0:
ws.add(p)
dws[p] = 1
ind = ws.bisect_left(p)
pre, nex = ws[ind - 1], ws[ind + 1]
wsm.__delitem__(wsm.bisect_left(nex - pre));
wsm.add(p - pre);
wsm.add(nex - p)
print(wsm[-1] * hsm[-1])
pass
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | output | 1 | 90,508 | 23 | 181,017 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image> | instruction | 0 | 90,509 | 23 | 181,018 |
Tags: binary search, data structures, implementation
Correct Solution:
```
w,h,n=map(int,input().split())
l=[-1]*(w+1)
r=[-1]*(w+1)
t=[-1]*(h+1)
b=[-1]*(h+1)
l[0]=0
b[0]=0
t[h]=h
r[w]=w
V=[0]*(n)
H=[0]*(n)
for i in range(n):
line,index=input().split()
index=int(index)
if line=="V":
r[index]=w
V[i]=index
else:
t[index]=h
H[i]=index
left=0
mxw=0
for i in range(1,w+1):
if r[i]!=-1:
l[i]=left
r[left]=i
mxw=max(mxw,i-left)
left=i
bottom=0
mxh=0
for i in range(1,h+1):
if t[i]!=-1:
b[i]=bottom
t[bottom]=i
mxh=max(mxh,i-bottom)
bottom=i
ans=[0]*(n)
ans[n-1]=mxh*mxw
for i in range(n-1,0,-1):
if V[i]!=0:
mxw=max(mxw,r[V[i]]-l[V[i]])
r[l[V[i]]]=r[V[i]]
l[r[V[i]]]=l[V[i]]
else:
mxh=max(mxh,t[H[i]]-b[H[i]])
b[t[H[i]]]=b[H[i]]
t[b[H[i]]]=t[H[i]]
ans[i-1]=mxh*mxw
for i in range(n):
print(ans[i])
``` | output | 1 | 90,509 | 23 | 181,019 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image> | instruction | 0 | 90,510 | 23 | 181,020 |
Tags: binary search, data structures, implementation
Correct Solution:
```
# -*- coding:utf-8 -*-
"""
created by shuangquan.huang at 1/7/20
reverse thinking of merging instead of split
"""
import collections
import time
import os
import sys
import bisect
import heapq
from typing import List
class Node:
val = None
def __init__(self, val):
self.val = val
self.left = Node
self.right = None
def solve(W, H, N, A):
xs = [0] + [v for t, v in A if t == 0] + [W]
ys = [0] + [v for t, v in A if t == 1] + [H]
xs.sort()
ys.sort()
xlist = Node(0)
h = xlist
xnodes = {0: h}
maxw = max([xs[i+1] - xs[i] for i in range(len(xs)-1)] or [0])
maxh = max([ys[i+1] - ys[i] for i in range(len(ys)-1)] or [0])
for v in xs[1:]:
n = Node(v)
xnodes[v] = n
h.right = n
n.left = h
h = n
ylist = Node(0)
h = ylist
ynodes = {0: h}
for v in ys[1:]:
n = Node(v)
ynodes[v] = n
h.right = n
n.left = h
h = n
ans = []
maxarea = maxh * maxw
for t, v in reversed(A):
ans.append(maxarea)
if t == 0:
node = xnodes[v]
w = node.right.val - node.left.val
maxw = max(maxw, w)
else:
node = ynodes[v]
h = node.right.val - node.left.val
maxh = max(maxh, h)
node.left.right = node.right
node.right.left = node.left
maxarea = maxh * maxw
return ans[::-1]
def solve2(W, H, N, A):
ws = [(-W, 0, W)]
hs = [(-H, 0, H)]
iw, ih = set(), set()
ans = []
xs, ys = [0, W], [0, H]
for t, v in A:
if t == 0:
bisect.insort_left(xs, v)
i = bisect.bisect_left(xs, v)
l, m, r = xs[i-1], xs[i], xs[i+1]
iw.add((l-r, l, r))
heapq.heappush(ws, (l - m, l, m))
heapq.heappush(ws, (m - r, m, r))
while ws[0] in iw:
heapq.heappop(ws)
else:
bisect.insort(ys, v)
i = bisect.bisect_left(ys, v)
l, m, r = ys[i-1], ys[i], ys[i+1]
ih.add((l-r, l, r))
heapq.heappush(hs, (l - m, l, m))
heapq.heappush(hs, (m - r, m, r))
while hs[0] in ih:
heapq.heappop(hs)
w, h = ws[0], hs[0]
ans.append(w[0] * h[0])
return ans
W, H, N = map(int,input().split())
A = []
for i in range(N):
a, b = input().split()
c = 0 if a == 'V' else 1
A.append((c, int(b)))
print('\n'.join(map(str, solve(W, H, N, A))))
``` | output | 1 | 90,510 | 23 | 181,021 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image> | instruction | 0 | 90,511 | 23 | 181,022 |
Tags: binary search, data structures, implementation
Correct Solution:
```
w, h, n = map(int, input().split())
x = [0, w]
y = [0, h]
rev = []
for _ in range(n):
s, d = input().split()
if s == 'H':
y.append(int(d))
else:
x.append(int(d))
rev.append((s, int(d)))
x.sort()
y.sort()
_max = 0
if len(x) > 1:
for idx in range(len(x) - 1):
_max = max(_max, x[idx + 1] - x[idx])
else:
_max = w
max_x = _max
_max = 0
if len(y) > 1:
for idx in range(len(y) - 1):
_max = max(_max, y[idx + 1] - y[idx])
else:
_max = w
max_y = _max
enum_x = {num : idx for idx, num in enumerate(x)}
enum_y = {num : idx for idx, num in enumerate(y)}
old_x = x
old_y = y
x = [[0, 0, 0]] * len(old_x)
y = [[0, 0, 0]] * len(old_y)
for idx in range(1, len(x) - 1):
x[idx] = [old_x[idx], idx-1, idx+1]
for idx in range(1, len(y) - 1):
y[idx] = [old_y[idx], idx-1, idx+1]
x[-1] = [w, 0, 0]
y[-1] = [h, 0, 0]
rev.reverse()
ans = [max_x * max_y]
for item in rev:
if item[0] == 'H':
elem = y[enum_y[item[1]]]
max_y = max(max_y, y[elem[2]][0] - y[elem[1]][0])
y[elem[1]][2] = elem[2]
y[elem[2]][1] = elem[1]
else:
elem = x[enum_x[item[1]]]
max_x = max(max_x, x[elem[2]][0] - x[elem[1]][0])
x[elem[1]][2] = elem[2]
x[elem[2]][1] = elem[1]
ans.append(max_x * max_y)
ans.pop()
print('\n'.join(map(str, reversed(ans))))
``` | output | 1 | 90,511 | 23 | 181,023 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image> | instruction | 0 | 90,512 | 23 | 181,024 |
Tags: binary search, data structures, implementation
Correct Solution:
```
def main():
from sys import stdin
w, h, n = map(int, stdin.readline().split())
res, vrt, hor = [], [], []
vh = (vrt, hor)
for i, s in enumerate(stdin.read().splitlines()):
x = int(s[2:])
flag = s[0] == 'V'
vh[flag].append(i)
res.append([x, flag])
dim = []
for tmp, m in zip(vh, (h, w)):
tmp.sort(key=lambda e: res[e][0])
u = [None, [0]]
dim.append(u)
j = z = 0
for i in tmp:
x = res[i][0]
if z < x - j:
z = x - j
j = x
v = [u, res[i]]
u.append(v)
u = v
res[i].append(u)
v = [u, [m], None]
u.append(v)
dim.append(v)
if z < m - j:
z = m - j
dim.append(z)
l, r, wmax, u, d, hmax = dim
whmax = [wmax, hmax]
for i in range(n - 1, -1, -1):
x, flag, link = res[i]
u = whmax[flag]
res[i] = u * whmax[not flag]
link[0][2] = link[2]
link[2][0] = link[0]
v = link[2][1][0] - link[0][1][0]
if u < v:
whmax[flag] = v
print('\n'.join(map(str, res)))
if __name__ == '__main__':
main()
``` | output | 1 | 90,512 | 23 | 181,025 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image> | instruction | 0 | 90,513 | 23 | 181,026 |
Tags: binary search, data structures, implementation
Correct Solution:
```
def main():
from sys import stdin
w, h, n = map(int, stdin.readline().split())
res, vrt, hor = [], [], []
vh = (vrt, hor)
for i, s in enumerate(stdin.read().splitlines()):
x = int(s[2:])
flag = s[0] == 'V'
vh[flag].append(i)
res.append([x, flag])
dim = []
for tmp, m in zip(vh, (h, w)):
tmp.sort(key=lambda e: res[e][0])
u = [None, [0]]
dim.append(u)
j = z = 0
for i in tmp:
x = res[i][0]
if z < x - j:
z = x - j
j = x
v = [u, res[i]]
u.append(v)
u = v
res[i].append(u)
v = [u, [m], None]
u.append(v)
dim.append(v)
if z < m - j:
z = m - j
dim.append(z)
l, r, wmax, u, d, hmax = dim
s = str(wmax * hmax)
for i in range(n - 1, -1, -1):
x, flag, link = res[i]
u = hmax if flag else wmax
res[i] = s
link[0][2] = link[2]
link[2][0] = link[0]
v = link[2][1][0] - link[0][1][0]
if u < v:
if flag:
hmax = v
else:
wmax = v
s = str(wmax * hmax)
print('\n'.join(res))
if __name__ == '__main__':
main()
``` | output | 1 | 90,513 | 23 | 181,027 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image>
Submitted Solution:
```
w,h,n=map(int,input().split())
l=[-1]*(w+1)
r=[-1]*(w+1)
t=[-1]*(h+1)
b=[-1]*(h+1)
l[0]=0
b[0]=0
V=[0]*(n)
H=[0]*(n)
for i in range(n):
line,index=input().split()
index=int(index)
if line=="V":
r[index]=w
V[i]=index
else:
t[index]=h
H[i]=index
left=0
mxw=0
for i in range(1,w+1):
if r[i]!=-1:
l[i]=left
r[left]=i
mxw=max(mxw,i-left)
left=i
bottom=0
mxh=0
for i in range(1,h+1):
if t[i]!=-1:
b[i]=bottom
t[bottom]=i
mxh=max(mxh,i-bottom)
bottom=i
ans=[0]*(n)
ans[n-1]=mxh*mxw
for i in range(n-1,0,-1):
if H[i]==0:
mxw=max(mxw,r[V[i]]-l[V[i]])
r[l[V[i]]]=r[V[i]]
l[r[V[i]]]=l[V[i]]
else:
mxh=max(mxh,t[H[i]]-b[H[i]])
b[t[H[i]]]=b[H[i]]
t[b[H[i]]]=t[H[i]]
ans[i-1]=mxh*mxw
for i in range(n):
print(ans[i])
``` | instruction | 0 | 90,514 | 23 | 181,028 |
No | output | 1 | 90,514 | 23 | 181,029 |
Provide a correct Python 3 solution for this coding contest problem.
There is a grid with R rows and C columns. We call the cell in the r-th row and c-th column (r,c).
Mr. Takahashi wrote non-negative integers into N of the cells, that is, he wrote a non-negative integer a_i into (r_i,c_i) for each i (1≤i≤N). After that he fell asleep.
Mr. Aoki found the grid and tries to surprise Mr. Takahashi by writing integers into all remaining cells. The grid must meet the following conditions to really surprise Mr. Takahashi.
* Condition 1: Each cell contains a non-negative integer.
* Condition 2: For any 2×2 square formed by cells on the grid, the sum of the top left and bottom right integers must always equal to the sum of the top right and bottom left integers.
Determine whether it is possible to meet those conditions by properly writing integers into all remaining cells.
Constraints
* 2≤R,C≤10^5
* 1≤N≤10^5
* 1≤r_i≤R
* 1≤c_i≤C
* (r_i,c_i) ≠ (r_j,c_j) (i≠j)
* a_i is an integer.
* 0≤a_i≤10^9
Input
The input is given from Standard Input in the following format:
R C
N
r_1 c_1 a_1
r_2 c_2 a_2
:
r_N c_N a_N
Output
Print `Yes` if it is possible to meet the conditions by properly writing integers into all remaining cells. Otherwise, print `No`.
Examples
Input
2 2
3
1 1 0
1 2 10
2 1 20
Output
Yes
Input
2 3
5
1 1 0
1 2 10
1 3 20
2 1 30
2 3 40
Output
No
Input
2 2
3
1 1 20
1 2 10
2 1 0
Output
No
Input
3 3
4
1 1 0
1 3 10
3 1 10
3 3 20
Output
Yes
Input
2 2
4
1 1 0
1 2 10
2 1 30
2 2 20
Output
No | instruction | 0 | 90,829 | 23 | 181,658 |
"Correct Solution:
```
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
R,C = map(int,input().split())
N = int(input())
RCA = [tuple(int(x) for x in input().split()) for _ in range(N)]
# 二部グラフ
graph = [[] for _ in range(R+C)]
for r,c,a in RCA:
graph[r-1].append((R+c-1,a))
graph[R+c-1].append((r-1,a))
graph
# グラフの頂点に値を割り当てて、頂点の重みの和が辺の重みになるようにする。
wt_temp = [None] * (R+C)
wt = [None] * (R+C)
for x in range(R+C):
if wt_temp[x] is not None:
continue
wt_temp[x] = 0
min_wt_row = 0
q = [x]
while q:
y = q.pop()
for z,a in graph[y]:
if wt_temp[z] is not None:
continue
wt_temp[z] = a - wt_temp[y]
q.append(z)
if z<R and min_wt_row > wt_temp[z]:
min_wt_row = wt_temp[z]
wt[x] = -min_wt_row
q = [x]
while q:
y = q.pop()
for z,a in graph[y]:
if wt[z] is not None:
continue
wt[z] = a - wt[y]
q.append(z)
bl = True
if any(x<0 for x in wt):
bl = False
for r,c,a in RCA:
if wt[r-1] + wt[R+c-1] != a:
bl = False
answer = 'Yes' if bl else 'No'
print(answer)
``` | output | 1 | 90,829 | 23 | 181,659 |
Provide a correct Python 3 solution for this coding contest problem.
There is a grid with R rows and C columns. We call the cell in the r-th row and c-th column (r,c).
Mr. Takahashi wrote non-negative integers into N of the cells, that is, he wrote a non-negative integer a_i into (r_i,c_i) for each i (1≤i≤N). After that he fell asleep.
Mr. Aoki found the grid and tries to surprise Mr. Takahashi by writing integers into all remaining cells. The grid must meet the following conditions to really surprise Mr. Takahashi.
* Condition 1: Each cell contains a non-negative integer.
* Condition 2: For any 2×2 square formed by cells on the grid, the sum of the top left and bottom right integers must always equal to the sum of the top right and bottom left integers.
Determine whether it is possible to meet those conditions by properly writing integers into all remaining cells.
Constraints
* 2≤R,C≤10^5
* 1≤N≤10^5
* 1≤r_i≤R
* 1≤c_i≤C
* (r_i,c_i) ≠ (r_j,c_j) (i≠j)
* a_i is an integer.
* 0≤a_i≤10^9
Input
The input is given from Standard Input in the following format:
R C
N
r_1 c_1 a_1
r_2 c_2 a_2
:
r_N c_N a_N
Output
Print `Yes` if it is possible to meet the conditions by properly writing integers into all remaining cells. Otherwise, print `No`.
Examples
Input
2 2
3
1 1 0
1 2 10
2 1 20
Output
Yes
Input
2 3
5
1 1 0
1 2 10
1 3 20
2 1 30
2 3 40
Output
No
Input
2 2
3
1 1 20
1 2 10
2 1 0
Output
No
Input
3 3
4
1 1 0
1 3 10
3 1 10
3 3 20
Output
Yes
Input
2 2
4
1 1 0
1 2 10
2 1 30
2 2 20
Output
No | instruction | 0 | 90,830 | 23 | 181,660 |
"Correct Solution:
```
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")
h,w = list(map(int, input().split()))
n = int(input())
from collections import defaultdict
mind = [10**15] * h
dw = defaultdict(list)
for i in range(n):
r,c,a = map(int, input().split())
r -= 1
c -= 1
mind[r] = min(mind[r], a)
dw[c].append((a,r))
# 0未満になる要素があるか判定
es = [[] for _ in range(h)]
def main():
ans = True
for c in range(w):
if len(dw[c])<=1:
continue
dw[c].sort()
tmp = 0
for i in range(len(dw[c])-1):
u = dw[c][i][1]
v = dw[c][i+1][1]
val = dw[c][i+1][0] - dw[c][i][0]
es[u].append((val, v))
es[v].append((-val, u))
tmp += val
if mind[v]<tmp:
return False
# print(es)
# print(dw)
vals = [None]*h
for start in range(h):
if vals[start] is not None:
continue
q = [start]
vals[start] = 0
l = [(0, mind[start])]
while q:
u = q.pop()
for d,v in es[u]:
if vals[v] is None:
vals[v] = vals[u] + d
l.append((vals[v], mind[v]))
q.append(v)
elif vals[v]!=vals[u]+d:
return False
l.sort()
for i in range(len(l)):
if l[i][1]<l[i][0]-l[0][0]:
return False
# for u in range(h):
# for d,v in es[u]:
# if vals[u]+d!=vals[v]:
# return False
return True
ans = main()
if ans:
print("Yes")
else:
print("No")
``` | output | 1 | 90,830 | 23 | 181,661 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.