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. The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares. There are the following methods to create a magic square with an odd number of squares on each side. 1. Put 1 in the square just below the center square. 2. Put the following numbers in the square at the bottom right. However, if the square you are trying to insert a number is out of the square, or if the number is already filled, search for the square to insert the number according to the following method. * If it extends to the right, it will be on the left side of the same row, if it extends to the left, it will be on the right side of the same row, and if it extends below, it will be on the top of the same column. Put in. * If the square you are trying to enter is filled, put it in the square diagonally below the left of the filled square. 3. Repeat 2 until all the squares are filled. Follow this method to create a program that takes the number n of squares on one side as input and outputs magic squares of that size. However, n is an odd number between 3 and 15. Output each number in the square as a right-justified 4-digit number. input Multiple inputs are given. Each input gives n (a positive integer) on one line. The input ends with 0. The number of inputs does not exceed 10. output Output n x n magic squares for each input. Example Input 3 5 0 Output 4 9 2 3 5 7 8 1 6 11 24 7 20 3 4 12 25 8 16 17 5 13 21 9 10 18 1 14 22 23 6 19 2 15 Submitted Solution: ``` for e in iter(input,'0'): n=int(e);m,f=[[0]*n for _ in[0]*n],'{:4}'*n s=lambda x:-~x%n j=n//2;i=j+1 m[i][j]=1 for k in range(2,n*n+1): i,j,t=s(i),s(j),j if m[i][j]:i,j=s(i),t m[i][j]=k for r in m:print(f.format(*r)) ```
instruction
0
84,932
23
169,864
Yes
output
1
84,932
23
169,865
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares. There are the following methods to create a magic square with an odd number of squares on each side. 1. Put 1 in the square just below the center square. 2. Put the following numbers in the square at the bottom right. However, if the square you are trying to insert a number is out of the square, or if the number is already filled, search for the square to insert the number according to the following method. * If it extends to the right, it will be on the left side of the same row, if it extends to the left, it will be on the right side of the same row, and if it extends below, it will be on the top of the same column. Put in. * If the square you are trying to enter is filled, put it in the square diagonally below the left of the filled square. 3. Repeat 2 until all the squares are filled. Follow this method to create a program that takes the number n of squares on one side as input and outputs magic squares of that size. However, n is an odd number between 3 and 15. Output each number in the square as a right-justified 4-digit number. input Multiple inputs are given. Each input gives n (a positive integer) on one line. The input ends with 0. The number of inputs does not exceed 10. output Output n x n magic squares for each input. Example Input 3 5 0 Output 4 9 2 3 5 7 8 1 6 11 24 7 20 3 4 12 25 8 16 17 5 13 21 9 10 18 1 14 22 23 6 19 2 15 Submitted Solution: ``` # -*- coding: utf-8 -*- import sys import os import math for s in sys.stdin: n = int(s) if n == 0: break M = [[None for i in range(n)] for j in range(n)] # 1 x = n // 2 y = n // 2 + 1 M[y][x] = 1 x = x + 1 y = y + 1 counter = 2 while counter < n * n + 1: if x >= n: x = 0 elif x < 0: x = n - 1 if y >= n: y = 0 elif y < 0: y = n - 1 if M[y][x] is not None: x -= 1 y += 1 else: M[y][x] = counter counter += 1 x += 1 y += 1 for row in M: print(*row) ```
instruction
0
84,933
23
169,866
No
output
1
84,933
23
169,867
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares. There are the following methods to create a magic square with an odd number of squares on each side. 1. Put 1 in the square just below the center square. 2. Put the following numbers in the square at the bottom right. However, if the square you are trying to insert a number is out of the square, or if the number is already filled, search for the square to insert the number according to the following method. * If it extends to the right, it will be on the left side of the same row, if it extends to the left, it will be on the right side of the same row, and if it extends below, it will be on the top of the same column. Put in. * If the square you are trying to enter is filled, put it in the square diagonally below the left of the filled square. 3. Repeat 2 until all the squares are filled. Follow this method to create a program that takes the number n of squares on one side as input and outputs magic squares of that size. However, n is an odd number between 3 and 15. Output each number in the square as a right-justified 4-digit number. input Multiple inputs are given. Each input gives n (a positive integer) on one line. The input ends with 0. The number of inputs does not exceed 10. output Output n x n magic squares for each input. Example Input 3 5 0 Output 4 9 2 3 5 7 8 1 6 11 24 7 20 3 4 12 25 8 16 17 5 13 21 9 10 18 1 14 22 23 6 19 2 15 Submitted Solution: ``` # -*- coding: utf-8 -*- """ http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0078 """ import sys class MagicSquare(): def __init__(self, size): self.size = size self.data = [['@']*self.size for _ in range(self.size)] self.fill_data() def fill_data(self): num = 1 x = self.size // 2 y = x + 1 self.data[y][x] = num while num < self.size**2: x += 1 if x >= self.size: x = 0 y += 1 if y >= self.size: y = 0 if self.data[y][x] == '@': num += 1 self.data[y][x] = num else: while self.data[y][x] != '@': x -= 1 if x < 0: x = self.size - 1 y += 1 if y >= self.size: y = 0 num += 1 self.data[y][x] = num def print_data(self): digits = len(str(self.size**2)) for row in self.data: print(*row) def main(args): while True: size = int(input()) if size < 3 or size%2 == 0: break ms = MagicSquare(size) ms.print_data() if __name__ == '__main__': main(sys.argv[1:]) ```
instruction
0
84,934
23
169,868
No
output
1
84,934
23
169,869
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares. There are the following methods to create a magic square with an odd number of squares on each side. 1. Put 1 in the square just below the center square. 2. Put the following numbers in the square at the bottom right. However, if the square you are trying to insert a number is out of the square, or if the number is already filled, search for the square to insert the number according to the following method. * If it extends to the right, it will be on the left side of the same row, if it extends to the left, it will be on the right side of the same row, and if it extends below, it will be on the top of the same column. Put in. * If the square you are trying to enter is filled, put it in the square diagonally below the left of the filled square. 3. Repeat 2 until all the squares are filled. Follow this method to create a program that takes the number n of squares on one side as input and outputs magic squares of that size. However, n is an odd number between 3 and 15. Output each number in the square as a right-justified 4-digit number. input Multiple inputs are given. Each input gives n (a positive integer) on one line. The input ends with 0. The number of inputs does not exceed 10. output Output n x n magic squares for each input. Example Input 3 5 0 Output 4 9 2 3 5 7 8 1 6 11 24 7 20 3 4 12 25 8 16 17 5 13 21 9 10 18 1 14 22 23 6 19 2 15 Submitted Solution: ``` import sys f = sys.stdin def set1(sq): x = len(sq) // 2 y = len(sq) // 2 + 1 square[y][x] = 1 return x, y, 1 def mv_r(sq, x, y): x = (x + 1) % len(sq) y = (y + 1) % len(sq) return x, y def mv_l(sq, x, y): x -= 1 if x < 0: x += len(sq) y = (y + 1) % len(sq) return x, y def setnext(sq, x, y, i): x, y = mv_r(sq, x,y) i += 1 while sq[y][x]: x, y = mv_l(sq, x, y) sq[y][x] = i return x, y, i while True: n = int(f.readline()) if n == 0: break square = [[None for j in range(n)] for i in range(n)] arg = set1(square) for i in range(n * n - 1): arg = setnext(square,*arg) for line in square: print(*line) ```
instruction
0
84,935
23
169,870
No
output
1
84,935
23
169,871
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares. There are the following methods to create a magic square with an odd number of squares on each side. 1. Put 1 in the square just below the center square. 2. Put the following numbers in the square at the bottom right. However, if the square you are trying to insert a number is out of the square, or if the number is already filled, search for the square to insert the number according to the following method. * If it extends to the right, it will be on the left side of the same row, if it extends to the left, it will be on the right side of the same row, and if it extends below, it will be on the top of the same column. Put in. * If the square you are trying to enter is filled, put it in the square diagonally below the left of the filled square. 3. Repeat 2 until all the squares are filled. Follow this method to create a program that takes the number n of squares on one side as input and outputs magic squares of that size. However, n is an odd number between 3 and 15. Output each number in the square as a right-justified 4-digit number. input Multiple inputs are given. Each input gives n (a positive integer) on one line. The input ends with 0. The number of inputs does not exceed 10. output Output n x n magic squares for each input. Example Input 3 5 0 Output 4 9 2 3 5 7 8 1 6 11 24 7 20 3 4 12 25 8 16 17 5 13 21 9 10 18 1 14 22 23 6 19 2 15 Submitted Solution: ``` from sys import stdin def sqmatrix(n): return [[0] * n for i in range(n)] def magicsq(m): n = len(m) j = int(n/2) i = j + 1 for num in range(1, n**2 + 1): m[i][j] = num i += 1 j += 1 i = i%n j = j % n if m[i][j] != 0: i += 1 j -= 1 if j < 0: j = n -1 i = i % n return m for line in stdin: n = int(line) if n == 0: break sm = sqmatrix(n) for row in magicsq(sm): print (' '.join(map(str,row))) ```
instruction
0
84,936
23
169,872
No
output
1
84,936
23
169,873
Provide a correct Python 3 solution for this coding contest problem. This is the story of 20XX. The number of air passengers increased as a result of the stable energy supply by the renewable power network and the invention of liquefied synthetic fuel. However, the threat of terrorism by aircraft still exists, and the importance of fast and highly reliable automatic baggage inspection systems is increasing. Since it is actually difficult for an inspector to inspect all the baggage, we would like to establish a mechanism for the inspector to inspect only the baggage judged to be suspicious by the automatic inspection. At the request of the aviation industry, the International Cabin Protection Company investigated recent passenger baggage in order to develop a new automated inspection system. As a result of the investigation, it was found that the baggage of recent passengers has the following tendency. * Baggage is shaped like a rectangular parallelepiped with only one side short. * Items that ordinary passengers pack in their baggage and bring into the aircraft include laptop computers, music players, handheld game consoles, and playing cards, all of which are rectangular. * Individual items are packed so that their rectangular sides are parallel to the sides of the baggage. * On the other hand, weapons such as those used for terrorism have a shape very different from a rectangle. Based on the above survey results, we devised the following model for baggage inspection. Each piece of baggage is considered to be a rectangular parallelepiped container that is transparent to X-rays. It contains multiple items that are opaque to X-rays. Here, consider a coordinate system with the three sides of the rectangular parallelepiped as the x-axis, y-axis, and z-axis, irradiate X-rays in the direction parallel to the x-axis, and take an image projected on the y-z plane. The captured image is divided into grids of appropriate size, and the material of the item reflected in each grid area is estimated by image analysis. Since this company has a very high level of analysis technology and can analyze even the detailed differences in materials, it can be considered that the materials of the products are different from each other. When multiple items overlap in the x-axis direction, the material of the item that is in the foreground for each lattice region, that is, the item with the smallest x-coordinate is obtained. We also assume that the x-coordinates of two or more items are never equal. Your job can be asserted that it contains non-rectangular (possibly a weapon) item when given the results of the image analysis, or that the baggage contains anything other than a rectangular item. It is to create a program that determines whether it is presumed that it is not included. Input The first line of input contains a single positive integer, which represents the number of datasets. Each dataset is given in the following format. > H W > Analysis result 1 > Analysis result 2 > ... > Analysis result H > H is the vertical size of the image, and W is an integer representing the horizontal size (1 <= h, w <= 50). Each line of the analysis result is composed of W characters, and the i-th character represents the analysis result in the grid region i-th from the left of the line. For the lattice region where the substance is detected, the material is represented by uppercase letters (A to Z). At this time, the same characters are used if they are made of the same material, and different characters are used if they are made of different materials. The lattice region where no substance was detected is represented by a dot (.). For all datasets, it is guaranteed that there are no more than seven material types. Output For each data set, output "SUSPICIOUS" if it contains items other than rectangles, and "SAFE" if not, on one line. Sample Input 6 1 1 .. 3 3 ... .W. ... 10 10 .......... .DDDDCC .. .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 .......... .DDDDDD ... .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE .... EEEEEEE ... .EEEEEEE .. ..EEEEEEE. ... EEEEEEE .... EEEEE. ..... EEE .. ...... E ... 16 50 ................................................................. ......... AAAAAAAAAAAAAAAAA ............................ .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA .... .... PPP .............. AAAAA.AAAAAAAAAAAAAAAA ....... .... PPP ................ A .... AAA.AAAAAAAAAA ........ .... PPP ........... IIIIIAAIIAIII.AAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIAAAAAAAAAAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIIIIIIII ... AAAAAAAAAAA ...... .... PPP .................. AAAAAAAAAAA ..... MMMMPPPMMMMMMMMMMMMMMM ............. AAAAAAAAAAA .... MMMMPPPMMMMMMMMMMMMMMM .............. AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............................ Output for the Sample Input SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS Example Input 6 1 1 . 3 3 ... .W. ... 10 10 .......... .DDDDCCC.. .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 .......... .DDDDDD... .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE.... EEEEEEE... .EEEEEEE.. ..EEEEEEE. ...EEEEEEE ....EEEEE. .....EEE.. ......E... 16 50 .................................................. .........AAAAAAAAAAAAAAAA......................... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.... ....PPP..............AAAAA.AAAAAAAAAAAAAAAA....... ....PPP................A....AAA.AAAAAAAAAA........ ....PPP...........IIIIIAAIIAIII.AAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIAAAAAAAAAAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIIIIIIII...AAAAAAAAAA...... ....PPP............................AAAAAAAAAA..... MMMMPPPMMMMMMMMMMMMMMM.............AAAAAAAAAAA.... MMMMPPPMMMMMMMMMMMMMMM..............AAAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM............................ Output SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS
instruction
0
84,961
23
169,922
"Correct Solution: ``` #!/usr/bin/env python3 #aoj b import re from collections import defaultdict def check(i):#メモ化再帰 if d[i] > 0: return d[i] d[i] = 1#チェック状態 for y in range(p[i][0],p[i][1]+1): for x in range(p[i][2],p[i][3]+1): if s[y][x] == ".":#長方形内部に空の部分が存在 d[i] = 3 #SUSPICIOUS return d[i] elif s[y][x] != i:#長方形内部に他の物質が存在 if d[s[y][x]] == 1:#その物質がチェック状態 d[i] = 3 #SUSPICIOUS(循環参照 テストケース4) return d[i] c = check(s[y][x])#そいつの状態確認の再帰 if c == 3: d[i] == 3 return d[i] d[i] = 2#SAFE return 2 N = int(input()) for _ in range(N): h,w = map(int,input().split()) s = [list(input()) for _ in range(h)] p = defaultdict(list) #p[0]:上端,p[1]:下端,p[2]:左端,p[3]:右端 #y座標の追加は横方向で見る(上端は上から、下端は下から) for y in range(h):#上端 for x in range(w): if s[y][x] != '.' and len(p[s[y][x]]) < 1: p[s[y][x]].append(y) for y in range(h)[::-1]:#下端 for x in range(w): if s[y][x] != '.' and len(p[s[y][x]]) < 2: p[s[y][x]].append(y) #x座標の追加は縦方向で見る(左端は左から、右端は右から) for x in range(w):#左端 for y in range(h): if s[y][x] != '.' and len(p[s[y][x]]) < 3: p[s[y][x]].append(x) for x in range(w)[::-1]:#右端 for y in range(h): if s[y][x] != '.' and len(p[s[y][x]]) < 4: p[s[y][x]].append(x) d = defaultdict(lambda : 0)#メモ化再帰用dict for i in p.keys(): if check(i) == 3: print('SUSPICIOUS') break else: print('SAFE') ```
output
1
84,961
23
169,923
Provide a correct Python 3 solution for this coding contest problem. This is the story of 20XX. The number of air passengers increased as a result of the stable energy supply by the renewable power network and the invention of liquefied synthetic fuel. However, the threat of terrorism by aircraft still exists, and the importance of fast and highly reliable automatic baggage inspection systems is increasing. Since it is actually difficult for an inspector to inspect all the baggage, we would like to establish a mechanism for the inspector to inspect only the baggage judged to be suspicious by the automatic inspection. At the request of the aviation industry, the International Cabin Protection Company investigated recent passenger baggage in order to develop a new automated inspection system. As a result of the investigation, it was found that the baggage of recent passengers has the following tendency. * Baggage is shaped like a rectangular parallelepiped with only one side short. * Items that ordinary passengers pack in their baggage and bring into the aircraft include laptop computers, music players, handheld game consoles, and playing cards, all of which are rectangular. * Individual items are packed so that their rectangular sides are parallel to the sides of the baggage. * On the other hand, weapons such as those used for terrorism have a shape very different from a rectangle. Based on the above survey results, we devised the following model for baggage inspection. Each piece of baggage is considered to be a rectangular parallelepiped container that is transparent to X-rays. It contains multiple items that are opaque to X-rays. Here, consider a coordinate system with the three sides of the rectangular parallelepiped as the x-axis, y-axis, and z-axis, irradiate X-rays in the direction parallel to the x-axis, and take an image projected on the y-z plane. The captured image is divided into grids of appropriate size, and the material of the item reflected in each grid area is estimated by image analysis. Since this company has a very high level of analysis technology and can analyze even the detailed differences in materials, it can be considered that the materials of the products are different from each other. When multiple items overlap in the x-axis direction, the material of the item that is in the foreground for each lattice region, that is, the item with the smallest x-coordinate is obtained. We also assume that the x-coordinates of two or more items are never equal. Your job can be asserted that it contains non-rectangular (possibly a weapon) item when given the results of the image analysis, or that the baggage contains anything other than a rectangular item. It is to create a program that determines whether it is presumed that it is not included. Input The first line of input contains a single positive integer, which represents the number of datasets. Each dataset is given in the following format. > H W > Analysis result 1 > Analysis result 2 > ... > Analysis result H > H is the vertical size of the image, and W is an integer representing the horizontal size (1 <= h, w <= 50). Each line of the analysis result is composed of W characters, and the i-th character represents the analysis result in the grid region i-th from the left of the line. For the lattice region where the substance is detected, the material is represented by uppercase letters (A to Z). At this time, the same characters are used if they are made of the same material, and different characters are used if they are made of different materials. The lattice region where no substance was detected is represented by a dot (.). For all datasets, it is guaranteed that there are no more than seven material types. Output For each data set, output "SUSPICIOUS" if it contains items other than rectangles, and "SAFE" if not, on one line. Sample Input 6 1 1 .. 3 3 ... .W. ... 10 10 .......... .DDDDCC .. .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 .......... .DDDDDD ... .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE .... EEEEEEE ... .EEEEEEE .. ..EEEEEEE. ... EEEEEEE .... EEEEE. ..... EEE .. ...... E ... 16 50 ................................................................. ......... AAAAAAAAAAAAAAAAA ............................ .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA .... .... PPP .............. AAAAA.AAAAAAAAAAAAAAAA ....... .... PPP ................ A .... AAA.AAAAAAAAAA ........ .... PPP ........... IIIIIAAIIAIII.AAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIAAAAAAAAAAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIIIIIIII ... AAAAAAAAAAA ...... .... PPP .................. AAAAAAAAAAA ..... MMMMPPPMMMMMMMMMMMMMMM ............. AAAAAAAAAAA .... MMMMPPPMMMMMMMMMMMMMMM .............. AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............................ Output for the Sample Input SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS Example Input 6 1 1 . 3 3 ... .W. ... 10 10 .......... .DDDDCCC.. .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 .......... .DDDDDD... .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE.... EEEEEEE... .EEEEEEE.. ..EEEEEEE. ...EEEEEEE ....EEEEE. .....EEE.. ......E... 16 50 .................................................. .........AAAAAAAAAAAAAAAA......................... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.... ....PPP..............AAAAA.AAAAAAAAAAAAAAAA....... ....PPP................A....AAA.AAAAAAAAAA........ ....PPP...........IIIIIAAIIAIII.AAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIAAAAAAAAAAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIIIIIIII...AAAAAAAAAA...... ....PPP............................AAAAAAAAAA..... MMMMPPPMMMMMMMMMMMMMMM.............AAAAAAAAAAA.... MMMMPPPMMMMMMMMMMMMMMM..............AAAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM............................ Output SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS
instruction
0
84,962
23
169,924
"Correct Solution: ``` def can_fill(image, k, v): for y in range(v[1], v[3] + 1): for x in range(v[0], v[2] + 1): m = image[y][x] if m != k and m != '*': return False return True def is_safe(image, p): keys = list(p.keys()) i = 0 while i < len(keys): k = keys[i] v = p[k] if can_fill(image, k, v): for y in range(v[1], v[3] + 1): for x in range(v[0], v[2] + 1): image[y][x] = '*' keys.remove(k) i = 0 else: i += 1 return len(keys) == 0 n = int(input()) for i in range(n): h, w = map(int, input().split(' ')) image = [list(input()) for y in range(h)] p = {} for y in range(h): for x in range(w): m = image[y][x] if m != '.': if m not in p: p[m] = [x, y, x, y] else: p[m][0] = min(p[m][0], x) p[m][1] = min(p[m][1], y) p[m][2] = max(p[m][2], x) p[m][3] = max(p[m][3], y) print('SAFE' if is_safe(image, p) else 'SUSPICIOUS') ```
output
1
84,962
23
169,925
Provide a correct Python 3 solution for this coding contest problem. This is the story of 20XX. The number of air passengers increased as a result of the stable energy supply by the renewable power network and the invention of liquefied synthetic fuel. However, the threat of terrorism by aircraft still exists, and the importance of fast and highly reliable automatic baggage inspection systems is increasing. Since it is actually difficult for an inspector to inspect all the baggage, we would like to establish a mechanism for the inspector to inspect only the baggage judged to be suspicious by the automatic inspection. At the request of the aviation industry, the International Cabin Protection Company investigated recent passenger baggage in order to develop a new automated inspection system. As a result of the investigation, it was found that the baggage of recent passengers has the following tendency. * Baggage is shaped like a rectangular parallelepiped with only one side short. * Items that ordinary passengers pack in their baggage and bring into the aircraft include laptop computers, music players, handheld game consoles, and playing cards, all of which are rectangular. * Individual items are packed so that their rectangular sides are parallel to the sides of the baggage. * On the other hand, weapons such as those used for terrorism have a shape very different from a rectangle. Based on the above survey results, we devised the following model for baggage inspection. Each piece of baggage is considered to be a rectangular parallelepiped container that is transparent to X-rays. It contains multiple items that are opaque to X-rays. Here, consider a coordinate system with the three sides of the rectangular parallelepiped as the x-axis, y-axis, and z-axis, irradiate X-rays in the direction parallel to the x-axis, and take an image projected on the y-z plane. The captured image is divided into grids of appropriate size, and the material of the item reflected in each grid area is estimated by image analysis. Since this company has a very high level of analysis technology and can analyze even the detailed differences in materials, it can be considered that the materials of the products are different from each other. When multiple items overlap in the x-axis direction, the material of the item that is in the foreground for each lattice region, that is, the item with the smallest x-coordinate is obtained. We also assume that the x-coordinates of two or more items are never equal. Your job can be asserted that it contains non-rectangular (possibly a weapon) item when given the results of the image analysis, or that the baggage contains anything other than a rectangular item. It is to create a program that determines whether it is presumed that it is not included. Input The first line of input contains a single positive integer, which represents the number of datasets. Each dataset is given in the following format. > H W > Analysis result 1 > Analysis result 2 > ... > Analysis result H > H is the vertical size of the image, and W is an integer representing the horizontal size (1 <= h, w <= 50). Each line of the analysis result is composed of W characters, and the i-th character represents the analysis result in the grid region i-th from the left of the line. For the lattice region where the substance is detected, the material is represented by uppercase letters (A to Z). At this time, the same characters are used if they are made of the same material, and different characters are used if they are made of different materials. The lattice region where no substance was detected is represented by a dot (.). For all datasets, it is guaranteed that there are no more than seven material types. Output For each data set, output "SUSPICIOUS" if it contains items other than rectangles, and "SAFE" if not, on one line. Sample Input 6 1 1 .. 3 3 ... .W. ... 10 10 .......... .DDDDCC .. .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 .......... .DDDDDD ... .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE .... EEEEEEE ... .EEEEEEE .. ..EEEEEEE. ... EEEEEEE .... EEEEE. ..... EEE .. ...... E ... 16 50 ................................................................. ......... AAAAAAAAAAAAAAAAA ............................ .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA .... .... PPP .............. AAAAA.AAAAAAAAAAAAAAAA ....... .... PPP ................ A .... AAA.AAAAAAAAAA ........ .... PPP ........... IIIIIAAIIAIII.AAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIAAAAAAAAAAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIIIIIIII ... AAAAAAAAAAA ...... .... PPP .................. AAAAAAAAAAA ..... MMMMPPPMMMMMMMMMMMMMMM ............. AAAAAAAAAAA .... MMMMPPPMMMMMMMMMMMMMMM .............. AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............................ Output for the Sample Input SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS Example Input 6 1 1 . 3 3 ... .W. ... 10 10 .......... .DDDDCCC.. .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 .......... .DDDDDD... .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE.... EEEEEEE... .EEEEEEE.. ..EEEEEEE. ...EEEEEEE ....EEEEE. .....EEE.. ......E... 16 50 .................................................. .........AAAAAAAAAAAAAAAA......................... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.... ....PPP..............AAAAA.AAAAAAAAAAAAAAAA....... ....PPP................A....AAA.AAAAAAAAAA........ ....PPP...........IIIIIAAIIAIII.AAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIAAAAAAAAAAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIIIIIIII...AAAAAAAAAA...... ....PPP............................AAAAAAAAAA..... MMMMPPPMMMMMMMMMMMMMMM.............AAAAAAAAAAA.... MMMMPPPMMMMMMMMMMMMMMM..............AAAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM............................ Output SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS
instruction
0
84,963
23
169,926
"Correct Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 998244353 dd = [(0,-1),(1,0),(0,1),(-1,0)] ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)] def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def pf(s): return print(s, flush=True) def main(): rr = [] n = I() ni = 0 while ni < n: ni += 1 h,w = LI() s = [[c for c in S()] for _ in range(h)] d = collections.defaultdict(lambda: [inf,-inf,inf,-inf]) for i in range(h): for j in range(w): if s[i][j] == '.': continue t = d[s[i][j]] if t[0] > i: t[0] = i if t[1] < i: t[1] = i if t[2] > j: t[2] = j if t[3] < j: t[3] = j f = True k = set(d.keys()) while f: f = False for t in list(k): hi,ha,wi,wa = d[t] ff = True for i in range(hi,ha+1): for j in range(wi,wa+1): if s[i][j] != t and s[i][j] != '?': ff = False break if not ff: break if ff: k.remove(t) f = True for i in range(hi,ha+1): for j in range(wi,wa+1): s[i][j] = '?' if not k: rr.append('SAFE') else: rr.append('SUSPICIOUS') return '\n'.join(map(str,rr)) print(main()) ```
output
1
84,963
23
169,927
Provide a correct Python 3 solution for this coding contest problem. This is the story of 20XX. The number of air passengers increased as a result of the stable energy supply by the renewable power network and the invention of liquefied synthetic fuel. However, the threat of terrorism by aircraft still exists, and the importance of fast and highly reliable automatic baggage inspection systems is increasing. Since it is actually difficult for an inspector to inspect all the baggage, we would like to establish a mechanism for the inspector to inspect only the baggage judged to be suspicious by the automatic inspection. At the request of the aviation industry, the International Cabin Protection Company investigated recent passenger baggage in order to develop a new automated inspection system. As a result of the investigation, it was found that the baggage of recent passengers has the following tendency. * Baggage is shaped like a rectangular parallelepiped with only one side short. * Items that ordinary passengers pack in their baggage and bring into the aircraft include laptop computers, music players, handheld game consoles, and playing cards, all of which are rectangular. * Individual items are packed so that their rectangular sides are parallel to the sides of the baggage. * On the other hand, weapons such as those used for terrorism have a shape very different from a rectangle. Based on the above survey results, we devised the following model for baggage inspection. Each piece of baggage is considered to be a rectangular parallelepiped container that is transparent to X-rays. It contains multiple items that are opaque to X-rays. Here, consider a coordinate system with the three sides of the rectangular parallelepiped as the x-axis, y-axis, and z-axis, irradiate X-rays in the direction parallel to the x-axis, and take an image projected on the y-z plane. The captured image is divided into grids of appropriate size, and the material of the item reflected in each grid area is estimated by image analysis. Since this company has a very high level of analysis technology and can analyze even the detailed differences in materials, it can be considered that the materials of the products are different from each other. When multiple items overlap in the x-axis direction, the material of the item that is in the foreground for each lattice region, that is, the item with the smallest x-coordinate is obtained. We also assume that the x-coordinates of two or more items are never equal. Your job can be asserted that it contains non-rectangular (possibly a weapon) item when given the results of the image analysis, or that the baggage contains anything other than a rectangular item. It is to create a program that determines whether it is presumed that it is not included. Input The first line of input contains a single positive integer, which represents the number of datasets. Each dataset is given in the following format. > H W > Analysis result 1 > Analysis result 2 > ... > Analysis result H > H is the vertical size of the image, and W is an integer representing the horizontal size (1 <= h, w <= 50). Each line of the analysis result is composed of W characters, and the i-th character represents the analysis result in the grid region i-th from the left of the line. For the lattice region where the substance is detected, the material is represented by uppercase letters (A to Z). At this time, the same characters are used if they are made of the same material, and different characters are used if they are made of different materials. The lattice region where no substance was detected is represented by a dot (.). For all datasets, it is guaranteed that there are no more than seven material types. Output For each data set, output "SUSPICIOUS" if it contains items other than rectangles, and "SAFE" if not, on one line. Sample Input 6 1 1 .. 3 3 ... .W. ... 10 10 .......... .DDDDCC .. .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 .......... .DDDDDD ... .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE .... EEEEEEE ... .EEEEEEE .. ..EEEEEEE. ... EEEEEEE .... EEEEE. ..... EEE .. ...... E ... 16 50 ................................................................. ......... AAAAAAAAAAAAAAAAA ............................ .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA .... .... PPP .............. AAAAA.AAAAAAAAAAAAAAAA ....... .... PPP ................ A .... AAA.AAAAAAAAAA ........ .... PPP ........... IIIIIAAIIAIII.AAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIAAAAAAAAAAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIIIIIIII ... AAAAAAAAAAA ...... .... PPP .................. AAAAAAAAAAA ..... MMMMPPPMMMMMMMMMMMMMMM ............. AAAAAAAAAAA .... MMMMPPPMMMMMMMMMMMMMMM .............. AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............................ Output for the Sample Input SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS Example Input 6 1 1 . 3 3 ... .W. ... 10 10 .......... .DDDDCCC.. .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 .......... .DDDDDD... .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE.... EEEEEEE... .EEEEEEE.. ..EEEEEEE. ...EEEEEEE ....EEEEE. .....EEE.. ......E... 16 50 .................................................. .........AAAAAAAAAAAAAAAA......................... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.... ....PPP..............AAAAA.AAAAAAAAAAAAAAAA....... ....PPP................A....AAA.AAAAAAAAAA........ ....PPP...........IIIIIAAIIAIII.AAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIAAAAAAAAAAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIIIIIIII...AAAAAAAAAA...... ....PPP............................AAAAAAAAAA..... MMMMPPPMMMMMMMMMMMMMMM.............AAAAAAAAAAA.... MMMMPPPMMMMMMMMMMMMMMM..............AAAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM............................ Output SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS
instruction
0
84,964
23
169,928
"Correct Solution: ``` import sys from collections import defaultdict def check(i): #メモ化再帰でやります if d[i] > 0: return d[i] d[i] = 1 #チェック状態 """長方形と仮定し、矛盾があればSUSPICUOUS""" for y in range(p[i][0],p[i][1]+1): for x in range(p[i][2],p[i][3]+1): if s[y][x] == ".": #長方形内部に空の部分が存在 d[i] = 3 #SUSPICUOUS return d[i] elif s[y][x] != i: #長方形内部に他の物質が存在 if d[s[y][x]] == 1: #その物質が現在チェック状態 d[i] = 3 #SUSPICUOUS(循環参照であるため。例:テストケース4) return d[i] c = check(s[y][x]) #再帰でそいつの状態をみる if c == 3: #SUSPICUOUS d[i] = 3 #SUSPICUOUS return d[i] d[i] = 2 #SAFE return 2 n = int(sys.stdin.readline()) for _ in range(n): h,w = map(int, sys.stdin.readline().split()) s = [sys.stdin.readline() for i in range(h)] p = defaultdict(list) """p[0]:上端,p[1]:下端,p[2]:左端,p[3]:右端""" for y in range(h): for x in range(w): if s[y][x] != "." and len(p[s[y][x]]) < 1: p[s[y][x]].append(y) for y in range(h)[::-1]: for x in range(w): if s[y][x] != "." and len(p[s[y][x]]) < 2: p[s[y][x]].append(y) for x in range(w): for y in range(h): if s[y][x] != "." and len(p[s[y][x]]) < 3: p[s[y][x]].append(x) for x in range(w)[::-1]: for y in range(h): if s[y][x] != "." and len(p[s[y][x]]) < 4: p[s[y][x]].append(x) d = defaultdict(lambda : 0) #メモ化再帰用のdict for i in p.keys(): if check(i) == 3: print("SUSPICIOUS") break else: print("SAFE") ```
output
1
84,964
23
169,929
Provide a correct Python 3 solution for this coding contest problem. This is the story of 20XX. The number of air passengers increased as a result of the stable energy supply by the renewable power network and the invention of liquefied synthetic fuel. However, the threat of terrorism by aircraft still exists, and the importance of fast and highly reliable automatic baggage inspection systems is increasing. Since it is actually difficult for an inspector to inspect all the baggage, we would like to establish a mechanism for the inspector to inspect only the baggage judged to be suspicious by the automatic inspection. At the request of the aviation industry, the International Cabin Protection Company investigated recent passenger baggage in order to develop a new automated inspection system. As a result of the investigation, it was found that the baggage of recent passengers has the following tendency. * Baggage is shaped like a rectangular parallelepiped with only one side short. * Items that ordinary passengers pack in their baggage and bring into the aircraft include laptop computers, music players, handheld game consoles, and playing cards, all of which are rectangular. * Individual items are packed so that their rectangular sides are parallel to the sides of the baggage. * On the other hand, weapons such as those used for terrorism have a shape very different from a rectangle. Based on the above survey results, we devised the following model for baggage inspection. Each piece of baggage is considered to be a rectangular parallelepiped container that is transparent to X-rays. It contains multiple items that are opaque to X-rays. Here, consider a coordinate system with the three sides of the rectangular parallelepiped as the x-axis, y-axis, and z-axis, irradiate X-rays in the direction parallel to the x-axis, and take an image projected on the y-z plane. The captured image is divided into grids of appropriate size, and the material of the item reflected in each grid area is estimated by image analysis. Since this company has a very high level of analysis technology and can analyze even the detailed differences in materials, it can be considered that the materials of the products are different from each other. When multiple items overlap in the x-axis direction, the material of the item that is in the foreground for each lattice region, that is, the item with the smallest x-coordinate is obtained. We also assume that the x-coordinates of two or more items are never equal. Your job can be asserted that it contains non-rectangular (possibly a weapon) item when given the results of the image analysis, or that the baggage contains anything other than a rectangular item. It is to create a program that determines whether it is presumed that it is not included. Input The first line of input contains a single positive integer, which represents the number of datasets. Each dataset is given in the following format. > H W > Analysis result 1 > Analysis result 2 > ... > Analysis result H > H is the vertical size of the image, and W is an integer representing the horizontal size (1 <= h, w <= 50). Each line of the analysis result is composed of W characters, and the i-th character represents the analysis result in the grid region i-th from the left of the line. For the lattice region where the substance is detected, the material is represented by uppercase letters (A to Z). At this time, the same characters are used if they are made of the same material, and different characters are used if they are made of different materials. The lattice region where no substance was detected is represented by a dot (.). For all datasets, it is guaranteed that there are no more than seven material types. Output For each data set, output "SUSPICIOUS" if it contains items other than rectangles, and "SAFE" if not, on one line. Sample Input 6 1 1 .. 3 3 ... .W. ... 10 10 .......... .DDDDCC .. .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 .......... .DDDDDD ... .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE .... EEEEEEE ... .EEEEEEE .. ..EEEEEEE. ... EEEEEEE .... EEEEE. ..... EEE .. ...... E ... 16 50 ................................................................. ......... AAAAAAAAAAAAAAAAA ............................ .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA .... .... PPP .............. AAAAA.AAAAAAAAAAAAAAAA ....... .... PPP ................ A .... AAA.AAAAAAAAAA ........ .... PPP ........... IIIIIAAIIAIII.AAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIAAAAAAAAAAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIIIIIIII ... AAAAAAAAAAA ...... .... PPP .................. AAAAAAAAAAA ..... MMMMPPPMMMMMMMMMMMMMMM ............. AAAAAAAAAAA .... MMMMPPPMMMMMMMMMMMMMMM .............. AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............................ Output for the Sample Input SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS Example Input 6 1 1 . 3 3 ... .W. ... 10 10 .......... .DDDDCCC.. .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 .......... .DDDDDD... .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE.... EEEEEEE... .EEEEEEE.. ..EEEEEEE. ...EEEEEEE ....EEEEE. .....EEE.. ......E... 16 50 .................................................. .........AAAAAAAAAAAAAAAA......................... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.... ....PPP..............AAAAA.AAAAAAAAAAAAAAAA....... ....PPP................A....AAA.AAAAAAAAAA........ ....PPP...........IIIIIAAIIAIII.AAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIAAAAAAAAAAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIIIIIIII...AAAAAAAAAA...... ....PPP............................AAAAAAAAAA..... MMMMPPPMMMMMMMMMMMMMMM.............AAAAAAAAAAA.... MMMMPPPMMMMMMMMMMMMMMM..............AAAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM............................ Output SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS
instruction
0
84,965
23
169,930
"Correct Solution: ``` n = int(input()) for _ in range(n): h, w = map(int, input().split()) mp = [list(input()) for _ in range(h)] range_dic = {} keys = [] for y in range(h): for x in range(w): c = mp[y][x] if c in range_dic: x1, x2, y1, y2 = range_dic[c] range_dic[c] = (min(x, x1), max(x, x2), min(y, y1), max(y, y2)) else: range_dic[c] = (x, x, y, y) keys.append(c) while keys: tmp = keys[:] for key in keys: break_flag = False x1, x2, y1, y2 = range_dic[key] for x in range(x1, x2 + 1): for y in range(y1, y2 + 1): if not mp[y][x] in (key, "#"): break_flag = True break if break_flag: break else: for y in range(y1, y2 + 1): mp[y][x1:x2 + 1] = ["#"] * (x2 - x1 + 1) keys.remove(key) if tmp == keys: print("SUSPICIOUS") break else: print("SAFE") ```
output
1
84,965
23
169,931
Provide a correct Python 3 solution for this coding contest problem. This is the story of 20XX. The number of air passengers increased as a result of the stable energy supply by the renewable power network and the invention of liquefied synthetic fuel. However, the threat of terrorism by aircraft still exists, and the importance of fast and highly reliable automatic baggage inspection systems is increasing. Since it is actually difficult for an inspector to inspect all the baggage, we would like to establish a mechanism for the inspector to inspect only the baggage judged to be suspicious by the automatic inspection. At the request of the aviation industry, the International Cabin Protection Company investigated recent passenger baggage in order to develop a new automated inspection system. As a result of the investigation, it was found that the baggage of recent passengers has the following tendency. * Baggage is shaped like a rectangular parallelepiped with only one side short. * Items that ordinary passengers pack in their baggage and bring into the aircraft include laptop computers, music players, handheld game consoles, and playing cards, all of which are rectangular. * Individual items are packed so that their rectangular sides are parallel to the sides of the baggage. * On the other hand, weapons such as those used for terrorism have a shape very different from a rectangle. Based on the above survey results, we devised the following model for baggage inspection. Each piece of baggage is considered to be a rectangular parallelepiped container that is transparent to X-rays. It contains multiple items that are opaque to X-rays. Here, consider a coordinate system with the three sides of the rectangular parallelepiped as the x-axis, y-axis, and z-axis, irradiate X-rays in the direction parallel to the x-axis, and take an image projected on the y-z plane. The captured image is divided into grids of appropriate size, and the material of the item reflected in each grid area is estimated by image analysis. Since this company has a very high level of analysis technology and can analyze even the detailed differences in materials, it can be considered that the materials of the products are different from each other. When multiple items overlap in the x-axis direction, the material of the item that is in the foreground for each lattice region, that is, the item with the smallest x-coordinate is obtained. We also assume that the x-coordinates of two or more items are never equal. Your job can be asserted that it contains non-rectangular (possibly a weapon) item when given the results of the image analysis, or that the baggage contains anything other than a rectangular item. It is to create a program that determines whether it is presumed that it is not included. Input The first line of input contains a single positive integer, which represents the number of datasets. Each dataset is given in the following format. > H W > Analysis result 1 > Analysis result 2 > ... > Analysis result H > H is the vertical size of the image, and W is an integer representing the horizontal size (1 <= h, w <= 50). Each line of the analysis result is composed of W characters, and the i-th character represents the analysis result in the grid region i-th from the left of the line. For the lattice region where the substance is detected, the material is represented by uppercase letters (A to Z). At this time, the same characters are used if they are made of the same material, and different characters are used if they are made of different materials. The lattice region where no substance was detected is represented by a dot (.). For all datasets, it is guaranteed that there are no more than seven material types. Output For each data set, output "SUSPICIOUS" if it contains items other than rectangles, and "SAFE" if not, on one line. Sample Input 6 1 1 .. 3 3 ... .W. ... 10 10 .......... .DDDDCC .. .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 .......... .DDDDDD ... .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE .... EEEEEEE ... .EEEEEEE .. ..EEEEEEE. ... EEEEEEE .... EEEEE. ..... EEE .. ...... E ... 16 50 ................................................................. ......... AAAAAAAAAAAAAAAAA ............................ .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA .... .... PPP .............. AAAAA.AAAAAAAAAAAAAAAA ....... .... PPP ................ A .... AAA.AAAAAAAAAA ........ .... PPP ........... IIIIIAAIIAIII.AAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIAAAAAAAAAAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIIIIIIII ... AAAAAAAAAAA ...... .... PPP .................. AAAAAAAAAAA ..... MMMMPPPMMMMMMMMMMMMMMM ............. AAAAAAAAAAA .... MMMMPPPMMMMMMMMMMMMMMM .............. AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............................ Output for the Sample Input SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS Example Input 6 1 1 . 3 3 ... .W. ... 10 10 .......... .DDDDCCC.. .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 .......... .DDDDDD... .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE.... EEEEEEE... .EEEEEEE.. ..EEEEEEE. ...EEEEEEE ....EEEEE. .....EEE.. ......E... 16 50 .................................................. .........AAAAAAAAAAAAAAAA......................... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.... ....PPP..............AAAAA.AAAAAAAAAAAAAAAA....... ....PPP................A....AAA.AAAAAAAAAA........ ....PPP...........IIIIIAAIIAIII.AAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIAAAAAAAAAAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIIIIIIII...AAAAAAAAAA...... ....PPP............................AAAAAAAAAA..... MMMMPPPMMMMMMMMMMMMMMM.............AAAAAAAAAAA.... MMMMPPPMMMMMMMMMMMMMMM..............AAAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM............................ Output SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS
instruction
0
84,966
23
169,932
"Correct Solution: ``` n = int(input()) for _ in range(n): h, w = map(int, input().split()) mp = [list(input()) for _ in range(h)] range_dic = {} keys = [] for y in range(h): for x in range(w): c = mp[y][x] if c in range_dic: x1, x2, y1, y2 = range_dic[c] range_dic[c] = (min(x, x1), max(x, x2), min(y, y1), max(y, y2)) else: range_dic[c] = (x, x, y, y) keys.append(c) while keys: tmp = keys[:] for key in keys: break_flag = False x1, x2, y1, y2 = range_dic[key] for x in range(x1, x2 + 1): for y in range(y1, y2 + 1): if not mp[y][x] in (key, "#"): break_flag = True break if break_flag: break else: for x in range(x1, x2 + 1): for y in range(y1, y2 + 1): mp[y][x] = "#" keys.remove(key) if tmp == keys: print("SUSPICIOUS") break else: print("SAFE") ```
output
1
84,966
23
169,933
Provide a correct Python 3 solution for this coding contest problem. This is the story of 20XX. The number of air passengers increased as a result of the stable energy supply by the renewable power network and the invention of liquefied synthetic fuel. However, the threat of terrorism by aircraft still exists, and the importance of fast and highly reliable automatic baggage inspection systems is increasing. Since it is actually difficult for an inspector to inspect all the baggage, we would like to establish a mechanism for the inspector to inspect only the baggage judged to be suspicious by the automatic inspection. At the request of the aviation industry, the International Cabin Protection Company investigated recent passenger baggage in order to develop a new automated inspection system. As a result of the investigation, it was found that the baggage of recent passengers has the following tendency. * Baggage is shaped like a rectangular parallelepiped with only one side short. * Items that ordinary passengers pack in their baggage and bring into the aircraft include laptop computers, music players, handheld game consoles, and playing cards, all of which are rectangular. * Individual items are packed so that their rectangular sides are parallel to the sides of the baggage. * On the other hand, weapons such as those used for terrorism have a shape very different from a rectangle. Based on the above survey results, we devised the following model for baggage inspection. Each piece of baggage is considered to be a rectangular parallelepiped container that is transparent to X-rays. It contains multiple items that are opaque to X-rays. Here, consider a coordinate system with the three sides of the rectangular parallelepiped as the x-axis, y-axis, and z-axis, irradiate X-rays in the direction parallel to the x-axis, and take an image projected on the y-z plane. The captured image is divided into grids of appropriate size, and the material of the item reflected in each grid area is estimated by image analysis. Since this company has a very high level of analysis technology and can analyze even the detailed differences in materials, it can be considered that the materials of the products are different from each other. When multiple items overlap in the x-axis direction, the material of the item that is in the foreground for each lattice region, that is, the item with the smallest x-coordinate is obtained. We also assume that the x-coordinates of two or more items are never equal. Your job can be asserted that it contains non-rectangular (possibly a weapon) item when given the results of the image analysis, or that the baggage contains anything other than a rectangular item. It is to create a program that determines whether it is presumed that it is not included. Input The first line of input contains a single positive integer, which represents the number of datasets. Each dataset is given in the following format. > H W > Analysis result 1 > Analysis result 2 > ... > Analysis result H > H is the vertical size of the image, and W is an integer representing the horizontal size (1 <= h, w <= 50). Each line of the analysis result is composed of W characters, and the i-th character represents the analysis result in the grid region i-th from the left of the line. For the lattice region where the substance is detected, the material is represented by uppercase letters (A to Z). At this time, the same characters are used if they are made of the same material, and different characters are used if they are made of different materials. The lattice region where no substance was detected is represented by a dot (.). For all datasets, it is guaranteed that there are no more than seven material types. Output For each data set, output "SUSPICIOUS" if it contains items other than rectangles, and "SAFE" if not, on one line. Sample Input 6 1 1 .. 3 3 ... .W. ... 10 10 .......... .DDDDCC .. .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 .......... .DDDDDD ... .DDDDCC .. .DDDDCC .. ADDDDCCC .. AAA .. CCC .. AAABB BBC .. AAABBBB ... ..BBBBB ... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE .... EEEEEEE ... .EEEEEEE .. ..EEEEEEE. ... EEEEEEE .... EEEEE. ..... EEE .. ...... E ... 16 50 ................................................................. ......... AAAAAAAAAAAAAAAAA ............................ .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ..... .... PPP ... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA .... .... PPP .............. AAAAA.AAAAAAAAAAAAAAAA ....... .... PPP ................ A .... AAA.AAAAAAAAAA ........ .... PPP ........... IIIIIAAIIAIII.AAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIAAAAAAAAAAAAAAAAAA ........ ..CCCCCCCCCCCCCC ... IIIIIIIIIIIII ... AAAAAAAAAAA ...... .... PPP .................. AAAAAAAAAAA ..... MMMMPPPMMMMMMMMMMMMMMM ............. AAAAAAAAAAA .... MMMMPPPMMMMMMMMMMMMMMM .............. AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............... AAAAAAAAAAA ... MMMMMMMMMMMMMMMMMMMMMM ............................ Output for the Sample Input SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS Example Input 6 1 1 . 3 3 ... .W. ... 10 10 .......... .DDDDCCC.. .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 .......... .DDDDDD... .DDDDCCC.. .DDDDCCC.. ADDDDCCC.. AAA..CCC.. AAABBBBC.. AAABBBB... ..BBBBB... .......... 10 10 R..E..C.T. R.EEE.C.T. .EEEEE.... EEEEEEE... .EEEEEEE.. ..EEEEEEE. ...EEEEEEE ....EEEEE. .....EEE.. ......E... 16 50 .................................................. .........AAAAAAAAAAAAAAAA......................... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA..... ....PPP...AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.... ....PPP..............AAAAA.AAAAAAAAAAAAAAAA....... ....PPP................A....AAA.AAAAAAAAAA........ ....PPP...........IIIIIAAIIAIII.AAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIAAAAAAAAAAAAAAAAAA........ ..CCCCCCCCCCCCC...IIIIIIIIIIIII...AAAAAAAAAA...... ....PPP............................AAAAAAAAAA..... MMMMPPPMMMMMMMMMMMMMMM.............AAAAAAAAAAA.... MMMMPPPMMMMMMMMMMMMMMM..............AAAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM...............AAAAAAAAAA... MMMMMMMMMMMMMMMMMMMMMM............................ Output SAFE SAFE SAFE SUSPICIOUS SUSPICIOUS SUSPICIOUS
instruction
0
84,967
23
169,934
"Correct Solution: ``` from collections import defaultdict,deque import sys,heapq,bisect,math,itertools,string,queue,copy,time sys.setrecursionlimit(10**8) INF = float('inf') mod = 10**9+7 eps = 10**-7 def inp(): return int(input()) def inpl(): return list(map(int, input().split())) def inpl_str(): return list(input().split()) def dfs(s,cnt): global ans if cnt > 10: ans = False return for t in lines[s]: dfs(t,cnt+1) N = inp() for _ in range(N): H,W = inpl() MAP = [['.']*(W+2)] + [['.']+list(input())+['.'] for y in range(H)] + [['.']*(W+2)] als = set([]) almm = [[INF,0,INF,0] for _ in range(30)] for y in range(1,H+1): for x in range(1,W+1): tmp = MAP[y][x] if tmp != '.': tmp = ord(tmp) - ord('A') als.add(tmp) almm[tmp][0] = min(almm[tmp][0],x) almm[tmp][1] = max(almm[tmp][1],x) almm[tmp][2] = min(almm[tmp][2],y) almm[tmp][3] = max(almm[tmp][3],y) ans = True lines = defaultdict(set) for a in als: xl,xr,yl,yr = almm[a] alpha = chr(a+ord('A')) for x in range(xl,xr+1): for y in range(yl,yr+1): if MAP[y][x] == '.': ans = False break elif MAP[y][x] != alpha: lines[a].add(ord(MAP[y][x])-ord('A')) for a in als: dfs(a,0) if not ans: print('SUSPICIOUS') else: print('SAFE') ```
output
1
84,967
23
169,935
Provide a correct Python 3 solution for this coding contest problem. You are recording a result of a secret experiment, which consists of a large set of N-dimensional vectors. Since the result may become very large, you are thinking of compressing it. Fortunately you already have a good compression method for vectors with small absolute values, all you have to do is to preprocess the vectors and make them small. You can record the set of vectors in any order you like. Let's assume you process them in the order v_1, v_2,..., v_M. Each vector v_i is recorded either as is, or as a difference vector. When it is recorded as a difference, you can arbitrarily pick up an already chosen vector v_j (j<i) and a real value r. Then the actual vector value recorded is (v_i - r v_j). The values of r and j do not affect the compression ratio so much, so you don't have to care about them. Given a set of vectors, your task is to write a program that calculates the minimum sum of the squared length of the recorded vectors. Input The input is like the following style. N M v_{1,1} v_{1,2} ... v_{1,N} ... v_{M,1} v_{M,2} ... v_{M,N} The first line contains two integers N and M (1 \leq N, M \leq 100), where N is the dimension of each vector, and M is the number of the vectors. Each of the following M lines contains N floating point values v_{i,j} (-1.0 \leq v_{i,j} \leq 1.0) which represents the j-th element value of the i-th vector. Output Output the minimum sum of the squared length of the recorded vectors. The output should not contain an absolute error greater than 10^{-6}. Examples Input 2 3 1.0 1.0 -1.0 0.0 0.5 0.5 Output 1.0 Input 1 1 1.0 Output 1.0 Input 4 3 1.0 1.0 0.0 0.0 -1.0 0.0 -1.0 0.0 0.5 0.5 0.5 0.5 Output 3.0
instruction
0
84,972
23
169,944
"Correct Solution: ``` import sys readline = sys.stdin.readline write = sys.stdout.write def calc(V, es, r): mins = [(10**18, -1)]*V for s, t, w in es: mins[t] = min(mins[t], (w, s)) mins[r] = (-1, -1) group = [0]*V comp = [0]*V cnt = 0 used = [0]*V for v in range(V): if not used[v]: chain = [] cur = v while cur!=-1 and not used[cur]: chain.append(cur) used[cur] = 1 cur = mins[cur][1] if cur!=-1: cycle = 0 for e in chain: group[e] = cnt if e==cur: cycle = 1 comp[cnt] = 1 if not cycle: cnt += 1 if cycle: cnt += 1 else: for e in chain: group[e] = cnt cnt += 1 if cnt == V: return sum(map(lambda x:x[0], mins)) + 1 res = sum(mins[v][0] for v in range(V) if v!=r and comp[group[v]]) n_es = [] for s, t, w in es: gs = group[s]; gt = group[t] if gs == gt: continue if comp[gt]: n_es.append((gs, gt, w - mins[t][0])) else: n_es.append((gs, gt, w)) return res + calc(cnt, n_es, group[r]) def solve(): N, M = map(int, readline().split()) V = [] D = [] for i in range(M): *Vi, = map(float, readline().split()) d = sum(e**2 for e in Vi) if d <= 1e-9: continue V.append(Vi) D.append(d) M = len(V) E = [] for i in range(M): Vi = V[i] for j in range(M): if i == j: continue Vj = V[j] t = 0 for k in range(N): t += Vi[k] * Vj[k] r = t / (D[j]) c = 0 for k in range(N): c += (Vi[k] - r*Vj[k])**2 E.append((j+1, i+1, c)) E.append((0, i+1, D[i])) write("%.16f\n" % calc(M+1, E, 0)) solve() ```
output
1
84,972
23
169,945
Provide a correct Python 3 solution for this coding contest problem. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000
instruction
0
84,982
23
169,964
"Correct Solution: ``` def cross(a: complex, b: complex) -> float: return a.real * b.imag - a.imag * b.real def cross_point(c: complex, d: complex) -> complex: global lt, lv vec = d - c v1 = cross(lv, vec) v2 = cross(lv, lt - c) return c + v2 / v1 * vec if __name__ == "__main__": n = int(input()) points = [complex(*map(int, input().split())) for _ in range(n)] point0 = points.pop(0) points.append(point0) q = int(input()) while q: x1, y1, x2, y2 = map(int, input().split()) ls, lt = (x1 + 1j * y1, x2 + 1j * y2) lv = lt - ls area = 0.0 prev = point0 prev_flag = 0 <= cross(lv, prev - ls) cp1, cp2 = None, None for p in points: curr_flag = 0 <= cross(lv, p - ls) if prev_flag and curr_flag: area += cross(prev, p) elif prev_flag != curr_flag: cp = cross_point(prev, p) if prev_flag: area += cross(prev, cp) cp1 = cp else: area += cross(cp, p) cp2 = cp prev, prev_flag = p, curr_flag if cp1 is not None and cp2 is not None: area += cross(cp1, cp2) print(area / 2) q -= 1 ```
output
1
84,982
23
169,965
Provide a correct Python 3 solution for this coding contest problem. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000
instruction
0
84,983
23
169,966
"Correct Solution: ``` import sys readline = sys.stdin.readline write = sys.stdout.write def cross3(O, A, B): ox, oy = O; ax, ay = A; bx, by = B return (ax - ox) * (by - oy) - (bx - ox) * (ay - oy) def cross_point(p0, p1, q0, q1): x0, y0 = p0; x1, y1 = p1 x2, y2 = q0; x3, y3 = q1 dx0 = x1 - x0; dy0 = y1 - y0 dx1 = x3 - x2; dy1 = y3 - y2 s = (y0-y2)*dx1 - (x0-x2)*dy1 sm = dx0*dy1 - dy0*dx1 if -EPS < sm < EPS: return None return x0 + s*dx0/sm, y0 + s*dy0/sm EPS = 1e-9 def convex_cut(P, line): q0, q1 = line N = len(P) Q = [] for i in range(N): p0 = P[i-1]; p1 = P[i] cv0 = cross3(q0, q1, p0) cv1 = cross3(q0, q1, p1) if cv0 * cv1 < EPS: v = cross_point(q0, q1, p0, p1) if v is not None: Q.append(v) if cv1 > -EPS: Q.append(p1) return Q def polygon_area(P): s = 0 N = len(P) for i in range(N): p0 = P[i-1]; p1 = P[i] s += p0[0]*p1[1] - p0[1]*p1[0] return abs(s) / 2 def solve(): N = int(readline()) P = [list(map(int, readline().split())) for i in range(N)] Q = int(readline()) for i in range(Q): x0, y0, x1, y1 = map(int, readline().split()) P0 = convex_cut(P, ((x0, y0), (x1, y1))) write("%.16f\n" % polygon_area(P0)) solve() ```
output
1
84,983
23
169,967
Provide a correct Python 3 solution for this coding contest problem. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000
instruction
0
84,984
23
169,968
"Correct Solution: ``` import cmath EPS = 1e-6 #外積 def OuterProduct(one, two): tmp = one.conjugate() * two return tmp.imag #点が直線上にあるか def IsOnLine(point, begin, end): return abs(OuterProduct(begin-point, end-point)) <= EPS #3点が反時計回りか #一直線上のときの例外処理できていない→F def CCW(p, q, r): one, two = q-p, r-q if OuterProduct(one, two) > EPS: return True else: return False def Crosspoint(a, b, c, d): if abs(OuterProduct(b-a, d-c)) <= EPS: return False else: u = OuterProduct(c-a, d-a) / OuterProduct(b-a, d-c) return (1-u)*a + u*b #凹多角形の面積(多角形は反時計回りに与えられる) def Area(dots): res = 0 for i in range(len(dots)-1): res += OuterProduct(dots[i], dots[i+1]) res += OuterProduct(dots[-1], dots[0]) return res/2 n = int(input()) dots = [] for _ in range(n): x, y = map(float, input().split()) dots.append(complex(x, y)) q = int(input()) for _ in range(q): x, y, z, w = map(int, input().split()) p1, p2 = complex(x, y), complex(z, w) res = [] for i in range(-1, n-1): if IsOnLine(dots[i], p1, p2) or CCW(p1, p2, dots[i]): res.append(dots[i]) if not IsOnLine(dots[i], p1, p2) and not IsOnLine(dots[i+1], p1, p2) and (CCW(p1, p2, dots[i]) != CCW(p1, p2, dots[i+1])): res.append(Crosspoint(dots[i], dots[i+1], p1, p2)) if not res: print(0) else: print(Area(res)) ```
output
1
84,984
23
169,969
Provide a correct Python 3 solution for this coding contest problem. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000
instruction
0
84,985
23
169,970
"Correct Solution: ``` #!/usr/bin/env python3 # CGL_4_C: Convex Polygon Convex Cut def cut(ps, p0, p1): polygon = [] for p2, p3 in zip(ps, ps[1:] + [ps[0]]): if cross(p0, p1, p0, p2) >= 0: polygon.append(p2) if intersect(p0, p1, p2, p3): p = intersect_point(p0, p1, p2, p3) if not same(p, p2): polygon.append(p) return polygon def intersect(p0, p1, p2, p3): if cross(p0, p1, p0, p2) >= 0 and cross(p0, p1, p0, p3) < 0: return True elif cross(p0, p1, p0, p2) <= 0 and cross(p0, p1, p0, p3) > 0: return True return False def same(p0, p1): x0, y0 = p0 x1, y1 = p1 return abs(x0 - x1) < 1e-10 and abs(y0 - y1) < 1e-10 def intersect_point(p0, p1, p2, p3): d1 = abs(cross(p0, p1, p0, p2)) d2 = abs(cross(p0, p1, p0, p3)) t = d1 / (d1 + d2) x2, y2 = p2 x3, y3 = p3 return x2 + (x3 - x2) * t, y2 + (y3 - y2) * t def area(ps): """Calculate area of a polygon. >>> area([(0, 0), (2, 2), (-1, 1)]) 2.0 >>> area([]) 0.0 >>> area([(0, 0)]) 0.0 >>> area([(0, 0), (1, 0)]) 0.0 """ area = 0.0 if ps: for p0, p1 in zip(ps, ps[1:]+[ps[0]]): area += cross((0, 0), p0, p0, p1) return area / 2 def cross(p0, p1, p2, p3): x0, y0 = p0 x1, y1 = p1 x2, y2 = p2 x3, y3 = p3 return (x1-x0)*(y3-y2) - (x3-x2)*(y1-y0) def run(): n = int(input()) ps = [] for _ in range(n): x, y = [int(i) for i in input().split()] ps.append((x, y)) q = int(input()) for _ in range(q): x1, y1, x2, y2 = [int(i) for i in input().split()] print("{:.10f}".format(area(cut(ps, (x1, y1), (x2, y2))))) if __name__ == '__main__': run() ```
output
1
84,985
23
169,971
Provide a correct Python 3 solution for this coding contest problem. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000
instruction
0
84,986
23
169,972
"Correct Solution: ``` from sys import stdin readline = stdin.readline class vector: 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 ccw(a, b, c): b -= a c -= a if vector.cross(b, c) > 0: return 1 if vector.cross(b, c) < 0: return 2 if vector.dot(b, c) < 0: return 3 if abs(b) < abs(c): return 4 return 5 def polygon(p): if len(p) < 3: return 0 return 0.5 * sum(vector.cross(p[i - 1], p[i]) for i in range(len(p))) def intersection(p1, p2, p3, p4): a1 = p4 - p2 b1 = p2 - p3 b2 = p1 - p2 s1 = vector.cross(a1, b2) / 2 s2 = vector.cross(a1, b1) / 2 if s1 + s2 == 0: return 0 c1 = p1 + (p3 - p1) * s1 / (s1 + s2) return c1 def main(): n = int(readline()) p = [map(float, readline().split()) for _ in range(n)] p = [x + y * 1j for x, y in p] q = int(readline()) for _ in range(q): p1x, p1y, p2x, p2y = map(float, readline().split()) p1, p2 = p1x + p1y * 1j, p2x + p2y * 1j pre_tmp = vector.ccw(p[-1], p1, p2) left = [] for i in range(len(p)): tmp = vector.ccw(p[i], p1, p2) if pre_tmp != tmp and all(i in (1, 2) for i in (pre_tmp, tmp)): c1 = vector.intersection(p1, p[i - 1], p2, p[i]) left.append(c1) if tmp != 2: left.append(p[i]) pre_tmp = tmp print('{:.6f}'.format(vector.polygon(left))) main() ```
output
1
84,986
23
169,973
Provide a correct Python 3 solution for this coding contest problem. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000
instruction
0
84,987
23
169,974
"Correct Solution: ``` def cross(a, b): return a.real * b.imag - a.imag * b.real def cross_point(c, d): l = d - c v1 = cross(lv, l) v2 = cross(lv, lt - c) return c + v2 / v1 * l n = int(input()) points = [complex(*map(int, input().split())) for _ in range(n)] point0 = points.pop(0) points.append(point0) q = int(input()) while q: x1, y1, x2, y2 = map(int, input().split()) ls, lt = (x1 + 1j * y1, x2 + 1j * y2) lv = lt - ls area = 0 prev = point0 prev_flag = cross(lv, prev - ls) >= 0 cp1, cp2 = None, None for p in points: curr_flag = cross(lv, p - ls) >= 0 if prev_flag and curr_flag: area += cross(prev, p) elif prev_flag != curr_flag: cp = cross_point(prev, p) if prev_flag: area += cross(prev, cp) cp1 = cp else: area += cross(cp, p) cp2 = cp prev, prev_flag = p, curr_flag if cp1 is not None and cp2 is not None: area += cross(cp1, cp2) print(area / 2) q -= 1 ```
output
1
84,987
23
169,975
Provide a correct Python 3 solution for this coding contest problem. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000
instruction
0
84,988
23
169,976
"Correct Solution: ``` # cross point def cross(c1, c2): return c1.real * c2.imag - c1.imag * c2.real def cross_point(p1, p2, p3, p4): # p1 and p2 are points on a segment. # p3 and p4 are points on the other segment. base = p4 - p3 hypo1 = p1 - p3 hypo2 = p2 - p3 d1 = cross(base, hypo1) / abs(base) d2 = cross(base, hypo2) / abs(base) cp = p1 + d1 / (d1 - d2) * (p2 - p1) return cp # area of a triangle def _area_of_triangle(c1, c2, c3): v1 = c2 - c1 v2 = c3 - c1 return abs(v1.real * v2.imag - v1.imag * v2.real) / 2 # convex cut def convex_cut(points, c1, c2): points.append(points[0]) ref_vec = c2 - c1 cross_point1 = None flag = 0 # Detection of one intersection point for i, segment in enumerate(zip(points, points[1:])): p1, p2 = segment cross1 = cross(ref_vec, p1 - c1) cross2 = cross(ref_vec, p2 - c1) flag += cross1 if cross1 <= 0 and cross2 > 0: cross_point1 = cross_point(c1, c2, p1, p2) points = points[i+1:] break elif cross1 > 0 and cross2 <= 0: cross_point1 = cross_point(c1, c2, p1, p2) points = points[i::-1] + points[:i:-1] break # Processing when there is no intersection point if cross_point1 == None: if flag > 0: cross_point1 = points[0] points = points[1:] else: return 0 # find area cut_area = 0 for p1, p2 in zip(points, points[1:]): if cross(ref_vec, p1 - c1) * cross(ref_vec, p2 - c1) <= 0: cross_point2 = cross_point(c1, c2, p1, p2) cut_area += _area_of_triangle(cross_point1, cross_point2, p1) break else: cut_area += _area_of_triangle(cross_point1, p1, p2) return cut_area # acceptance of input import sys file_input = sys.stdin n = int(file_input.readline()) def string_to_complex(s): x, y = map(float, s.split()) return x + y * 1j G = [string_to_complex(file_input.readline()) for i in range(n)] # output q = int(file_input.readline()) for line in file_input: p1x, p1y, p2x, p2y = map(int, line.split()) p1 = p1x + p1y * 1j p2 = p2x + p2y * 1j ans = convex_cut(G.copy(), p1, p2) print("{:f}".format(ans)) ```
output
1
84,988
23
169,977
Provide a correct Python 3 solution for this coding contest problem. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000
instruction
0
84,989
23
169,978
"Correct Solution: ``` from sys import stdin readline = stdin.readline class vector: 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 ccw(a, b, c): b -= a c -= a if vector.cross(b, c) > 0: return 1 if vector.cross(b, c) < 0: return 2 if vector.dot(b, c) < 0: return 3 if abs(b) < abs(c): return 4 return 5 def polygon(p): if len(p) < 3: return 0 return 0.5 * sum(vector.cross(p[i - 1], p[i]) for i in range(len(p))) def intersection(p1, p2, p3, p4): a1 = p4 - p2 b1 = p2 - p3 b2 = p1 - p2 s1 = vector.cross(a1, b2) / 2 s2 = vector.cross(a1, b1) / 2 if s1 + s2 == 0: return 0 c1 = p1 + (p3 - p1) * s1 / (s1 + s2) return c1 def main(): n = int(readline()) p = [map(float, readline().split()) for _ in range(n)] p = [x + y * 1j for x, y in p] q = int(readline()) for _ in range(q): p1x, p1y, p2x, p2y = map(float, readline().split()) p1, p2 = p1x + p1y * 1j, p2x + p2y * 1j pre_tmp = vector.ccw(p[-1], p1, p2) left = [] for i in range(len(p)): tmp = vector.ccw(p[i], p1, p2) if pre_tmp != tmp and all(i in (1, 2) for i in (pre_tmp, tmp)): c1 = vector.intersection(p1, p[i - 1], p2, p[i]) left.append(c1) if tmp != 2: left.append(p[i]) pre_tmp = tmp print('{:.6f}'.format(vector.polygon(left))) import sys if sys.hexversion >= 0x030203F0: main() else: print('Error') ```
output
1
84,989
23
169,979
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000 Submitted Solution: ``` #!/usr/bin/python3 import array from fractions import Fraction import functools import itertools import math import os import sys def main(): N = read_int() P = [Vec(*read_ints()) for _ in range(N)] Q = read_int() for _ in range(Q): x1, y1, x2, y2 = read_ints() print(solve(N, P, Vec(x1, y1), Vec(x2, y2))) def solve(N, P, A, B): b = B - A P = [p - A for p in P] ccw = 0 cw = 0 for p in P: c = b.cross(p) if c >= 0: ccw += 1 if c <= 0: cw += 1 if ccw == N: return float(poly_area(P)) if cw == N: return 0 cross_points = [] for i in range(N): j = (i + 1) % N p = P[i] q = P[j] qp = q - p cross_qp_b = qp.cross(b) if cross_qp_b == 0: continue k = Fraction(b.cross(p), cross_qp_b) if 0 < k <= 1: t = Fraction(p.cross(qp), b.cross(qp)) cross_points.append((t, i, k)) cross_points.sort() _, i1, k1 = cross_points[0] _, i2, k2 = cross_points[1] x1 = P[i1] + k1 * (P[(i1 + 1) % N] - P[i1]) x2 = P[i2] + k2 * (P[(i2 + 1) % N] - P[i2]) Q = [x2] j = (i2 + 1) % N while j != i1: Q.append(P[j]) j = (j + 1) % N Q.append(P[i1]) Q.append(x1) return float(poly_area(Q)) def poly_area(P): N = len(P) a = 0 for i in range(1, N - 1): a += Fraction((P[i + 1] - P[i]).cross(P[0] - P[i + 1]), 2) return a ############################################################################### # AUXILIARY FUNCTIONS class Vec(object): def __init__(self, x, y): self.x = x self.y = y super().__init__() def __add__(self, other): return Vec(self.x + other.x, self.y + other.y) def __sub__(self, other): return Vec(self.x - other.x, self.y - other.y) def __mul__(self, scalar): return Vec(self.x * scalar, self.y * scalar) def __rmul__(self, scalar): return Vec(self.x * scalar, self.y * scalar) def __truediv__(self, scalar): return Vec(self.x / scalar, self.y / scalar) def __iadd__(self, other): self.x += other.x self.y += other.y return self def __isub__(self, other): self.x -= other.x self.y -= other.y return self def __imul__(self, scalar): self.x *= scalar self.y *= scalar return self def __idiv__(self, scalar): self.x /= scalar self.y /= scalar return self def __neg__(self): return Vec(-self.x, -self.y) def __eq__(self, other): return self.x == other.x and self.y == other.y def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash('Vec', self.x, self.y) def dot(self, other): return self.x * other.x + self.y * other.y def cross(self, other): return self.x * other.y - self.y * other.x def abs2(self): return self.x * self.x + self.y * self.y def __abs__(self): return math.sqrt(float(self.abs2())) def __repr__(self): return '({}, {})'.format(self.x, self.y) DEBUG = 'DEBUG' in os.environ def inp(): return sys.stdin.readline().rstrip() def read_int(): return int(inp()) def read_ints(): return [int(e) for e in inp().split()] def dprint(*value, sep=' ', end='\n'): if DEBUG: print(*value, sep=sep, end=end) if __name__ == '__main__': main() ```
instruction
0
84,990
23
169,980
Yes
output
1
84,990
23
169,981
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000 Submitted Solution: ``` import cmath import math 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-10 class Point: """ 2次元空間上の点 """ # 反時計回り側にある CCW_COUNTER_CLOCKWISE = 1 # 時計回り側にある CCW_CLOCKWISE = -1 # 線分の後ろにある CCW_ONLINE_BACK = 2 # 線分の前にある CCW_ONLINE_FRONT = -2 # 線分上にある CCW_ON_SEGMENT = 0 def __init__(self, c: complex): self.c = c @property def x(self): return self.c.real @property def y(self): return self.c.imag @staticmethod def from_rect(x: float, y: float): return Point(complex(x, y)) @staticmethod def from_polar(r: float, phi: float): return Point(cmath.rect(r, phi)) def __add__(self, p): """ :param Point p: """ return Point(self.c + p.c) def __iadd__(self, p): """ :param Point p: """ self.c += p.c return self def __sub__(self, p): """ :param Point p: """ return Point(self.c - p.c) def __isub__(self, p): """ :param Point p: """ self.c -= p.c return self def __mul__(self, f: float): return Point(self.c * f) def __imul__(self, f: float): self.c *= f return self def __truediv__(self, f: float): return Point(self.c / f) def __itruediv__(self, f: float): self.c /= f return self def __repr__(self): return "({}, {})".format(round(self.x, 10), round(self.y, 10)) def __neg__(self): return Point(-self.c) def __eq__(self, p): return abs(self.c - p.c) < EPS def __abs__(self): return abs(self.c) @staticmethod def ccw(a, b, c): """ 線分 ab に対する c の位置 線分上にあるか判定するだけなら on_segment とかのが速い Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_C&lang=ja :param Point a: :param Point b: :param Point c: """ b = b - a c = c - a det = b.det(c) if det > EPS: return Point.CCW_COUNTER_CLOCKWISE if det < -EPS: return Point.CCW_CLOCKWISE if b.dot(c) < -EPS: return Point.CCW_ONLINE_BACK if c.norm() - b.norm() > EPS: return Point.CCW_ONLINE_FRONT return Point.CCW_ON_SEGMENT def dot(self, p): """ 内積 :param Point p: :rtype: float """ return self.x * p.x + self.y * p.y def det(self, p): """ 外積 :param Point p: :rtype: float """ return self.x * p.y - self.y * p.x def dist(self, p): """ 距離 :param Point p: :rtype: float """ return abs(self.c - p.c) def norm(self): """ 原点からの距離 :rtype: float """ return abs(self.c) def phase(self): """ 原点からの角度 :rtype: float """ return cmath.phase(self.c) def angle(self, p, q): """ p に向いてる状態から q まで反時計回りに回転するときの角度 -pi <= ret <= pi :param Point p: :param Point q: :rtype: float """ return (cmath.phase(q.c - self.c) - cmath.phase(p.c - self.c) + PI) % TAU - PI def area(self, p, q): """ p, q となす三角形の面積 :param Point p: :param Point q: :rtype: float """ return abs((p - self).det(q - self) / 2) def projection_point(self, p, q, allow_outer=False): """ 線分 pq を通る直線上に垂線をおろしたときの足の座標 Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_A&lang=ja :param Point p: :param Point q: :param allow_outer: 答えが線分の間になくても OK :rtype: Point|None """ diff_q = q - p # 答えの p からの距離 r = (self - p).dot(diff_q) / abs(diff_q) # 線分の角度 phase = diff_q.phase() ret = Point.from_polar(r, phase) + p if allow_outer or (p - ret).dot(q - ret) < EPS: return ret return None def reflection_point(self, p, q): """ 直線 pq を挟んで反対にある点 Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_B&lang=ja :param Point p: :param Point q: :rtype: Point """ # 距離 r = abs(self - p) # pq と p-self の角度 angle = p.angle(q, self) # 直線を挟んで角度を反対にする angle = (q - p).phase() - angle return Point.from_polar(r, angle) + p def on_segment(self, p, q, allow_side=True): """ 点が線分 pq の上に乗っているか Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_C&lang=ja :param Point p: :param Point q: :param allow_side: 端っこでギリギリ触れているのを許容するか :rtype: bool """ if not allow_side and (self == p or self == q): return False # 外積がゼロ: 面積がゼロ == 一直線 # 内積がマイナス: p - self - q の順に並んでる return abs((p - self).det(q - self)) < EPS and (p - self).dot(q - self) < EPS class Line: """ 2次元空間上の直線 """ def __init__(self, a: float, b: float, c: float): """ 直線 ax + by + c = 0 """ self.a = a self.b = b self.c = c @staticmethod def from_gradient(grad: float, intercept: float): """ 直線 y = ax + b :param grad: 傾き :param intercept: 切片 :return: """ return Line(grad, -1, intercept) @staticmethod def from_segment(p1, p2): """ :param Point p1: :param Point p2: """ a = p2.y - p1.y b = p1.x - p2.x c = p2.y * (p2.x - p1.x) - p2.x * (p2.y - p1.y) return Line(a, b, c) @property def gradient(self): """ 傾き """ return INF if self.b == 0 else -self.a / self.b @property def intercept(self): """ 切片 """ return INF if self.b == 0 else -self.c / self.b def is_parallel_to(self, l): """ 平行かどうか Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A&lang=ja :param Line l: """ # 法線ベクトル同士の外積がゼロ return abs(Point.from_rect(self.a, self.b).det(Point.from_rect(l.a, l.b))) < EPS def is_orthogonal_to(self, l): """ 直行しているかどうか Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A&lang=ja :param Line l: """ # 法線ベクトル同士の内積がゼロ return abs(Point.from_rect(self.a, self.b).dot(Point.from_rect(l.a, l.b))) < EPS def intersection_point(self, l): """ 交差する点 Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_C&lang=ja :param Line l: :rtype: Point|None """ a1, b1, c1 = self.a, self.b, self.c a2, b2, c2 = l.a, l.b, l.c det = a1 * b2 - a2 * b1 if abs(det) < EPS: # 並行 return None x = (b1 * c2 - b2 * c1) / det y = (a2 * c1 - a1 * c2) / det return Point.from_rect(x, y) def dist(self, p): """ 他の点との最短距離 :param Point p: """ raise NotImplementedError() def has_point(self, p): """ p が直線上に乗っているかどうか :param Point p: """ return abs(self.a * p.x + self.b * p.y + self.c) < EPS class Segment: """ 2次元空間上の線分 """ def __init__(self, p1, p2): """ :param Point p1: :param Point p2: """ self.p1 = p1 self.p2 = p2 def norm(self): """ 線分の長さ """ return abs(self.p1 - self.p2) def phase(self): """ p1 を原点としたときの p2 の角度 """ return cmath.phase(self.p2 - self.p1) def is_parallel_to(self, s): """ 平行かどうか Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A&lang=ja :param Segment s: :return: """ # 外積がゼロ return abs((self.p1 - self.p2).det(s.p1 - s.p2)) < EPS def is_orthogonal_to(self, s): """ 直行しているかどうか Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A&lang=ja :param Segment s: :return: """ # 内積がゼロ return abs((self.p1 - self.p2).dot(s.p1 - s.p2)) < EPS def intersects_with(self, s, allow_side=True): """ 交差するかどうか Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_B&lang=ja :param Segment s: :param allow_side: 端っこでギリギリ触れているのを許容するか """ if self.is_parallel_to(s): # 並行なら線分の端点がもう片方の線分の上にあるかどうか return (s.p1.on_segment(self.p1, self.p2, allow_side) or s.p2.on_segment(self.p1, self.p2, allow_side) or self.p1.on_segment(s.p1, s.p2, allow_side) or self.p2.on_segment(s.p1, s.p2, allow_side)) else: # allow_side ならゼロを許容する det_lower = EPS if allow_side else -EPS ok = True # self の両側に s.p1 と s.p2 があるか ok &= (self.p2 - self.p1).det(s.p1 - self.p1) * (self.p2 - self.p1).det(s.p2 - self.p1) < det_lower # s の両側に self.p1 と self.p2 があるか ok &= (s.p2 - s.p1).det(self.p1 - s.p1) * (s.p2 - s.p1).det(self.p2 - s.p1) < det_lower return ok def closest_point(self, p): """ 線分上の、p に最も近い点 :param Point p: """ # p からおろした垂線までの距離 d = (p - self.p1).dot(self.p2 - self.p1) / self.norm() # p1 より前 if d < EPS: return self.p1 # p2 より後 if -EPS < d - self.norm(): return self.p2 # 線分上 return Point.from_polar(d, (self.p2 - self.p1).phase()) + self.p1 def dist(self, p): """ 他の点との最短距離 :param Point p: """ return abs(p - self.closest_point(p)) def dist_segment(self, s): """ 他の線分との最短距離 Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_D&lang=ja :param Segment s: """ if self.intersects_with(s): return 0.0 return min( self.dist(s.p1), self.dist(s.p2), s.dist(self.p1), s.dist(self.p2), ) def has_point(self, p, allow_side=True): """ p が線分上に乗っているかどうか :param Point p: :param allow_side: 端っこでギリギリ触れているのを許容するか """ return p.on_segment(self.p1, self.p2, allow_side=allow_side) class Polygon: """ 2次元空間上の多角形 """ def __init__(self, points): """ :param list of Point points: """ self.points = points def iter2(self): """ 隣り合う2点を順に返すイテレータ :rtype: typing.Iterator[(Point, Point)] """ return zip(self.points, self.points[1:] + self.points[:1]) def iter3(self): """ 隣り合う3点を順に返すイテレータ :rtype: typing.Iterator[(Point, Point, Point)] """ return zip(self.points, self.points[1:] + self.points[:1], self.points[2:] + self.points[:2]) def area(self): """ 面積 Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_A&lang=ja """ # 外積の和 / 2 dets = [] for p, q in self.iter2(): dets.append(p.det(q)) return abs(math.fsum(dets)) / 2 def is_convex(self, allow_straight=False, allow_collapsed=False): """ 凸多角形かどうか Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_B&lang=ja :param allow_straight: 3点がまっすぐ並んでるのを許容するかどうか :param allow_collapsed: 面積がゼロの場合を許容するか """ ccw = [] for a, b, c in self.iter3(): ccw.append(Point.ccw(a, b, c)) ccw = set(ccw) if len(ccw) == 1: if ccw == {Point.CCW_CLOCKWISE}: return True if ccw == {Point.CCW_COUNTER_CLOCKWISE}: return True if allow_straight and len(ccw) == 2: if ccw == {Point.CCW_ONLINE_FRONT, Point.CCW_CLOCKWISE}: return True if ccw == {Point.CCW_ONLINE_FRONT, Point.CCW_COUNTER_CLOCKWISE}: return True if allow_collapsed and len(ccw) == 3: return ccw == {Point.CCW_ONLINE_FRONT, Point.CCW_ONLINE_BACK, Point.CCW_ON_SEGMENT} return False def has_point_on_edge(self, p): """ 指定した点が辺上にあるか :param Point p: :rtype: bool """ for a, b in self.iter2(): if p.on_segment(a, b): return True return False def contains(self, p, allow_on_edge=True): """ 指定した点を含むか Winding Number Algorithm https://www.nttpc.co.jp/technology/number_algorithm.html Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_C&lang=ja :param Point p: :param bool allow_on_edge: 辺上の点を許容するか """ angles = [] for a, b in self.iter2(): if p.on_segment(a, b): return allow_on_edge angles.append(p.angle(a, b)) # 一周以上するなら含む return abs(math.fsum(angles)) > EPS @staticmethod def convex_hull(points, allow_straight=False): """ 凸包。x が最も小さい点のうち y が最も小さい点から反時計回り。 Graham Scan O(N log N) Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_A&lang=ja :param list of Point points: :param allow_straight: 3点がまっすぐ並んでるのを許容するかどうか :rtype: list of Point """ points = points[:] points.sort(key=lambda p: (p.x, p.y)) # allow_straight なら 0 を許容する det_lower = -EPS if allow_straight else EPS sz = 0 #: :type: list of (Point|None) ret = [None] * (N * 2) for p in points: while sz > 1 and (ret[sz - 1] - ret[sz - 2]).det(p - ret[sz - 1]) < det_lower: sz -= 1 ret[sz] = p sz += 1 floor = sz for p in reversed(points[:-1]): while sz > floor and (ret[sz - 1] - ret[sz - 2]).det(p - ret[sz - 1]) < det_lower: sz -= 1 ret[sz] = p sz += 1 ret = ret[:sz - 1] if allow_straight and len(ret) > len(points): # allow_straight かつ全部一直線のときに二重にカウントしちゃう ret = points return ret @staticmethod def diameter(points): """ 直径 凸包構築 O(N log N) + カリパー法 O(N) Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_B&lang=ja :param list of Point points: """ # 反時計回り points = Polygon.convex_hull(points, allow_straight=False) if len(points) == 1: return 0.0 if len(points) == 2: return abs(points[0] - points[1]) # x軸方向に最も遠い点対 si = points.index(min(points, key=lambda p: (p.x, p.y))) sj = points.index(max(points, key=lambda p: (p.x, p.y))) n = len(points) ret = 0.0 # 半周回転 i, j = si, sj while i != sj or j != si: ret = max(ret, abs(points[i] - points[j])) ni = (i + 1) % n nj = (j + 1) % n # 2つの辺が並行になる方向にずらす if (points[ni] - points[i]).det(points[nj] - points[j]) > 0: j = nj else: i = ni return ret def convex_cut_by_line(self, line_p1, line_p2): """ 凸多角形を直線 line_p1-line_p2 でカットする。 凸じゃないといけません Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_C&lang=ja :param line_p1: :param line_p2: :return: (line_p1-line_p2 の左側の多角形, line_p1-line_p2 の右側の多角形) :rtype: (Polygon|None, Polygon|None) """ n = len(self.points) line = Line.from_segment(line_p1, line_p2) # 直線と重なる点 on_line_points = [] for i, p in enumerate(self.points): if line.has_point(p): on_line_points.append(i) # 辺が直線上にある has_on_line_edge = False if len(on_line_points) >= 3: has_on_line_edge = True elif len(on_line_points) == 2: # 直線上にある点が隣り合ってる has_on_line_edge = abs(on_line_points[0] - on_line_points[1]) in [1, n - 1] # 辺が直線上にある場合、どっちか片方に全部ある if has_on_line_edge: for p in self.points: ccw = Point.ccw(line_p1, line_p2, p) if ccw == Point.CCW_COUNTER_CLOCKWISE: return Polygon(self.points[:]), None if ccw == Point.CCW_CLOCKWISE: return None, Polygon(self.points[:]) ret_lefts = [] ret_rights = [] d = line_p2 - line_p1 for p, q in self.iter2(): det_p = d.det(p - line_p1) det_q = d.det(q - line_p1) if det_p > -EPS: ret_lefts.append(p) if det_p < EPS: ret_rights.append(p) # 外積の符号が違う == 直線の反対側にある場合は交点を追加 if det_p * det_q < -EPS: intersection = line.intersection_point(Line.from_segment(p, q)) ret_lefts.append(intersection) ret_rights.append(intersection) # 点のみの場合を除いて返す l = Polygon(ret_lefts) if len(ret_lefts) > 1 else None r = Polygon(ret_rights) if len(ret_rights) > 1 else None return l, r N = int(sys.stdin.buffer.readline()) XY = [list(map(float, sys.stdin.buffer.readline().split())) for _ in range(N)] points = [] for x, y in XY: points.append(Point(complex(x, y))) polygon = Polygon(points) Q = int(sys.stdin.buffer.readline()) POINTS = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(Q)] for x1, y1, x2, y2 in POINTS: l, r = polygon.convex_cut_by_line(Point.from_rect(x1, y1), Point.from_rect(x2, y2)) if l: print(l.area()) else: print(0) ```
instruction
0
84,991
23
169,982
Yes
output
1
84,991
23
169,983
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000 Submitted Solution: ``` from sys import stdin readline = stdin.readline from enum import Enum direction = Enum('direction', 'CCW CW CAB ABC ACB') class vector: 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 ccw(a, b, c): b -= a c -= a if vector.cross(b, c) > 0: return direction.CCW if vector.cross(b, c) < 0: return direction.CW if vector.dot(b, c) < 0: return direction.CAB if abs(b) < abs(c): return direction.ABC return direction.ACB def polygon(p): if len(p) < 3: return 0 return 0.5 * sum(vector.cross(p[i - 1], p[i]) for i in range(len(p))) def intersection(p1, p2, p3, p4): a1 = p4 - p2 b1 = p2 - p3 b2 = p1 - p2 s1 = vector.cross(a1, b2) / 2 s2 = vector.cross(a1, b1) / 2 if s1 + s2 == 0: return 0 c1 = p1 + (p3 - p1) * s1 / (s1 + s2) return c1 def main(): n = int(readline()) p = [map(float, readline().split()) for _ in range(n)] p = [x + y * 1j for x, y in p] q = int(readline()) for _ in range(q): p1x, p1y, p2x, p2y = map(float, readline().split()) p1, p2 = p1x + p1y * 1j, p2x + p2y * 1j pre_tmp = vector.ccw(p[-1], p1, p2) left = [] for i in range(len(p)): tmp = vector.ccw(p[i], p1, p2) if pre_tmp != tmp and all(i in (direction.CW, direction.CCW) for i in (pre_tmp, tmp)): c1 = vector.intersection(p1, p[i - 1], p2, p[i]) left.append(c1) if tmp != direction.CW: left.append(p[i]) pre_tmp = tmp print('{:.6f}'.format(vector.polygon(left))) main() ```
instruction
0
84,992
23
169,984
No
output
1
84,992
23
169,985
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000 Submitted Solution: ``` # cross point def cross(c1, c2): return c1.real * c2.imag - c1.imag * c2.real def cross_point(p1, p2, p3, p4): # p1 and p2 are points on a segment. # p3 and p4 are points on the other segment. base = p4 - p3 hypo1 = p1 - p3 hypo2 = p2 - p3 d1 = cross(base, hypo1) / abs(base) d2 = cross(base, hypo2) / abs(base) cp = p1 + d1 / (d1 - d2) * (p2 - p1) return cp # area of a triangle def _area_of_triangle(c1, c2, c3): v1 = c2 - c1 v2 = c3 - c1 return abs(v1.real * v2.imag - v1.imag * v2.real) / 2 # convex cut def convex_cut(points, c1, c2): points.append(points[0]) ref_vec = c2 - c1 for i, segment in enumerate(zip(points, points[1:])): p1, p2 = segment cross1 = cross(ref_vec, p1 - c1) cross2 = cross(ref_vec, p2 - c1) if cross1 <= 0 and cross2 > 0: cross_point1 = cross_point(c1, c2, p1, p2) points = points[i+1:] break elif cross1 > 0 and cross2 <= 0: cross_point1 = cross_point(c1, c2, p1, p2) points = points[i::-1] + points[:i:-1] break cut_area = 0 for p1, p2 in zip(points, points[1:]): if cross(ref_vec, p1 - c1) * cross(ref_vec, p2 - c1) <= 0: cross_point2 = cross_point(c1, c2, p1, p2) cut_area += _area_of_triangle(cross_point1, cross_point2, p1) break else: cut_area += _area_of_triangle(cross_point1, p1, p2) return cut_area # acceptance of input import sys file_input = sys.stdin n = int(file_input.readline()) def string_to_complex(s): x, y = map(float, s.split()) return x + y * 1j G = [string_to_complex(file_input.readline()) for i in range(n)] # output q = int(file_input.readline()) for line in file_input: p1x, p1y, p2x, p2y = map(int, line.split()) p1 = p1x + p1y * 1j p2 = p2x + p2y * 1j ans = convex_cut(G.copy(), p1, p2) print("{:f}".format(ans)) ```
instruction
0
84,993
23
169,986
No
output
1
84,993
23
169,987
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000 Submitted Solution: ``` from sys import stdin readline = stdin.readline from enum import Enum direction = Enum('direction', 'CCW CW CAB ABC ACB') class vector: 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 ccw(a, b, c): b -= a c -= a if vector.cross(b, c) > 0: return direction.CCW if vector.cross(b, c) < 0: return direction.CW if vector.dot(b, c) < 0: return direction.CAB if vector.abs(b) < abs(c): return direction.ABC return direction.ACB def polygon(p): if len(p) < 3: return 0 return 0.5 * sum(vector.cross(p[i - 1], p[i]) for i in range(len(p))) def intersection(p1, p2, p3, p4): a1 = p4 - p2 b1 = p2 - p3 b2 = p1 - p2 s1 = vector.cross(a1, b2) / 2 s2 = vector.cross(a1, b1) / 2 c1 = p1 + (p3 - p1) * s1 / (s1 + s2) return c1 def main(): n = int(readline()) p = [map(float, readline().split()) for _ in range(n)] p = [x + y * 1j for x, y in p] q = int(readline()) for _ in range(q): p1x, p1y, p2x, p2y = map(float, readline().split()) p1, p2 = p1x + p1y * 1j, p2x + p2y * 1j pre_tmp = vector.ccw(p[-1], p1, p2) left = [] for i in range(len(p)): tmp = vector.ccw(p[i], p1, p2) if pre_tmp != tmp and all(i in (direction.CW, direction.CCW) for i in (pre_tmp, tmp)): c1 = vector.intersection(p1, p[i - 1], p2, p[i]) left.append(c1) if tmp != direction.CW: left.append(p[i]) pre_tmp = tmp print('{:.6f}'.format(vector.polygon(left))) main() ```
instruction
0
84,994
23
169,988
No
output
1
84,994
23
169,989
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n−1) are sides of the convex polygon. The line segment connecting pn and p1 is also a side of the polygon. Constraints * 3 ≤ n ≤ 100 * 1 ≤ q ≤ 100 * -10000 ≤ xi, yi ≤ 10000 * -10000 ≤ p1x,p1y,p2x,p2y ≤ 10000 * No point in g will occur more than once. * p1 ≠ p2 Input The input is given in the following format: g (the sequence of the points of the polygon) q (the number of queries = the number of target lines) 1st query 2nd query : qth query g is given as a sequence of points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of the i-th point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Note that all interior angles of given convex polygons are less than or equal to 180. For each query, a line represented by two points p1 and p2 is given. The coordinates of the points are given by four integers p1x, p1y, p2x and p2y. Output For each query, print the area of the cut polygon. The output values should be in a decimal fraction with an error less than 0.00001. Example Input 4 1 1 4 1 4 3 1 3 2 2 0 2 4 2 4 2 0 Output 2.00000000 4.00000000 Submitted Solution: ``` from sys import stdin readline = stdin.readline from enum import Enum direction = Enum('direction', 'CCW CW CAB ABC ACB') class vector: 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 ccw(a, b, c): b -= a c -= a if vector.cross(b, c) > 0: return direction.CCW if vector.cross(b, c) < 0: return direction.CW if vector.dot(b, c) < 0: return direction.CAB if vector.abs(b) < abs(c): return direction.ABC return direction.ACB def polygon(p): return 0.5 * sum(vector.cross(p[i - 1], p[i]) for i in range(len(p))) def intersection(p1, p2, p3, p4): a1 = p4 - p2 b1 = p2 - p3 b2 = p1 - p2 s1 = vector.cross(a1, b2) / 2 s2 = vector.cross(a1, b1) / 2 c1 = p1 + (p3 - p1) * s1 / (s1 + s2) return c1 def main(): n = int(readline()) p = [map(int, readline().split()) for _ in range(n)] p = [x + y * 1j for x, y in p] q = int(readline()) for _ in range(q): p1x, p1y, p2x, p2y = map(int, readline().split()) p1, p2 = p1x + p1y * 1j, p2x + p2y * 1j pre_tmp = vector.ccw(p[-1], p1, p2) left = [] for i in range(len(p)): tmp = vector.ccw(p[i], p1, p2) if pre_tmp != tmp and all(i in (direction.CW, direction.CCW) for i in (pre_tmp, tmp)): c1 = vector.intersection(p1, p[i - 1], p2, p[i]) left.append(c1) if tmp != direction.CW: left.append(p[i]) pre_tmp = tmp print(vector.polygon(left)) main() ```
instruction
0
84,995
23
169,990
No
output
1
84,995
23
169,991
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given four positive integers n, m, a, b (1 ≤ b ≤ n ≤ 50; 1 ≤ a ≤ m ≤ 50). Find any such rectangular matrix of size n × m that satisfies all of the following conditions: * each row of the matrix contains exactly a ones; * each column of the matrix contains exactly b ones; * all other elements are zeros. If the desired matrix does not exist, indicate this. For example, for n=3, m=6, a=2, b=1, there exists a matrix satisfying the conditions above: $$$ \begin{vmatrix} 0 & 1 & 0 & 0 & 0 & 1 \\\ 1 & 0 & 0 & 1 & 0 & 0 \\\ 0 & 0 & 1 & 0 & 1 & 0 \end{vmatrix} $$$ Input The first line contains an integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow. Each test case is described by four positive integers n, m, a, b (1 ≤ b ≤ n ≤ 50; 1 ≤ a ≤ m ≤ 50), where n and m are the sizes of the matrix, and a and b are the number of ones for rows and columns, respectively. Output For each test case print: * "YES" (without quotes) and the required matrix (if there are several answers, print any) if it exists, or * "NO" (without quotes) if it does not exist. To print the matrix n × m, print n rows, each of which consists of m numbers 0 or 1 describing a row of the matrix. Numbers must be printed without spaces. Example Input 5 3 6 2 1 2 2 2 1 2 2 2 2 4 4 2 2 2 1 1 2 Output YES 010001 100100 001010 NO YES 11 11 YES 1100 1100 0011 0011 YES 1 1 Submitted Solution: ``` import sys input = sys.stdin.readline """ """ def is_valid(mat, a, b): sum_cols = [0] * len(mat[0]) for r in range(len(mat)): for c in range(len(mat[0])): sum_cols[c] += mat[r][c] # check row if sum(mat[r]) != a: return False # check cols for s in sum_cols: if s != b: return False return True def solve(n, m, a, b): if a > m or b > n: print("NO") mat = [[0] * m for _ in range(n)] r_i = 0 for r in range(n): for _ in range(a): mat[r][r_i] = 1 r_i = (r_i + 1 ) % m if is_valid(mat, a, b): print("YES") for row in mat: print("".join(map(str, row))) else: print("NO") t = int(input().strip()) for _ in range(t): n, m, a, b = map(int, input().split()) solve(n, m, a, b) ```
instruction
0
85,160
23
170,320
Yes
output
1
85,160
23
170,321
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given four positive integers n, m, a, b (1 ≤ b ≤ n ≤ 50; 1 ≤ a ≤ m ≤ 50). Find any such rectangular matrix of size n × m that satisfies all of the following conditions: * each row of the matrix contains exactly a ones; * each column of the matrix contains exactly b ones; * all other elements are zeros. If the desired matrix does not exist, indicate this. For example, for n=3, m=6, a=2, b=1, there exists a matrix satisfying the conditions above: $$$ \begin{vmatrix} 0 & 1 & 0 & 0 & 0 & 1 \\\ 1 & 0 & 0 & 1 & 0 & 0 \\\ 0 & 0 & 1 & 0 & 1 & 0 \end{vmatrix} $$$ Input The first line contains an integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow. Each test case is described by four positive integers n, m, a, b (1 ≤ b ≤ n ≤ 50; 1 ≤ a ≤ m ≤ 50), where n and m are the sizes of the matrix, and a and b are the number of ones for rows and columns, respectively. Output For each test case print: * "YES" (without quotes) and the required matrix (if there are several answers, print any) if it exists, or * "NO" (without quotes) if it does not exist. To print the matrix n × m, print n rows, each of which consists of m numbers 0 or 1 describing a row of the matrix. Numbers must be printed without spaces. Example Input 5 3 6 2 1 2 2 2 1 2 2 2 2 4 4 2 2 2 1 1 2 Output YES 010001 100100 001010 NO YES 11 11 YES 1100 1100 0011 0011 YES 1 1 Submitted Solution: ``` #!/usr/bin/env python #pyrival orz import os import sys from io import BytesIO, IOBase def main(): for _ in range(int(input())): n,m,a,b=map(int,input().split()) if a*n!=m*b: print("NO") continue def solve(a,b,fl): ans=[ [False for _ in range(m) ] for _ in range(n) ] cnt=[0]*n for r in range(m): cur=0 for c in range(n): if cur == b: break if cnt[c]>=a: continue cnt[c]+=1 cur+=1 ans[c][r]=True if cur<b: return False # print(a,b,fl) # print(ans) print("YES") for v in ans: print("".join( "%d"%(fl^x) for x in v)) return True if solve(a,b,False): continue if solve(n-a,m-b,True): continue print("NO") # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main() ```
instruction
0
85,163
23
170,326
No
output
1
85,163
23
170,327
Provide tags and a correct Python 3 solution for this coding contest problem. We have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k. <image> The description of the first test case. Since sometimes it's impossible to find such point B, we can, in one step, increase or decrease the coordinate of A by 1. What is the minimum number of steps we should do to make such point B exist? Input The first line contains one integer t (1 ≤ t ≤ 6000) — the number of test cases. The only line of each test case contains two integers n and k (0 ≤ n, k ≤ 10^6) — the initial position of point A and desirable absolute difference. Output For each test case, print the minimum number of steps to make point B exist. Example Input 6 4 0 5 8 0 1000000 0 0 1 0 1000000 1000000 Output 0 3 1000000 0 1 0 Note In the first test case (picture above), if we set the coordinate of B as 2 then the absolute difference will be equal to |(2 - 0) - (4 - 2)| = 0 and we don't have to move A. So the answer is 0. In the second test case, we can increase the coordinate of A by 3 and set the coordinate of B as 0 or 8. The absolute difference will be equal to |8 - 0| = 8, so the answer is 3. <image>
instruction
0
85,185
23
170,370
Tags: constructive algorithms, math Correct Solution: ``` from sys import stdout, stdin _input, _print = stdin.readline, stdout.write _range, _int = range, int def solution(): for _ in _range(_int(_input())): a, k = [_int(i) for i in _input().split()] if (a-k) >= 0: if (a - k) % 2 == 0: print(0) else: print(1) else: print(k-a) solution() ```
output
1
85,185
23
170,371
Provide tags and a correct Python 3 solution for this coding contest problem. We have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k. <image> The description of the first test case. Since sometimes it's impossible to find such point B, we can, in one step, increase or decrease the coordinate of A by 1. What is the minimum number of steps we should do to make such point B exist? Input The first line contains one integer t (1 ≤ t ≤ 6000) — the number of test cases. The only line of each test case contains two integers n and k (0 ≤ n, k ≤ 10^6) — the initial position of point A and desirable absolute difference. Output For each test case, print the minimum number of steps to make point B exist. Example Input 6 4 0 5 8 0 1000000 0 0 1 0 1000000 1000000 Output 0 3 1000000 0 1 0 Note In the first test case (picture above), if we set the coordinate of B as 2 then the absolute difference will be equal to |(2 - 0) - (4 - 2)| = 0 and we don't have to move A. So the answer is 0. In the second test case, we can increase the coordinate of A by 3 and set the coordinate of B as 0 or 8. The absolute difference will be equal to |8 - 0| = 8, so the answer is 3. <image>
instruction
0
85,186
23
170,372
Tags: constructive algorithms, math Correct Solution: ``` import math t=int(input()) out=[] for i in range(t): n,k=map(int,input().split()) x=(n-k)/2 if(x<0): z=int(-2*x) out.append(z) elif(x>0): if(x==math.ceil(x)): out.append(0) else: out.append(1) else: out.append(0) for i in out: print(i) ```
output
1
85,186
23
170,373
Provide tags and a correct Python 3 solution for this coding contest problem. We have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k. <image> The description of the first test case. Since sometimes it's impossible to find such point B, we can, in one step, increase or decrease the coordinate of A by 1. What is the minimum number of steps we should do to make such point B exist? Input The first line contains one integer t (1 ≤ t ≤ 6000) — the number of test cases. The only line of each test case contains two integers n and k (0 ≤ n, k ≤ 10^6) — the initial position of point A and desirable absolute difference. Output For each test case, print the minimum number of steps to make point B exist. Example Input 6 4 0 5 8 0 1000000 0 0 1 0 1000000 1000000 Output 0 3 1000000 0 1 0 Note In the first test case (picture above), if we set the coordinate of B as 2 then the absolute difference will be equal to |(2 - 0) - (4 - 2)| = 0 and we don't have to move A. So the answer is 0. In the second test case, we can increase the coordinate of A by 3 and set the coordinate of B as 0 or 8. The absolute difference will be equal to |8 - 0| = 8, so the answer is 3. <image>
instruction
0
85,188
23
170,376
Tags: constructive algorithms, math Correct Solution: ``` tests=int(input()) for i in range(tests): a,b=list(map(int,input().split())) if(b>a): print(b-a) elif((a-b)%2==1): print("1") else: print("0") ```
output
1
85,188
23
170,377
Provide tags and a correct Python 3 solution for this coding contest problem. We have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k. <image> The description of the first test case. Since sometimes it's impossible to find such point B, we can, in one step, increase or decrease the coordinate of A by 1. What is the minimum number of steps we should do to make such point B exist? Input The first line contains one integer t (1 ≤ t ≤ 6000) — the number of test cases. The only line of each test case contains two integers n and k (0 ≤ n, k ≤ 10^6) — the initial position of point A and desirable absolute difference. Output For each test case, print the minimum number of steps to make point B exist. Example Input 6 4 0 5 8 0 1000000 0 0 1 0 1000000 1000000 Output 0 3 1000000 0 1 0 Note In the first test case (picture above), if we set the coordinate of B as 2 then the absolute difference will be equal to |(2 - 0) - (4 - 2)| = 0 and we don't have to move A. So the answer is 0. In the second test case, we can increase the coordinate of A by 3 and set the coordinate of B as 0 or 8. The absolute difference will be equal to |8 - 0| = 8, so the answer is 3. <image>
instruction
0
85,190
23
170,380
Tags: constructive algorithms, math Correct Solution: ``` ''' Welcome to GDB Online. GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl, C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog. Code, Compile, Run and Debug online from anywhere in world. ''' for _ in range(int(input())): n,k=map(int,input().split()) if(n<=k): print(k-n) else: if((abs(k-n)%2)==0): print(0) else: print(1) ```
output
1
85,190
23
170,381
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k. <image> The description of the first test case. Since sometimes it's impossible to find such point B, we can, in one step, increase or decrease the coordinate of A by 1. What is the minimum number of steps we should do to make such point B exist? Input The first line contains one integer t (1 ≤ t ≤ 6000) — the number of test cases. The only line of each test case contains two integers n and k (0 ≤ n, k ≤ 10^6) — the initial position of point A and desirable absolute difference. Output For each test case, print the minimum number of steps to make point B exist. Example Input 6 4 0 5 8 0 1000000 0 0 1 0 1000000 1000000 Output 0 3 1000000 0 1 0 Note In the first test case (picture above), if we set the coordinate of B as 2 then the absolute difference will be equal to |(2 - 0) - (4 - 2)| = 0 and we don't have to move A. So the answer is 0. In the second test case, we can increase the coordinate of A by 3 and set the coordinate of B as 0 or 8. The absolute difference will be equal to |8 - 0| = 8, so the answer is 3. <image> Submitted Solution: ``` for i in range(int(input())): x,y=map(int,input().split()) if x>=y: if x%2==0 and y%2==0: print("0") elif x%2==1 and y%2==1: print("0") else: print("1") else: print(y-x) ```
instruction
0
85,194
23
170,388
Yes
output
1
85,194
23
170,389
Provide a correct Python 3 solution for this coding contest problem. Takahashi is doing a research on sets of points in a plane. Takahashi thinks a set S of points in a coordinate plane is a good set when S satisfies both of the following conditions: * The distance between any two points in S is not \sqrt{D_1}. * The distance between any two points in S is not \sqrt{D_2}. Here, D_1 and D_2 are positive integer constants that Takahashi specified. Let X be a set of points (i,j) on a coordinate plane where i and j are integers and satisfy 0 ≤ i,j < 2N. Takahashi has proved that, for any choice of D_1 and D_2, there exists a way to choose N^2 points from X so that the chosen points form a good set. However, he does not know the specific way to choose such points to form a good set. Find a subset of X whose size is N^2 that forms a good set. Constraints * 1 ≤ N ≤ 300 * 1 ≤ D_1 ≤ 2×10^5 * 1 ≤ D_2 ≤ 2×10^5 * All values in the input are integers. Input Input is given from Standard Input in the following format: N D_1 D_2 Output Print N^2 distinct points that satisfy the condition in the following format: x_1 y_1 x_2 y_2 : x_{N^2} y_{N^2} Here, (x_i,y_i) represents the i-th chosen point. 0 ≤ x_i,y_i < 2N must hold, and they must be integers. The chosen points may be printed in any order. In case there are multiple possible solutions, you can output any. Examples Input 2 1 2 Output 0 0 0 2 2 0 2 2 Input 3 1 5 Output 0 0 0 2 0 4 1 1 1 3 1 5 2 0 2 2 2 4
instruction
0
85,584
23
171,168
"Correct Solution: ``` from itertools import product def check_odd(i, j): return (i + j) % 2 == 0 def check_even(i, j): return i % 2 == 0 def solve(n, d1, d2): s1, s2 = 0, 0 while d1 % 4 == 0: d1 >>= 2 s1 += 1 while d2 % 4 == 0: d2 >>= 2 s2 += 1 f1 = check_odd if d1 % 2 else check_even f2 = check_odd if d2 % 2 else check_even lim = n ** 2 buf = [] cnt = 0 for i, j in product(range(2 * n), repeat=2): if f1(i >> s1, j >> s1) and f2(i >> s2, j >> s2): buf.append('{} {}'.format(i, j)) cnt += 1 if cnt == lim: break return buf n, d1, d2 = map(int, input().split()) print('\n'.join(solve(n, d1, d2))) ```
output
1
85,584
23
171,169
Provide a correct Python 3 solution for this coding contest problem. Takahashi is doing a research on sets of points in a plane. Takahashi thinks a set S of points in a coordinate plane is a good set when S satisfies both of the following conditions: * The distance between any two points in S is not \sqrt{D_1}. * The distance between any two points in S is not \sqrt{D_2}. Here, D_1 and D_2 are positive integer constants that Takahashi specified. Let X be a set of points (i,j) on a coordinate plane where i and j are integers and satisfy 0 ≤ i,j < 2N. Takahashi has proved that, for any choice of D_1 and D_2, there exists a way to choose N^2 points from X so that the chosen points form a good set. However, he does not know the specific way to choose such points to form a good set. Find a subset of X whose size is N^2 that forms a good set. Constraints * 1 ≤ N ≤ 300 * 1 ≤ D_1 ≤ 2×10^5 * 1 ≤ D_2 ≤ 2×10^5 * All values in the input are integers. Input Input is given from Standard Input in the following format: N D_1 D_2 Output Print N^2 distinct points that satisfy the condition in the following format: x_1 y_1 x_2 y_2 : x_{N^2} y_{N^2} Here, (x_i,y_i) represents the i-th chosen point. 0 ≤ x_i,y_i < 2N must hold, and they must be integers. The chosen points may be printed in any order. In case there are multiple possible solutions, you can output any. Examples Input 2 1 2 Output 0 0 0 2 2 0 2 2 Input 3 1 5 Output 0 0 0 2 0 4 1 1 1 3 1 5 2 0 2 2 2 4
instruction
0
85,585
23
171,170
"Correct Solution: ``` def judge(D): n = 0 while D%4==0: n += 1 D //= 4 def h1(x,y): return ~((x>>n)^(y>>n))&1 def h2(x,y): return ~(x>>n)&1 return h1 if D%2==1 else h2 N,D1,D2 = map(int,input().split()) j1,j2 = judge(D1),judge(D2) cnt = 0 for x in range(N*2): for y in range(N*2): if j1(x,y) and j2(x,y): print(x,y) cnt += 1 if cnt >= N*N: exit() ```
output
1
85,585
23
171,171
Provide a correct Python 3 solution for this coding contest problem. Takahashi is doing a research on sets of points in a plane. Takahashi thinks a set S of points in a coordinate plane is a good set when S satisfies both of the following conditions: * The distance between any two points in S is not \sqrt{D_1}. * The distance between any two points in S is not \sqrt{D_2}. Here, D_1 and D_2 are positive integer constants that Takahashi specified. Let X be a set of points (i,j) on a coordinate plane where i and j are integers and satisfy 0 ≤ i,j < 2N. Takahashi has proved that, for any choice of D_1 and D_2, there exists a way to choose N^2 points from X so that the chosen points form a good set. However, he does not know the specific way to choose such points to form a good set. Find a subset of X whose size is N^2 that forms a good set. Constraints * 1 ≤ N ≤ 300 * 1 ≤ D_1 ≤ 2×10^5 * 1 ≤ D_2 ≤ 2×10^5 * All values in the input are integers. Input Input is given from Standard Input in the following format: N D_1 D_2 Output Print N^2 distinct points that satisfy the condition in the following format: x_1 y_1 x_2 y_2 : x_{N^2} y_{N^2} Here, (x_i,y_i) represents the i-th chosen point. 0 ≤ x_i,y_i < 2N must hold, and they must be integers. The chosen points may be printed in any order. In case there are multiple possible solutions, you can output any. Examples Input 2 1 2 Output 0 0 0 2 2 0 2 2 Input 3 1 5 Output 0 0 0 2 0 4 1 1 1 3 1 5 2 0 2 2 2 4
instruction
0
85,586
23
171,172
"Correct Solution: ``` def judge(D): n = 0 while D%4==0: n += 1 D //= 4 return (lambda x,y: ~((x>>n)^(y>>n))&1) if D%2==1 else (lambda x,y: ~(x>>n)&1) N,D1,D2 = map(int,input().split()) j1,j2 = judge(D1),judge(D2) for _,(x,y) in zip(range(N*N),filter(lambda p: j1(*p) and j2(*p), ((x,y) for x in range(N*2) for y in range(N*2)))): print(x,y) ```
output
1
85,586
23
171,173
Provide a correct Python 3 solution for this coding contest problem. Takahashi is doing a research on sets of points in a plane. Takahashi thinks a set S of points in a coordinate plane is a good set when S satisfies both of the following conditions: * The distance between any two points in S is not \sqrt{D_1}. * The distance between any two points in S is not \sqrt{D_2}. Here, D_1 and D_2 are positive integer constants that Takahashi specified. Let X be a set of points (i,j) on a coordinate plane where i and j are integers and satisfy 0 ≤ i,j < 2N. Takahashi has proved that, for any choice of D_1 and D_2, there exists a way to choose N^2 points from X so that the chosen points form a good set. However, he does not know the specific way to choose such points to form a good set. Find a subset of X whose size is N^2 that forms a good set. Constraints * 1 ≤ N ≤ 300 * 1 ≤ D_1 ≤ 2×10^5 * 1 ≤ D_2 ≤ 2×10^5 * All values in the input are integers. Input Input is given from Standard Input in the following format: N D_1 D_2 Output Print N^2 distinct points that satisfy the condition in the following format: x_1 y_1 x_2 y_2 : x_{N^2} y_{N^2} Here, (x_i,y_i) represents the i-th chosen point. 0 ≤ x_i,y_i < 2N must hold, and they must be integers. The chosen points may be printed in any order. In case there are multiple possible solutions, you can output any. Examples Input 2 1 2 Output 0 0 0 2 2 0 2 2 Input 3 1 5 Output 0 0 0 2 0 4 1 1 1 3 1 5 2 0 2 2 2 4
instruction
0
85,587
23
171,174
"Correct Solution: ``` def check_odd(i, j): return (i + j) % 2 == 0 def check_even(i, j): return i % 2 == 0 def solve(n, d1, d2): s1, s2 = 0, 0 while d1 % 4 == 0: d1 >>= 2 s1 += 1 while d2 % 4 == 0: d2 >>= 2 s2 += 1 f1 = check_odd if d1 % 2 else check_even f2 = check_odd if d2 % 2 else check_even lim = n ** 2 buf = [] cnt = 0 for i in range(2 * n): _i1 = i >> s1 _i2 = i >> s2 for j in range(2 * n): if f1(_i1, j >> s1) and f2(_i2, j >> s2): buf.append('{} {}'.format(i, j)) cnt += 1 if cnt == lim: return buf n, d1, d2 = map(int, input().split()) print('\n'.join(solve(n, d1, d2))) ```
output
1
85,587
23
171,175
Provide a correct Python 3 solution for this coding contest problem. Takahashi is doing a research on sets of points in a plane. Takahashi thinks a set S of points in a coordinate plane is a good set when S satisfies both of the following conditions: * The distance between any two points in S is not \sqrt{D_1}. * The distance between any two points in S is not \sqrt{D_2}. Here, D_1 and D_2 are positive integer constants that Takahashi specified. Let X be a set of points (i,j) on a coordinate plane where i and j are integers and satisfy 0 ≤ i,j < 2N. Takahashi has proved that, for any choice of D_1 and D_2, there exists a way to choose N^2 points from X so that the chosen points form a good set. However, he does not know the specific way to choose such points to form a good set. Find a subset of X whose size is N^2 that forms a good set. Constraints * 1 ≤ N ≤ 300 * 1 ≤ D_1 ≤ 2×10^5 * 1 ≤ D_2 ≤ 2×10^5 * All values in the input are integers. Input Input is given from Standard Input in the following format: N D_1 D_2 Output Print N^2 distinct points that satisfy the condition in the following format: x_1 y_1 x_2 y_2 : x_{N^2} y_{N^2} Here, (x_i,y_i) represents the i-th chosen point. 0 ≤ x_i,y_i < 2N must hold, and they must be integers. The chosen points may be printed in any order. In case there are multiple possible solutions, you can output any. Examples Input 2 1 2 Output 0 0 0 2 2 0 2 2 Input 3 1 5 Output 0 0 0 2 0 4 1 1 1 3 1 5 2 0 2 2 2 4
instruction
0
85,588
23
171,176
"Correct Solution: ``` from sys import exit, setrecursionlimit, stderr from functools import reduce from itertools import * from collections import defaultdict from bisect import bisect def read(): return int(input()) def reads(): return [int(x) for x in input().split()] N, D1, D2 = reads() NN = 2 * N def deg(x): return next(i for i in count() if x >> i & 1 == 1) def group(x, y, d): p = deg(d) hp = p >> 1 if p & 1 == 0: return (x >> hp & 1) ^ (y >> hp & 1) else: return x >> hp & 1 pts = [(x, y) for x in range(NN) for y in range(NN) if group(x, y, D1) == 0 and group(x, y, D2) == 0] for x, y in pts[:N**2]: print(x, y) ```
output
1
85,588
23
171,177
Provide a correct Python 3 solution for this coding contest problem. Takahashi is doing a research on sets of points in a plane. Takahashi thinks a set S of points in a coordinate plane is a good set when S satisfies both of the following conditions: * The distance between any two points in S is not \sqrt{D_1}. * The distance between any two points in S is not \sqrt{D_2}. Here, D_1 and D_2 are positive integer constants that Takahashi specified. Let X be a set of points (i,j) on a coordinate plane where i and j are integers and satisfy 0 ≤ i,j < 2N. Takahashi has proved that, for any choice of D_1 and D_2, there exists a way to choose N^2 points from X so that the chosen points form a good set. However, he does not know the specific way to choose such points to form a good set. Find a subset of X whose size is N^2 that forms a good set. Constraints * 1 ≤ N ≤ 300 * 1 ≤ D_1 ≤ 2×10^5 * 1 ≤ D_2 ≤ 2×10^5 * All values in the input are integers. Input Input is given from Standard Input in the following format: N D_1 D_2 Output Print N^2 distinct points that satisfy the condition in the following format: x_1 y_1 x_2 y_2 : x_{N^2} y_{N^2} Here, (x_i,y_i) represents the i-th chosen point. 0 ≤ x_i,y_i < 2N must hold, and they must be integers. The chosen points may be printed in any order. In case there are multiple possible solutions, you can output any. Examples Input 2 1 2 Output 0 0 0 2 2 0 2 2 Input 3 1 5 Output 0 0 0 2 0 4 1 1 1 3 1 5 2 0 2 2 2 4
instruction
0
85,589
23
171,178
"Correct Solution: ``` from itertools import product N, D1, D2 = map(int, input().split()) # Dが「奇数」or「D%4=2」になるまで、4で割る Ds = [] Ms = [] for D in [D1, D2]: M = 1 while D % 4 == 0: D //= 4 M *= 2 Ds += [D] Ms += [M] # 各点(i,j)に対して、処理を行う num = 0 for i, j in product(range(2 * N), repeat=2): # 1/Mに縮小した平面で(0,0)と同じ色で塗るならば、出力する for D, M in zip(Ds, Ms): if D % 2: # Dが奇数→(x+y)の偶奇で塗り分ける if (i // M + j // M) % 2: break else: # D%4=2→xの偶奇で塗り分ける if (i // M) % 2: break else: print(i, j) num += 1 if num == N * N: break ```
output
1
85,589
23
171,179
Provide a correct Python 3 solution for this coding contest problem. Takahashi is doing a research on sets of points in a plane. Takahashi thinks a set S of points in a coordinate plane is a good set when S satisfies both of the following conditions: * The distance between any two points in S is not \sqrt{D_1}. * The distance between any two points in S is not \sqrt{D_2}. Here, D_1 and D_2 are positive integer constants that Takahashi specified. Let X be a set of points (i,j) on a coordinate plane where i and j are integers and satisfy 0 ≤ i,j < 2N. Takahashi has proved that, for any choice of D_1 and D_2, there exists a way to choose N^2 points from X so that the chosen points form a good set. However, he does not know the specific way to choose such points to form a good set. Find a subset of X whose size is N^2 that forms a good set. Constraints * 1 ≤ N ≤ 300 * 1 ≤ D_1 ≤ 2×10^5 * 1 ≤ D_2 ≤ 2×10^5 * All values in the input are integers. Input Input is given from Standard Input in the following format: N D_1 D_2 Output Print N^2 distinct points that satisfy the condition in the following format: x_1 y_1 x_2 y_2 : x_{N^2} y_{N^2} Here, (x_i,y_i) represents the i-th chosen point. 0 ≤ x_i,y_i < 2N must hold, and they must be integers. The chosen points may be printed in any order. In case there are multiple possible solutions, you can output any. Examples Input 2 1 2 Output 0 0 0 2 2 0 2 2 Input 3 1 5 Output 0 0 0 2 0 4 1 1 1 3 1 5 2 0 2 2 2 4
instruction
0
85,590
23
171,180
"Correct Solution: ``` from sys import exit, setrecursionlimit, stderr from functools import reduce from itertools import * from collections import defaultdict from bisect import bisect def read(): return int(input()) def reads(): return [int(x) for x in input().split()] N, D1, D2 = reads() NN = 2 * N def deg(x): return next(i for i in count() if x >> i & 1 == 1) p1 = deg(D1) p2 = deg(D2) def group(x, y, p): hp = p >> 1 if p & 1 == 0: return (x >> hp & 1) ^ (y >> hp & 1) else: return x >> hp & 1 pts = [(x, y) for x in range(NN) for y in range(NN) if group(x, y, p1) == 0 and group(x, y, p2) == 0] for x, y in pts[:N**2]: print(x, y) ```
output
1
85,590
23
171,181
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Takahashi is doing a research on sets of points in a plane. Takahashi thinks a set S of points in a coordinate plane is a good set when S satisfies both of the following conditions: * The distance between any two points in S is not \sqrt{D_1}. * The distance between any two points in S is not \sqrt{D_2}. Here, D_1 and D_2 are positive integer constants that Takahashi specified. Let X be a set of points (i,j) on a coordinate plane where i and j are integers and satisfy 0 ≤ i,j < 2N. Takahashi has proved that, for any choice of D_1 and D_2, there exists a way to choose N^2 points from X so that the chosen points form a good set. However, he does not know the specific way to choose such points to form a good set. Find a subset of X whose size is N^2 that forms a good set. Constraints * 1 ≤ N ≤ 300 * 1 ≤ D_1 ≤ 2×10^5 * 1 ≤ D_2 ≤ 2×10^5 * All values in the input are integers. Input Input is given from Standard Input in the following format: N D_1 D_2 Output Print N^2 distinct points that satisfy the condition in the following format: x_1 y_1 x_2 y_2 : x_{N^2} y_{N^2} Here, (x_i,y_i) represents the i-th chosen point. 0 ≤ x_i,y_i < 2N must hold, and they must be integers. The chosen points may be printed in any order. In case there are multiple possible solutions, you can output any. Examples Input 2 1 2 Output 0 0 0 2 2 0 2 2 Input 3 1 5 Output 0 0 0 2 0 4 1 1 1 3 1 5 2 0 2 2 2 4 Submitted Solution: ``` #!/usr/bin/python # -*- coding: utf-8 -*- import sys,collections,itertools,re,math,fractions,decimal,random,array,bisect,heapq # decimal.getcontext().prec = 50 # sys.setrecursionlimit(10000) # MOD = 10**9 + 7 def isqrt(n): """integer sqrt: the maximum integer less than or equal to sqrt(n)""" x = n y = (x + 1) // 2 while y < x: x = y y = (x + n // x) // 2 return x def solve(f): n, d1, d2 = f.read_int_list() a = [[0] * (2*n) for _ in range(2*n)] d = [d1, d2] for i in range(2): g = [[[] for _ in range(2*n)] for _ in range(2*n)] for dx in range(2*n): dy2 = d[i] - dx**2 if dy2 < 0: continue dy = isqrt(dy2) if dy**2 != dy2: continue for x in range(2*n): for y in range(2*n): for sgn in [1, -1]: if dx*dy == 0 and sgn == -1: continue if 0 <= x+dx < 2*n and 0 <= y+sgn*dy < 2*n: g[x][y].append((x+dx, y+sgn*dy)) g[x+dx][y+sgn*dy].append((x, y)) vis = [[False] * (2*n) for _ in range(2*n)] for x in range(2*n): for y in range(2*n): if not vis[x][y]: c = 2**i que = [(x, y)] while len(que) > 0: que2 = [] for xi, yi in que: if vis[xi][yi]: continue vis[xi][yi] = True a[xi][yi] += c que2.extend(g[xi][yi]) que = que2 c *= -1 cnt = collections.defaultdict(list) for x in range(2*n): for y in range(2*n): cnt[a[x][y]].append((x, y)) for k, v in cnt.items(): if len(v) >= n**2: return "\n".join(["%d %d"%item for item in v[:n**2]]) class Reader(object): def __init__(self, filename=None): self.file = open(filename) if filename is not None else None self.case = 1 def __readline(self): return next(self.file).strip() if self.file else input() def next_case(self): next(self.file) self.case += 1 def read_int(self): return int(self.__readline()) def read_float(self): return float(self.__readline()) def read_long(self): return long(self.__readline()) def read_decimal(self): return decimal.Decimal(self.__readline()) def read_str(self): return self.__readline() def read_int_list(self): return map(int, self.__readline().split()) def read_float_list(self): return map(float, self.__readline().split()) def read_long_list(self): return map(long, self.__readline().split()) def read_decimal_list(self): return map(decimal.Decimal, self.__readline().split()) def read_str_list(self): return self.__readline().split() if __name__ == '__main__': filename = sys.argv[1] if len(sys.argv) > 1 else None f = Reader(filename) if f.file: while True: print("Case #%d"%f.case) print(solve(f)) try: f.next_case() except StopIteration: break else: print(solve(f)) ```
instruction
0
85,591
23
171,182
No
output
1
85,591
23
171,183
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Takahashi is doing a research on sets of points in a plane. Takahashi thinks a set S of points in a coordinate plane is a good set when S satisfies both of the following conditions: * The distance between any two points in S is not \sqrt{D_1}. * The distance between any two points in S is not \sqrt{D_2}. Here, D_1 and D_2 are positive integer constants that Takahashi specified. Let X be a set of points (i,j) on a coordinate plane where i and j are integers and satisfy 0 ≤ i,j < 2N. Takahashi has proved that, for any choice of D_1 and D_2, there exists a way to choose N^2 points from X so that the chosen points form a good set. However, he does not know the specific way to choose such points to form a good set. Find a subset of X whose size is N^2 that forms a good set. Constraints * 1 ≤ N ≤ 300 * 1 ≤ D_1 ≤ 2×10^5 * 1 ≤ D_2 ≤ 2×10^5 * All values in the input are integers. Input Input is given from Standard Input in the following format: N D_1 D_2 Output Print N^2 distinct points that satisfy the condition in the following format: x_1 y_1 x_2 y_2 : x_{N^2} y_{N^2} Here, (x_i,y_i) represents the i-th chosen point. 0 ≤ x_i,y_i < 2N must hold, and they must be integers. The chosen points may be printed in any order. In case there are multiple possible solutions, you can output any. Examples Input 2 1 2 Output 0 0 0 2 2 0 2 2 Input 3 1 5 Output 0 0 0 2 0 4 1 1 1 3 1 5 2 0 2 2 2 4 Submitted Solution: ``` def main(): N, D1, D2 = map(int, input().split()) a1 = 0 a2 = 0 b1 = 0 b2 = 0 for i in range(int(D1**0.5)): if ((D1-i**2)**0.5)%1 == 0: a1 = i a2 = int((D1-i**2)**0.5) break for i in range(int(D2**0.5)): if ((D2-i**2)**0.5)%1 == 0: b1 = i b2 = int((D2-i**2)**0.5) break A = [[0 for _ in range(2*N)] for _ in range(2*N)] X = [] k = 0 for i in range(2*N): for j in range(2*N): if A[i][j] == 0: X.append([i,j]) k += 1 if i+a1<2*N: if j+a2<2*N: A[i+a1][j+a2]=1 if j-a2>=0: A[i+a1][j-a2]=1 if i+a2<2*N: if j+a1<2*N: A[i+a2][j+a1]=1 if j-a1>=0: A[i+a2][j-a1]=1 if i-a1>=0: if j+a2<2*N: A[i-a1][j+a2]=1 if j-a2>=0: A[i-a1][j-a2]=1 if i-a2>=0: if j+a1<2*N: A[i-a2][j+a1]=1 if j-a1>=0: A[i-a2][j-a1]=1 if i+b1<2*N: if j+b2<2*N: A[i+b1][j+b2]=1 if j-b2>=0: A[i+b1][j-b2]=1 if i+b2<2*N: if j+b1<2*N: A[i+b2][j+b1]=1 if j-b1>=0: A[i+b2][j-b1]=1 if i-b1>=0: if j+b2<2*N: A[i-b1][j+b2]=1 if j-a2>=0: A[i-b1][j-b2]=1 if i-b2>=0: if j+b1<2*N: A[i-b2][j+b1]=1 if j-b1>=0: A[i-b2][j-b1]=1 if k==N**2: break if k==N**2: break for i in range(N**2): print(str(X[i][0])+" "+str(X[i][1])) if __name__ == "__main__": main() ```
instruction
0
85,592
23
171,184
No
output
1
85,592
23
171,185
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Takahashi is doing a research on sets of points in a plane. Takahashi thinks a set S of points in a coordinate plane is a good set when S satisfies both of the following conditions: * The distance between any two points in S is not \sqrt{D_1}. * The distance between any two points in S is not \sqrt{D_2}. Here, D_1 and D_2 are positive integer constants that Takahashi specified. Let X be a set of points (i,j) on a coordinate plane where i and j are integers and satisfy 0 ≤ i,j < 2N. Takahashi has proved that, for any choice of D_1 and D_2, there exists a way to choose N^2 points from X so that the chosen points form a good set. However, he does not know the specific way to choose such points to form a good set. Find a subset of X whose size is N^2 that forms a good set. Constraints * 1 ≤ N ≤ 300 * 1 ≤ D_1 ≤ 2×10^5 * 1 ≤ D_2 ≤ 2×10^5 * All values in the input are integers. Input Input is given from Standard Input in the following format: N D_1 D_2 Output Print N^2 distinct points that satisfy the condition in the following format: x_1 y_1 x_2 y_2 : x_{N^2} y_{N^2} Here, (x_i,y_i) represents the i-th chosen point. 0 ≤ x_i,y_i < 2N must hold, and they must be integers. The chosen points may be printed in any order. In case there are multiple possible solutions, you can output any. Examples Input 2 1 2 Output 0 0 0 2 2 0 2 2 Input 3 1 5 Output 0 0 0 2 0 4 1 1 1 3 1 5 2 0 2 2 2 4 Submitted Solution: ``` import math n,d1,d2=map(int,input().split()) tmp = int(math.sqrt(max(d1,d2))) darr = [] for i in range(tmp+1): for j in range(i,tmp+1): if i*i + j*j == d1 or i*i + j*j == d2: if [i,j] not in darr and [j,i] not in darr: darr.append([i,j]) result = [] check = [] for x in range(2*n): if len(result) == n*n: break for y in range(2*n): if len(result) == n*n: break if [x,y] not in check: result.append([x,y]) for a in darr: if x+a[0] < 2*n and y+a[1] <= 2*n and [x+a[0],y+a[1]] not in check: check.append([x+a[0],y+a[1]]) if x+a[1] < 2*n and y+a[0] < 2*n and [x+a[1],y+a[0]] not in check: check.append([x+a[1],y+a[0]]) for r in result: print(str(r[0])+' '+str(r[1])) ```
instruction
0
85,593
23
171,186
No
output
1
85,593
23
171,187
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Takahashi is doing a research on sets of points in a plane. Takahashi thinks a set S of points in a coordinate plane is a good set when S satisfies both of the following conditions: * The distance between any two points in S is not \sqrt{D_1}. * The distance between any two points in S is not \sqrt{D_2}. Here, D_1 and D_2 are positive integer constants that Takahashi specified. Let X be a set of points (i,j) on a coordinate plane where i and j are integers and satisfy 0 ≤ i,j < 2N. Takahashi has proved that, for any choice of D_1 and D_2, there exists a way to choose N^2 points from X so that the chosen points form a good set. However, he does not know the specific way to choose such points to form a good set. Find a subset of X whose size is N^2 that forms a good set. Constraints * 1 ≤ N ≤ 300 * 1 ≤ D_1 ≤ 2×10^5 * 1 ≤ D_2 ≤ 2×10^5 * All values in the input are integers. Input Input is given from Standard Input in the following format: N D_1 D_2 Output Print N^2 distinct points that satisfy the condition in the following format: x_1 y_1 x_2 y_2 : x_{N^2} y_{N^2} Here, (x_i,y_i) represents the i-th chosen point. 0 ≤ x_i,y_i < 2N must hold, and they must be integers. The chosen points may be printed in any order. In case there are multiple possible solutions, you can output any. Examples Input 2 1 2 Output 0 0 0 2 2 0 2 2 Input 3 1 5 Output 0 0 0 2 0 4 1 1 1 3 1 5 2 0 2 2 2 4 Submitted Solution: ``` def judge(D): n = 0 while D%4==0: n += 1 D //= 4 return lambda x,y: ~((x>>n)^(y>>n))&1 if D%2==1 else lambda x,y: ~(x>>n)&1 N,D1,D2 = map(int,input().split()) j1,j2 = judge(D1),judge(D2) for _,(x,y) in zip(range(N*N),filter(lambda p: j1(*p) and j2(*p), ((x,y) for x in range(N*2) for y in range(N*2)))): print(x,y) ```
instruction
0
85,594
23
171,188
No
output
1
85,594
23
171,189
Provide a correct Python 3 solution for this coding contest problem. <image> For given three points p0, p1, p2, print COUNTER_CLOCKWISE if p0, p1, p2 make a counterclockwise turn (1), CLOCKWISE if p0, p1, p2 make a clockwise turn (2), ONLINE_BACK if p2 is on a line p2, p0, p1 in this order (3), ONLINE_FRONT if p2 is on a line p0, p1, p2 in this order (4), ON_SEGMENT if p2 is on a segment p0p1 (5). Constraints * 1 ≤ q ≤ 1000 * -10000 ≤ xi, yi ≤ 10000 * p0 and p1 are not identical. Input xp0 yp0 xp1 yp1 q xp20 yp20 xp21 yp21 ... xp2q-1 yp2q-1 In the first line, integer coordinates of p0 and p1 are given. Then, q queries are given for integer coordinates of p2. Output For each query, print the above mentioned status. Examples Input 0 0 2 0 2 -1 1 -1 -1 Output COUNTER_CLOCKWISE CLOCKWISE Input 0 0 2 0 3 -1 0 0 0 3 0 Output ONLINE_BACK ON_SEGMENT ONLINE_FRONT
instruction
0
85,688
23
171,376
"Correct Solution: ``` #! /usr/bin/env python3 from typing import List, Tuple from math import sqrt from enum import Enum EPS = 1e-10 def float_equal(x: float, y: float) -> bool: return abs(x - y) < EPS class PointLocation(Enum): COUNTER_CLOCKWISE = 1 CLOCKWISE = 2 ONLINE_BACK = 3 ONLINE_FRONT = 4 ON_SEGMENT = 5 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 (self - other).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_line(self, seg: 'Segment') -> float: return \ abs((self - seg.p1).cross(seg.vector())) / \ seg.length() def distance_to_segment(self, seg: 'Segment') -> float: if not self.in_side_of(seg): return self.distance(seg.p1) if not self.in_side_of(seg.reverse()): return self.distance(seg.p2) else: return self.distance_to_line(seg) def location(self, seg: 'Segment') -> PointLocation: p = self - seg.p1 d = seg.vector().cross(p) if d > EPS: return PointLocation.COUNTER_CLOCKWISE if d < -EPS: return PointLocation.CLOCKWISE if seg.vector().dot(p) < 0.0: return PointLocation.ONLINE_BACK if seg.vector().norm() < p.norm(): return PointLocation.ONLINE_FRONT return PointLocation.ON_SEGMENT 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 length(self) -> float: return self.p1.distance(self.p2) 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: x0, y0, x1, y1 = [int(x) for x in input().split()] s = Segment(Point(x0, y0), Point(x1, y1)) q = int(input()) for _ in range(q): x2, y2 = [int(x) for x in input().split()] print(Point(x2, y2).location(s).name) if __name__ == "__main__": main() ```
output
1
85,688
23
171,377
Provide a correct Python 3 solution for this coding contest problem. <image> For given three points p0, p1, p2, print COUNTER_CLOCKWISE if p0, p1, p2 make a counterclockwise turn (1), CLOCKWISE if p0, p1, p2 make a clockwise turn (2), ONLINE_BACK if p2 is on a line p2, p0, p1 in this order (3), ONLINE_FRONT if p2 is on a line p0, p1, p2 in this order (4), ON_SEGMENT if p2 is on a segment p0p1 (5). Constraints * 1 ≤ q ≤ 1000 * -10000 ≤ xi, yi ≤ 10000 * p0 and p1 are not identical. Input xp0 yp0 xp1 yp1 q xp20 yp20 xp21 yp21 ... xp2q-1 yp2q-1 In the first line, integer coordinates of p0 and p1 are given. Then, q queries are given for integer coordinates of p2. Output For each query, print the above mentioned status. Examples Input 0 0 2 0 2 -1 1 -1 -1 Output COUNTER_CLOCKWISE CLOCKWISE Input 0 0 2 0 3 -1 0 0 0 3 0 Output ONLINE_BACK ON_SEGMENT ONLINE_FRONT
instruction
0
85,689
23
171,378
"Correct Solution: ``` import sys import math input = sys.stdin.readline class Vector(): def __init__(self, x, y): self.x = x self.y = y def __add__(self, vec): return Vector(self.x+vec.x, self.y+vec.y) def __sub__(self, vec): return Vector(self.x-vec.x, self.y-vec.y) def __mul__(self, sc): return Vector(self.x*sc, self.y*sc) def __truediv__(self, sc): return Vector(self.x/sc, self.y/sc) def __iadd__(self, vec): self.x += vec.x self.y += vec.y return self def __isub__(self, vec): self.x -= vec.x self.y -= vec.y return self def __imul__(self, sc): self.x *= sc self.y *= sc return self def __itruediv__(self, sc): self.x /= sc self.y /= sc return self def __str__(self): return '{:.9f} {:.9f}'.format(self.x, self.y) def __eq__(self, vec): return self.x == vec.x and self.y == vec.y def dot(self, vec): return self.x * vec.x + self.y * vec.y def cross(self, vec): return self.x * vec.y - self.y * vec.x def abs(self): return (self.x*self.x + self.y*self.y)**0.5 def ortho(self): return Vector(-self.y, self.x) x0, y0, x1, y1 = map(int, input().split()) p0 = Vector(x0, y0) p1 = Vector(x1, y1) v1 = p1-p0 for _ in [0]*int(input()): x, y = map(int, input().split()) p2 = Vector(x, y) v2 = p2-p0 det = v2.cross(v1) if det > 0: print('CLOCKWISE') elif det < 0: print('COUNTER_CLOCKWISE') elif v2.dot(v1) < 0: print('ONLINE_BACK') elif v2.dot(v2) > v1.dot(v1): print('ONLINE_FRONT') else: print('ON_SEGMENT') ```
output
1
85,689
23
171,379
Provide a correct Python 3 solution for this coding contest problem. <image> For given three points p0, p1, p2, print COUNTER_CLOCKWISE if p0, p1, p2 make a counterclockwise turn (1), CLOCKWISE if p0, p1, p2 make a clockwise turn (2), ONLINE_BACK if p2 is on a line p2, p0, p1 in this order (3), ONLINE_FRONT if p2 is on a line p0, p1, p2 in this order (4), ON_SEGMENT if p2 is on a segment p0p1 (5). Constraints * 1 ≤ q ≤ 1000 * -10000 ≤ xi, yi ≤ 10000 * p0 and p1 are not identical. Input xp0 yp0 xp1 yp1 q xp20 yp20 xp21 yp21 ... xp2q-1 yp2q-1 In the first line, integer coordinates of p0 and p1 are given. Then, q queries are given for integer coordinates of p2. Output For each query, print the above mentioned status. Examples Input 0 0 2 0 2 -1 1 -1 -1 Output COUNTER_CLOCKWISE CLOCKWISE Input 0 0 2 0 3 -1 0 0 0 3 0 Output ONLINE_BACK ON_SEGMENT ONLINE_FRONT
instruction
0
85,690
23
171,380
"Correct Solution: ``` from math import sqrt x0,y0,x1,y1 = map(int, input().split()) a = [x0,y0] b = [x1, y1] q = int(input()) CCW = {1: 'COUNTER_CLOCKWISE', 2: 'CLOCKWISE', 3: 'ONLINE_BACK', 4: 'ONLINE_FRONT', 5: 'ON_SEGMENT',} 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 _abs(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 2 if dot(x,y)<0: return 3 if _abs(x) < _abs(y): return 4 return 5 for i in range(q): c = list(map(int, input().split())) print(CCW[ccw(a,b,c)]) ```
output
1
85,690
23
171,381
Provide a correct Python 3 solution for this coding contest problem. <image> For given three points p0, p1, p2, print COUNTER_CLOCKWISE if p0, p1, p2 make a counterclockwise turn (1), CLOCKWISE if p0, p1, p2 make a clockwise turn (2), ONLINE_BACK if p2 is on a line p2, p0, p1 in this order (3), ONLINE_FRONT if p2 is on a line p0, p1, p2 in this order (4), ON_SEGMENT if p2 is on a segment p0p1 (5). Constraints * 1 ≤ q ≤ 1000 * -10000 ≤ xi, yi ≤ 10000 * p0 and p1 are not identical. Input xp0 yp0 xp1 yp1 q xp20 yp20 xp21 yp21 ... xp2q-1 yp2q-1 In the first line, integer coordinates of p0 and p1 are given. Then, q queries are given for integer coordinates of p2. Output For each query, print the above mentioned status. Examples Input 0 0 2 0 2 -1 1 -1 -1 Output COUNTER_CLOCKWISE CLOCKWISE Input 0 0 2 0 3 -1 0 0 0 3 0 Output ONLINE_BACK ON_SEGMENT ONLINE_FRONT
instruction
0
85,691
23
171,382
"Correct Solution: ``` pp = list(map(int, input().split())) n = int(input()) def cross(a, b): return a[0]*b[1]-a[1]*b[0] def dot(a, b): n = len(a) if n != len(b): return None ans = 0 for i, j in zip(a, b): ans += i*j return ans for i in range(n): bb = list(map(int, input().split())) a = (pp[2]-pp[0], pp[3]-pp[1]) b = (bb[0]-pp[0], bb[1]-pp[1]) if cross(a, b) > 0: print("COUNTER_CLOCKWISE") elif cross(a, b) < 0: print("CLOCKWISE") else: if dot(a,b)<0: print("ONLINE_BACK") elif dot(a, (b[0]-a[0],b[1]-a[1]))>0: print("ONLINE_FRONT") else: print("ON_SEGMENT") ```
output
1
85,691
23
171,383
Provide a correct Python 3 solution for this coding contest problem. <image> For given three points p0, p1, p2, print COUNTER_CLOCKWISE if p0, p1, p2 make a counterclockwise turn (1), CLOCKWISE if p0, p1, p2 make a clockwise turn (2), ONLINE_BACK if p2 is on a line p2, p0, p1 in this order (3), ONLINE_FRONT if p2 is on a line p0, p1, p2 in this order (4), ON_SEGMENT if p2 is on a segment p0p1 (5). Constraints * 1 ≤ q ≤ 1000 * -10000 ≤ xi, yi ≤ 10000 * p0 and p1 are not identical. Input xp0 yp0 xp1 yp1 q xp20 yp20 xp21 yp21 ... xp2q-1 yp2q-1 In the first line, integer coordinates of p0 and p1 are given. Then, q queries are given for integer coordinates of p2. Output For each query, print the above mentioned status. Examples Input 0 0 2 0 2 -1 1 -1 -1 Output COUNTER_CLOCKWISE CLOCKWISE Input 0 0 2 0 3 -1 0 0 0 3 0 Output ONLINE_BACK ON_SEGMENT ONLINE_FRONT
instruction
0
85,692
23
171,384
"Correct Solution: ``` # coding=utf-8 def cross_product(vect1, vect2): return vect1[0]*vect2[1] - vect1[1]*vect2[0] def vector_plus(vect1, vect2): return [el1 + el2 for el1, el2 in zip(vect1, vect2)] def vector_minus(vect1, vect2): return [el1 - el2 for el1, el2 in zip(vect1, vect2)] def vector_product(vect1, vect2): return [el1 * el2 for el1, el2 in zip(vect1, vect2)] def vector_divide(vect1, vect2): return [el1 / el2 for el1, el2 in zip(vect1, vect2)] def which_place(origin, line_to1, line_to2): line1 = vector_minus(line_to1, origin) line2 = vector_minus(line_to2, origin) judge = cross_product(line1, line2) if judge > 0: return "COUNTER_CLOCKWISE" if judge < 0: return "CLOCKWISE" if judge == 0: try: judge2 = line2[0]/line1[0] except ZeroDivisionError: judge2 = line2[1]/line1[1] if judge2 < 0: return "ONLINE_BACK" if judge2 > 1: return "ONLINE_FRONT" else: return "ON_SEGMENT" if __name__ == '__main__': xy_list = list(map(int, input().split())) p0_list = xy_list[:2] p1_list = xy_list[2:] Q = int(input()) for i in range(Q): p2_list = list(map(int, input().split())) place = which_place(p0_list, p1_list, p2_list) print(place) ```
output
1
85,692
23
171,385