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.
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
Input
The first line contains two integers a, b (1 ≤ a, b ≤ 1000), separated by a single space.
Output
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers — the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
Examples
Input
1 1
Output
NO
Input
5 5
Output
YES
2 1
5 5
-2 4
Input
5 10
Output
YES
-10 4
-2 -2
1 2 | instruction | 0 | 12,813 | 23 | 25,626 |
Tags: brute force, geometry, implementation, math
Correct Solution:
```
import math
squares = set()
for i in range(1, 1001):
squares.add(i ** 2)
def check(n):
global squares
for i in range(1, 1001):
if (n - i ** 2) in squares:
return True
return False
a, b = map(int, input().split())
g = math.gcd(a ** 2, b ** 2)
if check(g):
f = False
for i in range(1, 1001):
if (g - i ** 2) in squares:
x = i
y = int((g - i ** 2) ** 0.5)
t = int((a ** 2 // g) ** 0.5)
s = int((b ** 2 // g) ** 0.5)
if (abs(t*x) != abs(s * y)):
print("YES")
print(-t * y, t * x)
print(0, 0)
print(s * x, s * y)
f = True
break
if not f:
print("NO")
else:
print("NO")
``` | output | 1 | 12,813 | 23 | 25,627 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
Input
The first line contains two integers a, b (1 ≤ a, b ≤ 1000), separated by a single space.
Output
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers — the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
Examples
Input
1 1
Output
NO
Input
5 5
Output
YES
2 1
5 5
-2 4
Input
5 10
Output
YES
-10 4
-2 -2
1 2 | instruction | 0 | 12,814 | 23 | 25,628 |
Tags: brute force, geometry, implementation, math
Correct Solution:
```
x,y = map(int,input().split())
if x>=y:
a=x
b=y
else:
a=y
b=x
lmb = a/b
f=1
for i in range(1,b):
p = lmb*pow((b**2-i**2),1/2)
q = lmb*i
if p-int(p)<=0.00001 and q-int(q)<=0.00001:
print("YES")
print("0 0")
print(str(int(p/lmb))+" "+str(i))
print(str(-1*int(q))+" "+str(int(p)))
f=0
break
if f:
print("NO")
``` | output | 1 | 12,814 | 23 | 25,629 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
Input
The first line contains two integers a, b (1 ≤ a, b ≤ 1000), separated by a single space.
Output
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers — the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
Examples
Input
1 1
Output
NO
Input
5 5
Output
YES
2 1
5 5
-2 4
Input
5 10
Output
YES
-10 4
-2 -2
1 2 | instruction | 0 | 12,815 | 23 | 25,630 |
Tags: brute force, geometry, implementation, math
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
def main():
pass
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def count1(s):
c=0
for i in s:
if(i=='1'):
c+=1
return(c)
def binary(n):
return(bin(n).replace("0b",""))
def decimal(s):
return(int(s,2))
def pow2(n):
p=0
while(n>1):
n//=2
p+=1
return(p)
def isPrime(n):
if(n==1):
return(False)
else:
root=int(n**0.5)
root+=1
for i in range(2,root):
if(n%i==0):
return(False)
return(True)
a,b=map(int,input().split())
a,b=min(a,b),max(a,b)
f=False
ans=[[0,0]]
f=False
l1=[]
l2=[]
for i in range(1,a):
t=(a*a-i*i)**0.5
if(int(t)==t):
l1.append([int(t),i])
for i in range(1,b):
t=(b*b-i*i)**0.5
if(int(t)==t):
l2.append([int(t),-i])
f=True
for i in range(0,len(l1)):
if(f):
for j in range(0,len(l2)):
x1=l1[i][0]
x2=l2[j][0]
y1=l1[i][1]
y2=l2[j][1]
if(x1!=x2 and ((y2-y1)**2+(x2-x1)**2)==(a**2+b**2)):
f=False
print("YES")
print(0,0)
print(x1,y1)
print(x2,y2)
break
if(f):
print("NO")
``` | output | 1 | 12,815 | 23 | 25,631 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
Input
The first line contains two integers a, b (1 ≤ a, b ≤ 1000), separated by a single space.
Output
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers — the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
Examples
Input
1 1
Output
NO
Input
5 5
Output
YES
2 1
5 5
-2 4
Input
5 10
Output
YES
-10 4
-2 -2
1 2 | instruction | 0 | 12,816 | 23 | 25,632 |
Tags: brute force, geometry, implementation, math
Correct Solution:
```
from math import *
a,b=map(int,input().split())
def gen(n):
for x in range(1,n):
y = round(sqrt(n*n-x*x))
if x*x+y*y == n*n:
yield (x,y)
for u in gen(a):
for v in gen(b):
if u[0]*v[0]-u[1]*v[1]==0 and u[0]!=v[0]:
print("YES\n0 0")
print(u[0],u[1])
print(v[0],-v[1])
exit()
print("NO")
``` | output | 1 | 12,816 | 23 | 25,633 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
Input
The first line contains two integers a, b (1 ≤ a, b ≤ 1000), separated by a single space.
Output
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers — the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
Examples
Input
1 1
Output
NO
Input
5 5
Output
YES
2 1
5 5
-2 4
Input
5 10
Output
YES
-10 4
-2 -2
1 2
Submitted Solution:
```
#!/usr/bin/python3 -SOO
from math import sqrt
a,b = map(int,input().strip().split())
for i in range(1,a):
x = a*a - i*i
if x<=0 or int(sqrt(x) + 0.5)**2 != x: continue
u = b*i/a
v = b*sqrt(x)/a
if abs(u-int(u)) < 0.0005 and abs(v-int(v)) < 0.0005 and int(v)!=i:
print('YES')
print('0 0')
print('%d %d'%(-int(u),int(v)))
print('%d %d'%(int(sqrt(x)),i))
break
else:
print('NO')
``` | instruction | 0 | 12,817 | 23 | 25,634 |
Yes | output | 1 | 12,817 | 23 | 25,635 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
Input
The first line contains two integers a, b (1 ≤ a, b ≤ 1000), separated by a single space.
Output
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers — the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
Examples
Input
1 1
Output
NO
Input
5 5
Output
YES
2 1
5 5
-2 4
Input
5 10
Output
YES
-10 4
-2 -2
1 2
Submitted Solution:
```
a,b=map(int,input().split())
def get(a):
return list([i,j] for i in range(1,a) for j in range(1,a) if i*i+j*j==a*a)
A=get(a)
B=get(b)
for [a,b] in A:
for [c,d] in B:
if a*c==b*d and b!=d:
print("YES\n0 0\n%d %d\n%d %d" %(-a,b,c,d))
exit(0)
print("NO")
``` | instruction | 0 | 12,818 | 23 | 25,636 |
Yes | output | 1 | 12,818 | 23 | 25,637 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
Input
The first line contains two integers a, b (1 ≤ a, b ≤ 1000), separated by a single space.
Output
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers — the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
Examples
Input
1 1
Output
NO
Input
5 5
Output
YES
2 1
5 5
-2 4
Input
5 10
Output
YES
-10 4
-2 -2
1 2
Submitted Solution:
```
a, b = map(int, input().split())
import math
EPS = 1e-9
for x1 in range(1, a):
y1 = math.sqrt(a**2 - x1**2)
if y1.is_integer():
y1 = round(y1)
g = math.gcd(x1, y1)
xv, yv = -1* (y1//g), x1//g
r = b / (math.sqrt(xv**2 + yv**2))
if r.is_integer() and round(yv*r) != y1:
print("YES")
print(0, 0)
print(round(x1), round(y1))
print(round(xv*r), round(yv*r))
break
else:
print("NO")
``` | instruction | 0 | 12,819 | 23 | 25,638 |
Yes | output | 1 | 12,819 | 23 | 25,639 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
Input
The first line contains two integers a, b (1 ≤ a, b ≤ 1000), separated by a single space.
Output
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers — the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
Examples
Input
1 1
Output
NO
Input
5 5
Output
YES
2 1
5 5
-2 4
Input
5 10
Output
YES
-10 4
-2 -2
1 2
Submitted Solution:
```
from math import hypot
a, b = map(int, input().split())
c = max(a, b)
for x in range(1, c + 1):
for y in range(1, c + 1):
if abs(hypot(x, y) - a) <= 1e-12:
nx = y
ny = -x
l = hypot(nx, ny)
nx = round(nx / l * b)
ny = round(ny / l * b)
if x != nx and abs(hypot(nx, ny) - b) <= 1e-12:
print("YES")
print(x, y)
print(nx, ny)
print(0, 0)
exit()
print("NO")
``` | instruction | 0 | 12,820 | 23 | 25,640 |
Yes | output | 1 | 12,820 | 23 | 25,641 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
Input
The first line contains two integers a, b (1 ≤ a, b ≤ 1000), separated by a single space.
Output
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers — the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
Examples
Input
1 1
Output
NO
Input
5 5
Output
YES
2 1
5 5
-2 4
Input
5 10
Output
YES
-10 4
-2 -2
1 2
Submitted Solution:
```
a, b = map(int, input().split())
cand_a = []
cand_b = []
for i in range(1, 1000):
j = 1
while j * j + i * i <= 1000000:
if i * i + j * j == a * a:
cand_a.append((i, j))
if i * i + j * j == b * b:
cand_b.append((-i, j))
j += 1
def dist(a, b):
return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2
for point_a in cand_a:
for point_b in cand_b:
print(point_a, point_b)
if dist(point_a, point_b) == a * a + b * b:
print("YES")
print("0 0")
print("%d %d" % (point_a[0], point_a[1]))
print("%d %d" % (point_b[0], point_b[1]))
exit(0)
print("NO")
``` | instruction | 0 | 12,821 | 23 | 25,642 |
No | output | 1 | 12,821 | 23 | 25,643 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
Input
The first line contains two integers a, b (1 ≤ a, b ≤ 1000), separated by a single space.
Output
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers — the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
Examples
Input
1 1
Output
NO
Input
5 5
Output
YES
2 1
5 5
-2 4
Input
5 10
Output
YES
-10 4
-2 -2
1 2
Submitted Solution:
```
import math
def square(a):
lis=[]
for k in range(a+1):
if math.sqrt(a**2-k **2)==int(math.sqrt(a**2-k **2)):
lis.append((k,math.sqrt(a**2-k **2)))
return lis
def check(a):
boo=1
if len(square(a))==2 and int(math.sqrt(a))==math.sqrt(a):
boo=0
return boo
a,b=input().split()
a=int(a)
b=int(b)
if check(a)*check(b)==0:
print('NO')
else:
v=0
lisA=[]
lisB=[]
for A in square(a):
for B in square(b):
if A[0]*B[0]-A[1]*B[1]==0:
v=1
lisA.append(A)
lisB.append(B)
if v==1:
print('YES')
print(0,0)
print(-int(lisA[1][0]),int(lisA[1][1]))
print(int(lisB[1][0]),int(lisB[1][1]))
else:
print('NO')
``` | instruction | 0 | 12,822 | 23 | 25,644 |
No | output | 1 | 12,822 | 23 | 25,645 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
Input
The first line contains two integers a, b (1 ≤ a, b ≤ 1000), separated by a single space.
Output
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers — the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
Examples
Input
1 1
Output
NO
Input
5 5
Output
YES
2 1
5 5
-2 4
Input
5 10
Output
YES
-10 4
-2 -2
1 2
Submitted Solution:
```
a,b=map(int,input().split())
x1,y1=0,0
for i in range(1,1001):
for j in range(i+1,1001):
if a**2==i**2+j**2 and x1==0:
x1,y1=i,j
x2,y2=-10**18,-10**18
for i in range(-1000,1001):
if i==0:
continue
for j in range(-1000,1001):
if j==0:
continue
if b**2==i**2+j**2 and i*x1+j*y1==0 and x2==-10**18 and (not x1==i or y1==j):
x2,y2=i,j
if x1>0 and x2!=-10**18:
print("YES")
print(0,0)
print(x1,y1)
print(x2,y2)
else:
print("NO")
``` | instruction | 0 | 12,823 | 23 | 25,646 |
No | output | 1 | 12,823 | 23 | 25,647 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
Input
The first line contains two integers a, b (1 ≤ a, b ≤ 1000), separated by a single space.
Output
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers — the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
Examples
Input
1 1
Output
NO
Input
5 5
Output
YES
2 1
5 5
-2 4
Input
5 10
Output
YES
-10 4
-2 -2
1 2
Submitted Solution:
```
from math import sqrt
def dist(A, B):
x = A[0] - B[0]
y = A[1] - B[1]
return sqrt(x**2 + y**2)
def is_int(gip, kat):
if not sqrt(gip**2 - kat**2)%1:
return True
else:
return False
A = 0, 0
B = 0, 0
C = 0, 0
a, b = list(map(int, input().split()))
#a, b = 5, 5
#print(a, b)
result = 'NO'
for x in range(A[0]+1, A[0]+a):
if is_int(a, x):
B = x, int(sqrt(a**2 - x**2))
cos = B[1]/a
#print(cos)
newx = cos*b
#print(newx%1)
if not newx%1:
C = -int(newx), int(sqrt(b**2 - newx**2))
result = 'YES'
#print(A, B, C)
#print(x)
print(result)
if result == 'YES':
print(A[0], A[1])
print(B[0], B[1])
print(C[0], C[1])
``` | instruction | 0 | 12,824 | 23 | 25,648 |
No | output | 1 | 12,824 | 23 | 25,649 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
* Icosahedron. Icosahedron has 20 triangular faces.
All five kinds of polyhedrons are shown on the picture below:
<image>
Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of polyhedrons in Anton's collection.
Each of the following n lines of the input contains a string si — the name of the i-th polyhedron in Anton's collection. The string can look like this:
* "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron.
* "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube.
* "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron.
* "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron.
* "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
Output
Output one number — the total number of faces in all the polyhedrons in Anton's collection.
Examples
Input
4
Icosahedron
Cube
Tetrahedron
Dodecahedron
Output
42
Input
3
Dodecahedron
Octahedron
Octahedron
Output
28
Note
In the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20 + 6 + 4 + 12 = 42 faces. | instruction | 0 | 12,982 | 23 | 25,964 |
Tags: implementation, strings
Correct Solution:
```
t=0
for i in range(int(input())):
x=input()
if x=='Tetrahedron':
t+=4
if x=='Cube':
t+=6
if x=='Octahedron':
t+=8
if x=='Dodecahedron':
t+=12
if x=='Icosahedron':
t+=20
print(t)
``` | output | 1 | 12,982 | 23 | 25,965 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
* Icosahedron. Icosahedron has 20 triangular faces.
All five kinds of polyhedrons are shown on the picture below:
<image>
Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of polyhedrons in Anton's collection.
Each of the following n lines of the input contains a string si — the name of the i-th polyhedron in Anton's collection. The string can look like this:
* "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron.
* "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube.
* "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron.
* "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron.
* "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
Output
Output one number — the total number of faces in all the polyhedrons in Anton's collection.
Examples
Input
4
Icosahedron
Cube
Tetrahedron
Dodecahedron
Output
42
Input
3
Dodecahedron
Octahedron
Octahedron
Output
28
Note
In the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20 + 6 + 4 + 12 = 42 faces. | instruction | 0 | 12,983 | 23 | 25,966 |
Tags: implementation, strings
Correct Solution:
```
Anzahl = int(input())
Sammlung = []
for i in range(Anzahl):
Sammlung.append(input())
Seitenzahl = {"Tetrahedron":4,"Cube":6,"Octahedron":8,"Dodecahedron":12,"Icosahedron":20}
Sammlung = [Seitenzahl[i] for i in Sammlung]
print(sum(Sammlung))
``` | output | 1 | 12,983 | 23 | 25,967 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
* Icosahedron. Icosahedron has 20 triangular faces.
All five kinds of polyhedrons are shown on the picture below:
<image>
Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of polyhedrons in Anton's collection.
Each of the following n lines of the input contains a string si — the name of the i-th polyhedron in Anton's collection. The string can look like this:
* "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron.
* "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube.
* "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron.
* "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron.
* "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
Output
Output one number — the total number of faces in all the polyhedrons in Anton's collection.
Examples
Input
4
Icosahedron
Cube
Tetrahedron
Dodecahedron
Output
42
Input
3
Dodecahedron
Octahedron
Octahedron
Output
28
Note
In the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20 + 6 + 4 + 12 = 42 faces. | instruction | 0 | 12,984 | 23 | 25,968 |
Tags: implementation, strings
Correct Solution:
```
import math as mt
import sys,string,bisect
input=sys.stdin.readline
import random
from collections import deque,defaultdict
L=lambda : list(map(int,input().split()))
Ls=lambda : list(input().split())
M=lambda : map(int,input().split())
I=lambda :int(input())
d={}
d["Tetrahedron"]=4
d["Cube"]=6
d["Octahedron"]=8
d["Dodecahedron"]=12
d["Icosahedron"]=20
n=I()
ans=0
for i in range(n):
s=input().strip()
ans+=d[s]
print(ans)
``` | output | 1 | 12,984 | 23 | 25,969 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
* Icosahedron. Icosahedron has 20 triangular faces.
All five kinds of polyhedrons are shown on the picture below:
<image>
Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of polyhedrons in Anton's collection.
Each of the following n lines of the input contains a string si — the name of the i-th polyhedron in Anton's collection. The string can look like this:
* "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron.
* "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube.
* "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron.
* "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron.
* "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
Output
Output one number — the total number of faces in all the polyhedrons in Anton's collection.
Examples
Input
4
Icosahedron
Cube
Tetrahedron
Dodecahedron
Output
42
Input
3
Dodecahedron
Octahedron
Octahedron
Output
28
Note
In the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20 + 6 + 4 + 12 = 42 faces. | instruction | 0 | 12,985 | 23 | 25,970 |
Tags: implementation, strings
Correct Solution:
```
n = int(input())
x = 0
for i in range(n):
a = input()
if a == "Tetrahedron":
x+=4
elif a == "Cube":
x+=6
elif a == "Octahedron":
x+=8
elif a == "Dodecahedron":
x+=12
elif a == "Icosahedron":
x+=20
print(x)
``` | output | 1 | 12,985 | 23 | 25,971 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
* Icosahedron. Icosahedron has 20 triangular faces.
All five kinds of polyhedrons are shown on the picture below:
<image>
Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of polyhedrons in Anton's collection.
Each of the following n lines of the input contains a string si — the name of the i-th polyhedron in Anton's collection. The string can look like this:
* "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron.
* "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube.
* "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron.
* "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron.
* "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
Output
Output one number — the total number of faces in all the polyhedrons in Anton's collection.
Examples
Input
4
Icosahedron
Cube
Tetrahedron
Dodecahedron
Output
42
Input
3
Dodecahedron
Octahedron
Octahedron
Output
28
Note
In the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20 + 6 + 4 + 12 = 42 faces. | instruction | 0 | 12,986 | 23 | 25,972 |
Tags: implementation, strings
Correct Solution:
```
shapes = {
"Tetrahedron": 4,
"Cube": 6,
"Octahedron": 8,
"Dodecahedron": 12,
"Icosahedron": 20,
}
num = int(input())
result = sum(shapes[input()] for _ in range(num))
print(result)
``` | output | 1 | 12,986 | 23 | 25,973 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
* Icosahedron. Icosahedron has 20 triangular faces.
All five kinds of polyhedrons are shown on the picture below:
<image>
Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of polyhedrons in Anton's collection.
Each of the following n lines of the input contains a string si — the name of the i-th polyhedron in Anton's collection. The string can look like this:
* "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron.
* "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube.
* "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron.
* "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron.
* "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
Output
Output one number — the total number of faces in all the polyhedrons in Anton's collection.
Examples
Input
4
Icosahedron
Cube
Tetrahedron
Dodecahedron
Output
42
Input
3
Dodecahedron
Octahedron
Octahedron
Output
28
Note
In the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20 + 6 + 4 + 12 = 42 faces. | instruction | 0 | 12,987 | 23 | 25,974 |
Tags: implementation, strings
Correct Solution:
```
n=int(input())
dic={'Cube':6,'Tetrahedron':4,'Octahedron':8,'Dodecahedron':12,'Icosahedron':20}
t=0
for i in range(n):
t+=dic[input()]
print(t)
``` | output | 1 | 12,987 | 23 | 25,975 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
* Icosahedron. Icosahedron has 20 triangular faces.
All five kinds of polyhedrons are shown on the picture below:
<image>
Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of polyhedrons in Anton's collection.
Each of the following n lines of the input contains a string si — the name of the i-th polyhedron in Anton's collection. The string can look like this:
* "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron.
* "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube.
* "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron.
* "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron.
* "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
Output
Output one number — the total number of faces in all the polyhedrons in Anton's collection.
Examples
Input
4
Icosahedron
Cube
Tetrahedron
Dodecahedron
Output
42
Input
3
Dodecahedron
Octahedron
Octahedron
Output
28
Note
In the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20 + 6 + 4 + 12 = 42 faces. | instruction | 0 | 12,988 | 23 | 25,976 |
Tags: implementation, strings
Correct Solution:
```
n = int(input())
p=[]
for i in range(0, n):
m= list(input())
k=""
l=k.join(m)
p.append(l)
j=[]
for i in range(0, n):
if p[i]=='Tetrahedron':
r=4
j.append(r)
elif p[i]=='Cube':
r=6
j.append(r)
elif p[i]=='Octahedron':
r=8
j.append(r)
elif p[i]=='Dodecahedron':
r=12
j.append(r)
elif p[i]=='Icosahedron':
r=20
j.append(r)
print(sum(j))
``` | output | 1 | 12,988 | 23 | 25,977 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
* Icosahedron. Icosahedron has 20 triangular faces.
All five kinds of polyhedrons are shown on the picture below:
<image>
Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of polyhedrons in Anton's collection.
Each of the following n lines of the input contains a string si — the name of the i-th polyhedron in Anton's collection. The string can look like this:
* "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron.
* "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube.
* "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron.
* "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron.
* "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
Output
Output one number — the total number of faces in all the polyhedrons in Anton's collection.
Examples
Input
4
Icosahedron
Cube
Tetrahedron
Dodecahedron
Output
42
Input
3
Dodecahedron
Octahedron
Octahedron
Output
28
Note
In the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20 + 6 + 4 + 12 = 42 faces. | instruction | 0 | 12,989 | 23 | 25,978 |
Tags: implementation, strings
Correct Solution:
```
n = int(input())
List = []
a = 0
for i in range(0, n):
List = input()
if List[0] == "T":
a += 4
if List[0] == "C":
a += 6
if List[0] == "O":
a += 8
if List[0] == "D":
a += 12
if List[0] == "I":
a += 20
print(a)
``` | output | 1 | 12,989 | 23 | 25,979 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
* Icosahedron. Icosahedron has 20 triangular faces.
All five kinds of polyhedrons are shown on the picture below:
<image>
Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of polyhedrons in Anton's collection.
Each of the following n lines of the input contains a string si — the name of the i-th polyhedron in Anton's collection. The string can look like this:
* "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron.
* "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube.
* "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron.
* "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron.
* "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
Output
Output one number — the total number of faces in all the polyhedrons in Anton's collection.
Examples
Input
4
Icosahedron
Cube
Tetrahedron
Dodecahedron
Output
42
Input
3
Dodecahedron
Octahedron
Octahedron
Output
28
Note
In the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20 + 6 + 4 + 12 = 42 faces.
Submitted Solution:
```
n = int(input())
cnt = 0
for i in range(1, n + 1):
str = input()
if str == "Tetrahedron":
cnt += 4
if str=="Cube":
cnt += 6
if str=="Octahedron":
cnt += 8
if str=="Dodecahedron":
cnt += 12
if str=="Icosahedron":
cnt += 20
print(cnt)
``` | instruction | 0 | 12,990 | 23 | 25,980 |
Yes | output | 1 | 12,990 | 23 | 25,981 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
* Icosahedron. Icosahedron has 20 triangular faces.
All five kinds of polyhedrons are shown on the picture below:
<image>
Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of polyhedrons in Anton's collection.
Each of the following n lines of the input contains a string si — the name of the i-th polyhedron in Anton's collection. The string can look like this:
* "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron.
* "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube.
* "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron.
* "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron.
* "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
Output
Output one number — the total number of faces in all the polyhedrons in Anton's collection.
Examples
Input
4
Icosahedron
Cube
Tetrahedron
Dodecahedron
Output
42
Input
3
Dodecahedron
Octahedron
Octahedron
Output
28
Note
In the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20 + 6 + 4 + 12 = 42 faces.
Submitted Solution:
```
polyhedron = {"Icosahedron" : 20,"Cube": 6,
"Tetrahedron": 4,
"Dodecahedron": 12,
"Octahedron": 8
}
n = input()
count = 0
for i in range(int(n)):
a = input()
count += polyhedron[a]
print(count)
``` | instruction | 0 | 12,991 | 23 | 25,982 |
Yes | output | 1 | 12,991 | 23 | 25,983 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
* Icosahedron. Icosahedron has 20 triangular faces.
All five kinds of polyhedrons are shown on the picture below:
<image>
Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of polyhedrons in Anton's collection.
Each of the following n lines of the input contains a string si — the name of the i-th polyhedron in Anton's collection. The string can look like this:
* "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron.
* "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube.
* "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron.
* "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron.
* "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
Output
Output one number — the total number of faces in all the polyhedrons in Anton's collection.
Examples
Input
4
Icosahedron
Cube
Tetrahedron
Dodecahedron
Output
42
Input
3
Dodecahedron
Octahedron
Octahedron
Output
28
Note
In the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20 + 6 + 4 + 12 = 42 faces.
Submitted Solution:
```
n=int(input())
r=0
str=''
for i in range(n):
str=input()
if str=='Tetrahedron':
r+=4
elif str=='Cube':
r+=6
elif str=='Octahedron':
r+=8
elif str=='Dodecahedron':
r+=12
elif str=='Icosahedron':
r+=20
str=''
print(r)
``` | instruction | 0 | 12,992 | 23 | 25,984 |
Yes | output | 1 | 12,992 | 23 | 25,985 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
* Icosahedron. Icosahedron has 20 triangular faces.
All five kinds of polyhedrons are shown on the picture below:
<image>
Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of polyhedrons in Anton's collection.
Each of the following n lines of the input contains a string si — the name of the i-th polyhedron in Anton's collection. The string can look like this:
* "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron.
* "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube.
* "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron.
* "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron.
* "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
Output
Output one number — the total number of faces in all the polyhedrons in Anton's collection.
Examples
Input
4
Icosahedron
Cube
Tetrahedron
Dodecahedron
Output
42
Input
3
Dodecahedron
Octahedron
Octahedron
Output
28
Note
In the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20 + 6 + 4 + 12 = 42 faces.
Submitted Solution:
```
n = eval(input())
faces = {
"Tetrahedron" : 4,
"Cube" : 6,
"Octahedron":8,
"Dodecahedron":12,
"Icosahedron": 20
}
k = 0
while(n>0):
line = input().rstrip()
k = k + faces[line]
n-=1
print(k)
``` | instruction | 0 | 12,993 | 23 | 25,986 |
Yes | output | 1 | 12,993 | 23 | 25,987 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
* Icosahedron. Icosahedron has 20 triangular faces.
All five kinds of polyhedrons are shown on the picture below:
<image>
Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of polyhedrons in Anton's collection.
Each of the following n lines of the input contains a string si — the name of the i-th polyhedron in Anton's collection. The string can look like this:
* "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron.
* "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube.
* "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron.
* "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron.
* "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
Output
Output one number — the total number of faces in all the polyhedrons in Anton's collection.
Examples
Input
4
Icosahedron
Cube
Tetrahedron
Dodecahedron
Output
42
Input
3
Dodecahedron
Octahedron
Octahedron
Output
28
Note
In the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20 + 6 + 4 + 12 = 42 faces.
Submitted Solution:
```
n = int(input())
l = []
for i in range(0, n):
l.append(input())
def calc_faces(item):
if item == "Tetrahedron":
return 4
elif item == "Cube":
return 6
elif item == "Octahedron":
return 8
elif item == "Dodecahedron":
return 12
elif item == "Icosahedron":
return 20
ans = 0
faces_list = list(map(calc_faces, l))
print(faces_list)
for i in faces_list:
# print(i)
ans = ans + int(i)
print(ans)
``` | instruction | 0 | 12,994 | 23 | 25,988 |
No | output | 1 | 12,994 | 23 | 25,989 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
* Icosahedron. Icosahedron has 20 triangular faces.
All five kinds of polyhedrons are shown on the picture below:
<image>
Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of polyhedrons in Anton's collection.
Each of the following n lines of the input contains a string si — the name of the i-th polyhedron in Anton's collection. The string can look like this:
* "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron.
* "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube.
* "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron.
* "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron.
* "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
Output
Output one number — the total number of faces in all the polyhedrons in Anton's collection.
Examples
Input
4
Icosahedron
Cube
Tetrahedron
Dodecahedron
Output
42
Input
3
Dodecahedron
Octahedron
Octahedron
Output
28
Note
In the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20 + 6 + 4 + 12 = 42 faces.
Submitted Solution:
```
faces = 0
for i in range(int(input())):
poly = input()
if(poly == "Tetrahedron"):
faces += 4
elif(poly == "Icosahedron"):
faces += 20
elif(poly == "Cube"):
faces += 6
elif(poly == "Dodecahedron"):
faces += 12
elif(poly == "Octahedron"):
faces == 8
print(faces)
``` | instruction | 0 | 12,995 | 23 | 25,990 |
No | output | 1 | 12,995 | 23 | 25,991 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
* Icosahedron. Icosahedron has 20 triangular faces.
All five kinds of polyhedrons are shown on the picture below:
<image>
Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of polyhedrons in Anton's collection.
Each of the following n lines of the input contains a string si — the name of the i-th polyhedron in Anton's collection. The string can look like this:
* "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron.
* "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube.
* "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron.
* "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron.
* "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
Output
Output one number — the total number of faces in all the polyhedrons in Anton's collection.
Examples
Input
4
Icosahedron
Cube
Tetrahedron
Dodecahedron
Output
42
Input
3
Dodecahedron
Octahedron
Octahedron
Output
28
Note
In the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20 + 6 + 4 + 12 = 42 faces.
Submitted Solution:
```
import sys
t = int(sys.stdin.readline())
shapes = ["Tetrahedron", "Cube","Octahedron","Dodecahedron", "Icosahedron"]
face = [4,6,8,12,20]
res = 0
for i in range(0,t):
s = sys.stdin.readline()
print(s)
for j in range(0,5):
print(j)
if s == shapes[j]:
res += face[j]
print(res)
``` | instruction | 0 | 12,996 | 23 | 25,992 |
No | output | 1 | 12,996 | 23 | 25,993 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
* Icosahedron. Icosahedron has 20 triangular faces.
All five kinds of polyhedrons are shown on the picture below:
<image>
Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of polyhedrons in Anton's collection.
Each of the following n lines of the input contains a string si — the name of the i-th polyhedron in Anton's collection. The string can look like this:
* "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron.
* "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube.
* "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron.
* "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron.
* "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
Output
Output one number — the total number of faces in all the polyhedrons in Anton's collection.
Examples
Input
4
Icosahedron
Cube
Tetrahedron
Dodecahedron
Output
42
Input
3
Dodecahedron
Octahedron
Octahedron
Output
28
Note
In the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20 + 6 + 4 + 12 = 42 faces.
Submitted Solution:
```
polyhedrons = {
"tetrahedron" : 4,
"cube" : 6,
"octahedron" : 10,
"dodecahedron" : 12,
"icosahedron" : 20
}
n = int(input())
res = 0
for line in range(0, n):
x = input().lower()
res += polyhedrons[x]
print(res)
``` | instruction | 0 | 12,997 | 23 | 25,994 |
No | output | 1 | 12,997 | 23 | 25,995 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bill is a famous mathematician in BubbleLand. Thanks to his revolutionary math discoveries he was able to make enough money to build a beautiful house. Unfortunately, for not paying property tax on time, court decided to punish Bill by making him lose a part of his property.
Bill’s property can be observed as a convex regular 2n-sided polygon A0 A1... A2n - 1 A2n, A2n = A0, with sides of the exactly 1 meter in length.
Court rules for removing part of his property are as follows:
* Split every edge Ak Ak + 1, k = 0... 2n - 1 in n equal parts of size 1 / n with points P0, P1, ..., Pn - 1
* On every edge A2k A2k + 1, k = 0... n - 1 court will choose one point B2k = Pi for some i = 0, ..., n - 1 such that <image>
* On every edge A2k + 1A2k + 2, k = 0...n - 1 Bill will choose one point B2k + 1 = Pi for some i = 0, ..., n - 1 such that <image>
* Bill gets to keep property inside of 2n-sided polygon B0 B1... B2n - 1
Luckily, Bill found out which B2k points the court chose. Even though he is a great mathematician, his house is very big and he has a hard time calculating. Therefore, he is asking you to help him choose points so he maximizes area of property he can keep.
Input
The first line contains one integer number n (2 ≤ n ≤ 50000), representing number of edges of 2n-sided polygon.
The second line contains n distinct integer numbers B2k (0 ≤ B2k ≤ n - 1, k = 0... n - 1) separated by a single space, representing points the court chose. If B2k = i, the court chose point Pi on side A2k A2k + 1.
Output
Output contains n distinct integers separated by a single space representing points B1, B3, ..., B2n - 1 Bill should choose in order to maximize the property area. If there are multiple solutions that maximize the area, return any of them.
Example
Input
3
0 1 2
Output
0 2 1
Note
To maximize area Bill should choose points: B1 = P0, B3 = P2, B5 = P1
<image>
Submitted Solution:
```
n = int(input())
a = input().split()
for i in range(n):
a[i] = int(a[i])
b = []
for i in range(1, n):
b.append((a[i-1]-(n-a[i]), i-1))
b.append((a[n-1]-(n-a[0]), n-1))
b = sorted(b)
ans = n*[0]
for i in range(n):
# the line segment at index b[i][1]
ans[b[i][1]] = a[i]
for i in range(1, n):
print(ans[i], end = ' ')
print(ans[0], end = ' ')
``` | instruction | 0 | 13,031 | 23 | 26,062 |
No | output | 1 | 13,031 | 23 | 26,063 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bill is a famous mathematician in BubbleLand. Thanks to his revolutionary math discoveries he was able to make enough money to build a beautiful house. Unfortunately, for not paying property tax on time, court decided to punish Bill by making him lose a part of his property.
Bill’s property can be observed as a convex regular 2n-sided polygon A0 A1... A2n - 1 A2n, A2n = A0, with sides of the exactly 1 meter in length.
Court rules for removing part of his property are as follows:
* Split every edge Ak Ak + 1, k = 0... 2n - 1 in n equal parts of size 1 / n with points P0, P1, ..., Pn - 1
* On every edge A2k A2k + 1, k = 0... n - 1 court will choose one point B2k = Pi for some i = 0, ..., n - 1 such that <image>
* On every edge A2k + 1A2k + 2, k = 0...n - 1 Bill will choose one point B2k + 1 = Pi for some i = 0, ..., n - 1 such that <image>
* Bill gets to keep property inside of 2n-sided polygon B0 B1... B2n - 1
Luckily, Bill found out which B2k points the court chose. Even though he is a great mathematician, his house is very big and he has a hard time calculating. Therefore, he is asking you to help him choose points so he maximizes area of property he can keep.
Input
The first line contains one integer number n (2 ≤ n ≤ 50000), representing number of edges of 2n-sided polygon.
The second line contains n distinct integer numbers B2k (0 ≤ B2k ≤ n - 1, k = 0... n - 1) separated by a single space, representing points the court chose. If B2k = i, the court chose point Pi on side A2k A2k + 1.
Output
Output contains n distinct integers separated by a single space representing points B1, B3, ..., B2n - 1 Bill should choose in order to maximize the property area. If there are multiple solutions that maximize the area, return any of them.
Example
Input
3
0 1 2
Output
0 2 1
Note
To maximize area Bill should choose points: B1 = P0, B3 = P2, B5 = P1
<image>
Submitted Solution:
```
#HAHAHAHAHA
print(0+0+0)
print(2+0)
print(1)
``` | instruction | 0 | 13,032 | 23 | 26,064 |
No | output | 1 | 13,032 | 23 | 26,065 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bill is a famous mathematician in BubbleLand. Thanks to his revolutionary math discoveries he was able to make enough money to build a beautiful house. Unfortunately, for not paying property tax on time, court decided to punish Bill by making him lose a part of his property.
Bill’s property can be observed as a convex regular 2n-sided polygon A0 A1... A2n - 1 A2n, A2n = A0, with sides of the exactly 1 meter in length.
Court rules for removing part of his property are as follows:
* Split every edge Ak Ak + 1, k = 0... 2n - 1 in n equal parts of size 1 / n with points P0, P1, ..., Pn - 1
* On every edge A2k A2k + 1, k = 0... n - 1 court will choose one point B2k = Pi for some i = 0, ..., n - 1 such that <image>
* On every edge A2k + 1A2k + 2, k = 0...n - 1 Bill will choose one point B2k + 1 = Pi for some i = 0, ..., n - 1 such that <image>
* Bill gets to keep property inside of 2n-sided polygon B0 B1... B2n - 1
Luckily, Bill found out which B2k points the court chose. Even though he is a great mathematician, his house is very big and he has a hard time calculating. Therefore, he is asking you to help him choose points so he maximizes area of property he can keep.
Input
The first line contains one integer number n (2 ≤ n ≤ 50000), representing number of edges of 2n-sided polygon.
The second line contains n distinct integer numbers B2k (0 ≤ B2k ≤ n - 1, k = 0... n - 1) separated by a single space, representing points the court chose. If B2k = i, the court chose point Pi on side A2k A2k + 1.
Output
Output contains n distinct integers separated by a single space representing points B1, B3, ..., B2n - 1 Bill should choose in order to maximize the property area. If there are multiple solutions that maximize the area, return any of them.
Example
Input
3
0 1 2
Output
0 2 1
Note
To maximize area Bill should choose points: B1 = P0, B3 = P2, B5 = P1
<image>
Submitted Solution:
```
#HAHAHAHAHA
print(0+0+0)
print(2)
print(1)
``` | instruction | 0 | 13,033 | 23 | 26,066 |
No | output | 1 | 13,033 | 23 | 26,067 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bill is a famous mathematician in BubbleLand. Thanks to his revolutionary math discoveries he was able to make enough money to build a beautiful house. Unfortunately, for not paying property tax on time, court decided to punish Bill by making him lose a part of his property.
Bill’s property can be observed as a convex regular 2n-sided polygon A0 A1... A2n - 1 A2n, A2n = A0, with sides of the exactly 1 meter in length.
Court rules for removing part of his property are as follows:
* Split every edge Ak Ak + 1, k = 0... 2n - 1 in n equal parts of size 1 / n with points P0, P1, ..., Pn - 1
* On every edge A2k A2k + 1, k = 0... n - 1 court will choose one point B2k = Pi for some i = 0, ..., n - 1 such that <image>
* On every edge A2k + 1A2k + 2, k = 0...n - 1 Bill will choose one point B2k + 1 = Pi for some i = 0, ..., n - 1 such that <image>
* Bill gets to keep property inside of 2n-sided polygon B0 B1... B2n - 1
Luckily, Bill found out which B2k points the court chose. Even though he is a great mathematician, his house is very big and he has a hard time calculating. Therefore, he is asking you to help him choose points so he maximizes area of property he can keep.
Input
The first line contains one integer number n (2 ≤ n ≤ 50000), representing number of edges of 2n-sided polygon.
The second line contains n distinct integer numbers B2k (0 ≤ B2k ≤ n - 1, k = 0... n - 1) separated by a single space, representing points the court chose. If B2k = i, the court chose point Pi on side A2k A2k + 1.
Output
Output contains n distinct integers separated by a single space representing points B1, B3, ..., B2n - 1 Bill should choose in order to maximize the property area. If there are multiple solutions that maximize the area, return any of them.
Example
Input
3
0 1 2
Output
0 2 1
Note
To maximize area Bill should choose points: B1 = P0, B3 = P2, B5 = P1
<image>
Submitted Solution:
```
print(0)
print(2)
print(1)
``` | instruction | 0 | 13,034 | 23 | 26,068 |
No | output | 1 | 13,034 | 23 | 26,069 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N(N+1)/2 dots arranged to form an equilateral triangle whose sides consist of N dots, as shown below. The j-th dot from the left in the i-th row from the top is denoted by (i, j) (1 \leq i \leq N, 1 \leq j \leq i). Also, we will call (i+1, j) immediately lower-left to (i, j), and (i+1, j+1) immediately lower-right to (i, j).
<image>
Takahashi is drawing M polygonal lines L_1, L_2, ..., L_M by connecting these dots. Each L_i starts at (1, 1), and visits the dot that is immediately lower-left or lower-right to the current dots N-1 times. More formally, there exist X_{i,1}, ..., X_{i,N} such that:
* L_i connects the N points (1, X_{i,1}), (2, X_{i,2}), ..., (N, X_{i,N}), in this order.
* For each j=1, 2, ..., N-1, either X_{i,j+1} = X_{i,j} or X_{i,j+1} = X_{i,j}+1 holds.
Takahashi would like to draw these lines so that no part of L_{i+1} is to the left of L_{i}. That is, for each j=1, 2, ..., N, X_{1,j} \leq X_{2,j} \leq ... \leq X_{M,j} must hold.
Additionally, there are K conditions on the shape of the lines that must be followed. The i-th condition is denoted by (A_i, B_i, C_i), which means:
* If C_i=0, L_{A_i} must visit the immediately lower-left dot for the B_i-th move.
* If C_i=1, L_{A_i} must visit the immediately lower-right dot for the B_i-th move.
That is, X_{A_i, {B_i}+1} = X_{A_i, B_i} + C_i must hold.
In how many ways can Takahashi draw M polygonal lines? Find the count modulo 1000000007.
Constraints
* 1 \leq N \leq 20
* 1 \leq M \leq 20
* 0 \leq K \leq (N-1)M
* 1 \leq A_i \leq M
* 1 \leq B_i \leq N-1
* C_i = 0 or 1
* No pair appears more than once as (A_i, B_i).
Input
Input is given from Standard Input in the following format:
N M K
A_1 B_1 C_1
A_2 B_2 C_2
:
A_K B_K C_K
Output
Print the number of ways for Takahashi to draw M polygonal lines, modulo 1000000007.
Examples
Input
3 2 1
1 2 0
Output
6
Input
3 2 2
1 1 1
2 1 0
Output
0
Input
5 4 2
1 3 1
4 2 0
Output
172
Input
20 20 0
Output
881396682
Submitted Solution:
```
print(881396682)
``` | instruction | 0 | 13,186 | 23 | 26,372 |
No | output | 1 | 13,186 | 23 | 26,373 |
Provide a correct Python 3 solution for this coding contest problem.
For given $n$ segments which are parallel to X-axis or Y-axis, find the number of intersections of them.
Constraints
* $1 \leq n \leq 100,000$
* $ -1,000,000,000 \leq x_1, y_1, x_2, y_2 \leq 1,000,000,000$
* Two parallel segments never overlap or touch.
* The number of intersections $\leq 1,000,000$
Input
In the first line, the number of segments $n$ is given. In the following $n$ lines, the $i$-th segment is given by coordinates of its end points in the following format:
$x_1 \; y_1 \; x_2 \; y_2$
The coordinates are given in integers.
Output
Print the number of intersections in a line.
Example
Input
6
2 2 2 5
1 3 5 3
4 1 4 4
5 2 7 2
6 1 6 3
6 5 6 7
Output
3 | instruction | 0 | 13,275 | 23 | 26,550 |
"Correct Solution:
```
# Acceptance of input
import sys
file_input = sys.stdin
n = file_input.readline()
EP = []
for line in file_input:
x1, y1, x2, y2 = (map(int, line.split()))
# point[2] corresponds to the position of the end point.
# 1 is left, 2 is lower, 3 is upper and 4 is right.
if y1 < y2:
p1 = (x1, y1, 2)
p2 = (x2, y2, 3)
elif y1 > y2:
p1 = (x1, y1, 3)
p2 = (x2, y2, 2)
elif x1 < x2:
p1 = (x1, y1, 1)
p2 = (x2, y2, 4)
else:
p1 = (x1, y1, 4)
p2 = (x2, y2, 1)
EP += [p1, p2]
# Sweep function
import bisect
def manhattan_intersection(point_list):
point_list.sort(key = lambda p: (p[1], p[0], p[2]))
T = []
cnt = 0
flag = False
for p in point_list:
position = p[2]
if position == 3:
i = bisect.bisect_left(T, p[0])
T.pop(i)
if flag:
cnt += 1
elif position == 2:
bisect.insort(T, p[0])
elif position == 4:
cnt += bisect.bisect(T, p[0]) - left_end
flag = False
else:
left_end = bisect.bisect_left(T, p[0])
flag = True
print(cnt)
# Output
manhattan_intersection(EP)
``` | output | 1 | 13,275 | 23 | 26,551 |
Provide a correct Python 3 solution for this coding contest problem.
For given $n$ segments which are parallel to X-axis or Y-axis, find the number of intersections of them.
Constraints
* $1 \leq n \leq 100,000$
* $ -1,000,000,000 \leq x_1, y_1, x_2, y_2 \leq 1,000,000,000$
* Two parallel segments never overlap or touch.
* The number of intersections $\leq 1,000,000$
Input
In the first line, the number of segments $n$ is given. In the following $n$ lines, the $i$-th segment is given by coordinates of its end points in the following format:
$x_1 \; y_1 \; x_2 \; y_2$
The coordinates are given in integers.
Output
Print the number of intersections in a line.
Example
Input
6
2 2 2 5
1 3 5 3
4 1 4 4
5 2 7 2
6 1 6 3
6 5 6 7
Output
3 | instruction | 0 | 13,276 | 23 | 26,552 |
"Correct Solution:
```
# Acceptance of input
import sys
file_input = sys.stdin
n = file_input.readline()
EP = []
l = -1000000001
u = 1000000001
vs_x = set()
for line in file_input:
x1, y1, x2, y2 = (map(int, line.split()))
if x1 == x2:
if y1 < y2:
EP.append((y1, l, x1))
EP.append((y2, u, x1))
else:
EP.append((y1, u, x1))
EP.append((y2, l, x1))
vs_x.add(x1)
else:
if x1 < x2:
EP.append((y1, x1, x2))
else:
EP.append((y1, x2, x1))
vs_x = sorted(vs_x)
# Binary Indexed Tree
class BinaryIndexedTree:
def __init__(self, n):
self.data = [0] * (n + 1)
self.num = n
def switch(self, i, d):
while i <= self.num:
self.data[i] += d
i += i & -i
def _sum(self, i):
s = 0
while i:
s += self.data[i]
i -= i & -i
return s
def seg_sum(self, a, b):
return self._sum(b) - self._sum(a - 1)
# Sweep
import bisect
EP.sort()
BIT = BinaryIndexedTree(len(vs_x))
cnt = 0
for p in EP:
e = p[1]
if e == l:
vx = bisect.bisect(vs_x, p[2])
BIT.switch(vx, 1)
elif e == u:
vx = bisect.bisect(vs_x, p[2])
BIT.switch(vx, -1)
else:
l_x = bisect.bisect_left(vs_x, e) + 1
r_x = bisect.bisect(vs_x, p[2])
cnt += BIT.seg_sum(l_x, r_x)
# Output
print(cnt)
``` | output | 1 | 13,276 | 23 | 26,553 |
Provide a correct Python 3 solution for this coding contest problem.
For given $n$ segments which are parallel to X-axis or Y-axis, find the number of intersections of them.
Constraints
* $1 \leq n \leq 100,000$
* $ -1,000,000,000 \leq x_1, y_1, x_2, y_2 \leq 1,000,000,000$
* Two parallel segments never overlap or touch.
* The number of intersections $\leq 1,000,000$
Input
In the first line, the number of segments $n$ is given. In the following $n$ lines, the $i$-th segment is given by coordinates of its end points in the following format:
$x_1 \; y_1 \; x_2 \; y_2$
The coordinates are given in integers.
Output
Print the number of intersections in a line.
Example
Input
6
2 2 2 5
1 3 5 3
4 1 4 4
5 2 7 2
6 1 6 3
6 5 6 7
Output
3 | instruction | 0 | 13,277 | 23 | 26,554 |
"Correct Solution:
```
import sys
import bisect
readline = sys.stdin.readline
n = int(readline())
EP = []
l = -1000000001
u = 1000000001
vs_x = set()
h_num = 0
for _ in [0] * n:
x1, y1, x2, y2 = (map(int, readline().split()))
if x1 == x2:
if y1 < y2:
EP.append((y1, l, x1))
EP.append((y2, u, x1))
else:
EP.append((y1, u, x1))
EP.append((y2, l, x1))
vs_x.add(x1)
else:
if x1 < x2:
EP.append((y1, x1, x2))
else:
EP.append((y1, x2, x1))
h_num += 1
class BinaryIndexedTree:
__slots__ = ('data', 'num')
def __init__(self, n):
self.data = [0] * (n + 1)
self.num = n
def switch(self, i, d):
while i <= self.num:
self.data[i] += d
i += i & -i
def _sum(self, i):
s = 0
while i:
s += self.data[i]
i -= i & -i
return s
def seg_sum(self, a, b):
return self._sum(b) - self._sum(a - 1)
EP.sort()
BIT = BinaryIndexedTree(len(vs_x))
vs_x = [l] + sorted(vs_x)
d_vs_x = {e: i for i, e in enumerate(vs_x)}
cnt = 0
for p in EP:
e = p[1]
if e == l:
BIT.switch(d_vs_x[p[2]], 1)
elif e == u:
BIT.switch(d_vs_x[p[2]], -1)
else:
l_x = bisect.bisect_left(vs_x, e)
r_x = bisect.bisect(vs_x, p[2]) - 1
cnt += BIT.seg_sum(l_x, r_x)
h_num -= 1
if h_num == 0: break
print(cnt)
``` | output | 1 | 13,277 | 23 | 26,555 |
Provide a correct Python 3 solution for this coding contest problem.
For given $n$ segments which are parallel to X-axis or Y-axis, find the number of intersections of them.
Constraints
* $1 \leq n \leq 100,000$
* $ -1,000,000,000 \leq x_1, y_1, x_2, y_2 \leq 1,000,000,000$
* Two parallel segments never overlap or touch.
* The number of intersections $\leq 1,000,000$
Input
In the first line, the number of segments $n$ is given. In the following $n$ lines, the $i$-th segment is given by coordinates of its end points in the following format:
$x_1 \; y_1 \; x_2 \; y_2$
The coordinates are given in integers.
Output
Print the number of intersections in a line.
Example
Input
6
2 2 2 5
1 3 5 3
4 1 4 4
5 2 7 2
6 1 6 3
6 5 6 7
Output
3 | instruction | 0 | 13,278 | 23 | 26,556 |
"Correct Solution:
```
from sys import stdin
from operator import itemgetter
readline = stdin.readline
#readline = open('???.txt').readline
VERTICAL_LOW, HORIZONTAL, VERTICAL_HIGH = 0, 1, 2
import math
class segment_tree:
# self.table is 1-indexed
# math.log2 not implemented 3.2.3
def __init__(self, size):
self.offset = 2 ** math.ceil(math.log(size, 2))
self.table = [0] * self.offset * 2
for i in reversed(range(1, self.offset)):
self.table[i] = self.table[2 * i] + self.table[2 * i + 1]
# [l, r] closed-interval
def sum(self, l, r):
return sum(self.__range(l,r))
def __range(self, l, r):
l += self.offset
r += self.offset
while l <= r:
if l & 1:
yield self.table[l]
l += 1
l >>= 1
if r & 1 == 0:
yield self.table[r]
r -= 1
r >>= 1
def add(self, i, x):
i += self.offset
self.table[i] += x
while 1 < i:
i >>= 1
self.table[i] = self.table[2 * i] + self.table[2 * i + 1]
def main():
n = int(readline())
p = [list(map(int, readline().split())) for _ in range(n)]
x = set(x1 for x1, y1, x2, y2 in p) | set(x2 for x1, y1, x2, y2 in p)
c = {xi:i for i, xi in enumerate(sorted(x))}
que = []
for x1, y1, x2, y2 in p:
if y1 == y2:
if x1 > x2:
x1, x2 = x2, x1
que.append((y1, HORIZONTAL, c[x1], c[x2]))
else:
if y1 > y2:
y1, y2 = y2, y1
x1 = c[x1]
que.append((y1, VERTICAL_LOW, x1, None))
que.append((y2, VERTICAL_HIGH, x1, None))
que.sort(key=itemgetter(0, 1))
vertical_info = segment_tree(len(x))
intersection = 0
for y1, action, x1, x2 in que:
if action == VERTICAL_LOW:
vertical_info.add(x1, 1)
elif action == HORIZONTAL:
intersection += vertical_info.sum(x1, x2)
else:
vertical_info.add(x1, -1)
print(intersection)
main()
``` | output | 1 | 13,278 | 23 | 26,557 |
Provide a correct Python 3 solution for this coding contest problem.
For given $n$ segments which are parallel to X-axis or Y-axis, find the number of intersections of them.
Constraints
* $1 \leq n \leq 100,000$
* $ -1,000,000,000 \leq x_1, y_1, x_2, y_2 \leq 1,000,000,000$
* Two parallel segments never overlap or touch.
* The number of intersections $\leq 1,000,000$
Input
In the first line, the number of segments $n$ is given. In the following $n$ lines, the $i$-th segment is given by coordinates of its end points in the following format:
$x_1 \; y_1 \; x_2 \; y_2$
The coordinates are given in integers.
Output
Print the number of intersections in a line.
Example
Input
6
2 2 2 5
1 3 5 3
4 1 4 4
5 2 7 2
6 1 6 3
6 5 6 7
Output
3 | instruction | 0 | 13,279 | 23 | 26,558 |
"Correct Solution:
```
import cmath
import itertools
import math
import operator
import os
import sys
from collections import defaultdict
if os.getenv("LOCAL"):
sys.stdin = open("_in.txt", "r")
sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353
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, c: complex):
self.c = c
@property
def x(self):
return self.c.real
@property
def y(self):
return self.c.imag
@staticmethod
def from_rect(x: float, y: float):
return Point(complex(x, y))
@staticmethod
def from_polar(r: float, phi: float):
return Point(cmath.rect(r, phi))
def __add__(self, p):
"""
:param Point p:
"""
return Point(self.c + p.c)
def __iadd__(self, p):
"""
:param Point p:
"""
self.c += p.c
return self
def __sub__(self, p):
"""
:param Point p:
"""
return Point(self.c - p.c)
def __isub__(self, p):
"""
:param Point p:
"""
self.c -= p.c
return self
def __mul__(self, f: float):
return Point(self.c * f)
def __imul__(self, f: float):
self.c *= f
return self
def __truediv__(self, f: float):
return Point(self.c / f)
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):
return Point(-self.c)
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 cmath.phase(self.p2 - self.p1)
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 SegmentTree:
# http://tsutaj.hatenablog.com/entry/2017/03/29/204841
def __init__(self, size, fn=operator.add, default=None, initial_values=None):
"""
:param int size:
:param callable fn: 区間に適用する関数。引数を 2 つ取る。min, max, operator.xor など
:param default:
:param list initial_values:
"""
default = default or 0
# size 以上である最小の 2 冪を size とする
n = 1
while n < size:
n *= 2
self._size = n
self._fn = fn
self._tree = [default] * (self._size * 2 - 1)
if initial_values:
i = self._size - 1
for v in initial_values:
self._tree[i] = v
i += 1
i = self._size - 2
while i >= 0:
self._tree[i] = self._fn(self._tree[i * 2 + 1], self._tree[i * 2 + 2])
i -= 1
def set(self, i, value):
"""
i 番目に value を設定
:param int i:
:param value:
:return:
"""
x = self._size - 1 + i
self._tree[x] = value
while x > 0:
x = (x - 1) // 2
self._tree[x] = self._fn(self._tree[x * 2 + 1], self._tree[x * 2 + 2])
def add(self, i, value):
"""
もとの i 番目と value に fn を適用したものを i 番目に設定
:param int i:
:param value:
:return:
"""
x = self._size - 1 + i
self.set(i, self._fn(self._tree[x], value))
def get(self, from_i, to_i=None, k=0, L=None, r=None):
"""
[from_i, to_i) に fn を適用した結果を返す
:param int from_i:
:param int to_i:
:param int k: self._tree[k] が、[L, r) に fn を適用した結果を持つ
:param int L:
:param int r:
:return:
"""
if to_i is None:
return self._tree[self._size - 1 + from_i]
L = 0 if L is None else L
r = self._size if r is None else r
if from_i <= L and r <= to_i:
return self._tree[k]
if to_i <= L or r <= from_i:
return None
ret_L = self.get(from_i, to_i, k * 2 + 1, L, (L + r) // 2)
ret_r = self.get(from_i, to_i, k * 2 + 2, (L + r) // 2, r)
if ret_L is None:
return ret_r
if ret_r is None:
return ret_L
return self._fn(ret_L, ret_r)
def __len__(self):
return self._size
def compress(li, origin=0):
"""
座圧
:param li:
:param int origin:
:rtype: list of int
"""
*ret, = map({v: i + origin for i, v in enumerate(sorted(set(li)))}.__getitem__, li)
return ret
N = int(sys.stdin.buffer.readline())
S = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(N)]
flatten = list(itertools.chain.from_iterable(S))
ranks = compress(flatten, origin=1)
MAX = max(ranks)
V = []
H = []
for x1, y1, x2, y2 in zip(*[iter(ranks)] * 4):
if x1 == x2:
if y1 > y2:
y1, y2 = y2, y1
V.append(Segment(Point(complex(x1, y1)), Point(complex(x2, y2))))
else:
if x1 > x2:
x1, x2 = x2, x1
H.append(Segment(Point(complex(x1, y1)), Point(complex(x2, y2))))
y_events = defaultdict(list)
for s in V:
y_events[s.p1.y].append((s.p1.x, 1))
y_events[s.p2.y + 1].append((s.p2.x, -1))
H.sort(key=lambda s: s.p1.y)
ys = sorted(y_events.keys())
yi = 0
ans = 0
st = SegmentTree(size=MAX + 100)
for s in H:
while yi < len(ys) and ys[yi] <= s.p1.y:
y = ys[yi]
for x, d in y_events[y]:
st.add(int(x), d)
yi += 1
ans += st.get(int(s.p1.x), int(s.p2.x + 1))
print(ans)
``` | output | 1 | 13,279 | 23 | 26,559 |
Provide a correct Python 3 solution for this coding contest problem.
For given $n$ segments which are parallel to X-axis or Y-axis, find the number of intersections of them.
Constraints
* $1 \leq n \leq 100,000$
* $ -1,000,000,000 \leq x_1, y_1, x_2, y_2 \leq 1,000,000,000$
* Two parallel segments never overlap or touch.
* The number of intersections $\leq 1,000,000$
Input
In the first line, the number of segments $n$ is given. In the following $n$ lines, the $i$-th segment is given by coordinates of its end points in the following format:
$x_1 \; y_1 \; x_2 \; y_2$
The coordinates are given in integers.
Output
Print the number of intersections in a line.
Example
Input
6
2 2 2 5
1 3 5 3
4 1 4 4
5 2 7 2
6 1 6 3
6 5 6 7
Output
3 | instruction | 0 | 13,280 | 23 | 26,560 |
"Correct Solution:
```
# Acceptance of input
import sys
file_input = sys.stdin
n = file_input.readline()
EP = []
l = -1000000001
r = 1000000001
for line in file_input:
x1, y1, x2, y2 = (map(int, line.split()))
if y1 == y2:
EP.append((min(x1, x2), l, y1))
EP.append((max(x1, x2), r, y1))
else:
EP.append((x1, min(y1, y2), max(y1, y2)))
# Sweep
import bisect
EP.sort()
BT = []
cnt = 0
for p in EP:
y1 = p[1]
if y1 == l:
bisect.insort(BT, p[2])
elif y1 == r:
i = bisect.bisect_left(BT, p[2])
BT.pop(i)
else:
cnt += bisect.bisect(BT, p[2]) - bisect.bisect_left(BT, y1)
# Output
print(cnt)
``` | output | 1 | 13,280 | 23 | 26,561 |
Provide a correct Python 3 solution for this coding contest problem.
For given $n$ segments which are parallel to X-axis or Y-axis, find the number of intersections of them.
Constraints
* $1 \leq n \leq 100,000$
* $ -1,000,000,000 \leq x_1, y_1, x_2, y_2 \leq 1,000,000,000$
* Two parallel segments never overlap or touch.
* The number of intersections $\leq 1,000,000$
Input
In the first line, the number of segments $n$ is given. In the following $n$ lines, the $i$-th segment is given by coordinates of its end points in the following format:
$x_1 \; y_1 \; x_2 \; y_2$
The coordinates are given in integers.
Output
Print the number of intersections in a line.
Example
Input
6
2 2 2 5
1 3 5 3
4 1 4 4
5 2 7 2
6 1 6 3
6 5 6 7
Output
3 | instruction | 0 | 13,281 | 23 | 26,562 |
"Correct Solution:
```
#!/usr/bin/env python3
# CGL_6_A: Segment Set - Segment Intersections: Manhattan Geometry
from enum import IntEnum
class Action(IntEnum):
ADD = 1
SEARCH = 2
REMOVE = 3
class Color(IntEnum):
BLACK = 0
RED = 1
@staticmethod
def flip(c):
return [Color.RED, Color.BLACK][c.value]
class Node:
__slots__ = ('value', 'left', 'right', 'color', 'valid')
def __init__(self, value):
self.value = value
self.left = Leaf
self.right = Leaf
self.color = Color.RED
self.valid = True
def flip_color(self):
self.color = Color.flip(self.color)
def is_red(self):
return self.color == Color.RED
def __str__(self):
return ('(' + str(self.left) + ', '
+ str(self.value) + ', ' + str(self.right) + ')')
class LeafNode(Node):
def __init__(self):
self.value = None
self.left = None
self.right = None
self.color = None
self.valid = False
def flip_color(self):
pass
def is_red(self):
return False
def __str__(self):
return 'Leaf'
Leaf = LeafNode()
class RedBlackBST:
def __init__(self):
self.root = Leaf
def add(self, value):
def _add(node):
if node is Leaf:
node = Node(value)
if node.value > value:
node.left = _add(node.left)
elif node.value < value:
node.right = _add(node.right)
else:
if not node.valid:
node.valid = True
node = self._balance(node)
return node
self.root = _add(self.root)
self.root.color = Color.BLACK
def _balance(self, node):
if node.right.is_red() and not node.left.is_red():
node = self._rotate_left(node)
if node.left.is_red() and node.left.left.is_red():
node = self._rotate_right(node)
if node.left.is_red() and node.right.is_red():
node = self._flip_colors(node)
return node
def _rotate_left(self, node):
x = node.right
node.right = x.left
x.left = node
x.color = node.color
node.color = Color.RED
return x
def _rotate_right(self, node):
x = node.left
node.left = x.right
x.right = node
x.color = node.color
node.color = Color.RED
return x
def _flip_colors(self, node):
node.flip_color()
node.left.flip_color()
node.right.flip_color()
return node
def remove(self, value):
def _remove(node):
if node is Leaf:
return
if node.value > value:
_remove(node.left)
elif node.value < value:
_remove(node.right)
else:
node.valid = False
_remove(self.root)
def count(self, min_, max_):
def _range(node):
if node is Leaf:
return 0
if node.value > max_:
return _range(node.left)
elif node.value < min_:
return _range(node.right)
else:
count = _range(node.left) + _range(node.right)
if node.valid:
count += 1
return count
return _range(self.root)
def __str__(self):
return str(self.root)
def count_intersections(segments):
segments.sort()
tree = RedBlackBST()
count = 0
for seg in segments:
x, action, y = seg
if action == Action.SEARCH:
count += tree.count(*y)
elif action == Action.ADD:
tree.add(y)
elif action == Action.REMOVE:
tree.remove(y)
return count
def run():
n = int(input())
segs = []
for _ in range(n):
x1, y1, x2, y2 = [int(i) for i in input().split()]
if x1 > x2 or y1 > y2:
x1, x2 = x2, x1
y1, y2 = y2, y1
if x1 == x2:
segs.append((x1, Action.SEARCH, (y1, y2)))
else:
segs.append((x1, Action.ADD, y1))
segs.append((x2, Action.REMOVE, y2))
print(count_intersections(segs))
if __name__ == '__main__':
run()
``` | output | 1 | 13,281 | 23 | 26,563 |
Provide a correct Python 3 solution for this coding contest problem.
For given $n$ segments which are parallel to X-axis or Y-axis, find the number of intersections of them.
Constraints
* $1 \leq n \leq 100,000$
* $ -1,000,000,000 \leq x_1, y_1, x_2, y_2 \leq 1,000,000,000$
* Two parallel segments never overlap or touch.
* The number of intersections $\leq 1,000,000$
Input
In the first line, the number of segments $n$ is given. In the following $n$ lines, the $i$-th segment is given by coordinates of its end points in the following format:
$x_1 \; y_1 \; x_2 \; y_2$
The coordinates are given in integers.
Output
Print the number of intersections in a line.
Example
Input
6
2 2 2 5
1 3 5 3
4 1 4 4
5 2 7 2
6 1 6 3
6 5 6 7
Output
3 | instruction | 0 | 13,282 | 23 | 26,564 |
"Correct Solution:
```
from enum import IntEnum
class Action(IntEnum):
ADD = 1
SEARCH = 2
REMOVE = 3
class Color(IntEnum):
BLACK = 0
RED = 1
@staticmethod
def flip(c):
return [Color.RED, Color.BLACK][c.value]
class Node:
__slots__ = ('value', 'left', 'right', 'color', 'valid')
def __init__(self, value):
self.value = value
self.left = Leaf
self.right = Leaf
self.color = Color.RED
self.valid = True
def flip_color(self):
self.color = Color.flip(self.color)
def is_red(self):
return self.color == Color.RED
def __str__(self):
return ('(' + str(self.left) + ', '
+ str(self.value) + ', ' + str(self.right) + ')')
class LeafNode(Node):
def __init__(self):
self.value = None
self.left = None
self.right = None
self.color = None
self.valid = False
def flip_color(self):
pass
def is_red(self):
return False
def __str__(self):
return 'Leaf'
Leaf = LeafNode()
class RedBlackBST:
def __init__(self):
self.root = Leaf
def add(self, value):
def _add(node):
if node is Leaf:
node = Node(value)
if node.value > value:
node.left = _add(node.left)
elif node.value < value:
node.right = _add(node.right)
else:
if not node.valid:
node.valid = True
node = self._balance(node)
return node
self.root = _add(self.root)
self.root.color = Color.BLACK
def _balance(self, node):
if node.right.is_red() and not node.left.is_red():
node = self._rotate_left(node)
if node.left.is_red() and node.left.left.is_red():
node = self._rotate_right(node)
if node.left.is_red() and node.right.is_red():
node = self._flip_colors(node)
return node
def _rotate_left(self, node):
x = node.right
node.right = x.left
x.left = node
x.color = node.color
node.color = Color.RED
return x
def _rotate_right(self, node):
x = node.left
node.left = x.right
x.right = node
x.color = node.color
node.color = Color.RED
return x
def _flip_colors(self, node):
node.flip_color()
node.left.flip_color()
node.right.flip_color()
return node
def remove(self, value):
def _remove(node):
if node is Leaf:
return
if node.value > value:
_remove(node.left)
elif node.value < value:
_remove(node.right)
else:
node.valid = False
_remove(self.root)
def count(self, min_, max_):
def _range(node):
if node is Leaf:
return 0
if node.value > max_:
return _range(node.left)
elif node.value < min_:
return _range(node.right)
else:
count = _range(node.left) + _range(node.right)
if node.valid:
count += 1
return count
return _range(self.root)
def __str__(self):
return str(self.root)
def count_intersections(segments):
segments.sort()
tree = RedBlackBST()
count = 0
for seg in segments:
x, action, y = seg
if action == Action.SEARCH:
count += tree.count(*y)
elif action == Action.ADD:
tree.add(y)
elif action == Action.REMOVE:
tree.remove(y)
return count
n=int(input())
segs=[]
for i in range(n):
x1,y1,x2,y2=map(int,input().split())
if x1>x2 or y1>y2:
x1,x2=x2,x1
y1,y2=y2,y1
if x1==x2:
segs.append((x1,Action.SEARCH,(y1,y2)))
else:
segs.append((x1,Action.ADD,y1))
segs.append((x2,Action.REMOVE,y2))
print(count_intersections(segs))
``` | output | 1 | 13,282 | 23 | 26,565 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For given $n$ segments which are parallel to X-axis or Y-axis, find the number of intersections of them.
Constraints
* $1 \leq n \leq 100,000$
* $ -1,000,000,000 \leq x_1, y_1, x_2, y_2 \leq 1,000,000,000$
* Two parallel segments never overlap or touch.
* The number of intersections $\leq 1,000,000$
Input
In the first line, the number of segments $n$ is given. In the following $n$ lines, the $i$-th segment is given by coordinates of its end points in the following format:
$x_1 \; y_1 \; x_2 \; y_2$
The coordinates are given in integers.
Output
Print the number of intersections in a line.
Example
Input
6
2 2 2 5
1 3 5 3
4 1 4 4
5 2 7 2
6 1 6 3
6 5 6 7
Output
3
Submitted Solution:
```
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
from sys import stdin
from typing import Any, List, Optional
from enum import IntEnum
class EPStatus(IntEnum):
BOTTOM = 0
LEFT = 1
RIGHT = 2
TOP = 3
class Point:
def __init__(self, x: float = 0.0, y: float = 0.0) -> None:
self.x = x
self.y = y
def __repr__(self) -> str:
return "({}, {})".format(self.x, self.y)
class Segment:
def __init__(
self, p1: Optional[Point] = None, p2: Optional[Point] = None
) -> None:
self.p1 = Point() if p1 is None else p1
self.p2 = Point() if p2 is None else p2
def __repr__(self) -> str:
return "({}, {})".format(self.p1, self.p2)
class EndPoint:
def __init__(self, p: Point, seg: Segment, st: EPStatus):
self.p = p
self.seg = seg
self.st = st
def __lt__(self, other: "EndPoint") -> bool:
return (
self.st < other.st
if self.p.y == other.p.y
else self.p.y < other.p.y
)
class Node:
def __init__(
self,
key: Any,
parent: Optional["Node"] = None,
left: Optional["Node"] = None,
right: Optional["Node"] = None,
) -> None:
self.key = key
self.parent = parent
self.left = left
self.right = right
def __str__(self) -> str:
return "({} {} {})".format(self.key, self.left, self.right)
def minimum_child(self) -> "Node":
x = self
while x.left is not None:
x = x.left
return x
def successor(self) -> Optional["Node"]:
if self.right is not None:
return self.right.minimum_child()
x = self
y = x.parent
while y is not None and x == y.right:
x = y
y = y.parent
return y
class Tree:
def __init__(self) -> None:
self.root: Optional[Node] = None
def __str__(self) -> str:
return str(self.root) if self.root else "()"
def insert(self, z: Node) -> None:
y = None
x = self.root
while x is not None:
y = x
x = x.left if z.key < x.key else x.right
z.parent = y
if y is None:
self.root = z
elif z.key < y.key:
y.left = z
else:
y.right = z
def find(self, key: Any) -> Optional[Node]:
x = self.root
while x is not None and key != x.key:
x = x.left if key < x.key else x.right
return x
def delete(self, z: Node) -> None:
y = z if z.left is None or z.right is None else z.successor()
x = y.right if y.left is None else y.left
if x is not None:
x.parent = y.parent
if y.parent is None:
self.root = x
elif y == y.parent.left:
y.parent.left = x
else:
y.parent.right = x
if y != z:
z.key = y.key
def lower_bound(self, key: Any) -> Optional[Node]:
x = self.root
b: Optional[Node] = None
while x is not None:
if key < x.key:
if b is None or x.key < b.key:
b = x
x = x.left
elif key == x.key:
b = x
break
else:
x = x.right
return b
def manhattanIntersection(S: List[Segment]) -> int:
def crosses(x1: float, x2: float) -> int:
cnt: int = 0
node: Optional[Node] = BT.lower_bound(x1)
while node is not None and node.key <= x2:
cnt += 1
node = node.successor()
return cnt
EP: List[EndPoint] = []
for s in S:
if (s.p1.y == s.p2.y and s.p1.x > s.p2.x) or (
s.p1.x == s.p2.x and s.p1.y > s.p2.y
):
s.p1, s.p2 = s.p2, s.p1
if s.p1.y == s.p2.y:
EP.append(EndPoint(s.p1, s, EPStatus.LEFT))
else:
EP.append(EndPoint(s.p1, s, EPStatus.BOTTOM))
EP.append(EndPoint(s.p2, s, EPStatus.TOP))
EP.sort()
BT = Tree()
cnt = 0
for e in EP:
if e.st == EPStatus.TOP:
BT.delete(BT.find(e.p.x))
elif e.st == EPStatus.BOTTOM:
BT.insert(Node(e.p.x))
elif e.st == EPStatus.LEFT:
cnt += crosses(e.seg.p1.x, e.seg.p2.x)
return cnt
def main() -> None:
S = []
n = int(stdin.readline())
for i in range(n):
x1, y1, x2, y2 = [int(x) for x in stdin.readline().split()]
S.append(Segment(Point(x1, y1), Point(x2, y2)))
print(manhattanIntersection(S))
main()
``` | instruction | 0 | 13,283 | 23 | 26,566 |
Yes | output | 1 | 13,283 | 23 | 26,567 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For given $n$ segments which are parallel to X-axis or Y-axis, find the number of intersections of them.
Constraints
* $1 \leq n \leq 100,000$
* $ -1,000,000,000 \leq x_1, y_1, x_2, y_2 \leq 1,000,000,000$
* Two parallel segments never overlap or touch.
* The number of intersections $\leq 1,000,000$
Input
In the first line, the number of segments $n$ is given. In the following $n$ lines, the $i$-th segment is given by coordinates of its end points in the following format:
$x_1 \; y_1 \; x_2 \; y_2$
The coordinates are given in integers.
Output
Print the number of intersections in a line.
Example
Input
6
2 2 2 5
1 3 5 3
4 1 4 4
5 2 7 2
6 1 6 3
6 5 6 7
Output
3
Submitted Solution:
```
import bisect
import sys
from typing import List, Tuple, Set
class BIT(object):
def __init__(self, n: int) -> None:
self.tree = [0] * (n + 1)
self.n = n
def add(self, i: int, v: int) -> None:
while i <= self.n:
self.tree[i] += v
i += i & -i
def _sum(self, i: int) -> int:
ret = 0
while i:
ret += self.tree[i]
i -= i & -i
return ret
def sum(self, l: int, h: int) -> int:
return self._sum(h) - self._sum(l - 1)
if __name__ == "__main__":
n = int(input())
vx: List[Tuple[int, int, int]] = []
x_init_set: Set[int] = set()
for _ in range(n):
x1, y1, x2, y2 = map(lambda x: int(x), input().split())
if x1 == x2:
if y1 > y2:
y1, y2 = y2, y1
vx.append((y1, -sys.maxsize, x1))
vx.append((y2, sys.maxsize, x1))
x_init_set.add(x1)
else:
if x1 > x2:
x1, x2 = x2, x1
vx.append((y1, x1, x2))
vx.sort()
bit = BIT(len(x_init_set))
xs = [-sys.maxsize] + sorted(x_init_set)
ix = {v: i for i, v in enumerate(xs)}
ans = 0
for y, j, x2 in vx:
if j == -sys.maxsize:
bit.add(ix[x2], 1)
elif j == sys.maxsize:
bit.add(ix[x2], -1)
else:
i1 = bisect.bisect_left(xs, j)
i2 = bisect.bisect(xs, x2) - 1
ans += bit.sum(i1, i2)
print(ans)
``` | instruction | 0 | 13,284 | 23 | 26,568 |
Yes | output | 1 | 13,284 | 23 | 26,569 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For given $n$ segments which are parallel to X-axis or Y-axis, find the number of intersections of them.
Constraints
* $1 \leq n \leq 100,000$
* $ -1,000,000,000 \leq x_1, y_1, x_2, y_2 \leq 1,000,000,000$
* Two parallel segments never overlap or touch.
* The number of intersections $\leq 1,000,000$
Input
In the first line, the number of segments $n$ is given. In the following $n$ lines, the $i$-th segment is given by coordinates of its end points in the following format:
$x_1 \; y_1 \; x_2 \; y_2$
The coordinates are given in integers.
Output
Print the number of intersections in a line.
Example
Input
6
2 2 2 5
1 3 5 3
4 1 4 4
5 2 7 2
6 1 6 3
6 5 6 7
Output
3
Submitted Solution:
```
# https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/all/CGL_6_A
from bisect import bisect_left, bisect_right, insort_left
from collections import deque
class BinarySearchTree:
def __init__(self, ls: list=[]):
'''
C++でいうsetを実装する。二分探索木をガチで実装しようとすると大変なので、ここでは配列二分法を用いる。
pythonの標準ライブラリがヨイショに抱っこしてくれるおかげで楽に実装できる。
https://docs.python.org/ja/3/library/bisect.html
ls ... 渡す初期配列
'''
self.bst = deque(sorted(ls)) # insertをO(1)にするためにlistの代わりにdequeを用います
def __repr__(self):
return f'BST:{self.bst}'
def __len__(self):
return len(self.bst)
def __getitem__(self, idx):
return self.bst[idx]
def size(self):
return len(self.bst)
def insert(self, x):
insort_left(self.bst, x)
def remove(self, x):
'''
xを取り除く。xがself.bstに存在することを保証してください。
同一のものが存在した場合は左から消していく
'''
del self.bst[self.find(x)]
def bisect_left(self, x):
'''
ソートされた順序を保ったまま x を self.bst に挿入できる点を探し当てます。
lower_bound in C++
'''
return bisect_left(self.bst, x)
def bisect_right(self, x):
'''
bisect_left() と似ていますが、 self.bst に含まれる x のうち、どのエントリーよりも後ろ(右)にくるような挿入点を返します。
upper_bound in C++
'''
return bisect_right(self.bst, x)
def find(self, x):
'''
xのidxを探索
'''
idx = bisect_left(self.bst, x)
if idx != len(self.bst) and self.bst[idx] == x:
return idx
raise ValueError
# load data
N = int(input())
lines = []
for _ in range(N):
x1, y1, x2, y2 = list(map(int, input().split()))
# 前処理として、x1,y1を必ず下端点or左端点にする
if y1 == y2: # 平行線の場合
if x1 > x2:
x1, x2 = x2, x1
else: # 垂直線の場合
if y1 > y2:
y1, y2 = y2, y1
lines.append((x1, y1, x2, y2))
# P409の下の方に書いてあるが、交差を判定する前に削除してしまったり、追加するまえに判定してしまったりすることを防ぐために
# うまい感じにソートするためにendpointsを導入する
# 各要素は(y,端点の種類,xで定義される)
BOTTOM = 0
LEFT = 1
RIGHT = 2
TOP = 3
# 線分の端点を必ず左下始まりにする
endpoints = []
for x1, y1, x2, y2 in lines:
if y1 == y2: # 平行線の場合
endpoints.append((y1, LEFT, x1, x2)) # 左端点の追加
endpoints.append((y2, RIGHT, x2, -1)) # 右端点の追加
else: # 垂直線の場合
endpoints.append((y1, BOTTOM, x1, -1)) # 下端点の追加
endpoints.append((y2, TOP, x2, -1)) # 下端点の追加
# yを下から走査するためにソート
endpoints.sort()
bst = BinarySearchTree()
ans = 0
for y, p_type, x, x_t in endpoints:
# if p_type == RIGHT:
# continue # 後述しますが、右端点は左端点とセットで処理するためスキップしても問題ないです
# 以下端点の種類ごとに操作を実装
if p_type == TOP:
bst.remove(x) # 上端点の場合はbstに登録してあるxを削除
elif p_type == BOTTOM:
bst.insert(x) # 下端点の場合はbstにxを登録
elif p_type == LEFT:
s = bst.bisect_left(x) # bstにおいて、水平線の左は何番目に大きいか
t = bst.bisect_right(x_t) # bstにおいて、水平線の右は何番目に大きいか(同じ値も含めて)
ans += t - s
print(ans)
``` | instruction | 0 | 13,285 | 23 | 26,570 |
Yes | output | 1 | 13,285 | 23 | 26,571 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For given $n$ segments which are parallel to X-axis or Y-axis, find the number of intersections of them.
Constraints
* $1 \leq n \leq 100,000$
* $ -1,000,000,000 \leq x_1, y_1, x_2, y_2 \leq 1,000,000,000$
* Two parallel segments never overlap or touch.
* The number of intersections $\leq 1,000,000$
Input
In the first line, the number of segments $n$ is given. In the following $n$ lines, the $i$-th segment is given by coordinates of its end points in the following format:
$x_1 \; y_1 \; x_2 \; y_2$
The coordinates are given in integers.
Output
Print the number of intersections in a line.
Example
Input
6
2 2 2 5
1 3 5 3
4 1 4 4
5 2 7 2
6 1 6 3
6 5 6 7
Output
3
Submitted Solution:
```
import bisect
class BIT:
def __init__(self, n):
self.tree = [0] * (n + 1)
self.n = n
def add(self, i, v):
while i <= self.n:
self.tree[i] += v
i += i & -i
def _sum(self, i):
ret = 0
while i:
ret += self.tree[i]
i -= i & -i
return ret
def sum(self, l, h):
return self._sum(h) - self._sum(l - 1)
n = int(input())
vx = []
xs = set()
for _ in range(n):
x1, y1, x2, y2 = map(int, input().split())
if x1 == x2:
if y1 > y2:
y1, y2 = y2, y1
vx.append((y1, float('-inf'), x1))
vx.append((y2, float('inf'), x1))
xs.add(x1)
else:
if x1 > x2:
x1, x2 = x2, x1
vx.append((y1, x1, x2))
vx.sort()
bit = BIT(len(xs))
xs = [float('-inf')] + sorted(xs)
ix = {v: i for i, v in enumerate(xs)}
ans = 0
for y, j, x2 in vx:
if j == float('-inf'):
bit.add(ix[x2], 1)
elif j == float('inf'):
bit.add(ix[x2], -1)
else:
i1 = bisect.bisect_left(xs, j)
i2 = bisect.bisect(xs, x2) - 1
ans += bit.sum(i1, i2)
print(ans)
``` | instruction | 0 | 13,286 | 23 | 26,572 |
Yes | output | 1 | 13,286 | 23 | 26,573 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For given $n$ segments which are parallel to X-axis or Y-axis, find the number of intersections of them.
Constraints
* $1 \leq n \leq 100,000$
* $ -1,000,000,000 \leq x_1, y_1, x_2, y_2 \leq 1,000,000,000$
* Two parallel segments never overlap or touch.
* The number of intersections $\leq 1,000,000$
Input
In the first line, the number of segments $n$ is given. In the following $n$ lines, the $i$-th segment is given by coordinates of its end points in the following format:
$x_1 \; y_1 \; x_2 \; y_2$
The coordinates are given in integers.
Output
Print the number of intersections in a line.
Example
Input
6
2 2 2 5
1 3 5 3
4 1 4 4
5 2 7 2
6 1 6 3
6 5 6 7
Output
3
Submitted Solution:
```
lass AvlTree(BinarySearchTree):
'''An extension t the BinarySearchTree data structure which
strives to keep itself balanced '''
def _put(self,key,val,currentNode):
if key < currentNode.key:
if current.Node.hasLeftChild():
self._put(key,val,currentNode.leftChild)
else:
currentNode.leftChild = TreeNode(key,val,parent=currentNode)
self.updateBalance(currentNode.leftChile)
else:
if currentNode.hasRightChild():
self._put(key,val,currentNode.rightChild)
else:
currentNode.rightChild = TreeNode(key,val,parent=currentNode)
self.updateBalance(currentNode.rightChild)
def updateBalance(self,node):
if node.balanceFactor > 1 or node.balanceFactor < -1:
self.rebalance(node)
return
if node.parent != None:
if node.isLeftChild():
node.parent.balancefactor += 1
elif node.isRightChild():
node.parent.balanceFactor -= 1
if node.parent.balanceFactor != 0:
self.updateBalance(node.parent)
def rotateLeft(self,rotRoot):
newRoot = rotRoot.rightChild
rotRoot.rightChild = newRoot.leftChild
if newRoot.leftChild != None:
newRoot.leftChild.parent = rotRoot
newRoot.parent = rotRoot.parent
if rotRoot.isRoot():
self.root = newRoot
else:
if rotRoot.isLeftChild():
rotRoot.parent.leftChild = newRoot
else:
rotRoot.parent.rightChild = newRoot
newRoot.leftChild = rotRoot
rotRoot.parent = newRoot
rotRoot.balanceFactor = rotRoot.balanceFactor + 1 - min(
newRoot.balanceFactor, 0)
newRoot.balanceFactor = newRoot.blanceFactor + 1 + max(
rotRoot.balanceFactor, 0)
def rotateRight(self,rotRoot):
newRoot = rotRoot.leftChild
rotRoot.leftChild = newRoot.rightChild
if newRoot.rightChild != None:
newRoot.rightChild.parent = rotRoot
newRoot.parent = rotRoot.parent
if rotRoot.isRoot():
self.root = newRoot
else:
if rotRoot.isRightChild():
rotRoot.parent.rightChild = newRoot
# leftchild??????
newRoot.rightChild = rotRoot
rotRoot.parent = newRoot
rotRoot.balanceFactor = rotRoot.balanceFactor + 1 - min(
newRoot.balanceFactor, 0)
newRoot.balanceFactor = newRoot.balanceFactor + 1 + max(
rotRoot.balanceFactor, 0)
def rebalance(self,node):
if node.balanceFactor < 0:
if node.rightChild.balanceFactor > 0:
self.rotateRight(node.rightChild)
self.rotateLeft(node)
else:
self.rotateLeft(node)
elif node.balanceFactor > 0:
if node.leftChild.balanceFactor < 0:
self.rotateLeft(node.leftchilc)
self.rotateRight(node)
else:
self.rotateRight(node)
``` | instruction | 0 | 13,287 | 23 | 26,574 |
No | output | 1 | 13,287 | 23 | 26,575 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For given $n$ segments which are parallel to X-axis or Y-axis, find the number of intersections of them.
Constraints
* $1 \leq n \leq 100,000$
* $ -1,000,000,000 \leq x_1, y_1, x_2, y_2 \leq 1,000,000,000$
* Two parallel segments never overlap or touch.
* The number of intersections $\leq 1,000,000$
Input
In the first line, the number of segments $n$ is given. In the following $n$ lines, the $i$-th segment is given by coordinates of its end points in the following format:
$x_1 \; y_1 \; x_2 \; y_2$
The coordinates are given in integers.
Output
Print the number of intersections in a line.
Example
Input
6
2 2 2 5
1 3 5 3
4 1 4 4
5 2 7 2
6 1 6 3
6 5 6 7
Output
3
Submitted Solution:
```
from sys import stdin
from operator import itemgetter
readline = stdin.readline
VERTICAL_LOW, HORIZONTAL, VERTICAL_HIGH = 2, 1, 0
import math
class segment_tree:
# self.table is 1-indexed
# math.log2 not implemented 3.2.3
def __init__(self, dat, query, default=0):
self.offset = 2 ** math.ceil(math.log(len(dat), 2))
self.table = [default] * self.offset + dat + [default] * (self.offset - len(dat))
self.query = query
for i in reversed(range(1, self.offset)):
self.table[i] = self.query([self.table[2 * i], self.table[2 * i + 1]])
# [l, r] closed-interval
def find(self, l, r):
return self.query(self.__range(l,r))
def __range(self, l, r):
l += self.offset
r += self.offset
while l <= r:
if l & 1:
yield self.table[l]
l += 1
l >>= 1
if r & 1 == 0:
yield self.table[r]
r -= 1
r >>= 1
def update(self, i, x):
i += self.offset
self.table[i] = x
while 1 < i:
i >>= 1
self.table[i] = self.query([self.table[2 * i], self.table[2 * i + 1]])
def main():
n = int(readline())
p = [list(map(int, readline().split())) for _ in range(n)]
x = set(x1 for x1, y1, x2, y2 in p) | set(x2 for x1, y1, x2, y2 in p)
c = {xi:i for i, xi in enumerate(x)}
que = []
for x1, y1, x2, y2 in p:
if y1 == y2:
if x1 > x2:
x1, x2 = x2, x1
que.append((y1, HORIZONTAL, c[x1], c[x2]))
else:
if y1 > y2:
y1, y2 = y2, y1
x1 = c[x1]
que.append((y1, VERTICAL_LOW, x1, None))
que.append((y2, VERTICAL_HIGH, x1, None))
que.sort(key=itemgetter(0, 1))
vertical_info = segment_tree([0] * len(x), sum, default=0)
intersection = 0
for y1, action, x1, x2 in que:
if action == VERTICAL_LOW:
vertical_info.update(x1, 1)
elif action == HORIZONTAL:
intersection += vertical_info.find(x1 + 1, x2 - 1)
else:
vertical_info.update(x1, 0)
print(intersection)
main()
``` | instruction | 0 | 13,288 | 23 | 26,576 |
No | output | 1 | 13,288 | 23 | 26,577 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For given $n$ segments which are parallel to X-axis or Y-axis, find the number of intersections of them.
Constraints
* $1 \leq n \leq 100,000$
* $ -1,000,000,000 \leq x_1, y_1, x_2, y_2 \leq 1,000,000,000$
* Two parallel segments never overlap or touch.
* The number of intersections $\leq 1,000,000$
Input
In the first line, the number of segments $n$ is given. In the following $n$ lines, the $i$-th segment is given by coordinates of its end points in the following format:
$x_1 \; y_1 \; x_2 \; y_2$
The coordinates are given in integers.
Output
Print the number of intersections in a line.
Example
Input
6
2 2 2 5
1 3 5 3
4 1 4 4
5 2 7 2
6 1 6 3
6 5 6 7
Output
3
Submitted Solution:
```
# -*- coding: utf-8 -*-
import collections
import math
import bisect
class Vector2(collections.namedtuple("Vector2", ["x", "y"])):
def __add__(self, other):
return Vector2(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector2(self.x - other.x, self.y - other.y)
def __mul__(self, scalar):
return Vector2(self.x * scalar, self.y * scalar)
def __neg__(self):
return Vector2(-self.x, -self.y)
def __pos__(self):
return Vector2(+self.x, +self.y)
def __abs__(self): # norm
return math.sqrt(float(self.x * self.x + self.y * self.y))
def __truediv__(self, scalar):
return Vector2(self.x / scalar, self.y / scalar)
def abs2(self):
return float(self.x * self.x + self.y * self.y)
def dot(self, other): # dot product
return self.x * other.x + self.y * other.y
def cross(self, other): # cross product
return self.x * other.y - self.y * other.x
def getDistanceSP(segment, point):
p = point
p1, p2 = segment
if (p2 - p1).dot(p - p1) < 0:
return abs(p - p1)
if (p1 - p2).dot(p - p2) < 0:
return abs(p - p2)
return abs((p2 - p1).cross(p - p1)) / abs(p2 - p1)
def getDistance(s1, s2):
a, b = s1
c, d = s2
if intersect(s1, s2): # intersect
return 0
return min(getDistanceSP(s1, c), getDistanceSP(s1, d), getDistanceSP(s2, a), getDistanceSP(s2, b))
def ccw(p0, p1, p2):
a = p1 - p0
b = p2 - p0
if a.cross(b) > 0:
return 1 # COUNTER_CLOCKWISE
elif a.cross(b) < 0:
return -1 # CLOCKWISE
elif a.dot(b) < 0:
return 2 # ONLINE_BACK
elif abs(a) < abs(b):
return -2 # ONLINE_FRONT
else:
return 0 # ON_SEGMENT
def intersect(s1, s2):
a, b = s1
c, d = s2
return ccw(a, b, c) * ccw(a, b, d) <= 0 and ccw(c, d, a) * ccw(c, d, b) <= 0
def project(l, p):
p1, p2 = l
base = p2 - p1
hypo = p - p1
return p1 + base * (hypo.dot(base) / abs(base)**2)
class Circle():
def __init__(self, c, r):
self.c = c
self.r = r
def getCrossPoints(c, l):
pr = project(l, c.c)
p1, p2 = l
e = (p2 - p1) / abs(p2 - p1)
base = math.sqrt(c.r * c.r - (pr - c.c).abs2())
return [pr + e * base, pr - e * base]
def polar(r, a):
return Vector2(r * math.cos(a), r * math.sin(a))
def getCrossPointsCircle(c1, c2):
base = c2.c - c1.c
d = abs(base)
a = math.acos((c1.r**2 + d**2 - c2.r**2) / (2 * c1.r * d))
t = math.atan2(base.y, base.x)
return [c1.c + polar(c1.r, t + a), c1.c + polar(c1.r, t - a)]
def contains(g, p):
n = len(g)
x = 0
for i in range(n):
a = g[i] - p
b = g[(i + 1) % n] - p
if a.cross(b) == 0 and a.dot(b) <= 0:
return 1
if a.y > b.y:
a, b = b, a
if a.y <= 0 and b.y > 0 and a.cross(b) > 0:
x += 1
if x % 2 == 1:
return 2
else:
return 0
def andrewScan(s):
u = []
l = []
s = sorted(s, key=lambda x: (x.x, x.y))
if len(s) < 3:
return s
u.append(s[0])
u.append(s[1])
l.append(s[-1])
l.append(s[-2])
for i in range(2, len(s)):
for n in range(len(u), 1, -1):
if ccw(u[n - 2], u[n - 1], s[i]) != 1:
break
else:
u.pop()
u.append(s[i])
for i in range(len(s) - 3, -1, -1):
for n in range(len(l), 1, -1):
if ccw(l[n - 2], l[n - 1], s[i]) != 1:
break
else:
l.pop()
l.append(s[i])
ans = l + u[1:-1]
ans.reverse()
return ans
class EndPoint():
def __init__(self, p, seg, st):
self.p = p
self.seg = seg
self.st = st
if __name__ == '__main__':
n = int(input())
EP = []
S = []
for i in range(n):
a, b, c, d = map(int, input().split())
if a == c: # y軸と平行
EP.append(EndPoint(Vector2(a, min(b, d)), i, 3)) # top
EP.append(EndPoint(Vector2(a, max(b, d)), i, 0)) # bottom
S.append([Vector2(a, max(b, d)), Vector2(a, min(b, d))])
else: # x軸と平行
EP.append(EndPoint(Vector2(min(a, c), b), i, 1)) # left
EP.append(EndPoint(Vector2(max(a, c), b), i, 2)) # right
S.append([Vector2(min(a, c), b), Vector2(max(a, c), b)])
EP = sorted(EP, key=lambda x: (x.p.y, x.st))
BT = []
cnt = 0
for e in EP:
if e.st == 0:
BT.remove(e.p.x)
elif e.st == 3:
bisect.insort_left(BT, e.p.x)
elif e.st == 1:
l = bisect.bisect_left(BT, S[e.seg][0].x)
r = bisect.bisect_right(BT, S[e.seg][1].x)
cnt += r-l
print(cnt)
``` | instruction | 0 | 13,289 | 23 | 26,578 |
No | output | 1 | 13,289 | 23 | 26,579 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For given $n$ segments which are parallel to X-axis or Y-axis, find the number of intersections of them.
Constraints
* $1 \leq n \leq 100,000$
* $ -1,000,000,000 \leq x_1, y_1, x_2, y_2 \leq 1,000,000,000$
* Two parallel segments never overlap or touch.
* The number of intersections $\leq 1,000,000$
Input
In the first line, the number of segments $n$ is given. In the following $n$ lines, the $i$-th segment is given by coordinates of its end points in the following format:
$x_1 \; y_1 \; x_2 \; y_2$
The coordinates are given in integers.
Output
Print the number of intersections in a line.
Example
Input
6
2 2 2 5
1 3 5 3
4 1 4 4
5 2 7 2
6 1 6 3
6 5 6 7
Output
3
Submitted Solution:
```
import bisect
import copy
EPS=10**(-10)
class Point():
def __init__(self,x=None,y=None):
self.x=x
self.y=y
def __lt__(self, value):
if self.x!=value.x:
return self.x<value.x
else:
return self.y<value.y
def __eq__(self,value):
cmp= abs(self.x-value.x)<EPS and abs(self.y-value.y)<EPS
return cmp
class Segment():
def __init__(self,p1=Point(0,0),p2=Point(0,0)):
self.p1=p1
self.p2=p2
BOTTOM =0
LEFT=1
RIGHT =2
TOP=3
class EndPoint():
def __init__(self,p=None,seg=None,st=None):
self.p=p
self.seg=seg
self.st=st
def __lt__(self, value):
if self.p.y==value.p.y:
return self.st<value.st
return self.p.y<value.p.y
#线段相交问题,曼哈顿几何
def manhattanIntersection(S):
n =len(S)
global EP
#按照端点的y坐标升序排序
EP.sort()
BT=[] # 二叉搜索树
#BT.insert(10000000001)# 设置标记
cnt = 0
for i in range(2*n):
if EP[i].st==TOP:
idx=bisect.bisect_left(BT,EP[i].p.x)
if idx>=0 and idx< len(EP):
BT.pop(idx)
#BT.erase(EP[i].p.x) #删除上端点
elif (EP[i].st == BOTTOM):
bisect.insort_left(BT,EP[i].p.x)
#BT.insert(EP[i].p.x)
elif (EP[i].st == LEFT):
idxb=bisect.bisect_left(BT,S[EP[i].seg].p1.x)
idxe=bisect.bisect_left(BT,S[EP[i].seg].p2.x)
#set<int>::iterator b = BT.lower_bound(S[EP[i].seg].p1.x);
#set<int>::iterator e = BT.upper_bound(S[EP[i].seg].p2.x);
#加上b到e距离
cnt +=abs(idxe-idxb) # distance(b, e);
return cnt
n=int(input())
EP=[ None for i in range(2*n)]
S=[]
seglist=[]
k=0
for i in range(n):
seg=Segment()
ss=[int(x) for x in input().split()]
seg.p1.x=ss[0]
seg.p1.y=ss[1]
seg.p2.x=ss[2]
seg.p2.y=ss[3]
copy.deepcopy(seg)
seglist.append(copy.deepcopy(seg))
seg=seglist[i]
if seg.p1.y==seg.p2.y:
if seg.p1.x>seg.p2.x:
seg.p1,seg.p2=seg.p2,seg.p1
elif seg.p1.y>seg.p2.y:
seg.p1,seg.p2=seg.p2,seg.p1
#将水平线段添加到端点列表
if (seg.p1.y == seg.p2.y) :
EP[k] = EndPoint(seg.p1, i, LEFT)
k+=1
EP[k] = EndPoint(seg.p2, i, RIGHT)
k+=1
else: # 将垂直线段添加到端点列表
EP[k] = EndPoint(seg.p1, i, BOTTOM)
k+=1
EP[k] = EndPoint(seg.p2, i, TOP)
k+=1
S.append(seg)
print("%d"%(manhattanIntersection(S)))
``` | instruction | 0 | 13,290 | 23 | 26,580 |
No | output | 1 | 13,290 | 23 | 26,581 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n segments drawn on a plane; the i-th segment connects two points (x_{i, 1}, y_{i, 1}) and (x_{i, 2}, y_{i, 2}). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every i ∈ [1, n] either x_{i, 1} = x_{i, 2} or y_{i, 1} = y_{i, 2} (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.
We say that four segments having indices h_1, h_2, v_1 and v_2 such that h_1 < h_2 and v_1 < v_2 form a rectangle if the following conditions hold:
* segments h_1 and h_2 are horizontal;
* segments v_1 and v_2 are vertical;
* segment h_1 intersects with segment v_1;
* segment h_2 intersects with segment v_1;
* segment h_1 intersects with segment v_2;
* segment h_2 intersects with segment v_2.
Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions h_1 < h_2 and v_1 < v_2 should hold.
Input
The first line contains one integer n (1 ≤ n ≤ 5000) — the number of segments.
Then n lines follow. The i-th line contains four integers x_{i, 1}, y_{i, 1}, x_{i, 2} and y_{i, 2} denoting the endpoints of the i-th segment. All coordinates of the endpoints are in the range [-5000, 5000].
It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.
Output
Print one integer — the number of ways to choose four segments so they form a rectangle.
Examples
Input
7
-1 4 -1 -2
6 -1 -2 -1
-2 3 6 3
2 -2 2 4
4 -1 4 3
5 3 5 1
5 2 1 2
Output
7
Input
5
1 5 1 0
0 1 5 1
5 4 0 4
4 2 4 0
4 3 4 5
Output
0
Note
The following pictures represent sample cases:
<image> <image>
Submitted Solution:
```
def bisect(arr,val):
l=0
r=len(arr)
while r-l!=1:
m=(l+r)//2
if arr[m][0]>val:
r=m
else:
l=m
return l
n=int(input())
v=[]
h=[]
for _ in range(n):
a,b,c,d=map(int,input().split())
a,b,c,d=a+5000,b+5000,c+5000,d+5000
if a==c:
v.append((a,min(b,d),abs(d-b)))
else:
h.append((b,min(a,c),abs(c-a)))
v=sorted(v,key=lambda x:x[0])
h=sorted(h,key=lambda x:x[0])
lv=len(v)
lh=len(h)
ans=0
for i in range(lv):
for j in range(i+1,lv):
if v[i][1]>(v[j][1]+v[j][2]):
continue
elif (v[i][1]+v[i][2])<v[j][1]:
continue
else:
bottom=max(v[i][1],v[j][1])
top=min((v[i][1]+v[i][2]),(v[j][1]+v[j][2]))
left=v[i][0]
right=v[j][0]
l=bisect(h,bottom)
r=bisect(h,top)
if h[l][0]<bottom:
l+=1
cnt=0
for k in range(l,r+1):
tleft=h[k][1]
tright=h[k][1]+h[k][2]
print(tleft,tright,left,right)
if tleft<=left and right<=tright:
cnt+=1
ans+=(cnt*(cnt-1))//2
print(ans)
``` | instruction | 0 | 13,394 | 23 | 26,788 |
No | output | 1 | 13,394 | 23 | 26,789 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.