message stringlengths 2 44.5k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 276 109k | cluster float64 23 23 | __index_level_0__ int64 552 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a square of size 10^6 × 10^6 on the coordinate plane with four points (0, 0), (0, 10^6), (10^6, 0), and (10^6, 10^6) as its vertices.
You are going to draw segments on the plane. All segments are either horizontal or vertical and intersect with at least one side of the square.
Now you are wondering how many pieces this square divides into after drawing all segments. Write a program calculating the number of pieces of the square.
Input
The first line contains two integers n and m (0 ≤ n, m ≤ 10^5) — the number of horizontal segments and the number of vertical segments.
The next n lines contain descriptions of the horizontal segments. The i-th line contains three integers y_i, lx_i and rx_i (0 < y_i < 10^6; 0 ≤ lx_i < rx_i ≤ 10^6), which means the segment connects (lx_i, y_i) and (rx_i, y_i).
The next m lines contain descriptions of the vertical segments. The i-th line contains three integers x_i, ly_i and ry_i (0 < x_i < 10^6; 0 ≤ ly_i < ry_i ≤ 10^6), which means the segment connects (x_i, ly_i) and (x_i, ry_i).
It's guaranteed that there are no two segments on the same line, and each segment intersects with at least one of square's sides.
Output
Print the number of pieces the square is divided into after drawing all the segments.
Example
Input
3 3
2 3 1000000
4 0 4
3 0 1000000
4 0 1
2 0 5
3 1 1000000
Output
7
Note
The sample is like this:
<image>
Submitted Solution:
```
n,m = map(int,input().split())
k = 10**6
heights = [[0,[0,k]],[0,[k,0]],[k,[0,k]],[k,[k,0]]]
ans=0
for i in range(n):
l1 = list(map(int,input().split()))
#heights.append(l1[0])
heights.append([l1[0],[l1[1],l1[2]]])
#vertisegs.append([l1[1],l1[2]])
for i in range(m):
l2 = list(map(int,input().split()))
for x in range(n+4):
if l2[0]>=heights[x][1][0] and l2[0]<=heights[x][1][1]:
if l2[1]<=heights[x][0] and l2[2]>=heights[x][0]:
ans+=1
print(ans)
``` | instruction | 0 | 32,715 | 23 | 65,430 |
No | output | 1 | 32,715 | 23 | 65,431 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a set of dominoes. Each domino is a rectangular tile with a line dividing its face into two square ends. Can you put all dominoes in a line one by one from left to right so that any two dominoes touched with the sides that had the same number of points? You can rotate the dominoes, changing the left and the right side (domino "1-4" turns into "4-1").
Input
The first line contains number n (1 ≤ n ≤ 100). Next n lines contains the dominoes. Each of these lines contains two numbers — the number of points (spots) on the left and the right half, correspondingly. The numbers of points (spots) are non-negative integers from 0 to 6.
Output
Print "No solution", if it is impossible to arrange the dominoes in the required manner. If the solution exists, then describe any way to arrange the dominoes. You put the dominoes from left to right. In each of n lines print the index of the domino to put in the corresponding position and then, after a space, character "+" (if you don't need to turn the domino) or "–" (if you need to turn it).
Examples
Input
5
1 2
2 4
2 4
6 4
2 1
Output
2 -
1 -
5 -
3 +
4 - | instruction | 0 | 32,809 | 23 | 65,618 |
Tags: dfs and similar, graphs
Correct Solution:
```
def euler(start):
s = [(start,0)]
ans = []
while s:
i,e = s[-1]
if i in mark:
mark.remove(i)
if degree[i]==0:
ans.append(e)
s.pop()
else:
for j,e in graph[i]:
if vis[abs(e)]==0:
degree[i]-=1
degree[j]-=1
vis[abs(e)]=1
s.append((j, e))
break
#ans.reverse()
if mark:
print("No solution")
else:
for i in ans:
if i<0:
print(-i,"+")
elif i>0:
print(i, "-")
n = int(input())
degree = [0]*7
vis = [0]*(n+1)
graph = [[] for _ in range(7)]
start = 0
mark = set()
for i in range(1,1+n):
x,y = map(int, input().split())
graph[x].append((y, i))
graph[y].append((x, -i))
degree[x]+=1
degree[y]+=1
mark.add(x)
mark.add(y)
start = x
odd =0
for i in range(0,7):
if degree[i]%2==1:
odd+=1
start=i
if odd not in [0,2]:
print("No solution")
else:
euler(start)
``` | output | 1 | 32,809 | 23 | 65,619 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a set of dominoes. Each domino is a rectangular tile with a line dividing its face into two square ends. Can you put all dominoes in a line one by one from left to right so that any two dominoes touched with the sides that had the same number of points? You can rotate the dominoes, changing the left and the right side (domino "1-4" turns into "4-1").
Input
The first line contains number n (1 ≤ n ≤ 100). Next n lines contains the dominoes. Each of these lines contains two numbers — the number of points (spots) on the left and the right half, correspondingly. The numbers of points (spots) are non-negative integers from 0 to 6.
Output
Print "No solution", if it is impossible to arrange the dominoes in the required manner. If the solution exists, then describe any way to arrange the dominoes. You put the dominoes from left to right. In each of n lines print the index of the domino to put in the corresponding position and then, after a space, character "+" (if you don't need to turn the domino) or "–" (if you need to turn it).
Examples
Input
5
1 2
2 4
2 4
6 4
2 1
Output
2 -
1 -
5 -
3 +
4 -
Submitted Solution:
```
def euler(i):
s = [(i,0)]
ans = []
while s:
i,e = s[-1]
if degree[i]==0:
ans.append(e)
s.pop()
for j,e in graph[i]:
if vis[abs(e)]==0:
degree[i]-=1
degree[j]-=1
vis[abs(e)]=1
s.append((j, e))
break
ans.reverse()
for i in ans:
if i<0:
print(-i,"-")
elif i>0:
print(i, "+")
n = int(input())
degree = [0]*7
vis = [0]*(n+1)
graph = [[] for _ in range(7)]
for i in range(1,1+n):
x,y = map(int, input().split())
graph[x].append((y, i))
graph[y].append((x, -i))
degree[x]+=1
degree[y]+=1
odd =0
start=0
for i in range(0,7):
if degree[i]%2==1:
odd+=1
start=i
if odd not in [0,2]:
print("Impossible")
else:
euler(start)
``` | instruction | 0 | 32,810 | 23 | 65,620 |
No | output | 1 | 32,810 | 23 | 65,621 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a set of dominoes. Each domino is a rectangular tile with a line dividing its face into two square ends. Can you put all dominoes in a line one by one from left to right so that any two dominoes touched with the sides that had the same number of points? You can rotate the dominoes, changing the left and the right side (domino "1-4" turns into "4-1").
Input
The first line contains number n (1 ≤ n ≤ 100). Next n lines contains the dominoes. Each of these lines contains two numbers — the number of points (spots) on the left and the right half, correspondingly. The numbers of points (spots) are non-negative integers from 0 to 6.
Output
Print "No solution", if it is impossible to arrange the dominoes in the required manner. If the solution exists, then describe any way to arrange the dominoes. You put the dominoes from left to right. In each of n lines print the index of the domino to put in the corresponding position and then, after a space, character "+" (if you don't need to turn the domino) or "–" (if you need to turn it).
Examples
Input
5
1 2
2 4
2 4
6 4
2 1
Output
2 -
1 -
5 -
3 +
4 -
Submitted Solution:
```
def euler(start):
s = [(start,0)]
ans = []
while s:
i,e = s[-1]
if i in mark:
mark.remove(i)
if degree[i]==0:
ans.append(e)
s.pop()
else:
for j,e in graph[i]:
if vis[abs(e)]==0:
degree[i]-=1
degree[j]-=1
vis[abs(e)]=1
s.append((j, e))
break
#ans.reverse()
if mark:
print("Impossible")
else:
for i in ans:
if i<0:
print(-i,"+")
elif i>0:
print(i, "-")
n = int(input())
degree = [0]*7
vis = [0]*(n+1)
graph = [[] for _ in range(7)]
start = 0
mark = set()
for i in range(1,1+n):
x,y = map(int, input().split())
graph[x].append((y, i))
graph[y].append((x, -i))
degree[x]+=1
degree[y]+=1
mark.add(x)
mark.add(y)
start = x
odd =0
for i in range(0,7):
if degree[i]%2==1:
odd+=1
start=i
if odd not in [0,2]:
print("Impossible")
else:
euler(start)
``` | instruction | 0 | 32,811 | 23 | 65,622 |
No | output | 1 | 32,811 | 23 | 65,623 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a set of dominoes. Each domino is a rectangular tile with a line dividing its face into two square ends. Can you put all dominoes in a line one by one from left to right so that any two dominoes touched with the sides that had the same number of points? You can rotate the dominoes, changing the left and the right side (domino "1-4" turns into "4-1").
Input
The first line contains number n (1 ≤ n ≤ 100). Next n lines contains the dominoes. Each of these lines contains two numbers — the number of points (spots) on the left and the right half, correspondingly. The numbers of points (spots) are non-negative integers from 0 to 6.
Output
Print "No solution", if it is impossible to arrange the dominoes in the required manner. If the solution exists, then describe any way to arrange the dominoes. You put the dominoes from left to right. In each of n lines print the index of the domino to put in the corresponding position and then, after a space, character "+" (if you don't need to turn the domino) or "–" (if you need to turn it).
Examples
Input
5
1 2
2 4
2 4
6 4
2 1
Output
2 -
1 -
5 -
3 +
4 -
Submitted Solution:
```
def euler(start):
s = [(start,0)]
ans = []
while s:
i,e = s[-1]
if degree[i]==0:
ans.append(e)
s.pop()
else:
for j,e in graph[i]:
if vis[abs(e)]==0:
degree[i]-=1
degree[j]-=1
vis[abs(e)]=1
s.append((j, e))
break
#ans.reverse()
for i in ans:
if i<0:
print(-i,"+")
elif i>0:
print(i, "-")
n = int(input())
degree = [0]*7
vis = [0]*(n+1)
graph = [[] for _ in range(7)]
start = 0
for i in range(1,1+n):
x,y = map(int, input().split())
graph[x].append((y, i))
graph[y].append((x, -i))
degree[x]+=1
degree[y]+=1
start = x
odd =0
for i in range(0,7):
if degree[i]%2==1:
odd+=1
start=i
if odd not in [0,2]:
print("Impossible")
else:
euler(start)
``` | instruction | 0 | 32,812 | 23 | 65,624 |
No | output | 1 | 32,812 | 23 | 65,625 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a set of dominoes. Each domino is a rectangular tile with a line dividing its face into two square ends. Can you put all dominoes in a line one by one from left to right so that any two dominoes touched with the sides that had the same number of points? You can rotate the dominoes, changing the left and the right side (domino "1-4" turns into "4-1").
Input
The first line contains number n (1 ≤ n ≤ 100). Next n lines contains the dominoes. Each of these lines contains two numbers — the number of points (spots) on the left and the right half, correspondingly. The numbers of points (spots) are non-negative integers from 0 to 6.
Output
Print "No solution", if it is impossible to arrange the dominoes in the required manner. If the solution exists, then describe any way to arrange the dominoes. You put the dominoes from left to right. In each of n lines print the index of the domino to put in the corresponding position and then, after a space, character "+" (if you don't need to turn the domino) or "–" (if you need to turn it).
Examples
Input
5
1 2
2 4
2 4
6 4
2 1
Output
2 -
1 -
5 -
3 +
4 -
Submitted Solution:
```
def euler(i):
s = [(i,0)]
ans = []
while s:
i,e = s[-1]
if degree[i]==0:
ans.append(e)
s.pop()
for j,e in graph[i]:
if vis[abs(e)]==0:
degree[i]-=1
degree[j]-=1
vis[abs(e)]=1
s.append((j, e))
break
#ans.reverse()
for i in ans:
if i<0:
print(-i,"+")
elif i>0:
print(i, "-")
n = int(input())
degree = [0]*7
vis = [0]*(n+1)
graph = [[] for _ in range(7)]
for i in range(1,1+n):
x,y = map(int, input().split())
graph[x].append((y, i))
graph[y].append((x, -i))
degree[x]+=1
degree[y]+=1
odd =0
start=0
for i in range(0,7):
if degree[i]%2==1:
odd+=1
start=i
if odd not in [0,2]:
print("Impossible")
else:
euler(start)
``` | instruction | 0 | 32,813 | 23 | 65,626 |
No | output | 1 | 32,813 | 23 | 65,627 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.
The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.
Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A:
<image>
The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.
However, there is much more to the homework. Chris has to process q queries; each query can be one of the following:
1. given a row index i, flip all the values in the i-th row in A;
2. given a column index i, flip all the values in the i-th column in A;
3. find the unusual square of A.
To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.
Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
Input
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A.
The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following:
* 1 i — flip the values of the i-th row;
* 2 i — flip the values of the i-th column;
* 3 — output the unusual square of A.
Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Output
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
Examples
Input
3
1 1 1
0 1 1
1 0 0
12
3
2 3
3
2 2
2 2
1 3
3
3
1 2
2 1
1 1
3
Output
01001 | instruction | 0 | 32,877 | 23 | 65,754 |
Tags: implementation, math
Correct Solution:
```
from sys import stdin
input=stdin.readline
n = int(input())
matrix = []
diagOnes = 0
for i in range(n):
row = input().split()
if row[i] == '1':
diagOnes += 1
matrix.append(row)
q = int(input())
result = []
for _ in range(q):
a = input().rstrip()
if a == '3':
result.append(str(diagOnes % 2))
else:
command, index = a.split()
index = int(index) - 1
if matrix[i][i] == '1':
diagOnes -= 1
else:
diagOnes += 1
print("".join(result))
``` | output | 1 | 32,877 | 23 | 65,755 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.
The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.
Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A:
<image>
The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.
However, there is much more to the homework. Chris has to process q queries; each query can be one of the following:
1. given a row index i, flip all the values in the i-th row in A;
2. given a column index i, flip all the values in the i-th column in A;
3. find the unusual square of A.
To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.
Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
Input
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A.
The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following:
* 1 i — flip the values of the i-th row;
* 2 i — flip the values of the i-th column;
* 3 — output the unusual square of A.
Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Output
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
Examples
Input
3
1 1 1
0 1 1
1 0 0
12
3
2 3
3
2 2
2 2
1 3
3
3
1 2
2 1
1 1
3
Output
01001 | instruction | 0 | 32,878 | 23 | 65,756 |
Tags: implementation, math
Correct Solution:
```
from sys import stdin
input=stdin.readline
n = int(input())
matrix = []
diagOnes = 0
for i in range(n):
row = input().split()
if row[i] == '1':
diagOnes += 1
matrix.append(row)
diagOnes%=2
ans=[]
q=int(input())
for _ in range(q):
x=input().split()
if x[0]=="1" or x[0]=="2":
diagOnes=1-diagOnes
else:
ans.append(str(diagOnes))
print("".join(ans))
``` | output | 1 | 32,878 | 23 | 65,757 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.
The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.
Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A:
<image>
The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.
However, there is much more to the homework. Chris has to process q queries; each query can be one of the following:
1. given a row index i, flip all the values in the i-th row in A;
2. given a column index i, flip all the values in the i-th column in A;
3. find the unusual square of A.
To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.
Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
Input
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A.
The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following:
* 1 i — flip the values of the i-th row;
* 2 i — flip the values of the i-th column;
* 3 — output the unusual square of A.
Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Output
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
Examples
Input
3
1 1 1
0 1 1
1 0 0
12
3
2 3
3
2 2
2 2
1 3
3
3
1 2
2 1
1 1
3
Output
01001 | instruction | 0 | 32,879 | 23 | 65,758 |
Tags: implementation, math
Correct Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
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 value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
#vsInput()
n=Int()
ans=0
for i in range(n):
a=array()
ans+=a[i]
#print(ans)
for _ in range(Int()):
s=input()
if(s=='3'):
print(ans%2,end="")
else:
t,c=map(int,s.split())
ans+=1
``` | output | 1 | 32,879 | 23 | 65,759 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.
The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.
Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A:
<image>
The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.
However, there is much more to the homework. Chris has to process q queries; each query can be one of the following:
1. given a row index i, flip all the values in the i-th row in A;
2. given a column index i, flip all the values in the i-th column in A;
3. find the unusual square of A.
To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.
Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
Input
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A.
The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following:
* 1 i — flip the values of the i-th row;
* 2 i — flip the values of the i-th column;
* 3 — output the unusual square of A.
Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Output
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
Examples
Input
3
1 1 1
0 1 1
1 0 0
12
3
2 3
3
2 2
2 2
1 3
3
3
1 2
2 1
1 1
3
Output
01001 | instruction | 0 | 32,880 | 23 | 65,760 |
Tags: implementation, math
Correct Solution:
```
def main():
from sys import stdin
from operator import xor
from functools import reduce
x, res = reduce(xor, (input()[i] == '1' for i in range(0, int(input()) * 2, 2))), []
input()
for s in stdin.read().splitlines():
if s == '3':
res.append("01"[x])
else:
x ^= True
print(''.join(res))
if __name__ == "__main__":
main()
``` | output | 1 | 32,880 | 23 | 65,761 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.
The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.
Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A:
<image>
The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.
However, there is much more to the homework. Chris has to process q queries; each query can be one of the following:
1. given a row index i, flip all the values in the i-th row in A;
2. given a column index i, flip all the values in the i-th column in A;
3. find the unusual square of A.
To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.
Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
Input
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A.
The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following:
* 1 i — flip the values of the i-th row;
* 2 i — flip the values of the i-th column;
* 3 — output the unusual square of A.
Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Output
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
Examples
Input
3
1 1 1
0 1 1
1 0 0
12
3
2 3
3
2 2
2 2
1 3
3
3
1 2
2 1
1 1
3
Output
01001 | instruction | 0 | 32,881 | 23 | 65,762 |
Tags: implementation, math
Correct Solution:
```
import sys
input=sys.stdin.readline
n=int(input())
a=[list(map(int,input().split())) for i in range(n)]
s=0
for i in range(n):
for j in range(n):
s+=a[i][j]*a[j][i]
s%=2
ans=[]
q=int(input())
for _ in range(q):
x=input().split()
if x[0]=="1" or x[0]=="2":
s=1-s
else:
ans.append(str(s))
print("".join(ans))
``` | output | 1 | 32,881 | 23 | 65,763 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.
The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.
Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A:
<image>
The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.
However, there is much more to the homework. Chris has to process q queries; each query can be one of the following:
1. given a row index i, flip all the values in the i-th row in A;
2. given a column index i, flip all the values in the i-th column in A;
3. find the unusual square of A.
To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.
Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
Input
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A.
The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following:
* 1 i — flip the values of the i-th row;
* 2 i — flip the values of the i-th column;
* 3 — output the unusual square of A.
Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Output
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
Examples
Input
3
1 1 1
0 1 1
1 0 0
12
3
2 3
3
2 2
2 2
1 3
3
3
1 2
2 1
1 1
3
Output
01001 | instruction | 0 | 32,882 | 23 | 65,764 |
Tags: implementation, math
Correct Solution:
```
from sys import stdin
input = stdin.readline
n = int(input())
lis=list(list(map(int, input().split())) for _ in range(n))
u=0
for i in range(n):
for j in range(n):
if i==j:
u^=lis[i][j]
ans =[]
k = int(input())
for i in range(k):
s = input()
if s[0]=='3':
ans.append(str(u))
else:
u^=1
print(''.join(ans))
``` | output | 1 | 32,882 | 23 | 65,765 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.
The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.
Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A:
<image>
The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.
However, there is much more to the homework. Chris has to process q queries; each query can be one of the following:
1. given a row index i, flip all the values in the i-th row in A;
2. given a column index i, flip all the values in the i-th column in A;
3. find the unusual square of A.
To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.
Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
Input
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A.
The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following:
* 1 i — flip the values of the i-th row;
* 2 i — flip the values of the i-th column;
* 3 — output the unusual square of A.
Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Output
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
Examples
Input
3
1 1 1
0 1 1
1 0 0
12
3
2 3
3
2 2
2 2
1 3
3
3
1 2
2 1
1 1
3
Output
01001 | instruction | 0 | 32,883 | 23 | 65,766 |
Tags: implementation, math
Correct Solution:
```
import sys
import math
MAXNUM = math.inf
MINNUM = -1 * math.inf
def getInt():
return int(sys.stdin.readline().rstrip())
def getInts():
return map(int, sys.stdin.readline().rstrip().split(" "))
def getString():
return sys.stdin.readline().rstrip()
def printOutput(ans):
sys.stdout.write("".join(ans) + "\n")
def countOnes(g):
total = 0
for i in range(len(g)):
if g[i][i] == 1:
total += 1
total = total % 2
return total
def solve(g, queries):
total = 0
### Initial Calculation ###
output = []
for i in range(len(g)):
if g[i][i] == 1:
total += 1
total = total & 1
for qType, value in queries:
if qType == 3:
total = total & 1
output.append(str(total))
else:
total = (
total + 1
) # flip middle bit, others don't matter, and it doesn't matter where
return output
def readinput():
k = getInt()
total = 0
for i in range(k):
string = getString()
if string[2 * i] == "1":
total += 1
total = total & 1
queries = getInt()
output = []
for query in sys.stdin.readlines():
q = query.rstrip()
if len(q) == 1: # print
total = total & 1
output.append(str(total))
else:
total += 1
printOutput(output)
readinput()
``` | output | 1 | 32,883 | 23 | 65,767 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.
The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.
Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A:
<image>
The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.
However, there is much more to the homework. Chris has to process q queries; each query can be one of the following:
1. given a row index i, flip all the values in the i-th row in A;
2. given a column index i, flip all the values in the i-th column in A;
3. find the unusual square of A.
To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.
Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
Input
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A.
The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following:
* 1 i — flip the values of the i-th row;
* 2 i — flip the values of the i-th column;
* 3 — output the unusual square of A.
Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Output
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
Examples
Input
3
1 1 1
0 1 1
1 0 0
12
3
2 3
3
2 2
2 2
1 3
3
3
1 2
2 1
1 1
3
Output
01001 | instruction | 0 | 32,884 | 23 | 65,768 |
Tags: implementation, math
Correct Solution:
```
# from operator import and_, xor
# from functools import reduce
# from itertools import chain
from sys import stdin
input = stdin.readline
n = int(input())
l = list(list(map(int, input().split())) for _ in range(n))
q = int(input())
output = []
ans = 0
# We don't care about anything except for the trace of the matrix
# Why? write the matrix with symbols not 0's and 1's
for i in range(n):
ans ^= l[i][i]
for i in range(q):
command = input()
if command[0] == '3':
output.append(ans)
else:
ans^=1
# Why? first, put in mind that all we care about is the trace of the matrix
# We will flip either the column or the row, we will be facing two possibilities
# either to subtract from the original answer or do addition ... well thanks to GF(2)
# both of the operations are just XORing
print(''.join([*map(str, output)]))
``` | output | 1 | 32,884 | 23 | 65,769 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.
The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.
Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A:
<image>
The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.
However, there is much more to the homework. Chris has to process q queries; each query can be one of the following:
1. given a row index i, flip all the values in the i-th row in A;
2. given a column index i, flip all the values in the i-th column in A;
3. find the unusual square of A.
To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.
Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
Input
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A.
The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following:
* 1 i — flip the values of the i-th row;
* 2 i — flip the values of the i-th column;
* 3 — output the unusual square of A.
Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Output
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
Examples
Input
3
1 1 1
0 1 1
1 0 0
12
3
2 3
3
2 2
2 2
1 3
3
3
1 2
2 1
1 1
3
Output
01001
Submitted Solution:
```
from sys import stdin
input = stdin.readline
n = int(input())
lis=list(list(map(int, input().split())) for _ in range(n))
val=0
for i in range(n):
tmp=0
for j in range(n):
tmp+=lis[i][j]*lis[j][i]
val+=tmp%2
val = val%2
q = int(input())
ans=[]
for i in range(q):
ss = input()
if ss[0]=='3':
ans.append(str(val))
else:
val=val^1
print(''.join(ans))
``` | instruction | 0 | 32,885 | 23 | 65,770 |
Yes | output | 1 | 32,885 | 23 | 65,771 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.
The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.
Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A:
<image>
The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.
However, there is much more to the homework. Chris has to process q queries; each query can be one of the following:
1. given a row index i, flip all the values in the i-th row in A;
2. given a column index i, flip all the values in the i-th column in A;
3. find the unusual square of A.
To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.
Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
Input
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A.
The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following:
* 1 i — flip the values of the i-th row;
* 2 i — flip the values of the i-th column;
* 3 — output the unusual square of A.
Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Output
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
Examples
Input
3
1 1 1
0 1 1
1 0 0
12
3
2 3
3
2 2
2 2
1 3
3
3
1 2
2 1
1 1
3
Output
01001
Submitted Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
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 value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
#vsInput()
n=Int()
ans=0
for i in range(n):
a=array()
ans+=sum(a)
for _ in range(Int()):
s=input()
if(s=='3'):
print(ans%2,end="")
else:
t,c=map(int,s.split())
ans+=n
``` | instruction | 0 | 32,886 | 23 | 65,772 |
No | output | 1 | 32,886 | 23 | 65,773 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.
The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.
Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A:
<image>
The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.
However, there is much more to the homework. Chris has to process q queries; each query can be one of the following:
1. given a row index i, flip all the values in the i-th row in A;
2. given a column index i, flip all the values in the i-th column in A;
3. find the unusual square of A.
To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.
Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
Input
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A.
The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following:
* 1 i — flip the values of the i-th row;
* 2 i — flip the values of the i-th column;
* 3 — output the unusual square of A.
Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Output
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
Examples
Input
3
1 1 1
0 1 1
1 0 0
12
3
2 3
3
2 2
2 2
1 3
3
3
1 2
2 1
1 1
3
Output
01001
Submitted Solution:
```
from sys import stdin
input=stdin.readline
n = int(input())
matrix = [list(input().replace(' ','')) for _ in range(n)]
countOneOne = 0
countMatrix = [0] * n
for i in range(n):
countMatrix[i] = [0] * 4
for i in range(n):
for j in range(n):
val = matrix[i][j] + matrix[j][i]
if val == '11':
countMatrix[i][0] += 1
countOneOne += 1
elif val == '10':
countMatrix[i][1] += 1
elif val == '01':
countMatrix[i][2] += 1
else:
countMatrix[i][3] += 1
q = int(input())
result = ''
for _ in range(q):
a = input().rstrip()
if a == '3':
result += '0' if countOneOne % 2 == 0 else '1'
else:
command, index = a.split()
index = int(index) - 1
if command == '1':
if matrix[i][i] == '1':
countMatrix[index][3] += 1
countMatrix[index][0] -= 1
countOneOne -= 1
matrix[i][i] = '0'
else:
countMatrix[index][3] -= 1
countMatrix[index][0] += 1
countOneOne += 1
matrix[i][i] = '1'
countOneOne = countOneOne - countMatrix[index][0] + countMatrix[index][2]
countMatrix[index][0], countMatrix[index][2] = countMatrix[index][2], countMatrix[index][0]
countMatrix[index][1], countMatrix[index][3] = countMatrix[index][3], countMatrix[index][1]
else:
if matrix[i][i] == '1':
countMatrix[index][3] += 1
countMatrix[index][0] -= 1
countOneOne -= 1
matrix[i][i] = '0'
else:
countMatrix[index][3] -= 1
countMatrix[index][0] += 1
countOneOne += 1
matrix[i][i] = '1'
countOneOne = countOneOne - countMatrix[index][0] + countMatrix[index][1]
countMatrix[index][0], countMatrix[index][1] = countMatrix[index][1], countMatrix[index][0]
countMatrix[index][2], countMatrix[index][3] = countMatrix[index][3], countMatrix[index][2]
print(result)
``` | instruction | 0 | 32,887 | 23 | 65,774 |
No | output | 1 | 32,887 | 23 | 65,775 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.
The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.
Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A:
<image>
The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.
However, there is much more to the homework. Chris has to process q queries; each query can be one of the following:
1. given a row index i, flip all the values in the i-th row in A;
2. given a column index i, flip all the values in the i-th column in A;
3. find the unusual square of A.
To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.
Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
Input
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A.
The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following:
* 1 i — flip the values of the i-th row;
* 2 i — flip the values of the i-th column;
* 3 — output the unusual square of A.
Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Output
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
Examples
Input
3
1 1 1
0 1 1
1 0 0
12
3
2 3
3
2 2
2 2
1 3
3
3
1 2
2 1
1 1
3
Output
01001
Submitted Solution:
```
def main():
from sys import stdin
from operator import xor
from functools import reduce
x, res = reduce(xor, (input()[i] == '1' for i in range(0, int(input()) * 2, 2))), []
for s in stdin.read().splitlines():
if s == '3':
res.append("01"[x])
else:
x ^= True
print(''.join(res))
if __name__ == "__main__":
main()
``` | instruction | 0 | 32,888 | 23 | 65,776 |
No | output | 1 | 32,888 | 23 | 65,777 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.
The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.
Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A:
<image>
The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.
However, there is much more to the homework. Chris has to process q queries; each query can be one of the following:
1. given a row index i, flip all the values in the i-th row in A;
2. given a column index i, flip all the values in the i-th column in A;
3. find the unusual square of A.
To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.
Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?
Input
The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A.
The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following:
* 1 i — flip the values of the i-th row;
* 2 i — flip the values of the i-th column;
* 3 — output the unusual square of A.
Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Output
Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.
Examples
Input
3
1 1 1
0 1 1
1 0 0
12
3
2 3
3
2 2
2 2
1 3
3
3
1 2
2 1
1 1
3
Output
01001
Submitted Solution:
```
from sys import stdin
input=stdin.readline
n = int(input())
matrix = [input().replace(' ','') for _ in range(n)]
countOneOne = 0
countMatrix = [0] * n
for i in range(n):
countMatrix[i] = [0] * 4
for i in range(n):
for j in range(n):
val = matrix[i][j] + matrix[j][i]
if val == '11':
countMatrix[i][0] += 1
countOneOne += 1
elif val == '10':
countMatrix[i][1] += 1
elif val == '01':
countMatrix[i][2] += 1
else:
countMatrix[i][3] += 1
q = int(input())
result = ''
for _ in range(q):
a = input().rstrip()
if a == '3':
result += '0' if countOneOne % 2 == 0 else '1'
else:
command, index = a.split()
index = int(index) - 1
if command == '2':
countOneOne = countOneOne - countMatrix[index][0] + countMatrix[index][2]
countMatrix[index][0], countMatrix[index][2] = countMatrix[index][2], countMatrix[index][0]
countMatrix[index][1], countMatrix[index][3] = countMatrix[index][3], countMatrix[index][1]
else:
countOneOne = countOneOne - countMatrix[index][0] + countMatrix[index][1]
countMatrix[index][0], countMatrix[index][1] = countMatrix[index][1], countMatrix[index][0]
countMatrix[index][2], countMatrix[index][3] = countMatrix[index][3], countMatrix[index][2]
print(result)
``` | instruction | 0 | 32,889 | 23 | 65,778 |
No | output | 1 | 32,889 | 23 | 65,779 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In a two-dimensional plane, we have a rectangle R whose vertices are (0,0), (W,0), (0,H), and (W,H), where W and H are positive integers. Here, find the number of triangles \Delta in the plane that satisfy all of the following conditions:
* Each vertex of \Delta is a grid point, that is, has integer x- and y-coordinates.
* \Delta and R shares no vertex.
* Each vertex of \Delta lies on the perimeter of R, and all the vertices belong to different sides of R.
* \Delta contains at most K grid points strictly within itself (excluding its perimeter and vertices).
Constraints
* 1 \leq W \leq 10^5
* 1 \leq H \leq 10^5
* 0 \leq K \leq 10^5
Input
Input is given from Standard Input in the following format:
W H K
Output
Print the answer.
Examples
Input
2 3 1
Output
12
Input
5 4 5
Output
132
Input
100 100 1000
Output
461316
Submitted Solution:
```
import sys
def count_h(y1, y2, w):
n = y1 * (w + 1)
if y2 == y1:
n += (w + 1)
else:
n += int((y2 - y1 + 1) * (w + 1) / 2 + 1)
return n - 2
def count_xy(x, y):
return int(((x+1) * (y+1) + 1) / 2) + 1 - 2
def test_count():
assert count_xy(1, 1) == 1
assert count_xy(1, 2) == 2
assert count_xy(2, 2) == 4
assert count_h(0, 0, 3) == 2
assert count_h(0, 1, 3) == 3
assert count_h(0, 2, 3) == 5
assert (3*4) - count_xy(1, 1) - count_xy(1, 1) - count_h(2, 2, 2) - 3 == 0
def count_k(w, h, k):
result = 0
for x1 in range(1, w+1):
count = 0
for y1 in range(1, h+1):
for y2 in range(y1, h+1):
dot = (1+w) * (1+h) - count_xy(x1, y1) - count_xy(w-x1, y2) - count_h(h-y1, h-y2, w) - 3
if dot == k:
#print([x1, 0], [0, y1], [w, y2], "match")
count = count + 1 if y1 == y2 else count + 2
else:
#print([x1, 0], [0, y1], [w, y2], "not", dot)
assert dot >= 0
for x2 in range(x1, w+1):
dot = (1+w) * (1+h) - count_xy(x1, y1) - count_xy(x2, h-y2) - count_h(w-x1, w-x2, h) - 3
if dot == k:
#print([x1, 0], [0, y1], [w, y2], "match")
count = count + 1 if x1 == x2 else count + 2
else:
#print([x1, 0], [0, y1], [w, y2], "not", dot)
assert dot >= 0
if w/2 != x1:
count *= 2
result += count
return result
w, h, k = map(int, sys.stdin.readline().split())
print(count_k(w, h, k))
``` | instruction | 0 | 33,129 | 23 | 66,258 |
No | output | 1 | 33,129 | 23 | 66,259 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In a two-dimensional plane, we have a rectangle R whose vertices are (0,0), (W,0), (0,H), and (W,H), where W and H are positive integers. Here, find the number of triangles \Delta in the plane that satisfy all of the following conditions:
* Each vertex of \Delta is a grid point, that is, has integer x- and y-coordinates.
* \Delta and R shares no vertex.
* Each vertex of \Delta lies on the perimeter of R, and all the vertices belong to different sides of R.
* \Delta contains at most K grid points strictly within itself (excluding its perimeter and vertices).
Constraints
* 1 \leq W \leq 10^5
* 1 \leq H \leq 10^5
* 0 \leq K \leq 10^5
Input
Input is given from Standard Input in the following format:
W H K
Output
Print the answer.
Examples
Input
2 3 1
Output
12
Input
5 4 5
Output
132
Input
100 100 1000
Output
461316
Submitted Solution:
```
w, h, k = map(int, input().split())
count =0
for a in range(1,w,1):
for b in range(1,h,1):
for c in range(1,h,1):
pc =0
for x in range(1,h,1):
for y in range(1,w,1):
if y<a+a/c*x and y>a-a/b*x and x< (c-b)/w*y+b:
pc =pc+1
if pc <=k:
count =count +2
w2 = w
w =h
h=w2
for a in range(1,w,1):
for b in range(1,h,1):
for c in range(1,h,1):
pc =0
for x in range(1,h,1):
for y in range(1,w,1):
if y<a+a/c*x and y>a-a/b*x and x< (c-b)/w*y+b:
pc =pc+1
if pc <=k:
count =count +2
print(count)
``` | instruction | 0 | 33,130 | 23 | 66,260 |
No | output | 1 | 33,130 | 23 | 66,261 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In a two-dimensional plane, we have a rectangle R whose vertices are (0,0), (W,0), (0,H), and (W,H), where W and H are positive integers. Here, find the number of triangles \Delta in the plane that satisfy all of the following conditions:
* Each vertex of \Delta is a grid point, that is, has integer x- and y-coordinates.
* \Delta and R shares no vertex.
* Each vertex of \Delta lies on the perimeter of R, and all the vertices belong to different sides of R.
* \Delta contains at most K grid points strictly within itself (excluding its perimeter and vertices).
Constraints
* 1 \leq W \leq 10^5
* 1 \leq H \leq 10^5
* 0 \leq K \leq 10^5
Input
Input is given from Standard Input in the following format:
W H K
Output
Print the answer.
Examples
Input
2 3 1
Output
12
Input
5 4 5
Output
132
Input
100 100 1000
Output
461316
Submitted Solution:
```
1
``` | instruction | 0 | 33,131 | 23 | 66,262 |
No | output | 1 | 33,131 | 23 | 66,263 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In a two-dimensional plane, we have a rectangle R whose vertices are (0,0), (W,0), (0,H), and (W,H), where W and H are positive integers. Here, find the number of triangles \Delta in the plane that satisfy all of the following conditions:
* Each vertex of \Delta is a grid point, that is, has integer x- and y-coordinates.
* \Delta and R shares no vertex.
* Each vertex of \Delta lies on the perimeter of R, and all the vertices belong to different sides of R.
* \Delta contains at most K grid points strictly within itself (excluding its perimeter and vertices).
Constraints
* 1 \leq W \leq 10^5
* 1 \leq H \leq 10^5
* 0 \leq K \leq 10^5
Input
Input is given from Standard Input in the following format:
W H K
Output
Print the answer.
Examples
Input
2 3 1
Output
12
Input
5 4 5
Output
132
Input
100 100 1000
Output
461316
Submitted Solution:
```
W, H, K = list(map(int,input().split()))
counter = int(0)
triangle_counter = 0
if (W <= 2 or H == 1):
print(0)
else:
for i in range(1, H):
for j in range(1, W):
for k in range(j, W):
counter = 0
if (j == k): # 三角形の1辺がy軸と垂直
for l in range(1,j):
counter += int((H-float(i))/float(k)*l+float(i)/float(j)*l)
if(counter <= K):
triangle_counter +=2
else: # j < k
for m in range(1,j):
counter += int((H-float(i))/float(k)*m+float(i)/float(j)*m)
for n in range (j, W):
counter += int((H-float(i))/float(k)*n+i-H*n/(float(k)-float(j)-H*j/(1+j)))
if(counter == K):
triangle_counter += 4
print(triangle_counter)
``` | instruction | 0 | 33,132 | 23 | 66,264 |
No | output | 1 | 33,132 | 23 | 66,265 |
Provide a correct Python 3 solution for this coding contest problem.
You received a card with an integer $S$ and a multiplication table of infinite size. All the elements in the table are integers, and an integer at the $i$-th row from the top and the $j$-th column from the left is $A_{i,j} = i \times j$ ($i,j \geq 1$). The table has infinite size, i.e., the number of the rows and the number of the columns are infinite.
You love rectangular regions of the table in which the sum of numbers is $S$. Your task is to count the number of integer tuples $(a, b, c, d)$ that satisfies $1 \leq a \leq b, 1 \leq c \leq d$ and $\sum_{i=a}^b \sum_{j=c}^d A_{i,j} = S$.
Input
The input consists of a single test case of the following form.
$S$
The first line consists of one integer $S$ ($1 \leq S \leq 10^5$), representing the summation of rectangular regions you have to find.
Output
Print the number of rectangular regions whose summation is $S$ in one line.
Examples
Input
25
Output
10
Input
1
Output
1
Input
5
Output
4
Input
83160
Output
5120 | instruction | 0 | 33,288 | 23 | 66,576 |
"Correct Solution:
```
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
return [I() for i in range(n)]
def LIR(n):
return [LI() for i in range(n)]
def SR(n):
return [S() for i in range(n)]
def LSR(n):
return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
mod = 1000000007
def solve():
def sum(a,b):
return ((b+a)*(b-a+1)) >> 1
def fact(n):
if n < 4:
return [1,n]
res = [1]
i = 2
while i**2 <= n:
if n%i == 0:
res.append(i)
m = n//i
if i != m:
res.append(m)
i += 1
res.append(n)
return res
s = I()
if s == 1:
print(1)
return
lis = fact(s)
f = defaultdict(lambda : 0)
p = defaultdict(lambda : 1)
lis.sort()
for k in lis:
for a in range(1,k+1):
b = k-a
if a <= b:
if p[(a,b)]:
f[sum(a,b)] += 1
p[(a,b)] = 0
for a in range(1,s+1):
b = k+a-1
if p[(a,b)]:
s_ = sum(a,b)
if s_ > s:
break
f[s_] += 1
p[(a,b)] = 0
ans = 0
for k in lis:
ans += f[k]*f[s//k]
print(ans)
return
#Solve
if __name__ == "__main__":
solve()
``` | output | 1 | 33,288 | 23 | 66,577 |
Provide a correct Python 3 solution for this coding contest problem.
For given two segments s1 and s2, print the distance between them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3.
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xpi, ypi ≤ 10000
* p0 ≠ p1 and p2 ≠ p3.
Input
The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth query
Each query consists of integer coordinates of end points of s1 and s2 in the following format:
xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3
Output
For each query, print the distance. The output values should be in a decimal fraction with an error less than 0.00000001.
Example
Input
3
0 0 1 0 0 1 1 1
0 0 1 0 2 1 1 2
-1 0 1 0 0 1 0 -1
Output
1.0000000000
1.4142135624
0.0000000000 | instruction | 0 | 33,289 | 23 | 66,578 |
"Correct Solution:
```
EPS = 1e-4
#点と線分の距離
def PointSegmentDistance(point, begin, end):
point, begin, end = point-begin, 0, end-begin
point = (point / end) * abs(end)
end = abs(end)
if -EPS <= point.real <= abs(end):
return abs(point.imag)
else:
return min(abs(point), abs(point - end))
#外積
def OuterProduct(one, two):
tmp = one.conjugate() * two
return tmp.imag
#内積
def InnerProduct(one, two):
tmp = one.conjugate() * two
return tmp.real
#点が線分上にあるか
def IsOnSegment(point, begin, end):
if abs(OuterProduct(begin-point, end-point)) <= EPS and InnerProduct(begin-point, end-point) <= EPS:
return True
else:
return False
#3点が反時計回りか
#一直線上のときの例外処理できていない→とりあえずF
def CCW(p, q, r):
one, two = q-p, r-q
if OuterProduct(one, two) > -EPS:
return True
else:
return False
#線分どうし交叉
def Intersect_SS(b1, e1, b2, e2):
if IsOnSegment(b1, b2, e2) or IsOnSegment(e1, b2, e2) or IsOnSegment(b2, b1, e1) or IsOnSegment(e2, b1, e1):
return True
elif (CCW(b1, e1, b2) != CCW(b1, e1, e2)) and (CCW(b2, e2, b1) != CCW(b2, e2, e1)):
return True
else:
return False
#点と線分の距離
def SegmentSegmentDistance(a, b, c, d):
if Intersect_SS(a, b, c, d):
return 0
else:
return min(PointSegmentDistance(a, c, d), PointSegmentDistance(b, c, d), PointSegmentDistance(c, a, b), PointSegmentDistance(d, a, b))
n = int(input())
for _ in range(n):
pp = list(map(int, input().split()))
p = [complex(pp[i], pp[i+1]) for i in range(0, 8, 2)]
print(SegmentSegmentDistance(p[0], p[1], p[2], p[3]))
``` | output | 1 | 33,289 | 23 | 66,579 |
Provide a correct Python 3 solution for this coding contest problem.
For given two segments s1 and s2, print the distance between them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3.
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xpi, ypi ≤ 10000
* p0 ≠ p1 and p2 ≠ p3.
Input
The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth query
Each query consists of integer coordinates of end points of s1 and s2 in the following format:
xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3
Output
For each query, print the distance. The output values should be in a decimal fraction with an error less than 0.00000001.
Example
Input
3
0 0 1 0 0 1 1 1
0 0 1 0 2 1 1 2
-1 0 1 0 0 1 0 -1
Output
1.0000000000
1.4142135624
0.0000000000 | instruction | 0 | 33,290 | 23 | 66,580 |
"Correct Solution:
```
import math
EPS = 1e-10
def equals(a, b):
return abs(a - b) < EPS
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, p):
return Point(self.x + p.x, self.y + p.y)
def __sub__(self, p):
return Point(self.x - p.x, self.y - p.y)
def __mul__(self, a):
return Point(self.x * a, self.y * a)
def __rmul__(self, a):
return self * a
def __truediv__(self, a):
return Point(self.x / a, self.y / a)
def norm(self):
return self.x * self.x + self.y * self.y
def abs(self):
return math.sqrt(self.norm())
def __lt__(self, p):
if self.x != p.x:
return self. x < p.x
else:
return self.y < p.y
def __eq__(self, p):
return equals(self.x, p.x) and equals(self.y, p.y)
class Segment:
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
def dot(a, b):
return a.x * b.x + a.y * b.y
def cross(a, b):
return a.x * b.y - a.y * b.x
def ccw(p0, p1, p2):
COUNTER_CLOCKWISE = 1
CLOCKWISE = -1
ONLINE_BACK = 2
ONLINE_FRONT = -2
ON_SEGMENT = 0
a = p1 - p0
b = p2 - p0
if cross(a, b) > EPS:
return COUNTER_CLOCKWISE
if cross(a, b) < -EPS:
return CLOCKWISE
if dot(a, b) < -EPS:
return ONLINE_BACK
if a.norm() < b.norm():
return ONLINE_FRONT
return ON_SEGMENT
def intersect(s1, s2):
p1 = s1.p1
p2 = s1.p2
p3 = s2.p1
p4 = s2.p2
return (ccw(p1, p2, p3) * ccw(p1, p2, p4) <= 0 and
ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0)
def getDistanceLP(l, p):
v = l.p2 - l.p1
return abs(cross(v, p - l.p1) / v.abs())
def getDistanceSP(s, p):
if dot(s.p2 - s.p1, p - s.p1) < 0:
v = p - s.p1
return v.abs()
if dot(s.p1 - s.p2, p - s.p2) < 0:
v = p - s.p2
return v.abs()
return getDistanceLP(s, p)
def getDistance(s1, s2):
if intersect(s1, s2):
return 0
return min(
getDistanceSP(s1, s2.p1),
getDistanceSP(s1, s2.p2),
getDistanceSP(s2, s1.p1),
getDistanceSP(s2, s1.p2)
)
if __name__ == '__main__':
q = int(input())
ans = []
for i in range(q):
x0, y0, x1, y1, x2, y2, x3, y3 = [int(v) for v in input().split()]
s1 = Segment(Point(x0, y0), Point(x1, y1))
s2 = Segment(Point(x2, y2), Point(x3, y3))
ans.append(getDistance(s1, s2))
for v in ans:
print('{0:.10f}'.format(v))
``` | output | 1 | 33,290 | 23 | 66,581 |
Provide a correct Python 3 solution for this coding contest problem.
For given two segments s1 and s2, print the distance between them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3.
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xpi, ypi ≤ 10000
* p0 ≠ p1 and p2 ≠ p3.
Input
The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth query
Each query consists of integer coordinates of end points of s1 and s2 in the following format:
xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3
Output
For each query, print the distance. The output values should be in a decimal fraction with an error less than 0.00000001.
Example
Input
3
0 0 1 0 0 1 1 1
0 0 1 0 2 1 1 2
-1 0 1 0 0 1 0 -1
Output
1.0000000000
1.4142135624
0.0000000000 | instruction | 0 | 33,291 | 23 | 66,582 |
"Correct Solution:
```
class Point:
def __init__(self, x , y):
self.x = x
self.y = y
def __sub__(self, p):
x_sub = self.x - p.x
y_sub = self.y - p.y
return Point(x_sub, y_sub)
class Vector:
def __init__(self, p):
self.x = p.x
self.y = p.y
self.norm = (p.x ** 2 + p.y ** 2) ** 0.5
def cross(v1, v2):
return v1.x * v2.y - v1.y * v2.x
def dot(v1, v2):
return v1.x * v2.x + v1.y * v2.y
def ccw(p0, p1, p2):
a = Vector(p1 - p0)
b = Vector(p2 - p0)
cross_ab = cross(a, b)
if cross_ab > 0:
return 1
elif cross_ab < 0:
return -1
elif dot(a, b) < 0:
return 1
elif a.norm < b.norm:
return -1
else:
return 0
def intersect(p1, p2, p3, p4):
if (ccw(p1, p2, p3) * ccw(p1, p2, p4) <= 0) and \
(ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0):
return True
else:
return False
def getDistanceSP(sp1, sp2, p):
a = Vector(sp2 - sp1)
b = Vector(p - sp1)
if dot(a, b) < 0:
return b.norm
c = Vector(sp1 - sp2)
d = Vector(p - sp2)
if dot(c, d) < 0:
return d.norm
return abs(cross(a, b) / a.norm)
def getDistance(p1, p2, p3, p4):
if intersect(p1, p2, p3, p4):
print("0.00000000")
else:
d = min(getDistanceSP(p1, p2, p3), getDistanceSP(p1, p2, p4),
getDistanceSP(p3, p4, p1), getDistanceSP(p3, p4, p2))
print("{0:.10f}".format(d))
import sys
file_input = sys.stdin
sq = file_input.readline()
for line in file_input:
x_p0, y_p0, x_p1, y_p1, x_p2, y_p2, x_p3, y_p3 = map(int, line.split())
p0 = Point(x_p0, y_p0)
p1 = Point(x_p1, y_p1)
p2 = Point(x_p2, y_p2)
p3 = Point(x_p3, y_p3)
getDistance(p0, p1, p2, p3)
``` | output | 1 | 33,291 | 23 | 66,583 |
Provide a correct Python 3 solution for this coding contest problem.
For given two segments s1 and s2, print the distance between them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3.
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xpi, ypi ≤ 10000
* p0 ≠ p1 and p2 ≠ p3.
Input
The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth query
Each query consists of integer coordinates of end points of s1 and s2 in the following format:
xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3
Output
For each query, print the distance. The output values should be in a decimal fraction with an error less than 0.00000001.
Example
Input
3
0 0 1 0 0 1 1 1
0 0 1 0 2 1 1 2
-1 0 1 0 0 1 0 -1
Output
1.0000000000
1.4142135624
0.0000000000 | instruction | 0 | 33,292 | 23 | 66,584 |
"Correct Solution:
```
#!/usr/bin/env python3
# CGL_2_D: Segments/Lines - Distance
from math import sqrt
class Segment:
def __init__(self, p0, p1):
self.end_points = (p0, p1)
def another(self, p):
if p == self.end_points[0]:
return self.end_points[1]
else:
return self.end_points[0]
def distance(self, other):
def _distance(p, seg):
p0 = seg._closest_point(p)
p1 = seg.another(p0)
x, y = p
x0, y0 = p0
x1, y1 = p1
vp = (x-x0, y-y0)
vseg = (x1-x0, y1-y0)
if dot(vp, vseg) <= 0:
return length(vp)
else:
x, y = vp
return length(projection(vp, orthogonal(vseg)))
if self.intersect(other):
return 0.0
dists = []
for p0 in self.end_points:
dists.append(_distance(p0, other))
for p1 in other.end_points:
dists.append(_distance(p1, self))
return min(dists)
def intersect(self, other):
p0, p1 = self.end_points
p2, p3 = other.end_points
if convex(p0, p2, p1, p3):
return True
else:
if (p0 in other or p1 in other
or p2 in self or p3 in self):
return True
return False
def _closest_point(self, p):
p0, p1 = self.end_points
x, y = p
x0, y0 = p0
x1, y1 = p1
if length((x0-x, y0-y)) < length((x1-x, y1-y)):
return p0
else:
return p1
def __contains__(self, p):
p0, p1 = self.end_points
x0, y0 = p0
x1, y1 = p1
x, y = p
v = (x1-x0, y1-y0)
v0 = (x-x0, y-y0)
v1 = (x-x1, y-y1)
if dot(orthogonal(v0), v1) == 0:
if abs(length(v0) + length(v1) - length(v)) < 1e-10:
return True
return False
def dot(v1, v2):
x1, y1 = v1
x2, y2 = v2
return x1 * x2 + y1 * y2
def orthogonal(v):
x, y = v
return -y, x
def length(v):
x, y = v
return sqrt(x**2 + y**2)
def projection(p, v):
x, y = v
r = dot(p, v) / dot(v, v)
return (x*r, y*r)
def convex(p0, p1, p2, p3):
ret = []
for pa, pb, pc in zip([p0, p1, p2, p3],
[p1, p2, p3, p0],
[p2, p3, p0, p1]):
xa, ya = pa
xb, yb = pb
xc, yc = pc
v1 = (xb - xa, yb - ya)
v2 = (xc - xb, yc - yb)
ret.append(dot(orthogonal(v1), v2))
return all([d > 0 for d in ret]) or all([d < 0 for d in ret])
def run():
q = int(input())
for _ in range(q):
x0, y0, x1, y1, x2, y2, x3, y3 = [int(i) for i in input().split()]
s0 = Segment((x0, y0), (x1, y1))
s1 = Segment((x2, y2), (x3, y3))
print("{:.10f}".format(s0.distance(s1)))
if __name__ == '__main__':
run()
``` | output | 1 | 33,292 | 23 | 66,585 |
Provide a correct Python 3 solution for this coding contest problem.
For given two segments s1 and s2, print the distance between them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3.
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xpi, ypi ≤ 10000
* p0 ≠ p1 and p2 ≠ p3.
Input
The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth query
Each query consists of integer coordinates of end points of s1 and s2 in the following format:
xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3
Output
For each query, print the distance. The output values should be in a decimal fraction with an error less than 0.00000001.
Example
Input
3
0 0 1 0 0 1 1 1
0 0 1 0 2 1 1 2
-1 0 1 0 0 1 0 -1
Output
1.0000000000
1.4142135624
0.0000000000 | instruction | 0 | 33,293 | 23 | 66,586 |
"Correct Solution:
```
EPS = 10**(-9)
def is_equal(a,b):
return abs(a-b) < EPS
def norm(v,i=2):
import math
ret = 0
n = len(v)
for j in range(n):
ret += abs(v[j])**i
return math.pow(ret,1/i)
class Vector(list):
"""
ベクトルクラス
対応演算子
+ : ベクトル和
- : ベクトル差
* : スカラー倍、または内積
/ : スカラー除法
** : 外積
+= : ベクトル和
-= : ベクトル差
*= : スカラー倍
/= : スカラー除法
メソッド
self.norm(i) : L{i}ノルムを計算
"""
def __add__(self,other):
n = len(self)
ret = [0]*n
for i in range(n):
ret[i] = super().__getitem__(i) + other.__getitem__(i)
return self.__class__(ret)
def __radd__(self,other):
n = len(self)
ret = [0]*n
for i in range(n):
ret[i] = other.__getitem__(i) + super().__getitem__(i)
return self.__class__(ret)
def __iadd__(self, other):
n = len(self)
for i in range(n):
self[i] += other.__getitem__(i)
return self
def __sub__(self,others):
n = len(self)
ret = [0]*n
for i in range(n):
ret[i] = super().__getitem__(i) - others.__getitem__(i)
return self.__class__(ret)
def __iadd__(self, other):
n = len(self)
for i in range(n):
self[i] -= other.__getitem__(i)
return self
def __rsub__(self,others):
n = len(self)
ret = [0]*n
for i in range(n):
ret[i] = others.__getitem__(i) - super().__getitem__(i)
return self.__class__(ret)
def __mul__(self,other):
n = len(self)
if isinstance(other,list):
ret = 0
for i in range(n):
ret += super().__getitem__(i)*other.__getitem__(i)
return ret
else:
ret = [0]*n
for i in range(n):
ret[i] = super().__getitem__(i)*other
return self.__class__(ret)
def __rmul__(self,other):
n = len(self)
if isinstance(other,list):
ret = 0
for i in range(n):
ret += super().__getitem__(i)*other.__getitem__(i)
return ret
else:
ret = [0]*n
for i in range(n):
ret[i] = super().__getitem__(i)*other
return self.__class__(ret)
def __truediv__(self,other):
"""
ベクトルのスカラー除法
Vector/scalar
"""
n = len(self)
ret = [0]*n
for i in range(n):
ret[i] = super().__getitem__(i)/other
return self.__class__(ret)
def norm(self,i):
"""
L{i}ノルム
self.norm(i)
"""
return norm(self,i)
def __pow__(self,other):
"""
外積
self**other
"""
n = len(self)
ret = [0]*3
x = self[:]
y = other[:]
if n == 2:
x.append(0)
y.append(0)
if n == 2 or n == 3:
for i in range(3):
ret[0],ret[1],ret[2] = x[1]*y[2]-x[2]*y[1],x[2]*y[0]-x[0]*y[2],x[0]*y[1]-x[1]*y[0]
ret = Vector(ret)
if n == 2:
return ret
else:
return ret
class Segment:
"""
線分クラス
"""
def __init__(self,v1,v2):
self.v1 = v1
self.v2 = v2
def length(self):
return norm(self.v1-self.v2)
def get_unit_vec(self):
#方向単位ベクトル
dist = norm(self.v2-self.v1)
if dist != 0:
return (self.v2-self.v1)/dist
else:
return False
def projection(self,vector):
#射影点(線分を直線と見たときの)
unit_vec = self.get_unit_vec()
t = unit_vec*(vector-self.v1)
return self.v1 + t*unit_vec
def is_vertical(self,other):
#線分の直交判定
return is_equal(0,self.get_unit_vec()*other.get_unit_vec())
def is_horizontal(self,other):
#線分の平行判定
return is_equal(0,self.get_unit_vec()**other.get_unit_vec())
def reflection(self,vector):
#反射点(線分を直線と見たときの)
projection = self.projection(vector)
v = projection - vector
return projection + vector
def include(self,vector):
#線分が点を含むか否か
proj = self.projection(vector)
if not is_equal(norm(proj-vector),0):
return False
else:
n = len(self.v1)
f = True
for i in range(n):
f &= ((self.v1[i] <= vector[i] <= self.v2[i]) or (self.v2[i] <= vector[i] <=self.v1[i]))
return f
def distance(self,other):
#点と線分の距離
if isinstance(other,Vector):
proj = self.projection(other)
if self.include(proj):
return norm(proj-other)
else:
ret = []
ret.append(norm(self.v1-other))
ret.append(norm(self.v2-other))
return min(ret)
def ccw(self,vector):
"""
線分に対して点が反時計回りの位置にある(1)か時計回りの位置にある(-1)か線分上にある(0)か
"""
direction = self.v2 - self.v1
v = vector - self.v1
if self.include(vector):
return 0
else:
cross = direction**v
if cross[2] <= 0:
return 1
else:
return -1
def intersect(self,segment):
"""
線分の交差判定
"""
ccw12 = self.ccw(segment.v1)
ccw13 = self.ccw(segment.v2)
ccw20 = segment.ccw(self.v1)
ccw21 = segment.ccw(self.v2)
if ccw12*ccw13*ccw20*ccw21 == 0:
return True
else:
if ccw12*ccw13 < 0 and ccw20*ccw21 < 0:
return True
else:
return False
class Line(Segment):
"""
直線クラス
"""
#直線上に点が存在するか否か
def include(self,vector):
proj = self.projection(vector)
return is_equal(norm(proj-vector),0)
q = int(input())
ps =[[[0] for _ in range(4)] for _ in range(q)]
for i in range(q):
tmp = list(map(int,input().split()))
for j in range(4):
ps[i][j] = Vector(tmp[2*j:2*(j+1)])
for i in range(q):
ans = []
p0,p1,p2,p3 = ps[i]
S1 = Segment(p0,p1)
S2 = Segment(p2,p3)
if S1.intersect(S2):
ans.append(0)
else:
ans.append(S1.distance(p2))
ans.append(S1.distance(p3))
ans.append(S2.distance(p0))
ans.append(S2.distance(p1))
print(min(ans))
``` | output | 1 | 33,293 | 23 | 66,587 |
Provide a correct Python 3 solution for this coding contest problem.
For given two segments s1 and s2, print the distance between them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3.
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xpi, ypi ≤ 10000
* p0 ≠ p1 and p2 ≠ p3.
Input
The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth query
Each query consists of integer coordinates of end points of s1 and s2 in the following format:
xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3
Output
For each query, print the distance. The output values should be in a decimal fraction with an error less than 0.00000001.
Example
Input
3
0 0 1 0 0 1 1 1
0 0 1 0 2 1 1 2
-1 0 1 0 0 1 0 -1
Output
1.0000000000
1.4142135624
0.0000000000 | instruction | 0 | 33,294 | 23 | 66,588 |
"Correct Solution:
```
import sys
from collections import namedtuple
from itertools import starmap
readline = sys.stdin.readline
EPS = 1e-9
class Segment(object):
__slots__ = ('fi', 'se')
def __init__(self, fi, se):
self.fi = fi
self.se = se
def cross(a, b):
return a.real * b.imag - a.imag * b.real
def dot(a, b):
return a.real * b.real + a.imag * b.imag
def norm(base):
return abs(base) ** 2
def project(s, p2):
base = s.fi - s.se
r = dot(p2 - s.fi, base) / norm(base)
return s.fi + base * r
def reflect(s, p):
return p + (project(s, p) - p) * 2.0
def ccw(p1, p2, p3):
a = p2 - p1
b = p3 - p1
if cross(a, b) > EPS: return 1
if cross(a, b) < -EPS: return -1
if dot(a, b) < -EPS: return 2
if norm(a) < norm(b): return -2
return 0
def intersect4(p1, p2, p3, p4):
return (ccw(p1, p2, p3) * ccw(p1, p2, p4) <= 0 and
ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0)
def intersect2(s1, s2):
return intersect4(s1.fi, s1.se, s2.fi, s2.se)
def getDistance(a, b): return abs(a - b)
def getDistanceLP(l, p):
return abs(cross(l.se - l.fi, p - l.fi) / abs(l.se - l.fi))
def getDistanceSP(s, p):
if dot(s.se - s.fi, p - s.fi) < 0.0: return abs(p - s.fi)
if dot(s.fi - s.se, p - s.se) < 0.0: return abs(p - s.se)
return getDistanceLP(s, p)
def getDistances(s1, s2):
if intersect2(s1, s2): return 0.0
return min(getDistanceSP(s1, s2.fi), getDistanceSP(s1, s2.se),
getDistanceSP(s2, s1.fi), getDistanceSP(s2, s1.se))
n = int(readline())
for _ in [0] * n:
li = tuple(map(int, readline().split()))
p0, p1, p2, p3 = (x + y * 1j for x, y in zip(li[::2], li[1::2]))
s1 = Segment(p0, p1)
s2 = Segment(p2, p3)
print("{0:.10f}".format(getDistances(s1, s2)))
``` | output | 1 | 33,294 | 23 | 66,589 |
Provide a correct Python 3 solution for this coding contest problem.
For given two segments s1 and s2, print the distance between them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3.
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xpi, ypi ≤ 10000
* p0 ≠ p1 and p2 ≠ p3.
Input
The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth query
Each query consists of integer coordinates of end points of s1 and s2 in the following format:
xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3
Output
For each query, print the distance. The output values should be in a decimal fraction with an error less than 0.00000001.
Example
Input
3
0 0 1 0 0 1 1 1
0 0 1 0 2 1 1 2
-1 0 1 0 0 1 0 -1
Output
1.0000000000
1.4142135624
0.0000000000 | instruction | 0 | 33,295 | 23 | 66,590 |
"Correct Solution:
```
#! /usr/bin/env python3
from typing import List, Tuple
from math import sqrt
EPS = 1e-10
def float_equal(x: float, y: float) -> bool:
return abs(x - y) < EPS
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 "Point({}, {})".format(self.x, self.y)
def __eq__(self, other: object) -> bool:
if not isinstance(other, Point):
# print("NotImplemented in Point")
return NotImplemented
return float_equal(self.x, other.x) and \
float_equal(self.y, other.y)
def __add__(self, other: 'Point') -> 'Point':
return Point(self.x + other.x, self.y + other.y)
def __sub__(self, other: 'Point') -> 'Point':
return Point(self.x - other.x, self.y - other.y)
def __mul__(self, k: float) -> 'Point':
return Point(self.x * k, self.y * k)
def __rmul__(self, k: float) -> 'Point':
return self * k
def __truediv__(self, k: float) -> 'Point':
return Point(self.x / k, self.y / k)
def __lt__(self, other: 'Point') -> bool:
return self.y < other.y \
if abs(self.x - other.x) < EPS \
else self.x < other.x
def norm(self):
return self.x * self.x + self.y * self.y
def abs(self):
return sqrt(self.norm())
def dot(self, other: 'Point') -> float:
return self.x * other.x + self.y * other.y
def cross(self, other: 'Point') -> float:
return self.x * other.y - self.y * other.x
def is_orthogonal(self, other: 'Point') -> bool:
return float_equal(self.dot(other), 0.0)
def is_parallel(self, other: 'Point') -> bool:
return float_equal(self.cross(other), 0.0)
def distance(self, other: 'Point') -> float:
return Segment(self, other).vector().abs()
def in_side_of(self, seg: 'Segment') -> bool:
return seg.vector().dot(
Segment(seg.p1, self).vector()) >= 0
def in_width_of(self, seg: 'Segment') -> bool:
return \
self.in_side_of(seg) and \
self.in_side_of(seg.reverse())
def distance_to_segment(self, seg: 'Segment') -> float:
if self.in_width_of(seg):
return self.distance(seg.projection(self))
else:
return min(self.distance(seg.p1),
self.distance(seg.p2))
Vector = Point
class Segment:
def __init__(self, p1: Point = None, p2: Point = None) -> None:
self.p1: Point = Point() if p1 is None else p1
self.p2: Point = Point() if p2 is None else p2
def __repr__(self) -> str:
return "Segment({}, {})".format(self.p1, self.p2)
def __eq__(self, other: object) -> bool:
if not isinstance(other, Segment):
# print("NotImplemented in Segment")
return NotImplemented
return self.p1 == other.p1 and self.p2 == other.p2
def vector(self) -> Vector:
return self.p2 - self.p1
def reverse(self) -> 'Segment':
return Segment(self.p2, self.p1)
def is_orthogonal(self, other: 'Segment') -> bool:
return self.vector().is_orthogonal(other.vector())
def is_parallel(self, other: 'Segment') -> bool:
return self.vector().is_parallel(other.vector())
def projection(self, p: Point) -> Point:
v = self.vector()
vp = p - self.p1
return v.dot(vp) / v.norm() * v + self.p1
def reflection(self, p: Point) -> Point:
x = self.projection(p)
return p + 2 * (x - p)
def intersect_ratio(self, other: 'Segment') -> Tuple[float, float]:
a = self.vector()
b = other.vector()
c = self.p1 - other.p1
s = b.cross(c) / a.cross(b)
t = a.cross(c) / a.cross(b)
return s, t
def intersects(self, other: 'Segment') -> bool:
s, t = self.intersect_ratio(other)
return (0 <= s <= 1) and (0 <= t <= 1)
def intersection(self, other: 'Segment') -> Point:
s, _ = self.intersect_ratio(other)
return self.p1 + s * self.vector()
def distance_with_segment(self, other: 'Segment') -> float:
if not self.is_parallel(other) and \
self.intersects(other):
return 0
else:
return min(
self.p1.distance_to_segment(other),
self.p2.distance_to_segment(other),
other.p1.distance_to_segment(self),
other.p2.distance_to_segment(self))
Line = Segment
class Circle:
def __init__(self, c: Point=None, r: float=0.0) -> None:
self.c: Point = Point() if c is None else c
self.r: float = r
def __eq__(self, other: object) -> bool:
if not isinstance(other, Circle):
return NotImplemented
return self.c == other.c and self.r == other.r
def __repr__(self) -> str:
return "Circle({}, {})".format(self.c, self.r)
def main() -> None:
n = int(input())
for _ in range(n):
x1, y1, x2, y2, x3, y3, x4, y4 = [int(x) for x in input().split()]
s1 = Segment(Point(x1, y1), Point(x2, y2))
s2 = Segment(Point(x3, y3), Point(x4, y4))
print(s1.distance_with_segment(s2))
if __name__ == "__main__":
main()
``` | output | 1 | 33,295 | 23 | 66,591 |
Provide a correct Python 3 solution for this coding contest problem.
For given two segments s1 and s2, print the distance between them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3.
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xpi, ypi ≤ 10000
* p0 ≠ p1 and p2 ≠ p3.
Input
The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth query
Each query consists of integer coordinates of end points of s1 and s2 in the following format:
xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3
Output
For each query, print the distance. The output values should be in a decimal fraction with an error less than 0.00000001.
Example
Input
3
0 0 1 0 0 1 1 1
0 0 1 0 2 1 1 2
-1 0 1 0 0 1 0 -1
Output
1.0000000000
1.4142135624
0.0000000000 | instruction | 0 | 33,296 | 23 | 66,592 |
"Correct Solution:
```
# coding: utf-8
# Your code here!
EPS = 0.0000000001
COUNTER_CLOCKWISE = 1
CLOCKWISE = -1
ONLINE_BACK = 2
ONLINE_FRONT = -2
ON_SEGMENT = 0
class Point:
global EPS
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def __add__(a, b):
s = a.x + b.x
t = a.y + b.y
return Point(s, t)
def __sub__(a, b):
s = a.x - b.x
t = a.y - b.y
return Point(s, t)
def __mul__(self, a):
s = a * self.x
t = a * self.y
return Point(s, t)
def __truediv__(self, a):
s = self.x / a
t = self.y / a
return Point(s, t)
def norm(self):
return self.x * self.x + self.y * self.y
def abs(self):
return self.norm() ** 0.5
def __eq__(self, other):
return abs(self.x - other.y) < self.EPS and abs(self.y - other.y) < self.EPS
def dot(self, b):
return self.x * b.x + self.y * b.y
def cross(self, b):
return self.x * b.y - self.y * b.x
class Segment:
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
def project(s, p):
base = s.p2 - s.p1
hypo = p - s.p1
r = hypo.dot(base) / base.norm()
return s.p1 + base * r
def reflecton(s, p):
return p + (project(s,p) - p) * 2
def getDistance(a, b):
return (a-b).abs()
def getDistanceLP(l, p):
return abs((l.p2-l.p1).cross(p-l.p1)) / ((l.p2-l.p1).abs())
def getDistanceSP(s, p):
if (s.p2 - s.p1).dot(p-s.p1) < 0:
return (p-s.p1).abs()
elif (s.p1 - s.p2).dot(p-s.p2) < 0:
return (p-s.p2).abs()
return getDistanceLP(s,p)
def getDistanceSS(s1, s2):
if intersectS(s1, s2):
return 0
return min(getDistanceSP(s1, s2.p1), getDistanceSP(s1, s2.p2), getDistanceSP(s2, s1.p1), getDistanceSP(s2, s1.p2))
def ccw(p0, p1, p2):
a = p1-p0
b = p2-p0
if a.cross(b) > 0:
return COUNTER_CLOCKWISE
elif a.cross(b) <0:
return CLOCKWISE
elif a.dot(b) < 0:
return ONLINE_BACK
elif a.abs() < b.abs():
return ONLINE_FRONT
else:
return ON_SEGMENT
def intersect(p1, p2, p3, p4):
return ccw(p1, p2, p3) *ccw(p1, p2, p4) <=0 and ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0
def intersectS(s1, s2):
return intersect(s1.p1, s1.p2, s2.p1, s2.p2)
n = int(input())
for i in range(n):
nums=list(map(int,input().split()))
s1 = Segment(Point(nums[0], nums[1]), Point(nums[2], nums[3]))
s2 = Segment(Point(nums[4], nums[5]), Point(nums[6], nums[7]))
print(getDistanceSS(s1, s2))
``` | output | 1 | 33,296 | 23 | 66,593 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For given two segments s1 and s2, print the distance between them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3.
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xpi, ypi ≤ 10000
* p0 ≠ p1 and p2 ≠ p3.
Input
The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth query
Each query consists of integer coordinates of end points of s1 and s2 in the following format:
xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3
Output
For each query, print the distance. The output values should be in a decimal fraction with an error less than 0.00000001.
Example
Input
3
0 0 1 0 0 1 1 1
0 0 1 0 2 1 1 2
-1 0 1 0 0 1 0 -1
Output
1.0000000000
1.4142135624
0.0000000000
Submitted Solution:
```
import cmath
import os
import sys
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-8
class Point:
"""
2次元空間上の点
"""
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)
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 r(self):
"""
原点からの距離
:rtype: float
"""
return abs(self.c)
def phase(self):
"""
原点からの角度
:rtype: float
"""
return cmath.phase(self.c)
def angle(self, p, q):
"""
p に向かってる状態から q まで反時計回りに回転するときの角度
:param Point p:
:param Point q:
:rtype: float
"""
return (cmath.phase(q.c - self.c) - cmath.phase(p.c - self.c)) % TAU
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_B&lang=ja
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_C&lang=ja
FIXME: 誤差が気になる。EPS <= 1e-9 だと CGL_2_B ダメだった。
:param 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)
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 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: 端っこでギリギリ触れているのを許容するか
"""
l1 = Line.from_segment(self.p1, self.p2)
l2 = Line.from_segment(s.p1, s.p2)
if l1.is_parallel_to(l2):
# 並行なら線分の端点がもう片方の線分の上にあるかどうか
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:
# 直線同士の交点が線分の上にあるかどうか
p = l1.intersection_point(l2)
return p.on_segment(self.p1, self.p2, allow_side) and p.on_segment(s.p1, s.p2, allow_side)
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):
"""
他の線分との最短距離
: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),
)
Q = int(sys.stdin.buffer.readline())
ROWS = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(Q)]
for x0, y0, x1, y1, x2, y2, x3, y3 in ROWS:
s1 = Segment(Point.from_rect(x0, y0), Point.from_rect(x1, y1))
s2 = Segment(Point.from_rect(x2, y2), Point.from_rect(x3, y3))
print(s1.dist_segment(s2))
``` | instruction | 0 | 33,297 | 23 | 66,594 |
Yes | output | 1 | 33,297 | 23 | 66,595 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For given two segments s1 and s2, print the distance between them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3.
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xpi, ypi ≤ 10000
* p0 ≠ p1 and p2 ≠ p3.
Input
The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth query
Each query consists of integer coordinates of end points of s1 and s2 in the following format:
xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3
Output
For each query, print the distance. The output values should be in a decimal fraction with an error less than 0.00000001.
Example
Input
3
0 0 1 0 0 1 1 1
0 0 1 0 2 1 1 2
-1 0 1 0 0 1 0 -1
Output
1.0000000000
1.4142135624
0.0000000000
Submitted Solution:
```
def dot(a, b):
return a.real * b.real + a.imag * b.imag
def cross(a, b):
return a.real * b.imag - a.imag * b.real
def ccw(p0, p1, p2):
a = p1-p0
b = p2-p0
if cross(a,b) > 0:
return 1 #couner_clockwise
elif cross(a,b) <0:
return -1 #clockwise
elif dot(a,b) < 0:
return 2 #online_back
elif abs(a) < abs(b):
return -2 #online_front
else:
return 0 #on_segment
def get_distanceLP(p0,p1,p2):
return abs(cross(p1 - p0,p2-p0)/abs(p1-p0))
def get_distanceSP(p0,p1,p2):
if dot(p1-p0,p2-p0)<0:
return abs(p2-p0)
if dot(p0-p1,p2-p1)<0:
return abs(p2-p1)
return get_distanceLP(p0,p1,p2)
def get_distance(a,b,c,d):
if intersect(a,b,c,d):
return 0
return min(min(get_distanceSP(a,b,c),get_distanceSP(a,b,d)),min(get_distanceSP(c,d,a),get_distanceSP(c,d,b)))
def intersect(a,b,c,d):
return ccw(a,b,c) * ccw(a,b,d) <=0 and ccw(c,d,a) * ccw(c,d,b) <=0
n=int(input())
for i in range(n):
x0,y0,x1,y1,x2,y2,x3,y3 = map(int,input().split())
p0=complex(x0,y0)
p1=complex(x1,y1)
p2=complex(x2,y2)
p3=complex(x3,y3)
print(get_distance(p0,p1,p2,p3))
``` | instruction | 0 | 33,298 | 23 | 66,596 |
Yes | output | 1 | 33,298 | 23 | 66,597 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For given two segments s1 and s2, print the distance between them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3.
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xpi, ypi ≤ 10000
* p0 ≠ p1 and p2 ≠ p3.
Input
The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth query
Each query consists of integer coordinates of end points of s1 and s2 in the following format:
xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3
Output
For each query, print the distance. The output values should be in a decimal fraction with an error less than 0.00000001.
Example
Input
3
0 0 1 0 0 1 1 1
0 0 1 0 2 1 1 2
-1 0 1 0 0 1 0 -1
Output
1.0000000000
1.4142135624
0.0000000000
Submitted Solution:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
input:
3
0 0 1 0 0 1 1 1
0 0 1 0 2 1 1 2
-1 0 1 0 0 1 0 -1
output:
1.0000000000
1.4142135624
0.0000000000
"""
import sys
from collections import namedtuple
EPS = 1e-9
def cross(a, b):
return a.real * b.imag - a.imag * b.real
def dot(a, b):
return a.real * b.real + a.imag * b.imag
def get_distance_lp(l, p):
return abs(cross(l.target - l.source, p - l.source) / abs(l.target - l.source))
def get_distance_sp(s, p):
if dot(s.target - s.source, p - s.source) < 0:
return abs(p - s.source)
elif dot(s.source - s.target, p - s.target) < 0:
return abs(p - s.target)
else:
return get_distance_lp(s, p)
def check_ccw(p0, p1, p2):
a, b = p1 - p0, p2 - p0
if cross(a, b) > EPS:
flag = 1
elif cross(a, b) < -1 * EPS:
flag = -1
elif dot(a, b) < -1 * EPS:
flag = 2
elif abs(a) < abs(b):
flag = -2
else:
flag = 0
return flag
def check_intersection(p0, p1, p2, p3):
intersected = (check_ccw(p0, p1, p2) * check_ccw(p0, p1, p3) <= 0) and \
(check_ccw(p2, p3, p0) * check_ccw(p2, p3, p1) <= 0)
return intersected
def solve(_segments):
for segment in _segments:
axis = tuple(map(int, segment))
p0, p1, p2, p3 = (x + y * 1j for x, y in zip(axis[::2], axis[1::2]))
s1, s2 = Segment(p0, p1), Segment(p2, p3)
intersected = check_intersection(s1.source, s1.target, s2.source, s2.target)
if intersected:
distance = 0
else:
distance = min(min(get_distance_sp(s1, s2.source), get_distance_sp(s1, s2.target)),
min(get_distance_sp(s2, s1.source), get_distance_sp(s2, s1.target)))
print('{ans:.10f}'.format(ans=distance))
return None
if __name__ == '__main__':
_input = sys.stdin.readlines()
questions = int(_input[0])
segments = map(lambda x: x.split(), _input[1:])
Segment = namedtuple('Segment', ('source', 'target'))
solve(segments)
``` | instruction | 0 | 33,299 | 23 | 66,598 |
Yes | output | 1 | 33,299 | 23 | 66,599 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For given two segments s1 and s2, print the distance between them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3.
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xpi, ypi ≤ 10000
* p0 ≠ p1 and p2 ≠ p3.
Input
The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth query
Each query consists of integer coordinates of end points of s1 and s2 in the following format:
xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3
Output
For each query, print the distance. The output values should be in a decimal fraction with an error less than 0.00000001.
Example
Input
3
0 0 1 0 0 1 1 1
0 0 1 0 2 1 1 2
-1 0 1 0 0 1 0 -1
Output
1.0000000000
1.4142135624
0.0000000000
Submitted Solution:
```
from math import sqrt
q = int(input())
class Segment(): pass
def dot(a, b):
return sum([i * j for i,j in zip(a, b)])
def sub(a, b):
return [a[0] - b[0],a[1] - b[1]]
def cross(a, b):
return a[0] * b[1] - a[1] * b[0]
def norm(a):
return sqrt(a[0] ** 2 + a[1] ** 2)
def ccw(a, b, c):
x = sub(b, a)
y = sub(c, a)
if cross(x, y) > 0: return 1
if cross(x, y) < 0: return -1
if dot(x, y) < 0: return 2
if norm(x) < norm(y): return -2
return 0
def intersect(p1, p2, p3, p4):
return ccw(p1, p2, p3) * ccw(p1, p2, p4) <= 0 and \
ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0
def getDistLP(s, p):
return abs(cross(sub(s.r, s.l), sub(p, s.l))) / norm(sub(s.r, s.l))
def getDistSP(s, p):
if dot(sub(s.r, s.l),sub(p, s.l)) < 0: return norm(sub(p, s.l))
if dot(sub(s.l, s.r),sub(p, s.r)) < 0: return norm(sub(p, s.r))
return getDistLP(s, p)
def getDist(s1, s2):
if intersect(s1.l, s1.r, s2.l, s2.r): return 0
return min(getDistSP(s1, s2.l),
getDistSP(s1, s2.r),
getDistSP(s2, s1.l),
getDistSP(s2, s1.r))
for i in range(q):
xp0, yp0, xp1, yp1, xp2, yp2, xp3, yp3 = map(int, input().split())
s1 = Segment()
s2 = Segment()
s1.l = [xp0, yp0]
s1.r = [xp1, yp1]
s2.l = [xp2, yp2]
s2.r = [xp3, yp3]
print(getDist(s1, s2))
``` | instruction | 0 | 33,300 | 23 | 66,600 |
Yes | output | 1 | 33,300 | 23 | 66,601 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For given two segments s1 and s2, print the distance between them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3.
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xpi, ypi ≤ 10000
* p0 ≠ p1 and p2 ≠ p3.
Input
The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth query
Each query consists of integer coordinates of end points of s1 and s2 in the following format:
xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3
Output
For each query, print the distance. The output values should be in a decimal fraction with an error less than 0.00000001.
Example
Input
3
0 0 1 0 0 1 1 1
0 0 1 0 2 1 1 2
-1 0 1 0 0 1 0 -1
Output
1.0000000000
1.4142135624
0.0000000000
Submitted Solution:
```
import sys
class Line:
def __init__(self,p1,p2):
if p1[1] < p2[1]:self.s=p2;self.e=p1
elif p1[1] > p2[1]:self.s=p1;self.e=p2
else:
if p1[0] < p2[0]:self.s=p1;self.e=p2
else:self.s=p2;self.e=p1
def cross(a,b):return a[0]*b[1] - a[1]*b[0]
def dot(a,b):return a[0]*b[0]+a[1]*b[1]
def dif(a,b):return [x-y for x,y in zip(a,b)]
def dist(a,b):return ((a[0]-b[0])**2+(a[1]-b[1])**2)**0.5
def isec(l,m):
a = dif(l.e,l.s);b = dif(m.e,l.s);c = dif(m.s,l.s)
d = dif(m.e,m.s);e = dif(l.e,m.s);f = dif(l.s,m.s)
g = lambda a, b : cross(a,b)==0 and dot(a,b)>0 and dot(b,b)<dot(a,a)
if g(a,b) or g(a,c) or g(d,e) or g(d,f):return True
elif l.s == m.e or l.s == m.s or l.e == m.e or l.e == m.s:return True
elif cross(a,b) * cross(a,c) >= 0 or cross(d,e) * cross(d,f) >= 0:return False
else:return True
def plus(a,b):return [x+y for x,y in zip(a,b)]
def projection(a,b):return [x*dot(a,b)/dot(a,a) for x in a]
def proj(A,B,C,D):
AB = dif(B,A) ; AC = dif(C,A) ; AD = dif(D,A)
CD = dif(D,C) ; CA = dif(A,C) ; CB = dif(B,C)
_A = plus(projection(CD,CA),C)
_B = plus(projection(CD,CB),C)
_C = plus(projection(AB,AC),A)
_D = plus(projection(AB,AD),A)
return [_A,_B,_C,_D]
def Order(a,b):
crs = cross(a,b)
if crs > 0 : return "COUNTER_CLOCKWISE"
elif crs < 0 : return "CLOCKWISE"
else:
if dot(a,b) < 0 : return "ONLINE_BACK"
elif dot(a,a) < dot(b,b) : return "ONLINE_FRONT"
else : return "ON_SEGMENT"
q = int(input())
for i in range(q):
a,b,c,d,e,f,g,h = [int(i) for i in input().split()]
A = [a,b] ; B = [c,d] ; C = [e,f] ; D = [g,h]
l = Line(A,B) ; m = Line(C,D)
if isec(l,m):
print(0.0)
continue
_A,_B,_C,_D = proj(A,B,C,D)
AB = dif(B,A) ; CD = dif(D,C)
A_C = dif(_C,A) ; A_D = dif(_D,A) ; C_A = dif(_A,C) ; C_B = dif(_B,C)
DIST = [dist(A,C),dist(A,D),dist(B,C),dist(B,D),dist(_A,A),dist(_B,B),dist(_C,C),dist(_D,D)]
fun = lambda x : x != "ON_SEGMENT"
if fun(Order(CD,C_A)) : DIST[4] = sys.maxsize
if fun(Order(CD,C_B)) : DIST[5] = sys.maxsize
if fun(Order(AB,A_C)) : DIST[6] = sys.maxsize
if fun(Order(AB,A_D)) : DIST[7] = sys.maxsize
print(min(DIST))
``` | instruction | 0 | 33,301 | 23 | 66,602 |
No | output | 1 | 33,301 | 23 | 66,603 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For given two segments s1 and s2, print the distance between them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3.
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xpi, ypi ≤ 10000
* p0 ≠ p1 and p2 ≠ p3.
Input
The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth query
Each query consists of integer coordinates of end points of s1 and s2 in the following format:
xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3
Output
For each query, print the distance. The output values should be in a decimal fraction with an error less than 0.00000001.
Example
Input
3
0 0 1 0 0 1 1 1
0 0 1 0 2 1 1 2
-1 0 1 0 0 1 0 -1
Output
1.0000000000
1.4142135624
0.0000000000
Submitted Solution:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
input:
3
0 0 1 0 0 1 1 1
0 0 1 0 2 1 1 2
-1 0 1 0 0 1 0 -1
output:
1.0000000000
1.4142135624
0.0000000000
"""
import sys
class Segment(object):
__slots__ = ('source', 'target')
def __init__(self, source, target):
self.source = complex(source)
self.target = complex(target)
def cross(a, b):
return a.real * b.imag - a.imag * b.real
def dot(a, b):
return a.real * b.real + a.imag * b.imag
def get_distance_lp(l, p):
return abs(cross(l.target - l.source, p - l.source) / abs(l.target - l.source))
def get_distance_sp(s, p):
if dot(s.target - s.source, p - s.source) < 0:
return abs(p - s.source)
elif dot(s.source - s.target, p - s.target) < 0:
return abs(p - s.target)
else:
return get_distance_lp(s, p)
def calc_distance(line_info):
for line_pair in line_info:
line_axis = tuple(map(int, line_pair))
p0, p1, p2, p3 = (x + y * 1j for x, y in zip(line_axis[::2], line_axis[1::2]))
s1, s2 = Segment(p0, p1), Segment(p2, p3)
# TODO: check intersection of segments: s1, s2
distance = min(min(get_distance_sp(s1, s2.source), get_distance_sp(s1, s2.target)),
min(get_distance_sp(s2, s1.source), get_distance_sp(s2, s1.target))
)
print('{0:.10f}'.format(distance))
return None
if __name__ == '__main__':
_input = sys.stdin.readlines()
questions = int(_input[0])
lines = map(lambda x: x.split(), _input[1:])
calc_distance(lines)
``` | instruction | 0 | 33,302 | 23 | 66,604 |
No | output | 1 | 33,302 | 23 | 66,605 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For given two segments s1 and s2, print the distance between them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3.
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xpi, ypi ≤ 10000
* p0 ≠ p1 and p2 ≠ p3.
Input
The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth query
Each query consists of integer coordinates of end points of s1 and s2 in the following format:
xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3
Output
For each query, print the distance. The output values should be in a decimal fraction with an error less than 0.00000001.
Example
Input
3
0 0 1 0 0 1 1 1
0 0 1 0 2 1 1 2
-1 0 1 0 0 1 0 -1
Output
1.0000000000
1.4142135624
0.0000000000
Submitted Solution:
```
import sys
class Line:
def __init__(self,p1,p2):
if p1[1] < p2[1]:self.s=p2;self.e=p1
elif p1[1] > p2[1]:self.s=p1;self.e=p2
else:
if p1[0] < p2[0]:self.s=p1;self.e=p2
else:self.s=p2;self.e=p1
def cross(a,b):return a[0]*b[1] - a[1]*b[0]
def dot(a,b):return a[0]*b[0]+a[1]*b[1]
def dif(a,b):return [x-y for x,y in zip(a,b)]
def dist(a,b):return ((a[0]-b[0])**2+(a[1]-b[1])**2)**0.5
def isec(l,m):
a = dif(l.e,l.s);b = dif(m.e,l.s);c = dif(m.s,l.s)
d = dif(m.e,m.s);e = dif(l.e,m.s);f = dif(l.s,m.s)
g = lambda a, b : cross(a,b)==0 and dot(a,b)>0 and dot(b,b)<dot(a,a)
if g(a,b) or g(a,c) or g(d,e) or g(d,f):return True
elif l.s == m.e or l.s == m.s or l.e == m.e or l.e == m.s:return True
elif cross(a,b) * cross(a,c) >= 0 or cross(d,e) * cross(d,f) >= 0:return False
else:return True
def plus(a,b):return [x+y for x,y in zip(a,b)]
def projection(a,b):return [x*dot(a,b)/dot(a,a) for x in a]
def proj(A,B,C,D):
AB = dif(B,A) ; AC = dif(C,A) ; AD = dif(D,A)
CD = dif(D,C) ; CA = dif(A,C) ; CB = dif(B,C)
_A = plus(projection(CD,CA),C)
_B = plus(projection(CD,CB),C)
_C = plus(projection(AB,AC),A)
_D = plus(projection(AB,AD),A)
return [_A,_B,_C,_D]
def Order(a,b):
crs = cross(a,b)
if abs(crs) < 1.0e-11 : crs = 0.0
if crs > 0 : return "COUNTER_CLOCKWISE"
elif crs < 0 : return "CLOCKWISE"
else:
if dot(a,b) < 0 : return "ONLINE_BACK"
elif dot(a,a) < dot(b,b) : return "ONLINE_FRONT"
else : return "ON_SEGMENT"
q = int(input())
for i in range(q):
a,b,c,d,e,f,g,h = [int(i) for i in input().split()]
A = [a,b] ; B = [c,d] ; C = [e,f] ; D = [g,h]
l = Line(A,B) ; m = Line(C,D)
if isec(l,m):
print(0.0)
continue
_A,_B,_C,_D = proj(A,B,C,D)
AB = dif(B,A) ; CD = dif(D,C)
A_C = dif(_C,A) ; A_D = dif(_D,A) ; C_A = dif(_A,C) ; C_B = dif(_B,C)
DIST = [dist(A,C),dist(A,D),dist(B,C),dist(B,D),dist(_A,A),dist(_B,B),dist(_C,C),dist(_D,D)]
fun = lambda x : x != "ON_SEGMENT"
if fun(Order(CD,C_A)) : DIST[4] = sys.maxsize
if fun(Order(CD,C_B)) : DIST[5] = sys.maxsize
if fun(Order(AB,A_C)) : DIST[6] = sys.maxsize
if fun(Order(AB,A_D)) : DIST[7] = sys.maxsize
print(min(DIST))
``` | instruction | 0 | 33,303 | 23 | 66,606 |
No | output | 1 | 33,303 | 23 | 66,607 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For given two segments s1 and s2, print the distance between them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3.
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xpi, ypi ≤ 10000
* p0 ≠ p1 and p2 ≠ p3.
Input
The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth query
Each query consists of integer coordinates of end points of s1 and s2 in the following format:
xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3
Output
For each query, print the distance. The output values should be in a decimal fraction with an error less than 0.00000001.
Example
Input
3
0 0 1 0 0 1 1 1
0 0 1 0 2 1 1 2
-1 0 1 0 0 1 0 -1
Output
1.0000000000
1.4142135624
0.0000000000
Submitted Solution:
```
import math
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, pnt):
return math.sqrt((self.x - pnt.x)**2 + (self.y - pnt.y)**2)
class Segment():
def __init__(self, x1, y1, x2, y2):
self.p1 = Point(x1, y1)
self.p2 = Point(x2, y2)
if self.p1.x == self.p2.x:
self.a = float('inf')
self.b = None
else:
self.a = (self.p1.y - self.p2.y)/(self.p1.x - self.p2.x)
self.b = self.p1.y - self.a*self.p1.x
def is_intersect(self, seg):
a = (seg.p1.x - seg.p2.x) * (self.p1.y - seg.p1.y) + (seg.p1.y - seg.p2.y) * (seg.p1.x - self.p1.x)
b = (seg.p1.x - seg.p2.x) * (self.p2.y - seg.p1.y) + (seg.p1.y - seg.p2.y) * (seg.p1.x - self.p2.x)
c = (self.p1.x - self.p2.x) * (seg.p1.y - self.p1.y) + (self.p1.y - self.p2.y) * (self.p1.x - seg.p1.x)
d = (self.p1.x - self.p2.x) * (seg.p2.y - self.p1.y) + (self.p1.y - self.p2.y) * (self.p1.x - seg.p2.x)
e = (self.p1.x - seg.p1.x)*(self.p2.x - seg.p2.x)
f = (self.p1.x - seg.p2.x)*(self.p2.x - seg.p1.x)
g = (self.p1.y - seg.p1.y)*(self.p2.y - seg.p2.y)
h = (self.p1.y - seg.p2.y)*(self.p2.y - seg.p1.y)
return a*b <= 0 and c*d <= 0 and (e <= 0 or f <= 0) and (g <= 0 or h <= 0)
def cross_point(self, seg):
if self.is_intersect(seg) == False: return None
if self.a == float('inf'):
return self.p1.x, seg.a * self.p1.x + seg.b
elif seg.a == float('inf'):
return seg.p1.x, self.a * seg.p1.x + self.b
else:
x = -(self.b - seg.b)/(self.a - seg.a)
y = seg.a * x + seg.b
return x, y
def distance_with_point(self, pnt):
if self.a == float('inf'):
return abs(pnt.x - self.p1.x)
dist = abs(pnt.y - self.a*pnt.x - self.b)/math.sqrt(1 + self.a**2)
a, b = pnt.distance(self.p1), pnt.distance(self.p2)
lower_bound = min(a, b)
if lower_bound < dist:
return dist
else:
return lower_bound
def distance(self, seg):
if self.is_intersect(seg): return 0
a = self.distance_with_point(seg.p1)
b = self.distance_with_point(seg.p2)
c = seg.distance_with_point(self.p1)
d = seg.distance_with_point(self.p2)
return min(a, b, c, d)
q = int(input())
for i in range(q):
x0, y0, x1, y1, x2, y2, x3, y3 = list(map(int, input().split(' ')))
line1, line2 = Segment(x0, y0, x1, y1), Segment(x2, y2, x3, y3)
dist = line1.distance(line2)
print('%.9f'%dist)
``` | instruction | 0 | 33,304 | 23 | 66,608 |
No | output | 1 | 33,304 | 23 | 66,609 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has got three integers n, m and k. He'd like to find three integer points (x_1, y_1), (x_2, y_2), (x_3, y_3), such that 0 ≤ x_1, x_2, x_3 ≤ n, 0 ≤ y_1, y_2, y_3 ≤ m and the area of the triangle formed by these points is equal to nm/k.
Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.
Input
The single line contains three integers n, m, k (1≤ n, m ≤ 10^9, 2 ≤ k ≤ 10^9).
Output
If there are no such points, print "NO".
Otherwise print "YES" in the first line. The next three lines should contain integers x_i, y_i — coordinates of the points, one point per line. If there are multiple solutions, print any of them.
You can print each letter in any case (upper or lower).
Examples
Input
4 3 3
Output
YES
1 0
2 3
4 1
Input
4 4 7
Output
NO
Note
In the first example area of the triangle should be equal to nm/k = 4. The triangle mentioned in the output is pictured below:
<image>
In the second example there is no triangle with area nm/k = 16/7. | instruction | 0 | 33,336 | 23 | 66,672 |
Tags: geometry, number theory
Correct Solution:
```
def check(d1, k1, d2, k2):
n1 = n*k1 // d1
m1 = m*k2 // d2
if n1 * m1 == 2 * n * m // k and n1 <= n and m1 <= m:
print("YES")
print(0, 0)
print(n1, 0)
print(0, m1)
exit()
read = lambda: map(int, input().split())
gcd = lambda a, b: a if b == 0 else gcd(b, a % b)
n, m, k = read()
if (2 * n * m) % k:
print("NO")
exit()
d = 1
while d * d <= k:
if k % d == 0:
d2 = k // d
d1 = d
check(d1, 1, d2, 2)
check(d2, 1, d1, 2)
check(d1, 2, d2, 1)
check(d2, 2, d1, 1)
d += 1
print("NO")
``` | output | 1 | 33,336 | 23 | 66,673 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has got three integers n, m and k. He'd like to find three integer points (x_1, y_1), (x_2, y_2), (x_3, y_3), such that 0 ≤ x_1, x_2, x_3 ≤ n, 0 ≤ y_1, y_2, y_3 ≤ m and the area of the triangle formed by these points is equal to nm/k.
Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.
Input
The single line contains three integers n, m, k (1≤ n, m ≤ 10^9, 2 ≤ k ≤ 10^9).
Output
If there are no such points, print "NO".
Otherwise print "YES" in the first line. The next three lines should contain integers x_i, y_i — coordinates of the points, one point per line. If there are multiple solutions, print any of them.
You can print each letter in any case (upper or lower).
Examples
Input
4 3 3
Output
YES
1 0
2 3
4 1
Input
4 4 7
Output
NO
Note
In the first example area of the triangle should be equal to nm/k = 4. The triangle mentioned in the output is pictured below:
<image>
In the second example there is no triangle with area nm/k = 16/7. | instruction | 0 | 33,337 | 23 | 66,674 |
Tags: geometry, number theory
Correct Solution:
```
def gcd(a, b):
if a==0:
return b
elif b==0:
return a
else:
if a>b:
return gcd (a%b, b)
else:
return gcd (a, b%a)
n, m, k = map(int, input().split())
n1, m1, k1=n, m, k
f=0
if (2*m*n)%k!=0:
print ("NO")
else:
f=0
if k%2==0:
k=k//2
f=1
t=gcd(n, k)
while t!=1:
n=n//t
k=k//t
t=gcd(n, k)
t=gcd(m, k)
while t!=1:
m=m//t
k=k//t
t=gcd(m, k)
if f==0:
if m*2<=m1:
m*=2
print ("YES")
print ('0 0')
print (0, m)
print (n, 0)
else:
if n*2<=n1:
n*=2
print ("YES")
print ('0 0')
print (0, m)
print (n, 0)
else:
print ('NO')
else:
if n<=n1 and m<=m1:
print ("YES")
print ('0 0')
print (0, m)
print (n, 0)
else:
print ("NO")
``` | output | 1 | 33,337 | 23 | 66,675 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has got three integers n, m and k. He'd like to find three integer points (x_1, y_1), (x_2, y_2), (x_3, y_3), such that 0 ≤ x_1, x_2, x_3 ≤ n, 0 ≤ y_1, y_2, y_3 ≤ m and the area of the triangle formed by these points is equal to nm/k.
Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.
Input
The single line contains three integers n, m, k (1≤ n, m ≤ 10^9, 2 ≤ k ≤ 10^9).
Output
If there are no such points, print "NO".
Otherwise print "YES" in the first line. The next three lines should contain integers x_i, y_i — coordinates of the points, one point per line. If there are multiple solutions, print any of them.
You can print each letter in any case (upper or lower).
Examples
Input
4 3 3
Output
YES
1 0
2 3
4 1
Input
4 4 7
Output
NO
Note
In the first example area of the triangle should be equal to nm/k = 4. The triangle mentioned in the output is pictured below:
<image>
In the second example there is no triangle with area nm/k = 16/7. | instruction | 0 | 33,338 | 23 | 66,676 |
Tags: geometry, number theory
Correct Solution:
```
from collections import Counter as __Counter
import sys as __sys
def find_points_vasya_want(size_x, size_y, k):
if 2*size_x*size_y % k != 0:
raise ValueError("can't make such triangle")
size_x_factors = __represent_as_prime_factors(size_x)
size_y_factors = __represent_as_prime_factors(size_y)
k_factors = __represent_as_prime_factors(k)
x_factors = size_x_factors.copy()
y_factors = size_y_factors.copy()
# need to multiply x*y by 2/k
# 2*x*y % k == 0
if 2 in k_factors:
__remove_one_prime_factor(k_factors, 2)
else:
max_k_factor = max(k_factors)
if max_k_factor in x_factors:
__remove_one_prime_factor(x_factors, max_k_factor)
__add_one_prime_factor(x_factors, 2)
else:
__remove_one_prime_factor(y_factors, max_k_factor)
__add_one_prime_factor(y_factors, 2)
__remove_one_prime_factor(k_factors, max_k_factor)
for x_factor in tuple(x_factors.keys()):
if x_factor in k_factors:
disappear_n = min(x_factors[x_factor], k_factors[x_factor])
__remove_n_prime_factors(x_factors, x_factor, disappear_n)
__remove_n_prime_factors(k_factors, x_factor, disappear_n)
for y_factor in tuple(y_factors.keys()):
if y_factor in k_factors:
disappear_n = min(y_factors[y_factor], k_factors[y_factor])
__remove_n_prime_factors(y_factors, y_factor, disappear_n)
__remove_n_prime_factors(k_factors, y_factor, disappear_n)
assert not k_factors
x = __prime_factors_to_number(x_factors)
y = __prime_factors_to_number(y_factors)
return [
(0, 0),
(x, 0),
(0, y)
]
def __represent_as_prime_factors(x):
assert isinstance(x, int)
assert x >= 1
result = dict()
factor_to_check = 2
while factor_to_check ** 2 <= x:
if x % factor_to_check == 0:
result[factor_to_check] = __count_factor(x, factor_to_check)
x //= factor_to_check ** result[factor_to_check]
factor_to_check += 1
if x != 1:
result[x] = 1
return __Counter(result)
def __prime_factors_to_number(x_factors):
result = 1
for factor, factor_count in x_factors.items():
result *= factor ** factor_count
return result
def __count_factor(x, factor):
result = 0
while x % factor == 0:
x //= factor
result += 1
return result
def __add_one_prime_factor(x_factors, factor):
if factor not in x_factors:
x_factors[factor] = 0
x_factors[factor] += 1
def __remove_one_prime_factor(x_factors, factor):
__remove_n_prime_factors(x_factors, factor, 1)
def __remove_n_prime_factors(x_factors, factor, n):
assert factor in x_factors and x_factors[factor] >= n
x_factors[factor] -= n
if x_factors[factor] == 0:
del x_factors[factor]
def __main():
n, m, k = __read_ints()
try:
points = find_points_vasya_want(n, m, k)
except ValueError:
print("NO")
else:
print("YES")
for x, y in points:
print(x, y)
def __read_line():
result = __sys.stdin.readline()
assert result[-1] == "\n"
return result[:-1]
def __read_ints():
return map(int, __read_line().split())
if __name__ == '__main__':
__main()
``` | output | 1 | 33,338 | 23 | 66,677 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has got three integers n, m and k. He'd like to find three integer points (x_1, y_1), (x_2, y_2), (x_3, y_3), such that 0 ≤ x_1, x_2, x_3 ≤ n, 0 ≤ y_1, y_2, y_3 ≤ m and the area of the triangle formed by these points is equal to nm/k.
Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.
Input
The single line contains three integers n, m, k (1≤ n, m ≤ 10^9, 2 ≤ k ≤ 10^9).
Output
If there are no such points, print "NO".
Otherwise print "YES" in the first line. The next three lines should contain integers x_i, y_i — coordinates of the points, one point per line. If there are multiple solutions, print any of them.
You can print each letter in any case (upper or lower).
Examples
Input
4 3 3
Output
YES
1 0
2 3
4 1
Input
4 4 7
Output
NO
Note
In the first example area of the triangle should be equal to nm/k = 4. The triangle mentioned in the output is pictured below:
<image>
In the second example there is no triangle with area nm/k = 16/7. | instruction | 0 | 33,339 | 23 | 66,678 |
Tags: geometry, number theory
Correct Solution:
```
from collections import defaultdict
def generate(factors, arr, ind, current):
if ind == len(arr):
factors.add(current)
return
num = 1
for i in range(arr[ind][1]+1):
generate(factors, arr, ind+1, current*num)
num *= arr[ind][0]
n, m, k = map(int, input().split())
orin = n
orim = m
orik = k
x1, y1, x3, y2 = 0, 0, 0, 0
nprimes = defaultdict(int)
mprimes = defaultdict(int)
kprimes = defaultdict(int)
if 2*n*m % k != 0:
print("NO\n")
exit()
curnum = 2
while curnum <= int(n**0.5):
while n%curnum == 0:
nprimes[curnum] += 1
n //= curnum
curnum += 1;
if n != 1:
nprimes[n] += 1
curnum = 2
while curnum <= int(m**0.5):
while m%curnum == 0:
mprimes[curnum] += 1
m //= curnum
curnum += 1;
if m != 1:
mprimes[m] += 1
curnum = 2
while curnum <= int(k**0.5):
while k%curnum == 0:
kprimes[curnum] += 1
k //= curnum
curnum += 1;
if k != 1:
kprimes[k] += 1
# print(kprimes)
for x in mprimes:
nprimes[x] += mprimes[x]
nprimes[2] += 1
for x in kprimes:
nprimes[x] -= kprimes[x]
factors = set()
arr = []
for x in nprimes:
if nprimes[x] != 0:
arr += [[x, nprimes[x]]]
generate(factors, arr, 0, 1)
numerator = 2*orin*orim//orik
x2, y3 = -1, -1
for x in factors:
if x <= orin and numerator//x <= orim:
x2, y3 = x, numerator//x
elif x <= orim and numerator//x <= orin:
y3, x2 = x, numerator//x
# print(factors)
if x2 == -1:
print("NO")
else:
print("YES")
print(x1, y1)
print(x2, y2)
print(x3, y3)
``` | output | 1 | 33,339 | 23 | 66,679 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has got three integers n, m and k. He'd like to find three integer points (x_1, y_1), (x_2, y_2), (x_3, y_3), such that 0 ≤ x_1, x_2, x_3 ≤ n, 0 ≤ y_1, y_2, y_3 ≤ m and the area of the triangle formed by these points is equal to nm/k.
Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.
Input
The single line contains three integers n, m, k (1≤ n, m ≤ 10^9, 2 ≤ k ≤ 10^9).
Output
If there are no such points, print "NO".
Otherwise print "YES" in the first line. The next three lines should contain integers x_i, y_i — coordinates of the points, one point per line. If there are multiple solutions, print any of them.
You can print each letter in any case (upper or lower).
Examples
Input
4 3 3
Output
YES
1 0
2 3
4 1
Input
4 4 7
Output
NO
Note
In the first example area of the triangle should be equal to nm/k = 4. The triangle mentioned in the output is pictured below:
<image>
In the second example there is no triangle with area nm/k = 16/7. | instruction | 0 | 33,340 | 23 | 66,680 |
Tags: geometry, number theory
Correct Solution:
```
from math import gcd
n,m,k=map(int,input().split())
tt,pp=n,m
xx=gcd(n,k)
k=k//xx
n=n//xx
xx=gcd(m,k)
k=k//xx
m=m//xx
if k>2:
print('NO')
else:
if k==1:
x=0
print('YES')
print(0,0)
if 2*n<=tt:
print(2*n,0)
x=1
else:
print(n,0)
if 2*m<=pp and not x:
print(0,2*m)
else:
print(0,m)
else:
x = 0
print('YES')
print(0, 0)
print(n, 0)
print(0, m)
``` | output | 1 | 33,340 | 23 | 66,681 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has got three integers n, m and k. He'd like to find three integer points (x_1, y_1), (x_2, y_2), (x_3, y_3), such that 0 ≤ x_1, x_2, x_3 ≤ n, 0 ≤ y_1, y_2, y_3 ≤ m and the area of the triangle formed by these points is equal to nm/k.
Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.
Input
The single line contains three integers n, m, k (1≤ n, m ≤ 10^9, 2 ≤ k ≤ 10^9).
Output
If there are no such points, print "NO".
Otherwise print "YES" in the first line. The next three lines should contain integers x_i, y_i — coordinates of the points, one point per line. If there are multiple solutions, print any of them.
You can print each letter in any case (upper or lower).
Examples
Input
4 3 3
Output
YES
1 0
2 3
4 1
Input
4 4 7
Output
NO
Note
In the first example area of the triangle should be equal to nm/k = 4. The triangle mentioned in the output is pictured below:
<image>
In the second example there is no triangle with area nm/k = 16/7. | instruction | 0 | 33,341 | 23 | 66,682 |
Tags: geometry, number theory
Correct Solution:
```
from sys import stdin
input=lambda : stdin.readline().strip()
lin=lambda :list(map(int,input().split()))
iin=lambda :int(input())
main=lambda :map(int,input().split())
from math import ceil,sqrt,factorial,log
from collections import deque
from bisect import bisect_left
def gcd(a,b):
a,b=max(a,b),min(a,b)
while a%b!=0:
a,b=b,a%b
return b
def solve():
n,m,k=main()
if (2*m*n)%k!=0:
print("NO")
else:
t=(2*n*m)//k
print("YES")
print(0,0)
x=0
y=0
f=0
if k%2==0:
k=k//2
f=1
x=gcd(n,k)
k=k//x
a=n//x
x=gcd(m,k)
k=k//x
b=m//x
if f==0:
if a<n:
a+=a
else:
b+=b
print(a,0)
print(0,b)
qwe=1
# qwe=int(input())
for _ in range(qwe):
solve()
``` | output | 1 | 33,341 | 23 | 66,683 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has got three integers n, m and k. He'd like to find three integer points (x_1, y_1), (x_2, y_2), (x_3, y_3), such that 0 ≤ x_1, x_2, x_3 ≤ n, 0 ≤ y_1, y_2, y_3 ≤ m and the area of the triangle formed by these points is equal to nm/k.
Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.
Input
The single line contains three integers n, m, k (1≤ n, m ≤ 10^9, 2 ≤ k ≤ 10^9).
Output
If there are no such points, print "NO".
Otherwise print "YES" in the first line. The next three lines should contain integers x_i, y_i — coordinates of the points, one point per line. If there are multiple solutions, print any of them.
You can print each letter in any case (upper or lower).
Examples
Input
4 3 3
Output
YES
1 0
2 3
4 1
Input
4 4 7
Output
NO
Note
In the first example area of the triangle should be equal to nm/k = 4. The triangle mentioned in the output is pictured below:
<image>
In the second example there is no triangle with area nm/k = 16/7. | instruction | 0 | 33,342 | 23 | 66,684 |
Tags: geometry, number theory
Correct Solution:
```
n, m, k = map(int, input().split())
n1 = n
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
n, k = n // gcd(n, k), k // gcd(n, k)
m, k = m // gcd(m, k), k // gcd(m, k)
if 2 < k:
print("NO")
elif 2 == k:
print("YES")
print(0, 0)
print(n, 0)
print(0, m)
else:
if n * 2 > n1:
print("YES")
print(0, 0)
print(n, 0)
print(0, m * 2)
else:
print("YES")
print(0, 0)
print(n * 2, 0)
print(0, m)
``` | output | 1 | 33,342 | 23 | 66,685 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has got three integers n, m and k. He'd like to find three integer points (x_1, y_1), (x_2, y_2), (x_3, y_3), such that 0 ≤ x_1, x_2, x_3 ≤ n, 0 ≤ y_1, y_2, y_3 ≤ m and the area of the triangle formed by these points is equal to nm/k.
Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.
Input
The single line contains three integers n, m, k (1≤ n, m ≤ 10^9, 2 ≤ k ≤ 10^9).
Output
If there are no such points, print "NO".
Otherwise print "YES" in the first line. The next three lines should contain integers x_i, y_i — coordinates of the points, one point per line. If there are multiple solutions, print any of them.
You can print each letter in any case (upper or lower).
Examples
Input
4 3 3
Output
YES
1 0
2 3
4 1
Input
4 4 7
Output
NO
Note
In the first example area of the triangle should be equal to nm/k = 4. The triangle mentioned in the output is pictured below:
<image>
In the second example there is no triangle with area nm/k = 16/7. | instruction | 0 | 33,343 | 23 | 66,686 |
Tags: geometry, number theory
Correct Solution:
```
def factorization(n):
ans = []
while (n % 2 == 0):
n //= 2
yield 2
d = 3
while d * d <= n:
while n % d == 0:
n //= d
yield d
d += 2
if n > 1:
yield n
def solve1(n, m, k):
kmod2 = False
if k % 2 == 0:
k //= 2
kmod2 = True
x, y = n, m
ok = True
for d in factorization(k):
if x % d == 0:
x //= d
elif y % d == 0:
y //= d
else:
ok = False
break
if not kmod2:
if x * 2 <= n:
x *= 2
elif y * 2 <= m:
y *= 2
else:
ok = False
if ok:
print('YES')
print(0, 0)
print(x, 0)
print(0, y)
return ok
def solve2(n, m, k):
kmod2 = False
if k % 2 == 0:
k //= 2
kmod2 = True
x, y = n, m
ok = True
for d in factorization(k):
if y % d == 0:
y //= d
elif x % d == 0:
x //= d
else:
ok = False
break
if not kmod2:
if x * 2 <= n:
x *= 2
elif y * 2 <= m:
y *= 2
else:
ok = False
if ok:
print('YES')
print(0, 0)
print(x, 0)
print(0, y)
return ok
n, m, k = map(int, input().split())
if (2 * n * m) % k != 0:
print('NO')
else:
if not solve1(n, m, k) and \
not solve2(n, m, k):
print('NO')
``` | output | 1 | 33,343 | 23 | 66,687 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has got three integers n, m and k. He'd like to find three integer points (x_1, y_1), (x_2, y_2), (x_3, y_3), such that 0 ≤ x_1, x_2, x_3 ≤ n, 0 ≤ y_1, y_2, y_3 ≤ m and the area of the triangle formed by these points is equal to nm/k.
Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.
Input
The single line contains three integers n, m, k (1≤ n, m ≤ 10^9, 2 ≤ k ≤ 10^9).
Output
If there are no such points, print "NO".
Otherwise print "YES" in the first line. The next three lines should contain integers x_i, y_i — coordinates of the points, one point per line. If there are multiple solutions, print any of them.
You can print each letter in any case (upper or lower).
Examples
Input
4 3 3
Output
YES
1 0
2 3
4 1
Input
4 4 7
Output
NO
Note
In the first example area of the triangle should be equal to nm/k = 4. The triangle mentioned in the output is pictured below:
<image>
In the second example there is no triangle with area nm/k = 16/7.
Submitted Solution:
```
from sys import stdin, stdout
input = stdin.buffer.readline
#print = stdout.write
n, m, k = map(int, input().split())
if 2 * n * m % k == 0:
i = 2
t = k
N = n
while i * i <= k:
while t % i == 0 and (n % i == 0 or m % i == 0):
t //= i
if n % i == 0:
n //= i
else:
m //= i
i += 1
if t % 2:
if t > 1:
if n % t == 0:
n //= t
else:
m //= t
if n * 2 <= N:
n *= 2
else:
m *= 2
else:
t //= 2
if t > 1:
if n % t == 0:
n //= t
else:
m //= t
print('YES')
print(0, 0)
print(n, 0)
print(0, m)
else:
print('NO')
``` | instruction | 0 | 33,344 | 23 | 66,688 |
Yes | output | 1 | 33,344 | 23 | 66,689 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has got three integers n, m and k. He'd like to find three integer points (x_1, y_1), (x_2, y_2), (x_3, y_3), such that 0 ≤ x_1, x_2, x_3 ≤ n, 0 ≤ y_1, y_2, y_3 ≤ m and the area of the triangle formed by these points is equal to nm/k.
Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.
Input
The single line contains three integers n, m, k (1≤ n, m ≤ 10^9, 2 ≤ k ≤ 10^9).
Output
If there are no such points, print "NO".
Otherwise print "YES" in the first line. The next three lines should contain integers x_i, y_i — coordinates of the points, one point per line. If there are multiple solutions, print any of them.
You can print each letter in any case (upper or lower).
Examples
Input
4 3 3
Output
YES
1 0
2 3
4 1
Input
4 4 7
Output
NO
Note
In the first example area of the triangle should be equal to nm/k = 4. The triangle mentioned in the output is pictured below:
<image>
In the second example there is no triangle with area nm/k = 16/7.
Submitted Solution:
```
n, m, k = map(int, input().split())
def gcd(x, y):
if y > 0:
return gcd(y, x % y)
else:
return x
if m * n * 2 % k != 0:
print("NO")
else:
print("YES")
a = m * n * 2 / k
g = gcd(2 * n, k)
if g != 1:
x = 2 * n / g
y = m * g / k
else:
x = n
y = m * 2 / k
print(0, 0)
print(int(x), 0)
print(0, int(y))
``` | instruction | 0 | 33,345 | 23 | 66,690 |
Yes | output | 1 | 33,345 | 23 | 66,691 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.