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 |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other.
Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible.
Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length
<image> The picture corresponds to the first example
Input
The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles.
n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle.
It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other.
Output
Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color.
Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle.
Example
Input
8
0 0 5 3
2 -1 5 0
-3 -4 2 -1
-1 -1 2 0
-3 0 0 5
5 2 10 3
7 -3 10 2
4 -2 7 -1
Output
YES
1
2
2
3
2
2
4
1 | instruction | 0 | 91,339 | 23 | 182,678 |
Tags: constructive algorithms, geometry
Correct Solution:
```
n = int(input())
print('YES')
for _ in range(n):
x1,y1,x2,y2 = [int(el) for el in input().split()]
print(x1%2+(y1%2)*2+1)
``` | output | 1 | 91,339 | 23 | 182,679 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other.
Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible.
Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length
<image> The picture corresponds to the first example
Input
The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles.
n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle.
It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other.
Output
Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color.
Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle.
Example
Input
8
0 0 5 3
2 -1 5 0
-3 -4 2 -1
-1 -1 2 0
-3 0 0 5
5 2 10 3
7 -3 10 2
4 -2 7 -1
Output
YES
1
2
2
3
2
2
4
1 | instruction | 0 | 91,340 | 23 | 182,680 |
Tags: constructive algorithms, geometry
Correct Solution:
```
n = int(input())
ans = 'YES\n'
for i in range(n):
x1, y1, x2, y2 = map(int, input().split())
res = (x1 & 1) * 2 + (y1 & 1) + 1
ans += str(res) + '\n'
print(ans)
``` | output | 1 | 91,340 | 23 | 182,681 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other.
Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible.
Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length
<image> The picture corresponds to the first example
Input
The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles.
n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle.
It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other.
Output
Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color.
Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle.
Example
Input
8
0 0 5 3
2 -1 5 0
-3 -4 2 -1
-1 -1 2 0
-3 0 0 5
5 2 10 3
7 -3 10 2
4 -2 7 -1
Output
YES
1
2
2
3
2
2
4
1
Submitted Solution:
```
from sys import stdin,stdout
n = int(stdin.readline())
a = [0 for i in range(n)]
for i in range(n):
inp = stdin.readline().split()
x = int(inp[0])
y = int(inp[1])
a[i] = 2 * (x % 2) + (y % 2) + 1
stdout.write("YES")
stdout.write('\n')
stdout.write("\n".join(str(i) for i in a))
``` | instruction | 0 | 91,341 | 23 | 182,682 |
Yes | output | 1 | 91,341 | 23 | 182,683 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other.
Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible.
Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length
<image> The picture corresponds to the first example
Input
The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles.
n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle.
It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other.
Output
Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color.
Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle.
Example
Input
8
0 0 5 3
2 -1 5 0
-3 -4 2 -1
-1 -1 2 0
-3 0 0 5
5 2 10 3
7 -3 10 2
4 -2 7 -1
Output
YES
1
2
2
3
2
2
4
1
Submitted Solution:
```
n = int(input())
rectangles = []
for i in range(n):
a, b, c, d = tuple(map(int,input().split()))
rectangles.append((a,b))
print("YES")
for i in range(n):
a,b = rectangles[i][0], rectangles[i][1]
if a%2 == 0 and b%2 == 0:
print(1)
elif a%2 == 0 and b%2 == 1:
print(2)
elif a%2 == 1 and b%2 == 0:
print(3)
else:
print(4)
``` | instruction | 0 | 91,342 | 23 | 182,684 |
Yes | output | 1 | 91,342 | 23 | 182,685 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other.
Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible.
Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length
<image> The picture corresponds to the first example
Input
The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles.
n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle.
It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other.
Output
Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color.
Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle.
Example
Input
8
0 0 5 3
2 -1 5 0
-3 -4 2 -1
-1 -1 2 0
-3 0 0 5
5 2 10 3
7 -3 10 2
4 -2 7 -1
Output
YES
1
2
2
3
2
2
4
1
Submitted Solution:
```
p = int(input())
print("YES")
for i in range(p):
a, b, c, d = [abs(int(i)) for i in input().split()]
if a % 2 == 0:
print("1" if b % 2 == 0 else "2")
else:
print("3" if b % 2 == 0 else "4")
``` | instruction | 0 | 91,343 | 23 | 182,686 |
Yes | output | 1 | 91,343 | 23 | 182,687 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other.
Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible.
Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length
<image> The picture corresponds to the first example
Input
The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles.
n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle.
It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other.
Output
Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color.
Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle.
Example
Input
8
0 0 5 3
2 -1 5 0
-3 -4 2 -1
-1 -1 2 0
-3 0 0 5
5 2 10 3
7 -3 10 2
4 -2 7 -1
Output
YES
1
2
2
3
2
2
4
1
Submitted Solution:
```
n=int(input())
print("YES")
while n:
(x,y,a,b)=list(map(int, input().split()))
print(1+x%2+2*(y%2))
n=n-1
# Made By Mostafa_Khaled
``` | instruction | 0 | 91,344 | 23 | 182,688 |
Yes | output | 1 | 91,344 | 23 | 182,689 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other.
Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible.
Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length
<image> The picture corresponds to the first example
Input
The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles.
n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle.
It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other.
Output
Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color.
Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle.
Example
Input
8
0 0 5 3
2 -1 5 0
-3 -4 2 -1
-1 -1 2 0
-3 0 0 5
5 2 10 3
7 -3 10 2
4 -2 7 -1
Output
YES
1
2
2
3
2
2
4
1
Submitted Solution:
```
n = int(input())
arr = [[] for i in range(n)]
ans = [0 for i in range(n)]
for i in range(n):
x, y, xx, yy = map(int, input().split())
arr[i] = ((x * x + y * y) ** 0.5, y, xx, yy, i)
arr.sort()
print("YES")
for i in range(n):
ans[arr[i][4]] = i % 4 + 1
print(*ans, sep='\n')
``` | instruction | 0 | 91,345 | 23 | 182,690 |
No | output | 1 | 91,345 | 23 | 182,691 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other.
Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible.
Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length
<image> The picture corresponds to the first example
Input
The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles.
n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle.
It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other.
Output
Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color.
Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle.
Example
Input
8
0 0 5 3
2 -1 5 0
-3 -4 2 -1
-1 -1 2 0
-3 0 0 5
5 2 10 3
7 -3 10 2
4 -2 7 -1
Output
YES
1
2
2
3
2
2
4
1
Submitted Solution:
```
n = int(input())
arr = [[] for i in range(n)]
ans = [0 for i in range(n)]
for i in range(n):
x, y, xx, yy = map(int, input().split())
arr[i] = (y, x, yy, xx, i)
arr.sort()
print("YES")
for i in range(n):
ans[arr[i][4]] = i % 4 + 1
print(*ans, sep='\n')
``` | instruction | 0 | 91,346 | 23 | 182,692 |
No | output | 1 | 91,346 | 23 | 182,693 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other.
Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible.
Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length
<image> The picture corresponds to the first example
Input
The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles.
n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle.
It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other.
Output
Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color.
Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle.
Example
Input
8
0 0 5 3
2 -1 5 0
-3 -4 2 -1
-1 -1 2 0
-3 0 0 5
5 2 10 3
7 -3 10 2
4 -2 7 -1
Output
YES
1
2
2
3
2
2
4
1
Submitted Solution:
```
from sys import stdin,stdout
n = int(stdin.readline())
stdout.write("YES")
for i in range(n):
x1, y1, x2, y2 = map(int,stdin.readline().split())
stdout.write(str((x1 % 2) * 2 + (y1 % 2) + 1))
stdout.write('\n')
``` | instruction | 0 | 91,347 | 23 | 182,694 |
No | output | 1 | 91,347 | 23 | 182,695 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other.
Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible.
Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length
<image> The picture corresponds to the first example
Input
The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles.
n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle.
It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other.
Output
Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color.
Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle.
Example
Input
8
0 0 5 3
2 -1 5 0
-3 -4 2 -1
-1 -1 2 0
-3 0 0 5
5 2 10 3
7 -3 10 2
4 -2 7 -1
Output
YES
1
2
2
3
2
2
4
1
Submitted Solution:
```
for _ in range(int(input())):
a,b,c,d = map(int, input().split())
print(1 + a%2 + 2*(b%2))
``` | instruction | 0 | 91,348 | 23 | 182,696 |
No | output | 1 | 91,348 | 23 | 182,697 |
Provide a correct Python 3 solution for this coding contest problem.
Find the area of intersection between a circle $c$ and a polygon $g$. The center coordinate of the circle is ($0, 0$).
The polygon $g$ is represented by a sequence of points $p_1$, $p_2$,..., $p_n$ where line segments connecting $p_i$ and $p_{i+1}$ ($1 \leq i \leq n−1$) are sides of the polygon. The line segment connecting $p_n$ and $p_1$ is also a side of the polygon.
Note that the polygon is not necessarily convex.
Constraints
* $3 \leq n \leq 100$
* $1 \leq r \leq 100$
* $-100 \leq x_i, y_i \leq 100$
Input
The input is given in the following format.
$n$ $r$
$x_1$ $y_1$
$x_2$ $y_2$
:
$x_n$ $y_n$
In the first line, an integer n representing the number of points in the polygon is given. The coordinate of a point $p_i$ is given by two integers $x_i$ and $y_i$. The coordinates of the points are given in the order of counter-clockwise visit of them. All input values are given in integers.
Output
Print the area of intersection in a line. The output values should be in a decimal fraction with an error less than 0.00001.
Examples
Input
3 5
1 1
4 1
5 5
Output
4.639858417607
Input
4 5
0 0
-3 -6
1 -3
5 -4
Output
11.787686807576 | instruction | 0 | 91,706 | 23 | 183,412 |
"Correct Solution:
```
from math import acos, hypot, isclose, sqrt
from typing import List, Tuple
def intersection(circle: Tuple[int, int, int],
polygon: List[Tuple[float, float]]) -> float:
x, y, r = circle
area = 0.0
for p1, p2 in zip(polygon, polygon[1:] + [polygon[0]]):
ps = seg_intersection(circle, (p1, p2))
for pp1, pp2 in zip([p1] + ps, ps + [p2]):
c = cross(pp1, pp2)
if c == 0:
continue
d1 = hypot(*pp1)
d2 = hypot(*pp2)
if le(d1, r) and le(d2, r):
area += c / 2
else:
t = acos(dot(pp1, pp2) / (d1 * d2))
sign = c // abs(c)
area += sign * r * r * t / 2
return area
def cross(v1: Tuple[float, float], v2: Tuple[float, float]) -> float:
x1, y1 = v1
x2, y2 = v2
return x1 * y2 - x2 * y1
def dot(v1: Tuple[float, float], v2: Tuple[float, float]) -> float:
x1, y1 = v1
x2, y2 = v2
return x1 * x2 + y1 * y2
def seg_intersection(circle: Tuple[int, int, int],
seg: Tuple[Tuple[float, float],
Tuple[float, float]]) -> List[Tuple[float, float]]:
x0, y0, r = circle
p1, p2 = seg
x1, y1 = p1
x2, y2 = p2
p1p2 = (x2 - x1) ** 2 + (y2 - y1) ** 2
op1 = (x1 - x0) ** 2 + (y1 - y0) ** 2
rr = r * r
dp = dot((x1 - x0, y1 - y0), (x2 - x1, y2 - y1))
d = dp * dp - p1p2 * (op1 - rr)
ps = []
if isclose(d, 0.0, abs_tol=1e-9):
t = - dp / p1p2
if ge(t, 0.0) and le(t, 1.0):
ps.append((x1 + t * (x2 - x1), y1 + t * (y2 - y1)))
elif d > 0.0:
t1 = (- dp - sqrt(d)) / p1p2
if ge(t1, 0.0) and le(t1, 1.0):
ps.append((x1 + t1 * (x2 - x1), y1 + t1 * (y2 - y1)))
t2 = (- dp + sqrt(d)) / p1p2
if ge(t2, 0.0) and le(t2, 1.0):
ps.append((x1 + t2 * (x2 - x1), y1 + t2 * (y2 - y1)))
return ps
def le(f1: float, f2: float) -> bool:
return f1 < f2 or isclose(f1, f2, abs_tol=1e-9)
def ge(f1: float, f2: float) -> bool:
return f1 > f2 or isclose(f1, f2, abs_tol=1e-9)
if __name__ == "__main__":
n, r = [int(i) for i in input().split()]
ps: List[Tuple[float, float]] = []
for _ in range(n):
x, y = map(lambda x: float(x), input().split())
ps.append((x, y))
print("{:.6f}".format(intersection((0, 0, r), ps)))
``` | output | 1 | 91,706 | 23 | 183,413 |
Provide a correct Python 3 solution for this coding contest problem.
Find the area of intersection between a circle $c$ and a polygon $g$. The center coordinate of the circle is ($0, 0$).
The polygon $g$ is represented by a sequence of points $p_1$, $p_2$,..., $p_n$ where line segments connecting $p_i$ and $p_{i+1}$ ($1 \leq i \leq n−1$) are sides of the polygon. The line segment connecting $p_n$ and $p_1$ is also a side of the polygon.
Note that the polygon is not necessarily convex.
Constraints
* $3 \leq n \leq 100$
* $1 \leq r \leq 100$
* $-100 \leq x_i, y_i \leq 100$
Input
The input is given in the following format.
$n$ $r$
$x_1$ $y_1$
$x_2$ $y_2$
:
$x_n$ $y_n$
In the first line, an integer n representing the number of points in the polygon is given. The coordinate of a point $p_i$ is given by two integers $x_i$ and $y_i$. The coordinates of the points are given in the order of counter-clockwise visit of them. All input values are given in integers.
Output
Print the area of intersection in a line. The output values should be in a decimal fraction with an error less than 0.00001.
Examples
Input
3 5
1 1
4 1
5 5
Output
4.639858417607
Input
4 5
0 0
-3 -6
1 -3
5 -4
Output
11.787686807576 | instruction | 0 | 91,707 | 23 | 183,414 |
"Correct Solution:
```
#!/usr/bin/env python3
# CGL_7_H: Circles - Intersection of a Circle and a Polygon
from math import acos, hypot, isclose, sqrt
def intersection(circle, polygon):
x, y, r = circle
area = 0.0
for p1, p2 in zip(polygon, polygon[1:]+[polygon[0]]):
ps = seg_intersection(circle, (p1, p2))
for pp1, pp2 in zip([p1] + ps, ps + [p2]):
c = cross(pp1, pp2)
if c == 0:
continue
d1 = hypot(*pp1)
d2 = hypot(*pp2)
if le(d1, r) and le(d2, r):
area += c / 2
else:
t = acos(dot(pp1, pp2) / (d1 * d2))
sign = c // abs(c)
area += sign * r * r * t / 2
return area
def cross(v1, v2):
x1, y1 = v1
x2, y2 = v2
return x1*y2 - x2*y1
def dot(v1, v2):
x1, y1 = v1
x2, y2 = v2
return x1*x2 + y1*y2
def seg_intersection(circle, seg):
x0, y0, r = circle
p1, p2 = seg
x1, y1 = p1
x2, y2 = p2
p1p2 = (x2-x1)**2 + (y2-y1)**2
op1 = (x1-x0)**2 + (y1-y0)**2
rr = r*r
dp = dot((x1-x0, y1-y0), (x2-x1, y2-y1))
d = dp*dp - p1p2*(op1 - rr)
ps = []
if isclose(d, 0.0, abs_tol=1e-9):
t = -dp / p1p2
if ge(t, 0.0) and le(t, 1.0):
ps.append((x1 + t*(x2-x1), y1 + t*(y2-y1)))
elif d > 0.0:
t1 = (-dp-sqrt(d)) / p1p2
if ge(t1, 0.0) and le(t1, 1.0):
ps.append((x1 + t1*(x2-x1), y1 + t1*(y2-y1)))
t2 = (-dp+sqrt(d)) / p1p2
if ge(t2, 0.0) and le(t2, 1.0):
ps.append((x1 + t2*(x2-x1), y1 + t2*(y2-y1)))
# assert all(isclose(r, hypot(x, y)) for x, y in ps)
return ps
def le(f1, f2):
return f1 < f2 or isclose(f1, f2, abs_tol=1e-9)
def ge(f1, f2):
return f1 > f2 or isclose(f1, f2, abs_tol=1e-9)
def eliminate_minus_zero(f):
if isclose(f, 0.0, abs_tol=1e-9):
return 0.0
else:
return f
def run():
n, r = [int(i) for i in input().split()]
ps = []
for _ in range(n):
x, y = [int(i) for i in input().split()]
ps.append((x, y))
print("{:.10f}".format(eliminate_minus_zero(intersection((0, 0, r), ps))))
if __name__ == '__main__':
run()
``` | output | 1 | 91,707 | 23 | 183,415 |
Provide a correct Python 3 solution for this coding contest problem.
Find the area of intersection between a circle $c$ and a polygon $g$. The center coordinate of the circle is ($0, 0$).
The polygon $g$ is represented by a sequence of points $p_1$, $p_2$,..., $p_n$ where line segments connecting $p_i$ and $p_{i+1}$ ($1 \leq i \leq n−1$) are sides of the polygon. The line segment connecting $p_n$ and $p_1$ is also a side of the polygon.
Note that the polygon is not necessarily convex.
Constraints
* $3 \leq n \leq 100$
* $1 \leq r \leq 100$
* $-100 \leq x_i, y_i \leq 100$
Input
The input is given in the following format.
$n$ $r$
$x_1$ $y_1$
$x_2$ $y_2$
:
$x_n$ $y_n$
In the first line, an integer n representing the number of points in the polygon is given. The coordinate of a point $p_i$ is given by two integers $x_i$ and $y_i$. The coordinates of the points are given in the order of counter-clockwise visit of them. All input values are given in integers.
Output
Print the area of intersection in a line. The output values should be in a decimal fraction with an error less than 0.00001.
Examples
Input
3 5
1 1
4 1
5 5
Output
4.639858417607
Input
4 5
0 0
-3 -6
1 -3
5 -4
Output
11.787686807576 | instruction | 0 | 91,708 | 23 | 183,416 |
"Correct Solution:
```
import cmath
import itertools
import math
from collections import defaultdict
INF = float("inf")
PI = cmath.pi
TAU = cmath.pi * 2
EPS = 1e-10
class Point:
"""
2次元空間上の点
"""
# 反時計回り側にある
CCW_COUNTER_CLOCKWISE = 1
# 時計回り側にある
CCW_CLOCKWISE = -1
# 線分の後ろにある
CCW_ONLINE_BACK = 2
# 線分の前にある
CCW_ONLINE_FRONT = -2
# 線分上にある
CCW_ON_SEGMENT = 0
def __init__(self, x: float, y: float):
self.c = complex(x, y)
@property
def x(self):
return self.c.real
@property
def y(self):
return self.c.imag
@staticmethod
def from_complex(c: complex):
return Point(c.real, c.imag)
@staticmethod
def from_polar(r: float, phi: float):
c = cmath.rect(r, phi)
return Point(c.real, c.imag)
def __add__(self, p):
"""
:param Point p:
"""
c = self.c + p.c
return Point(c.real, c.imag)
def __iadd__(self, p):
"""
:param Point p:
"""
self.c += p.c
return self
def __sub__(self, p):
"""
:param Point p:
"""
c = self.c - p.c
return Point(c.real, c.imag)
def __isub__(self, p):
"""
:param Point p:
"""
self.c -= p.c
return self
def __mul__(self, f: float):
c = self.c * f
return Point(c.real, c.imag)
def __imul__(self, f: float):
self.c *= f
return self
def __truediv__(self, f: float):
c = self.c / f
return Point(c.real, c.imag)
def __itruediv__(self, f: float):
self.c /= f
return self
def __repr__(self):
return "({}, {})".format(round(self.x, 10), round(self.y, 10))
def __neg__(self):
c = -self.c
return Point(c.real, c.imag)
def __eq__(self, p):
return abs(self.c - p.c) < EPS
def __abs__(self):
return abs(self.c)
@staticmethod
def ccw(a, b, c):
"""
線分 ab に対する c の位置
線分上にあるか判定するだけなら on_segment とかのが速い
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_C&lang=ja
:param Point a:
:param Point b:
:param Point c:
"""
b = b - a
c = c - a
det = b.det(c)
if det > EPS:
return Point.CCW_COUNTER_CLOCKWISE
if det < -EPS:
return Point.CCW_CLOCKWISE
if b.dot(c) < -EPS:
return Point.CCW_ONLINE_BACK
if c.norm() - b.norm() > EPS:
return Point.CCW_ONLINE_FRONT
return Point.CCW_ON_SEGMENT
def dot(self, p):
"""
内積
:param Point p:
:rtype: float
"""
return self.x * p.x + self.y * p.y
def det(self, p):
"""
外積
:param Point p:
:rtype: float
"""
return self.x * p.y - self.y * p.x
def dist(self, p):
"""
距離
:param Point p:
:rtype: float
"""
return abs(self.c - p.c)
def norm(self):
"""
原点からの距離
:rtype: float
"""
return abs(self.c)
def phase(self):
"""
原点からの角度
:rtype: float
"""
return cmath.phase(self.c)
def angle(self, p, q):
"""
p に向いてる状態から q まで反時計回りに回転するときの角度
-pi <= ret <= pi
:param Point p:
:param Point q:
:rtype: float
"""
return (cmath.phase(q.c - self.c) - cmath.phase(p.c - self.c) + PI) % TAU - PI
def area(self, p, q):
"""
p, q となす三角形の面積
:param Point p:
:param Point q:
:rtype: float
"""
return abs((p - self).det(q - self) / 2)
def projection_point(self, p, q, allow_outer=False):
"""
線分 pq を通る直線上に垂線をおろしたときの足の座標
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_A&lang=ja
:param Point p:
:param Point q:
:param allow_outer: 答えが線分の間になくても OK
:rtype: Point|None
"""
diff_q = q - p
# 答えの p からの距離
r = (self - p).dot(diff_q) / abs(diff_q)
# 線分の角度
phase = diff_q.phase()
ret = Point.from_polar(r, phase) + p
if allow_outer or (p - ret).dot(q - ret) < EPS:
return ret
return None
def reflection_point(self, p, q):
"""
直線 pq を挟んで反対にある点
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_B&lang=ja
:param Point p:
:param Point q:
:rtype: Point
"""
# 距離
r = abs(self - p)
# pq と p-self の角度
angle = p.angle(q, self)
# 直線を挟んで角度を反対にする
angle = (q - p).phase() - angle
return Point.from_polar(r, angle) + p
def on_segment(self, p, q, allow_side=True):
"""
点が線分 pq の上に乗っているか
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_C&lang=ja
:param Point p:
:param Point q:
:param allow_side: 端っこでギリギリ触れているのを許容するか
:rtype: bool
"""
if not allow_side and (self == p or self == q):
return False
# 外積がゼロ: 面積がゼロ == 一直線
# 内積がマイナス: p - self - q の順に並んでる
return abs((p - self).det(q - self)) < EPS and (p - self).dot(q - self) < EPS
class Line:
"""
2次元空間上の直線
"""
def __init__(self, a: float, b: float, c: float):
"""
直線 ax + by + c = 0
"""
self.a = a
self.b = b
self.c = c
@staticmethod
def from_gradient(grad: float, intercept: float):
"""
直線 y = ax + b
:param grad: 傾き
:param intercept: 切片
:return:
"""
return Line(grad, -1, intercept)
@staticmethod
def from_segment(p1, p2):
"""
:param Point p1:
:param Point p2:
"""
a = p2.y - p1.y
b = p1.x - p2.x
c = p2.y * (p2.x - p1.x) - p2.x * (p2.y - p1.y)
return Line(a, b, c)
@property
def gradient(self):
"""
傾き
"""
return INF if self.b == 0 else -self.a / self.b
@property
def intercept(self):
"""
切片
"""
return INF if self.b == 0 else -self.c / self.b
def is_parallel_to(self, l):
"""
平行かどうか
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A&lang=ja
:param Line l:
"""
# 法線ベクトル同士の外積がゼロ
return abs(Point.from_rect(self.a, self.b).det(Point.from_rect(l.a, l.b))) < EPS
def is_orthogonal_to(self, l):
"""
直行しているかどうか
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A&lang=ja
:param Line l:
"""
# 法線ベクトル同士の内積がゼロ
return abs(Point.from_rect(self.a, self.b).dot(Point.from_rect(l.a, l.b))) < EPS
def intersection_point(self, l):
"""
交差する点
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_C&lang=ja
:param Line l:
:rtype: Point|None
"""
a1, b1, c1 = self.a, self.b, self.c
a2, b2, c2 = l.a, l.b, l.c
det = a1 * b2 - a2 * b1
if abs(det) < EPS:
# 並行
return None
x = (b1 * c2 - b2 * c1) / det
y = (a2 * c1 - a1 * c2) / det
return Point.from_rect(x, y)
def dist(self, p):
"""
他の点との最短距離
:param Point p:
"""
raise NotImplementedError()
def has_point(self, p):
"""
p が直線上に乗っているかどうか
:param Point p:
"""
return abs(self.a * p.x + self.b * p.y + self.c) < EPS
class Segment:
"""
2次元空間上の線分
"""
def __init__(self, p1, p2):
"""
:param Point p1:
:param Point p2:
"""
self.p1 = p1
self.p2 = p2
def norm(self):
"""
線分の長さ
"""
return abs(self.p1 - self.p2)
def phase(self):
"""
p1 を原点としたときの p2 の角度
"""
return (self.p2 - self.p1).phase()
def is_parallel_to(self, s):
"""
平行かどうか
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A&lang=ja
:param Segment s:
:return:
"""
# 外積がゼロ
return abs((self.p1 - self.p2).det(s.p1 - s.p2)) < EPS
def is_orthogonal_to(self, s):
"""
直行しているかどうか
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A&lang=ja
:param Segment s:
:return:
"""
# 内積がゼロ
return abs((self.p1 - self.p2).dot(s.p1 - s.p2)) < EPS
def intersects_with(self, s, allow_side=True):
"""
交差するかどうか
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_B&lang=ja
:param Segment s:
:param allow_side: 端っこでギリギリ触れているのを許容するか
"""
if self.is_parallel_to(s):
# 並行なら線分の端点がもう片方の線分の上にあるかどうか
return (s.p1.on_segment(self.p1, self.p2, allow_side) or
s.p2.on_segment(self.p1, self.p2, allow_side) or
self.p1.on_segment(s.p1, s.p2, allow_side) or
self.p2.on_segment(s.p1, s.p2, allow_side))
else:
# allow_side ならゼロを許容する
det_upper = EPS if allow_side else -EPS
ok = True
# self の両側に s.p1 と s.p2 があるか
ok &= (self.p2 - self.p1).det(s.p1 - self.p1) * (self.p2 - self.p1).det(s.p2 - self.p1) < det_upper
# s の両側に self.p1 と self.p2 があるか
ok &= (s.p2 - s.p1).det(self.p1 - s.p1) * (s.p2 - s.p1).det(self.p2 - s.p1) < det_upper
return ok
def closest_point(self, p):
"""
線分上の、p に最も近い点
:param Point p:
"""
# p からおろした垂線までの距離
d = (p - self.p1).dot(self.p2 - self.p1) / self.norm()
# p1 より前
if d < EPS:
return self.p1
# p2 より後
if -EPS < d - self.norm():
return self.p2
# 線分上
return Point.from_polar(d, (self.p2 - self.p1).phase()) + self.p1
def dist(self, p):
"""
他の点との最短距離
:param Point p:
"""
return abs(p - self.closest_point(p))
def dist_segment(self, s):
"""
他の線分との最短距離
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_D&lang=ja
:param Segment s:
"""
if self.intersects_with(s):
return 0.0
return min(
self.dist(s.p1),
self.dist(s.p2),
s.dist(self.p1),
s.dist(self.p2),
)
def has_point(self, p, allow_side=True):
"""
p が線分上に乗っているかどうか
:param Point p:
:param allow_side: 端っこでギリギリ触れているのを許容するか
"""
return p.on_segment(self.p1, self.p2, allow_side=allow_side)
class Polygon:
"""
2次元空間上の多角形
"""
def __init__(self, points):
"""
:param list of Point points:
"""
self.points = points
def iter2(self):
"""
隣り合う2点を順に返すイテレータ
:rtype: typing.Iterator[(Point, Point)]
"""
return zip(self.points, self.points[1:] + self.points[:1])
def iter3(self):
"""
隣り合う3点を順に返すイテレータ
:rtype: typing.Iterator[(Point, Point, Point)]
"""
return zip(self.points,
self.points[1:] + self.points[:1],
self.points[2:] + self.points[:2])
def area(self):
"""
面積
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_A&lang=ja
"""
# 外積の和 / 2
dets = []
for p, q in self.iter2():
dets.append(p.det(q))
return abs(math.fsum(dets)) / 2
def is_convex(self, allow_straight=False, allow_collapsed=False):
"""
凸多角形かどうか
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_B&lang=ja
:param allow_straight: 3点がまっすぐ並んでるのを許容するかどうか
:param allow_collapsed: 面積がゼロの場合を許容するか
"""
ccw = []
for a, b, c in self.iter3():
ccw.append(Point.ccw(a, b, c))
ccw = set(ccw)
if len(ccw) == 1:
if ccw == {Point.CCW_CLOCKWISE}:
return True
if ccw == {Point.CCW_COUNTER_CLOCKWISE}:
return True
if allow_straight and len(ccw) == 2:
if ccw == {Point.CCW_ONLINE_FRONT, Point.CCW_CLOCKWISE}:
return True
if ccw == {Point.CCW_ONLINE_FRONT, Point.CCW_COUNTER_CLOCKWISE}:
return True
if allow_collapsed and len(ccw) == 3:
return ccw == {Point.CCW_ONLINE_FRONT, Point.CCW_ONLINE_BACK, Point.CCW_ON_SEGMENT}
return False
def has_point_on_edge(self, p):
"""
指定した点が辺上にあるか
:param Point p:
:rtype: bool
"""
for a, b in self.iter2():
if p.on_segment(a, b):
return True
return False
def contains(self, p, allow_on_edge=True):
"""
指定した点を含むか
Winding Number Algorithm
https://www.nttpc.co.jp/technology/number_algorithm.html
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_C&lang=ja
:param Point p:
:param bool allow_on_edge: 辺上の点を許容するか
"""
angles = []
for a, b in self.iter2():
if p.on_segment(a, b):
return allow_on_edge
angles.append(p.angle(a, b))
# 一周以上するなら含む
return abs(math.fsum(angles)) > EPS
@staticmethod
def convex_hull(points, allow_straight=False):
"""
凸包。x が最も小さい点のうち y が最も小さい点から反時計回り。
Graham Scan O(N log N)
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_A&lang=ja
:param list of Point points:
:param allow_straight: 3点がまっすぐ並んでるのを許容するかどうか
:rtype: list of Point
"""
points = points[:]
points.sort(key=lambda p: (p.x, p.y))
# allow_straight なら 0 を許容する
det_lower = -EPS if allow_straight else EPS
sz = 0
#: :type: list of (Point|None)
ret = [None] * (len(points) * 2)
for p in points:
while sz > 1 and (ret[sz - 1] - ret[sz - 2]).det(p - ret[sz - 1]) < det_lower:
sz -= 1
ret[sz] = p
sz += 1
floor = sz
for p in reversed(points[:-1]):
while sz > floor and (ret[sz - 1] - ret[sz - 2]).det(p - ret[sz - 1]) < det_lower:
sz -= 1
ret[sz] = p
sz += 1
ret = ret[:sz - 1]
if allow_straight and len(ret) > len(points):
# allow_straight かつ全部一直線のときに二重にカウントしちゃう
ret = points
return ret
@staticmethod
def diameter(points):
"""
直径
凸包構築 O(N log N) + カリパー法 O(N)
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_B&lang=ja
:param list of Point points:
"""
# 反時計回り
points = Polygon.convex_hull(points, allow_straight=False)
if len(points) == 1:
return 0.0
if len(points) == 2:
return abs(points[0] - points[1])
# x軸方向に最も遠い点対
si = points.index(min(points, key=lambda p: (p.x, p.y)))
sj = points.index(max(points, key=lambda p: (p.x, p.y)))
n = len(points)
ret = 0.0
# 半周回転
i, j = si, sj
while i != sj or j != si:
ret = max(ret, abs(points[i] - points[j]))
ni = (i + 1) % n
nj = (j + 1) % n
# 2つの辺が並行になる方向にずらす
if (points[ni] - points[i]).det(points[nj] - points[j]) > 0:
j = nj
else:
i = ni
return ret
def convex_cut_by_line(self, line_p1, line_p2):
"""
凸多角形を直線 line_p1-line_p2 でカットする。
凸じゃないといけません
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_C&lang=ja
:param line_p1:
:param line_p2:
:return: (line_p1-line_p2 の左側の多角形, line_p1-line_p2 の右側の多角形)
:rtype: (Polygon|None, Polygon|None)
"""
n = len(self.points)
line = Line.from_segment(line_p1, line_p2)
# 直線と重なる点
on_line_points = []
for i, p in enumerate(self.points):
if line.has_point(p):
on_line_points.append(i)
# 辺が直線上にある
has_on_line_edge = False
if len(on_line_points) >= 3:
has_on_line_edge = True
elif len(on_line_points) == 2:
# 直線上にある点が隣り合ってる
has_on_line_edge = abs(on_line_points[0] - on_line_points[1]) in [1, n - 1]
# 辺が直線上にある場合、どっちか片方に全部ある
if has_on_line_edge:
for p in self.points:
ccw = Point.ccw(line_p1, line_p2, p)
if ccw == Point.CCW_COUNTER_CLOCKWISE:
return Polygon(self.points[:]), None
if ccw == Point.CCW_CLOCKWISE:
return None, Polygon(self.points[:])
ret_lefts = []
ret_rights = []
d = line_p2 - line_p1
for p, q in self.iter2():
det_p = d.det(p - line_p1)
det_q = d.det(q - line_p1)
if det_p > -EPS:
ret_lefts.append(p)
if det_p < EPS:
ret_rights.append(p)
# 外積の符号が違う == 直線の反対側にある場合は交点を追加
if det_p * det_q < -EPS:
intersection = line.intersection_point(Line.from_segment(p, q))
ret_lefts.append(intersection)
ret_rights.append(intersection)
# 点のみの場合を除いて返す
l = Polygon(ret_lefts) if len(ret_lefts) > 1 else None
r = Polygon(ret_rights) if len(ret_rights) > 1 else None
return l, r
def closest_pair(points):
"""
最近点対 O(N log N)
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_5_A&lang=ja
:param list of Point points:
:rtype: (float, (Point, Point))
:return: (距離, 点対)
"""
assert len(points) >= 2
def _rec(xsorted):
"""
:param list of Point xsorted:
:rtype: (float, (Point, Point))
"""
n = len(xsorted)
if n <= 2:
return xsorted[0].dist(xsorted[1]), (xsorted[0], xsorted[1])
if n <= 3:
# 全探索
d = INF
pair = None
for p, q in itertools.combinations(xsorted, r=2):
if p.dist(q) < d:
d = p.dist(q)
pair = p, q
return d, pair
# 分割統治
# 両側の最近点対
ld, lp = _rec(xsorted[:n // 2])
rd, rp = _rec(xsorted[n // 2:])
if ld <= rd:
d = ld
ret_pair = lp
else:
d = rd
ret_pair = rp
mid_x = xsorted[n // 2].x
# 中央から d 以内のやつを集める
mid_points = []
for p in xsorted:
# if abs(p.x - mid_x) < d:
if abs(p.x - mid_x) - d < -EPS:
mid_points.append(p)
# この中で距離が d 以内のペアがあれば更新
mid_points.sort(key=lambda p: p.y)
mid_n = len(mid_points)
for i in range(mid_n - 1):
j = i + 1
p = mid_points[i]
q = mid_points[j]
# while q.y - p.y < d
while (q.y - p.y) - d < -EPS:
pq_d = p.dist(q)
if pq_d < d:
d = pq_d
ret_pair = p, q
j += 1
if j >= mid_n:
break
q = mid_points[j]
return d, ret_pair
return _rec(list(sorted(points, key=lambda p: p.x)))
def closest_pair_randomized(points):
"""
最近点対 乱択版 O(N)
http://ir5.hatenablog.com/entry/20131221/1387557630
グリッドの管理が dict だから定数倍気になる
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_5_A&lang=ja
:param list of Point points:
:rtype: (float, (Point, Point))
:return: (距離, 点対)
"""
n = len(points)
assert n >= 2
if n == 2:
return points[0].dist(points[1]), (points[0], points[1])
# 逐次構成法
import random
points = points[:]
random.shuffle(points)
DELTA_XY = list(itertools.product([-1, 0, 1], repeat=2))
grid = defaultdict(list)
delta = INF
dist = points[0].dist(points[1])
ret_pair = points[0], points[1]
for i in range(2, n):
if delta < EPS:
return 0.0, ret_pair
# i 番目より前までを含む grid を構築
# if dist < delta:
if dist - delta < -EPS:
delta = dist
grid = defaultdict(list)
for a in points[:i]:
grid[a.x // delta, a.y // delta].append(a)
else:
p = points[i - 1]
grid[p.x // delta, p.y // delta].append(p)
p = points[i]
dist = delta
grid_x = p.x // delta
grid_y = p.y // delta
# 周り 9 箇所だけ調べれば OK
for dx, dy in DELTA_XY:
for q in grid[grid_x + dx, grid_y + dy]:
d = p.dist(q)
# if d < dist:
if d - dist < -EPS:
dist = d
ret_pair = p, q
return min(delta, dist), ret_pair
class Circle:
def __init__(self, o, r):
"""
:param Point o:
:param float r:
"""
self.o = o
self.r = r
def __eq__(self, other):
return self.o == other.o and abs(self.r - other.r) < EPS
def ctc(self, c):
"""
共通接線 common tangent の数
4: 離れてる
3: 外接
2: 交わってる
1: 内接
0: 内包
inf: 同一
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_A&lang=ja
:param Circle c:
:rtype: int
"""
if self.o == c.o:
return INF if abs(self.r - c.r) < EPS else 0
# 円同士の距離
d = self.o.dist(c.o) - self.r - c.r
if d > EPS:
return 4
elif d > -EPS:
return 3
# elif d > -min(self.r, c.r) * 2:
elif d + min(self.r, c.r) * 2 > EPS:
return 2
elif d + min(self.r, c.r) * 2 > -EPS:
return 1
return 0
def has_point_on_edge(self, p):
"""
指定した点が円周上にあるか
:param Point p:
:rtype: bool
"""
return abs(self.o.dist(p) - self.r) < EPS
def contains(self, p, allow_on_edge=True):
"""
指定した点を含むか
:param Point p:
:param bool allow_on_edge: 辺上の点を許容するか
"""
if allow_on_edge:
# return self.o.dist(p) <= self.r
return self.o.dist(p) - self.r < EPS
else:
# return self.o.dist(p) < self.r
return self.o.dist(p) - self.r < -EPS
def area(self):
"""
面積
"""
return self.r ** 2 * PI
def circular_segment_area(self, angle):
"""
弓形⌓の面積
:param float angle: 角度ラジアン
"""
# 扇形の面積
sector_area = self.area() * angle / TAU
# 三角形部分を引く
return sector_area - self.r ** 2 * math.sin(angle) / 2
def intersection_points(self, other, allow_outer=False):
"""
:param Segment|Circle other:
:param bool allow_outer:
"""
if isinstance(other, Segment):
return self.intersection_points_with_segment(other, allow_outer=allow_outer)
if isinstance(other, Circle):
return self.intersection_points_with_circle(other)
raise NotImplementedError()
def intersection_points_with_segment(self, s, allow_outer=False):
"""
線分と交差する点のリスト
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_D&lang=ja
:param Segment s:
:param bool allow_outer: 線分の間にない点を含む
:rtype: list of Point
"""
# 垂線の足
projection_point = self.o.projection_point(s.p1, s.p2, allow_outer=True)
# 線分との距離
dist = self.o.dist(projection_point)
# if dist > self.r:
if dist - self.r > EPS:
return []
if dist - self.r > -EPS:
if allow_outer or s.has_point(projection_point):
return [projection_point]
else:
return []
# 足から左右に diff だけ動かした座標が答え
diff = Point.from_polar(math.sqrt(self.r ** 2 - dist ** 2), s.phase())
ret1 = projection_point + diff
ret2 = projection_point - diff
ret = []
if allow_outer or s.has_point(ret1):
ret.append(ret1)
if allow_outer or s.has_point(ret2):
ret.append(ret2)
return ret
def intersection_points_with_circle(self, other):
"""
円と交差する点のリスト
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_E&langja
:param circle other:
:rtype: list of Point
"""
ctc = self.ctc(other)
if not 1 <= ctc <= 3:
return []
if ctc == 3:
# 外接
return [Point.from_polar(self.r, (other.o - self.o).phase()) + self.o]
if ctc == 1:
# 内接
if self.r > other.r:
return [Point.from_polar(self.r, (other.o - self.o).phase()) + self.o]
else:
return [Point.from_polar(self.r, (self.o - other.o).phase()) + self.o]
# 2つ交点がある
assert ctc == 2
a = other.r
b = self.r
c = self.o.dist(other.o)
# 余弦定理で cos(a) を求めます
cos_a = (b ** 2 + c ** 2 - a ** 2) / (2 * b * c)
angle = math.acos(cos_a)
phi = (other.o - self.o).phase()
return [
self.o + Point.from_polar(self.r, phi + angle),
self.o + Point.from_polar(self.r, phi - angle),
]
def tangent_points_with_point(self, p):
"""
p を通る接線との接点
:param Point p:
:rtype: list of Point
"""
dist = self.o.dist(p)
# if dist < self.r:
if dist - self.r < -EPS:
# p が円の内部にある
return []
if dist - self.r < EPS:
# p が円周上にある
return [Point(p.x, p.y)]
a = math.sqrt(dist ** 2 - self.r ** 2)
b = self.r
c = dist
# 余弦定理で cos(a) を求めます
cos_a = (b ** 2 + c ** 2 - a ** 2) / (2 * b * c)
angle = math.acos(cos_a)
phi = (p - self.o).phase()
return [
self.o + Point.from_polar(self.r, phi + angle),
self.o + Point.from_polar(self.r, phi - angle),
]
def tangent_points_with_circle(self, other):
"""
other との共通接線との接点
:param Circle other:
:rtype: list of Point
"""
ctc = self.ctc(other)
if ctc > 4:
raise ValueError('2つの円が同一です')
if ctc == 0:
return []
if ctc == 1:
return self.intersection_points_with_circle(other)
assert ctc in (2, 3, 4)
ret = []
# 共通外接線を求める
# if self.r == other.r:
if abs(self.r - other.r) < EPS:
# 半径が同じ == 2つの共通外接線が並行
phi = (other.o - self.o).phase()
ret.append(self.o + Point.from_polar(self.r, phi + PI / 2))
ret.append(self.o + Point.from_polar(self.r, phi - PI / 2))
else:
# 2つの共通外接線の交点から接線を引く
intersection = self.o + (other.o - self.o) / (self.r - other.r) * self.r
ret += self.tangent_points_with_point(intersection)
# 共通内接線を求める
# 2つの共通内接線の交点から接線を引く
intersection = self.o + (other.o - self.o) / (self.r + other.r) * self.r
ret += self.tangent_points_with_point(intersection)
return ret
def round_point(p):
"""
8桁で四捨五入して、-0を0に変換する
:param p:
:return:
"""
return round(p.x, 10) + 0, round(p.y, 10) + 0
def solve():
import sys
N, R = list(map(int, sys.stdin.buffer.readline().split()))
XY = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(N)]
circle = Circle(Point(0, 0), R)
points = []
for x, y in XY:
points.append(Point(x, y))
polygon = Polygon(points)
# 円との交点を含む点リスト
points_with_on_circle = []
for p, q in polygon.iter2():
points_with_on_circle.append(p)
s = Segment(p, q)
intersections = circle.intersection_points_with_segment(s, allow_outer=False)
# p に近い順にする
intersections.sort(key=lambda ip: p.dist(ip))
for ip in intersections:
if ip != p and ip != q:
points_with_on_circle.append(ip)
outer_index = None
for i, p in enumerate(points_with_on_circle):
if not circle.contains(p, allow_on_edge=True):
outer_index = i
break
# 全部円の内側
if outer_index is None:
return polygon.area()
inner_index = None
i = outer_index + 1
while i != outer_index:
j = (i + 1) % len(points_with_on_circle)
p = points_with_on_circle[i]
q = points_with_on_circle[j]
if circle.contains(p, allow_on_edge=True) and circle.contains(q, allow_on_edge=True):
inner_index = i
break
i = j
# 全部円の外側
if inner_index is None:
return 0.0
points_with_on_circle = points_with_on_circle[inner_index:] + points_with_on_circle[:inner_index]
points_on_circle = []
# 次外に出るか中に入るか
for pl, p, pr in Polygon(points_with_on_circle).iter3():
if circle.has_point_on_edge(p) and (circle.contains(pl) or circle.contains(pr)):
points_on_circle.append((p, not circle.contains(pr, allow_on_edge=True)))
# 偏角ソート
points_on_circle.sort(key=lambda pf: (pf[0] - circle.o).phase())
seen = [False] * len(points_on_circle)
ret = 0
# O(N) にしたい
while not all(seen):
partial_points = []
i = seen.index(False)
p, out = points_on_circle[i]
seen[i] = True
partial_points.append(p)
j = points_with_on_circle.index(p)
end_p = p
first = True
while first or p != end_p:
# 円周上かつ out なら次の円周上の点に飛ばす
if out:
i = (i + 1) % len(points_on_circle)
q, out = points_on_circle[i]
ret += circle.circular_segment_area(circle.o.angle(p, q) % TAU)
p = q
partial_points.append(p)
j = points_with_on_circle.index(p)
else:
j = (j + 1) % len(points_with_on_circle)
p = points_with_on_circle[j]
partial_points.append(p)
if circle.has_point_on_edge(p):
i = [i for i, (q, _) in enumerate(points_on_circle) if p == q][0]
p, out = points_on_circle[i]
if seen[i]:
pp = [p]
partial_points.pop()
while partial_points and partial_points[-1] != p:
pp.append(partial_points.pop())
ret += Polygon(pp).area()
out = True
seen[i] = True
first = False
return ret
print(solve())
``` | output | 1 | 91,708 | 23 | 183,417 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n rectangles in a row. You can either turn each rectangle by 90 degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. You can not change the order of the rectangles.
Find out if there is a way to make the rectangles go in order of non-ascending height. In other words, after all the turns, a height of every rectangle has to be not greater than the height of the previous rectangle (if it is such).
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of rectangles.
Each of the next n lines contains two integers w_i and h_i (1 ≤ w_i, h_i ≤ 10^9) — the width and the height of the i-th rectangle.
Output
Print "YES" (without quotes) if there is a way to make the rectangles go in order of non-ascending height, otherwise print "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3
3 4
4 6
3 5
Output
YES
Input
2
3 4
5 5
Output
NO
Note
In the first test, you can rotate the second and the third rectangles so that the heights will be [4, 4, 3].
In the second test, there is no way the second rectangle will be not higher than the first one. | instruction | 0 | 91,723 | 23 | 183,446 |
Tags: greedy, sortings
Correct Solution:
```
import sys
from sys import stdin,stdout
from math import *
from collections import *
from itertools import *
int_arr = lambda: list(map(int,stdin.readline().strip().split()))
str_arr = lambda: list(map(int,stdin.readline().strip().split()))
get_str = lambda: map(str,stdin.readline().strip().split())
get_int = lambda: map(int,stdin.readline().strip().split())
def solve(lis):
val = max(lis[0][0],lis[0][1])
for i in lis[1:]:
h,w = i[0],i[1]
if max(h,w) <= val:
val = max(h,w)
elif min(h,w) <= val:
val = min(h,w)
else:
print('NO')
break
else:
print('YES')
lis = []
for _ in range(int(stdin.readline())):
a = int_arr()
lis.append(a)
solve(lis)
``` | output | 1 | 91,723 | 23 | 183,447 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n rectangles in a row. You can either turn each rectangle by 90 degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. You can not change the order of the rectangles.
Find out if there is a way to make the rectangles go in order of non-ascending height. In other words, after all the turns, a height of every rectangle has to be not greater than the height of the previous rectangle (if it is such).
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of rectangles.
Each of the next n lines contains two integers w_i and h_i (1 ≤ w_i, h_i ≤ 10^9) — the width and the height of the i-th rectangle.
Output
Print "YES" (without quotes) if there is a way to make the rectangles go in order of non-ascending height, otherwise print "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3
3 4
4 6
3 5
Output
YES
Input
2
3 4
5 5
Output
NO
Note
In the first test, you can rotate the second and the third rectangles so that the heights will be [4, 4, 3].
In the second test, there is no way the second rectangle will be not higher than the first one.
Submitted Solution:
```
import sys
input = sys.stdin.readline
n = int(input())
a, b = map(int,input().split())
minh = max(a, b)
f = True
for _ in range(n - 1):
w, h = map(int,input().split())
if min(w, h) > minh:
f = False
break
else:
if max(w, h) > minh:
minh = min(w, h)
else:
minh = max(w, h)
print('YES' if f else 'NO')
``` | instruction | 0 | 91,730 | 23 | 183,460 |
Yes | output | 1 | 91,730 | 23 | 183,461 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n rectangles in a row. You can either turn each rectangle by 90 degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. You can not change the order of the rectangles.
Find out if there is a way to make the rectangles go in order of non-ascending height. In other words, after all the turns, a height of every rectangle has to be not greater than the height of the previous rectangle (if it is such).
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of rectangles.
Each of the next n lines contains two integers w_i and h_i (1 ≤ w_i, h_i ≤ 10^9) — the width and the height of the i-th rectangle.
Output
Print "YES" (without quotes) if there is a way to make the rectangles go in order of non-ascending height, otherwise print "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3
3 4
4 6
3 5
Output
YES
Input
2
3 4
5 5
Output
NO
Note
In the first test, you can rotate the second and the third rectangles so that the heights will be [4, 4, 3].
In the second test, there is no way the second rectangle will be not higher than the first one.
Submitted Solution:
```
'''Author- Akshit Monga'''
from sys import stdin, stdout
# input = stdin.readline
t = 1
for _ in range(t):
n = int(input())
vals=[]
for i in range(n):
a,b=map(int,input().split())
vals.append((a,b))
ans="YES"
s=max(vals[0][0],vals[0][1])
for i in range(1,n):
x=min(vals[i][0],vals[i][1])
y=max(vals[i][0],vals[i][1])
if x>s:
ans="NO"
break
if y<=s:
s=y
else:
s=x
print(ans)
``` | instruction | 0 | 91,731 | 23 | 183,462 |
Yes | output | 1 | 91,731 | 23 | 183,463 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n rectangles in a row. You can either turn each rectangle by 90 degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. You can not change the order of the rectangles.
Find out if there is a way to make the rectangles go in order of non-ascending height. In other words, after all the turns, a height of every rectangle has to be not greater than the height of the previous rectangle (if it is such).
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of rectangles.
Each of the next n lines contains two integers w_i and h_i (1 ≤ w_i, h_i ≤ 10^9) — the width and the height of the i-th rectangle.
Output
Print "YES" (without quotes) if there is a way to make the rectangles go in order of non-ascending height, otherwise print "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3
3 4
4 6
3 5
Output
YES
Input
2
3 4
5 5
Output
NO
Note
In the first test, you can rotate the second and the third rectangles so that the heights will be [4, 4, 3].
In the second test, there is no way the second rectangle will be not higher than the first one.
Submitted Solution:
```
num = int(input())
prev = list(map(int, input().split()))
num -= 1
if prev[0] > prev[1]: prev[0], prev[1] = prev[1], prev[0]
ans = ""
for i in range(num):
cur = list(map(int, input().split()))
temp1 = cur[1] - prev[1]
temp2 = cur[0] - prev[1]
if temp1 <= 0 and temp2 <= 0:
if max(temp1, temp2) == temp2:
cur[0], cur[1] = cur[1], cur[0]
elif temp2 <= 0:
cur[0], cur[1] = cur[1], cur[0]
elif temp1 <= 0:
k = 0;
else:
ans = "NO"
break
prev = cur
if ans != "":
print(ans)
else: print("YES")
``` | instruction | 0 | 91,732 | 23 | 183,464 |
Yes | output | 1 | 91,732 | 23 | 183,465 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n rectangles in a row. You can either turn each rectangle by 90 degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. You can not change the order of the rectangles.
Find out if there is a way to make the rectangles go in order of non-ascending height. In other words, after all the turns, a height of every rectangle has to be not greater than the height of the previous rectangle (if it is such).
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of rectangles.
Each of the next n lines contains two integers w_i and h_i (1 ≤ w_i, h_i ≤ 10^9) — the width and the height of the i-th rectangle.
Output
Print "YES" (without quotes) if there is a way to make the rectangles go in order of non-ascending height, otherwise print "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3
3 4
4 6
3 5
Output
YES
Input
2
3 4
5 5
Output
NO
Note
In the first test, you can rotate the second and the third rectangles so that the heights will be [4, 4, 3].
In the second test, there is no way the second rectangle will be not higher than the first one.
Submitted Solution:
```
n=int(input())
m=[]
a=[]
for i in range(n):
m.append(list(map(int,input().split())))
comp=0
for i in range(n):
if i==0:
comp=max(m[i][0],m[i][1])
a.append(comp)
continue
maxa=max(m[i][0],m[i][1])
mina=min(m[i][0],m[i][1])
if maxa<=comp:
comp=maxa
a.append(comp)
else:
comp=mina
a.append(comp)
for i in range(0,len(a)-1):
if a[i]<a[i+1]:
print("NO")
exit()
print("YES")
``` | instruction | 0 | 91,733 | 23 | 183,466 |
Yes | output | 1 | 91,733 | 23 | 183,467 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n rectangles in a row. You can either turn each rectangle by 90 degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. You can not change the order of the rectangles.
Find out if there is a way to make the rectangles go in order of non-ascending height. In other words, after all the turns, a height of every rectangle has to be not greater than the height of the previous rectangle (if it is such).
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of rectangles.
Each of the next n lines contains two integers w_i and h_i (1 ≤ w_i, h_i ≤ 10^9) — the width and the height of the i-th rectangle.
Output
Print "YES" (without quotes) if there is a way to make the rectangles go in order of non-ascending height, otherwise print "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3
3 4
4 6
3 5
Output
YES
Input
2
3 4
5 5
Output
NO
Note
In the first test, you can rotate the second and the third rectangles so that the heights will be [4, 4, 3].
In the second test, there is no way the second rectangle will be not higher than the first one.
Submitted Solution:
```
n = int(input())
w = []
h = []
for i in range(n):
u,v = map(int,input().split(' '))
w.append(u)
h.append(v)
def swap(a,b):
return b,a
p = 1
for i in range(n-1):
if h[i]>=h[i+1]:
p = 1
else:
if h[i]>=w[i+1]:
w[i+1],h[i+1] = swap(w[i+1],h[i+1])
p = 1
else:
p = 0
break
if p==1:
print('YES')
else:
print('NO')
``` | instruction | 0 | 91,734 | 23 | 183,468 |
No | output | 1 | 91,734 | 23 | 183,469 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n rectangles in a row. You can either turn each rectangle by 90 degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. You can not change the order of the rectangles.
Find out if there is a way to make the rectangles go in order of non-ascending height. In other words, after all the turns, a height of every rectangle has to be not greater than the height of the previous rectangle (if it is such).
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of rectangles.
Each of the next n lines contains two integers w_i and h_i (1 ≤ w_i, h_i ≤ 10^9) — the width and the height of the i-th rectangle.
Output
Print "YES" (without quotes) if there is a way to make the rectangles go in order of non-ascending height, otherwise print "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3
3 4
4 6
3 5
Output
YES
Input
2
3 4
5 5
Output
NO
Note
In the first test, you can rotate the second and the third rectangles so that the heights will be [4, 4, 3].
In the second test, there is no way the second rectangle will be not higher than the first one.
Submitted Solution:
```
n=int(input())
l=[]
done=0
for i in range(n):
a, b=map(int,input().split())
x=max(a,b)
y=min(a,b)
if len(l)==0:
l.append(x)
else:
z=l[len(l)-1]
if y>z:
done=1
else:
l.append(y)
if done==1:
print("NO")
else:
print("YES")
``` | instruction | 0 | 91,735 | 23 | 183,470 |
No | output | 1 | 91,735 | 23 | 183,471 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n rectangles in a row. You can either turn each rectangle by 90 degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. You can not change the order of the rectangles.
Find out if there is a way to make the rectangles go in order of non-ascending height. In other words, after all the turns, a height of every rectangle has to be not greater than the height of the previous rectangle (if it is such).
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of rectangles.
Each of the next n lines contains two integers w_i and h_i (1 ≤ w_i, h_i ≤ 10^9) — the width and the height of the i-th rectangle.
Output
Print "YES" (without quotes) if there is a way to make the rectangles go in order of non-ascending height, otherwise print "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3
3 4
4 6
3 5
Output
YES
Input
2
3 4
5 5
Output
NO
Note
In the first test, you can rotate the second and the third rectangles so that the heights will be [4, 4, 3].
In the second test, there is no way the second rectangle will be not higher than the first one.
Submitted Solution:
```
def check(k) :
for x in range(1,len(k) - 1) :
if k[x][0] > k[x - 1][0] and k[x][1] >= k[x - 1][0] :
return "YES"
return "NO"
n = int(input())
k = []
for _ in range(n) :
l = []
l = list(map(int,input().split()))
k.append(l)
print(check(k))
``` | instruction | 0 | 91,736 | 23 | 183,472 |
No | output | 1 | 91,736 | 23 | 183,473 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n rectangles in a row. You can either turn each rectangle by 90 degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. You can not change the order of the rectangles.
Find out if there is a way to make the rectangles go in order of non-ascending height. In other words, after all the turns, a height of every rectangle has to be not greater than the height of the previous rectangle (if it is such).
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of rectangles.
Each of the next n lines contains two integers w_i and h_i (1 ≤ w_i, h_i ≤ 10^9) — the width and the height of the i-th rectangle.
Output
Print "YES" (without quotes) if there is a way to make the rectangles go in order of non-ascending height, otherwise print "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3
3 4
4 6
3 5
Output
YES
Input
2
3 4
5 5
Output
NO
Note
In the first test, you can rotate the second and the third rectangles so that the heights will be [4, 4, 3].
In the second test, there is no way the second rectangle will be not higher than the first one.
Submitted Solution:
```
n = int(input())
check = True
wtf = max(map(int, input().split()))
for i in range(n - 1):
x, y = (map(int, input().split()))
if wtf < x and wtf < y:
check = False
break
if check:
print('Yes')
else:
print('No')
``` | instruction | 0 | 91,737 | 23 | 183,474 |
No | output | 1 | 91,737 | 23 | 183,475 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Cybermen solved that first test much quicker than the Daleks. Luckily for us, the Daleks were angry (shocking!) and they destroyed some of the Cybermen.
After the fighting stopped, Heidi gave them another task to waste their time on.
There are n points on a plane. Given a radius r, find the maximum number of points that can be covered by an L^1-ball with radius r.
An L^1-ball with radius r and center (x_0, y_0) in a 2D-plane is defined as the set of points (x, y) such that the Manhattan distance between (x_0, y_0) and (x, y) is at most r.
Manhattan distance between (x_0, y_0) and (x, y) is defined as |x - x_0| + |y - y_0|.
Input
The first line contains two integers n, r (1 ≤ n ≤ 300 000, 1 ≤ r ≤ 10^6), the number of points and the radius of the ball, respectively.
Each of the next n lines contains integers x_i, y_i (-10^6 ≤ x_i, y_i ≤ 10^6), describing the coordinates of the i-th point.
It is guaranteed, that all points are distinct.
Output
Print one integer — the maximum number points that an L^1-ball with radius r can cover.
Examples
Input
5 1
1 1
1 -1
-1 1
-1 -1
2 0
Output
3
Input
5 2
1 1
1 -1
-1 1
-1 -1
2 0
Output
5
Note
In the first example, a ball centered at (1, 0) covers the points (1, 1), (1, -1), (2, 0).
In the second example, a ball centered at (0, 0) covers all the points.
Note that x_0 and y_0 need not be integer. | instruction | 0 | 91,793 | 23 | 183,586 |
Tags: data structures
Correct Solution:
```
import sys
NORM = 2000000
LIMIT = NORM * 2 + 1
class segmentTree:
def __init__(self, n):
self.n = n
self.t = [0] * (n * 2)
self.lazy = [0] * n
def apply(self, p, value):
self.t[p] += value
if p < self.n:
self.lazy[p] += value
def build(self, p):
while p > 1:
p >>= 1
self.t[p] = max(self.t[p * 2], self.t[p * 2 + 1]) + self.lazy[p]
def push(self, p):
log = 0
while (1 << log) <= self.n:
log += 1
for s in range(log, 0, -1):
parent = p >> s
if self.lazy[parent] != 0:
self.apply(parent * 2, self.lazy[parent])
self.apply(parent * 2 + 1, self.lazy[parent])
self.lazy[parent] = 0
def inc(self, l, r, value):
l += self.n
r += self.n
l0, r0 = l, r
while l < r:
if l & 1:
self.apply(l, value)
l += 1
if r & 1:
self.apply(r - 1, value)
r -= 1
l >>= 1
r >>= 1
self.build(l0)
self.build(r0 - 1)
def query(self, l, r):
l += self.n
r += self.n
self.push(l)
self.push(r - 1)
res = 0
while l < r:
if l & 1:
res = max(res, self.t[l])
l += 1
if r & 1:
res = max(res, self.t[r - 1])
r -= 1
l >>= 1
r >>= 1
return res
inp = [int(x) for x in sys.stdin.read().split()]
n, r = inp[0], inp[1]
inp_idx = 2
points = []
env = {}
for _ in range(n):
x, y = inp[inp_idx], inp[inp_idx + 1]
inp_idx += 2
new_x = x - y
new_y = x + y
new_x += NORM
new_y += NORM
if not new_y in env:
env[new_y] = []
env[new_y].append(new_x)
points.append([new_x, new_y])
sq_side = r * 2
tree = segmentTree(LIMIT)
ys = []
for y in env.keys():
ys.append(y)
ys = sorted(ys)
ans = 0
last = 0
for i in range(len(ys)):
y = ys[i]
while i > last and ys[last] < y - sq_side:
low_y = ys[last]
for x in env[low_y]:
low_x = max(0, x - sq_side)
tree.inc(low_x, x + 1, -1)
last += 1
for x in env[y]:
low_x = max(0, x - sq_side)
tree.inc(low_x, x + 1, +1)
ans = max(ans, tree.query(0, LIMIT))
print(ans)
``` | output | 1 | 91,793 | 23 | 183,587 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r.
Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible.
Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:
* if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100];
* if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6].
Obviously, a union is a set of pairwise non-intersecting segments.
You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible.
For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then:
* erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union;
* erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union.
Thus, you are required to erase the third segment to get answer 2.
Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow.
The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively.
The segments are given in an arbitrary order.
It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5.
Output
Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Example
Input
3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
Output
2
1
5 | instruction | 0 | 91,844 | 23 | 183,688 |
Tags: brute force, constructive algorithms, data structures, dp, graphs, sortings, trees, two pointers
Correct Solution:
```
import sys
t = int(sys.stdin.readline())
for _ in range(t):
n = int(sys.stdin.readline())
intervals = [None]*n
for i in range(n):
intervals[i] = tuple([int(a) for a in sys.stdin.readline().split()])
intervals = list(zip(intervals, range(n)))
starts = sorted(intervals, key = lambda x: x[0][0])
ends = sorted(intervals, key = lambda x: x[0][1])
connects = [0]*n
gaps = 0
covering = set()
atS = 0
atE = 0
# print(starts)
while atE<n:
# print("%d, %d"%(atS, atE))
# print(covering)
# print(connects)
if atS!=n and ends[atE][0][1]>=starts[atS][0][0]:
if len(covering)==1:
gap = list(covering)[0]
connects[gap]+=0.5
covering.add(starts[atS][1])
atS += 1
if len(covering)==1:
gap = list(covering)[0]
connects[gap]-=0.5
else:
if len(covering)==1:
gap = list(covering)[0]
connects[gap]-=0.5
covering.remove(ends[atE][1])
atE += 1
if len(covering)==1:
gap = list(covering)[0]
connects[gap]+=0.5
if len(covering)==0:
gaps += 1
connects = [int(a) for a in connects]
print(max(connects)+gaps)
``` | output | 1 | 91,844 | 23 | 183,689 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r.
Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible.
Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:
* if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100];
* if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6].
Obviously, a union is a set of pairwise non-intersecting segments.
You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible.
For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then:
* erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union;
* erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union.
Thus, you are required to erase the third segment to get answer 2.
Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow.
The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively.
The segments are given in an arbitrary order.
It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5.
Output
Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Example
Input
3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
Output
2
1
5 | instruction | 0 | 91,845 | 23 | 183,690 |
Tags: brute force, constructive algorithms, data structures, dp, graphs, sortings, trees, two pointers
Correct Solution:
```
import sys
from collections import deque
def input():
return sys.stdin.readline().rstrip()
t = int(input())
for _ in range(t):
n = int(input())
segs = []
for i in range(n):
l,r = list(map(int, input().split()))
segs.append((l,0,i))
segs.append((r,1,i))
segs.sort()
active = set()
increase = [0 for _ in range(n)]
seq = []
ans = 0
for pos, p, i in segs:
if p == 0:
if len(seq)>1 and seq[-2:] == [2,1]:
increase[next(iter(active))]+=1
active.add(i)
else:
active.remove(i)
if len(active) == 0:
ans+=1
seq.append(len(active))
m = max(increase)
seq = set(seq)
if seq == {0,1}:
print(ans-1)
else:
print(ans+max(increase))
``` | output | 1 | 91,845 | 23 | 183,691 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r.
Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible.
Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:
* if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100];
* if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6].
Obviously, a union is a set of pairwise non-intersecting segments.
You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible.
For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then:
* erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union;
* erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union.
Thus, you are required to erase the third segment to get answer 2.
Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow.
The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively.
The segments are given in an arbitrary order.
It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5.
Output
Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Example
Input
3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
Output
2
1
5 | instruction | 0 | 91,846 | 23 | 183,692 |
Tags: brute force, constructive algorithms, data structures, dp, graphs, sortings, trees, two pointers
Correct Solution:
```
import io
import os
from collections import Counter, defaultdict, deque
# From: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SegmentTree.py
class SegmentTree:
def __init__(self, data, default=0, func=max):
"""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):
"""func of data[start, stop)"""
start += self._size
stop += self._size
res_left = res_right = self._default
while start < stop:
if start & 1:
res_left = self._func(res_left, self.data[start])
start += 1
if stop & 1:
stop -= 1
res_right = self._func(self.data[stop], res_right)
start >>= 1
stop >>= 1
return self._func(res_left, res_right)
def __repr__(self):
return "SegmentTree({0})".format(self.data)
def pack(a, b, c):
return [a, b, c]
return (a, b, c)
return (a << 40) + (b << 20) + c
def unpack(abc):
return abc
ab, c = divmod(abc, 1 << 20)
a, b = divmod(ab, 1 << 20)
return a, b, c
def merge(x, y):
# Track numClose, numNonOverlapping, numOpen:
# e.g., )))) (...)(...)(...) ((((((
xClose, xFull, xOpen = unpack(x)
yClose, yFull, yOpen = unpack(y)
if xOpen == yClose == 0:
ret = xClose, xFull + yFull, yOpen
elif xOpen == yClose:
ret = xClose, xFull + 1 + yFull, yOpen
elif xOpen > yClose:
ret = xClose, xFull, xOpen - yClose + yOpen
elif xOpen < yClose:
ret = xClose + yClose - xOpen, yFull, yOpen
# print(x, y, ret)
return pack(*ret)
def solve(N, intervals):
endpoints = []
for i, (l, r) in enumerate(intervals):
endpoints.append((l, 0, i))
endpoints.append((r, 1, i))
endpoints.sort(key=lambda t: t[1])
endpoints.sort(key=lambda t: t[0])
# Build the segment tree and track the endpoints of each interval in the segment tree
data = []
# Note: defaultdict seems to be faster. Maybe because it traverses in segment tree order rather than randomly?
idToIndices = defaultdict(list)
for x, kind, intervalId in endpoints:
if kind == 0:
data.append(pack(0, 0, 1)) # '('
else:
assert kind == 1
data.append(pack(1, 0, 0)) # ')'
idToIndices[intervalId].append(len(data) - 1)
assert len(data) == 2 * N
segTree = SegmentTree(data, pack(0, 0, 0), merge)
# print("init", unpack(segTree.query(0, 2 * N)))
best = 0
for intervalId, indices in idToIndices.items():
# Remove the two endpoints
i, j = indices
removed1, removed2 = segTree[i], segTree[j]
segTree[i], segTree[j] = pack(0, 0, 0), pack(0, 0, 0)
# Query
res = unpack(segTree.query(0, 2 * N))
assert res[0] == 0
assert res[2] == 0
best = max(best, res[1])
# print("after removing", intervals[intervalId], res)
# Add back the two endpoints
segTree[i], segTree[j] = removed1, removed2
return best
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for t in range(T):
(N,) = [int(x) for x in input().split()]
intervals = [[int(x) for x in input().split()] for i in range(N)]
ans = solve(N, intervals)
print(ans)
``` | output | 1 | 91,846 | 23 | 183,693 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r.
Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible.
Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:
* if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100];
* if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6].
Obviously, a union is a set of pairwise non-intersecting segments.
You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible.
For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then:
* erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union;
* erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union.
Thus, you are required to erase the third segment to get answer 2.
Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow.
The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively.
The segments are given in an arbitrary order.
It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5.
Output
Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Example
Input
3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
Output
2
1
5 | instruction | 0 | 91,847 | 23 | 183,694 |
Tags: brute force, constructive algorithms, data structures, dp, graphs, sortings, trees, two pointers
Correct Solution:
```
from sys import stdin
input = stdin.readline
q = int(input())
for rwere in range(q):
n = int(input())
seg = []
pts = []
for i in range(n):
pocz, kon = map(int,input().split())
seg.append([2*pocz, 2*kon])
pts.append(2*kon+1)
p,k = map(list,zip(*seg))
pts += (p + k)
pts.sort()
ind = -1
while True:
if pts[ind] == pts[-1]:
ind -= 1
else:
break
ind += 1
pts = pts[:ind]
mapa = {}
val = 0
mapa[pts[0]] = val
for i in range(1, len(pts)):
if pts[i] != pts[i-1]:
val += 1
mapa[pts[i]] = val
val += 1
for i in range(n):
seg[i] = [mapa[seg[i][0]], mapa[seg[i][1]]]
seg.sort()
dupa = [0] * (val+1)
for s in seg:
dupa[s[0]] += 1
dupa[s[1] + 1] -= 1
cov = [0] * val
cov[0] = dupa[0]
for i in range(1, val):
cov[i] = cov[i-1] + dupa[i]
przyn = [0] * val
cur = seg[0][0]
label = 1
for i in range(n):
kon = seg[i][1]
if cur <= kon:
for j in range(cur, kon + 1):
przyn[j] = label
label += 1
cur = kon + 1
final = [(przyn[i] if cov[i] == 1 else (-1 if cov[i] == 0 else 0)) for i in range(val)]
baza = final.count(-1) + 1
final = [-1] + final + [-1]
val += 2
if max(final) <= 0:
print(baza)
else:
comp = {}
comp[0] = -100000000000
for i in final:
if i > 0:
comp[i] = 0
for i in range(1, val - 1):
if final[i] > 0 and final[i] != final[i-1]:
comp[final[i]] += 1
if final[i-1] == -1:
comp[final[i]] -= 1
if final[i+1] == -1:
comp[final[i]] -= 1
best = -10000000000000
for i in comp:
best = max(best, comp[i])
if max(final) == n:
print(baza + best)
else:
print(max(baza + best, baza))
``` | output | 1 | 91,847 | 23 | 183,695 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r.
Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible.
Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:
* if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100];
* if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6].
Obviously, a union is a set of pairwise non-intersecting segments.
You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible.
For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then:
* erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union;
* erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union.
Thus, you are required to erase the third segment to get answer 2.
Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow.
The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively.
The segments are given in an arbitrary order.
It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5.
Output
Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Example
Input
3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
Output
2
1
5 | instruction | 0 | 91,848 | 23 | 183,696 |
Tags: brute force, constructive algorithms, data structures, dp, graphs, sortings, trees, two pointers
Correct Solution:
```
import io
import os
from collections import defaultdict
# From: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SegmentTree.py
class SegmentTree:
def __init__(self, data, default=0, func=max):
"""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):
"""func of data[start, stop)"""
start += self._size
stop += self._size
res_left = res_right = self._default
while start < stop:
if start & 1:
res_left = self._func(res_left, self.data[start])
start += 1
if stop & 1:
stop -= 1
res_right = self._func(self.data[stop], res_right)
start >>= 1
stop >>= 1
return self._func(res_left, res_right)
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class Node:
def __init__(self, numClose, count, numOpen):
self.close = numClose
self.count = count
self.open = numOpen
neutral = Node(0, 0, 0)
def combine(x, y):
# Track numClose, numCount, numOpen:
# e.g., )))) (...)(...)(...) ((((((
if x.open == y.close == 0:
ret = x.close, x.count + y.count, y.open
elif x.open == y.close:
ret = x.close, x.count + 1 + y.count, y.open
elif x.open > y.close:
ret = x.close, x.count, x.open - y.close + y.open
elif x.open < y.close:
ret = x.close + y.close - x.open, y.count, y.open
return Node(*ret)
def solve(N, intervals):
OPEN = 0
CLOSE = 1
endpoints = []
for i, (l, r) in enumerate(intervals):
endpoints.append((l, OPEN, i))
endpoints.append((r, CLOSE, i))
endpoints.sort(key=lambda t: t[1])
endpoints.sort(key=lambda t: t[0])
# Build the segment tree and track the endpoints of each interval in the segment tree
data = []
idToIndices = defaultdict(list)
for x, kind, intervalId in endpoints:
if kind == OPEN:
data.append(Node(0, 0, 1))
else:
assert kind == CLOSE
data.append(Node(1, 0, 0))
idToIndices[intervalId].append(len(data) - 1)
assert len(data) == 2 * N
segTree = SegmentTree(data, Node(0, 0, 0), combine)
best = 0
for intervalId, indices in idToIndices.items():
# Remove the two endpoints
i, j = indices
removed1, removed2 = segTree[i], segTree[j]
segTree[i], segTree[j] = neutral, neutral
# Query
res = segTree.query(0, 2 * N)
assert res.open == 0
assert res.close == 0
best = max(best, res.count)
# Add back the two endpoints
segTree[i], segTree[j] = removed1, removed2
return best
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for t in range(T):
(N,) = [int(x) for x in input().split()]
intervals = [[int(x) for x in input().split()] for i in range(N)]
ans = solve(N, intervals)
print(ans)
``` | output | 1 | 91,848 | 23 | 183,697 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r.
Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible.
Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:
* if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100];
* if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6].
Obviously, a union is a set of pairwise non-intersecting segments.
You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible.
For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then:
* erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union;
* erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union.
Thus, you are required to erase the third segment to get answer 2.
Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow.
The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively.
The segments are given in an arbitrary order.
It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5.
Output
Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Example
Input
3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
Output
2
1
5 | instruction | 0 | 91,849 | 23 | 183,698 |
Tags: brute force, constructive algorithms, data structures, dp, graphs, sortings, trees, two pointers
Correct Solution:
```
import sys
input = sys.stdin.readline
from itertools import accumulate
import random
t=int(input())
for testcases in range(t):
n=int(input())
S=[list(map(int,input().split())) for i in range(n)]
compression_list=[]
for l,r in S:
compression_list.append(l)
compression_list.append(r)
compression_dict={a: ind for ind, a in enumerate(sorted(set(compression_list)))}
for i in range(n):
S[i][0]=compression_dict[S[i][0]]*2
S[i][1]=compression_dict[S[i][1]]*2
LEN=len(compression_dict)*2
R=[0]*(LEN+1)
for l,r in S:
R[l]+=1
R[r+1]-=1
SR=list(accumulate(R))
NOW=0
for i in range(LEN):
if SR[i]!=0 and SR[i+1]==0:
NOW+=1
ONECOUNT=[0]*(LEN+1)
for i in range(1,LEN):
if SR[i-1]!=1 and SR[i]==1:
ONECOUNT[i]+=1
SO=list(accumulate(ONECOUNT))
SO.append(0)
ANS=1
for l,r in S:
lr=0
if SR[r]==1:
lr-=1
ANS=max(ANS,NOW+SO[r-1]-SO[l]+lr)
print(ANS)
``` | output | 1 | 91,849 | 23 | 183,699 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r.
Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible.
Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:
* if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100];
* if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6].
Obviously, a union is a set of pairwise non-intersecting segments.
You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible.
For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then:
* erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union;
* erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union.
Thus, you are required to erase the third segment to get answer 2.
Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow.
The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively.
The segments are given in an arbitrary order.
It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5.
Output
Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Example
Input
3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
Output
2
1
5 | instruction | 0 | 91,850 | 23 | 183,700 |
Tags: brute force, constructive algorithms, data structures, dp, graphs, sortings, trees, two pointers
Correct Solution:
```
def solve(lsts):
points = []
for i in range(len(lsts)):
points.append((lst[i][0], 0, i))
points.append((lst[i][1], 1, i))
points.sort()
open = set()
increased = [0] * len(lsts)
original = 0
for i in range(len(points)):
p = points[i]
if p[1] == 0:
open.add(p[2])
else:
open.remove(p[2])
if len(open) == 1 and p[1] == 1 and points[i+1][1] == 0 :
increased[list(open)[0]] += 1
if len(open) == 1 and p[1] == 0 and points[i+1][1] == 1:
increased[list(open)[0]] -= 1
# also keep track of what was the original answer without removing
if len(open) == 0:
original += 1
res = -float('inf')
for i in range(len(lsts)):
res = max(res, increased[i])
return res + original
n = int(input())
for _ in range(n):
m = int(input())
lst = []
for _ in range(m):
lst.append(list(map(int, input().split())))
print(solve(lst))
``` | output | 1 | 91,850 | 23 | 183,701 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r.
Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible.
Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:
* if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100];
* if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6].
Obviously, a union is a set of pairwise non-intersecting segments.
You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible.
For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then:
* erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union;
* erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union.
Thus, you are required to erase the third segment to get answer 2.
Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow.
The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively.
The segments are given in an arbitrary order.
It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5.
Output
Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Example
Input
3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
Output
2
1
5 | instruction | 0 | 91,851 | 23 | 183,702 |
Tags: brute force, constructive algorithms, data structures, dp, graphs, sortings, trees, two pointers
Correct Solution:
```
import io
import os
from collections import Counter, defaultdict, deque
# From: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SegmentTree.py
class SegmentTree:
def __init__(self, data, default=0, func=max):
"""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):
"""func of data[start, stop)"""
start += self._size
stop += self._size
res_left = res_right = self._default
while start < stop:
if start & 1:
res_left = self._func(res_left, self.data[start])
start += 1
if stop & 1:
stop -= 1
res_right = self._func(self.data[stop], res_right)
start >>= 1
stop >>= 1
return self._func(res_left, res_right)
def __repr__(self):
return "SegmentTree({0})".format(self.data)
def pack(a, b, c):
return (a, b, c)
return (a << 40) + (b << 20) + c
def unpack(abc):
return abc
ab, c = divmod(abc, 1 << 20)
a, b = divmod(ab, 1 << 20)
return a, b, c
def merge(x, y):
# Track numClose, numNonOverlapping, numOpen:
# e.g., )))) (...)(...)(...) ((((((
xClose, xFull, xOpen = unpack(x)
yClose, yFull, yOpen = unpack(y)
if xOpen == yClose == 0:
ret = xClose, xFull + yFull, yOpen
elif xOpen == yClose:
ret = xClose, xFull + 1 + yFull, yOpen
elif xOpen > yClose:
ret = xClose, xFull, xOpen - yClose + yOpen
elif xOpen < yClose:
ret = xClose + yClose - xOpen, yFull, yOpen
# print(x, y, ret)
return pack(*ret)
def solve(N, intervals):
endpoints = []
for i, (l, r) in enumerate(intervals):
endpoints.append((l, 0, i))
endpoints.append((r, 1, i))
endpoints.sort(key=lambda t: t[1])
endpoints.sort(key=lambda t: t[0])
# Build the segment tree and track the endpoints of each interval in the segment tree
data = []
# Note: defaultdict seems to be faster. Maybe because it traverses in segment tree order rather than randomly?
idToIndices = defaultdict(list)
for x, kind, intervalId in endpoints:
if kind == 0:
data.append(pack(0, 0, 1)) # '('
else:
assert kind == 1
data.append(pack(1, 0, 0)) # ')'
idToIndices[intervalId].append(len(data) - 1)
assert len(data) == 2 * N
segTree = SegmentTree(data, pack(0, 0, 0), merge)
# print("init", unpack(segTree.query(0, 2 * N)))
best = 0
for intervalId, indices in idToIndices.items():
# Remove the two endpoints
i, j = indices
removed1, removed2 = segTree[i], segTree[j]
segTree[i], segTree[j] = pack(0, 0, 0), pack(0, 0, 0)
# Query
res = unpack(segTree.query(0, 2 * N))
assert res[0] == 0
assert res[2] == 0
best = max(best, res[1])
# print("after removing", intervals[intervalId], res)
# Add back the two endpoints
segTree[i], segTree[j] = removed1, removed2
return best
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for t in range(T):
(N,) = [int(x) for x in input().split()]
intervals = [[int(x) for x in input().split()] for i in range(N)]
ans = solve(N, intervals)
print(ans)
``` | output | 1 | 91,851 | 23 | 183,703 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r.
Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible.
Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:
* if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100];
* if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6].
Obviously, a union is a set of pairwise non-intersecting segments.
You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible.
For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then:
* erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union;
* erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union.
Thus, you are required to erase the third segment to get answer 2.
Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow.
The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively.
The segments are given in an arbitrary order.
It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5.
Output
Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Example
Input
3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
Output
2
1
5
Submitted Solution:
```
import io
import os
from collections import Counter, defaultdict, deque
# From: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SegmentTree.py
class SegmentTree:
def __init__(self, data, default=0, func=max):
"""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):
"""func of data[start, stop)"""
start += self._size
stop += self._size
res_left = res_right = self._default
while start < stop:
if start & 1:
res_left = self._func(res_left, self.data[start])
start += 1
if stop & 1:
stop -= 1
res_right = self._func(self.data[stop], res_right)
start >>= 1
stop >>= 1
return self._func(res_left, res_right)
def __repr__(self):
return "SegmentTree({0})".format(self.data)
def merge(x, y):
# Track )))) ()()() ((((((
# numClose, numFull, numOpen
xClose, xFull, xOpen = x
yClose, yFull, yOpen = y
if xOpen == yClose:
if xOpen:
ret = xClose, xFull + 1 + yFull, yOpen
else:
ret = xClose, xFull + yFull, yOpen
elif xOpen > yClose:
ret = xClose, xFull, xOpen - yClose + yOpen
elif xOpen < yClose:
ret = xClose + yClose - xOpen, yFull, yOpen
#print(x, y, ret)
return ret
def solve(N, segments):
endpoints = []
for i, (l, r) in enumerate(segments):
endpoints.append((l, 0, i))
endpoints.append((r, 1, i))
endpoints.sort()
#print(endpoints)
data = []
idToIndices = defaultdict(list)
for x, kind, segmentId in endpoints:
if kind == 0:
data.append((0, 0, 1)) # (
else:
assert kind == 1
data.append((1, 0, 0)) # )
idToIndices[segmentId].append(len(data) - 1)
#print(data)
assert len(data) == 2 * N
segTree = SegmentTree(data, (0, 0, 0), merge)
#print('init', segTree.query(0, 2 * N))
#print(segTree)
best = 0
for k, indices in idToIndices.items():
# Remove the two endpoints
assert len(indices) == 2
removed = []
for i in indices:
removed.append(segTree[i])
segTree[i] = (0, 0, 0)
res = segTree.query(0, 2 * N)
assert res[0] == 0
assert res[2] == 0
#print('after removing', segments[k], 'res is', res)
best = max(best, res[1])
# Add back the two endpoints
for i, old in zip(indices, removed):
segTree[i] = old
return best
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for t in range(T):
(N,) = [int(x) for x in input().split()]
segments = [[int(x) for x in input().split()] for i in range(N)]
ans = solve(N, segments)
print(ans)
``` | instruction | 0 | 91,852 | 23 | 183,704 |
Yes | output | 1 | 91,852 | 23 | 183,705 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r.
Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible.
Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:
* if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100];
* if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6].
Obviously, a union is a set of pairwise non-intersecting segments.
You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible.
For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then:
* erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union;
* erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union.
Thus, you are required to erase the third segment to get answer 2.
Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow.
The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively.
The segments are given in an arbitrary order.
It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5.
Output
Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Example
Input
3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
Output
2
1
5
Submitted Solution:
```
import sys
# inf = open('input.txt', 'r')
# reader = (line.rstrip() for line in inf)
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
t = int(input())
for _ in range(t):
n = int(input())
edges = []
for i in range(n):
li, ri = map(int, input().split())
edges.append((li, 0, i))
edges.append((ri, 1, i))
edges.sort()
ctr = [0] * n
opened = set()
segmCtr = 0
for k, (e, isEnd, i) in enumerate(edges):
if isEnd:
opened.remove(i)
if not opened and edges[k-1][2] == i:
ctr[i] -= 1
elif len(opened) == 1 and edges[k+1][1] == 0:
for j in opened:
ctr[j] += 1
else:
if not opened:
segmCtr += 1
opened.add(i)
print(segmCtr + max(ctr))
# inf.close()
``` | instruction | 0 | 91,853 | 23 | 183,706 |
Yes | output | 1 | 91,853 | 23 | 183,707 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r.
Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible.
Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:
* if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100];
* if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6].
Obviously, a union is a set of pairwise non-intersecting segments.
You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible.
For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then:
* erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union;
* erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union.
Thus, you are required to erase the third segment to get answer 2.
Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow.
The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively.
The segments are given in an arbitrary order.
It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5.
Output
Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Example
Input
3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
Output
2
1
5
Submitted Solution:
```
import io
import os
from collections import Counter, defaultdict, deque
# From: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SegmentTree.py
class SegmentTree:
def __init__(self, data, default=0, func=max):
"""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):
"""func of data[start, stop)"""
start += self._size
stop += self._size
res_left = res_right = self._default
while start < stop:
if start & 1:
res_left = self._func(res_left, self.data[start])
start += 1
if stop & 1:
stop -= 1
res_right = self._func(self.data[stop], res_right)
start >>= 1
stop >>= 1
return self._func(res_left, res_right)
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class SegmentData:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def pack(a, b, c):
return SegmentData(a, b, c) # 2588 ms
return [a, b, c] # 3790 ms
return (a, b, c) # 3027 ms
return (a << 40) + (b << 20) + c # TLE. Nicer on local because of 64-bit but cf is 32 bit
def unpack(abc):
return abc.a, abc.b, abc.c
return abc
return abc
ab, c = divmod(abc, 1 << 20)
a, b = divmod(ab, 1 << 20)
return a, b, c
def merge(x, y):
# Track numClose, numNonOverlapping, numOpen:
# e.g., )))) (...)(...)(...) ((((((
xClose, xFull, xOpen = unpack(x)
yClose, yFull, yOpen = unpack(y)
if xOpen == yClose == 0:
ret = xClose, xFull + yFull, yOpen
elif xOpen == yClose:
ret = xClose, xFull + 1 + yFull, yOpen
elif xOpen > yClose:
ret = xClose, xFull, xOpen - yClose + yOpen
elif xOpen < yClose:
ret = xClose + yClose - xOpen, yFull, yOpen
# print(x, y, ret)
return pack(*ret)
def solve(N, intervals):
endpoints = []
for i, (l, r) in enumerate(intervals):
endpoints.append((l, 0, i))
endpoints.append((r, 1, i))
endpoints.sort(key=lambda t: t[1])
endpoints.sort(key=lambda t: t[0])
# Build the segment tree and track the endpoints of each interval in the segment tree
data = []
# Note: defaultdict seems to be faster. Maybe because it traverses in segment tree order rather than randomly?
idToIndices = defaultdict(list)
for x, kind, intervalId in endpoints:
if kind == 0:
data.append(pack(0, 0, 1)) # '('
else:
assert kind == 1
data.append(pack(1, 0, 0)) # ')'
idToIndices[intervalId].append(len(data) - 1)
assert len(data) == 2 * N
segTree = SegmentTree(data, pack(0, 0, 0), merge)
# print("init", unpack(segTree.query(0, 2 * N)))
best = 0
for intervalId, indices in idToIndices.items():
# Remove the two endpoints
i, j = indices
removed1, removed2 = segTree[i], segTree[j]
segTree[i], segTree[j] = pack(0, 0, 0), pack(0, 0, 0)
# Query
res = unpack(segTree.query(0, 2 * N))
assert res[0] == 0
assert res[2] == 0
best = max(best, res[1])
# print("after removing", intervals[intervalId], res)
# Add back the two endpoints
segTree[i], segTree[j] = removed1, removed2
return best
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for t in range(T):
(N,) = [int(x) for x in input().split()]
intervals = [[int(x) for x in input().split()] for i in range(N)]
ans = solve(N, intervals)
print(ans)
``` | instruction | 0 | 91,854 | 23 | 183,708 |
Yes | output | 1 | 91,854 | 23 | 183,709 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r.
Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible.
Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:
* if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100];
* if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6].
Obviously, a union is a set of pairwise non-intersecting segments.
You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible.
For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then:
* erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union;
* erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union.
Thus, you are required to erase the third segment to get answer 2.
Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow.
The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively.
The segments are given in an arbitrary order.
It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5.
Output
Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Example
Input
3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
Output
2
1
5
Submitted Solution:
```
import sys
from math import gcd
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
def solve():
n = mint()
a = [None]*(2*n)
c = [0]*(2*n)
for i in range(0,2*n,2):
l, r = mints()
a[i] = (l*2, 0, i)
a[i+1] = (r*2+1, 1, i)
c[i+1] = (l*2, r*2+1)
a.sort()
#print(a)
s = set()
p = None
start = None
px = int(-2e9-5) # prev event
pt = -1
pp = px
segs = []
for i in range(0, 2*n):
x, t, id = a[i]
if px != x:
#print(px,x)
cd = len(s)
if cd == 1:
segs.append((px, x, cd, next(iter(s))))
else:
segs.append((px, x, cd, None))
px = x
if t == 0:
s.add(id)
else:
s.remove(id)
segs.append((px,int(2e9+5), 0, None))
res = 0
p = False
for i in range(1,len(segs)-1):
px, x, cd, e = segs[i]
if e != None:
l,r = c[e+1]
cl = segs[i-1][2]
cr = segs[i+1][2]
if cl - (segs[i-1][0] >= l) > 0 \
and cr - (segs[i-1][0] <= r) > 0:
c[e] += 1
if cl == 0 and cr == 0:
c[e] -= 1
if cd > 0 and p == False:
res += 1
p = (cd > 0)
z = c[0]
for i in range(0, 2*n, 2):
z = max(z, c[i])
print(res+z)
for i in range(mint()):
solve()
``` | instruction | 0 | 91,855 | 23 | 183,710 |
Yes | output | 1 | 91,855 | 23 | 183,711 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r.
Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible.
Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:
* if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100];
* if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6].
Obviously, a union is a set of pairwise non-intersecting segments.
You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible.
For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then:
* erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union;
* erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union.
Thus, you are required to erase the third segment to get answer 2.
Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow.
The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively.
The segments are given in an arbitrary order.
It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5.
Output
Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Example
Input
3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
Output
2
1
5
Submitted Solution:
```
def solve(lsts):
points = []
for i in range(len(lsts)):
points.append((lst[i][0], 0, i))
points.append((lst[i][1], 1, i))
points.sort()
open = set()
increased = [0] * len(lsts)
original = 0
for i in range(len(points)):
p = points[i]
if p[1] == 0:
open.add(p[2])
else:
open.remove(p[2])
if len(open) == 1 and p[1] == 1 and points[i+1][1] == 0 :
increased[list(open)[0]] += 1
if len(open) == 1 and p[1] == 0 and points[i+1][1] == 1:
increased[list(open)[0]] -= 1
# also keep track of what was the original answer without removing
if len(open) == 0:
original += 1
res = 0
for i in range(len(lsts)):
res = max(res, increased[i])
return res + original
n = int(input())
for _ in range(n):
m = int(input())
lst = []
for _ in range(m):
lst.append(list(map(int, input().split())))
print(solve(lst))
``` | instruction | 0 | 91,856 | 23 | 183,712 |
No | output | 1 | 91,856 | 23 | 183,713 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r.
Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible.
Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:
* if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100];
* if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6].
Obviously, a union is a set of pairwise non-intersecting segments.
You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible.
For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then:
* erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union;
* erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union.
Thus, you are required to erase the third segment to get answer 2.
Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow.
The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively.
The segments are given in an arbitrary order.
It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5.
Output
Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Example
Input
3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
Output
2
1
5
Submitted Solution:
```
import sys
from collections import deque
def input():
return sys.stdin.readline().rstrip()
t = int(input())
for _ in range(t):
n = int(input())
segs = []
for i in range(n):
l,r = list(map(int, input().split()))
segs.append((l,0,i))
segs.append((r,1,i))
segs.sort()
active = set()
increase = [0 for _ in range(n)]
seq = []
ans = 0
for pos, p, i in segs:
if p == 0:
if len(seq)>1 and seq[-2:] == [2,1]:
increase[next(iter(active))]+=1
active.add(i)
else:
active.remove(i)
if len(active) == 0:
ans+=1
seq.append(len(active))
print(ans+max(increase))
``` | instruction | 0 | 91,857 | 23 | 183,714 |
No | output | 1 | 91,857 | 23 | 183,715 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r.
Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible.
Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:
* if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100];
* if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6].
Obviously, a union is a set of pairwise non-intersecting segments.
You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible.
For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then:
* erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union;
* erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union.
Thus, you are required to erase the third segment to get answer 2.
Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow.
The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively.
The segments are given in an arbitrary order.
It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5.
Output
Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Example
Input
3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
Output
2
1
5
Submitted Solution:
```
import sys
from math import gcd
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
def solve():
n = mint()
a = [None]*(2*n)
c = [0]*(2*n)
for i in range(0,2*n,2):
l, r = mints()
a[i] = (l*2, 0, i)
a[i+1] = (r*2+1, 1, i)
c[i+1] = (l*2, r*2+1)
a.sort()
#print(a)
s = set()
p = None
start = None
px = int(-2e9-5) # prev event
pt = -1
pp = px
segs = []
for i in range(0, 2*n):
x, t, id = a[i]
if px != x:
#print(px,x)
cd = len(s)
if cd == 1:
segs.append((px, x, cd, next(iter(s))))
else:
segs.append((px, x, cd, None))
px = x
if t == 0:
s.add(id)
else:
s.remove(id)
segs.append((px,int(2e9+5), 0, None))
res = 0
p = False
for i in range(1,len(segs)-1):
px, x, cd, e = segs[i]
if e != None:
l,r = c[e+1]
cl = segs[i-1][2]
cr = segs[i+1][2]
if cl - (segs[i-1][0] >= l) > 0 \
and cr - (segs[i-1][0] <= r) > 0 \
or cl == 0 and cr == 0:
c[e] += 1
if cd > 0 and p == False:
res += 1
p = (cd > 0)
z = 0
for i in range(0, 2*n, 2):
z = max(z, c[i])
print(res+z)
for i in range(mint()):
solve()
``` | instruction | 0 | 91,858 | 23 | 183,716 |
No | output | 1 | 91,858 | 23 | 183,717 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n segments on a Ox axis [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Segment [l, r] covers all points from l to r inclusive, so all x such that l ≤ x ≤ r.
Segments can be placed arbitrarily — be inside each other, coincide and so on. Segments can degenerate into points, that is l_i=r_i is possible.
Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:
* if n=3 and there are segments [3, 6], [100, 100], [5, 8] then their union is 2 segments: [3, 8] and [100, 100];
* if n=5 and there are segments [1, 2], [2, 3], [4, 5], [4, 6], [6, 6] then their union is 2 segments: [1, 3] and [4, 6].
Obviously, a union is a set of pairwise non-intersecting segments.
You are asked to erase exactly one segment of the given n so that the number of segments in the union of the rest n-1 segments is maximum possible.
For example, if n=4 and there are segments [1, 4], [2, 3], [3, 6], [5, 7], then:
* erasing the first segment will lead to [2, 3], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the second segment will lead to [1, 4], [3, 6], [5, 7] remaining, which have 1 segment in their union;
* erasing the third segment will lead to [1, 4], [2, 3], [5, 7] remaining, which have 2 segments in their union;
* erasing the fourth segment will lead to [1, 4], [2, 3], [3, 6] remaining, which have 1 segment in their union.
Thus, you are required to erase the third segment to get answer 2.
Write a program that will find the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n-1 segments.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the test. Then the descriptions of t test cases follow.
The first of each test case contains a single integer n (2 ≤ n ≤ 2⋅10^5) — the number of segments in the given set. Then n lines follow, each contains a description of a segment — a pair of integers l_i, r_i (-10^9 ≤ l_i ≤ r_i ≤ 10^9), where l_i and r_i are the coordinates of the left and right borders of the i-th segment, respectively.
The segments are given in an arbitrary order.
It is guaranteed that the sum of n over all test cases does not exceed 2⋅10^5.
Output
Print t integers — the answers to the t given test cases in the order of input. The answer is the maximum number of segments in the union of n-1 segments if you erase any of the given n segments.
Example
Input
3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
Output
2
1
5
Submitted Solution:
```
import sys
input = sys.stdin.readline
import bisect
t=int(input())
for test in range(t):
n=int(input())
S=[tuple(map(int,input().split())) for i in range(n)]
S.append((1<<31,1<<31))
S.sort()
MAX=[S[0][1]]
for l,r in S[1:]:
MAX.append(max(MAX[-1],r))
#print(S)
#print(MAX)
restmove=[0]*(n+1)
for i in range(n-1,-1,-1):
l,r=S[i]
x=bisect.bisect_left(S,(r,1<<31))
if x-1!=i:
restmove[i]=restmove[x-1]
else:
restmove[i]=restmove[i+1]+1
frontmove=[0]*(n+1)
frontmove[0]=1
for i in range(1,n):
if MAX[i-1]<S[i][0]:
frontmove[i]=frontmove[i-1]+1
else:
frontmove[i]=frontmove[i-1]
#print(restmove)
#print(frontmove)
ANS=restmove[0]
for i in range(1,n):
l,r=S[i]
if r<=MAX[i-1]:
continue
else:
l2,r2=S[i-1]
x=bisect.bisect_left(S,(MAX[i-1],1<<31))
if r2>=S[x][0]:
continue
else:
ANS=max(ANS,restmove[x]+frontmove[i-1])
print(ANS)
``` | instruction | 0 | 91,859 | 23 | 183,718 |
No | output | 1 | 91,859 | 23 | 183,719 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that
* starts in the upper left cell of the matrix;
* each following cell is to the right or down from the current cell;
* the way ends in the bottom right cell.
Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros.
Input
The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109).
Output
In the first line print the least number of trailing zeros. In the second line print the correspondent way itself.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
0
DDRR | instruction | 0 | 92,054 | 23 | 184,108 |
Tags: dp, math
Correct Solution:
```
"""
#If FastIO not needed, use this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""
import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
import time
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
self.os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string
start_time = time.time()
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input()
def listStr():
return list(input())
def getMat(n):
return [getInts() for _ in range(n)]
def isInt(s):
return '0' <= s[0] <= '9'
MOD = 998244353
"""
For any given path we only need to know its factors of 2 and 5
"""
def calc(x,f):
if not x:
return -1
ans = 0
while x % f == 0:
x //= f
ans += 1
return ans
def solve():
N = getInt()
M = getMat(N)
M2 = [[calc(M[i][j],2) for j in range(N)] for i in range(N)]
M5 = [[calc(M[i][j],5) for j in range(N)] for i in range(N)]
dp2 = [[0 for j in range(N)] for i in range(N)]
dp5 = [[0 for j in range(N)] for i in range(N)]
dp2[0][0] = M2[0][0]
dp5[0][0] = M5[0][0]
zero = [10**18,10**18]
if M[0][0] == 0: zero = [0,0]
for i in range(1,N):
if M[0][i] == 0: zero = [0,i]
if M[i][0] == 0: zero = [i,0]
if -1 in [dp2[i-1][0],M2[i][0]]:
dp2[i][0] = -1
else:
dp2[i][0] = dp2[i-1][0] + M2[i][0]
if -1 in [dp2[0][i-1],M2[0][i]]:
dp2[0][i] = -1
else:
dp2[0][i] = dp2[0][i-1] + M2[0][i]
if -1 in [dp5[i-1][0],M5[i][0]]:
dp5[i][0] = -1
else:
dp5[i][0] = dp5[i-1][0] + M5[i][0]
if -1 in [dp5[0][i-1],M5[0][i]]:
dp5[0][i] = -1
else:
dp5[0][i] = dp5[0][i-1] + M5[0][i]
for i in range(1,N):
for j in range(1,N):
if M[i][j] == 0: zero = [i,j]
if dp2[i-1][j]*dp2[i][j-1]+M2[i][j] == 0:
dp2[i][j] = 0
elif -1 in [dp2[i-1][j],dp2[i][j-1],M2[i][j]]:
dp2[i][j] = -1
else:
dp2[i][j] = min(dp2[i-1][j],dp2[i][j-1]) + M2[i][j]
if dp5[i-1][j]*dp5[i][j-1]+M5[i][j] == 0:
dp5[i][j] = 0
elif -1 in [dp5[i-1][j],dp5[i][j-1],M5[i][j]]:
dp5[i][j] = -1
else:
dp5[i][j] = min(dp5[i-1][j],dp5[i][j-1]) + M5[i][j]
i, j = N-1, N-1
ans1 = dp2[i][j]
ans2 = dp5[i][j]
ans = []
if not ans1:
print(0)
while i+j:
if not i:
ans.append('R')
j -= 1
elif not j:
ans.append('D')
i -= 1
elif dp2[i-1][j] + M2[i][j] == dp2[i][j]:
ans.append('D')
i -= 1
else:
ans.append('R')
j -= 1
print(''.join(ans[::-1]))
return
elif not ans2:
print(0)
while i+j:
if not i:
ans.append('R')
j -= 1
elif not j:
ans.append('D')
i -= 1
elif dp5[i-1][j] + M5[i][j] == dp5[i][j]:
ans.append('D')
i -= 1
else:
ans.append('R')
j -= 1
print(''.join(ans[::-1]))
return
elif -1 in [ans1,ans2]:
print(1)
i, j = zero
ans = ['R']*j + ['D']*i + ['R']*(N-j-1) + ['D']*(N-i-1)
print(''.join(ans))
return
print(min(ans1,ans2))
if ans1 <= ans2:
while i+j:
if not i:
ans.append('R')
j -= 1
elif not j:
ans.append('D')
i -= 1
elif dp2[i-1][j] + M2[i][j] == dp2[i][j]:
ans.append('D')
i -= 1
else:
ans.append('R')
j -= 1
else:
while i+j:
if not i:
ans.append('R')
j -= 1
elif not j:
ans.append('D')
i -= 1
elif dp5[i-1][j] + M5[i][j] == dp5[i][j]:
ans.append('D')
i -= 1
else:
ans.append('R')
j -= 1
print(''.join(ans[::-1]))
return
#for _ in range(getInt()):
#print(solve())
solve()
#print(time.time()-start_time)
``` | output | 1 | 92,054 | 23 | 184,109 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that
* starts in the upper left cell of the matrix;
* each following cell is to the right or down from the current cell;
* the way ends in the bottom right cell.
Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros.
Input
The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109).
Output
In the first line print the least number of trailing zeros. In the second line print the correspondent way itself.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
0
DDRR
Submitted Solution:
```
#2B - The least round way
n = int(input())
m = []
for i in range(n):
m.append(list(map(int, input().split())))
#Empty nxn matrix for the divisors of 2
div2 = [[0 for i in range(n)] for ii in range(n)]
#Empty nxn matrix for the divisors of 5
div5 = [[0 for i in range(n)] for ii in range(n)]
ans = 0
#Loop for cases where we have 0 in input
for i in range(n):
for ii in range(n):
if m[i][ii] == 0:
ans = 1
#The following variable will store the final path
path = 'R' * ii + 'D' * i + 'R' * (n - 1 - ii) + 'D' * (n - 1 - i)
m[i][ii] = 10
#Loop for rest of the cases
#We try to find cells that decompose in factors of 2 and 5
for i in range(n):
for ii in range(n):
x = m[i][ii]
while x % 2 == 0 and x > 0:
div2[i][ii] += 1
x //= 2
while x % 5 == 0 and x > 0:
div5[i][ii] += 1
x //= 5
#Now, we start the actual movement
#We add each number we pass to the previous one as we go
for i in range(1, n):
div2[i][0] += div2[i - 1][0]
div2[0][i] += div2[0][i - 1]
div5[i][0] += div5[i - 1][0]
div5[0][i] += div5[0][i - 1]
#We apply the previous loop procedure to the entire list
for i in range(1, n):
for ii in range(1, n):
div2[i][ii] += min(div2[i - 1][ii], div2[i][ii - 1])
div5[i][ii] += min(div5[i - 1][ii], div5[i][ii - 1])
#We record the number of zeros resulted from our movement
if div2[-1][-1] < div5[-1][-1]:
dp = div2
else:
dp = div5
if ans == 1 and dp[-1][-1]:
print(ans)
print(path)
#We start from the top left corner, recording our moves on our
#way to the bottom right corner
else:
i, ii = n - 1, n - 1
path = ''
#Now, we determine the direction we moved into by comparing our
#current position to the previous one and include the record in path
while i or ii:
if not i:
path += 'R'
ii -= 1
elif not ii:
path += 'D'
i -= 1
else:
if dp[i - 1][ii] < dp[i][ii - 1]:
path += 'D'
i -= 1
else:
path += 'R'
ii -= 1
path = path[::-1]
#Now, we print the least number of trailing zeros, then the full record of the moves
print(dp[-1][-1])
print(path)
``` | instruction | 0 | 92,058 | 23 | 184,116 |
Yes | output | 1 | 92,058 | 23 | 184,117 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that
* starts in the upper left cell of the matrix;
* each following cell is to the right or down from the current cell;
* the way ends in the bottom right cell.
Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros.
Input
The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109).
Output
In the first line print the least number of trailing zeros. In the second line print the correspondent way itself.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
0
DDRR
Submitted Solution:
```
import sys,math
# Initialize grid
n = int(sys.stdin.readline())
grid = []
for i in range(0,n):
grid.append(list(map(int,sys.stdin.readline().split())))
# Check for 0 (which will make the answer at most 1, does not play well)
zero_exists = False
zero_row = 0
zero_col = 0
for i in range(0,n):
for j in range(0,n):
if grid[i][j] == 0:
zero_exists = True
zero_row = i
zero_col = j
# Purely minimize 2s (ignoring 2s)
def v_p(n, p):
if n == 0:
return math.inf
elif n%p != 0:
return 0
else:
return 1+v_p(n//p,p)
twos = list(map(lambda row: list(map(lambda i: v_p(i,2),row)), grid))
twos_dp = []
twos_path = []
for i in range(0,n):
twos_dp.append([])
twos_path.append([])
for j in range(0,n):
twos_dp[i].append(0)
twos_path[i].append('')
for index_sum in range(0,2*n-1):
for i in range(max(0,index_sum-n+1),min(n,index_sum+1)):
j = index_sum - i
if i == 0 and j == 0:
twos_dp[0][0] = twos[0][0]
elif i == 0:
twos_dp[0][j] = twos_dp[0][j-1] + twos[0][j]
twos_path[0][j] = 'R'
elif j == 0:
twos_dp[i][0] = twos_dp[i-1][0] + twos[i][0]
twos_path[i][0] = 'D'
else:
if twos_dp[i-1][j] < twos_dp[i][j-1]:
twos_dp[i][j] = twos_dp[i-1][j] + twos[i][j]
twos_path[i][j] = 'D'
else:
twos_dp[i][j] = twos_dp[i][j-1] + twos[i][j]
twos_path[i][j] = 'R'
# Purely minimize 5s (ignoring 5s)
fives = list(map(lambda row: list(map(lambda i: v_p(i,5),row)), grid))
fives_dp = []
fives_path = []
for i in range(0,n):
fives_dp.append([])
fives_path.append([])
for j in range(0,n):
fives_dp[i].append(0)
fives_path[i].append(0)
for index_sum in range(0,2*n-1):
for i in range(max(0,index_sum-n+1),min(n,index_sum+1)):
j = index_sum - i
if i == 0 and j == 0:
fives_dp[0][0] = fives[0][0]
elif i == 0:
fives_dp[0][j] = fives_dp[0][j-1] + fives[0][j]
fives_path[0][j] = 'R'
elif j == 0:
fives_dp[i][0] = fives_dp[i-1][0] + fives[i][0]
fives_path[i][0] = 'D'
else:
if fives_dp[i-1][j] < fives_dp[i][j-1]:
fives_dp[i][j] = fives_dp[i-1][j] + fives[i][j]
fives_path[i][j] = 'D'
else:
fives_dp[i][j] = fives_dp[i][j-1] + fives[i][j]
fives_path[i][j] ='R'
def recover_path(grid):
i = n-1
j = n-1
string = ''
while i != 0 or j != 0:
string = grid[i][j] + string
if grid[i][j] == 'R':
j -= 1
elif grid[i][j] == 'D':
i -= 1
else:
print("This should not be reached")
return string
# The answer is as least as good and cannot be better than either one
if zero_exists and twos_dp[n-1][n-1] >= 1 and fives_dp[n-1][n-1] > 1:
print(1)
path = ''
for i in range(0,zero_row):
path += 'D'
for j in range(0,zero_col):
path += 'R'
for i in range(zero_row+1,n):
path += 'D'
for j in range(zero_col+1,n):
path += 'R'
print(path)
elif twos_dp[n-1][n-1] <= fives_dp[n-1][n-1]:
print(twos_dp[n-1][n-1])
print(recover_path(twos_path))
else:
print(fives_dp[n-1][n-1])
print(recover_path(fives_path))
``` | instruction | 0 | 92,059 | 23 | 184,118 |
Yes | output | 1 | 92,059 | 23 | 184,119 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that
* starts in the upper left cell of the matrix;
* each following cell is to the right or down from the current cell;
* the way ends in the bottom right cell.
Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros.
Input
The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109).
Output
In the first line print the least number of trailing zeros. In the second line print the correspondent way itself.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
0
DDRR
Submitted Solution:
```
def sqr_5_converter(i):
global num_called
num_called += 1
if i != 0:
b = (i%2 == 0) or (i%5 == 0); num_2s = 0; num_5s = 0
while b:
if i%2 == 0: num_2s += 1; i = i//2;
if i%5 == 0: num_5s += 1; i = i//5;
b = (i%2 == 0) or (i%5 == 0)
return (num_2s, num_5s)
else:
global zero
if not zero:
zero = True
global zero_spot
rem = num_called%n
quot = num_called//n
if num_called%n == 0:
zero_spot = (quot - 1, n - 1)
else:
zero_spot = (quot, rem - 1)
return (1, 1)
#needs to choose the one with less 0's.
def grim_reaper(r, d, add):
if r[0] < d[0]:
if r[1] < d[1]: return (r[0] + add[0], r[1] + add[1])
else: return (r[0] + add[0], d[1] + add[1])
else:
if r[1] < d[1]: return (d[0] + add[0], r[1] + add[1])
else: return (d[0] + add[0], d[1] + add[1])
def backtracker(mode, path, m, n): # backtracker now needs to follow the zero in case of zero
if mode == 2:
global zero_spot
x = zero_spot[1]; y = zero_spot[0]
print('R'*x + 'D'*y + 'R'*(n-x) + 'D'*(m-y)); return;
else:
if m == 0 or n == 0:
if m == 0 and n == 0: print(path); return;
elif m == 0: print('R'*n + path); return;
else: print('D'*m + path); return;
else: # 0 for 2 and 1 for 5
if arr[m-1][n][mode] < arr[m][n-1][mode]: backtracker(mode, 'D' + path, m-1,n);
elif arr[m-1][n][mode] == arr[m][n-1][mode]:
if arr[m-1][n][(mode + 1)%2] <= arr[m][n-1][(mode + 1)%2]: backtracker(mode, 'D' + path, m-1,n)
else: backtracker(mode, 'R' + path, m,n-1);
else: backtracker(mode, 'R' + path, m,n-1);
#first route is for the 2s and second is for the 5s
n = int(input())
arr = [[1]]*n
zero = False
zero_spot = (0, 0)
num_called = 0
for i in range(n):
a = list(map(sqr_5_converter, (map(int, input().split()))))
arr[i] = a
for j in range(n):
for k in range(n):
if j == 0 or k == 0:
if j == 0 and k == 0: continue
elif j == 0: arr[j][k] = (arr[j][k-1][0] + arr[j][k][0], arr[j][k-1][1] + arr[j][k][1])
else: arr[j][k] = (arr[j-1][k][0] + arr[j][k][0], arr[j-1][k][1] + arr[j][k][1])
else:
arr[j][k] = grim_reaper(arr[j][k-1], arr[j-1][k], arr[j][k])
val = min(arr[n-1][n-1][0], arr[n-1][n-1][1])
if zero and val >= 1:
print(1)
backtracker(2,'',n-1,n-1)
else:
print(val)
if arr[n-1][n-1][0] < arr[n-1][n-1][1]: backtracker(0,'',n-1,n-1)
else: backtracker(1,'',n-1,n-1)
``` | instruction | 0 | 92,060 | 23 | 184,120 |
Yes | output | 1 | 92,060 | 23 | 184,121 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that
* starts in the upper left cell of the matrix;
* each following cell is to the right or down from the current cell;
* the way ends in the bottom right cell.
Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros.
Input
The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109).
Output
In the first line print the least number of trailing zeros. In the second line print the correspondent way itself.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
0
DDRR
Submitted Solution:
```
from pprint import pprint
def countzero(num):
if num==0:
return 1
i = 0
while num > 0:
if num%10:
break
num = num // 10
i += 1
return i
def solve(block, n):
# create a copy
dp = []
for i in range(n):
dp.append([0]*n)
for i in range(n):
for j in range(n):
if i==0 and j==0:
dp[i][j] = (0, 0, block[0][0])
elif i==0 and not j==0:
__, __, c = dp[i][j-1]
dp[i][j] = (i, j-1, c*block[i][j])
elif not i==0 and j==0:
__, __, c = dp[i-1][j]
dp[i][j] = (i-1, j, c*block[i][j])
else:
__, __, c1 = dp[i][j-1]
__, __, c2 = dp[i-1][j]
if countzero(c1) < countzero(c2):
dp[i][j] = (i, j-1, c1*block[i][j])
else:
dp[i][j] = (i-1, j, c2*block[i][j])
print(countzero(dp[n-1][n-1][2]))
#get path
path=""
start = (0, 0)
cur = (n-1, n-1)
while not cur == start:
a, b = cur
c, d, __ = dp[a][b]
if c == a-1:
path = "D" + path
if d == b-1:
path = "R" + path
cur = (c, d)
print(path)
return dp
n = int(input())
block = []
for i in range(n):
row = input().split()
row = list(map(int, row))
block.append(row)
ans = solve(block, n)
#pprint(ans)
``` | instruction | 0 | 92,063 | 23 | 184,126 |
No | output | 1 | 92,063 | 23 | 184,127 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that
* starts in the upper left cell of the matrix;
* each following cell is to the right or down from the current cell;
* the way ends in the bottom right cell.
Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros.
Input
The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109).
Output
In the first line print the least number of trailing zeros. In the second line print the correspondent way itself.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
0
DDRR
Submitted Solution:
```
import sys
input = sys.stdin.readline
from math import *
from bisect import *
from functools import reduce, lru_cache
from collections import Counter, defaultdict
n = int(input())
D = [list(map(int, input().split())) for _ in range(n)]
F = lambda x, p: 0 if x % p else 1 + F(x // p, p)
L = [((inf, ""), (inf, ""))] * (n + 1)
for x in range(n):
for y in range(n):
l2 = min(y, y + 1, key = lambda i: L[i][0][0])
l5 = min(y, y + 1, key = lambda i: L[i][1][0])
c2 = L[y][0][1] + "R" if l2 == y else L[y + 1][0][1] + "D"
c5 = L[y][1][1] + "R" if l5 == y else L[y + 1][1][1] + "D"
L[y + 1] = ((F(D[x][y], 2) +l2, c2), (F(D[x][y], 5) + l5, c5))
R = min(L[n])
print(R[0])
print(R[1][1:])
``` | instruction | 0 | 92,065 | 23 | 184,130 |
No | output | 1 | 92,065 | 23 | 184,131 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gena doesn't like geometry, so he asks you to solve this problem for him.
A rectangle with sides parallel to coordinate axes contains n dots. Let's consider some point of the plane. Let's count the distances from this point to the given n points. Let's sort these numbers in the non-decreasing order. We'll call the beauty of the point the second element of this array. If there are two mimimum elements in this array, the beaty will be equal to this minimum.
Find the maximum beauty of a point inside the given rectangle.
Input
The first line contains three integers w, h, n (1 ≤ w, h ≤ 106, 2 ≤ n ≤ 1000) — the lengths of the rectangle sides and the number of points. Next n lines contain two integers xi, yi (0 ≤ xi ≤ w, 0 ≤ yi ≤ h) each — the coordinates of a point. It is possible that it will be coincident points.
Output
Print a single number — the maximum beauty of a point with the absolute or relative error of at most 10 - 9.
Examples
Input
5 5 4
0 0
5 0
0 5
5 5
Output
4.99999999941792340
Input
5 5 3
4 0
2 5
4 1
Output
5.65685424744772010
Note
The point which beauty we need to find must have coordinates (x, y), where 0 ≤ x ≤ w, 0 ≤ y ≤ h. Some of the n points can coincide.
Submitted Solution:
```
import math
d = [eval(i) for i in input().split()]
v = []
for i in range(int(d[2])):
s = input().split()
v.append(round(float(math.sqrt(float(s[0])**2 + float(s[1])**2)), 9))
v = sorted(v)
print(v[1])
``` | instruction | 0 | 92,130 | 23 | 184,260 |
No | output | 1 | 92,130 | 23 | 184,261 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A big company decided to launch a new series of rectangular displays, and decided that the display must have exactly n pixels.
Your task is to determine the size of the rectangular display — the number of lines (rows) of pixels a and the number of columns of pixels b, so that:
* there are exactly n pixels on the display;
* the number of rows does not exceed the number of columns, it means a ≤ b;
* the difference b - a is as small as possible.
Input
The first line contains the positive integer n (1 ≤ n ≤ 106) — the number of pixels display should have.
Output
Print two integers — the number of rows and columns on the display.
Examples
Input
8
Output
2 4
Input
64
Output
8 8
Input
5
Output
1 5
Input
999999
Output
999 1001
Note
In the first example the minimum possible difference equals 2, so on the display should be 2 rows of 4 pixels.
In the second example the minimum possible difference equals 0, so on the display should be 8 rows of 8 pixels.
In the third example the minimum possible difference equals 4, so on the display should be 1 row of 5 pixels. | instruction | 0 | 92,251 | 23 | 184,502 |
Tags: brute force, math
Correct Solution:
```
from math import sqrt
def div(n):
i = 1
list = []
while i <= n:
if n % i == 0:
list.append(i)
i = i + 1
return list
n=int(input())
root=sqrt(n)
divs=div(n)
#print(divs)
listy=[abs(root-x) for x in divs]
min_index=listy.index(min(listy))
print("{} {}".format(int(divs[min_index]),int(n/divs[min_index])))
``` | output | 1 | 92,251 | 23 | 184,503 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A big company decided to launch a new series of rectangular displays, and decided that the display must have exactly n pixels.
Your task is to determine the size of the rectangular display — the number of lines (rows) of pixels a and the number of columns of pixels b, so that:
* there are exactly n pixels on the display;
* the number of rows does not exceed the number of columns, it means a ≤ b;
* the difference b - a is as small as possible.
Input
The first line contains the positive integer n (1 ≤ n ≤ 106) — the number of pixels display should have.
Output
Print two integers — the number of rows and columns on the display.
Examples
Input
8
Output
2 4
Input
64
Output
8 8
Input
5
Output
1 5
Input
999999
Output
999 1001
Note
In the first example the minimum possible difference equals 2, so on the display should be 2 rows of 4 pixels.
In the second example the minimum possible difference equals 0, so on the display should be 8 rows of 8 pixels.
In the third example the minimum possible difference equals 4, so on the display should be 1 row of 5 pixels. | instruction | 0 | 92,252 | 23 | 184,504 |
Tags: brute force, math
Correct Solution:
```
n = int(input())
for i in range(1,n+1):
if (n%i==0):
if (i>n//i):
break
a= i
b= n//i
print(a, b)
``` | output | 1 | 92,252 | 23 | 184,505 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A big company decided to launch a new series of rectangular displays, and decided that the display must have exactly n pixels.
Your task is to determine the size of the rectangular display — the number of lines (rows) of pixels a and the number of columns of pixels b, so that:
* there are exactly n pixels on the display;
* the number of rows does not exceed the number of columns, it means a ≤ b;
* the difference b - a is as small as possible.
Input
The first line contains the positive integer n (1 ≤ n ≤ 106) — the number of pixels display should have.
Output
Print two integers — the number of rows and columns on the display.
Examples
Input
8
Output
2 4
Input
64
Output
8 8
Input
5
Output
1 5
Input
999999
Output
999 1001
Note
In the first example the minimum possible difference equals 2, so on the display should be 2 rows of 4 pixels.
In the second example the minimum possible difference equals 0, so on the display should be 8 rows of 8 pixels.
In the third example the minimum possible difference equals 4, so on the display should be 1 row of 5 pixels. | instruction | 0 | 92,253 | 23 | 184,506 |
Tags: brute force, math
Correct Solution:
```
n = int(input())
res = 1
for i in range(2, int(n**0.5)+1):
if n%i == 0:
res = i
print(res, n//res)
``` | output | 1 | 92,253 | 23 | 184,507 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A big company decided to launch a new series of rectangular displays, and decided that the display must have exactly n pixels.
Your task is to determine the size of the rectangular display — the number of lines (rows) of pixels a and the number of columns of pixels b, so that:
* there are exactly n pixels on the display;
* the number of rows does not exceed the number of columns, it means a ≤ b;
* the difference b - a is as small as possible.
Input
The first line contains the positive integer n (1 ≤ n ≤ 106) — the number of pixels display should have.
Output
Print two integers — the number of rows and columns on the display.
Examples
Input
8
Output
2 4
Input
64
Output
8 8
Input
5
Output
1 5
Input
999999
Output
999 1001
Note
In the first example the minimum possible difference equals 2, so on the display should be 2 rows of 4 pixels.
In the second example the minimum possible difference equals 0, so on the display should be 8 rows of 8 pixels.
In the third example the minimum possible difference equals 4, so on the display should be 1 row of 5 pixels. | instruction | 0 | 92,254 | 23 | 184,508 |
Tags: brute force, math
Correct Solution:
```
from math import sqrt
n=int(input())
q=int(sqrt(n))
k=t=1
for i in range(1,q+1):
if n%i==0:
t=i
k=max(k,t)
print(k,n//k)
``` | output | 1 | 92,254 | 23 | 184,509 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.