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 Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:
* Elements of the main diagonal.
* Elements of the secondary diagonal.
* Elements of the "middle" row — the row which has exactly <image> rows above it and the same number of rows below it.
* Elements of the "middle" column — the column that has exactly <image> columns to the left of it and the same number of columns to the right of it.
<image> The figure shows a 5 × 5 matrix. The good elements are marked with green.
Help the Smart Beaver count the sum of good elements of the given matrix.
Input
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix.
The input limitations for getting 30 points are:
* 1 ≤ n ≤ 5
The input limitations for getting 100 points are:
* 1 ≤ n ≤ 101
Output
Print a single integer — the sum of good matrix elements.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
45
Input
5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Output
17
Note
In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Submitted Solution:
```
n=int(input())
y=[]
s=0
j=0
for i in range(n):
x=list(map(int,input().split()))
y.append(x)
for i in range(n):
s+=y[i][i]
for i in range(n):
s+=y[i][-i]
for i in range(i):
s+=y[n//2][i]
s+=y[i][n//2]
print(s-1)
``` | instruction | 0 | 108,128 | 23 | 216,256 |
No | output | 1 | 108,128 | 23 | 216,257 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:
* Elements of the main diagonal.
* Elements of the secondary diagonal.
* Elements of the "middle" row — the row which has exactly <image> rows above it and the same number of rows below it.
* Elements of the "middle" column — the column that has exactly <image> columns to the left of it and the same number of columns to the right of it.
<image> The figure shows a 5 × 5 matrix. The good elements are marked with green.
Help the Smart Beaver count the sum of good elements of the given matrix.
Input
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix.
The input limitations for getting 30 points are:
* 1 ≤ n ≤ 5
The input limitations for getting 100 points are:
* 1 ≤ n ≤ 101
Output
Print a single integer — the sum of good matrix elements.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
45
Input
5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Output
17
Note
In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Submitted Solution:
```
n = int(input())
a = []
b = [1]
for i in range(0,n):
a.append(1)
for i in range(1,n):
b = [1]
for j in range(1,n):
k = a[j] + b[j-1]
b.append(k)
a = b
print(b[n-1])
``` | instruction | 0 | 108,129 | 23 | 216,258 |
No | output | 1 | 108,129 | 23 | 216,259 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 ≤ n ≤ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either « / » (slash), « \ » (backslash), « » (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span"> / </span><span class="tex-span">\</span><span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Input
3
1 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt | instruction | 0 | 108,201 | 23 | 216,402 |
Tags: implementation
Correct Solution:
```
import sys
from math import *
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
n = mint()
y = 0
x = 0
a = []
t = 0
mx = dict()
my = 10**9
for i in mints():
for j in range(i):
if t == 0:
a.append((x,y,'/'))
mx[y] = max(mx.get(y, -1), x)
my = min(my, y)
y -= 1
else:
y += 1
a.append((x,y,'\\'))
mx[y] = max(mx.get(y, -1), x)
my = min(my, y)
x += 1
t ^= 1
i = 0
b = []
while (my+i) in mx:
b.append([' ']*(mx[my+i]+1))
i += 1
for i in a:
b[i[1]-my][i[0]] = i[2]
for i in b:
print(*(i+[' ']*(x-len(i))),sep='')
``` | output | 1 | 108,201 | 23 | 216,403 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 ≤ n ≤ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either « / » (slash), « \ » (backslash), « » (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span"> / </span><span class="tex-span">\</span><span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Input
3
1 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt | instruction | 0 | 108,202 | 23 | 216,404 |
Tags: implementation
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
x = [0] * (n + 1)
y = [0] * (n + 1)
for i in range(1, n + 1):
x[i] = x[i - 1] + a[i - 1]
y[i] = y[i - 1]
if i % 2 == 0:
y[i] -= a[i - 1]
else:
y[i] += a[i - 1]
m = min(y)
if m < 0:
for i in range(n + 1):
y[i] -= m
w = max(x)
h = max(y)
d = [[" "] * w for i in range(h)]
for i in range(n):
if y[i] < y[i + 1]:
for j in range(a[i]):
d[y[i] + j][x[i] + j] = "/"
else:
for j in range(a[i]):
d[y[i] - j - 1][x[i] + j] = "\\"
print("\n".join("".join(d[i]) for i in reversed(range(h))))
``` | output | 1 | 108,202 | 23 | 216,405 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 ≤ n ≤ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either « / » (slash), « \ » (backslash), « » (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span"> / </span><span class="tex-span">\</span><span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Input
3
1 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt | instruction | 0 | 108,203 | 23 | 216,406 |
Tags: implementation
Correct Solution:
```
n = input()
a = list(map(int,input().split()))
l = sum(a)
h = maxh = minh = 1000
table = [[" "]*l for i in range(2001)]
k = 0
sign = 1
for i in a:
if sign == 1:
for j in range(i):
table[h+j][k+j] = "/"
maxh = max(maxh,h+(i-1))
h += i-1
else:
for j in range(i):
table[h-j][k+j] = "\\"
minh = min(minh,h-(i-1))
h -= i-1
k += i
sign *= -1
for i in range(maxh,minh-1,-1):
print (''.join(table[i]))
``` | output | 1 | 108,203 | 23 | 216,407 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 ≤ n ≤ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either « / » (slash), « \ » (backslash), « » (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span"> / </span><span class="tex-span">\</span><span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Input
3
1 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt | instruction | 0 | 108,204 | 23 | 216,408 |
Tags: implementation
Correct Solution:
```
n=int(input())
l=list(map(int, input().split()))
mx=0
mn=0
s=0
sm=0
a=[0]*(n+1)
for i in range(n):
sm+=l[i]
if i%2==0:
s+=l[i]
else:
s-=l[i]
mx=max(mx,s)
mn=min(mn,s)
a[i+1]=s
for i in range(n+1):
a[i]-=mn
mat=[]
for i in range(mx-mn):
ll=[" "]*sm
mat.append(ll)
j=a[0]
k=0
a.append(5)
# print(a,mx,mn,sm)
f=0
for i in range(n):
for g in range(l[i]):
# print(i,j,k)
if i%2==0:
if f==1:
j+=1
f=0
mat[j][k]="/"
k+=1
j+=1
if j>=a[i+1]:
j-=1
else:
# print(j,k)
mat[j][k]='\\'
k+=1
j-=1
f=1
# if j<=a[i+1]:
# j+=1
i=len(mat)-1
while(i>=0):
for j in mat[i]:
print(j,end="")
print()
i-=1
# for i in l:
# print(i)
# print(1)
``` | output | 1 | 108,204 | 23 | 216,409 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 ≤ n ≤ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either « / » (slash), « \ » (backslash), « » (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span"> / </span><span class="tex-span">\</span><span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Input
3
1 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt | instruction | 0 | 108,205 | 23 | 216,410 |
Tags: implementation
Correct Solution:
```
N = int(2e3+3)
n = int(input())
a = list(map(int, input().split()))
maxi, mini = N//2, N//2
res = [[' '] * N for i in range(N)]
x, y = N//2, 0
for i in range(n):
if i % 2 == 0:
for j in range(a[i]):
res[x][y] = '/'
x -= 1
y += 1
x += 1
else:
for j in range(a[i]):
res[x][y] = '\\'
x += 1
y += 1
x -= 1
maxi = max(maxi, x)
mini = min(mini, x)
for i in range(mini, maxi+1):
print(''.join(res[i][:y]))
``` | output | 1 | 108,205 | 23 | 216,411 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 ≤ n ≤ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either « / » (slash), « \ » (backslash), « » (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span"> / </span><span class="tex-span">\</span><span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Input
3
1 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt | instruction | 0 | 108,206 | 23 | 216,412 |
Tags: implementation
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
x = [0] * (n + 1)
y = [0] * (n + 1)
for i in range(1, n + 1):
x[i] = x[i - 1] + a[i - 1]
y[i] = y[i - 1]
if i % 2 == 0:
y[i] -= a[i - 1]
else:
y[i] += a[i - 1]
# print(x)
# print(y)
m = min(y)
if m < 0:
for i in range(n + 1):
y[i] -= m
# print(y)
w = max(x)
h = max(y)
# print(h, w)
d = [[" "] * w for i in range(h)]
for i in range(n):
if y[i] < y[i + 1]:
for j in range(a[i]):
# print(y[i] + j, x[i] + j, "/")
d[y[i] + j][x[i] + j] = "/"
else:
for j in range(a[i]):
# print(y[i] - j - 1, x[i] + j, "\\")
d[y[i] - j - 1][x[i] + j] = "\\"
print("\n".join("".join(d[i]) for i in reversed(range(h))))
``` | output | 1 | 108,206 | 23 | 216,413 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 ≤ n ≤ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either « / » (slash), « \ » (backslash), « » (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span"> / </span><span class="tex-span">\</span><span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Input
3
1 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt | instruction | 0 | 108,207 | 23 | 216,414 |
Tags: implementation
Correct Solution:
```
n, a = int(input()), list(map(int, input().split()))
if n & 1: a.append(0)
x, t = 0, [[' '] * sum(a) for i in range(2001)]
y = u = v = 1000
for i in range(0, n, 2):
for j in range(a[i]):
t[y][x] = '/'
x += 1
y += 1
v = max(v, y)
for j in range(a[i + 1]):
y -= 1
t[y][x] = '\\'
x += 1
u = min(u, y)
for i in range(v - 1, u - 1, -1): print(''.join(t[i]))
# Made By Mostafa_Khaled
``` | output | 1 | 108,207 | 23 | 216,415 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 ≤ n ≤ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either « / » (slash), « \ » (backslash), « » (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span"> / </span><span class="tex-span">\</span><span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Input
3
1 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt | instruction | 0 | 108,208 | 23 | 216,416 |
Tags: implementation
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
graph = [[' '] * 1000 for _ in range(2001)]
x, y = 0, 1000
for i in range(n):
for j in range(a[i]):
if i % 2:
graph[y][x] = '\\'
if j != a[i] - 1:
y += 1
else:
graph[y][x] = '/'
if j != a[i] - 1:
y -= 1
x += 1
for i in range(2000, -1, -1):
graph[i] = ''.join(graph[i][:x])
if not len(set(graph[i]) & set(['/', '\\'])):
graph.pop(i)
print('\n'.join(graph))
``` | output | 1 | 108,208 | 23 | 216,417 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 ≤ n ≤ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either « / » (slash), « \ » (backslash), « » (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span"> / </span><span class="tex-span">\</span><span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Input
3
1 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt
Submitted Solution:
```
import operator
n = int(input())
a = tuple(map(int, str.split(input())))
p = [(0, 0)]
for i, x in enumerate(a):
p.append((p[-1][0] + x, p[-1][1] + (-1) ** i * x))
ymax = max(p, key=operator.itemgetter(1))[1]
ymin = min(p, key=operator.itemgetter(1))[1]
columns = []
for i in range(n):
x1, y1 = p[i]
x2, y2 = p[i + 1]
while x1 != x2:
if y1 < y2:
columns.append(" " * (ymax - y1 - 1) + "/" + " " * (y1 - ymin))
y1 += 1
else:
columns.append(" " * (ymax - y1) + "\\" + " " * (y1 - ymin - 1))
y1 -= 1
x1 += 1
print(str.join("\n", map(lambda t: str.join("", t), zip(*columns))))
``` | instruction | 0 | 108,209 | 23 | 216,418 |
Yes | output | 1 | 108,209 | 23 | 216,419 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 ≤ n ≤ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either « / » (slash), « \ » (backslash), « » (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span"> / </span><span class="tex-span">\</span><span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Input
3
1 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt
Submitted Solution:
```
import math,sys
#from itertools import permutations, combinations;import heapq,random;
from collections import defaultdict,deque
import bisect as bi
def yes():print('YES')
def no():print('NO')
def I():return (int(sys.stdin.readline()))
def In():return(map(int,sys.stdin.readline().split()))
def Sn():return sys.stdin.readline().strip()
#sys.setrecursionlimit(1500)
def dict(a):
d={}
for x in a:
if d.get(x,-1)!=-1:
d[x]+=1
else:
d[x]=1
return d
def find_gt(a, x):
'Find leftmost value greater than x'
i = bi.bisect_left(a, x)
if i != len(a):
return i
else:
return -1
def main():
try:
n=I()
l=list(In())
su,mx,t=0,0,0
for i in range(n):
su+=l[i]
if i&1:
t-=l[i]
else:
t+=l[i]
mx=max(l[i],mx,abs(t))
ans=[[' ' for i in range(su)] for j in range(2*(mx+1))]
st_y=mx
st_x=0
for i in range(n):
for j in range(l[i]):
if i%2==0:
ans[st_y][st_x]='/'
if j!=l[i]-1:
st_y-=1
st_x+=1
else:
ans[st_y][st_x]="\\"
if j!=l[i]-1:
st_y+=1
st_x+=1
for x in ans:
if x.count('\\')+x.count('/'):
print(''.join(x))
except:
pass
M = 998244353
P = 1000000007
if __name__ == '__main__':
# for _ in range(I()):main()
for _ in range(1):main()
# ******************* All The Best ******************* #
``` | instruction | 0 | 108,210 | 23 | 216,420 |
Yes | output | 1 | 108,210 | 23 | 216,421 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 ≤ n ≤ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either « / » (slash), « \ » (backslash), « » (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span"> / </span><span class="tex-span">\</span><span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Input
3
1 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt
Submitted Solution:
```
n = int(input())
a = [int(i) for i in input().split()]
miny = 0
maxy = 0
s = 0
for i in range(n):
if i % 2 == 0:
s += a[i]
else:
s -= a[i]
maxy = max(s, maxy)
miny = min(s, miny)
dif = maxy - miny
size = sum(a)
res = [[" "] * size for i in range(dif)]
cur = [maxy, 0]
for i in range(n):
if i % 2 == 0:
cur[0] -= 1
else:
cur[0] += 1
for j in range(a[i]):
if i % 2 == 0:
res[cur[0]][cur[1]] = "/"
cur[0] -= 1
else:
res[cur[0]][cur[1]] = "\\"
cur[0] += 1
cur[1] += 1
for i in res:
print("".join(i))
``` | instruction | 0 | 108,211 | 23 | 216,422 |
Yes | output | 1 | 108,211 | 23 | 216,423 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 ≤ n ≤ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either « / » (slash), « \ » (backslash), « » (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span"> / </span><span class="tex-span">\</span><span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Input
3
1 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt
Submitted Solution:
```
import operator
n = int(input())
points = list(map(int, input().split()))
def praf(g):
for i in g[1:]:
print(''.join(i))
def calc(n):
global points
a = b = 0
step = 1
for i in range(n):
a += points[i]
b += points[i] * step
step = -step
return (a, b)
seq = [(0, 0)]
for i in range(len(points)):
seq.append(calc(i+1))
seq = sorted(seq, key=lambda x: x[0])
seq = {i: seq[i] for i in range(len(seq))}
#print(seq)
for i in range(len(seq)):
r = 0
if i != len(seq)-1:
if seq[i][1] > seq[i+1][1]:
r = -1
else:
r = 1
seq[i] = seq[i] + tuple([r])
seqy = sorted(seq.items(), key=lambda x: x[1][1], reverse=True)
pts = {x[0]: x[2] for x in seq.values()}
pts[seq[len(seq)-1][0]] = 1
#print('---seq---')
#print(seq)
#print('----seqy---')
#print(seqy)
#print('---pts---')
#print(pts)
graph = [[' '] * seq[len(seq)-1][0] for x in range(seqy[0][1][1]-seqy[-1][1][1]+1)]
y = seqy[0][1][1]
way = pts[0]
for i in range(len(graph[0])):
if i in pts.keys():
if pts[i] != way:
if way == 1:
y+=1
else:
y-=1
way = pts[i]
graph[y][i] = '/' if way == 1 else '\\'
y -= way
# praf(graph)
#print('----------------graph-----------------------------------------------------------')
praf(graph)
#praf(graph)
``` | instruction | 0 | 108,212 | 23 | 216,424 |
Yes | output | 1 | 108,212 | 23 | 216,425 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 ≤ n ≤ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either « / » (slash), « \ » (backslash), « » (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span"> / </span><span class="tex-span">\</span><span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Input
3
1 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt
Submitted Solution:
```
n = int(input())
cardio = list(map(int, input().split()))
strings = [' ' * (sum(cardio) + 1) for i in range(2500)]
xc = 0
yc = 1250
for i in range(n):
for j in range(cardio[i]):
xc += 1
if i % 2 == 0:
yc -= 1
strings[yc] = strings[yc][:xc] + '/' + strings[yc][xc + 1:]
else:
yc += 1
strings[yc] = strings[yc][:xc] + chr(92) + strings[yc][xc + 1:]
if i % 2 == 0:
yc -= 1
else:
yc += 1
i = 0
while max(strings[i]) == ' ':
i += 1
for j in range(i, i + max(cardio)):
print(strings[j][1:])
``` | instruction | 0 | 108,213 | 23 | 216,426 |
No | output | 1 | 108,213 | 23 | 216,427 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 ≤ n ≤ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either « / » (slash), « \ » (backslash), « » (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span"> / </span><span class="tex-span">\</span><span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Input
3
1 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt
Submitted Solution:
```
import math,sys
#from itertools import permutations, combinations;import heapq,random;
from collections import defaultdict,deque
import bisect as bi
def yes():print('YES')
def no():print('NO')
def I():return (int(sys.stdin.readline()))
def In():return(map(int,sys.stdin.readline().split()))
def Sn():return sys.stdin.readline().strip()
#sys.setrecursionlimit(1500)
def dict(a):
d={}
for x in a:
if d.get(x,-1)!=-1:
d[x]+=1
else:
d[x]=1
return d
def find_gt(a, x):
'Find leftmost value greater than x'
i = bi.bisect_left(a, x)
if i != len(a):
return i
else:
return -1
def main():
try:
n=I()
l=list(In())
su,mx,t=0,0,0
for i in range(n):
su+=l[i]
if i&1:
t-=l[i]
else:
t+=l[i]
mx=max(l[i],mx,abs(t))
ans=[[' ' for i in range(su)] for j in range(2*(mx+1))]
st_y=mx
st_x=0
for i in range(n):
for j in range(l[i]):
if i%2==0:
ans[st_y][st_x]='/'
if j!=l[i]-1:
st_y-=1
st_x+=1
else:
ans[st_y][st_x]="\\"
if j!=l[i]-1:
st_y+=1
st_x+=1
for x in ans:
if x.count('\\')+x.count('/'):
print(*x)
except:
pass
M = 998244353
P = 1000000007
if __name__ == '__main__':
# for _ in range(I()):main()
for _ in range(1):main()
# ******************* All The Best ******************* #
``` | instruction | 0 | 108,214 | 23 | 216,428 |
No | output | 1 | 108,214 | 23 | 216,429 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 ≤ n ≤ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either « / » (slash), « \ » (backslash), « » (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span"> / </span><span class="tex-span">\</span><span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Input
3
1 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt
Submitted Solution:
```
n = input()
a = list(map(int,input().split()))
l = sum(a)
h = maxh = minh = 1000
table = [[" "]*l for i in range(2001)]
k = 0
sign = 1
for i in a:
if sign == 1:
for j in range(i):
table[h+j][k+j] = "/"
maxh = max(maxh,h+(i-1))
h += i-1
else:
for j in range(i):
table[h-j][k+j] = "\\"
minh = min(minh,h-(i-1))
h -= i-1
k += i
sign *= -1
for i in range(maxh,minh-1,-1):
print (" ".join(table[i]))
``` | instruction | 0 | 108,215 | 23 | 216,430 |
No | output | 1 | 108,215 | 23 | 216,431 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 ≤ n ≤ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either « / » (slash), « \ » (backslash), « » (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span"> / </span><span class="tex-span">\</span><span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span"> / </span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Input
3
1 5 1
Output
<span class="tex-span"> / </span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span"> / </span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt
Submitted Solution:
```
n = int(input())
lis = list(map(int,input().split()))
ma=r=0
mi=a=0
for i in range(n):
if i%2==0:
a+=lis[i]
else:
a-=lis[i]
ma=max(ma,a)
mi=min(mi,a)
r+=lis[i]
mat=[[' ']*(r) for i in range(ma+abs(mi)+2)]
ro=ma
col=0
for i in range(n):
if i%2==0:
ro-=1
for k in range(lis[i]):
mat[ro][col]='/'
ro-=1
col+=1
else:
ro+=1
for k in range(lis[i]):
mat[ro][col]='\\'
ro+=1
col+=1
for i in mat[:]:
print(*i)
``` | instruction | 0 | 108,216 | 23 | 216,432 |
No | output | 1 | 108,216 | 23 | 216,433 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya trains to compose crossword puzzles. He can only compose crosswords of a very simplе type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular "eight" or infinity sign, not necessarily symmetrical.
The top-left corner of the crossword coincides with the top-left corner of the rectangle. The same thing is correct for the right-bottom corners. The crossword can't degrade, i.e. it always has exactly four blank areas, two of which are surrounded by letters. Look into the output for the samples for clarification.
Help Vasya — compose a crossword of the described type using the given six words. It is allowed to use the words in any order.
Input
Six lines contain the given words. Every word consists of no more than 30 and no less than 3 uppercase Latin letters.
Output
If it is impossible to solve the problem, print Impossible. Otherwise, print the sought crossword. All the empty squares should be marked as dots.
If there can be several solutions to that problem, print the lexicographically minimum one. I.e. the solution where the first line is less than the first line of other solutions should be printed. If the two lines are equal, compare the second lines and so on. The lexicographical comparison of lines is realized by the < operator in the modern programming languages.
Examples
Input
NOD
BAA
YARD
AIRWAY
NEWTON
BURN
Output
BAA...
U.I...
R.R...
NEWTON
..A..O
..YARD
Input
AAA
AAA
AAAAA
AAA
AAA
AAAAA
Output
AAA..
A.A..
AAAAA
..A.A
..AAA
Input
PTC
JYNYFDSGI
ZGPPC
IXEJNDOP
JJFS
SSXXQOFGJUZ
Output
JJFS....
Y..S....
N..X....
Y..X....
F..Q....
D..O....
S..F....
G..G....
IXEJNDOP
...U...T
...ZGPPC
Submitted Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
from itertools import permutations
def main():
s = [input().strip() for _ in range(6)]
ans = [['a']*30 for _ in range(30)]
dx = [0,1,0,-1,0,-1]
dy = [1,0,1,0,-1,0]
for i in enumerate(permutations(s)):
i = list(i[1])
i[3],i[4],i[5] = i[3][::-1],i[4][::-1],i[5][::-1]
fl = 0
for j in range(1,7):
if i[j%6][0] != i[j-1][-1]:
fl = 1
break
if fl:
continue
ans1 = [['a']*30 for _ in range(30)]
x,y,fl = 0,0,0
for ind,j in enumerate(i):
for ch in j:
if x < 0 or y < 0:
fl = 1
break
ans1[x][y] = ch
x += dx[ind]
y += dy[ind]
if fl:
break
x -= dx[ind]
y -= dy[ind]
if fl or x or y:
continue
ans = min(ans,ans1)
if ans == [['a']*30 for _ in range(30)]:
print('Impossible')
exit()
ma = 0
for i in range(30):
ma = max(ma,30-ans[i].count('a'))
fin = []
for i in range(30):
fin.append(''.join(ans[i][:ma]))
fin[-1] = fin[-1].replace('a','.')
if fin[-1] == '.'*ma:
fin.pop()
break
print(*fin,sep='\n')
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | instruction | 0 | 108,222 | 23 | 216,444 |
No | output | 1 | 108,222 | 23 | 216,445 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya trains to compose crossword puzzles. He can only compose crosswords of a very simplе type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular "eight" or infinity sign, not necessarily symmetrical.
The top-left corner of the crossword coincides with the top-left corner of the rectangle. The same thing is correct for the right-bottom corners. The crossword can't degrade, i.e. it always has exactly four blank areas, two of which are surrounded by letters. Look into the output for the samples for clarification.
Help Vasya — compose a crossword of the described type using the given six words. It is allowed to use the words in any order.
Input
Six lines contain the given words. Every word consists of no more than 30 and no less than 3 uppercase Latin letters.
Output
If it is impossible to solve the problem, print Impossible. Otherwise, print the sought crossword. All the empty squares should be marked as dots.
If there can be several solutions to that problem, print the lexicographically minimum one. I.e. the solution where the first line is less than the first line of other solutions should be printed. If the two lines are equal, compare the second lines and so on. The lexicographical comparison of lines is realized by the < operator in the modern programming languages.
Examples
Input
NOD
BAA
YARD
AIRWAY
NEWTON
BURN
Output
BAA...
U.I...
R.R...
NEWTON
..A..O
..YARD
Input
AAA
AAA
AAAAA
AAA
AAA
AAAAA
Output
AAA..
A.A..
AAAAA
..A.A
..AAA
Input
PTC
JYNYFDSGI
ZGPPC
IXEJNDOP
JJFS
SSXXQOFGJUZ
Output
JJFS....
Y..S....
N..X....
Y..X....
F..Q....
D..O....
S..F....
G..G....
IXEJNDOP
...U...T
...ZGPPC
Submitted Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
from itertools import permutations
def main():
s = [input().strip() for _ in range(6)]
ans = [['a']*30 for _ in range(30)]
dx = [0,1,0,-1,0,-1]
dy = [1,0,1,0,-1,0]
for i in enumerate(permutations(s)):
i = list(i[1])
i[3],i[4],i[5] = i[3][::-1],i[4][::-1],i[5][::-1]
fl = 0
for j in range(1,7):
if i[j%6][0] != i[j-1][-1]:
fl = 1
break
if fl:
continue
ans1 = [['a']*30 for _ in range(30)]
x,y,fl,s = 0,0,0,-1
for ind,j in enumerate(i):
for ch in j:
if x < 0 or y < 0 or x >= 30 or y >= 30:
fl = 1
break
ans1[x][y] = ch
x += dx[ind]
y += dy[ind]
if fl:
break
x -= dx[ind]
y -= dy[ind]
if s == -1:
s = y
if s != -1:
ii = 0
for xx in i[1]:
if ans1[ii][s] != xx:
fl = 1
break
ii += 1
if fl or x or y:
continue
for ii in range(30):
if ans1[ii] < ans[ii]:
ans = ans1
break
elif ans1[ii] > ans[ii]:
break
if ans == [['a']*30 for _ in range(30)]:
print('Impossible')
exit()
ma = 0
for i in range(30):
ma = max(ma,30-ans[i].count('a'))
fin = []
for i in range(30):
fin.append(''.join(ans[i][:ma]))
fin[-1] = fin[-1].replace('a','.')
if fin[-1] == '.'*ma:
fin.pop()
break
print(*fin,sep='\n')
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | instruction | 0 | 108,223 | 23 | 216,446 |
No | output | 1 | 108,223 | 23 | 216,447 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya trains to compose crossword puzzles. He can only compose crosswords of a very simplе type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular "eight" or infinity sign, not necessarily symmetrical.
The top-left corner of the crossword coincides with the top-left corner of the rectangle. The same thing is correct for the right-bottom corners. The crossword can't degrade, i.e. it always has exactly four blank areas, two of which are surrounded by letters. Look into the output for the samples for clarification.
Help Vasya — compose a crossword of the described type using the given six words. It is allowed to use the words in any order.
Input
Six lines contain the given words. Every word consists of no more than 30 and no less than 3 uppercase Latin letters.
Output
If it is impossible to solve the problem, print Impossible. Otherwise, print the sought crossword. All the empty squares should be marked as dots.
If there can be several solutions to that problem, print the lexicographically minimum one. I.e. the solution where the first line is less than the first line of other solutions should be printed. If the two lines are equal, compare the second lines and so on. The lexicographical comparison of lines is realized by the < operator in the modern programming languages.
Examples
Input
NOD
BAA
YARD
AIRWAY
NEWTON
BURN
Output
BAA...
U.I...
R.R...
NEWTON
..A..O
..YARD
Input
AAA
AAA
AAAAA
AAA
AAA
AAAAA
Output
AAA..
A.A..
AAAAA
..A.A
..AAA
Input
PTC
JYNYFDSGI
ZGPPC
IXEJNDOP
JJFS
SSXXQOFGJUZ
Output
JJFS....
Y..S....
N..X....
Y..X....
F..Q....
D..O....
S..F....
G..G....
IXEJNDOP
...U...T
...ZGPPC
Submitted Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
from itertools import permutations
def main():
s = [input().strip() for _ in range(6)]
ma = max(map(len,s))
ans = [['a']*30 for _ in range(30)]
dx = [0,1,0,-1,0,-1]
dy = [1,0,1,0,-1,0]
for i in enumerate(permutations(s)):
i = list(i[1])
i[3],i[4],i[5] = i[3][::-1],i[4][::-1],i[5][::-1]
fl = 0
for j in range(1,7):
if i[j%6][0] != i[j-1][-1]:
fl = 1
break
if fl:
continue
ans1 = [['a']*30 for _ in range(30)]
x,y,fl = 0,0,0
for ind,j in enumerate(i):
for ch in j:
if x < 0 or y < 0 or x >= ma or y >= ma:
fl = 1
break
ans1[x][y] = ch
x += dx[ind]
y += dy[ind]
if fl:
break
x -= dx[ind]
y -= dy[ind]
if fl:
continue
ans = min(ans,ans1)
if ans == [['a']*30 for _ in range(30)]:
print('Impossible')
exit()
fin = []
for i in range(30):
fin.append(''.join(ans[i][:ma]))
fin[-1] = fin[-1].replace('a','.')
if fin[-1] == '.'*ma:
fin.pop()
break
print(*fin,sep='\n')
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | instruction | 0 | 108,224 | 23 | 216,448 |
No | output | 1 | 108,224 | 23 | 216,449 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya trains to compose crossword puzzles. He can only compose crosswords of a very simplе type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular "eight" or infinity sign, not necessarily symmetrical.
The top-left corner of the crossword coincides with the top-left corner of the rectangle. The same thing is correct for the right-bottom corners. The crossword can't degrade, i.e. it always has exactly four blank areas, two of which are surrounded by letters. Look into the output for the samples for clarification.
Help Vasya — compose a crossword of the described type using the given six words. It is allowed to use the words in any order.
Input
Six lines contain the given words. Every word consists of no more than 30 and no less than 3 uppercase Latin letters.
Output
If it is impossible to solve the problem, print Impossible. Otherwise, print the sought crossword. All the empty squares should be marked as dots.
If there can be several solutions to that problem, print the lexicographically minimum one. I.e. the solution where the first line is less than the first line of other solutions should be printed. If the two lines are equal, compare the second lines and so on. The lexicographical comparison of lines is realized by the < operator in the modern programming languages.
Examples
Input
NOD
BAA
YARD
AIRWAY
NEWTON
BURN
Output
BAA...
U.I...
R.R...
NEWTON
..A..O
..YARD
Input
AAA
AAA
AAAAA
AAA
AAA
AAAAA
Output
AAA..
A.A..
AAAAA
..A.A
..AAA
Input
PTC
JYNYFDSGI
ZGPPC
IXEJNDOP
JJFS
SSXXQOFGJUZ
Output
JJFS....
Y..S....
N..X....
Y..X....
F..Q....
D..O....
S..F....
G..G....
IXEJNDOP
...U...T
...ZGPPC
Submitted Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
from itertools import permutations
def main():
s = [input().strip() for _ in range(6)]
ans = [['a']*30 for _ in range(30)]
dx = [0,1,0,-1,0,-1]
dy = [1,0,1,0,-1,0]
for i in enumerate(permutations(s)):
i = list(i[1])
i[3],i[4],i[5] = i[3][::-1],i[4][::-1],i[5][::-1]
fl = 0
for j in range(1,7):
if i[j%6][0] != i[j-1][-1]:
fl = 1
break
if fl:
continue
ans1 = [['a']*30 for _ in range(30)]
x,y,fl,s,s1 = 0,0,0,-1,-1
for ind,j in enumerate(i):
for ch in j:
if x < 0 or y < 0 or x >= 30 or y >= 30:
fl = 1
break
ans1[x][y] = ch
x += dx[ind]
y += dy[ind]
if fl:
break
x -= dx[ind]
y -= dy[ind]
if s == -1 and s1 == -1:
s,s1 = x,y
if s != -1:
for xx in i[1]:
if ans1[s][s1] != xx:
fl = 1
break
s += 1
if fl or x or y:
continue
ans = min(ans,ans1)
if ans == [['a']*30 for _ in range(30)]:
print('Impossible')
exit()
ma = 0
for i in range(30):
ma = max(ma,30-ans[i].count('a'))
fin = []
for i in range(30):
fin.append(''.join(ans[i][:ma]))
fin[-1] = fin[-1].replace('a','.')
if fin[-1] == '.'*ma:
fin.pop()
break
print(*fin,sep='\n')
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | instruction | 0 | 108,225 | 23 | 216,450 |
No | output | 1 | 108,225 | 23 | 216,451 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image> | instruction | 0 | 108,226 | 23 | 216,452 |
Tags: binary search, data structures, implementation
Correct Solution:
```
def main():
from sys import stdin
w, h, n = map(int, stdin.readline().split())
res, vrt, hor = [], [], []
vh = (vrt, hor)
for i, s in enumerate(stdin.read().splitlines()):
x = int(s[2:])
flag = s[0] == 'V'
vh[flag].append(i)
res.append([x, flag])
dim = []
for tmp, m in zip(vh, (h, w)):
tmp.sort(key=lambda e: res[e][0])
u = [None, [0]]
dim.append(u)
j = z = 0
for i in tmp:
x = res[i][0]
if z < x - j:
z = x - j
j = x
v = [u, res[i]]
u.append(v)
u = v
res[i].append(u)
v = [u, [m], None]
u.append(v)
dim.append(v)
if z < m - j:
z = m - j
dim.append(z)
l, r, wmax, u, d, hmax = dim
whmax = [wmax, hmax]
for i in range(n - 1, -1, -1):
x, flag, link = res[i]
u = whmax[flag]
res[i] = u * whmax[not flag]
link[0][2] = link[2]
link[2][0] = link[0]
v = link[2][1][0] - link[0][1][0]
if u < v:
whmax[flag] = v
print('\n'.join(map(str, res)))
if __name__ == '__main__':
main()
# Made By Mostafa_Khaled
``` | output | 1 | 108,226 | 23 | 216,453 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image> | instruction | 0 | 108,227 | 23 | 216,454 |
Tags: binary search, data structures, implementation
Correct Solution:
```
def main():
from sys import stdin
w, h, n = map(int, stdin.readline().split())
res, vrt, hor = [], [], []
vh = (vrt, hor)
for i, s in enumerate(stdin.read().splitlines()):
x = int(s[2:])
flag = s[0] == 'V'
vh[flag].append(i)
res.append([x, flag])
dim = []
for tmp, m in zip(vh, (h, w)):
tmp.sort(key=lambda e: res[e][0])
u = [None, [0]]
dim.append(u)
j = z = 0
for i in tmp:
x = res[i][0]
if z < x - j:
z = x - j
j = x
v = [u, res[i]]
u.append(v)
u = v
res[i].append(u)
v = [u, [m], None]
u.append(v)
dim.append(v)
if z < m - j:
z = m - j
dim.append(z)
l, r, wmax, u, d, hmax = dim
whmax = [wmax, hmax]
for i in range(n - 1, -1, -1):
x, flag, link = res[i]
u = whmax[flag]
res[i] = u * whmax[not flag]
link[0][2] = link[2]
link[2][0] = link[0]
v = link[2][1][0] - link[0][1][0]
if u < v:
whmax[flag] = v
print('\n'.join(map(str, res)))
if __name__ == '__main__':
main()
``` | output | 1 | 108,227 | 23 | 216,455 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image> | instruction | 0 | 108,228 | 23 | 216,456 |
Tags: binary search, data structures, implementation
Correct Solution:
```
w,h,n=map(int,input().split())
l=[-1]*(w+1)
r=[-1]*(w+1)
t=[-1]*(h+1)
b=[-1]*(h+1)
l[0]=0
b[0]=0
t[h]=h
r[w]=w
V=[0]*(n)
H=[0]*(n)
for i in range(n):
line,index=input().split()
index=int(index)
if line=="V":
r[index]=w
V[i]=index
else:
t[index]=h
H[i]=index
left=0
mxw=0
for i in range(1,w+1):
if r[i]!=-1:
l[i]=left
r[left]=i
mxw=max(mxw,i-left)
left=i
bottom=0
mxh=0
for i in range(1,h+1):
if t[i]!=-1:
b[i]=bottom
t[bottom]=i
mxh=max(mxh,i-bottom)
bottom=i
ans=[0]*(n)
ans[n-1]=mxh*mxw
for i in range(n-1,0,-1):
if V[i]!=0:
mxw=max(mxw,r[V[i]]-l[V[i]])
r[l[V[i]]]=r[V[i]]
l[r[V[i]]]=l[V[i]]
else:
mxh=max(mxh,t[H[i]]-b[H[i]])
b[t[H[i]]]=b[H[i]]
t[b[H[i]]]=t[H[i]]
ans[i-1]=mxh*mxw
for i in range(n):
print(ans[i])
``` | output | 1 | 108,228 | 23 | 216,457 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image> | instruction | 0 | 108,229 | 23 | 216,458 |
Tags: binary search, data structures, implementation
Correct Solution:
```
w, h, n = map(int, input().split())
l, r = [-1] * (w+1), [-1] * (w+1)
t, b = [-1] * (h+1), [-1] * (h+1)
l[0], b[0], t[h], r[w] = 0, 0, h, w
V, H = [0] * n, [0] * n
for i in range(n):
line, idx = input().split()
idx = int(idx)
if line == 'V':
r[idx] = w
V[i] = idx
else:
t[idx] = h
H[i] = idx
left, max_w = 0, 0
for i in range(1, w+1):
if r[i] != -1:
l[i] = left
r[left] = i
max_w = max(max_w, i - left)
left = i
bottom, max_h = 0, 0
for i in range(1 ,h+1):
if t[i] != -1:
b[i] = bottom
t[bottom] = i
max_h = max(max_h, i - bottom)
bottom = i
res = [0] * n
res[n-1] = max_h * max_w
for i in range(n-1, 0, -1):
if V[i] != 0:
max_w = max(max_w, r[V[i]] - l[V[i]])
r[l[V[i]]] = r[V[i]]
l[r[V[i]]] = l[V[i]]
else:
max_h = max(max_h, t[H[i]] - b[H[i]])
b[t[H[i]]] = b[H[i]]
t[b[H[i]]] = t[H[i]]
res[i-1] = max_h * max_w
for i in range(n):
print(res[i])
``` | output | 1 | 108,229 | 23 | 216,459 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image> | instruction | 0 | 108,230 | 23 | 216,460 |
Tags: binary search, data structures, implementation
Correct Solution:
```
# -*- coding:utf-8 -*-
"""
created by shuangquan.huang at 1/7/20
reverse thinking of merging instead of split
"""
import collections
import time
import os
import sys
import bisect
import heapq
from typing import List
class Node:
val = None
def __init__(self, val):
self.val = val
self.left = Node
self.right = None
def solve(W, H, N, A):
xs = [0] + [v for t, v in A if t == 0] + [W]
ys = [0] + [v for t, v in A if t == 1] + [H]
xs.sort()
ys.sort()
xlist = Node(0)
h = xlist
xnodes = {0: h}
maxw = max([xs[i+1] - xs[i] for i in range(len(xs)-1)] or [0])
maxh = max([ys[i+1] - ys[i] for i in range(len(ys)-1)] or [0])
for v in xs[1:]:
n = Node(v)
xnodes[v] = n
h.right = n
n.left = h
h = n
ylist = Node(0)
h = ylist
ynodes = {0: h}
for v in ys[1:]:
n = Node(v)
ynodes[v] = n
h.right = n
n.left = h
h = n
ans = []
maxarea = maxh * maxw
for t, v in reversed(A):
ans.append(maxarea)
if t == 0:
node = xnodes[v]
w = node.right.val - node.left.val
maxw = max(maxw, w)
else:
node = ynodes[v]
h = node.right.val - node.left.val
maxh = max(maxh, h)
node.left.right = node.right
node.right.left = node.left
maxarea = maxh * maxw
return ans[::-1]
def solve2(W, H, N, A):
ws = [(-W, 0, W)]
hs = [(-H, 0, H)]
iw, ih = set(), set()
ans = []
xs, ys = [0, W], [0, H]
for t, v in A:
if t == 0:
bisect.insort_left(xs, v)
i = bisect.bisect_left(xs, v)
l, m, r = xs[i-1], xs[i], xs[i+1]
iw.add((l-r, l, r))
heapq.heappush(ws, (l - m, l, m))
heapq.heappush(ws, (m - r, m, r))
while ws[0] in iw:
heapq.heappop(ws)
else:
bisect.insort(ys, v)
i = bisect.bisect_left(ys, v)
l, m, r = ys[i-1], ys[i], ys[i+1]
ih.add((l-r, l, r))
heapq.heappush(hs, (l - m, l, m))
heapq.heappush(hs, (m - r, m, r))
while hs[0] in ih:
heapq.heappop(hs)
w, h = ws[0], hs[0]
ans.append(w[0] * h[0])
return ans
W, H, N = map(int,input().split())
A = []
for i in range(N):
a, b = input().split()
c = 0 if a == 'V' else 1
A.append((c, int(b)))
print('\n'.join(map(str, solve(W, H, N, A))))
``` | output | 1 | 108,230 | 23 | 216,461 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image> | instruction | 0 | 108,231 | 23 | 216,462 |
Tags: binary search, data structures, implementation
Correct Solution:
```
from sys import stdin, stdout
w, h, n = map(int, stdin.readline().split())
a = [stdin.readline().split() for _ in range(n)]
y = [0, h]
x = [0, w]
for m in a:
m[1] = int(m[1])
if m[0] == 'H':
y.append(m[1])
else:
x.append(m[1])
y.sort()
x.sort()
iy = {t: i for i, t in enumerate(y)}
ix = {t: i for i, t in enumerate(x)}
ny = len(y)
nx = len(x)
pary = list(range(len(y)))
parx = list(range(len(x)))
p = 0
dy = [0] * ny
for i in range(ny - 1):
dy[i] = y[i+1] - y[i]
my = max(dy)
dx = [0] * nx
for i in range(nx - 1):
dx[i] = x[i+1] - x[i]
mx = max(dx)
ans = [my * mx]
for t in reversed(a):
if t[0] == 'H':
i = iy[t[1]]
st = [i]
while pary[i] != i:
i = pary[i]
st.append(i)
nl = dy[i]
i = iy[t[1]] - 1
st.append(i)
while pary[i] != i:
i = pary[i]
st.append(i)
dy[i] += nl
if my < dy[i]:
my = dy[i]
i = st.pop()
for j in st:
pary[j] = i
else:
i = ix[t[1]]
st = [i]
while parx[i] != i:
i = parx[i]
st.append(i)
nl = dx[i]
i = ix[t[1]] - 1
st.append(i)
while parx[i] != i:
i = parx[i]
st.append(i)
dx[i] += nl
if mx < dx[i]:
mx = dx[i]
i = st.pop()
for j in st:
parx[j] = i
ans.append(mx * my)
ans.pop()
stdout.write('\n'.join(map(str, reversed(ans))))
``` | output | 1 | 108,231 | 23 | 216,463 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image> | instruction | 0 | 108,232 | 23 | 216,464 |
Tags: binary search, data structures, implementation
Correct Solution:
```
# import itertools
# import bisect
# import math
from collections import defaultdict, Counter
import os
import sys
from io import BytesIO, IOBase
# sys.setrecursionlimit(10 ** 5)
ii = lambda: int(input())
lmii = lambda: list(map(int, input().split()))
slmii = lambda: sorted(map(int, input().split()))
li = lambda: list(input())
mii = lambda: map(int, input().split())
msi = lambda: map(str, input().split())
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
def gcd(a, b):
if b == 0: return a
return gcd(b, a % b)
def lcm(a, b): return (a * b) // gcd(a, b)
def main():
# for _ in " " * int(input()):
w, h, n = mii()
ws, dws, hs, dhs, hsm, wsm = SortedList([]), defaultdict(int), SortedList([]), defaultdict(int), SortedList(
[]), SortedList([])
hsm.add(h);
wsm.add(w);
hs.add(0);
ws.add(0);
hs.add(h);
ws.add(w);
dhs[h] = 1;
dhs[0] = 1;
dws[0] = 1;
dws[w] = 1
for i in range(n):
t, p = map(str, input().split())
p = int(p)
if t == "H":
if dhs[p] == 0:
hs.add(p)
dhs[p] = 1
ind = hs.bisect_left(p)
pre, nex = hs[ind - 1], hs[ind + 1]
hsm.__delitem__(hsm.bisect_left(nex - pre));
hsm.add(p - pre);
hsm.add(nex - p)
else:
if dws[p] == 0:
ws.add(p)
dws[p] = 1
ind = ws.bisect_left(p)
pre, nex = ws[ind - 1], ws[ind + 1]
wsm.__delitem__(wsm.bisect_left(nex - pre));
wsm.add(p - pre);
wsm.add(nex - p)
print(wsm[-1] * hsm[-1])
pass
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | output | 1 | 108,232 | 23 | 216,465 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image> | instruction | 0 | 108,233 | 23 | 216,466 |
Tags: binary search, data structures, implementation
Correct Solution:
```
def main():
w, h, n = map(int, input().split())
res, vrt, hor = [], [], []
vh = (vrt, hor)
for i in range(n):
s = input()
x = int(s[2:])
flag = s[0] == 'V'
vh[flag].append(i)
res.append([x, flag])
dim = []
for tmp, m in zip(vh, (h, w)):
tmp.sort(key=lambda e: res[e][0])
u = [None, [0]]
dim.append(u)
j = z = 0
for i in tmp:
x = res[i][0]
if z < x - j:
z = x - j
j = x
v = [u, res[i]]
u.append(v)
u = v
res[i].append(u)
v = [u, [m], None]
u.append(v)
dim.append(v)
if z < m - j:
z = m - j
dim.append(z)
l, r, wmax, u, d, hmax = dim
whmax = [wmax, hmax]
for i in range(n - 1, -1, -1):
x, flag, link = res[i]
u = whmax[flag]
res[i] = u * whmax[not flag]
link[0][2] = link[2]
link[2][0] = link[0]
v = link[2][1][0] - link[0][1][0]
if u < v:
whmax[flag] = v
print('\n'.join(map(str, res)))
if __name__ == '__main__':
main()
``` | output | 1 | 108,233 | 23 | 216,467 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image>
Submitted Solution:
```
w, h, n = map(int, input().split())
x = [0, w]
y = [0, h]
rev = []
for _ in range(n):
s, d = input().split()
if s == 'H':
y.append(int(d))
else:
x.append(int(d))
rev.append((s, int(d)))
x.sort()
y.sort()
_max = 0
if len(x) > 1:
for idx in range(len(x) - 1):
_max = max(_max, x[idx + 1] - x[idx])
else:
_max = w
max_x = _max
_max = 0
if len(y) > 1:
for idx in range(len(y) - 1):
_max = max(_max, y[idx + 1] - y[idx])
else:
_max = w
max_y = _max
enum_x = {num : idx for idx, num in enumerate(x)}
enum_y = {num : idx for idx, num in enumerate(y)}
old_x = x
old_y = y
x = [[0, 0, 0]] * len(old_x)
y = [[0, 0, 0]] * len(old_y)
for idx in range(1, len(x) - 1):
x[idx] = [old_x[idx], idx-1, idx+1]
for idx in range(1, len(y) - 1):
y[idx] = [old_y[idx], idx-1, idx+1]
x[-1] = [w, 0, 0]
y[-1] = [h, 0, 0]
rev.reverse()
ans = [max_x * max_y]
for item in rev:
if item[0] == 'H':
elem = y[enum_y[item[1]]]
max_y = max(max_y, y[elem[2]][0] - y[elem[1]][0])
y[elem[1]][2] = elem[2]
y[elem[2]][1] = elem[1]
else:
elem = x[enum_x[item[1]]]
max_x = max(max_x, x[elem[2]][0] - x[elem[1]][0])
x[elem[1]][2] = elem[2]
x[elem[2]][1] = elem[1]
ans.append(max_x * max_y)
ans.pop()
print('\n'.join(map(str, reversed(ans))))
``` | instruction | 0 | 108,234 | 23 | 216,468 |
Yes | output | 1 | 108,234 | 23 | 216,469 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image>
Submitted Solution:
```
def main():
from sys import stdin
w, h, n = map(int, stdin.readline().split())
res, vrt, hor = [], [], []
vh = (vrt, hor)
for i, s in enumerate(stdin.read().splitlines()):
x = int(s[2:])
flag = s[0] == 'V'
vh[flag].append(i)
res.append([x, flag])
dim = []
for tmp, m in zip(vh, (h, w)):
tmp.sort(key=lambda e: res[e][0])
u = [None, [0]]
dim.append(u)
j = z = 0
for i in tmp:
x = res[i][0]
if z < x - j:
z = x - j
j = x
v = [u, res[i]]
u.append(v)
u = v
res[i].append(u)
v = [u, [m], None]
u.append(v)
dim.append(v)
if z < m - j:
z = m - j
dim.append(z)
l, r, wmax, u, d, hmax = dim
s = str(wmax * hmax)
for i in range(n - 1, -1, -1):
x, flag, link = res[i]
u = hmax if flag else wmax
res[i] = s
link[0][2] = link[2]
link[2][0] = link[0]
v = link[2][1][0] - link[0][1][0]
if u < v:
if flag:
hmax = v
else:
wmax = v
s = str(wmax * hmax)
print('\n'.join(res))
if __name__ == '__main__':
main()
``` | instruction | 0 | 108,235 | 23 | 216,470 |
Yes | output | 1 | 108,235 | 23 | 216,471 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image>
Submitted Solution:
```
w, h, n = (int(x) for x in input().split())
squares = [((0, 0), (w, h), w*h)]
for i in range(n):
s = input().split()
key, val = s[0], int(s[1])
max = 0
if key == "H":
k = 0
while k < len(squares):
block = squares[k]
if block[0][1] < h-val < block[1][1]:
squares.remove(block)
s = (block[1][0]-block[0][0])*(h-val-block[0][1])
if s > max:
max = s
if block[2] - s > max:
max = block[2] - s
squares.append((block[0], (block[1][0], h-val), s))
squares.append(((block[0][0], h-val), block[1], block[2] - s))
else:
k += 1
if key == "V":
k = 0
while k < len(squares):
block = squares[k]
if block[0][0] < w-val < block[1][0]:
squares.remove(block)
s = (w-val-block[0][0])*(block[1][1]-block[0][1])
if s > max:
max = s
if block[2] - s > max:
max = block[2] - s
squares.append((block[0], (w-val, block[1][1]), s))
squares.append(((w-val, block[0][1]), block[1], block[2] - s))
else:
k += 1
print(max)
``` | instruction | 0 | 108,236 | 23 | 216,472 |
No | output | 1 | 108,236 | 23 | 216,473 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image>
Submitted Solution:
```
w, h, n = (int(x) for x in input().split())
squares = [((0, 0), (w, h), w*h)]
for i in range(n):
s = input().split()
key, val = s[0], int(s[1])
max = 0
if key == "H":
k = 0
while k < len(squares):
block = squares[k]
if block[2] > max:
max = block[2]
if block[0][1] < h-val < block[1][1]:
squares.remove(block)
s = (block[1][0]-block[0][0])*(h-val-block[0][1])
if s > max:
max = s
if block[2] - s > max:
max = block[2] - s
squares.append((block[0], (block[1][0], h-val), s))
squares.append(((block[0][0], h-val), block[1], block[2] - s))
else:
k += 1
if key == "V":
k = 0
while k < len(squares):
block = squares[k]
if block[2] > max:
max = block[2]
if block[0][0] < w-val < block[1][0]:
squares.remove(block)
s = (w-val-block[0][0])*(block[1][1]-block[0][1])
if s > max:
max = s
if block[2] - s > max:
max = block[2] - s
squares.append((block[0], (w-val, block[1][1]), s))
squares.append(((w-val, block[0][1]), block[1], block[2] - s))
else:
k += 1
print(max)
``` | instruction | 0 | 108,237 | 23 | 216,474 |
No | output | 1 | 108,237 | 23 | 216,475 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image>
Submitted Solution:
```
w,h,n=map(int,input().split())
l=[-1]*(w+1)
r=[-1]*(w+1)
t=[-1]*(h+1)
b=[-1]*(h+1)
l[0]=0
b[0]=0
V=[0]*(n)
H=[0]*(n)
for i in range(n):
line,index=input().split()
index=int(index)
if line=="V":
r[index]=w
V[i]=index
else:
t[index]=h
H[i]=index
left=0
mxw=0
for i in range(1,w+1):
if r[i]!=-1:
l[i]=left
r[left]=i
mxw=max(mxw,i-left)
left=i
bottom=0
mxh=0
for i in range(1,h+1):
if t[i]!=-1:
b[i]=bottom
t[bottom]=i
mxh=max(mxh,i-bottom)
bottom=i
ans=[0]*(n)
ans[n-1]=mxh*mxw
for i in range(n-1,0,-1):
if H[i]==0:
mxw=max(mxw,r[V[i]]-l[V[i]])
r[l[V[i]]]=r[V[i]]
l[r[V[i]]]=l[V[i]]
else:
mxh=max(mxh,t[H[i]]-b[H[i]])
b[t[H[i]]]=b[H[i]]
t[b[H[i]]]=t[H[i]]
ans[i-1]=mxh*mxw
for i in range(n):
print(ans[i])
``` | instruction | 0 | 108,238 | 23 | 216,476 |
No | output | 1 | 108,238 | 23 | 216,477 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image>
Submitted Solution:
```
from heapq import *
w, h, n = map(int, input().split())
wSegments = dict()
hSegments = dict()
wSegments[0] = w - 1
hSegments[0] = h - 1
maxW = w
maxH = h
for i in range(n):
info = input().split()
value = int(info[1])
value -= 1
if info[0] == "V":
maxW = 0
tW = None
for segment in wSegments:
if segment <= value and wSegments[segment] >= value:
tW = segment
else:
maxW = max(maxW, wSegments[segment] - segment + 1)
maxW = max([value - tW + 1, wSegments[tW] - value, maxW])
wSegments[value + 1] = wSegments[tW]
wSegments[tW] = value
else:
maxH = 0
tH = None
for segment in hSegments:
if segment <= value and hSegments[segment] >= value:
tH = segment
else:
maxH = max(maxH, hSegments[segment] - segment + 1)
maxH = max([value - tH + 1, hSegments[tH] - value + 1, maxH])
hSegments[value + 1] = hSegments[tH]
hSegments[tH] = value
#for key in hSegments:
# print(key, end= ' ')
# print(hSegments[key])
#print()
#print(maxH)
#print(maxW)
print(maxH * maxW)
``` | instruction | 0 | 108,239 | 23 | 216,478 |
No | output | 1 | 108,239 | 23 | 216,479 |
Provide a correct Python 3 solution for this coding contest problem.
Sunuke received a d-dimensional hypercube with a side length of l1 × ... × ld as a birthday present. Sunuke placed this rectangular parallelepiped so that the range of the i-th coordinate was 0 or more and li or less, and ate the part that satisfied x1 + ... + xd ≤ s. However, xi represents the i-th coordinate. If the volume of the part eaten by Sunuke is V, it can be proved that d! V (V multiplied by the factorial of d) is an integer. Find the remainder of d! V divided by 1,000,000,007.
Constraints
* 2 ≤ d ≤ 300
* 1 ≤ li ≤ 300
* 0 ≤ s ≤ $ \ sum l_ {i} $
* All inputs are integers
Input
d
l1
.. ..
ld
s
Output
Output d! V divided by 1,000,000,007.
Examples
Input
2
6
3
4
Output
15
Input
5
12
34
56
78
90
123
Output
433127538 | instruction | 0 | 108,598 | 23 | 217,196 |
"Correct Solution:
```
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
MOD = 10**9 + 7
D = int(readline())
L = [int(readline()) for i in range(D)]
S = int(readline())
dp = [0]*(S+1)
dp[S] = 1
for i in range(D):
l = L[i]
for i in range(l, S+1):
dp[i-l] -= dp[i]
ans = 0
for i in range(S+1):
ans += pow(i, D, MOD) * dp[i]
ans %= MOD
write("%d\n" % ans)
solve()
``` | output | 1 | 108,598 | 23 | 217,197 |
Provide a correct Python 3 solution for this coding contest problem.
Find the tangent lines between a point $p$ and a circle $c$.
Constraints
* $-1,000 \leq px, py, cx, cy \leq 1,000$
* $1 \leq r \leq 1,000$
* Distance between $p$ and the center of $c$ is greater than the radius of $c$.
Input
The input is given in the following format.
$px \; py$
$cx \; cy \; r$
$px$ and $py$ represents the coordinate of the point $p$. $cx$, $cy$ and $r$ represents the center coordinate and radius of the circle $c$ respectively. All input values are given in integers.
Output
Print coordinates of the tangent points on the circle $c$ based on the following rules.
* Print the coordinate with smaller $x$ first. In case of a tie, print the coordinate with smaller $y$ first.
The output values should be in a decimal fraction with an error less than 0.00001.
Examples
Input
0 0
2 2 2
Output
0.0000000000 2.0000000000
2.0000000000 0.0000000000
Input
-3 0
2 2 2
Output
0.6206896552 3.4482758621
2.0000000000 0.0000000000 | instruction | 0 | 108,600 | 23 | 217,200 |
"Correct Solution:
```
from math import asin, atan2, cos, sin, sqrt
from typing import List, Tuple
def tangent_point(circle: Tuple[float, float, float],
point: Tuple[float, float]) -> List[Tuple[float, float]]:
cx, cy, cr = circle
x, y = point
p = (cx - x) ** 2 + (cy - y) ** 2
q = cr ** 2
r = sqrt(p - q)
t0 = atan2(cy - y, cx - x)
t1 = asin(cr / sqrt(p))
return [(x + r * cos(t0 + t1), y + r * sin(t0 + t1)),
(x + r * cos(t0 - t1), y + r * sin(t0 - t1))]
if __name__ == '__main__':
x, y = map(lambda x: float(x), input().split())
cx, cy, cr = map(lambda x: float(x), input().split())
ps = tangent_point((cx, cy, cr), (x, y))
p1, p2 = ps
if p1 > p2:
p1, p2 = p2, p1
print("{:.6f} {:.6f}".format(*p1))
print("{:.6f} {:.6f}".format(*p2))
``` | output | 1 | 108,600 | 23 | 217,201 |
Provide a correct Python 3 solution for this coding contest problem.
Find the tangent lines between a point $p$ and a circle $c$.
Constraints
* $-1,000 \leq px, py, cx, cy \leq 1,000$
* $1 \leq r \leq 1,000$
* Distance between $p$ and the center of $c$ is greater than the radius of $c$.
Input
The input is given in the following format.
$px \; py$
$cx \; cy \; r$
$px$ and $py$ represents the coordinate of the point $p$. $cx$, $cy$ and $r$ represents the center coordinate and radius of the circle $c$ respectively. All input values are given in integers.
Output
Print coordinates of the tangent points on the circle $c$ based on the following rules.
* Print the coordinate with smaller $x$ first. In case of a tie, print the coordinate with smaller $y$ first.
The output values should be in a decimal fraction with an error less than 0.00001.
Examples
Input
0 0
2 2 2
Output
0.0000000000 2.0000000000
2.0000000000 0.0000000000
Input
-3 0
2 2 2
Output
0.6206896552 3.4482758621
2.0000000000 0.0000000000 | instruction | 0 | 108,601 | 23 | 217,202 |
"Correct Solution:
```
import cmath
import itertools
import math
import os
import sys
from collections import defaultdict
if os.getenv("LOCAL"):
sys.stdin = open("_in.txt", "r")
sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353
PI = cmath.pi
TAU = cmath.pi * 2
EPS = 1e-10
class Point:
"""
2次元空間上の点
"""
# 反時計回り側にある
CCW_COUNTER_CLOCKWISE = 1
# 時計回り側にある
CCW_CLOCKWISE = -1
# 線分の後ろにある
CCW_ONLINE_BACK = 2
# 線分の前にある
CCW_ONLINE_FRONT = -2
# 線分上にある
CCW_ON_SEGMENT = 0
def __init__(self, c: complex):
self.c = c
@property
def x(self):
return self.c.real
@property
def y(self):
return self.c.imag
@staticmethod
def from_rect(x: float, y: float):
return Point(complex(x, y))
@staticmethod
def from_polar(r: float, phi: float):
return Point(cmath.rect(r, phi))
def __add__(self, p):
"""
:param Point p:
"""
return Point(self.c + p.c)
def __iadd__(self, p):
"""
:param Point p:
"""
self.c += p.c
return self
def __sub__(self, p):
"""
:param Point p:
"""
return Point(self.c - p.c)
def __isub__(self, p):
"""
:param Point p:
"""
self.c -= p.c
return self
def __mul__(self, f: float):
return Point(self.c * f)
def __imul__(self, f: float):
self.c *= f
return self
def __truediv__(self, f: float):
return Point(self.c / f)
def __itruediv__(self, f: float):
self.c /= f
return self
def __repr__(self):
return "({}, {})".format(round(self.x, 10), round(self.y, 10))
def __neg__(self):
return Point(-self.c)
def __eq__(self, p):
return abs(self.c - p.c) < EPS
def __abs__(self):
return abs(self.c)
@staticmethod
def ccw(a, b, c):
"""
線分 ab に対する c の位置
線分上にあるか判定するだけなら on_segment とかのが速い
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_C&lang=ja
:param Point a:
:param Point b:
:param Point c:
"""
b = b - a
c = c - a
det = b.det(c)
if det > EPS:
return Point.CCW_COUNTER_CLOCKWISE
if det < -EPS:
return Point.CCW_CLOCKWISE
if b.dot(c) < -EPS:
return Point.CCW_ONLINE_BACK
if c.norm() - b.norm() > EPS:
return Point.CCW_ONLINE_FRONT
return Point.CCW_ON_SEGMENT
def dot(self, p):
"""
内積
:param Point p:
:rtype: float
"""
return self.x * p.x + self.y * p.y
def det(self, p):
"""
外積
:param Point p:
:rtype: float
"""
return self.x * p.y - self.y * p.x
def dist(self, p):
"""
距離
:param Point p:
:rtype: float
"""
return abs(self.c - p.c)
def norm(self):
"""
原点からの距離
:rtype: float
"""
return abs(self.c)
def phase(self):
"""
原点からの角度
:rtype: float
"""
return cmath.phase(self.c)
def angle(self, p, q):
"""
p に向いてる状態から q まで反時計回りに回転するときの角度
-pi <= ret <= pi
:param Point p:
:param Point q:
:rtype: float
"""
return (cmath.phase(q.c - self.c) - cmath.phase(p.c - self.c) + PI) % TAU - PI
def area(self, p, q):
"""
p, q となす三角形の面積
:param Point p:
:param Point q:
:rtype: float
"""
return abs((p - self).det(q - self) / 2)
def projection_point(self, p, q, allow_outer=False):
"""
線分 pq を通る直線上に垂線をおろしたときの足の座標
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_A&lang=ja
:param Point p:
:param Point q:
:param allow_outer: 答えが線分の間になくても OK
:rtype: Point|None
"""
diff_q = q - p
# 答えの p からの距離
r = (self - p).dot(diff_q) / abs(diff_q)
# 線分の角度
phase = diff_q.phase()
ret = Point.from_polar(r, phase) + p
if allow_outer or (p - ret).dot(q - ret) < EPS:
return ret
return None
def reflection_point(self, p, q):
"""
直線 pq を挟んで反対にある点
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_B&lang=ja
:param Point p:
:param Point q:
:rtype: Point
"""
# 距離
r = abs(self - p)
# pq と p-self の角度
angle = p.angle(q, self)
# 直線を挟んで角度を反対にする
angle = (q - p).phase() - angle
return Point.from_polar(r, angle) + p
def on_segment(self, p, q, allow_side=True):
"""
点が線分 pq の上に乗っているか
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_1_C&lang=ja
:param Point p:
:param Point q:
:param allow_side: 端っこでギリギリ触れているのを許容するか
:rtype: bool
"""
if not allow_side and (self == p or self == q):
return False
# 外積がゼロ: 面積がゼロ == 一直線
# 内積がマイナス: p - self - q の順に並んでる
return abs((p - self).det(q - self)) < EPS and (p - self).dot(q - self) < EPS
class Line:
"""
2次元空間上の直線
"""
def __init__(self, a: float, b: float, c: float):
"""
直線 ax + by + c = 0
"""
self.a = a
self.b = b
self.c = c
@staticmethod
def from_gradient(grad: float, intercept: float):
"""
直線 y = ax + b
:param grad: 傾き
:param intercept: 切片
:return:
"""
return Line(grad, -1, intercept)
@staticmethod
def from_segment(p1, p2):
"""
:param Point p1:
:param Point p2:
"""
a = p2.y - p1.y
b = p1.x - p2.x
c = p2.y * (p2.x - p1.x) - p2.x * (p2.y - p1.y)
return Line(a, b, c)
@property
def gradient(self):
"""
傾き
"""
return INF if self.b == 0 else -self.a / self.b
@property
def intercept(self):
"""
切片
"""
return INF if self.b == 0 else -self.c / self.b
def is_parallel_to(self, l):
"""
平行かどうか
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A&lang=ja
:param Line l:
"""
# 法線ベクトル同士の外積がゼロ
return abs(Point.from_rect(self.a, self.b).det(Point.from_rect(l.a, l.b))) < EPS
def is_orthogonal_to(self, l):
"""
直行しているかどうか
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A&lang=ja
:param Line l:
"""
# 法線ベクトル同士の内積がゼロ
return abs(Point.from_rect(self.a, self.b).dot(Point.from_rect(l.a, l.b))) < EPS
def intersection_point(self, l):
"""
交差する点
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_C&lang=ja
:param Line l:
:rtype: Point|None
"""
a1, b1, c1 = self.a, self.b, self.c
a2, b2, c2 = l.a, l.b, l.c
det = a1 * b2 - a2 * b1
if abs(det) < EPS:
# 並行
return None
x = (b1 * c2 - b2 * c1) / det
y = (a2 * c1 - a1 * c2) / det
return Point.from_rect(x, y)
def dist(self, p):
"""
他の点との最短距離
:param Point p:
"""
raise NotImplementedError()
def has_point(self, p):
"""
p が直線上に乗っているかどうか
:param Point p:
"""
return abs(self.a * p.x + self.b * p.y + self.c) < EPS
class Segment:
"""
2次元空間上の線分
"""
def __init__(self, p1, p2):
"""
:param Point p1:
:param Point p2:
"""
self.p1 = p1
self.p2 = p2
def norm(self):
"""
線分の長さ
"""
return abs(self.p1 - self.p2)
def phase(self):
"""
p1 を原点としたときの p2 の角度
"""
return (self.p2 - self.p1).phase()
def is_parallel_to(self, s):
"""
平行かどうか
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A&lang=ja
:param Segment s:
:return:
"""
# 外積がゼロ
return abs((self.p1 - self.p2).det(s.p1 - s.p2)) < EPS
def is_orthogonal_to(self, s):
"""
直行しているかどうか
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_A&lang=ja
:param Segment s:
:return:
"""
# 内積がゼロ
return abs((self.p1 - self.p2).dot(s.p1 - s.p2)) < EPS
def intersects_with(self, s, allow_side=True):
"""
交差するかどうか
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_B&lang=ja
:param Segment s:
:param allow_side: 端っこでギリギリ触れているのを許容するか
"""
if self.is_parallel_to(s):
# 並行なら線分の端点がもう片方の線分の上にあるかどうか
return (s.p1.on_segment(self.p1, self.p2, allow_side) or
s.p2.on_segment(self.p1, self.p2, allow_side) or
self.p1.on_segment(s.p1, s.p2, allow_side) or
self.p2.on_segment(s.p1, s.p2, allow_side))
else:
# allow_side ならゼロを許容する
det_upper = EPS if allow_side else -EPS
ok = True
# self の両側に s.p1 と s.p2 があるか
ok &= (self.p2 - self.p1).det(s.p1 - self.p1) * (self.p2 - self.p1).det(s.p2 - self.p1) < det_upper
# s の両側に self.p1 と self.p2 があるか
ok &= (s.p2 - s.p1).det(self.p1 - s.p1) * (s.p2 - s.p1).det(self.p2 - s.p1) < det_upper
return ok
def closest_point(self, p):
"""
線分上の、p に最も近い点
:param Point p:
"""
# p からおろした垂線までの距離
d = (p - self.p1).dot(self.p2 - self.p1) / self.norm()
# p1 より前
if d < EPS:
return self.p1
# p2 より後
if -EPS < d - self.norm():
return self.p2
# 線分上
return Point.from_polar(d, (self.p2 - self.p1).phase()) + self.p1
def dist(self, p):
"""
他の点との最短距離
:param Point p:
"""
return abs(p - self.closest_point(p))
def dist_segment(self, s):
"""
他の線分との最短距離
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_D&lang=ja
:param Segment s:
"""
if self.intersects_with(s):
return 0.0
return min(
self.dist(s.p1),
self.dist(s.p2),
s.dist(self.p1),
s.dist(self.p2),
)
def has_point(self, p, allow_side=True):
"""
p が線分上に乗っているかどうか
:param Point p:
:param allow_side: 端っこでギリギリ触れているのを許容するか
"""
return p.on_segment(self.p1, self.p2, allow_side=allow_side)
class Polygon:
"""
2次元空間上の多角形
"""
def __init__(self, points):
"""
:param list of Point points:
"""
self.points = points
def iter2(self):
"""
隣り合う2点を順に返すイテレータ
:rtype: typing.Iterator[(Point, Point)]
"""
return zip(self.points, self.points[1:] + self.points[:1])
def iter3(self):
"""
隣り合う3点を順に返すイテレータ
:rtype: typing.Iterator[(Point, Point, Point)]
"""
return zip(self.points,
self.points[1:] + self.points[:1],
self.points[2:] + self.points[:2])
def area(self):
"""
面積
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_A&lang=ja
"""
# 外積の和 / 2
dets = []
for p, q in self.iter2():
dets.append(p.det(q))
return abs(math.fsum(dets)) / 2
def is_convex(self, allow_straight=False, allow_collapsed=False):
"""
凸多角形かどうか
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_B&lang=ja
:param allow_straight: 3点がまっすぐ並んでるのを許容するかどうか
:param allow_collapsed: 面積がゼロの場合を許容するか
"""
ccw = []
for a, b, c in self.iter3():
ccw.append(Point.ccw(a, b, c))
ccw = set(ccw)
if len(ccw) == 1:
if ccw == {Point.CCW_CLOCKWISE}:
return True
if ccw == {Point.CCW_COUNTER_CLOCKWISE}:
return True
if allow_straight and len(ccw) == 2:
if ccw == {Point.CCW_ONLINE_FRONT, Point.CCW_CLOCKWISE}:
return True
if ccw == {Point.CCW_ONLINE_FRONT, Point.CCW_COUNTER_CLOCKWISE}:
return True
if allow_collapsed and len(ccw) == 3:
return ccw == {Point.CCW_ONLINE_FRONT, Point.CCW_ONLINE_BACK, Point.CCW_ON_SEGMENT}
return False
def has_point_on_edge(self, p):
"""
指定した点が辺上にあるか
:param Point p:
:rtype: bool
"""
for a, b in self.iter2():
if p.on_segment(a, b):
return True
return False
def contains(self, p, allow_on_edge=True):
"""
指定した点を含むか
Winding Number Algorithm
https://www.nttpc.co.jp/technology/number_algorithm.html
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_3_C&lang=ja
:param Point p:
:param bool allow_on_edge: 辺上の点を許容するか
"""
angles = []
for a, b in self.iter2():
if p.on_segment(a, b):
return allow_on_edge
angles.append(p.angle(a, b))
# 一周以上するなら含む
return abs(math.fsum(angles)) > EPS
@staticmethod
def convex_hull(points, allow_straight=False):
"""
凸包。x が最も小さい点のうち y が最も小さい点から反時計回り。
Graham Scan O(N log N)
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_A&lang=ja
:param list of Point points:
:param allow_straight: 3点がまっすぐ並んでるのを許容するかどうか
:rtype: list of Point
"""
points = points[:]
points.sort(key=lambda p: (p.x, p.y))
# allow_straight なら 0 を許容する
det_lower = -EPS if allow_straight else EPS
sz = 0
#: :type: list of (Point|None)
ret = [None] * (len(points) * 2)
for p in points:
while sz > 1 and (ret[sz - 1] - ret[sz - 2]).det(p - ret[sz - 1]) < det_lower:
sz -= 1
ret[sz] = p
sz += 1
floor = sz
for p in reversed(points[:-1]):
while sz > floor and (ret[sz - 1] - ret[sz - 2]).det(p - ret[sz - 1]) < det_lower:
sz -= 1
ret[sz] = p
sz += 1
ret = ret[:sz - 1]
if allow_straight and len(ret) > len(points):
# allow_straight かつ全部一直線のときに二重にカウントしちゃう
ret = points
return ret
@staticmethod
def diameter(points):
"""
直径
凸包構築 O(N log N) + カリパー法 O(N)
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_B&lang=ja
:param list of Point points:
"""
# 反時計回り
points = Polygon.convex_hull(points, allow_straight=False)
if len(points) == 1:
return 0.0
if len(points) == 2:
return abs(points[0] - points[1])
# x軸方向に最も遠い点対
si = points.index(min(points, key=lambda p: (p.x, p.y)))
sj = points.index(max(points, key=lambda p: (p.x, p.y)))
n = len(points)
ret = 0.0
# 半周回転
i, j = si, sj
while i != sj or j != si:
ret = max(ret, abs(points[i] - points[j]))
ni = (i + 1) % n
nj = (j + 1) % n
# 2つの辺が並行になる方向にずらす
if (points[ni] - points[i]).det(points[nj] - points[j]) > 0:
j = nj
else:
i = ni
return ret
def convex_cut_by_line(self, line_p1, line_p2):
"""
凸多角形を直線 line_p1-line_p2 でカットする。
凸じゃないといけません
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_C&lang=ja
:param line_p1:
:param line_p2:
:return: (line_p1-line_p2 の左側の多角形, line_p1-line_p2 の右側の多角形)
:rtype: (Polygon|None, Polygon|None)
"""
n = len(self.points)
line = Line.from_segment(line_p1, line_p2)
# 直線と重なる点
on_line_points = []
for i, p in enumerate(self.points):
if line.has_point(p):
on_line_points.append(i)
# 辺が直線上にある
has_on_line_edge = False
if len(on_line_points) >= 3:
has_on_line_edge = True
elif len(on_line_points) == 2:
# 直線上にある点が隣り合ってる
has_on_line_edge = abs(on_line_points[0] - on_line_points[1]) in [1, n - 1]
# 辺が直線上にある場合、どっちか片方に全部ある
if has_on_line_edge:
for p in self.points:
ccw = Point.ccw(line_p1, line_p2, p)
if ccw == Point.CCW_COUNTER_CLOCKWISE:
return Polygon(self.points[:]), None
if ccw == Point.CCW_CLOCKWISE:
return None, Polygon(self.points[:])
ret_lefts = []
ret_rights = []
d = line_p2 - line_p1
for p, q in self.iter2():
det_p = d.det(p - line_p1)
det_q = d.det(q - line_p1)
if det_p > -EPS:
ret_lefts.append(p)
if det_p < EPS:
ret_rights.append(p)
# 外積の符号が違う == 直線の反対側にある場合は交点を追加
if det_p * det_q < -EPS:
intersection = line.intersection_point(Line.from_segment(p, q))
ret_lefts.append(intersection)
ret_rights.append(intersection)
# 点のみの場合を除いて返す
l = Polygon(ret_lefts) if len(ret_lefts) > 1 else None
r = Polygon(ret_rights) if len(ret_rights) > 1 else None
return l, r
def closest_pair(points):
"""
最近点対 O(N log N)
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_5_A&lang=ja
:param list of Point points:
:rtype: (float, (Point, Point))
:return: (距離, 点対)
"""
assert len(points) >= 2
def _rec(xsorted):
"""
:param list of Point xsorted:
:rtype: (float, (Point, Point))
"""
n = len(xsorted)
if n <= 2:
return xsorted[0].dist(xsorted[1]), (xsorted[0], xsorted[1])
if n <= 3:
# 全探索
d = INF
pair = None
for p, q in itertools.combinations(xsorted, r=2):
if p.dist(q) < d:
d = p.dist(q)
pair = p, q
return d, pair
# 分割統治
# 両側の最近点対
ld, lp = _rec(xsorted[:n // 2])
rd, rp = _rec(xsorted[n // 2:])
if ld <= rd:
d = ld
ret_pair = lp
else:
d = rd
ret_pair = rp
mid_x = xsorted[n // 2].x
# 中央から d 以内のやつを集める
mid_points = []
for p in xsorted:
# if abs(p.x - mid_x) < d:
if abs(p.x - mid_x) - d < -EPS:
mid_points.append(p)
# この中で距離が d 以内のペアがあれば更新
mid_points.sort(key=lambda p: p.y)
mid_n = len(mid_points)
for i in range(mid_n - 1):
j = i + 1
p = mid_points[i]
q = mid_points[j]
# while q.y - p.y < d
while (q.y - p.y) - d < -EPS:
pq_d = p.dist(q)
if pq_d < d:
d = pq_d
ret_pair = p, q
j += 1
if j >= mid_n:
break
q = mid_points[j]
return d, ret_pair
return _rec(list(sorted(points, key=lambda p: p.x)))
def closest_pair_randomized(points):
"""
最近点対 乱択版 O(N)
http://ir5.hatenablog.com/entry/20131221/1387557630
グリッドの管理が dict だから定数倍気になる
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_5_A&lang=ja
:param list of Point points:
:rtype: (float, (Point, Point))
:return: (距離, 点対)
"""
n = len(points)
assert n >= 2
if n == 2:
return points[0].dist(points[1]), (points[0], points[1])
# 逐次構成法
import random
points = points[:]
random.shuffle(points)
DELTA_XY = list(itertools.product([-1, 0, 1], repeat=2))
grid = defaultdict(list)
delta = INF
dist = points[0].dist(points[1])
ret_pair = points[0], points[1]
for i in range(2, n):
if delta < EPS:
return 0.0, ret_pair
# i 番目より前までを含む grid を構築
# if dist < delta:
if dist - delta < -EPS:
delta = dist
grid = defaultdict(list)
for a in points[:i]:
grid[a.x // delta, a.y // delta].append(a)
else:
p = points[i - 1]
grid[p.x // delta, p.y // delta].append(p)
p = points[i]
dist = delta
grid_x = p.x // delta
grid_y = p.y // delta
# 周り 9 箇所だけ調べれば OK
for dx, dy in DELTA_XY:
for q in grid[grid_x + dx, grid_y + dy]:
d = p.dist(q)
# if d < dist:
if d - dist < -EPS:
dist = d
ret_pair = p, q
return min(delta, dist), ret_pair
class Circle:
def __init__(self, o, r):
"""
:param Point o:
:param float r:
"""
self.o = o
self.r = r
def __eq__(self, other):
return self.o == other.o and abs(self.r - other.r) < EPS
def ctc(self, c):
"""
共通接線 common tangent の数
4: 離れてる
3: 外接
2: 交わってる
1: 内接
0: 内包
inf: 同一
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_A&lang=ja
:param Circle c:
:rtype: int
"""
if self.o == c.o:
return INF if abs(self.r - c.r) < EPS else 0
# 円同士の距離
d = self.o.dist(c.o) - self.r - c.r
if d > EPS:
return 4
elif d > -EPS:
return 3
# elif d > -min(self.r, c.r) * 2:
elif d + min(self.r, c.r) * 2 > EPS:
return 2
elif d + min(self.r, c.r) * 2 > -EPS:
return 1
return 0
def area(self):
"""
面積
"""
return self.r ** 2 * PI
def intersection_points(self, other, allow_outer=False):
"""
:param Segment|Circle other:
:param bool allow_outer:
"""
if isinstance(other, Segment):
return self.intersection_points_with_segment(other, allow_outer=allow_outer)
if isinstance(other, Circle):
return self.intersection_points_with_circle(other)
raise NotImplementedError()
def intersection_points_with_segment(self, s, allow_outer=False):
"""
線分と交差する点のリスト
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_D&lang=ja
:param Segment s:
:param bool allow_outer: 線分の間にない点を含む
:rtype: list of Point
"""
# 垂線の足
projection_point = self.o.projection_point(s.p1, s.p2, allow_outer=True)
# 線分との距離
dist = self.o.dist(projection_point)
# if dist > self.r:
if dist - self.r > EPS:
return []
if dist - self.r > -EPS:
if allow_outer or s.has_point(projection_point):
return [projection_point]
else:
return []
# 足から左右に diff だけ動かした座標が答え
diff = Point.from_polar(math.sqrt(self.r ** 2 - dist ** 2), s.phase())
ret1 = projection_point + diff
ret2 = projection_point - diff
ret = []
if allow_outer or s.has_point(ret1):
ret.append(ret1)
if allow_outer or s.has_point(ret2):
ret.append(ret2)
return ret
def intersection_points_with_circle(self, other):
"""
円と交差する点のリスト
Verify: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_7_E&langja
:param circle other:
:rtype: list of Point
"""
ctc = self.ctc(other)
if not 1 <= ctc <= 3:
return []
if ctc in (1, 3):
return [Point.from_polar(self.r, (other.o - self.o).phase()) + self.o]
# 2つ交点がある
assert ctc == 2
# 余弦定理で cos(a) を求めます
a = other.r
b = self.r
c = self.o.dist(other.o)
cos_a = (b ** 2 + c ** 2 - a ** 2) / (2 * b * c)
angle = math.acos(cos_a)
phi = (other.o - self.o).phase()
return [
self.o + Point.from_polar(self.r, phi + angle),
self.o + Point.from_polar(self.r, phi - angle),
]
def tangent_points(self, p):
"""
p を通る接線との接点
:param Point p:
:rtype: list of Point
"""
dist = self.o.dist(p)
# if dist < self.r:
if dist - self.r < -EPS:
# p が円の内部にある
return []
if dist - self.r < EPS:
# p が円周上にある
return [Point(p.c)]
# 余弦定理で cos(a) を求めます
a = math.sqrt(dist ** 2 - self.r ** 2)
b = self.r
c = dist
cos_a = (b ** 2 + c ** 2 - a ** 2) / (2 * b * c)
angle = math.acos(cos_a)
phi = (p - self.o).phase()
return [
self.o + Point.from_polar(self.r, phi + angle),
self.o + Point.from_polar(self.r, phi - angle),
]
def round_point(p):
"""
8桁で四捨五入して、-0を0に変換する
:param p:
:return:
"""
return round(p.x, 8) + 0, round(p.y, 8) + 0
px, py = list(map(int, sys.stdin.buffer.readline().split()))
cx, cy, r = list(map(int, sys.stdin.buffer.readline().split()))
circle = Circle(Point(complex(cx, cy)), r)
point = Point(complex(px, py))
ans = circle.tangent_points(point)
assert len(ans) == 2
p1, p2 = list(sorted(map(round_point, ans)))
print('{:.8f} {:.8f}'.format(*p1))
print('{:.8f} {:.8f}'.format(*p2))
``` | output | 1 | 108,601 | 23 | 217,203 |
Provide a correct Python 3 solution for this coding contest problem.
Find the tangent lines between a point $p$ and a circle $c$.
Constraints
* $-1,000 \leq px, py, cx, cy \leq 1,000$
* $1 \leq r \leq 1,000$
* Distance between $p$ and the center of $c$ is greater than the radius of $c$.
Input
The input is given in the following format.
$px \; py$
$cx \; cy \; r$
$px$ and $py$ represents the coordinate of the point $p$. $cx$, $cy$ and $r$ represents the center coordinate and radius of the circle $c$ respectively. All input values are given in integers.
Output
Print coordinates of the tangent points on the circle $c$ based on the following rules.
* Print the coordinate with smaller $x$ first. In case of a tie, print the coordinate with smaller $y$ first.
The output values should be in a decimal fraction with an error less than 0.00001.
Examples
Input
0 0
2 2 2
Output
0.0000000000 2.0000000000
2.0000000000 0.0000000000
Input
-3 0
2 2 2
Output
0.6206896552 3.4482758621
2.0000000000 0.0000000000 | instruction | 0 | 108,602 | 23 | 217,204 |
"Correct Solution:
```
#!/usr/bin/env python3
# CGL_7_F: Circles - Tangent to a Circle
from math import asin, atan2, cos, sin, sqrt
def tangent_point(circle, point):
cx, cy, cr = circle
x, y = point
p = (cx-x)**2 + (cy-y)**2
q = cr**2
r = sqrt(p - q)
t0 = atan2(cy-y, cx-x)
t1 = asin(cr/sqrt(p))
return [(x + r*cos(t0+t1), y + r*sin(t0+t1)),
(x + r*cos(t0-t1), y + r*sin(t0-t1))]
def run():
x, y = [int(i) for i in input().split()]
c = [int(i) for i in input().split()]
ps = tangent_point(c, (x, y))
p1, p2 = ps
if p1 > p2:
p1, p2 = p2, p1
print("{:.10f} {:.10f}".format(*p1))
print("{:.10f} {:.10f}".format(*p2))
if __name__ == '__main__':
run()
``` | output | 1 | 108,602 | 23 | 217,205 |
Provide a correct Python 3 solution for this coding contest problem.
Find the tangent lines between a point $p$ and a circle $c$.
Constraints
* $-1,000 \leq px, py, cx, cy \leq 1,000$
* $1 \leq r \leq 1,000$
* Distance between $p$ and the center of $c$ is greater than the radius of $c$.
Input
The input is given in the following format.
$px \; py$
$cx \; cy \; r$
$px$ and $py$ represents the coordinate of the point $p$. $cx$, $cy$ and $r$ represents the center coordinate and radius of the circle $c$ respectively. All input values are given in integers.
Output
Print coordinates of the tangent points on the circle $c$ based on the following rules.
* Print the coordinate with smaller $x$ first. In case of a tie, print the coordinate with smaller $y$ first.
The output values should be in a decimal fraction with an error less than 0.00001.
Examples
Input
0 0
2 2 2
Output
0.0000000000 2.0000000000
2.0000000000 0.0000000000
Input
-3 0
2 2 2
Output
0.6206896552 3.4482758621
2.0000000000 0.0000000000 | instruction | 0 | 108,603 | 23 | 217,206 |
"Correct Solution:
```
from math import pi, cos, sin, atan2
EPS = 10**(-9)
def eq(value1, value2):
return abs(value1-value2) <= EPS
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
self.arg = atan2(y, x) # -PI ~ PI
def __str__(self):
return "{0:.8f} {1:.8f}".format(self.x, self.y)
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Point(self.x - other.x, self.y - other.y)
def __mul__(self, scal):
return Point(self.x*scal, self.y*scal)
def __truediv__(self, scal):
return Point(self.x/scal, self.y/scal)
def __eq__(self, other):
return eq(self.x, other.x) and eq(self.y, other.y)
# 原点からの距離
def __abs__(self):
return (self.x**2+self.y**2)**0.5
# 原点を中心にrad角だけ回転した点
def Rotation(vec: Point, rad):
return Point(vec.x*cos(rad)-vec.y*sin(rad), vec.x*sin(rad)+vec.y*cos(rad))
class Circle():
def __init__(self, p, r):
self.p = p
self.r = r
class Line():
# 点a, bを通る
def __init__(self, a, b):
self.a = a
self.b = b
self.arg = (a-b).arg % pi
def __str__(self):
return "[({0}, {1}) - ({2}, {3})]".format(self.a.x, self.a.y, self.b.x, self.b.y)
# pointを通って平行
def par(self, point):
return Line(point, point+(self.a-self.b))
# pointを通って垂直
def tan(self, point):
return Line(point, point + Rotation(self.a-self.b, pi/2))
class Segment(Line):
def __init__(self, a, b):
super().__init__(a, b)
# 符号付き面積
def cross(vec1: Point, vec2: Point):
return vec1.x*vec2.y - vec1.y*vec2.x
# 内積
def dot(vec1: Point, vec2: Point):
return vec1.x*vec2.x + vec1.y*vec2.y
# 点a->b->cの回転方向
def ccw(a, b, c):
if cross(b-a, c-a) > EPS: return +1 # COUNTER_CLOCKWISE
if cross(b-a, c-a) < -EPS: return -1 # CLOCKWISE
if dot(c-a, b-a) < -EPS: return +2 # c -> a -> b
if abs(b-a) < abs(c-a): return -2 # a -> b -> c
return 0 # a -> c -> b
# pのlへの射影
def projection(l, p):
t = dot(l.b-l.a, p-l.a) / abs(l.a-l.b)**2
return l.a + (l.b-l.a)*t
# pのlによる反射
def reflection(l, p):
return p + (projection(l, p) - p)*2
def isPararell(l1, l2):
return eq(cross(l1.a-l1.b, l2.a-l2.b), 0)
def isVertical(l1, l2):
return eq(dot(l1.a-l1.b, l2.a-l2.b), 0)
def isIntersect_lp(l, p):
return abs(ccw(l.a, l.b, p)) != 1
def isIntersect_ll(l1, l2):
return not isPararell(l1, l2) or isIntersect_lp(l1, l2.a)
def isIntersect_sp(s, p):
return ccw(s.a, s.b, p) == 0
def isIntersect_ss(s1, s2):
return ccw(s1.a, s1.b, s2.a)*ccw(s1.a, s1.b, s2.b) <= 0 and ccw(s2.a, s2.b, s1.a)*ccw(s2.a, s2.b, s1.b) <= 0
def isIntersect_ls(l, s):
return cross(l.b - l.a, s.a - l.a) * cross(l.b - l.a, s.b - l.a) < EPS
def isIntersect_cp(c, p):
return abs(abs(c.p - p) - c.r) < EPS
def isIntersect_cl(c, l):
return distance_lp(l, c.p) <= c.r + EPS
def isIntersect_cs(c, s):
pass
def intersect_cc(c1, c2):
if c1.r < c2.r:
c1, c2 = c2, c1
d = abs(c1.p - c2.p)
if eq(c1.r + c2.r, d): return 3 # 内接
if eq(c1.r - c2.r, d): return 1 # 外接
if c1.r + c2.r < d: return 4 # 含まれてる
if c1.r - c2.r < d: return 2 # 2交点持つ
return 0 # 離れてる
def distance_pp(p1, p2):
return abs(p1-p2)
def distance_lp(l, p):
return abs(projection(l,p)-p)
def distance_ll(l1, l2):
return 0 if isIntersect_ll(l1, l2) else distance_lp(l1, l2.a)
def distance_sp(s, p):
r = projection(s, p)
if isIntersect_sp(s, r): return abs(r-p)
return min(abs(s.a-p), abs(s.b-p))
def distance_ss(s1, s2):
if isIntersect_ss(s1, s2): return 0
return min([distance_sp(s1, s2.a), distance_sp(s1, s2.b), distance_sp(s2, s1.a), distance_sp(s2, s1.b)])
def distance_ls(l, s):
if isIntersect_ls(l, s): return 0
return min(distance_lp(l, s.a), distance_lp(l, s.b))
def crosspoint_ll(l1, l2):
A = cross(l1.b - l1.a, l2.b - l2.a)
B = cross(l1.b - l1.a, l1.b - l2.a)
if eq(abs(A), 0) and eq(abs(B), 0): return l2.a
return l2.a + (l2.b - l2.a) * B / A
def crosspoint_ss(s1, s2):
return crosspoint_ll(s1, s2)
def crosspoint_lc(l, c):
p = projection(l, c.p)
if eq(distance_lp(l, c.p), c.r): return [p]
e = (l.b - l.a) / abs(l.b-l.a)
dis = (c.r**2-abs(p-c.p)**2)**0.5
return [p + e*dis, p - e*dis]
def crosspoint_sc(s, c):
pass
def crosspoint_cc(c1, c2):
d = abs(c1.p-c2.p)
if not abs(c1.r-c2.r) <= d <= c1.r+c2.r:
return []
mid_p = (c2.p * (c1.r**2-c2.r**2+d**2) + c1.p * (c2.r**2-c1.r**2+d**2)) / (2*d**2)
tanvec = Rotation(c1.p-c2.p, pi/2)
return crosspoint_lc(Line(mid_p, mid_p+tanvec), c1)
# pからのcの接点
def tangent_cp(c, p):
return crosspoint_cc(c, Circle(p, (abs(p-c.p)**2 - c.r**2)**0.5))
import sys
input = sys.stdin.readline
def verify_1A():
p1x, p1y, p2x, p2y = map(int, input().split())
l = Line(Point(p1x, p1y), Point(p2x, p2y))
Q = int(input())
Query = [list(map(int, input().split())) for _ in range(Q)]
for px, py in Query:
p = Point(px, py)
print(projection(l, p))
def verify_1B():
p1x, p1y, p2x, p2y = map(int, input().split())
l = Line(Point(p1x, p1y), Point(p2x, p2y))
Q = int(input())
Query = [list(map(int, input().split())) for _ in range(Q)]
for px, py in Query:
p = Point(px, py)
print(reflection(l, p))
def verify_1C():
p1x, p1y, p2x, p2y = map(int, input().split())
p1 = Point(p1x, p1y); p2 = Point(p2x, p2y)
Q = int(input())
Query = [list(map(int, input().split())) for _ in range(Q)]
for px, py in Query:
p = Point(px, py)
result = ccw(p1, p2, p)
if result == 1:
print("COUNTER_CLOCKWISE")
elif result == -1:
print("CLOCKWISE")
elif result == 2:
print("ONLINE_BACK")
elif result == -2:
print("ONLINE_FRONT")
else:
print("ON_SEGMENT")
def verify_2A():
Q = int(input())
Query = [list(map(int, input().split())) for _ in range(Q)]
for p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y in Query:
l1 = Line(Point(p0x, p0y), Point(p1x, p1y))
l2 = Line(Point(p2x, p2y), Point(p3x, p3y))
if isPararell(l1, l2):
print(2)
elif isVertical(l1, l2):
print(1)
else:
print(0)
def verify_2B():
Q = int(input())
Query = [list(map(int, input().split())) for _ in range(Q)]
for p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y in Query:
s1 = Segment(Point(p0x, p0y), Point(p1x, p1y))
s2 = Segment(Point(p2x, p2y), Point(p3x, p3y))
if isIntersect_ss(s1, s2):
print(1)
else:
print(0)
def verify_2C():
Q = int(input())
Query = [list(map(int, input().split())) for _ in range(Q)]
for p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y in Query:
s1 = Segment(Point(p0x, p0y), Point(p1x, p1y))
s2 = Segment(Point(p2x, p2y), Point(p3x, p3y))
print(crosspoint_ss(s1, s2))
def verify_2D():
Q = int(input())
Query = [list(map(int, input().split())) for _ in range(Q)]
for p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y in Query:
s1 = Segment(Point(p0x, p0y), Point(p1x, p1y))
s2 = Segment(Point(p2x, p2y), Point(p3x, p3y))
print("{:.8f}".format(distance_ss(s1, s2)))
def verify_7A():
c1x, c1y, c1r = map(int, input().split())
c2x, c2y, c2r = map(int, input().split())
print(intersect_cc(Circle(Point(c1x, c1y), c1r), Circle(Point(c2x, c2y), c2r)))
def verify_7D():
cx, cy, cr = map(int, input().split())
c = Circle(Point(cx, cy), cr)
Q = int(input())
Query = [list(map(int, input().split())) for _ in range(Q)]
for x1, y1, x2, y2 in Query:
Points = crosspoint_lc(Line(Point(x1, y1), Point(x2,y2)), c)
if len(Points) == 1:
Points.append(Points[-1])
Points.sort(key=lambda p: p.y)
Points.sort(key=lambda p: p.x)
print(*Points)
def verify_7E():
c1x, c1y, c1r = map(int, input().split())
c1 = Circle(Point(c1x, c1y), c1r)
c2x, c2y, c2r = map(int, input().split())
c2 = Circle(Point(c2x, c2y), c2r)
Points = crosspoint_cc(c1, c2)
if len(Points) == 1:
Points.append(Points[-1])
Points.sort(key=lambda p: p.y)
Points.sort(key=lambda p: p.x)
print(*Points)
def verify_7F():
px, py = map(int, input().split())
cx, cy, cr = map(int, input().split())
Points = tangent_cp(Circle(Point(cx, cy), cr), Point(px, py))
if len(Points) == 1:
Points.append(Points[-1])
Points.sort(key=lambda p: p.y)
Points.sort(key=lambda p: p.x)
print(*Points, sep="\n")
verify_7F()
``` | output | 1 | 108,603 | 23 | 217,207 |
Provide a correct Python 3 solution for this coding contest problem.
Find the tangent lines between a point $p$ and a circle $c$.
Constraints
* $-1,000 \leq px, py, cx, cy \leq 1,000$
* $1 \leq r \leq 1,000$
* Distance between $p$ and the center of $c$ is greater than the radius of $c$.
Input
The input is given in the following format.
$px \; py$
$cx \; cy \; r$
$px$ and $py$ represents the coordinate of the point $p$. $cx$, $cy$ and $r$ represents the center coordinate and radius of the circle $c$ respectively. All input values are given in integers.
Output
Print coordinates of the tangent points on the circle $c$ based on the following rules.
* Print the coordinate with smaller $x$ first. In case of a tie, print the coordinate with smaller $y$ first.
The output values should be in a decimal fraction with an error less than 0.00001.
Examples
Input
0 0
2 2 2
Output
0.0000000000 2.0000000000
2.0000000000 0.0000000000
Input
-3 0
2 2 2
Output
0.6206896552 3.4482758621
2.0000000000 0.0000000000 | instruction | 0 | 108,604 | 23 | 217,208 |
"Correct Solution:
```
px, py = map(int, input().split())
cx, cy, r = map(int, input().split())
dx, dy = px - cx, py - cy
s2 = dx ** 2 + dy ** 2
df = (s2 - r ** 2) ** 0.5
ix1, ix2 = (dx * r + dy * df) * r / s2, (dx * r - dy * df) * r / s2
iy1, iy2 = (dy * r - dx * df) * r / s2, (dy * r + dx * df) * r / s2
if (ix1, iy1) > (ix2, iy2):
ix1, ix2 = ix2, ix1
iy1, iy2 = iy2, iy1
print(ix1 + cx, iy1 + cy)
print(ix2 + cx, iy2 + cy)
``` | output | 1 | 108,604 | 23 | 217,209 |
Provide a correct Python 3 solution for this coding contest problem.
Find the tangent lines between a point $p$ and a circle $c$.
Constraints
* $-1,000 \leq px, py, cx, cy \leq 1,000$
* $1 \leq r \leq 1,000$
* Distance between $p$ and the center of $c$ is greater than the radius of $c$.
Input
The input is given in the following format.
$px \; py$
$cx \; cy \; r$
$px$ and $py$ represents the coordinate of the point $p$. $cx$, $cy$ and $r$ represents the center coordinate and radius of the circle $c$ respectively. All input values are given in integers.
Output
Print coordinates of the tangent points on the circle $c$ based on the following rules.
* Print the coordinate with smaller $x$ first. In case of a tie, print the coordinate with smaller $y$ first.
The output values should be in a decimal fraction with an error less than 0.00001.
Examples
Input
0 0
2 2 2
Output
0.0000000000 2.0000000000
2.0000000000 0.0000000000
Input
-3 0
2 2 2
Output
0.6206896552 3.4482758621
2.0000000000 0.0000000000 | instruction | 0 | 108,605 | 23 | 217,210 |
"Correct Solution:
```
import math
line = input()
px, py = list(map(int, line.split()))
line = input()
cx, cy, r = list(map(int, line.split()))
def solve():
d2 = (px - cx)*(px - cx) + (py - cy)*(py - cy)
d = math.sqrt(d2)
sine = r / d
sin2 = r * r / d2
cosine = math.sqrt(1 - sin2)
cos2 = 1 - sin2
x1 = (cx - px) * cos2 - (cy - py) * sine * cosine + px
y1 = (cx - px) * sine * cosine + (cy - py) * cos2 + py
x2 = (cx - px) * cos2 + (cy - py) * sine * cosine + px
y2 = - (cx - px) * sine * cosine + (cy - py) * cos2 + py
if x1 > x2:
x1, x2 = x2, x1
y1, y2 = y2, y1
print(x1, y1)
print(x2, y2)
solve()
``` | output | 1 | 108,605 | 23 | 217,211 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Find the tangent lines between a point $p$ and a circle $c$.
Constraints
* $-1,000 \leq px, py, cx, cy \leq 1,000$
* $1 \leq r \leq 1,000$
* Distance between $p$ and the center of $c$ is greater than the radius of $c$.
Input
The input is given in the following format.
$px \; py$
$cx \; cy \; r$
$px$ and $py$ represents the coordinate of the point $p$. $cx$, $cy$ and $r$ represents the center coordinate and radius of the circle $c$ respectively. All input values are given in integers.
Output
Print coordinates of the tangent points on the circle $c$ based on the following rules.
* Print the coordinate with smaller $x$ first. In case of a tie, print the coordinate with smaller $y$ first.
The output values should be in a decimal fraction with an error less than 0.00001.
Examples
Input
0 0
2 2 2
Output
0.0000000000 2.0000000000
2.0000000000 0.0000000000
Input
-3 0
2 2 2
Output
0.6206896552 3.4482758621
2.0000000000 0.0000000000
Submitted Solution:
```
px, py = map(int, input().split())
cx, cy, r = map(int, input().split())
dx, dy = px - cx, py - cy
s2 = dx ** 2 + dy ** 2
df = (s2 - r ** 2) ** 0.5
ix1, ix2 = (dx * r + dy * df) / s2, (dx * r - dy * df) / s2
iy1, iy2 = (dy * r - dx * df) / s2, (dy * r + dx * df) / s2
if (ix1, iy1) > (ix2, iy2):
ix1, ix2 = ix2, ix1
iy1, iy2 = iy2, iy1
print(ix1 + cx, iy1 + cy)
print(ix2 + cx, iy2 + cy)
``` | instruction | 0 | 108,606 | 23 | 217,212 |
No | output | 1 | 108,606 | 23 | 217,213 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.