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.
Given are N points on the circumference of a circle centered at (0,0) in an xy-plane. The coordinates of the i-th point are (\cos(\frac{2\pi T_i}{L}),\sin(\frac{2\pi T_i}{L})).
Three distinct points will be chosen uniformly at random from these N points. Find the expected x- and y-coordinates of the center of the circle inscribed in the triangle formed by the chosen points.
Constraints
* 3 \leq N \leq 3000
* N \leq L \leq 10^9
* 0 \leq T_i \leq L-1
* T_i<T_{i+1}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N L
T_1
:
T_N
Output
Print the expected x- and y-coordinates of the center of the circle inscribed in the triangle formed by the chosen points. Your output will be considered correct when the absolute or relative error is at most 10^{-9}.
Examples
Input
3 4
0
1
3
Output
0.414213562373095 -0.000000000000000
Input
4 8
1
3
5
6
Output
-0.229401949926902 -0.153281482438188
Input
10 100
2
11
35
42
54
69
89
91
93
99
Output
0.352886583546338 -0.109065017701873
Submitted Solution:
```
import math
pi=math.pi
def X(t,l) :
return cos(2*pi*t/l)
def Y(t,l) :
return sin(2*pi*t/l)
def midpoint(a,b,l) :
if a<b : return (a+b)/2
elif a+b < l : return (l+a+b)/2
else : return (a+b-l)/2
t=[0]
a=input().split()
n=int(a[0]);l=int(a[1])
x=0;y=0
for i in range(n) : t.append(int(input()))
for i in range(1,n+1) :
for j in range(i+1,n+1) :
pos=midpoint(t[i],t[j],l)
x+=X(pos,l)*(n-j+i-1)
y+=Y(pos,l)*(n-j+i-1)
pos=midpoint(t[j],t[i],l)
x+=X(pos,l)*(j-i-1)
y+=Y(pos,l)*(j-i-1)
tot=n*(n-1)*(n-2)/6
print(x,y)
``` | instruction | 0 | 35,791 | 23 | 71,582 |
No | output | 1 | 35,791 | 23 | 71,583 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given are N points on the circumference of a circle centered at (0,0) in an xy-plane. The coordinates of the i-th point are (\cos(\frac{2\pi T_i}{L}),\sin(\frac{2\pi T_i}{L})).
Three distinct points will be chosen uniformly at random from these N points. Find the expected x- and y-coordinates of the center of the circle inscribed in the triangle formed by the chosen points.
Constraints
* 3 \leq N \leq 3000
* N \leq L \leq 10^9
* 0 \leq T_i \leq L-1
* T_i<T_{i+1}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N L
T_1
:
T_N
Output
Print the expected x- and y-coordinates of the center of the circle inscribed in the triangle formed by the chosen points. Your output will be considered correct when the absolute or relative error is at most 10^{-9}.
Examples
Input
3 4
0
1
3
Output
0.414213562373095 -0.000000000000000
Input
4 8
1
3
5
6
Output
-0.229401949926902 -0.153281482438188
Input
10 100
2
11
35
42
54
69
89
91
93
99
Output
0.352886583546338 -0.109065017701873
Submitted Solution:
```
import math
def calc_incenters(x,y,xx,yy,xxx,yyy):
def calc_len(x,y,xx,yy):
return(math.sqrt((x - xx)**2 + (y - yy)**2))
a = calc_len(x,y,xx,yy)
b = calc_len(xx,yy,xxx,yyy)
c = calc_len(xxx,yyy,x,y)
out_x = (a * xxx + b * x + c * xx)/(a+b+c)
out_y = (a * yyy + b * y + c * yy)/(a+b+c)
return([out_x, out_y])
n,l =map(int, input().split())
tlis = []
for i in range(n):
t = int(input())
tlis.append(t)
xlis = []
ylis = []
for i in range(n-2):
for j in range(n-i-2):
for k in range(n-j-i-2):
xlis.append(calc_incenters(math.cos(2*math.pi*tlis[i]/l), math.sin(2*math.pi*tlis[i]/l), math.cos(2*math.pi*tlis[j+i+1]/l),math.sin(2*math.pi*tlis[j+i+1]/l), math.cos(2*math.pi*tlis[k+j+i+2]/l), math.sin(2*math.pi*tlis[k+j+i+2]/l))[0])
ylis.append(calc_incenters(math.cos(2*math.pi*tlis[i]/l), math.sin(2*math.pi*tlis[i]/l), math.cos(2*math.pi*tlis[j+i+1]/l),math.sin(2*math.pi*tlis[j+i+1]/l), math.cos(2*math.pi*tlis[k+j+i+2]/l), math.sin(2*math.pi*tlis[k+j+i+2]/l))[1])
print(sum(xlis)/len(xlis),sum(ylis)/len(ylis))
``` | instruction | 0 | 35,792 | 23 | 71,584 |
No | output | 1 | 35,792 | 23 | 71,585 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Andrey has been skipping physical education lessons for the whole term, and now he must somehow get a passing grade on this subject. Obviously, it is impossible to do this by legal means, but Andrey doesn't give up. Having obtained an empty certificate from a local hospital, he is going to use his knowledge of local doctor's handwriting to make a counterfeit certificate of illness. However, after writing most of the certificate, Andrey suddenly discovered that doctor's signature is impossible to forge. Or is it?
For simplicity, the signature is represented as an n× m grid, where every cell is either filled with ink or empty. Andrey's pen can fill a 3×3 square without its central cell if it is completely contained inside the grid, as shown below.
xxx
x.x
xxx
Determine whether is it possible to forge the signature on an empty n× m grid.
Input
The first line of input contains two integers n and m (3 ≤ n, m ≤ 1000).
Then n lines follow, each contains m characters. Each of the characters is either '.', representing an empty cell, or '#', representing an ink filled cell.
Output
If Andrey can forge the signature, output "YES". Otherwise output "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3 3
###
#.#
###
Output
YES
Input
3 3
###
###
###
Output
NO
Input
4 3
###
###
###
###
Output
YES
Input
5 7
.......
.#####.
.#.#.#.
.#####.
.......
Output
YES
Note
In the first sample Andrey can paint the border of the square with the center in (2, 2).
In the second sample the signature is impossible to forge.
In the third sample Andrey can paint the borders of the squares with the centers in (2, 2) and (3, 2):
1. we have a clear paper:
...
...
...
...
2. use the pen with center at (2, 2).
###
#.#
###
...
3. use the pen with center at (3, 2).
###
###
###
###
In the fourth sample Andrey can paint the borders of the squares with the centers in (3, 3) and (3, 5). | instruction | 0 | 36,014 | 23 | 72,028 |
Tags: implementation
Correct Solution:
```
n,m = [int (i) for i in input().split()]
a = []
b = []
a.append ('.'*(m+4))
a.append ('.'*(m+4))
b.append ([0 for i in range (m+4)])
b.append ([0 for i in range (m+4)])
t = False
for i in range (n):
s = input ()
a.append ('..'+s+'..')
b.append([0 for i in range (m+4)])
a.append ('.'*(m+4))
a.append ('.'*(m+4))
b.append ([0 for i in range (m+4)])
b.append ([0 for i in range (m+4)])
for i in range (2,n+2):
if t:
break;
for j in range (2,m+2):
if a[i][j] == '#':
if a[i][j+1] == '#' and a[i][j+2] == '#' and a[i+1][j+2] == '#' and a[i+2][j+2] == '#' and a[i+2][j+1] == '#' and a[i+2][j] == '#' and a[i+1][j] == '#':
b[i][j] +=1
b[i][j+1] += 1
b[i][j+2] += 1
b[i+1][j+2] += 1
b[i+2][j+2] += 1
b[i+2][j+1] += 1
b[i+2][j] += 1
b[i+1][j] += 1
elif b[i][j] == 0:
t = True
break;
if t:
print ('NO')
else:
print ('YES')
``` | output | 1 | 36,014 | 23 | 72,029 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Andrey has been skipping physical education lessons for the whole term, and now he must somehow get a passing grade on this subject. Obviously, it is impossible to do this by legal means, but Andrey doesn't give up. Having obtained an empty certificate from a local hospital, he is going to use his knowledge of local doctor's handwriting to make a counterfeit certificate of illness. However, after writing most of the certificate, Andrey suddenly discovered that doctor's signature is impossible to forge. Or is it?
For simplicity, the signature is represented as an n× m grid, where every cell is either filled with ink or empty. Andrey's pen can fill a 3×3 square without its central cell if it is completely contained inside the grid, as shown below.
xxx
x.x
xxx
Determine whether is it possible to forge the signature on an empty n× m grid.
Input
The first line of input contains two integers n and m (3 ≤ n, m ≤ 1000).
Then n lines follow, each contains m characters. Each of the characters is either '.', representing an empty cell, or '#', representing an ink filled cell.
Output
If Andrey can forge the signature, output "YES". Otherwise output "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3 3
###
#.#
###
Output
YES
Input
3 3
###
###
###
Output
NO
Input
4 3
###
###
###
###
Output
YES
Input
5 7
.......
.#####.
.#.#.#.
.#####.
.......
Output
YES
Note
In the first sample Andrey can paint the border of the square with the center in (2, 2).
In the second sample the signature is impossible to forge.
In the third sample Andrey can paint the borders of the squares with the centers in (2, 2) and (3, 2):
1. we have a clear paper:
...
...
...
...
2. use the pen with center at (2, 2).
###
#.#
###
...
3. use the pen with center at (3, 2).
###
###
###
###
In the fourth sample Andrey can paint the borders of the squares with the centers in (3, 3) and (3, 5). | instruction | 0 | 36,015 | 23 | 72,030 |
Tags: implementation
Correct Solution:
```
from sys import stdin,stdout
from math import gcd,sqrt
from collections import deque
input=stdin.readline
R=lambda:map(int,input().split())
I=lambda:int(input())
S=lambda:input().rstrip('\n')
L=lambda:list(R())
P=lambda x:stdout.write(x)
hg=lambda x,y:((y+x-1)//x)*x
pw=lambda x:1 if x==1 else 1+pw(x//2)
chk=lambda x:chk(x//2) if not x%2 else True if x==1 else False
def mj(x,y):
flg=False
if a[x][y]==a[x+1][y]==a[x+2][y]==a[x][y+1]==a[x][y+2]==a[x+1][y+2]==a[x+2][y+2]==a[x+2][y+1]=='#':flg=True
elif a[x][y]==a[x-1][y]==a[x+1][y]==a[x-1][y+1]==a[x-1][y+2]==a[x][y+2]==a[x+1][y+2]==a[x+1][y+1]=='#':flg=True
elif a[x][y]==a[x-1][y]==a[x-2][y]==a[x][y+1]==a[x][y+2]==a[x-1][y+2]==a[x-2][y+2]==a[x-2][y+1]=='#':flg=True
elif a[x][y]==a[x][y+1]==a[x][y-1]==a[x+1][y-1]==a[x+1][y+1]==a[x+2][y-1]==a[x+2][y]==a[x+2][y+1]=='#':flg=True
elif a[x][y]==a[x][y+1]==a[x][y-1]==a[x-1][y-1]==a[x-1][y+1]==a[x-2][y-1]==a[x-2][y]==a[x-2][y+1]=='#':flg=True
elif a[x][y]==a[x][y-1]==a[x][y-2]==a[x-1][y]==a[x-1][y-2]==a[x-2][y]==a[x-2][y-1]==a[x-2][y-2]=='#':flg=True
elif a[x][y]==a[x+1][y]==a[x-1][y]==a[x+1][y-1]==a[x+1][y-2]==a[x][y-2]==a[x-1][y-1]==a[x-1][y-1]=='#':flg=True
elif a[x][y]==a[x][y-1]==a[x][y-2]==a[x+1][y]==a[x+1][y-2]==a[x+2][y]==a[x+2][y-1]==a[x+2][y-2]=='#':flg=True
return flg
r,c=R()
a=['.'*(c+4),'.'*(c+4)]
for i in range(r):
a.append('..'+S()+'..')
a.extend(['.'*(c+4),'.'*(c+4)])
for i in range(2,r+2):
for j in range(2,c+2):
if a[i][j]=='#' and not mj(i,j):exit(print('NO'))
print('YES')
``` | output | 1 | 36,015 | 23 | 72,031 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Andrey has been skipping physical education lessons for the whole term, and now he must somehow get a passing grade on this subject. Obviously, it is impossible to do this by legal means, but Andrey doesn't give up. Having obtained an empty certificate from a local hospital, he is going to use his knowledge of local doctor's handwriting to make a counterfeit certificate of illness. However, after writing most of the certificate, Andrey suddenly discovered that doctor's signature is impossible to forge. Or is it?
For simplicity, the signature is represented as an n× m grid, where every cell is either filled with ink or empty. Andrey's pen can fill a 3×3 square without its central cell if it is completely contained inside the grid, as shown below.
xxx
x.x
xxx
Determine whether is it possible to forge the signature on an empty n× m grid.
Input
The first line of input contains two integers n and m (3 ≤ n, m ≤ 1000).
Then n lines follow, each contains m characters. Each of the characters is either '.', representing an empty cell, or '#', representing an ink filled cell.
Output
If Andrey can forge the signature, output "YES". Otherwise output "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3 3
###
#.#
###
Output
YES
Input
3 3
###
###
###
Output
NO
Input
4 3
###
###
###
###
Output
YES
Input
5 7
.......
.#####.
.#.#.#.
.#####.
.......
Output
YES
Note
In the first sample Andrey can paint the border of the square with the center in (2, 2).
In the second sample the signature is impossible to forge.
In the third sample Andrey can paint the borders of the squares with the centers in (2, 2) and (3, 2):
1. we have a clear paper:
...
...
...
...
2. use the pen with center at (2, 2).
###
#.#
###
...
3. use the pen with center at (3, 2).
###
###
###
###
In the fourth sample Andrey can paint the borders of the squares with the centers in (3, 3) and (3, 5). | instruction | 0 | 36,016 | 23 | 72,032 |
Tags: implementation
Correct Solution:
```
n,m=map(int,input().split())
a=[list('') for x in range(n)]
b=[list('.'*m) for x in range(n)]
start=0
#end=n-2
for i in range(n):
a[i]=list(input())
if (start==0):
if ('.' in a[i]):
start=((i-3)//3) *3
for i in range(start):
b[i]=list('#'*m)
#print(start)
for i in range(start,n-2):
for j in range(m-2):
ok=True
if a[i][j]=='#':
for y in range(i,i+3):
if ok==False:
break
for x in range(j,j+3):
if not((y==i+1)and(x==j+1)):
if a[y][x]!='#':
#print('lel')
#print(x,y)
ok=False
break
if ok:
for y in range(i,i+3):
for x in range(j,j+3):
if not((y==i+1)and(x==j+1)):
b[y][x]='#'
#for i in a:
# print(i)
#print()
#for i in b:
# print(i)
if a==b:
print('YES')
else:
print('NO')
``` | output | 1 | 36,016 | 23 | 72,033 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Andrey has been skipping physical education lessons for the whole term, and now he must somehow get a passing grade on this subject. Obviously, it is impossible to do this by legal means, but Andrey doesn't give up. Having obtained an empty certificate from a local hospital, he is going to use his knowledge of local doctor's handwriting to make a counterfeit certificate of illness. However, after writing most of the certificate, Andrey suddenly discovered that doctor's signature is impossible to forge. Or is it?
For simplicity, the signature is represented as an n× m grid, where every cell is either filled with ink or empty. Andrey's pen can fill a 3×3 square without its central cell if it is completely contained inside the grid, as shown below.
xxx
x.x
xxx
Determine whether is it possible to forge the signature on an empty n× m grid.
Input
The first line of input contains two integers n and m (3 ≤ n, m ≤ 1000).
Then n lines follow, each contains m characters. Each of the characters is either '.', representing an empty cell, or '#', representing an ink filled cell.
Output
If Andrey can forge the signature, output "YES". Otherwise output "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3 3
###
#.#
###
Output
YES
Input
3 3
###
###
###
Output
NO
Input
4 3
###
###
###
###
Output
YES
Input
5 7
.......
.#####.
.#.#.#.
.#####.
.......
Output
YES
Note
In the first sample Andrey can paint the border of the square with the center in (2, 2).
In the second sample the signature is impossible to forge.
In the third sample Andrey can paint the borders of the squares with the centers in (2, 2) and (3, 2):
1. we have a clear paper:
...
...
...
...
2. use the pen with center at (2, 2).
###
#.#
###
...
3. use the pen with center at (3, 2).
###
###
###
###
In the fourth sample Andrey can paint the borders of the squares with the centers in (3, 3) and (3, 5). | instruction | 0 | 36,017 | 23 | 72,034 |
Tags: implementation
Correct Solution:
```
n = [int(i) for i in input().split()]
l = [[0 for i in range(n[1])] for j in range(n[0])]
for i in range(n[0]):
x = input()
for j in range(n[1]):
if(x[j]=='#'):
l[i][j] = 2
else:
l[i][j] = 0
m = 1
for i in range(n[0]):
for j in range(n[1]):
if(l[i][j]!=0 and (i+3)<=n[0] and(j+3)<=n[1]):
# print('ko')
c = 0
for i1 in range(3):
for j1 in range(3):
if(l[i+i1][j+j1] == 0 and (i1!=j1 or j1!=1)):
# print('YES!')
c = 1
if(c == 0):
for i1 in range(3):
for j1 in range(3):
if(i1!=j1 or j1!=1):
l[i+i1][j+j1] = 1
if(l[i][j] == 2):
# print(i,j)
m = 0
break
if(m==0):
break
if(m==1):
print('YES')
else:
print('NO')
``` | output | 1 | 36,017 | 23 | 72,035 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Andrey has been skipping physical education lessons for the whole term, and now he must somehow get a passing grade on this subject. Obviously, it is impossible to do this by legal means, but Andrey doesn't give up. Having obtained an empty certificate from a local hospital, he is going to use his knowledge of local doctor's handwriting to make a counterfeit certificate of illness. However, after writing most of the certificate, Andrey suddenly discovered that doctor's signature is impossible to forge. Or is it?
For simplicity, the signature is represented as an n× m grid, where every cell is either filled with ink or empty. Andrey's pen can fill a 3×3 square without its central cell if it is completely contained inside the grid, as shown below.
xxx
x.x
xxx
Determine whether is it possible to forge the signature on an empty n× m grid.
Input
The first line of input contains two integers n and m (3 ≤ n, m ≤ 1000).
Then n lines follow, each contains m characters. Each of the characters is either '.', representing an empty cell, or '#', representing an ink filled cell.
Output
If Andrey can forge the signature, output "YES". Otherwise output "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3 3
###
#.#
###
Output
YES
Input
3 3
###
###
###
Output
NO
Input
4 3
###
###
###
###
Output
YES
Input
5 7
.......
.#####.
.#.#.#.
.#####.
.......
Output
YES
Note
In the first sample Andrey can paint the border of the square with the center in (2, 2).
In the second sample the signature is impossible to forge.
In the third sample Andrey can paint the borders of the squares with the centers in (2, 2) and (3, 2):
1. we have a clear paper:
...
...
...
...
2. use the pen with center at (2, 2).
###
#.#
###
...
3. use the pen with center at (3, 2).
###
###
###
###
In the fourth sample Andrey can paint the borders of the squares with the centers in (3, 3) and (3, 5). | instruction | 0 | 36,018 | 23 | 72,036 |
Tags: implementation
Correct Solution:
```
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
n, m = [int(t) for t in input().split()]
#n, m = 1000, 1000
a = []
for i in range(n):
#s = ['#'] * 1000
s = list(input())
a.append(s)
for i in range(n-2):
for j in range(m-2):
if (a[i][j] == '#' or a[i][j] == 'x') and \
(a[i+1][j] == '#' or a[i+1][j] == 'x') and \
(a[i+2][j] == '#' or a[i+2][j] == 'x') and \
(a[i][j+1] == '#' or a[i][j+1] == 'x') and \
(a[i][j+2] == '#' or a[i][j+2] == 'x') and \
(a[i+1][j+2] == '#' or a[i+1][j+2] == 'x') and \
(a[i+2][j+1] == '#' or a[i+2][j+1] == 'x') and \
(a[i+2][j+2] == '#' or a[i+2][j+2] == 'x'):
a[i][j] = a[i+1][j] = a[i+2][j] = a[i][j+1] = a[i][j+2] = a[i+1][j+2] = a[i+2][j+1] = a[i+2][j+2] = 'x'
for i in range(n):
for j in range(m):
if a[i][j] == '#':
print('NO')
exit(0)
print('YES')
``` | output | 1 | 36,018 | 23 | 72,037 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Andrey has been skipping physical education lessons for the whole term, and now he must somehow get a passing grade on this subject. Obviously, it is impossible to do this by legal means, but Andrey doesn't give up. Having obtained an empty certificate from a local hospital, he is going to use his knowledge of local doctor's handwriting to make a counterfeit certificate of illness. However, after writing most of the certificate, Andrey suddenly discovered that doctor's signature is impossible to forge. Or is it?
For simplicity, the signature is represented as an n× m grid, where every cell is either filled with ink or empty. Andrey's pen can fill a 3×3 square without its central cell if it is completely contained inside the grid, as shown below.
xxx
x.x
xxx
Determine whether is it possible to forge the signature on an empty n× m grid.
Input
The first line of input contains two integers n and m (3 ≤ n, m ≤ 1000).
Then n lines follow, each contains m characters. Each of the characters is either '.', representing an empty cell, or '#', representing an ink filled cell.
Output
If Andrey can forge the signature, output "YES". Otherwise output "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3 3
###
#.#
###
Output
YES
Input
3 3
###
###
###
Output
NO
Input
4 3
###
###
###
###
Output
YES
Input
5 7
.......
.#####.
.#.#.#.
.#####.
.......
Output
YES
Note
In the first sample Andrey can paint the border of the square with the center in (2, 2).
In the second sample the signature is impossible to forge.
In the third sample Andrey can paint the borders of the squares with the centers in (2, 2) and (3, 2):
1. we have a clear paper:
...
...
...
...
2. use the pen with center at (2, 2).
###
#.#
###
...
3. use the pen with center at (3, 2).
###
###
###
###
In the fourth sample Andrey can paint the borders of the squares with the centers in (3, 3) and (3, 5). | instruction | 0 | 36,019 | 23 | 72,038 |
Tags: implementation
Correct Solution:
```
def mi():
return map(int, input().split())
'''
5 7
.......
.#####.
.#.#.#.
.#####.
.......
'''
n,m = mi()
a = [0]*n
b = [0]*n
for i in range(n):
a[i] = list(input())
b[i] = a[i].copy()
for i in range(n-2):
for j in range(m-2):
if a[i][j]=='#' and a[i+1][j]=='#' and a[i+2][j]=='#' and a[i+2][j+1]=='#' and a[i+2][j+2]=='#' and a[i+1][j+2]=='#' and a[i][j+2]=='#' and a[i][j+1]=='#':
b[i][j]=b[i+1][j]=b[i+2][j]=b[i+2][j+1]=b[i+2][j+2]=b[i+1][j+2]=b[i][j+2]=b[i][j+1]='.'
for i in range(n):
for j in range(m):
if b[i][j]=='#':
print ('NO')
exit(0)
print ('YES')
``` | output | 1 | 36,019 | 23 | 72,039 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Andrey has been skipping physical education lessons for the whole term, and now he must somehow get a passing grade on this subject. Obviously, it is impossible to do this by legal means, but Andrey doesn't give up. Having obtained an empty certificate from a local hospital, he is going to use his knowledge of local doctor's handwriting to make a counterfeit certificate of illness. However, after writing most of the certificate, Andrey suddenly discovered that doctor's signature is impossible to forge. Or is it?
For simplicity, the signature is represented as an n× m grid, where every cell is either filled with ink or empty. Andrey's pen can fill a 3×3 square without its central cell if it is completely contained inside the grid, as shown below.
xxx
x.x
xxx
Determine whether is it possible to forge the signature on an empty n× m grid.
Input
The first line of input contains two integers n and m (3 ≤ n, m ≤ 1000).
Then n lines follow, each contains m characters. Each of the characters is either '.', representing an empty cell, or '#', representing an ink filled cell.
Output
If Andrey can forge the signature, output "YES". Otherwise output "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3 3
###
#.#
###
Output
YES
Input
3 3
###
###
###
Output
NO
Input
4 3
###
###
###
###
Output
YES
Input
5 7
.......
.#####.
.#.#.#.
.#####.
.......
Output
YES
Note
In the first sample Andrey can paint the border of the square with the center in (2, 2).
In the second sample the signature is impossible to forge.
In the third sample Andrey can paint the borders of the squares with the centers in (2, 2) and (3, 2):
1. we have a clear paper:
...
...
...
...
2. use the pen with center at (2, 2).
###
#.#
###
...
3. use the pen with center at (3, 2).
###
###
###
###
In the fourth sample Andrey can paint the borders of the squares with the centers in (3, 3) and (3, 5). | instruction | 0 | 36,020 | 23 | 72,040 |
Tags: implementation
Correct Solution:
```
N, M = map(int, input().split())
grid = []
for _ in range(N):
grid.append(list(input()))
def check(grid, i, j, sx, sy):
if i - sx >= 0 and j - sy >= 0 and i + 2 - sx < N and j + 2 - sy < M:
i -= sx
j -= sy
v = grid[i][j] == '#' and grid[i+1][j] == '#' and grid[i+2][j] == '#' and grid[i][j+1] == '#' and grid[i+2][j+1] == '#' and grid[i][j+2] == '#' and grid[i+1][j+2] == '#' and grid[i+2][j+2] == '#'
return v
return False
prev = False
for m in range(M):
for n in range(N):
if grid[n][m] == '#':
if not (check(grid, n, m, 0, 0) or check(grid, n, m, 1, 0) or check(grid, n, m, 2, 0) or check(grid, n, m, 0, 1) or check(grid, n, m, 2, 1) or check(grid, n, m, 0, 2) or check(grid, n, m, 1, 2) or check(grid, n, m, 2, 2)):
print("NO")
exit(0)
print("YES")
``` | output | 1 | 36,020 | 23 | 72,041 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Student Andrey has been skipping physical education lessons for the whole term, and now he must somehow get a passing grade on this subject. Obviously, it is impossible to do this by legal means, but Andrey doesn't give up. Having obtained an empty certificate from a local hospital, he is going to use his knowledge of local doctor's handwriting to make a counterfeit certificate of illness. However, after writing most of the certificate, Andrey suddenly discovered that doctor's signature is impossible to forge. Or is it?
For simplicity, the signature is represented as an n× m grid, where every cell is either filled with ink or empty. Andrey's pen can fill a 3×3 square without its central cell if it is completely contained inside the grid, as shown below.
xxx
x.x
xxx
Determine whether is it possible to forge the signature on an empty n× m grid.
Input
The first line of input contains two integers n and m (3 ≤ n, m ≤ 1000).
Then n lines follow, each contains m characters. Each of the characters is either '.', representing an empty cell, or '#', representing an ink filled cell.
Output
If Andrey can forge the signature, output "YES". Otherwise output "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3 3
###
#.#
###
Output
YES
Input
3 3
###
###
###
Output
NO
Input
4 3
###
###
###
###
Output
YES
Input
5 7
.......
.#####.
.#.#.#.
.#####.
.......
Output
YES
Note
In the first sample Andrey can paint the border of the square with the center in (2, 2).
In the second sample the signature is impossible to forge.
In the third sample Andrey can paint the borders of the squares with the centers in (2, 2) and (3, 2):
1. we have a clear paper:
...
...
...
...
2. use the pen with center at (2, 2).
###
#.#
###
...
3. use the pen with center at (3, 2).
###
###
###
###
In the fourth sample Andrey can paint the borders of the squares with the centers in (3, 3) and (3, 5). | instruction | 0 | 36,021 | 23 | 72,042 |
Tags: implementation
Correct Solution:
```
n,m=map(int,input().split())
a=[[*input()]for _ in range(n)]
b=[['.']*m for i in range(n)]
#print(b)
p=[(0,0),(0,1),(0,2),(1,0),(1,2),(2,0),(2,1),(2,2)]
for i in range(n-2):
for j in range(m-2):
if all(a[i+x][j+y]=='#' for x,y in p):
#print('YES')
for x,y in p:
b[i+x][y+j]='#'
if a==b:
print('YES')
else:
print('NO')
``` | output | 1 | 36,021 | 23 | 72,043 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Student Andrey has been skipping physical education lessons for the whole term, and now he must somehow get a passing grade on this subject. Obviously, it is impossible to do this by legal means, but Andrey doesn't give up. Having obtained an empty certificate from a local hospital, he is going to use his knowledge of local doctor's handwriting to make a counterfeit certificate of illness. However, after writing most of the certificate, Andrey suddenly discovered that doctor's signature is impossible to forge. Or is it?
For simplicity, the signature is represented as an n× m grid, where every cell is either filled with ink or empty. Andrey's pen can fill a 3×3 square without its central cell if it is completely contained inside the grid, as shown below.
xxx
x.x
xxx
Determine whether is it possible to forge the signature on an empty n× m grid.
Input
The first line of input contains two integers n and m (3 ≤ n, m ≤ 1000).
Then n lines follow, each contains m characters. Each of the characters is either '.', representing an empty cell, or '#', representing an ink filled cell.
Output
If Andrey can forge the signature, output "YES". Otherwise output "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3 3
###
#.#
###
Output
YES
Input
3 3
###
###
###
Output
NO
Input
4 3
###
###
###
###
Output
YES
Input
5 7
.......
.#####.
.#.#.#.
.#####.
.......
Output
YES
Note
In the first sample Andrey can paint the border of the square with the center in (2, 2).
In the second sample the signature is impossible to forge.
In the third sample Andrey can paint the borders of the squares with the centers in (2, 2) and (3, 2):
1. we have a clear paper:
...
...
...
...
2. use the pen with center at (2, 2).
###
#.#
###
...
3. use the pen with center at (3, 2).
###
###
###
###
In the fourth sample Andrey can paint the borders of the squares with the centers in (3, 3) and (3, 5).
Submitted Solution:
```
n,m = map(int,input().split())
mat = []
cnt = 0
for i in range(n):
s = input()
cnt += s.count("#")
mat.append(s)
tmat = []
for i in range(n):
o = []
for j in range(m):
o.append(".")
tmat.append(o)
for i in range(n):
for j in range(m):
l = []
for e1 in range(i-1,i+2):
for e2 in range(j-1,j+2):
# print(e1,e2)
if e1 > -1 and e1 < n and e2 > -1 and e2 < m:
# print(i,j,"lo")
if e1 == i and e2 == j:
continue
l.append((e1,e2))
if len(l) < 8:
continue
# print("HI")
flag = 1
for x in l:
if mat[x[0]][x[1]] == ".":
flag = 0
break
if flag:
for x in l:
tmat[x[0]][x[1]] = "#"
res = []
# print(tmat)
for x in tmat:
res.append("".join(x))
# print(res)
if res == mat:
print("YES")
else:
print("NO")
``` | instruction | 0 | 36,022 | 23 | 72,044 |
Yes | output | 1 | 36,022 | 23 | 72,045 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Student Andrey has been skipping physical education lessons for the whole term, and now he must somehow get a passing grade on this subject. Obviously, it is impossible to do this by legal means, but Andrey doesn't give up. Having obtained an empty certificate from a local hospital, he is going to use his knowledge of local doctor's handwriting to make a counterfeit certificate of illness. However, after writing most of the certificate, Andrey suddenly discovered that doctor's signature is impossible to forge. Or is it?
For simplicity, the signature is represented as an n× m grid, where every cell is either filled with ink or empty. Andrey's pen can fill a 3×3 square without its central cell if it is completely contained inside the grid, as shown below.
xxx
x.x
xxx
Determine whether is it possible to forge the signature on an empty n× m grid.
Input
The first line of input contains two integers n and m (3 ≤ n, m ≤ 1000).
Then n lines follow, each contains m characters. Each of the characters is either '.', representing an empty cell, or '#', representing an ink filled cell.
Output
If Andrey can forge the signature, output "YES". Otherwise output "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3 3
###
#.#
###
Output
YES
Input
3 3
###
###
###
Output
NO
Input
4 3
###
###
###
###
Output
YES
Input
5 7
.......
.#####.
.#.#.#.
.#####.
.......
Output
YES
Note
In the first sample Andrey can paint the border of the square with the center in (2, 2).
In the second sample the signature is impossible to forge.
In the third sample Andrey can paint the borders of the squares with the centers in (2, 2) and (3, 2):
1. we have a clear paper:
...
...
...
...
2. use the pen with center at (2, 2).
###
#.#
###
...
3. use the pen with center at (3, 2).
###
###
###
###
In the fourth sample Andrey can paint the borders of the squares with the centers in (3, 3) and (3, 5).
Submitted Solution:
```
ss = []
visited = []
n, m = list(map(int, input().split()))
flag = True
ss.append("."*(m+4))
ss.append("."*(m+4))
visited.append([1]*(m+4))
visited.append([1]*(m+4))
for i in range(n):
s = input()
s = ".." + s + ".."
ss.append(s)
visited.append([1,1] + [0] * m + [1,1])
ss.append("."*(m+4))
ss.append("."*(m+4))
visited.append([1]*(m+4))
visited.append([1]*(m+4))
for i in range(n+2):
if not flag:
break
for j in range(m+2):
#print(ss[i][j:j+3] == "###")
if ss[i][j:j+3] == "###" and ss[i+1][j] =="#" and ss[i+1][j+2] =="#" and ss[i+2][j:j+3] == "###":
visited[i][j:j+3] = [1,1,1]
if ss[i+1][j+1] ==".":
visited[i+1][j+1] = 1
visited[i+1][j] = 1
visited[i+1][j+2] = 1
visited[i+2][j:j+3] = [1,1,1]
#print( visited[i][j:j+3])
if ss[i][j] == '#' and not visited[i][j]:
flag = False
if not flag:
print("NO")
else:
print("YES")
``` | instruction | 0 | 36,023 | 23 | 72,046 |
Yes | output | 1 | 36,023 | 23 | 72,047 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Student Andrey has been skipping physical education lessons for the whole term, and now he must somehow get a passing grade on this subject. Obviously, it is impossible to do this by legal means, but Andrey doesn't give up. Having obtained an empty certificate from a local hospital, he is going to use his knowledge of local doctor's handwriting to make a counterfeit certificate of illness. However, after writing most of the certificate, Andrey suddenly discovered that doctor's signature is impossible to forge. Or is it?
For simplicity, the signature is represented as an n× m grid, where every cell is either filled with ink or empty. Andrey's pen can fill a 3×3 square without its central cell if it is completely contained inside the grid, as shown below.
xxx
x.x
xxx
Determine whether is it possible to forge the signature on an empty n× m grid.
Input
The first line of input contains two integers n and m (3 ≤ n, m ≤ 1000).
Then n lines follow, each contains m characters. Each of the characters is either '.', representing an empty cell, or '#', representing an ink filled cell.
Output
If Andrey can forge the signature, output "YES". Otherwise output "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3 3
###
#.#
###
Output
YES
Input
3 3
###
###
###
Output
NO
Input
4 3
###
###
###
###
Output
YES
Input
5 7
.......
.#####.
.#.#.#.
.#####.
.......
Output
YES
Note
In the first sample Andrey can paint the border of the square with the center in (2, 2).
In the second sample the signature is impossible to forge.
In the third sample Andrey can paint the borders of the squares with the centers in (2, 2) and (3, 2):
1. we have a clear paper:
...
...
...
...
2. use the pen with center at (2, 2).
###
#.#
###
...
3. use the pen with center at (3, 2).
###
###
###
###
In the fourth sample Andrey can paint the borders of the squares with the centers in (3, 3) and (3, 5).
Submitted Solution:
```
a=list(map(int,input().split()))
b=[]
c=[]
d=[]
for i in range(a[0]):b.append(list(input()))
for i in range(a[0]):
for j in range(a[1]):
if b[i][j]=="#":c.append("b["+str(i)+"]["+str(j)+"]")
for i in range(a[0]-2):
for j in range(a[1]-2):
if b[i][j]=="#":
if b[i][j+1]=="#":
if b[i][j+2]=="#":
if b[i+1][j]=="#":
if b[i+1][j+2]=="#":
if b[i+2][j]=="#":
if b[i+2][j+1]=="#":
if b[i+2][j+2]=="#":
d.append("b["+str(i)+"]["+str(j)+"]")
d.append("b["+str(i)+"]["+str(j+1)+"]")
d.append("b["+str(i)+"]["+str(j+2)+"]")
d.append("b["+str(i+1)+"]["+str(j)+"]")
d.append("b["+str(i+1)+"]["+str(j+2)+"]")
d.append("b["+str(i+2)+"]["+str(j)+"]")
d.append("b["+str(i+2)+"]["+str(j+1)+"]")
d.append("b["+str(i+2)+"]["+str(j+2)+"]")
if set(c)==set(d):print("YES")
else:print("NO")
``` | instruction | 0 | 36,024 | 23 | 72,048 |
Yes | output | 1 | 36,024 | 23 | 72,049 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Student Andrey has been skipping physical education lessons for the whole term, and now he must somehow get a passing grade on this subject. Obviously, it is impossible to do this by legal means, but Andrey doesn't give up. Having obtained an empty certificate from a local hospital, he is going to use his knowledge of local doctor's handwriting to make a counterfeit certificate of illness. However, after writing most of the certificate, Andrey suddenly discovered that doctor's signature is impossible to forge. Or is it?
For simplicity, the signature is represented as an n× m grid, where every cell is either filled with ink or empty. Andrey's pen can fill a 3×3 square without its central cell if it is completely contained inside the grid, as shown below.
xxx
x.x
xxx
Determine whether is it possible to forge the signature on an empty n× m grid.
Input
The first line of input contains two integers n and m (3 ≤ n, m ≤ 1000).
Then n lines follow, each contains m characters. Each of the characters is either '.', representing an empty cell, or '#', representing an ink filled cell.
Output
If Andrey can forge the signature, output "YES". Otherwise output "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3 3
###
#.#
###
Output
YES
Input
3 3
###
###
###
Output
NO
Input
4 3
###
###
###
###
Output
YES
Input
5 7
.......
.#####.
.#.#.#.
.#####.
.......
Output
YES
Note
In the first sample Andrey can paint the border of the square with the center in (2, 2).
In the second sample the signature is impossible to forge.
In the third sample Andrey can paint the borders of the squares with the centers in (2, 2) and (3, 2):
1. we have a clear paper:
...
...
...
...
2. use the pen with center at (2, 2).
###
#.#
###
...
3. use the pen with center at (3, 2).
###
###
###
###
In the fourth sample Andrey can paint the borders of the squares with the centers in (3, 3) and (3, 5).
Submitted Solution:
```
n, m = [int(i) for i in input().split()]
A = []
ct = []
for i in range(n):
x = list(input())
y = [0]*m
A.append(x)
ct.append(y)
ok = 1
for i in range(n-2):
for j in range(m-2):
if A[i][j]=='#' and A[i][j+1]=='#' and A[i][j+2]=='#' and A[i+1][j]=='#' and A[i+2][j]=='#' and A[i+2][j+1]=='#' and A[i+2][j+2]=='#' and A[i+1][j+2]=='#':
ct[i][j] = 1
ct[i][j+1] = 1
ct[i][j+2] = 1
ct[i+1][j] = 1
ct[i+1][j+2] = 1
ct[i+2][j] = 1
ct[i+2][j+1] = 1
ct[i+2][j+2] = 1
xct = 0
xhs = 0
for i in range(len(ct)):
for j in range(len(ct[i])):
if ct[i][j] == 1:
xct+=1
if A[i][j] == '#':
xhs+=1
if xhs==xct:
print('YES')
else:
print('NO')
``` | instruction | 0 | 36,025 | 23 | 72,050 |
Yes | output | 1 | 36,025 | 23 | 72,051 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Student Andrey has been skipping physical education lessons for the whole term, and now he must somehow get a passing grade on this subject. Obviously, it is impossible to do this by legal means, but Andrey doesn't give up. Having obtained an empty certificate from a local hospital, he is going to use his knowledge of local doctor's handwriting to make a counterfeit certificate of illness. However, after writing most of the certificate, Andrey suddenly discovered that doctor's signature is impossible to forge. Or is it?
For simplicity, the signature is represented as an n× m grid, where every cell is either filled with ink or empty. Andrey's pen can fill a 3×3 square without its central cell if it is completely contained inside the grid, as shown below.
xxx
x.x
xxx
Determine whether is it possible to forge the signature on an empty n× m grid.
Input
The first line of input contains two integers n and m (3 ≤ n, m ≤ 1000).
Then n lines follow, each contains m characters. Each of the characters is either '.', representing an empty cell, or '#', representing an ink filled cell.
Output
If Andrey can forge the signature, output "YES". Otherwise output "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3 3
###
#.#
###
Output
YES
Input
3 3
###
###
###
Output
NO
Input
4 3
###
###
###
###
Output
YES
Input
5 7
.......
.#####.
.#.#.#.
.#####.
.......
Output
YES
Note
In the first sample Andrey can paint the border of the square with the center in (2, 2).
In the second sample the signature is impossible to forge.
In the third sample Andrey can paint the borders of the squares with the centers in (2, 2) and (3, 2):
1. we have a clear paper:
...
...
...
...
2. use the pen with center at (2, 2).
###
#.#
###
...
3. use the pen with center at (3, 2).
###
###
###
###
In the fourth sample Andrey can paint the borders of the squares with the centers in (3, 3) and (3, 5).
Submitted Solution:
```
n,m=input().split()
n=int(n)
m=int(m)
x=False
if n==3 and m==3:
for i in range(n):
a=input()
if i==1 and a[1]==".":
x=True
else:
x=True
for i in range(n):
a=input()
if x:
print("YES")
else:
print("NO")
``` | instruction | 0 | 36,026 | 23 | 72,052 |
No | output | 1 | 36,026 | 23 | 72,053 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Student Andrey has been skipping physical education lessons for the whole term, and now he must somehow get a passing grade on this subject. Obviously, it is impossible to do this by legal means, but Andrey doesn't give up. Having obtained an empty certificate from a local hospital, he is going to use his knowledge of local doctor's handwriting to make a counterfeit certificate of illness. However, after writing most of the certificate, Andrey suddenly discovered that doctor's signature is impossible to forge. Or is it?
For simplicity, the signature is represented as an n× m grid, where every cell is either filled with ink or empty. Andrey's pen can fill a 3×3 square without its central cell if it is completely contained inside the grid, as shown below.
xxx
x.x
xxx
Determine whether is it possible to forge the signature on an empty n× m grid.
Input
The first line of input contains two integers n and m (3 ≤ n, m ≤ 1000).
Then n lines follow, each contains m characters. Each of the characters is either '.', representing an empty cell, or '#', representing an ink filled cell.
Output
If Andrey can forge the signature, output "YES". Otherwise output "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3 3
###
#.#
###
Output
YES
Input
3 3
###
###
###
Output
NO
Input
4 3
###
###
###
###
Output
YES
Input
5 7
.......
.#####.
.#.#.#.
.#####.
.......
Output
YES
Note
In the first sample Andrey can paint the border of the square with the center in (2, 2).
In the second sample the signature is impossible to forge.
In the third sample Andrey can paint the borders of the squares with the centers in (2, 2) and (3, 2):
1. we have a clear paper:
...
...
...
...
2. use the pen with center at (2, 2).
###
#.#
###
...
3. use the pen with center at (3, 2).
###
###
###
###
In the fourth sample Andrey can paint the borders of the squares with the centers in (3, 3) and (3, 5).
Submitted Solution:
```
import sys
fil=sys.stdin
def trytype2(i,j):
if i+2>=n or j+1>=m or j-1<0:
return False
if s[i+1][j-1]==".":
return False
if s[i+2][j-1]==".":
return False
if s[i][j+1]==".":
return False
if s[i][j-1]==".":
return False
if s[i+1][j+1]==".":
return False
if s[i+2][j+1]==".":
return False
if s[i+2][j-1]==".":
return False
return True
def trytype3(i,j):
if i+2>=n or j-2<0:
return False
if s[i][j-1]==".":
return False
if s[i][j-1]==".":
return False
if s[i+1][j]==".":
return False
if s[i+1][j-2]==".":
return False
if s[i+2][j]==".":
return False
if s[i+2][j-1]==".":
return False
if s[i+2][j-2]==".":
return False
return True
n,m=map(int,fil.readline().rstrip('\r\n').split())
s=[]
for i in range(n):
tmp=list(fil.readline().rstrip('\r\n'))
s.append(tmp)
f=0
for i in range(n):
for j in range(m):
f=0
if s[i][j]=='#':
if i+2>=n or j+2>=m:
f=1
if f==0 and s[i+1][j]==".":
f=1
if f==0 and s[i+2][j]==".":
f=1
if f==0 and s[i][j+1]==".":
f=1
if f==0 and s[i][j+2]==".":
f=1
if f==0 and s[i+1][j+2]==".":
f=1
if f==0 and s[i+2][j+1]==".":
f=1
if f==0 and s[i+2][j+2]==".":
f=1
if f==0:
s[i][j]='$'
s[i+1][j]='$'
s[i+2][j]='$'
s[i][j+1]='$'
s[i][j+2]='$'
s[i+1][j+2]='$'
s[i+2][j+1]='$'
s[i+2][j+2]='$'
else:
if(trytype2(i,j)):
f=0
s[i][j]='$'
s[i+2][j]='$'
s[i][j+1]='$'
s[i][j-1]='$'
s[i+1][j+1]='$'
s[i+1][j-1]='$'
s[i+2][j+1]='$'
s[i+2][j-1]='$'
elif(trytype3(i,j)):
f=0
s[i][j]='$'
s[i+1][j]='$'
s[i+2][j]='$'
s[i][j-1]='$'
s[i][j-2]='$'
s[i+1][j-2]='$'
s[i+2][j-1]='$'
s[i+2][j-2]='$'
if f==1:
break
if f==0:
z=0
for i in range(n):
for j in range(m):
if s[i][j]=='#':
z=1
break
if z==1:
break
if z==0:
print("YES")
else:
print("NO")
else:
print("NO")
``` | instruction | 0 | 36,027 | 23 | 72,054 |
No | output | 1 | 36,027 | 23 | 72,055 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Student Andrey has been skipping physical education lessons for the whole term, and now he must somehow get a passing grade on this subject. Obviously, it is impossible to do this by legal means, but Andrey doesn't give up. Having obtained an empty certificate from a local hospital, he is going to use his knowledge of local doctor's handwriting to make a counterfeit certificate of illness. However, after writing most of the certificate, Andrey suddenly discovered that doctor's signature is impossible to forge. Or is it?
For simplicity, the signature is represented as an n× m grid, where every cell is either filled with ink or empty. Andrey's pen can fill a 3×3 square without its central cell if it is completely contained inside the grid, as shown below.
xxx
x.x
xxx
Determine whether is it possible to forge the signature on an empty n× m grid.
Input
The first line of input contains two integers n and m (3 ≤ n, m ≤ 1000).
Then n lines follow, each contains m characters. Each of the characters is either '.', representing an empty cell, or '#', representing an ink filled cell.
Output
If Andrey can forge the signature, output "YES". Otherwise output "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3 3
###
#.#
###
Output
YES
Input
3 3
###
###
###
Output
NO
Input
4 3
###
###
###
###
Output
YES
Input
5 7
.......
.#####.
.#.#.#.
.#####.
.......
Output
YES
Note
In the first sample Andrey can paint the border of the square with the center in (2, 2).
In the second sample the signature is impossible to forge.
In the third sample Andrey can paint the borders of the squares with the centers in (2, 2) and (3, 2):
1. we have a clear paper:
...
...
...
...
2. use the pen with center at (2, 2).
###
#.#
###
...
3. use the pen with center at (3, 2).
###
###
###
###
In the fourth sample Andrey can paint the borders of the squares with the centers in (3, 3) and (3, 5).
Submitted Solution:
```
from collections import Counter,defaultdict,deque
import sys
sys.setrecursionlimit(1000000)
read = lambda: list(map(int,input().split()))
getinfo = lambda grid: print(list(map(print,grid)))
mod = 10**9 + 7
inf = float('inf')
dx = [-1, 0, 1]
dy = [-1, 0, 1]
def checkpoint(i,j):
for xx in dx:
for yy in dy:
if xx == 0 and yy == 0: continue
x, y = i + xx, j + yy
if 0<=x<n and 0<=y<m:
if grid[x][y] == '.': return False
for xx in dx:
for yy in dy:
x, y = i + xx, j + yy
if 0<=x<n and 0<=y<m:
if grid[x][y] == '#':
left.discard((x,y))
return True
while True:
try:
n,m = read()
grid = []
left = set()
for _ in range(n): grid.append(list(input()))
for i in range(n):
for j in range(m):
if grid[i][j] == '#':
left.add((i,j))
cnt = len(left)
for i in range(n):
for j in range(m):
if grid[i][j] == '.': checkpoint(i,j)
# print(left)
if len(left) == 0 or (len(left) == cnt and (n>3 or m>3)):
print('YES')
else:
print('NO')
except:
break
``` | instruction | 0 | 36,028 | 23 | 72,056 |
No | output | 1 | 36,028 | 23 | 72,057 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Student Andrey has been skipping physical education lessons for the whole term, and now he must somehow get a passing grade on this subject. Obviously, it is impossible to do this by legal means, but Andrey doesn't give up. Having obtained an empty certificate from a local hospital, he is going to use his knowledge of local doctor's handwriting to make a counterfeit certificate of illness. However, after writing most of the certificate, Andrey suddenly discovered that doctor's signature is impossible to forge. Or is it?
For simplicity, the signature is represented as an n× m grid, where every cell is either filled with ink or empty. Andrey's pen can fill a 3×3 square without its central cell if it is completely contained inside the grid, as shown below.
xxx
x.x
xxx
Determine whether is it possible to forge the signature on an empty n× m grid.
Input
The first line of input contains two integers n and m (3 ≤ n, m ≤ 1000).
Then n lines follow, each contains m characters. Each of the characters is either '.', representing an empty cell, or '#', representing an ink filled cell.
Output
If Andrey can forge the signature, output "YES". Otherwise output "NO".
You can print each letter in any case (upper or lower).
Examples
Input
3 3
###
#.#
###
Output
YES
Input
3 3
###
###
###
Output
NO
Input
4 3
###
###
###
###
Output
YES
Input
5 7
.......
.#####.
.#.#.#.
.#####.
.......
Output
YES
Note
In the first sample Andrey can paint the border of the square with the center in (2, 2).
In the second sample the signature is impossible to forge.
In the third sample Andrey can paint the borders of the squares with the centers in (2, 2) and (3, 2):
1. we have a clear paper:
...
...
...
...
2. use the pen with center at (2, 2).
###
#.#
###
...
3. use the pen with center at (3, 2).
###
###
###
###
In the fourth sample Andrey can paint the borders of the squares with the centers in (3, 3) and (3, 5).
Submitted Solution:
```
n, m = map(int,input().split())
mat = []
for r in range(n):
mat.append(str(input()))
rb = True
for r in range(1,n-1):
for c in range(1,m-1):
if mat[r][c] == '#':
if mat[r-1][c] == '#' and mat[r-1][c-1] == '#' and mat[r-1][c+1] and\
mat[r][c-1] == '#' and mat[r][c+1] and \
mat[r+1][c] == '#' and mat[r+1][c-1] == '#' and mat[r+1][c+1]:
rb = False
print("NO")
break
if rb != False:
print("YES")
``` | instruction | 0 | 36,029 | 23 | 72,058 |
No | output | 1 | 36,029 | 23 | 72,059 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is constraints.
You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [l_i; r_i] (l_i ≤ r_i) and it covers all integer points j such that l_i ≤ j ≤ r_i.
The integer point is called bad if it is covered by strictly more than k segments.
Your task is to remove the minimum number of segments so that there are no bad points at all.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of segments and the maximum number of segments by which each integer point can be covered.
The next n lines contain segments. The i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 2 ⋅ 10^5) — the endpoints of the i-th segment.
Output
In the first line print one integer m (0 ≤ m ≤ n) — the minimum number of segments you need to remove so that there are no bad points.
In the second line print m distinct integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ n) — indices of segments you remove in any order. If there are multiple answers, you can print any of them.
Examples
Input
7 2
11 11
9 11
7 8
8 9
7 8
9 11
7 9
Output
3
4 6 7
Input
5 1
29 30
30 30
29 29
28 30
30 30
Output
3
1 4 5
Input
6 1
2 3
3 3
2 3
2 2
2 3
2 3
Output
4
1 3 5 6 | instruction | 0 | 36,158 | 23 | 72,316 |
Tags: data structures, greedy, sortings
Correct Solution:
```
import sys
input = sys.stdin.readline
n,k=map(int,input().split())
S=[tuple(map(int,input().split()))+(i+1,) for i in range(n)]
S.sort()
segtemp=2*10**5
seg_el=1<<((segtemp).bit_length())# Segment treeの台の要素数
SEG=[0]*(2*seg_el)# 1-indexedなので、要素数2*seg_el.Segment treeの初期値で初期化
def getvalue(n,seg_el):# 一点の値を取得
i=n+seg_el
ANS=0
ANS+=SEG[i]
i>>=1# 子ノードへ
while i!=0:
ANS+=SEG[i]
i>>=1
return ANS
def updates(l,r,x):# 区間[l,r)のminを更新.
L=l+seg_el
R=r+seg_el
while L<R:
if L & 1:
SEG[L]+=x
L+=1
if R & 1:
R-=1
SEG[R]+=x
L>>=1
R>>=1
ind=0
SH=[]
ANS=[]
import heapq
for point in range(segtemp):
while ind<n and S[ind][0]<=point:
l,r,x=S[ind]
updates(l,r+1,1)
ind+=1
heapq.heappush(SH,(-r,l,x))
#print(getvalue(point,seg_el),SH)
while getvalue(point,seg_el)>k:
r,l,x=heapq.heappop(SH)
r=-r
ANS.append(x)
updates(l,r+1,-1)
#print(point,ANS,getvalue(point,seg_el))
print(len(ANS))
print(*ANS)
``` | output | 1 | 36,158 | 23 | 72,317 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is constraints.
You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [l_i; r_i] (l_i ≤ r_i) and it covers all integer points j such that l_i ≤ j ≤ r_i.
The integer point is called bad if it is covered by strictly more than k segments.
Your task is to remove the minimum number of segments so that there are no bad points at all.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of segments and the maximum number of segments by which each integer point can be covered.
The next n lines contain segments. The i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 2 ⋅ 10^5) — the endpoints of the i-th segment.
Output
In the first line print one integer m (0 ≤ m ≤ n) — the minimum number of segments you need to remove so that there are no bad points.
In the second line print m distinct integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ n) — indices of segments you remove in any order. If there are multiple answers, you can print any of them.
Examples
Input
7 2
11 11
9 11
7 8
8 9
7 8
9 11
7 9
Output
3
4 6 7
Input
5 1
29 30
30 30
29 29
28 30
30 30
Output
3
1 4 5
Input
6 1
2 3
3 3
2 3
2 2
2 3
2 3
Output
4
1 3 5 6 | instruction | 0 | 36,160 | 23 | 72,320 |
Tags: data structures, greedy, sortings
Correct Solution:
```
'''
template author-: Pyduper
'''
import sys
# stdin = open("testdata.txt", "r")
# ip = stdin
# def input():
# return ip.readline().strip()
def input():
return sys.stdin.readline().strip()
import heapq
maxn = 200005
def lowbit(x):
return x&-x
def add(t,i,v):
while i<len(t):
t[i]+=v
i += lowbit(i)
def sum(t,i):
ans = 0
while i>0:
ans += t[i]
i -= lowbit(i)
return ans
trees = [0]*maxn
n,k = map(int,input().split(" "))
seg = []
points = [0]*maxn
cand = []
for i in range(n):
l,r = map(int,input().split(" "))
seg.append((l,r,i+1))
points[l] += 1
points[r+1] -= 1
st = 0
for i in range(maxn):
st += points[i]
if st > k:
cand.append((i,st-k))
seg.sort(key = lambda x:(x[0],x[1]))
pq = []
j = 0
ans = []
for i,v in cand:
v = v-sum(trees,i)
if v <= 0:
continue
while j<n and seg[j][0] <= i:
heapq.heappush(pq,(-seg[j][1],seg[j][0],seg[j][2]))
j += 1
for t in range(v):
r,l,idx = heapq.heappop(pq)
ans.append(idx)
add(trees,l,1)
add(trees,-r+1,-1)
print(len(ans))
print(*ans)
``` | output | 1 | 36,160 | 23 | 72,321 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is constraints.
You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [l_i; r_i] (l_i ≤ r_i) and it covers all integer points j such that l_i ≤ j ≤ r_i.
The integer point is called bad if it is covered by strictly more than k segments.
Your task is to remove the minimum number of segments so that there are no bad points at all.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of segments and the maximum number of segments by which each integer point can be covered.
The next n lines contain segments. The i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 2 ⋅ 10^5) — the endpoints of the i-th segment.
Output
In the first line print one integer m (0 ≤ m ≤ n) — the minimum number of segments you need to remove so that there are no bad points.
In the second line print m distinct integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ n) — indices of segments you remove in any order. If there are multiple answers, you can print any of them.
Examples
Input
7 2
11 11
9 11
7 8
8 9
7 8
9 11
7 9
Output
3
4 6 7
Input
5 1
29 30
30 30
29 29
28 30
30 30
Output
3
1 4 5
Input
6 1
2 3
3 3
2 3
2 2
2 3
2 3
Output
4
1 3 5 6 | instruction | 0 | 36,161 | 23 | 72,322 |
Tags: data structures, greedy, sortings
Correct Solution:
```
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
import sys
from io import BytesIO, IOBase
class SortedList:
def __init__(self, iterable=None, _load=200):
"""Initialize sorted list instance."""
if iterable is None:
iterable = []
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 main():
n,k=map(int,input().split())
a,ma=[],0
for i in range(n):
l,r=map(int,input().split())
a.append((l,r,i))
ma=max(ma,r)
a.sort(key=lambda x:x[0])
b,d=[0]*(ma+2),SortedList()
for i in a:
b[i[0]]+=1
b[i[1]+1]-=1
for i in range(1,ma+2):
b[i]+=b[i-1]
ans,c,j=[],[0]*(ma+2),0
for i in range(1,ma+1):
while j<n and a[j][0]<=i:
d.add((a[j][1],a[j][0],a[j][2]))
j+=1
while d and d[0][0]<i:
d.discard(d[0])
c[i]+=c[i-1]
if c[i]+b[i]>k:
z=c[i]+b[i]-k
c[i]-=z
while z:
y=d[-1]
d.discard(d[-1])
c[y[0]+1]+=1
ans.append(y[-1]+1)
z-=1
print(len(ans))
print(*ans)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | output | 1 | 36,161 | 23 | 72,323 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is constraints.
You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [l_i; r_i] (l_i ≤ r_i) and it covers all integer points j such that l_i ≤ j ≤ r_i.
The integer point is called bad if it is covered by strictly more than k segments.
Your task is to remove the minimum number of segments so that there are no bad points at all.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of segments and the maximum number of segments by which each integer point can be covered.
The next n lines contain segments. The i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 2 ⋅ 10^5) — the endpoints of the i-th segment.
Output
In the first line print one integer m (0 ≤ m ≤ n) — the minimum number of segments you need to remove so that there are no bad points.
In the second line print m distinct integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ n) — indices of segments you remove in any order. If there are multiple answers, you can print any of them.
Examples
Input
7 2
11 11
9 11
7 8
8 9
7 8
9 11
7 9
Output
3
4 6 7
Input
5 1
29 30
30 30
29 29
28 30
30 30
Output
3
1 4 5
Input
6 1
2 3
3 3
2 3
2 2
2 3
2 3
Output
4
1 3 5 6 | instruction | 0 | 36,162 | 23 | 72,324 |
Tags: data structures, greedy, sortings
Correct Solution:
```
from sys import stdin,stdout
from math import gcd,sqrt,factorial,pi,inf
from collections import deque,defaultdict
from bisect import bisect,bisect_left
from time import time
from itertools import permutations as per
from heapq import heapify,heappush,heappop,heappushpop
input=stdin.readline
R=lambda:map(int,input().split())
I=lambda:int(input())
S=lambda:input().rstrip('\r\n')
L=lambda:list(R())
P=lambda x:stdout.write(str(x)+'\n')
lcm=lambda x,y:(x*y)//gcd(x,y)
nCr=lambda x,y:(f[x]*inv((f[y]*f[x-y])%N))%N
inv=lambda x:pow(x,N-2,N)
sm=lambda x:(x**2+x)//2
N=10**9+7
n,k=R()
a=[0]*(2*10**5+7)
v=[defaultdict(list) for i in range(2*10**5+7)]
for i in range(n):
x,y=R()
a[y+1]-=1
v[x][y]+=i+1,
p=0
h=[]
ans=[]
ind=defaultdict(list)
for i in range(2*10**5+7):
p+=a[i]
for j in v[i]:
for g in v[i][j]:
ind[j]+=g,
if p<k:
heappush(h,-j)
p+=1
else:
x=-heappushpop(h,-j)
ans+=ind[x].pop(),
a[x+1]+=1
print(len(ans))
print(*ans)
``` | output | 1 | 36,162 | 23 | 72,325 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is constraints.
You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [l_i; r_i] (l_i ≤ r_i) and it covers all integer points j such that l_i ≤ j ≤ r_i.
The integer point is called bad if it is covered by strictly more than k segments.
Your task is to remove the minimum number of segments so that there are no bad points at all.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of segments and the maximum number of segments by which each integer point can be covered.
The next n lines contain segments. The i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 2 ⋅ 10^5) — the endpoints of the i-th segment.
Output
In the first line print one integer m (0 ≤ m ≤ n) — the minimum number of segments you need to remove so that there are no bad points.
In the second line print m distinct integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ n) — indices of segments you remove in any order. If there are multiple answers, you can print any of them.
Examples
Input
7 2
11 11
9 11
7 8
8 9
7 8
9 11
7 9
Output
3
4 6 7
Input
5 1
29 30
30 30
29 29
28 30
30 30
Output
3
1 4 5
Input
6 1
2 3
3 3
2 3
2 2
2 3
2 3
Output
4
1 3 5 6 | instruction | 0 | 36,163 | 23 | 72,326 |
Tags: data structures, greedy, sortings
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
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")
####################################################
import heapq as h
from collections import defaultdict
n,m=map(int,input().split())
d=defaultdict(lambda:[])
dd=defaultdict(lambda :[])
q=(2*10**5)+2
for i in range(n):
l,r=map(int,input().split())
dd[r].append(i+1)
d[l].append([r,i+1])
active=0
heap=[]
visited=[0 for i in range(q)]
var=0
l=[]
for i in range(q):
for k in d[i]:
h.heappush(heap,[-k[0],k[1]])
active+=1
while active>m:
var=h.heappop(heap)
while(visited[var[1]]==1):
var=h.heappop(heap)
visited[var[1]]=1
active-=1
l.append(var[1])
for j in dd[i]:
if(visited[j]==0):
visited[j]=1
active-=1
print(len(l))
print(*l)
``` | output | 1 | 36,163 | 23 | 72,327 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is constraints.
You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [l_i; r_i] (l_i ≤ r_i) and it covers all integer points j such that l_i ≤ j ≤ r_i.
The integer point is called bad if it is covered by strictly more than k segments.
Your task is to remove the minimum number of segments so that there are no bad points at all.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of segments and the maximum number of segments by which each integer point can be covered.
The next n lines contain segments. The i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 2 ⋅ 10^5) — the endpoints of the i-th segment.
Output
In the first line print one integer m (0 ≤ m ≤ n) — the minimum number of segments you need to remove so that there are no bad points.
In the second line print m distinct integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ n) — indices of segments you remove in any order. If there are multiple answers, you can print any of them.
Examples
Input
7 2
11 11
9 11
7 8
8 9
7 8
9 11
7 9
Output
3
4 6 7
Input
5 1
29 30
30 30
29 29
28 30
30 30
Output
3
1 4 5
Input
6 1
2 3
3 3
2 3
2 2
2 3
2 3
Output
4
1 3 5 6 | instruction | 0 | 36,165 | 23 | 72,330 |
Tags: data structures, greedy, sortings
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
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")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**51, func=lambda a, b: a & b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
n,k=map(int,input().split())
l=[0]*(2*10**5+2)
ma=0
rt=[]
for i in range(n):
a,b=map(int,input().split())
rt.append((a,b,i+1))
ma=max(b,ma)
l[a]+=1
l[b+1]-=1
s1=SegmentTree(l)
rt.sort()
t=0
g=[]
heapq.heapify(g)
ans=[]
for i in range(1,ma+1):
cou=s1.query(0,i)
while (t<n and rt[t][0] <= i):
heapq.heappush(g, (-rt[t][1], rt[t][0],rt[t][2]))
t+=1
if t==n:
break
if cou>k:
c=cou-k
for i in range(c):
r,l1,ind=heapq.heappop(g)
ans.append(ind)
r*=-1
l[l1]-=1
l[r+1]+=1
s1.__setitem__(l1,l[l1])
s1.__setitem__(r+1,l[r+1])
print(len(ans))
print(*ans)
``` | output | 1 | 36,165 | 23 | 72,331 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is constraints.
You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [l_i; r_i] (l_i ≤ r_i) and it covers all integer points j such that l_i ≤ j ≤ r_i.
The integer point is called bad if it is covered by strictly more than k segments.
Your task is to remove the minimum number of segments so that there are no bad points at all.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of segments and the maximum number of segments by which each integer point can be covered.
The next n lines contain segments. The i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 2 ⋅ 10^5) — the endpoints of the i-th segment.
Output
In the first line print one integer m (0 ≤ m ≤ n) — the minimum number of segments you need to remove so that there are no bad points.
In the second line print m distinct integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ n) — indices of segments you remove in any order. If there are multiple answers, you can print any of them.
Examples
Input
7 2
11 11
9 11
7 8
8 9
7 8
9 11
7 9
Output
3
4 6 7
Input
5 1
29 30
30 30
29 29
28 30
30 30
Output
3
1 4 5
Input
6 1
2 3
3 3
2 3
2 2
2 3
2 3
Output
4
1 3 5 6
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
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")
##########################################################
#for _ in range(int(input())):
#n = int(input())
import heapq as h
from collections import defaultdict
#arr=list(map(int, input().split()))
n,ma= map(int, input().split())
d=defaultdict(lambda :[])
he=[]
dd=defaultdict(lambda :[])
for i in range(n):
l,r= map(int, input().split())
dd[r].append(i+1)
d[l].append([r,i+1])
l=[]
vis=[0]*(2*10**5+2)
active=0
for i in range(1,2*(10**5)+1):
for k in d[i]:
active+=1
h.heappush(he,[-k[0],k[1]])
while active>ma:
var=h.heappop(he)
while vis[var[1]]==1:
var=h.heappop(he)
vis[var[1]]=1
l.append(var[1])
active-=1
for j in dd[i]:
if vis[j]==0:
vis[j]=1
active-=1
print(len(l))
print(*l)
``` | instruction | 0 | 36,166 | 23 | 72,332 |
Yes | output | 1 | 36,166 | 23 | 72,333 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is constraints.
You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [l_i; r_i] (l_i ≤ r_i) and it covers all integer points j such that l_i ≤ j ≤ r_i.
The integer point is called bad if it is covered by strictly more than k segments.
Your task is to remove the minimum number of segments so that there are no bad points at all.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of segments and the maximum number of segments by which each integer point can be covered.
The next n lines contain segments. The i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 2 ⋅ 10^5) — the endpoints of the i-th segment.
Output
In the first line print one integer m (0 ≤ m ≤ n) — the minimum number of segments you need to remove so that there are no bad points.
In the second line print m distinct integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ n) — indices of segments you remove in any order. If there are multiple answers, you can print any of them.
Examples
Input
7 2
11 11
9 11
7 8
8 9
7 8
9 11
7 9
Output
3
4 6 7
Input
5 1
29 30
30 30
29 29
28 30
30 30
Output
3
1 4 5
Input
6 1
2 3
3 3
2 3
2 2
2 3
2 3
Output
4
1 3 5 6
Submitted Solution:
```
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))
class OrderedList(SortedList): #Codeforces, Ordered Multiset
def __init__(self, arg):
super().__init__(arg)
def rangeCountByValue(self, leftVal, rightVal): #returns number of items in range [leftVal,rightVal] inclusive
leftCummulative = self.bisect_left(leftVal)
rightCummulative = self.bisect_left(rightVal + 1)
return rightCummulative - leftCummulative
def main():
n,k=readIntArr()
lr=[]
for i in range(n):
l,r=readIntArr()
lr.append([l,r,i+1])
lr.sort(key=lambda x:x[0])
storedRandI=OrderedList([]) # [r,i]
ans=[]
cnts=0
for l,r,i in lr:
while storedRandI and storedRandI[0][0]<l:
storedRandI.pop(0)
cnts-=1
storedRandI.add([r,i])
cnts+=1
while cnts>k:
# print('cnts:{} l:{} r:{}'.format(cnts,l,r))
r,i=storedRandI.pop(-1)
cnts-=1
ans.append(i)
# print('l:{} r:{} storedRAndI:{}'.format(l,r,storedRandI))
print(len(ans))
oneLineArrayPrint(ans)
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultVal,dimensionArr): # eg. makeArr(0,[n,m])
dv=defaultVal;da=dimensionArr
if len(da)==1:return [dv for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(x,y):
print('? {} {}'.format(x,y))
sys.stdout.flush()
return int(input())
def answerInteractive(ans):
print('! {}'.format(ans))
sys.stdout.flush()
inf=float('inf')
MOD=10**9+7
# MOD=998244353
for _abc in range(1):
main()
``` | instruction | 0 | 36,167 | 23 | 72,334 |
Yes | output | 1 | 36,167 | 23 | 72,335 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is constraints.
You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [l_i; r_i] (l_i ≤ r_i) and it covers all integer points j such that l_i ≤ j ≤ r_i.
The integer point is called bad if it is covered by strictly more than k segments.
Your task is to remove the minimum number of segments so that there are no bad points at all.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of segments and the maximum number of segments by which each integer point can be covered.
The next n lines contain segments. The i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 2 ⋅ 10^5) — the endpoints of the i-th segment.
Output
In the first line print one integer m (0 ≤ m ≤ n) — the minimum number of segments you need to remove so that there are no bad points.
In the second line print m distinct integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ n) — indices of segments you remove in any order. If there are multiple answers, you can print any of them.
Examples
Input
7 2
11 11
9 11
7 8
8 9
7 8
9 11
7 9
Output
3
4 6 7
Input
5 1
29 30
30 30
29 29
28 30
30 30
Output
3
1 4 5
Input
6 1
2 3
3 3
2 3
2 2
2 3
2 3
Output
4
1 3 5 6
Submitted Solution:
```
# -*- coding: utf-8 -*-
import sys
import bisect
import heapq
line_count = 0
segments = [None]
num_points = 200000
for line in sys.stdin.readlines():
inputs = line.split()
if line_count == 0:
n = int(inputs[0])
k = int(inputs[1])
opening = {}
closing = {}
removed_right = {}
segment_index = 0
for i in range(1, num_points + 1):
opening[i] = []
closing[i] = []
removed_right[i] = 0
else:
l = int(inputs[0])
r = int(inputs[1])
segment_index += 1
segments.append((l, r))
opening[l].append(segment_index)
closing[r].append(segment_index)
if line_count == n:
break
line_count += 1
working = []
working_count = 0
removed = []
for i in range(1, num_points + 1):
for segment_index in opening[i]:
_, r = segments[segment_index]
heapq.heappush(working, (- r, segment_index))
working_count += 1
# bisect.insort_right(working, (r, segment_index))
while working_count > k:
r, segment_index = heapq.heappop(working)
# r, segment_index = working.pop()
working_count -= 1
removed.append(segment_index)
removed_right[- r] += 1
squeezed_out = len(closing[i]) - removed_right[i]
working_count -= squeezed_out
# working = working[squeezed_out: ]
print(len(removed))
for j in removed:
print(j, end = " ")
``` | instruction | 0 | 36,168 | 23 | 72,336 |
Yes | output | 1 | 36,168 | 23 | 72,337 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is constraints.
You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [l_i; r_i] (l_i ≤ r_i) and it covers all integer points j such that l_i ≤ j ≤ r_i.
The integer point is called bad if it is covered by strictly more than k segments.
Your task is to remove the minimum number of segments so that there are no bad points at all.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of segments and the maximum number of segments by which each integer point can be covered.
The next n lines contain segments. The i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 2 ⋅ 10^5) — the endpoints of the i-th segment.
Output
In the first line print one integer m (0 ≤ m ≤ n) — the minimum number of segments you need to remove so that there are no bad points.
In the second line print m distinct integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ n) — indices of segments you remove in any order. If there are multiple answers, you can print any of them.
Examples
Input
7 2
11 11
9 11
7 8
8 9
7 8
9 11
7 9
Output
3
4 6 7
Input
5 1
29 30
30 30
29 29
28 30
30 30
Output
3
1 4 5
Input
6 1
2 3
3 3
2 3
2 2
2 3
2 3
Output
4
1 3 5 6
Submitted Solution:
```
from sys import stdin
from sys import setrecursionlimit as SRL
SRL(10 ** 7)
rd = stdin.readline
rrd = lambda: map(int, rd().strip().split())
n, k = rrd()
ll = [[] for _i in range(200005)]
rr = [[] for _i in range(200005)]
for i in range(n):
l, r = rrd()
ll[l].append([-r, i + 1])
rr[r].append(i + 1)
from heapq import *
q = []
lenth = 0
ans = []
vis = [0] * 200005
for i in range(1, 200005):
for j in ll[i]:
heappush(q, j)
lenth += 1
while lenth > k:
now = heappop(q)
while vis[now[1]]:
now = heappop(q)
vis[now[1]] = 1
ans.append(now[1])
lenth -= 1
for j in rr[i]:
if not vis[j]:
vis[j] = 1
lenth -= 1
print(len(ans))
print(' '.join(map(str, ans)))
``` | instruction | 0 | 36,169 | 23 | 72,338 |
Yes | output | 1 | 36,169 | 23 | 72,339 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is constraints.
You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [l_i; r_i] (l_i ≤ r_i) and it covers all integer points j such that l_i ≤ j ≤ r_i.
The integer point is called bad if it is covered by strictly more than k segments.
Your task is to remove the minimum number of segments so that there are no bad points at all.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of segments and the maximum number of segments by which each integer point can be covered.
The next n lines contain segments. The i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 2 ⋅ 10^5) — the endpoints of the i-th segment.
Output
In the first line print one integer m (0 ≤ m ≤ n) — the minimum number of segments you need to remove so that there are no bad points.
In the second line print m distinct integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ n) — indices of segments you remove in any order. If there are multiple answers, you can print any of them.
Examples
Input
7 2
11 11
9 11
7 8
8 9
7 8
9 11
7 9
Output
3
4 6 7
Input
5 1
29 30
30 30
29 29
28 30
30 30
Output
3
1 4 5
Input
6 1
2 3
3 3
2 3
2 2
2 3
2 3
Output
4
1 3 5 6
Submitted Solution:
```
from heapq import *
n, k = map(int, input().split())
N = int(2e5+2)
seg = [[] for x in range(N)]
for i in range(n):
l, r = map(int, input().split())
seg[l].append((r, i+1))
rs = []
ans = []
for x in range(1, N):
for e in seg[x]:
heappush(rs, e)
while rs and rs[0][0] < x:
heappop(rs)
while len(rs) > k:
e = max(rs)
ans.append(e[1])
rs.remove(e)
heappop(rs)
print(len(ans))
print(*ans)
``` | instruction | 0 | 36,170 | 23 | 72,340 |
No | output | 1 | 36,170 | 23 | 72,341 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is constraints.
You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [l_i; r_i] (l_i ≤ r_i) and it covers all integer points j such that l_i ≤ j ≤ r_i.
The integer point is called bad if it is covered by strictly more than k segments.
Your task is to remove the minimum number of segments so that there are no bad points at all.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of segments and the maximum number of segments by which each integer point can be covered.
The next n lines contain segments. The i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 2 ⋅ 10^5) — the endpoints of the i-th segment.
Output
In the first line print one integer m (0 ≤ m ≤ n) — the minimum number of segments you need to remove so that there are no bad points.
In the second line print m distinct integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ n) — indices of segments you remove in any order. If there are multiple answers, you can print any of them.
Examples
Input
7 2
11 11
9 11
7 8
8 9
7 8
9 11
7 9
Output
3
4 6 7
Input
5 1
29 30
30 30
29 29
28 30
30 30
Output
3
1 4 5
Input
6 1
2 3
3 3
2 3
2 2
2 3
2 3
Output
4
1 3 5 6
Submitted Solution:
```
import heapq as h
from collections import defaultdict
n,m=map(int,input().split())
d=defaultdict(lambda:[])
dd=defaultdict(lambda :[])
q=(2*10**5)+2
vv=[0 for i in range(q)]
u=[]
count=0
for i in range(n):
l,r=map(int,input().split())
if(vv[l]==0):
vv[l]=1
u.append(l)
count+=1
dd[r].append(i+1)
d[l].append([r,i+1])
u.sort()
active=0
heap=[]
visited=[0 for i in range(q)]
var=0
l=[]
i=0
p=0
while(p<count):
i=u[p]
for k in d[i]:
h.heappush(heap,[-k[0],k[1]])
active+=1
while active>m:
var=h.heappop(heap)
while(visited[var[1]]==1):
var=h.heappop(heap)
visited[var[1]]=1
active-=1
l.append(var[1])
for j in dd[i]:
if(visited[j]==0):
visited[j]=1
active-=1
p+=1
print(len(l))
print(*l)
``` | instruction | 0 | 36,171 | 23 | 72,342 |
No | output | 1 | 36,171 | 23 | 72,343 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is constraints.
You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [l_i; r_i] (l_i ≤ r_i) and it covers all integer points j such that l_i ≤ j ≤ r_i.
The integer point is called bad if it is covered by strictly more than k segments.
Your task is to remove the minimum number of segments so that there are no bad points at all.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of segments and the maximum number of segments by which each integer point can be covered.
The next n lines contain segments. The i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 2 ⋅ 10^5) — the endpoints of the i-th segment.
Output
In the first line print one integer m (0 ≤ m ≤ n) — the minimum number of segments you need to remove so that there are no bad points.
In the second line print m distinct integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ n) — indices of segments you remove in any order. If there are multiple answers, you can print any of them.
Examples
Input
7 2
11 11
9 11
7 8
8 9
7 8
9 11
7 9
Output
3
4 6 7
Input
5 1
29 30
30 30
29 29
28 30
30 30
Output
3
1 4 5
Input
6 1
2 3
3 3
2 3
2 2
2 3
2 3
Output
4
1 3 5 6
Submitted Solution:
```
from heapq import *
n, k = map(int, input().split())
N = int(2e5+2)
seg = [[] for x in range(N)]
for i in range(n):
l, r = map(int, input().split())
seg[l].append((r, i+1))
rs = []
ans = []
for x in range(1, N):
for e in seg[x]:
heappush(rs, e)
while rs and rs[0][0] < x:
heappop(rs)
while len(rs) > k:
e = max(rs)
ans.append(e[1])
rs.remove(e)
print(len(ans))
print(*ans)
``` | instruction | 0 | 36,172 | 23 | 72,344 |
No | output | 1 | 36,172 | 23 | 72,345 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is constraints.
You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [l_i; r_i] (l_i ≤ r_i) and it covers all integer points j such that l_i ≤ j ≤ r_i.
The integer point is called bad if it is covered by strictly more than k segments.
Your task is to remove the minimum number of segments so that there are no bad points at all.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of segments and the maximum number of segments by which each integer point can be covered.
The next n lines contain segments. The i-th line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 2 ⋅ 10^5) — the endpoints of the i-th segment.
Output
In the first line print one integer m (0 ≤ m ≤ n) — the minimum number of segments you need to remove so that there are no bad points.
In the second line print m distinct integers p_1, p_2, ..., p_m (1 ≤ p_i ≤ n) — indices of segments you remove in any order. If there are multiple answers, you can print any of them.
Examples
Input
7 2
11 11
9 11
7 8
8 9
7 8
9 11
7 9
Output
3
4 6 7
Input
5 1
29 30
30 30
29 29
28 30
30 30
Output
3
1 4 5
Input
6 1
2 3
3 3
2 3
2 2
2 3
2 3
Output
4
1 3 5 6
Submitted Solution:
```
import heapq
def main():
n,k=readIntArr()
lr=[]
for i in range(n):
l,r=readIntArr()
lr.append([l,r,i+1])
lr.sort(key=lambda x:x[0])
# store [r,idx] of segments
maxHeapRs=[]
minHeapRs=[]
removedIdxes=set()
ans=[]
cnts=0
for l,r,i in lr:
while len(minHeapRs)>0 and minHeapRs[0][0]<l:
leftestRIdx=minHeapRs[0][0]
heapq.heappop(minHeapRs)
if leftestRIdx not in removedIdxes: # not removed previously
removedIdxes.add(leftestRIdx)
cnts-=1
heapq.heappush(minHeapRs,[r,i])
heapq.heappush(maxHeapRs,[-r,i])
cnts+=1
while cnts>k: # get rid of segment with furthest r
rightestRIdx=maxHeapRs[0][1]
heapq.heappop(maxHeapRs)
if rightestRIdx not in removedIdxes:
removedIdxes.add(rightestRIdx)
ans.append(rightestRIdx)
cnts-=1
print(len(ans))
oneLineArrayPrint(ans)
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultVal,dimensionArr): # eg. makeArr(0,[n,m])
dv=defaultVal;da=dimensionArr
if len(da)==1:return [dv for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(x,y):
print('? {} {}'.format(x,y))
sys.stdout.flush()
return int(input())
def answerInteractive(ans):
print('! {}'.format(ans))
sys.stdout.flush()
inf=float('inf')
MOD=10**9+7
# MOD=998244353
for _abc in range(1):
main()
``` | instruction | 0 | 36,173 | 23 | 72,346 |
No | output | 1 | 36,173 | 23 | 72,347 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.
Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
Input
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order.
The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order.
The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
Output
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
Examples
Input
6
-2 1
0 3
3 3
4 1
3 -2
2 -2
4
0 1
2 2
3 1
1 0
Output
YES
Input
5
1 2
4 2
3 -3
-2 -2
-2 1
4
0 1
1 2
4 1
2 -1
Output
NO
Input
5
-1 2
2 3
4 1
3 -2
0 -3
5
1 0
1 1
3 1
5 -1
2 -1
Output
NO | instruction | 0 | 36,350 | 23 | 72,700 |
Tags: geometry, sortings
Correct Solution:
```
import sys
input = sys.stdin.readline
#for _ in range(int(input())):
a,b,temp=[],[],set()
arr=[]
n=int(input())
for _ in range(n):
x,y=[int(x) for x in input().split()]
arr.append([x,y])
m=int(input())
for _ in range(m):
x,y=[int(x) for x in input().split()]
temp.add((x,y))
arr.append([x,y])
arr.sort()
#print(arr)
p1=arr[0]
p2=arr[-1]
up=[p1]
l1,l2=1,1
down=[p1]
for i in range(1,n+m):
if i==n+m-1 or p1[0]*(arr[i][1]-p2[1])+arr[i][0]*(p2[1]-p1[1])+p2[0]*(p1[1]-arr[i][1])>0:
while l1>=2 and up[-2][0]*(up[-1][1]-arr[i][1])+up[-1][0]*(arr[i][1]-up[-2][1])+arr[i][0]*(up[-2][1]-up[-1][1])<0:
up.pop()
l1-=1
up.append(arr[i])
l1+=1
if i==n+m-1 or p1[0]*(arr[i][1]-p2[1])+arr[i][0]*(p2[1]-p1[1])+p2[0]*(p1[1]-arr[i][1])<0:
while l2>=2 and down[-2][0]*(down[-1][1]-arr[i][1])+down[-1][0]*(arr[i][1]-down[-2][1])+arr[i][0]*(down[-2][1]-down[-1][1])>0:
down.pop()
l2-=1
down.append(arr[i])
l2+=1
#print(up,down)
f=True
up.append(p2)
#print(up,down)
for x,y in up:
if (x,y) in temp:
f=False
#print(x,y)
break
for x,y in down:
if (x,y) in temp:
f=False
#print(x,y)
break
if f:
print('YES')
else:
print('NO')
``` | output | 1 | 36,350 | 23 | 72,701 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.
Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
Input
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order.
The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order.
The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
Output
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
Examples
Input
6
-2 1
0 3
3 3
4 1
3 -2
2 -2
4
0 1
2 2
3 1
1 0
Output
YES
Input
5
1 2
4 2
3 -3
-2 -2
-2 1
4
0 1
1 2
4 1
2 -1
Output
NO
Input
5
-1 2
2 3
4 1
3 -2
0 -3
5
1 0
1 1
3 1
5 -1
2 -1
Output
NO | instruction | 0 | 36,351 | 23 | 72,702 |
Tags: geometry, sortings
Correct Solution:
```
def cw(a, b, c):
return a[0] * (b[1] - c[1]) + b[0] * (c[1] - a[1]) + c[0] * (a[1] - b[1]) <= 0
def ccw(a, b, c):
return a[0] * (b[1] - c[1]) + b[0] * (c[1] - a[1]) + c[0] * (a[1] - b[1]) >= 0
def convex_hull(points):
points = sorted(points, key = lambda x: (x[0], x[1]))
up = [points[0]]
down = [points[0]]
for i in range(1, len(points)):
if (i == len(points)-1 or cw(points[0], points[i], points[-1])):
while (len(up) >= 2 and not cw(up[-2], up[-1], points[i])):
up.pop(-1)
up.append(points[i])
if (i == len(points)-1 or ccw(points[0], points[i], points[-1])):
while (len(down) >= 2 and not ccw(down[-2], down[-1], points[i])):
down.pop(-1)
down.append(points[i])
points = up[:] + down[1:-1][::-1]
return points
points = []
n = int(input())
for i in range(n):
x, y = map(int, input().split())
points.append([x, y, 0])
m = int(input())
for i in range(m):
x, y = map(int, input().split())
points.append([x, y, 1])
points = convex_hull(points)
for p in points:
if p[-1] == 1:
print('NO')
break
else:
print('YES')
``` | output | 1 | 36,351 | 23 | 72,703 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.
Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
Input
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order.
The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order.
The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
Output
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
Examples
Input
6
-2 1
0 3
3 3
4 1
3 -2
2 -2
4
0 1
2 2
3 1
1 0
Output
YES
Input
5
1 2
4 2
3 -3
-2 -2
-2 1
4
0 1
1 2
4 1
2 -1
Output
NO
Input
5
-1 2
2 3
4 1
3 -2
0 -3
5
1 0
1 1
3 1
5 -1
2 -1
Output
NO | instruction | 0 | 36,352 | 23 | 72,704 |
Tags: geometry, sortings
Correct Solution:
```
from sys import stdin, stdout
from math import atan2
def square(x1, y1, x2, y2, x3, y3):
return (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)
n = int(stdin.readline())
first = []
axel = 0
for i in range(n):
first.append(tuple(map(int, stdin.readline().split())))
axel = min(axel, i, key = lambda x: first[x])
first = [first[axel]] + first[:axel][::-1] + first[axel + 1:][::-1]
axel = 0
k = int(stdin.readline())
second = []
for i in range(k):
second.append(tuple(map(int, stdin.readline().split())))
label = 1
for i in range(k):
l, r = 1, len(first) - 1
if atan2(first[r][1] - first[axel][1], first[r][0] - first[axel][0]) <= atan2(second[i][1] - first[axel][1], second[i][0] - first[axel][0]):
label = 0
break
if atan2(first[l][1] - first[axel][1], first[l][0] - first[axel][0]) >= atan2(second[i][1] - first[axel][1], second[i][0] - first[axel][0]):
label = 0
break
while (r - l > 1):
m = (r + l) // 2
#print(first[m], first[axel], second[i])
#print(atan2(first[m][1] - first[axel][1], first[m][0] - first[axel][0]), atan2(second[i][1] - first[axel][1], second[i][0] - first[axel][0]))
if atan2(first[m][1] - first[axel][1], first[m][0] - first[axel][0]) >= atan2(second[i][1] - first[axel][1], second[i][0] - first[axel][0]):
r = m
else:
l = m
if abs(square(first[axel][0], first[axel][1], first[r][0], first[r][1], first[l][0], first[l][1])) == abs(square(second[i][0], second[i][1], first[r][0], first[r][1], first[l][0], first[l][1])) + abs(square(first[axel][0], first[axel][1], second[i][0], second[i][1], first[l][0], first[l][1])) + abs(square(first[axel][0], first[axel][1], first[r][0], first[r][1], second[i][0], second[i][1])) and abs(square(second[i][0], second[i][1], first[r][0], first[r][1], first[l][0], first[l][1])):
continue
else:
label = 0
if label:
stdout.write('YES')
else:
stdout.write('NO')
``` | output | 1 | 36,352 | 23 | 72,705 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.
Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
Input
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order.
The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order.
The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
Output
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
Examples
Input
6
-2 1
0 3
3 3
4 1
3 -2
2 -2
4
0 1
2 2
3 1
1 0
Output
YES
Input
5
1 2
4 2
3 -3
-2 -2
-2 1
4
0 1
1 2
4 1
2 -1
Output
NO
Input
5
-1 2
2 3
4 1
3 -2
0 -3
5
1 0
1 1
3 1
5 -1
2 -1
Output
NO | instruction | 0 | 36,353 | 23 | 72,706 |
Tags: geometry, sortings
Correct Solution:
```
from functools import reduce
def convex_hull_graham(points):
TURN_LEFT, TURN_RIGHT, TURN_NONE = (1, -1, 0)
def cmp(a, b):
return (a > b) - (a < b)
def turn(p, q, r):
return cmp((q[0] - p[0])*(r[1] - p[1]) - (r[0] - p[0])*(q[1] - p[1]), 0)
def _keep_left(hull, r):
while len(hull) > 1 and turn(hull[-2], hull[-1], r) not in {TURN_LEFT,TURN_NONE}:
#Agregar a {TURN_LEFT} el elemento TURN_NONE si se quieren alineados
#En la frontera
hull.pop()
if not len(hull) or hull[-1] != r:
hull.append(r)
return hull
points = sorted(points)
l = reduce(_keep_left, points, [])
u = reduce(_keep_left, reversed(points), [])
return l.extend(u[i] for i in range(1, len(u) - 1)) or l
def d():
total = []
n = int(input())
a, b = [], []
for i in range(n):
x,y = map(int,input().split())
total.append((x,y))
a.append((x,y))
m = int(input())
for j in range(m):
x,y = map(int,input().split())
total.append((x,y))
b.append((x,y))
set_a = set()
for i in a:
set_a.add(i)
for j in b:
if(j in set_a):
print("NO")
return
if(sorted(a)==sorted(convex_hull_graham(total))):
print("YES")
else:
print("NO")
d()
``` | output | 1 | 36,353 | 23 | 72,707 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.
Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
Input
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order.
The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order.
The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
Output
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
Examples
Input
6
-2 1
0 3
3 3
4 1
3 -2
2 -2
4
0 1
2 2
3 1
1 0
Output
YES
Input
5
1 2
4 2
3 -3
-2 -2
-2 1
4
0 1
1 2
4 1
2 -1
Output
NO
Input
5
-1 2
2 3
4 1
3 -2
0 -3
5
1 0
1 1
3 1
5 -1
2 -1
Output
NO | instruction | 0 | 36,354 | 23 | 72,708 |
Tags: geometry, sortings
Correct Solution:
```
def convex_hull(points):
points = sorted(set(points))
if len(points) <= 1:
return points
def cross(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
lower = []
for p in points:
while len(lower) >= 2 and cross(lower[-2], lower[-1], p) < 0:
lower.pop()
lower.append(p)
upper = []
for p in reversed(points):
while len(upper) >= 2 and cross(upper[-2], upper[-1], p) < 0:
upper.pop()
upper.append(p)
return lower[:-1] + upper[:-1]
def d():
total = []
n = int(input())
a, b = [], []
for i in range(n):
x,y = map(int,input().split())
total.append((x,y))
a.append((x,y))
m = int(input())
for j in range(m):
x,y = map(int,input().split())
total.append((x,y))
b.append((x,y))
set_a = set()
for i in a:
set_a.add(i)
for j in b:
if(j in set_a):
print("NO")
return
if(sorted(a)==sorted(convex_hull(total))):
print("YES")
else:
print("NO")
d()
``` | output | 1 | 36,354 | 23 | 72,709 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.
Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
Input
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order.
The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order.
The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
Output
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
Examples
Input
6
-2 1
0 3
3 3
4 1
3 -2
2 -2
4
0 1
2 2
3 1
1 0
Output
YES
Input
5
1 2
4 2
3 -3
-2 -2
-2 1
4
0 1
1 2
4 1
2 -1
Output
NO
Input
5
-1 2
2 3
4 1
3 -2
0 -3
5
1 0
1 1
3 1
5 -1
2 -1
Output
NO | instruction | 0 | 36,355 | 23 | 72,710 |
Tags: geometry, sortings
Correct Solution:
```
from math import *
from collections import defaultdict as dd
from sys import stdin,stdout,setrecursionlimit as srl
from bisect import bisect_right as br,bisect_left as bl
from heapq import heapify,heappush as hpush,heappop as hpop
srl(10**6+999);mod=int(1e9)+7;yes='YES';no='NO';
class graph:
def __init__(self,n):
self.d=dd(list)
self.vis=[0]*(n+1)
self.dp=[[0,0] for i in range(n+1)]
def addvrtx(self,src,dest):
self.d[src].append(dest)
self.d[dest].append(src)
def value(a,b,c):
return a[0]*(b[1]-c[1])+b[0]*(c[1]-a[1])+c[0]*(a[1]-b[1])
def cw(a,b,c):
return value(a,b,c)>0
def acw(a,b,c):
return value(a,b,c)<0
def collinear(a,b,c):
return value(a,b,c)==0
def ConvexHull(p,n):
if(n<=2):return
p.sort()
p1=p[0] # bottom left point
p2=p[-1] # top right point
up=[p1];down=[p1]
for i in range(1,n):
if(i==n-1 or (not acw(p1,p[i],p2))):
while(len(up)>=2 and acw(up[-2],up[-1],p[i])):
up.pop()
up.append(p[i])
if(i==n-1 or (not cw(p1,p[i],p2))):
while(len(down)>=2 and cw(down[-2],down[-1],p[i])):
down.pop()
down.append(p[i])
ans=up+down
return sorted(set(ans))
if __name__=='__main__':
for tc in range(1):
d=dd(int)
val=yes
n=int(input())
a=[tuple(map(int,input().split())) for i in range(n)]
m=int(input())
b=[tuple(map(int,input().split())) for i in range(m)]
ans=ConvexHull(a+b,n+m)
for i in b:
d[i]=1
for i in ans:
if(d[i]==1):
val=no
break
print(val)
``` | output | 1 | 36,355 | 23 | 72,711 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.
Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
Input
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order.
The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order.
The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
Output
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
Examples
Input
6
-2 1
0 3
3 3
4 1
3 -2
2 -2
4
0 1
2 2
3 1
1 0
Output
YES
Input
5
1 2
4 2
3 -3
-2 -2
-2 1
4
0 1
1 2
4 1
2 -1
Output
NO
Input
5
-1 2
2 3
4 1
3 -2
0 -3
5
1 0
1 1
3 1
5 -1
2 -1
Output
NO | instruction | 0 | 36,356 | 23 | 72,712 |
Tags: geometry, sortings
Correct Solution:
```
# Author : nitish420 --------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
import functools
class Point:
def __init__(self,x,y):
self.x=x
self.y=y
def main():
# enter number of vertices
n=int(input())
zz=n
points=[]
miny=10**10
minpos=0
seta=set()
for i in range(n):
a,b=map(int,input().split())
if b<miny:
miny=b
minpos=i
elif b==miny:
if a<points[minpos].x:
minpos=i
seta.add((a,b))
points.append(Point(a,b))
m=int(input())
pointsb=[]
for _ in range(m):
a,b=map(int,input().split())
if (a,b) not in seta and b>= miny:
pointsb.append(Point(a,b))
else:
print("NO")
exit()
n+=m
points+=pointsb
# swapping min with 0th term
points[0],points[minpos]=points[minpos],points[0]
base=points[0]
points=points[1:]
def direction(p,q,r):
val=((q.x-p.x)*(r.y-p.y)-(r.x-p.x)*(q.y-p.y))
if val>0:
return 1
elif val<0:
return -1
else:
return 0
def sqdist(x):
a=base.x-x.x
b=base.y-x.y
# no need to square root coz we only need this to compare
return a*a+b*b
def compare(a,b):
z=direction(base,a,b)
if z==0:
return sqdist(a)-sqdist(b)
else:
return -z
points.sort(key= functools.cmp_to_key(compare))
points=[base]+points
ans=[]
ans.append(points[0])
ans.append(points[1])
ans.append(points[2])
for i in range(3,n):
while len(ans)>1:
d=direction(ans[-2],ans[-1],points[i])
if d<0:
ans.pop()
else:
break
ans.append(points[i])
# for item in ans:
# print(item.x,item.y)
if len(ans)==zz:
for item in ans:
if (item.x,item.y) not in seta:
print("NO")
exit()
base=ans[0]
last=ans[-1]
# checking from last one to first one
for item in pointsb:
if direction(base,last,item)==0:
print("NO")
exit()
print("YES")
else:
print("NO")
'''
4
-10 -10
-10 10
10 10
10 -10
3
0 -10
1 5
2 2
4
-10 -10
-10 10
10 10
10 -10
3
-10 0
1 5
2 2
'''
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = 'x' in file.mode or 'r' not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b'\n') + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda: self.buffer.read().decode('ascii')
self.readline = lambda: self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
# endregion
if __name__ == '__main__':
main()
``` | output | 1 | 36,356 | 23 | 72,713 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.
Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
Input
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order.
The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order.
The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
Output
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
Examples
Input
6
-2 1
0 3
3 3
4 1
3 -2
2 -2
4
0 1
2 2
3 1
1 0
Output
YES
Input
5
1 2
4 2
3 -3
-2 -2
-2 1
4
0 1
1 2
4 1
2 -1
Output
NO
Input
5
-1 2
2 3
4 1
3 -2
0 -3
5
1 0
1 1
3 1
5 -1
2 -1
Output
NO | instruction | 0 | 36,357 | 23 | 72,714 |
Tags: geometry, sortings
Correct Solution:
```
#Juli
def convex_hull(points):
points = sorted(set(points))
if len(points) <= 1:
return points
def cross(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
lower = []
for p in points:
while len(lower) >= 2 and cross(lower[-2], lower[-1], p) < 0:
lower.pop()
lower.append(p)
upper = []
for p in reversed(points):
while len(upper) >= 2 and cross(upper[-2], upper[-1], p) < 0:
upper.pop()
upper.append(p)
return lower[:-1] + upper[:-1]
def d():
total = []
n = int(input())
a, b = [], []
for i in range(n):
x,y = map(int,input().split())
total.append((x,y))
a.append((x,y))
m = int(input())
for j in range(m):
x,y = map(int,input().split())
total.append((x,y))
b.append((x,y))
set_a = set()
for i in a:
set_a.add(i)
for j in b:
if(j in set_a):
print("NO")
return
if(sorted(a)==sorted(convex_hull(total))):
print("YES")
else:
print("NO")
d()
``` | output | 1 | 36,357 | 23 | 72,715 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.
Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
Input
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order.
The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order.
The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
Output
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
Examples
Input
6
-2 1
0 3
3 3
4 1
3 -2
2 -2
4
0 1
2 2
3 1
1 0
Output
YES
Input
5
1 2
4 2
3 -3
-2 -2
-2 1
4
0 1
1 2
4 1
2 -1
Output
NO
Input
5
-1 2
2 3
4 1
3 -2
0 -3
5
1 0
1 1
3 1
5 -1
2 -1
Output
NO
Submitted Solution:
```
from sys import stdin, stdout
def square(x1, y1, x2, y2, x3, y3):
return (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)
n = int(stdin.readline())
first = []
axel = 0
for i in range(n):
first.append(tuple(map(int, stdin.readline().split())))
axel = min(axel, i, key = lambda x: first[x])
first = [first[axel]] + first[:axel:-1] + first[axel + 1::-1]
k = int(stdin.readline())
second = []
for i in range(k):
second.append(tuple(map(int, stdin.readline().split())))
label = 1
for i in range(k):
if second[i][0] <= first[axel][0]:
label = 0
l, r = -1, len(first) + 1
while (r - l > 1):
m = (r + l) // 2
if square(first[axel][0], first[axel][1], second[i][0], second[i][1], first[m][0], first[m][1]) >= 0:
r = m
else:
l = m
if not(abs(square(first[axel][0], first[axel][1], first[r][0], first[r][1], first[l][0], first[l][1])) == abs(square(second[i][0], second[i][1], first[r][0], first[r][1], first[l][0], first[l][1])) + abs(square(first[axel][0], first[axel][1], second[i][0], second[i][1], first[l][0], first[l][1])) + abs(square(first[axel][0], first[axel][1], first[r][0], first[r][1], second[i][0], second[i][1])) and abs(square(second[i][0], second[i][1], first[r][0], first[r][1], first[l][0], first[l][1]))):
label = 0
if label:
stdout.write('YES')
else:
stdout.write('NO')
``` | instruction | 0 | 36,358 | 23 | 72,716 |
No | output | 1 | 36,358 | 23 | 72,717 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.
Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
Input
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order.
The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order.
The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
Output
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
Examples
Input
6
-2 1
0 3
3 3
4 1
3 -2
2 -2
4
0 1
2 2
3 1
1 0
Output
YES
Input
5
1 2
4 2
3 -3
-2 -2
-2 1
4
0 1
1 2
4 1
2 -1
Output
NO
Input
5
-1 2
2 3
4 1
3 -2
0 -3
5
1 0
1 1
3 1
5 -1
2 -1
Output
NO
Submitted Solution:
```
def reader(taille):
liste = []
for i in range(taille):
coordonates = input().split()
liste.append((int(coordonates[0]), int(coordonates[1])))
return liste
def checker(index, array1, array2):
listeA = [x[index] for x in array1]
listeb = [x[index] for x in array2]
if max(listeb) >= max(listeA) or min(listeb) <= min(listeA):
return 0
return 1
o=0
a = int(input())
coordA = reader(a)
b = int(input())
coordB = reader(b)
test1 = checker(0, coordA, coordB)
test2 = checker(1, coordA, coordB)
if test1 == 1 and test2 == 1:
print('YES')
else:
print("NO")
``` | instruction | 0 | 36,359 | 23 | 72,718 |
No | output | 1 | 36,359 | 23 | 72,719 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.
Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
Input
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order.
The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order.
The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
Output
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
Examples
Input
6
-2 1
0 3
3 3
4 1
3 -2
2 -2
4
0 1
2 2
3 1
1 0
Output
YES
Input
5
1 2
4 2
3 -3
-2 -2
-2 1
4
0 1
1 2
4 1
2 -1
Output
NO
Input
5
-1 2
2 3
4 1
3 -2
0 -3
5
1 0
1 1
3 1
5 -1
2 -1
Output
NO
Submitted Solution:
```
# Author : nitish420 --------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
class Point:
def __init__(self,x,y):
self.x=x
self.y=y
def main():
n=int(input())
zz=n
points=[]
seta=set()
for i in range(n):
a,b=map(int,input().split())
seta.add((a,b))
points.append(Point(a,b))
m=int(input())
for i in range(m):
a,b=map(int,input().split())
if (a,b) not in seta:
points.append(Point(a,b))
else:
print("NO")
exit()
n+=m
points.sort(key=lambda z : (z.x,z.y))
def direction(p,q,r):
val=((q.x-p.x)*(r.y-p.y)-(r.x-p.x)*(q.y-p.y))
if val>0:
return 1
elif val<0:
return -1
else:
return 0
ans=[0]*(2*n)
z=0
# build lower hull
for i in range(n):
while z>=2 and direction(ans[z-2],ans[z-1],points[i])<=0:
z-=1
ans[z]=points[i]
z+=1
k=z+1
for i in range(n-1,-1,-1):
while z>=k and direction(ans[z-2],ans[z-1],points[i-1])<=0:
z-=1
ans[z]=points[i-1]
z+=1
ans=ans[:z-2]
if len(ans)==zz:
for item in ans:
if (item.x,item.y) not in seta:
print("NO")
exit()
print("YES")
else:
print("NO")
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = 'x' in file.mode or 'r' not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b'\n') + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda: self.buffer.read().decode('ascii')
self.readline = lambda: self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
# endregion
if __name__ == '__main__':
main()
``` | instruction | 0 | 36,360 | 23 | 72,720 |
No | output | 1 | 36,360 | 23 | 72,721 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.
Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
Input
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order.
The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order.
The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
Output
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
Examples
Input
6
-2 1
0 3
3 3
4 1
3 -2
2 -2
4
0 1
2 2
3 1
1 0
Output
YES
Input
5
1 2
4 2
3 -3
-2 -2
-2 1
4
0 1
1 2
4 1
2 -1
Output
NO
Input
5
-1 2
2 3
4 1
3 -2
0 -3
5
1 0
1 1
3 1
5 -1
2 -1
Output
NO
Submitted Solution:
```
from sys import stdin, stdout
def square(x1, y1, x2, y2, x3, y3):
return (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)
n = int(stdin.readline())
first = []
axel = 0
for i in range(n):
first.append(tuple(map(int, stdin.readline().split())))
axel = min(axel, i, key = lambda x: first[x])
first = [first[axel]] + first[:axel:-1] + first[axel + 1::-1]
axel = 0
k = int(stdin.readline())
second = []
for i in range(k):
second.append(tuple(map(int, stdin.readline().split())))
label = 1
for i in range(k):
if second[i][0] <= first[axel][0]:
label = 0
l, r = -1, len(first)
while (r - l > 1):
m = (r + l) // 2
if square(first[axel][0], first[axel][1], second[i][0], second[i][1], first[m][0], first[m][1]) >= 0:
r = m
else:
l = m
if not(r != len(first) and (l != -1 or square(first[axel][0], first[axel][1], second[i][0], second[i][1], first[r][0], first[r][1]) == 0) and abs(square(first[axel][0], first[axel][1], first[r][0], first[r][1], first[l][0], first[l][1])) == abs(square(second[i][0], second[i][1], first[r][0], first[r][1], first[l][0], first[l][1])) + abs(square(first[axel][0], first[axel][1], second[i][0], second[i][1], first[l][0], first[l][1])) + abs(square(first[axel][0], first[axel][1], first[r][0], first[r][1], second[i][0], second[i][1])) and abs(square(second[i][0], second[i][1], first[r][0], first[r][1], first[l][0], first[l][1]))):
label = 0
if label:
stdout.write('YES')
else:
stdout.write('NO')
``` | instruction | 0 | 36,361 | 23 | 72,722 |
No | output | 1 | 36,361 | 23 | 72,723 |
Provide a correct Python 3 solution for this coding contest problem.
As shown in the following figure, there is a paper consisting of a grid structure where each cell is indicated by (x, y) coordinate system.
We are going to put drops of ink on the paper. A drop comes in three different sizes: Large, Medium, and Small. From the point of fall, the ink sinks into surrounding cells as shown in the figure depending on its size. In the figure, a star denotes the point of fall and a circle denotes the surrounding cells.
<image>
Originally, the paper is white that means for each cell the value of density is 0. The value of density is increased by 1 when the ink sinks into the corresponding cells. For example, if we put a drop of Small ink at (1, 2) and a drop of Medium ink at (3, 2), the ink will sink as shown in the following figure (left side):
<image>
In the figure, density values of empty cells are 0. The ink sinking into out of the paper should be ignored as shown in the figure (top side). We can put several drops of ink at the same point.
Your task is to write a program which reads a sequence of points of fall (x, y) with its size (Small = 1, Medium = 2, Large = 3), and prints the number of cells whose density value is 0. The program must also print the maximum value of density.
You may assume that the paper always consists of 10 × 10, and 0 ≤ x < 10, 0 ≤ y < 10.
Input
x1,y1,s1
x2,y2,s2
:
:
(xi, yi) represents the position of the i-th drop and si denotes its size. The number of drops is less than or equal to 50.
Output
Print the number of cells whose density value is 0 in first line.
Print the maximum value of density in the second line.
Example
Input
2,5,3
3,6,1
3,4,2
4,5,2
3,6,3
2,4,1
Output
77
5 | instruction | 0 | 36,744 | 23 | 73,488 |
"Correct Solution:
```
#sheet...紙全体、sheet[x][y]は(x, y)のインクの濃さ
sheet = [[0 for _ in range(10)] for _ in range(10)]
#小、中、大のインクの範囲
small_range = ((0, 0), (1, 0), (0, 1), (-1, 0), (0, -1))
middle_range = ((0, 0), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1))
large_range = ((0, 0), (1, 0), (2, 0), (1, 1), (0, 1), (0, 2), (-1, 1), (-1, 0), (-2, 0), (-1, -1), (0, -1), (0, -2), (1, -1))
#範囲内か判定してインクを足す
def drop(x, y, drop_range):
for dx, dy in drop_range:
newx, newy = x + dx, y + dy
if 0 <= newx <= 9 and 0 <= newy <= 9:
sheet[newx][newy] += 1
while True:
try:
x, y, s = map(int, input().split(","))
if s == 1:
drop(x, y, small_range)
elif s == 2:
drop(x, y, middle_range)
else:
drop(x, y, large_range)
except EOFError:
break
#0の個数
zero_cnt = 0
#インクの最大値
max_ink = 0
for x in range(10):
for y in range(10):
ink = sheet[x][y]
if ink == 0:
zero_cnt += 1
if max_ink < ink:
max_ink = ink
print(zero_cnt)
print(max_ink)
``` | output | 1 | 36,744 | 23 | 73,489 |
Provide a correct Python 3 solution for this coding contest problem.
As shown in the following figure, there is a paper consisting of a grid structure where each cell is indicated by (x, y) coordinate system.
We are going to put drops of ink on the paper. A drop comes in three different sizes: Large, Medium, and Small. From the point of fall, the ink sinks into surrounding cells as shown in the figure depending on its size. In the figure, a star denotes the point of fall and a circle denotes the surrounding cells.
<image>
Originally, the paper is white that means for each cell the value of density is 0. The value of density is increased by 1 when the ink sinks into the corresponding cells. For example, if we put a drop of Small ink at (1, 2) and a drop of Medium ink at (3, 2), the ink will sink as shown in the following figure (left side):
<image>
In the figure, density values of empty cells are 0. The ink sinking into out of the paper should be ignored as shown in the figure (top side). We can put several drops of ink at the same point.
Your task is to write a program which reads a sequence of points of fall (x, y) with its size (Small = 1, Medium = 2, Large = 3), and prints the number of cells whose density value is 0. The program must also print the maximum value of density.
You may assume that the paper always consists of 10 × 10, and 0 ≤ x < 10, 0 ≤ y < 10.
Input
x1,y1,s1
x2,y2,s2
:
:
(xi, yi) represents the position of the i-th drop and si denotes its size. The number of drops is less than or equal to 50.
Output
Print the number of cells whose density value is 0 in first line.
Print the maximum value of density in the second line.
Example
Input
2,5,3
3,6,1
3,4,2
4,5,2
3,6,3
2,4,1
Output
77
5 | instruction | 0 | 36,745 | 23 | 73,490 |
"Correct Solution:
```
import sys
b = [ list(0 for i in range(14)) for j in range(14)]
def s(b,x,y):
b[x][y] += 1
b[x+1][y] += 1
b[x-1][y] += 1
b[x][y+1] += 1
b[x][y-1] += 1
def m(b,x,y):
b[x-1][y-1] += 1
b[x ][y-1] += 1
b[x+1][y-1] += 1
b[x-1][y ] += 1
b[x ][y ] += 1
b[x+1][y ] += 1
b[x-1][y+1] += 1
b[x ][y+1] += 1
b[x+1][y+1] += 1
def l(b,x,y):
b[x ][y-2] += 1
b[x-1][y-1] += 1
b[x ][y-1] += 1
b[x+1][y-1] += 1
b[x-2][y ] += 1
b[x-1][y ] += 1
b[x ][y ] += 1
b[x+1][y ] += 1
b[x+2][y ] += 1
b[x-1][y+1] += 1
b[x ][y+1] += 1
b[x+1][y+1] += 1
b[x ][y+2] += 1
for line in sys.stdin:
d = list(map(int,line.split(",")))
c = d[2]
x = d[0] + 2
y = d[1] + 2
if c == 1:
s(b,x,y)
elif c == 2:
m(b,x,y)
elif c == 3:
l(b,x,y)
ttl = 0
num = 0
max = 0
for x in range(2,12):
for y in range(2,12):
ttl += 1
if b[x][y] == 0:
num += 1
if b[x][y] > max:
max = b[x][y]
print(num)
print(max)
``` | output | 1 | 36,745 | 23 | 73,491 |
Provide a correct Python 3 solution for this coding contest problem.
As shown in the following figure, there is a paper consisting of a grid structure where each cell is indicated by (x, y) coordinate system.
We are going to put drops of ink on the paper. A drop comes in three different sizes: Large, Medium, and Small. From the point of fall, the ink sinks into surrounding cells as shown in the figure depending on its size. In the figure, a star denotes the point of fall and a circle denotes the surrounding cells.
<image>
Originally, the paper is white that means for each cell the value of density is 0. The value of density is increased by 1 when the ink sinks into the corresponding cells. For example, if we put a drop of Small ink at (1, 2) and a drop of Medium ink at (3, 2), the ink will sink as shown in the following figure (left side):
<image>
In the figure, density values of empty cells are 0. The ink sinking into out of the paper should be ignored as shown in the figure (top side). We can put several drops of ink at the same point.
Your task is to write a program which reads a sequence of points of fall (x, y) with its size (Small = 1, Medium = 2, Large = 3), and prints the number of cells whose density value is 0. The program must also print the maximum value of density.
You may assume that the paper always consists of 10 × 10, and 0 ≤ x < 10, 0 ≤ y < 10.
Input
x1,y1,s1
x2,y2,s2
:
:
(xi, yi) represents the position of the i-th drop and si denotes its size. The number of drops is less than or equal to 50.
Output
Print the number of cells whose density value is 0 in first line.
Print the maximum value of density in the second line.
Example
Input
2,5,3
3,6,1
3,4,2
4,5,2
3,6,3
2,4,1
Output
77
5 | instruction | 0 | 36,746 | 23 | 73,492 |
"Correct Solution:
```
def paint(masu,data):
masu[data[1]][data[0]]+=1 #インクを垂らした場所
#print(masu)
if data[2]==1: #インク小の時
if data[0]!=0:
masu[data[1]][data[0]-1]+=1
if data[0]!=9:
masu[data[1]][data[0]+1]+=1
if data[1]!=0:
masu[data[1]-1][data[0]]+=1
if data[1]!=9:
masu[data[1]+1][data[0]]+=1
#print("小の時",masu)
elif data[2]==2: #インク中の時
if data[0]!=0:
masu[data[1]][data[0]-1]+=1
if data[0]!=9:
masu[data[1]][data[0]+1]+=1
if data[1]!=0:
masu[data[1]-1][data[0]]+=1
if data[1]!=9:
masu[data[1]+1][data[0]]+=1
if data[1]!=9 and data[0]!=9:
masu[data[1]+1][data[0]+1]+=1
if data[1]!=9 and data[0]!=0:
masu[data[1]+1][data[0]-1]+=1
if data[1]!=0 and data[0]!=9:
masu[data[1]-1][data[0]+1]+=1
if data[1]!=0 and data[0]!=0:
masu[data[1]-1][data[0]-1]+=1
#print("中の時",masu)
elif data[2]==3: #インク大の時
if data[0]!=0:
masu[data[1]][data[0]-1]+=1
if data[0]!=9:
masu[data[1]][data[0]+1]+=1
if data[1]!=0:
masu[data[1]-1][data[0]]+=1
if data[1]!=9:
masu[data[1]+1][data[0]]+=1
if data[1]!=9 and data[0]!=9:
masu[data[1]+1][data[0]+1]+=1
if data[1]!=9 and data[0]!=0:
masu[data[1]+1][data[0]-1]+=1
if data[1]!=0 and data[0]!=9:
masu[data[1]-1][data[0]+1]+=1
if data[1]!=0 and data[0]!=0:
masu[data[1]-1][data[0]-1]+=1
if data[1]>=2:
masu[data[1]-2][data[0]]+=1
if data[1]<=7:
masu[data[1]+2][data[0]]+=1
if data[0]>=2:
masu[data[1]][data[0]-2]+=1
if data[0]<=7:
masu[data[1]][data[0]+2]+=1
#print("大の時",masu)
return masu
masu=[
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0]
]
def keisan(masu):
max=0
num1=0
for na in range(10):
for ma in range(10):
if masu[na][ma]==0:
num1+=1
if masu[na][ma]>max:
max=masu[na][ma]
print(num1)
print(max)
while True:
try:
x,y,s=list(map(int, input().split(',')))
data=[x,y,s]
masu2=paint(masu,data)
except:
break
#print("masu",masu2)
#print("masu2",masu2)
keisan(masu2)
``` | output | 1 | 36,746 | 23 | 73,493 |
Provide a correct Python 3 solution for this coding contest problem.
As shown in the following figure, there is a paper consisting of a grid structure where each cell is indicated by (x, y) coordinate system.
We are going to put drops of ink on the paper. A drop comes in three different sizes: Large, Medium, and Small. From the point of fall, the ink sinks into surrounding cells as shown in the figure depending on its size. In the figure, a star denotes the point of fall and a circle denotes the surrounding cells.
<image>
Originally, the paper is white that means for each cell the value of density is 0. The value of density is increased by 1 when the ink sinks into the corresponding cells. For example, if we put a drop of Small ink at (1, 2) and a drop of Medium ink at (3, 2), the ink will sink as shown in the following figure (left side):
<image>
In the figure, density values of empty cells are 0. The ink sinking into out of the paper should be ignored as shown in the figure (top side). We can put several drops of ink at the same point.
Your task is to write a program which reads a sequence of points of fall (x, y) with its size (Small = 1, Medium = 2, Large = 3), and prints the number of cells whose density value is 0. The program must also print the maximum value of density.
You may assume that the paper always consists of 10 × 10, and 0 ≤ x < 10, 0 ≤ y < 10.
Input
x1,y1,s1
x2,y2,s2
:
:
(xi, yi) represents the position of the i-th drop and si denotes its size. The number of drops is less than or equal to 50.
Output
Print the number of cells whose density value is 0 in first line.
Print the maximum value of density in the second line.
Example
Input
2,5,3
3,6,1
3,4,2
4,5,2
3,6,3
2,4,1
Output
77
5 | instruction | 0 | 36,747 | 23 | 73,494 |
"Correct Solution:
```
p = [[0 for j in range(10)] for i in range(10)]
s1i = [-1, 0, 0, 1]
s1j = [0, -1, 1, 0]
s2i = [-1, -1, -1, 0, 0, 1, 1, 1]
s2j = [-1, 0, 1, -1, 1, -1, 0, 1]
s3i = [-2, -1, -1, -1, 0, 0, 0, 0, 1, 1, 1, 2]
s3j = [0, -1, 0, 1, -2, -1, 1, 2, -1, 0, 1, 0]
while True:
try:
x, y, s = map(int, input().split(","))
except:
break
p[y][x] += 1
if s == 1:
for k in range(len(s1i)):
xx = x + s1j[k]
yy = y + s1i[k]
if 0 <= xx and xx < 10 and 0 <= yy and yy < 10:
p[yy][xx] += 1
elif s == 2:
for k in range(len(s2i)):
xx = x + s2j[k]
yy = y + s2i[k]
if 0 <= xx and xx < 10 and 0 <= yy and yy < 10:
p[yy][xx] += 1
else:
for k in range(len(s3i)):
xx = x + s3j[k]
yy = y + s3i[k]
if 0 <= xx and xx < 10 and 0 <= yy and yy < 10:
p[yy][xx] += 1
cnt = 0
m = 0
for i in range(10):
#print(p[i])
for j in range(10):
if p[i][j] == 0:
cnt += 1
else:
pass
m = max(p[i][j], m)
#print()
print(cnt)
print(m)
``` | output | 1 | 36,747 | 23 | 73,495 |
Provide a correct Python 3 solution for this coding contest problem.
As shown in the following figure, there is a paper consisting of a grid structure where each cell is indicated by (x, y) coordinate system.
We are going to put drops of ink on the paper. A drop comes in three different sizes: Large, Medium, and Small. From the point of fall, the ink sinks into surrounding cells as shown in the figure depending on its size. In the figure, a star denotes the point of fall and a circle denotes the surrounding cells.
<image>
Originally, the paper is white that means for each cell the value of density is 0. The value of density is increased by 1 when the ink sinks into the corresponding cells. For example, if we put a drop of Small ink at (1, 2) and a drop of Medium ink at (3, 2), the ink will sink as shown in the following figure (left side):
<image>
In the figure, density values of empty cells are 0. The ink sinking into out of the paper should be ignored as shown in the figure (top side). We can put several drops of ink at the same point.
Your task is to write a program which reads a sequence of points of fall (x, y) with its size (Small = 1, Medium = 2, Large = 3), and prints the number of cells whose density value is 0. The program must also print the maximum value of density.
You may assume that the paper always consists of 10 × 10, and 0 ≤ x < 10, 0 ≤ y < 10.
Input
x1,y1,s1
x2,y2,s2
:
:
(xi, yi) represents the position of the i-th drop and si denotes its size. The number of drops is less than or equal to 50.
Output
Print the number of cells whose density value is 0 in first line.
Print the maximum value of density in the second line.
Example
Input
2,5,3
3,6,1
3,4,2
4,5,2
3,6,3
2,4,1
Output
77
5 | instruction | 0 | 36,748 | 23 | 73,496 |
"Correct Solution:
```
a = [[0] * 14 for _ in range(14)]
while True:
try:
x, y, s = map(int, input().split(','))
except:
break
x += 2
y += 2
for d in [(0, 0), (0, -1), (0, 1), (-1, 0), (1, 0)]:
a[x + d[0]][y + d[1]] += 1
if s >= 2:
for d in [(1, 1), (1, -1), (-1, 1), (-1, -1)]:
a[x + d[0]][y + d[1]] += 1
if s == 3:
for d in [(0, 2), (0, -2), (2, 0), (-2, 0)]:
a[x + d[0]][y + d[1]] += 1
print(sum(a[i][2:12].count(0) for i in range(2, 12)))
print(max(max(a[i][2:12]) for i in range(2, 12)))
``` | output | 1 | 36,748 | 23 | 73,497 |
Provide a correct Python 3 solution for this coding contest problem.
As shown in the following figure, there is a paper consisting of a grid structure where each cell is indicated by (x, y) coordinate system.
We are going to put drops of ink on the paper. A drop comes in three different sizes: Large, Medium, and Small. From the point of fall, the ink sinks into surrounding cells as shown in the figure depending on its size. In the figure, a star denotes the point of fall and a circle denotes the surrounding cells.
<image>
Originally, the paper is white that means for each cell the value of density is 0. The value of density is increased by 1 when the ink sinks into the corresponding cells. For example, if we put a drop of Small ink at (1, 2) and a drop of Medium ink at (3, 2), the ink will sink as shown in the following figure (left side):
<image>
In the figure, density values of empty cells are 0. The ink sinking into out of the paper should be ignored as shown in the figure (top side). We can put several drops of ink at the same point.
Your task is to write a program which reads a sequence of points of fall (x, y) with its size (Small = 1, Medium = 2, Large = 3), and prints the number of cells whose density value is 0. The program must also print the maximum value of density.
You may assume that the paper always consists of 10 × 10, and 0 ≤ x < 10, 0 ≤ y < 10.
Input
x1,y1,s1
x2,y2,s2
:
:
(xi, yi) represents the position of the i-th drop and si denotes its size. The number of drops is less than or equal to 50.
Output
Print the number of cells whose density value is 0 in first line.
Print the maximum value of density in the second line.
Example
Input
2,5,3
3,6,1
3,4,2
4,5,2
3,6,3
2,4,1
Output
77
5 | instruction | 0 | 36,749 | 23 | 73,498 |
"Correct Solution:
```
def dot(h, w):
global area
if 0 <= h and h < 10 and 0 <= w and w < 10:
area[h][w] += 1
def sdot(h,w):
[dot(h + i, w + j) for j in range(-1, 2) for i in range(-1 + abs(j), 2 - abs(j))]
def mdot(h,w):
[dot(h + i, w + j) for j in range(-1, 2) for i in range(-1, 2)]
def ldot(h, w):
[dot(h + i, w + j) for j in range(-2, 3) for i in range(-2 + abs(j), 3 - abs(j))]
dots = (sdot, mdot, ldot)
area = [[0 for _ in range(10)] for _ in range(10)]
while True:
try:w, h, s = map(int, input().split(","))
except:break
dots[s - 1](h, w)
print(sum(i.count(0) for i in area))
print(max(max(i) for i in area))
``` | output | 1 | 36,749 | 23 | 73,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.