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.
Have you ever heard of the unit "○○ tsubo" that expresses the area of land? Since ancient times, one samurai has said the area for making rice to eat in a day.
There is a land of a [m] x b [m]. Enter a and b and create a program that outputs the tsubo area S [tsubo] of the land. 1 tsubo = 3.305785 [m2], and a and b are integers less than or equal to 100.
input
a b
A and b separated by one space are given on one line.
output
Output the tsubo area S in one line. An error of 0.0001 or less is allowed.
Example
Input
15 25
Output
113.437508
Submitted Solution:
```
import sys
f = sys.stdin
a, b = map(int, f.readline().split())
print('{:.6f}'.format(a * b * 0.3025))
``` | instruction | 0 | 14,939 | 23 | 29,878 |
No | output | 1 | 14,939 | 23 | 29,879 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a marine area map that is a mesh of squares, each representing either a land or sea area. Figure B-1 is an example of a map.
<image>
Figure B-1: A marine area map
You can walk from a square land area to another if they are horizontally, vertically, or diagonally adjacent to each other on the map. Two areas are on the same island if and only if you can walk from one to the other possibly through other land areas. The marine area on the map is surrounded by the sea and therefore you cannot go outside of the area on foot.
You are requested to write a program that reads the map and counts the number of islands on it. For instance, the map in Figure B-1 includes three islands.
Input
The input consists of a series of datasets, each being in the following format.
> w h
> c1,1 c1,2 ... c1,w
> c2,1 c2,2 ... c2,w
> ...
> ch,1 ch,2 ... ch,w
>
w and h are positive integers no more than 50 that represent the width and the height of the given map, respectively. In other words, the map consists of w×h squares of the same size. w and h are separated by a single space.
ci, j is either 0 or 1 and delimited by a single space. If ci, j = 0, the square that is the i-th from the left and j-th from the top on the map represents a sea area. Otherwise, that is, if ci, j = 1, it represents a land area.
The end of the input is indicated by a line containing two zeros separated by a single space.
Output
For each dataset, output the number of the islands in a line. No extra characters should occur in the output.
Sample Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output for the Sample Input
0
1
1
3
1
9
Example
Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output
0
1
1
3
1
9 | instruction | 0 | 14,981 | 23 | 29,962 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(2500)
def erase(x, y):
c[y][x] = '0'
for dx, dy in ((1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)):
nx, ny = x + dx, y + dy
if 0 <= nx < w and 0 <= ny < h and c[ny][nx] == '1':
erase(nx, ny)
while True:
w, h = map(int, sys.stdin.readline().split())
if w == h == 0:
break
c = [sys.stdin.readline().split() for _ in range(h)]
ans = 0
for y in range(h):
for x in range(w):
if c[y][x] == '1':
ans += 1
erase(x, y)
print(ans)
``` | output | 1 | 14,981 | 23 | 29,963 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a marine area map that is a mesh of squares, each representing either a land or sea area. Figure B-1 is an example of a map.
<image>
Figure B-1: A marine area map
You can walk from a square land area to another if they are horizontally, vertically, or diagonally adjacent to each other on the map. Two areas are on the same island if and only if you can walk from one to the other possibly through other land areas. The marine area on the map is surrounded by the sea and therefore you cannot go outside of the area on foot.
You are requested to write a program that reads the map and counts the number of islands on it. For instance, the map in Figure B-1 includes three islands.
Input
The input consists of a series of datasets, each being in the following format.
> w h
> c1,1 c1,2 ... c1,w
> c2,1 c2,2 ... c2,w
> ...
> ch,1 ch,2 ... ch,w
>
w and h are positive integers no more than 50 that represent the width and the height of the given map, respectively. In other words, the map consists of w×h squares of the same size. w and h are separated by a single space.
ci, j is either 0 or 1 and delimited by a single space. If ci, j = 0, the square that is the i-th from the left and j-th from the top on the map represents a sea area. Otherwise, that is, if ci, j = 1, it represents a land area.
The end of the input is indicated by a line containing two zeros separated by a single space.
Output
For each dataset, output the number of the islands in a line. No extra characters should occur in the output.
Sample Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output for the Sample Input
0
1
1
3
1
9
Example
Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output
0
1
1
3
1
9 | instruction | 0 | 14,982 | 23 | 29,964 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(10 ** 7)
def dfs(y, x):
if not (0 <= y < h) or not (0 <= x < w) or not L[y][x]:
return
else:
L[y][x] = 0
dy = [1, 1, 1, 0, 0, -1, -1, -1]
dx = [-1, 0, 1, -1, 1, -1, 0, 1]
for i in range(8):
ny = y + dy[i]
nx = x + dx[i]
dfs(ny, nx)
while True:
w, h = map(int, input().split())
if w == h == 0:
break
L = [list(map(int, input().split())) for _ in range(h)]
cnt = 0
for i in range(h):
for j in range(w):
if L[i][j]:
cnt += 1
dfs(i, j)
print(cnt)
``` | output | 1 | 14,982 | 23 | 29,965 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a marine area map that is a mesh of squares, each representing either a land or sea area. Figure B-1 is an example of a map.
<image>
Figure B-1: A marine area map
You can walk from a square land area to another if they are horizontally, vertically, or diagonally adjacent to each other on the map. Two areas are on the same island if and only if you can walk from one to the other possibly through other land areas. The marine area on the map is surrounded by the sea and therefore you cannot go outside of the area on foot.
You are requested to write a program that reads the map and counts the number of islands on it. For instance, the map in Figure B-1 includes three islands.
Input
The input consists of a series of datasets, each being in the following format.
> w h
> c1,1 c1,2 ... c1,w
> c2,1 c2,2 ... c2,w
> ...
> ch,1 ch,2 ... ch,w
>
w and h are positive integers no more than 50 that represent the width and the height of the given map, respectively. In other words, the map consists of w×h squares of the same size. w and h are separated by a single space.
ci, j is either 0 or 1 and delimited by a single space. If ci, j = 0, the square that is the i-th from the left and j-th from the top on the map represents a sea area. Otherwise, that is, if ci, j = 1, it represents a land area.
The end of the input is indicated by a line containing two zeros separated by a single space.
Output
For each dataset, output the number of the islands in a line. No extra characters should occur in the output.
Sample Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output for the Sample Input
0
1
1
3
1
9
Example
Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output
0
1
1
3
1
9 | instruction | 0 | 14,983 | 23 | 29,966 |
"Correct Solution:
```
# 25
import sys
import itertools
sys.setrecursionlimit(10**7) #再帰関数の呼び出し制限
while True:
w, h = map(int, input().split())
if w == 0 and h == 0:
break
c_l = [[int(x) for x in input().split()] for y in range(h)]
s_l = [[True] * w for x in range(h)]
v_l = list(itertools.product([-1,0,1],repeat=2))
def dfs(y, x):
if x < 0 or y < 0 or x >=w or y >= h:
return False
if not s_l[y][x]:
return False
s_l[y][x] = False
_c = c_l[y][x]
if _c == 0:
return False
for _v in v_l:
dfs(y+_v[0],x+_v[1])
return True
ans = 0
for i in range(h):
for j in range(w):
if s_l[i][j]:
if dfs(i, j):
ans += 1
print(ans)
``` | output | 1 | 14,983 | 23 | 29,967 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a marine area map that is a mesh of squares, each representing either a land or sea area. Figure B-1 is an example of a map.
<image>
Figure B-1: A marine area map
You can walk from a square land area to another if they are horizontally, vertically, or diagonally adjacent to each other on the map. Two areas are on the same island if and only if you can walk from one to the other possibly through other land areas. The marine area on the map is surrounded by the sea and therefore you cannot go outside of the area on foot.
You are requested to write a program that reads the map and counts the number of islands on it. For instance, the map in Figure B-1 includes three islands.
Input
The input consists of a series of datasets, each being in the following format.
> w h
> c1,1 c1,2 ... c1,w
> c2,1 c2,2 ... c2,w
> ...
> ch,1 ch,2 ... ch,w
>
w and h are positive integers no more than 50 that represent the width and the height of the given map, respectively. In other words, the map consists of w×h squares of the same size. w and h are separated by a single space.
ci, j is either 0 or 1 and delimited by a single space. If ci, j = 0, the square that is the i-th from the left and j-th from the top on the map represents a sea area. Otherwise, that is, if ci, j = 1, it represents a land area.
The end of the input is indicated by a line containing two zeros separated by a single space.
Output
For each dataset, output the number of the islands in a line. No extra characters should occur in the output.
Sample Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output for the Sample Input
0
1
1
3
1
9
Example
Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output
0
1
1
3
1
9 | instruction | 0 | 14,984 | 23 | 29,968 |
"Correct Solution:
```
from collections import deque
while True:
w,h=map(int,input().split())
if w==0 and h==0:
exit()
field=[input().split() for i in range(h)]
option=deque()
for i in range(h):
for j in range(w):
if field[i][j]=="1":
option.append([i,j])
break
else:
continue
break
completed=[[0]*w for i in range(h)]
cnt=1
while option:
y,x=option.pop()
completed[y][x]=cnt
for dy,dx in ((-1,0),(1,0),(0,-1),(0,1),(-1,-1),(1,-1),(-1,1),(1,1)):
if 0<=y+dy<=h-1 and 0<=x+dx<=w-1 and field[y+dy][x+dx]=="1" and completed[y+dy][x+dx]==0:
ny=y+dy
nx=x+dx
option.append([ny,nx])
if len(option)==0:
for i in range(h):
for j in range(w):
if field[i][j]=="1" and completed[i][j]==0:
option.append([i,j])
cnt+=1
break
else:
continue
break
ans=0
for i in completed:
tmp=max(i)
ans=max(ans,tmp)
print(ans)
``` | output | 1 | 14,984 | 23 | 29,969 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a marine area map that is a mesh of squares, each representing either a land or sea area. Figure B-1 is an example of a map.
<image>
Figure B-1: A marine area map
You can walk from a square land area to another if they are horizontally, vertically, or diagonally adjacent to each other on the map. Two areas are on the same island if and only if you can walk from one to the other possibly through other land areas. The marine area on the map is surrounded by the sea and therefore you cannot go outside of the area on foot.
You are requested to write a program that reads the map and counts the number of islands on it. For instance, the map in Figure B-1 includes three islands.
Input
The input consists of a series of datasets, each being in the following format.
> w h
> c1,1 c1,2 ... c1,w
> c2,1 c2,2 ... c2,w
> ...
> ch,1 ch,2 ... ch,w
>
w and h are positive integers no more than 50 that represent the width and the height of the given map, respectively. In other words, the map consists of w×h squares of the same size. w and h are separated by a single space.
ci, j is either 0 or 1 and delimited by a single space. If ci, j = 0, the square that is the i-th from the left and j-th from the top on the map represents a sea area. Otherwise, that is, if ci, j = 1, it represents a land area.
The end of the input is indicated by a line containing two zeros separated by a single space.
Output
For each dataset, output the number of the islands in a line. No extra characters should occur in the output.
Sample Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output for the Sample Input
0
1
1
3
1
9
Example
Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output
0
1
1
3
1
9 | instruction | 0 | 14,985 | 23 | 29,970 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(200000)
readline = sys.stdin.buffer.readline
def dfs(C, h, w):
# 一度訪ねた陸地は'0'(海)に置き換える
C[h][w] = '0'
for i in range(-1, 2):
for j in range(-1, 2):
if 0 <= h+i < len(C) and 0 <= w+j < len(C[0]) and C[h+i][w+j] == '1':
dfs(C, h+i, w+j)
W, H = 1, 1
while W != 0 or H != 0:
W, H = map(int, input().split())
C = []
for h in range(H):
c = list(input().split())
#c = readline().split()
C.append(c)
count = 0
for h in range(H):
for w in range(W):
if C[h][w] == '1':
dfs(C, h, w)
count += 1
if W != 0 or H != 0:
print(count)
``` | output | 1 | 14,985 | 23 | 29,971 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a marine area map that is a mesh of squares, each representing either a land or sea area. Figure B-1 is an example of a map.
<image>
Figure B-1: A marine area map
You can walk from a square land area to another if they are horizontally, vertically, or diagonally adjacent to each other on the map. Two areas are on the same island if and only if you can walk from one to the other possibly through other land areas. The marine area on the map is surrounded by the sea and therefore you cannot go outside of the area on foot.
You are requested to write a program that reads the map and counts the number of islands on it. For instance, the map in Figure B-1 includes three islands.
Input
The input consists of a series of datasets, each being in the following format.
> w h
> c1,1 c1,2 ... c1,w
> c2,1 c2,2 ... c2,w
> ...
> ch,1 ch,2 ... ch,w
>
w and h are positive integers no more than 50 that represent the width and the height of the given map, respectively. In other words, the map consists of w×h squares of the same size. w and h are separated by a single space.
ci, j is either 0 or 1 and delimited by a single space. If ci, j = 0, the square that is the i-th from the left and j-th from the top on the map represents a sea area. Otherwise, that is, if ci, j = 1, it represents a land area.
The end of the input is indicated by a line containing two zeros separated by a single space.
Output
For each dataset, output the number of the islands in a line. No extra characters should occur in the output.
Sample Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output for the Sample Input
0
1
1
3
1
9
Example
Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output
0
1
1
3
1
9 | instruction | 0 | 14,986 | 23 | 29,972 |
"Correct Solution:
```
def solve():
from sys import stdin, setrecursionlimit
setrecursionlimit(4000)
f_i = stdin
def dfs(pos):
area_map[pos] = '0'
for mv in move:
next_pos = pos + mv
if area_map[next_pos] == '1':
dfs(next_pos)
while True:
w, h = map(int, f_i.readline().split())
if w == 0:
break
area_map = ['0'] * (w + 2)
for i in range(h):
area_map += ['0'] + f_i.readline().split() + ['0']
area_map += ['0'] * (w + 2)
move = (1, -1, w + 1, w + 2, w + 3, -w - 3, -w - 2, -w - 1)
ans = 0
for i in range((w + 2) * (h + 2)):
if area_map[i] == '1':
dfs(i)
ans += 1
print(ans)
solve()
``` | output | 1 | 14,986 | 23 | 29,973 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a marine area map that is a mesh of squares, each representing either a land or sea area. Figure B-1 is an example of a map.
<image>
Figure B-1: A marine area map
You can walk from a square land area to another if they are horizontally, vertically, or diagonally adjacent to each other on the map. Two areas are on the same island if and only if you can walk from one to the other possibly through other land areas. The marine area on the map is surrounded by the sea and therefore you cannot go outside of the area on foot.
You are requested to write a program that reads the map and counts the number of islands on it. For instance, the map in Figure B-1 includes three islands.
Input
The input consists of a series of datasets, each being in the following format.
> w h
> c1,1 c1,2 ... c1,w
> c2,1 c2,2 ... c2,w
> ...
> ch,1 ch,2 ... ch,w
>
w and h are positive integers no more than 50 that represent the width and the height of the given map, respectively. In other words, the map consists of w×h squares of the same size. w and h are separated by a single space.
ci, j is either 0 or 1 and delimited by a single space. If ci, j = 0, the square that is the i-th from the left and j-th from the top on the map represents a sea area. Otherwise, that is, if ci, j = 1, it represents a land area.
The end of the input is indicated by a line containing two zeros separated by a single space.
Output
For each dataset, output the number of the islands in a line. No extra characters should occur in the output.
Sample Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output for the Sample Input
0
1
1
3
1
9
Example
Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output
0
1
1
3
1
9 | instruction | 0 | 14,987 | 23 | 29,974 |
"Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
def resolve():
while True:
w, h = map(int, input().split())
if w==h==0:
break
c = [list(map(int, input().split())) for _ in range(h)]
stk = []
visited = [[False]*w for _ in range(h)]
dir = ((0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1))
ans = 0
for i in range(h):
for j in range(w):
if c[i][j]==1 and not visited[i][j]:
stk.append((i, j))
while len(stk)>0:
a = stk.pop()
visited[a[0]][a[1]] = True
for d in dir:
ad = (a[0]+d[0], a[1]+d[1])
if 0<=ad[0]<h and 0<=ad[1]<w and c[ad[0]][ad[1]]==1 and not visited[ad[0]][ad[1]]:
stk.append(ad)
ans += 1
print(ans)
if __name__ == '__main__':
resolve()
``` | output | 1 | 14,987 | 23 | 29,975 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a marine area map that is a mesh of squares, each representing either a land or sea area. Figure B-1 is an example of a map.
<image>
Figure B-1: A marine area map
You can walk from a square land area to another if they are horizontally, vertically, or diagonally adjacent to each other on the map. Two areas are on the same island if and only if you can walk from one to the other possibly through other land areas. The marine area on the map is surrounded by the sea and therefore you cannot go outside of the area on foot.
You are requested to write a program that reads the map and counts the number of islands on it. For instance, the map in Figure B-1 includes three islands.
Input
The input consists of a series of datasets, each being in the following format.
> w h
> c1,1 c1,2 ... c1,w
> c2,1 c2,2 ... c2,w
> ...
> ch,1 ch,2 ... ch,w
>
w and h are positive integers no more than 50 that represent the width and the height of the given map, respectively. In other words, the map consists of w×h squares of the same size. w and h are separated by a single space.
ci, j is either 0 or 1 and delimited by a single space. If ci, j = 0, the square that is the i-th from the left and j-th from the top on the map represents a sea area. Otherwise, that is, if ci, j = 1, it represents a land area.
The end of the input is indicated by a line containing two zeros separated by a single space.
Output
For each dataset, output the number of the islands in a line. No extra characters should occur in the output.
Sample Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output for the Sample Input
0
1
1
3
1
9
Example
Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output
0
1
1
3
1
9 | instruction | 0 | 14,988 | 23 | 29,976 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(10 ** 7)
def dfs(h, w, grid):
grid[h][w] = 0
# 八方向を探索
for dh in range(-1, 2):
for dw in range(-1, 2):
nh = dh + h
nw = dw + w
# 場外だった場合はするー(番兵)
if nh < 0 or nw < 0:
continue
if grid[nh][nw] == 0:
continue
# 次に進む
dfs(nh, nw, grid)
while True:
grid = []
W, H = map(int, input().split())
if W == 0 and H == 0:
break
grid.append([0] * (W+2))
grid += [[0] + list(map(int, input().split())) + [0] for _ in range(H)]
grid.append([0] * (W+2))
cnt = 0
for h in range(1, H+1):
for w in range(1, W+1):
if grid[h][w] == 0:
continue
dfs(h, w, grid)
cnt += 1
print(cnt)
``` | output | 1 | 14,988 | 23 | 29,977 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a marine area map that is a mesh of squares, each representing either a land or sea area. Figure B-1 is an example of a map.
<image>
Figure B-1: A marine area map
You can walk from a square land area to another if they are horizontally, vertically, or diagonally adjacent to each other on the map. Two areas are on the same island if and only if you can walk from one to the other possibly through other land areas. The marine area on the map is surrounded by the sea and therefore you cannot go outside of the area on foot.
You are requested to write a program that reads the map and counts the number of islands on it. For instance, the map in Figure B-1 includes three islands.
Input
The input consists of a series of datasets, each being in the following format.
> w h
> c1,1 c1,2 ... c1,w
> c2,1 c2,2 ... c2,w
> ...
> ch,1 ch,2 ... ch,w
>
w and h are positive integers no more than 50 that represent the width and the height of the given map, respectively. In other words, the map consists of w×h squares of the same size. w and h are separated by a single space.
ci, j is either 0 or 1 and delimited by a single space. If ci, j = 0, the square that is the i-th from the left and j-th from the top on the map represents a sea area. Otherwise, that is, if ci, j = 1, it represents a land area.
The end of the input is indicated by a line containing two zeros separated by a single space.
Output
For each dataset, output the number of the islands in a line. No extra characters should occur in the output.
Sample Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output for the Sample Input
0
1
1
3
1
9
Example
Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output
0
1
1
3
1
9
Submitted Solution:
```
import sys
sys.setrecursionlimit(10**5)
def erase(x, y):
c[y][x] = '0'
for dx, dy in ((1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)):
nx, ny = x + dx, y + dy
if 0 <= nx < w and 0 <= ny < h and c[ny][nx] == '1':
erase(nx, ny)
while True:
w, h = map(int, input().split())
if w == h == 0:
break
c = [[i for i in input().split()] for _ in range(h)]
ans = 0
for y in range(h):
for x in range(w):
if c[y][x] == '1':
ans += 1
erase(x, y)
print(ans)
``` | instruction | 0 | 14,989 | 23 | 29,978 |
Yes | output | 1 | 14,989 | 23 | 29,979 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a marine area map that is a mesh of squares, each representing either a land or sea area. Figure B-1 is an example of a map.
<image>
Figure B-1: A marine area map
You can walk from a square land area to another if they are horizontally, vertically, or diagonally adjacent to each other on the map. Two areas are on the same island if and only if you can walk from one to the other possibly through other land areas. The marine area on the map is surrounded by the sea and therefore you cannot go outside of the area on foot.
You are requested to write a program that reads the map and counts the number of islands on it. For instance, the map in Figure B-1 includes three islands.
Input
The input consists of a series of datasets, each being in the following format.
> w h
> c1,1 c1,2 ... c1,w
> c2,1 c2,2 ... c2,w
> ...
> ch,1 ch,2 ... ch,w
>
w and h are positive integers no more than 50 that represent the width and the height of the given map, respectively. In other words, the map consists of w×h squares of the same size. w and h are separated by a single space.
ci, j is either 0 or 1 and delimited by a single space. If ci, j = 0, the square that is the i-th from the left and j-th from the top on the map represents a sea area. Otherwise, that is, if ci, j = 1, it represents a land area.
The end of the input is indicated by a line containing two zeros separated by a single space.
Output
For each dataset, output the number of the islands in a line. No extra characters should occur in the output.
Sample Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output for the Sample Input
0
1
1
3
1
9
Example
Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output
0
1
1
3
1
9
Submitted Solution:
```
def bfs(field, start_i, start_j, w, h):
OFFSETS = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
queue = [(start_i,start_j)]
while len(queue) > 0:
i, j = queue.pop()
field[i][j] = "0"
for di, dj in OFFSETS:
if i+di < 0 or i+di >= h:
continue
if j+dj < 0 or j+dj >= w:
continue
if field[i+di][j+dj] == "1":
queue.append((i+di, j+dj))
def main():
while True:
w, h = [int(s) for s in input().strip().split()]
if w == 0 and h == 0:
break
num_island = 0
field = []
for _ in range(h):
field.append(input().strip().split())
#print(field)
for i in range(h):
for j in range(w):
if field[i][j] == "1":
num_island += 1
bfs(field, i, j, w, h)
print(num_island)
if __name__ == "__main__":
main()
``` | instruction | 0 | 14,990 | 23 | 29,980 |
Yes | output | 1 | 14,990 | 23 | 29,981 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a marine area map that is a mesh of squares, each representing either a land or sea area. Figure B-1 is an example of a map.
<image>
Figure B-1: A marine area map
You can walk from a square land area to another if they are horizontally, vertically, or diagonally adjacent to each other on the map. Two areas are on the same island if and only if you can walk from one to the other possibly through other land areas. The marine area on the map is surrounded by the sea and therefore you cannot go outside of the area on foot.
You are requested to write a program that reads the map and counts the number of islands on it. For instance, the map in Figure B-1 includes three islands.
Input
The input consists of a series of datasets, each being in the following format.
> w h
> c1,1 c1,2 ... c1,w
> c2,1 c2,2 ... c2,w
> ...
> ch,1 ch,2 ... ch,w
>
w and h are positive integers no more than 50 that represent the width and the height of the given map, respectively. In other words, the map consists of w×h squares of the same size. w and h are separated by a single space.
ci, j is either 0 or 1 and delimited by a single space. If ci, j = 0, the square that is the i-th from the left and j-th from the top on the map represents a sea area. Otherwise, that is, if ci, j = 1, it represents a land area.
The end of the input is indicated by a line containing two zeros separated by a single space.
Output
For each dataset, output the number of the islands in a line. No extra characters should occur in the output.
Sample Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output for the Sample Input
0
1
1
3
1
9
Example
Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output
0
1
1
3
1
9
Submitted Solution:
```
# coding: utf-8
import sys
sys.setrecursionlimit(1000000)
class DFSSolver:
def __init__(self, table, h, w):
self.table = table
self.count = 0
self.h = h
self.w = w
def delta(self, i, j):
candididate = [(i-1, j-1), (i-1, j), (i-1, j+1),
(i, j-1), (i, j+1),
(i+1, j-1), (i+1, j), (i+1, j+1)]
return candididate
def dfs(self, i, j):
self.table[i][j] = 0
for i, j in self.delta(i, j):
if i < 0 or j < 0 or i >= self.h or j >= self.w:
pass
elif self.table[i][j] == 1:
self.dfs(i, j)
def solve(self):
for i in range(self.h):
for j in range(self.w):
if self.table[i][j] == 1:
self.dfs(i, j)
self.count += 1
print(self.count)
W, H = list(map(int, input().split(" ")))
while W != 0 and H != 0:
t = []
for _ in range(H):
t.append(list(map(int, input().split(" "))))
d = DFSSolver(t, H, W)
d.solve()
W, H = list(map(int, input().split(" ")))
``` | instruction | 0 | 14,991 | 23 | 29,982 |
Yes | output | 1 | 14,991 | 23 | 29,983 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a marine area map that is a mesh of squares, each representing either a land or sea area. Figure B-1 is an example of a map.
<image>
Figure B-1: A marine area map
You can walk from a square land area to another if they are horizontally, vertically, or diagonally adjacent to each other on the map. Two areas are on the same island if and only if you can walk from one to the other possibly through other land areas. The marine area on the map is surrounded by the sea and therefore you cannot go outside of the area on foot.
You are requested to write a program that reads the map and counts the number of islands on it. For instance, the map in Figure B-1 includes three islands.
Input
The input consists of a series of datasets, each being in the following format.
> w h
> c1,1 c1,2 ... c1,w
> c2,1 c2,2 ... c2,w
> ...
> ch,1 ch,2 ... ch,w
>
w and h are positive integers no more than 50 that represent the width and the height of the given map, respectively. In other words, the map consists of w×h squares of the same size. w and h are separated by a single space.
ci, j is either 0 or 1 and delimited by a single space. If ci, j = 0, the square that is the i-th from the left and j-th from the top on the map represents a sea area. Otherwise, that is, if ci, j = 1, it represents a land area.
The end of the input is indicated by a line containing two zeros separated by a single space.
Output
For each dataset, output the number of the islands in a line. No extra characters should occur in the output.
Sample Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output for the Sample Input
0
1
1
3
1
9
Example
Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output
0
1
1
3
1
9
Submitted Solution:
```
# http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1160&lang=jp
import sys
read = sys.stdin.read
readline = sys.stdin.readline
def main():
ans = []
while True:
w, h = map(int, readline().split())
if w == 0:
break
c = [[0] * (w+2)]
for _ in range(h):
c.append([0] + [int(i) for i in readline().split()] + [0])
c.append([0] * (w+2))
cnt = 0
seen = [[-1] * (w+2) for _ in range(h+2)]
def dfs(sx, sy):
stack = [(sx, sy)]
while stack:
x, y = stack.pop()
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
if dx == 0 and dy == 0:
continue
nx = x + dx
ny = y + dy
if c[nx][ny] and seen[nx][ny] == -1:
seen[nx][ny] = 1
stack.append((nx, ny))
for i in range(1,h+1):
for j in range(1,w+1):
if c[i][j] and seen[i][j] == -1:
cnt += 1
dfs(i, j)
ans.append(cnt)
print("\n".join(map(str, ans)))
if __name__ == "__main__":
main()
``` | instruction | 0 | 14,992 | 23 | 29,984 |
Yes | output | 1 | 14,992 | 23 | 29,985 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a marine area map that is a mesh of squares, each representing either a land or sea area. Figure B-1 is an example of a map.
<image>
Figure B-1: A marine area map
You can walk from a square land area to another if they are horizontally, vertically, or diagonally adjacent to each other on the map. Two areas are on the same island if and only if you can walk from one to the other possibly through other land areas. The marine area on the map is surrounded by the sea and therefore you cannot go outside of the area on foot.
You are requested to write a program that reads the map and counts the number of islands on it. For instance, the map in Figure B-1 includes three islands.
Input
The input consists of a series of datasets, each being in the following format.
> w h
> c1,1 c1,2 ... c1,w
> c2,1 c2,2 ... c2,w
> ...
> ch,1 ch,2 ... ch,w
>
w and h are positive integers no more than 50 that represent the width and the height of the given map, respectively. In other words, the map consists of w×h squares of the same size. w and h are separated by a single space.
ci, j is either 0 or 1 and delimited by a single space. If ci, j = 0, the square that is the i-th from the left and j-th from the top on the map represents a sea area. Otherwise, that is, if ci, j = 1, it represents a land area.
The end of the input is indicated by a line containing two zeros separated by a single space.
Output
For each dataset, output the number of the islands in a line. No extra characters should occur in the output.
Sample Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output for the Sample Input
0
1
1
3
1
9
Example
Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output
0
1
1
3
1
9
Submitted Solution:
```
def dfs(w,h,W,H,ID,islands,islandsID):
if islands[h][w]==1 and islandsID[h][w]!=0:
for i in range(-1,2):
for j in range(-1,2):
dw=w+i
dh=h+j
if dw>=0 and dw<W and dh>=0 and dh<H:
if islands[dh][dw]==1:
islandsID[dh][dw]=islandsID[h][w]
if islands[h][w]==1 and islandsID[h][w]==0:
for i in range(-1,2):
for j in range(-1,2):
dw=w+i
dh=h+j
if dw>=0 and dw<W and dh>=0 and dh<H:
if islands[dh][dw]==1:
islandsID[dh][dw]=ID
ID+=1
return ID
while True:
islands=[]
islandsID=[]
ID=1
W,H=map(int,input().split())
if W==0:
break
for i in range(H):
islandsID.append([0 for j in range(W)])
for _ in range(H):
islands.append(list(map(int,input().split())))
for h in range(H):
for w in range(W):
ID=dfs(w,h,W,H,ID,islands,islandsID)
print(ID-1)
``` | instruction | 0 | 14,993 | 23 | 29,986 |
No | output | 1 | 14,993 | 23 | 29,987 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a marine area map that is a mesh of squares, each representing either a land or sea area. Figure B-1 is an example of a map.
<image>
Figure B-1: A marine area map
You can walk from a square land area to another if they are horizontally, vertically, or diagonally adjacent to each other on the map. Two areas are on the same island if and only if you can walk from one to the other possibly through other land areas. The marine area on the map is surrounded by the sea and therefore you cannot go outside of the area on foot.
You are requested to write a program that reads the map and counts the number of islands on it. For instance, the map in Figure B-1 includes three islands.
Input
The input consists of a series of datasets, each being in the following format.
> w h
> c1,1 c1,2 ... c1,w
> c2,1 c2,2 ... c2,w
> ...
> ch,1 ch,2 ... ch,w
>
w and h are positive integers no more than 50 that represent the width and the height of the given map, respectively. In other words, the map consists of w×h squares of the same size. w and h are separated by a single space.
ci, j is either 0 or 1 and delimited by a single space. If ci, j = 0, the square that is the i-th from the left and j-th from the top on the map represents a sea area. Otherwise, that is, if ci, j = 1, it represents a land area.
The end of the input is indicated by a line containing two zeros separated by a single space.
Output
For each dataset, output the number of the islands in a line. No extra characters should occur in the output.
Sample Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output for the Sample Input
0
1
1
3
1
9
Example
Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output
0
1
1
3
1
9
Submitted Solution:
```
import sys
def solve():
while 1:
w, h = map(int, sys.stdin.readline().split())
if w == h == 0:
return
room = [[int(j) for j in sys.stdin.readline().split()] for i in range(h)]
cnt = 0
for i in range(h):
for j in range(w):
if room[i][j]:
cnt += 1
dfs(w, h, room, i, j)
print(cnt)
def dfs(w, h, room, i, j):
if i < 0 or i >= h or j < 0 or j >= w or (not room[i][j]):
return
room[i][j] = 0
dfs(w, h, room, i + 1, j)
dfs(w, h, room, i - 1, j)
dfs(w, h, room, i, j + 1)
dfs(w, h, room, i, j - 1)
dfs(w, h, room, i + 1, j + 1)
dfs(w, h, room, i + 1, j - 1)
dfs(w, h, room, i - 1, j + 1)
dfs(w, h, room, i - 1, j - 1)
if __name__ == '__main__':
solve()
``` | instruction | 0 | 14,994 | 23 | 29,988 |
No | output | 1 | 14,994 | 23 | 29,989 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a marine area map that is a mesh of squares, each representing either a land or sea area. Figure B-1 is an example of a map.
<image>
Figure B-1: A marine area map
You can walk from a square land area to another if they are horizontally, vertically, or diagonally adjacent to each other on the map. Two areas are on the same island if and only if you can walk from one to the other possibly through other land areas. The marine area on the map is surrounded by the sea and therefore you cannot go outside of the area on foot.
You are requested to write a program that reads the map and counts the number of islands on it. For instance, the map in Figure B-1 includes three islands.
Input
The input consists of a series of datasets, each being in the following format.
> w h
> c1,1 c1,2 ... c1,w
> c2,1 c2,2 ... c2,w
> ...
> ch,1 ch,2 ... ch,w
>
w and h are positive integers no more than 50 that represent the width and the height of the given map, respectively. In other words, the map consists of w×h squares of the same size. w and h are separated by a single space.
ci, j is either 0 or 1 and delimited by a single space. If ci, j = 0, the square that is the i-th from the left and j-th from the top on the map represents a sea area. Otherwise, that is, if ci, j = 1, it represents a land area.
The end of the input is indicated by a line containing two zeros separated by a single space.
Output
For each dataset, output the number of the islands in a line. No extra characters should occur in the output.
Sample Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output for the Sample Input
0
1
1
3
1
9
Example
Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output
0
1
1
3
1
9
Submitted Solution:
```
def erase(x, y):
c[y][x] = '0'
for dx, dy in ((1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)):
nx, ny = x + dx, y + dy
if 0 <= nx <= w -1 and 0 <= ny <= h - 1:
if c[ny][nx] == '1':
erase(nx, ny)
while True:
w, h = map(int, input().split())
c = [[i for i in input().split()] for _ in range(h)]
ans = 0
for y in range(h):
for x in range(w):
if c[y][x] == '1':
ans += 1
erase(x, y)
print(ans)
``` | instruction | 0 | 14,995 | 23 | 29,990 |
No | output | 1 | 14,995 | 23 | 29,991 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a marine area map that is a mesh of squares, each representing either a land or sea area. Figure B-1 is an example of a map.
<image>
Figure B-1: A marine area map
You can walk from a square land area to another if they are horizontally, vertically, or diagonally adjacent to each other on the map. Two areas are on the same island if and only if you can walk from one to the other possibly through other land areas. The marine area on the map is surrounded by the sea and therefore you cannot go outside of the area on foot.
You are requested to write a program that reads the map and counts the number of islands on it. For instance, the map in Figure B-1 includes three islands.
Input
The input consists of a series of datasets, each being in the following format.
> w h
> c1,1 c1,2 ... c1,w
> c2,1 c2,2 ... c2,w
> ...
> ch,1 ch,2 ... ch,w
>
w and h are positive integers no more than 50 that represent the width and the height of the given map, respectively. In other words, the map consists of w×h squares of the same size. w and h are separated by a single space.
ci, j is either 0 or 1 and delimited by a single space. If ci, j = 0, the square that is the i-th from the left and j-th from the top on the map represents a sea area. Otherwise, that is, if ci, j = 1, it represents a land area.
The end of the input is indicated by a line containing two zeros separated by a single space.
Output
For each dataset, output the number of the islands in a line. No extra characters should occur in the output.
Sample Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output for the Sample Input
0
1
1
3
1
9
Example
Input
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
Output
0
1
1
3
1
9
Submitted Solution:
```
def fill(y,x):
global w,h,l
if 0<=y<h and 0<=x+1<w and l[y][x+1]==1:
l[y][x+1]=0
fill(y,x+1)
if 0<=y<h and 0<=x-1<w and l[y][x-1]==1:
l[y][x-1]=0
fill(y,x-1)
if 0<=y+1<h and 0<=x<w and l[y+1][x]==1:
l[y+1][x]=0
fill(y+1,x)
if 0<=y-1<h and 0<=x<w and l[y-1][x]==1:
l[y-1][x]=0
fill(y-1,x)
if 0<=y+1<h and 0<=x+1<w and l[y+1][x+1]==1:
l[y+1][x+1]=0
fill(y+1,x+1)
if 0<=y-1<h and 0<=x+1<w and l[y-1][x+1]==1:
l[y-1][x+1]=0
fill(y-1,x+1)
if 0<=y+1<h and 0<=x-1<w and l[y+1][x-1]==1:
l[y+1][x-1]=0
fill(y+1,x-1)
if 0<=y-1<h and 0<=x-1<w and l[y-1][x-1]==1:
l[y-1][x-1]=0
fill(y-1,x-1)
while 1:
w,h=map(int,input().split())
if not w and not h:break
l=[map(int,input().split()) for _ in range(h)]
cnt=0
while 1:
cds=[[i,j.index(1)] for (i,j) in enumerate(l) if 1 in j]
if not cds:
break
else:
y,x=cds[0]
l[y][x]=0
fill(y,x)
cnt+=1
print(cnt)
``` | instruction | 0 | 14,996 | 23 | 29,992 |
No | output | 1 | 14,996 | 23 | 29,993 |
Provide a correct Python 3 solution for this coding contest problem.
The configuration of three circles packed inside a triangle such that each circle is tangent to the other two circles and to two of the edges of the triangle has been studied by many mathematicians for more than two centuries. Existence and uniqueness of such circles for an arbitrary triangle are easy to prove. Many methods of numerical calculation or geometric construction of such circles from an arbitrarily given triangle have been discovered. Today, such circles are called the Malfatti circles.
Figure 7 illustrates an example. The Malfatti circles of the triangle with the vertices (20, 80), (-40, -20) and (120, -20) are approximately
* the circle with the center (24.281677, 45.219486) and the radius 21.565935,
* the circle with the center (3.110950, 4.409005) and the radius 24.409005, and
* the circle with the center (54.556724, 7.107493) and the radius 27.107493.
Figure 8 illustrates another example. The Malfatti circles of the triangle with the vertices (20, -20), (120, -20) and (-40, 80) are approximately
* the circle with the center (25.629089, −10.057956) and the radius 9.942044,
* the circle with the center (53.225883, −0.849435) and the radius 19.150565, and
* the circle with the center (19.701191, 19.203466) and the radius 19.913790.
Your mission is to write a program to calculate the radii of the Malfatti circles of the given triangles.
<image>
Input
The input is a sequence of datasets. A dataset is a line containing six integers x1, y1 , x2 , y2, x3 and y3 in this order, separated by a space. The coordinates of the vertices of the given triangle are (x1 , y1 ), (x2 , y2 ) and (x3 , y3 ), respectively. You can assume that the vertices form a triangle counterclockwise. You can also assume that the following two conditions hold.
* All of the coordinate values are greater than −1000 and less than 1000.
* None of the Malfatti circles of the triangle has a radius less than 0.1.
The end of the input is indicated by a line containing six zeros separated by a space.
Output
For each input dataset, three decimal fractions r1 , r2 and r3 should be printed in a line in this order separated by a space. The radii of the Malfatti circles nearest to the vertices with the coordinates (x1 , y1 ), (x2 , y2 ) and (x3 , y3 ) should be r1 , r2 and r3 , respectively.
None of the output values may have an error greater than 0.0001. No extra character should appear in the output.
Example
Input
20 80 -40 -20 120 -20
20 -20 120 -20 -40 80
0 0 1 0 0 1
0 0 999 1 -999 1
897 -916 847 -972 890 -925
999 999 -999 -998 -998 -999
-999 -999 999 -999 0 731
-999 -999 999 -464 -464 999
979 -436 -955 -337 157 -439
0 0 0 0 0 0
Output
21.565935 24.409005 27.107493
9.942044 19.150565 19.913790
0.148847 0.207107 0.207107
0.125125 0.499750 0.499750
0.373458 0.383897 0.100456
0.706768 0.353509 0.353509
365.638023 365.638023 365.601038
378.524085 378.605339 378.605339
21.895803 22.052921 5.895714 | instruction | 0 | 14,997 | 23 | 29,994 |
"Correct Solution:
```
from functools import reduce
import math
def length(p1, p2):
sub2 = [(a - b)**2 for a, b in zip(p1, p2)]
return math.sqrt(sum(sub2))
def r_center(lines):
lines_sum = reduce(lambda a, b: a + b, lines)
s = lines_sum / 2
area = math.sqrt(s * (s - lines[0]) * (s - lines[1]) * (s - lines[2]))
return 2 * area / (lines_sum)
def r_length(lines, r_center):
x = (lines[0] + lines[2] - lines[1]) / 2
b_l = math.sqrt(x**2 + r_center**2)
a_l = math.sqrt((lines[2] - x)**2 + r_center**2)
c_l = math.sqrt((lines[0] - x)**2 + r_center**2)
return [a_l, b_l, c_l]
while True:
positions = list(map(int, input().split()))
if reduce(lambda a, b: a | b, positions) == 0:
break
p1, p2, p3 = [[i, j] for i, j in zip(positions[::2], positions[1::2])]
lines = [length(a, b) for a, b in ((p1, p2), (p2, p3), (p3, p1))]
lines_sum = reduce(lambda a, b: a + b, lines)
r_c = r_center(lines)
round_half = lines_sum / 2
rc_len = r_length(lines, r_c)
r1 = r_c * (round_half + rc_len[0] - r_c - rc_len[1] -
rc_len[2]) / (2 * (round_half - lines[0]))
r2 = r_c * (round_half + rc_len[1] - r_c - rc_len[0] -
rc_len[2]) / (2 * (round_half - lines[1]))
r3 = r_c * (round_half + rc_len[2] - r_c - rc_len[1] -
rc_len[0]) / (2 * (round_half - lines[2]))
print(r2, r3, r1)
``` | output | 1 | 14,997 | 23 | 29,995 |
Provide a correct Python 3 solution for this coding contest problem.
The configuration of three circles packed inside a triangle such that each circle is tangent to the other two circles and to two of the edges of the triangle has been studied by many mathematicians for more than two centuries. Existence and uniqueness of such circles for an arbitrary triangle are easy to prove. Many methods of numerical calculation or geometric construction of such circles from an arbitrarily given triangle have been discovered. Today, such circles are called the Malfatti circles.
Figure 7 illustrates an example. The Malfatti circles of the triangle with the vertices (20, 80), (-40, -20) and (120, -20) are approximately
* the circle with the center (24.281677, 45.219486) and the radius 21.565935,
* the circle with the center (3.110950, 4.409005) and the radius 24.409005, and
* the circle with the center (54.556724, 7.107493) and the radius 27.107493.
Figure 8 illustrates another example. The Malfatti circles of the triangle with the vertices (20, -20), (120, -20) and (-40, 80) are approximately
* the circle with the center (25.629089, −10.057956) and the radius 9.942044,
* the circle with the center (53.225883, −0.849435) and the radius 19.150565, and
* the circle with the center (19.701191, 19.203466) and the radius 19.913790.
Your mission is to write a program to calculate the radii of the Malfatti circles of the given triangles.
<image>
Input
The input is a sequence of datasets. A dataset is a line containing six integers x1, y1 , x2 , y2, x3 and y3 in this order, separated by a space. The coordinates of the vertices of the given triangle are (x1 , y1 ), (x2 , y2 ) and (x3 , y3 ), respectively. You can assume that the vertices form a triangle counterclockwise. You can also assume that the following two conditions hold.
* All of the coordinate values are greater than −1000 and less than 1000.
* None of the Malfatti circles of the triangle has a radius less than 0.1.
The end of the input is indicated by a line containing six zeros separated by a space.
Output
For each input dataset, three decimal fractions r1 , r2 and r3 should be printed in a line in this order separated by a space. The radii of the Malfatti circles nearest to the vertices with the coordinates (x1 , y1 ), (x2 , y2 ) and (x3 , y3 ) should be r1 , r2 and r3 , respectively.
None of the output values may have an error greater than 0.0001. No extra character should appear in the output.
Example
Input
20 80 -40 -20 120 -20
20 -20 120 -20 -40 80
0 0 1 0 0 1
0 0 999 1 -999 1
897 -916 847 -972 890 -925
999 999 -999 -998 -998 -999
-999 -999 999 -999 0 731
-999 -999 999 -464 -464 999
979 -436 -955 -337 157 -439
0 0 0 0 0 0
Output
21.565935 24.409005 27.107493
9.942044 19.150565 19.913790
0.148847 0.207107 0.207107
0.125125 0.499750 0.499750
0.373458 0.383897 0.100456
0.706768 0.353509 0.353509
365.638023 365.638023 365.601038
378.524085 378.605339 378.605339
21.895803 22.052921 5.895714 | instruction | 0 | 14,998 | 23 | 29,996 |
"Correct Solution:
```
def solve():
from sys import stdin
file_input = stdin
while True:
x1, y1, x2, y2, x3, y3 = map(int, file_input.readline().split())
if x1 == y1 == x2 == y2 == 0:
break
A = x1 + y1 * 1j
B = x2 + y2 * 1j
C = x3 + y3 * 1j
a = abs(B - C)
b = abs(C - A)
c = abs(A - B)
s = (a + b + c) / 2
r = (s * (s - a) * (s - b) * (s - c)) ** 0.5 / s
D = (b * B + c * C) / (c + b)
BD = abs(D - B)
I = (BD * A + c * D) / (c + BD)
d = abs(A - I)
e = abs(B - I)
f = abs(C - I)
r1 = r / 2 / (s - a) * (s + d - r - e - f)
r2 = r / 2 / (s - b) * (s + e - r - d - f)
r3 = r / 2 / (s - c) * (s + f - r - d - e)
print(r1, r2, r3)
solve()
``` | output | 1 | 14,998 | 23 | 29,997 |
Provide a correct Python 3 solution for this coding contest problem.
The configuration of three circles packed inside a triangle such that each circle is tangent to the other two circles and to two of the edges of the triangle has been studied by many mathematicians for more than two centuries. Existence and uniqueness of such circles for an arbitrary triangle are easy to prove. Many methods of numerical calculation or geometric construction of such circles from an arbitrarily given triangle have been discovered. Today, such circles are called the Malfatti circles.
Figure 7 illustrates an example. The Malfatti circles of the triangle with the vertices (20, 80), (-40, -20) and (120, -20) are approximately
* the circle with the center (24.281677, 45.219486) and the radius 21.565935,
* the circle with the center (3.110950, 4.409005) and the radius 24.409005, and
* the circle with the center (54.556724, 7.107493) and the radius 27.107493.
Figure 8 illustrates another example. The Malfatti circles of the triangle with the vertices (20, -20), (120, -20) and (-40, 80) are approximately
* the circle with the center (25.629089, −10.057956) and the radius 9.942044,
* the circle with the center (53.225883, −0.849435) and the radius 19.150565, and
* the circle with the center (19.701191, 19.203466) and the radius 19.913790.
Your mission is to write a program to calculate the radii of the Malfatti circles of the given triangles.
<image>
Input
The input is a sequence of datasets. A dataset is a line containing six integers x1, y1 , x2 , y2, x3 and y3 in this order, separated by a space. The coordinates of the vertices of the given triangle are (x1 , y1 ), (x2 , y2 ) and (x3 , y3 ), respectively. You can assume that the vertices form a triangle counterclockwise. You can also assume that the following two conditions hold.
* All of the coordinate values are greater than −1000 and less than 1000.
* None of the Malfatti circles of the triangle has a radius less than 0.1.
The end of the input is indicated by a line containing six zeros separated by a space.
Output
For each input dataset, three decimal fractions r1 , r2 and r3 should be printed in a line in this order separated by a space. The radii of the Malfatti circles nearest to the vertices with the coordinates (x1 , y1 ), (x2 , y2 ) and (x3 , y3 ) should be r1 , r2 and r3 , respectively.
None of the output values may have an error greater than 0.0001. No extra character should appear in the output.
Example
Input
20 80 -40 -20 120 -20
20 -20 120 -20 -40 80
0 0 1 0 0 1
0 0 999 1 -999 1
897 -916 847 -972 890 -925
999 999 -999 -998 -998 -999
-999 -999 999 -999 0 731
-999 -999 999 -464 -464 999
979 -436 -955 -337 157 -439
0 0 0 0 0 0
Output
21.565935 24.409005 27.107493
9.942044 19.150565 19.913790
0.148847 0.207107 0.207107
0.125125 0.499750 0.499750
0.373458 0.383897 0.100456
0.706768 0.353509 0.353509
365.638023 365.638023 365.601038
378.524085 378.605339 378.605339
21.895803 22.052921 5.895714 | instruction | 0 | 14,999 | 23 | 29,998 |
"Correct Solution:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Problems 1301
Problem G: Malfatti Circles
"""
import math
def main():
while True:
x1, y1, x2, y2, x3, y3 = map(int,input().split())
if x1 == y1 == x2 == y2 == x3 == y3 == 0:
break
a = math.sqrt( (x2-x3)*(x2-x3) + (y2-y3)*(y2-y3) ) # aの長さ
b = math.sqrt( (x1-x3)*(x1-x3) + (y1-y3)*(y1-y3) ) # bの長さ
c = math.sqrt( (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) ) # cの長さ
cosA = round((b*b + c*c - a*a),10) / round(2*b*c,10) # 余弦定理
cosB = round((a*a + c*c - b*b),10) / round(2*a*c,10) # 余弦定理
cosC = round((a*a + b*b - c*c),6) / round(2*a*b,10) # 余弦定理
A = math.degrees(math.acos(cosA)) # bcの角度
B = math.degrees(math.acos(cosB)) # acの角度
C = math.degrees(math.acos(cosC)) # abの角度
S = 1/2*a*c*math.sin(math.radians(B)) # 三角形の面積
r = 2*S / (a+b+c) # 内接円半径
tanA4 = round(math.tan(math.radians(A)/4),10) # tan(A/4)
tanB4 = round(math.tan(math.radians(B)/4),10) # tan(B/4)
tanC4 = round(math.tan(math.radians(C)/4),10) # tan(C/4)
r1 = ((1+tanB4)*(1+tanC4))/(2*(1+tanA4))*r
r2 = ((1+tanC4)*(1+tanA4))/(2*(1+tanB4))*r
r3 = ((1+tanA4)*(1+tanB4))/(2*(1+tanC4))*r
print(r1, r2, r3)
if __name__ == "__main__":
main()
``` | output | 1 | 14,999 | 23 | 29,999 |
Provide a correct Python 3 solution for this coding contest problem.
The configuration of three circles packed inside a triangle such that each circle is tangent to the other two circles and to two of the edges of the triangle has been studied by many mathematicians for more than two centuries. Existence and uniqueness of such circles for an arbitrary triangle are easy to prove. Many methods of numerical calculation or geometric construction of such circles from an arbitrarily given triangle have been discovered. Today, such circles are called the Malfatti circles.
Figure 7 illustrates an example. The Malfatti circles of the triangle with the vertices (20, 80), (-40, -20) and (120, -20) are approximately
* the circle with the center (24.281677, 45.219486) and the radius 21.565935,
* the circle with the center (3.110950, 4.409005) and the radius 24.409005, and
* the circle with the center (54.556724, 7.107493) and the radius 27.107493.
Figure 8 illustrates another example. The Malfatti circles of the triangle with the vertices (20, -20), (120, -20) and (-40, 80) are approximately
* the circle with the center (25.629089, −10.057956) and the radius 9.942044,
* the circle with the center (53.225883, −0.849435) and the radius 19.150565, and
* the circle with the center (19.701191, 19.203466) and the radius 19.913790.
Your mission is to write a program to calculate the radii of the Malfatti circles of the given triangles.
<image>
Input
The input is a sequence of datasets. A dataset is a line containing six integers x1, y1 , x2 , y2, x3 and y3 in this order, separated by a space. The coordinates of the vertices of the given triangle are (x1 , y1 ), (x2 , y2 ) and (x3 , y3 ), respectively. You can assume that the vertices form a triangle counterclockwise. You can also assume that the following two conditions hold.
* All of the coordinate values are greater than −1000 and less than 1000.
* None of the Malfatti circles of the triangle has a radius less than 0.1.
The end of the input is indicated by a line containing six zeros separated by a space.
Output
For each input dataset, three decimal fractions r1 , r2 and r3 should be printed in a line in this order separated by a space. The radii of the Malfatti circles nearest to the vertices with the coordinates (x1 , y1 ), (x2 , y2 ) and (x3 , y3 ) should be r1 , r2 and r3 , respectively.
None of the output values may have an error greater than 0.0001. No extra character should appear in the output.
Example
Input
20 80 -40 -20 120 -20
20 -20 120 -20 -40 80
0 0 1 0 0 1
0 0 999 1 -999 1
897 -916 847 -972 890 -925
999 999 -999 -998 -998 -999
-999 -999 999 -999 0 731
-999 -999 999 -464 -464 999
979 -436 -955 -337 157 -439
0 0 0 0 0 0
Output
21.565935 24.409005 27.107493
9.942044 19.150565 19.913790
0.148847 0.207107 0.207107
0.125125 0.499750 0.499750
0.373458 0.383897 0.100456
0.706768 0.353509 0.353509
365.638023 365.638023 365.601038
378.524085 378.605339 378.605339
21.895803 22.052921 5.895714 | instruction | 0 | 15,000 | 23 | 30,000 |
"Correct Solution:
```
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
x1, y1, x2, y2, x3, y3 = map(int, readline().split())
if x1 == y1 == x2 == y2 == x3 == y3 == 0:
return False
d12 = ((x1-x2)**2 + (y1-y2)**2)**.5
d23 = ((x2-x3)**2 + (y2-y3)**2)**.5
d31 = ((x3-x1)**2 + (y3-y1)**2)**.5
e1 = ((x1, y1), ((x2-x1)/d12, (y2-y1)/d12), ((x3-x1)/d31, (y3-y1)/d31))
e2 = ((x2, y2), ((x3-x2)/d23, (y3-y2)/d23), ((x1-x2)/d12, (y1-y2)/d12))
e3 = ((x3, y3), ((x1-x3)/d31, (y1-y3)/d31), ((x2-x3)/d23, (y2-y3)/d23))
def calc(e, x):
p0, p1, p2 = e
x0, y0 = p0; x1, y1 = p1; x2, y2 = p2
xc = (x1 + x2)/2; yc = (y1 + y2)/2; dc = (xc**2 + yc**2)**.5
cv = (x1*xc + y1*yc)/dc
sv = (x1*yc - y1*xc)/dc
d = x / cv
return (x0 + xc * d / dc, y0 + yc * d / dc), x * sv / cv
EPS = 1e-8
def check(p0, r0):
x0, y0 = p0
left = 0; right = min(d12, d23)
while right - left > EPS:
mid = (left + right) / 2
(x1, y1), r1 = calc(e2, mid)
if (x0-x1)**2 + (y0-y1)**2 < (r0+r1)**2:
right = mid
else:
left = mid
(x1, y1), r1 = calc(e2, left)
left = 0; right = min(d23, d31)
while right - left > EPS:
mid = (left + right) / 2
(x2, y2), r2 = calc(e3, mid)
if (x0-x2)**2 + (y0-y2)**2 < (r0+r2)**2:
right = mid
else:
left = mid
(x2, y2), r2 = calc(e3, left)
return (x1-x2)**2 + (y1-y2)**2 < (r1+r2)**2, r1, r2
left = 0; right = min(d12, d31)
while right - left > EPS:
mid = (left + right) / 2
p0, r0 = calc(e1, mid)
if check(p0, r0)[0]:
left = mid
else:
right = mid
p0, r0 = calc(e1, right)
e, r1, r2 = check(p0, r0)
write("%.16f %.16f %.16f\n" % (r0, r1, r2))
return True
while solve():
...
``` | output | 1 | 15,000 | 23 | 30,001 |
Provide a correct Python 3 solution for this coding contest problem.
The configuration of three circles packed inside a triangle such that each circle is tangent to the other two circles and to two of the edges of the triangle has been studied by many mathematicians for more than two centuries. Existence and uniqueness of such circles for an arbitrary triangle are easy to prove. Many methods of numerical calculation or geometric construction of such circles from an arbitrarily given triangle have been discovered. Today, such circles are called the Malfatti circles.
Figure 7 illustrates an example. The Malfatti circles of the triangle with the vertices (20, 80), (-40, -20) and (120, -20) are approximately
* the circle with the center (24.281677, 45.219486) and the radius 21.565935,
* the circle with the center (3.110950, 4.409005) and the radius 24.409005, and
* the circle with the center (54.556724, 7.107493) and the radius 27.107493.
Figure 8 illustrates another example. The Malfatti circles of the triangle with the vertices (20, -20), (120, -20) and (-40, 80) are approximately
* the circle with the center (25.629089, −10.057956) and the radius 9.942044,
* the circle with the center (53.225883, −0.849435) and the radius 19.150565, and
* the circle with the center (19.701191, 19.203466) and the radius 19.913790.
Your mission is to write a program to calculate the radii of the Malfatti circles of the given triangles.
<image>
Input
The input is a sequence of datasets. A dataset is a line containing six integers x1, y1 , x2 , y2, x3 and y3 in this order, separated by a space. The coordinates of the vertices of the given triangle are (x1 , y1 ), (x2 , y2 ) and (x3 , y3 ), respectively. You can assume that the vertices form a triangle counterclockwise. You can also assume that the following two conditions hold.
* All of the coordinate values are greater than −1000 and less than 1000.
* None of the Malfatti circles of the triangle has a radius less than 0.1.
The end of the input is indicated by a line containing six zeros separated by a space.
Output
For each input dataset, three decimal fractions r1 , r2 and r3 should be printed in a line in this order separated by a space. The radii of the Malfatti circles nearest to the vertices with the coordinates (x1 , y1 ), (x2 , y2 ) and (x3 , y3 ) should be r1 , r2 and r3 , respectively.
None of the output values may have an error greater than 0.0001. No extra character should appear in the output.
Example
Input
20 80 -40 -20 120 -20
20 -20 120 -20 -40 80
0 0 1 0 0 1
0 0 999 1 -999 1
897 -916 847 -972 890 -925
999 999 -999 -998 -998 -999
-999 -999 999 -999 0 731
-999 -999 999 -464 -464 999
979 -436 -955 -337 157 -439
0 0 0 0 0 0
Output
21.565935 24.409005 27.107493
9.942044 19.150565 19.913790
0.148847 0.207107 0.207107
0.125125 0.499750 0.499750
0.373458 0.383897 0.100456
0.706768 0.353509 0.353509
365.638023 365.638023 365.601038
378.524085 378.605339 378.605339
21.895803 22.052921 5.895714 | instruction | 0 | 15,001 | 23 | 30,002 |
"Correct Solution:
```
import math
def length(x1, y1, x2, y2):
return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
while True:
p = list(map(int, input().split()))
if not list(filter(lambda x: x, p)):
break
a, b, c = length(p[0], p[1], p[2], p[3]), length(p[0], p[1], p[4], p[5]), length(p[2], p[3], p[4], p[5])
S = 0.5 * a * b * (1 - ((a ** 2 + b ** 2 - c ** 2) / (a * b * 2)) ** 2) ** 0.5
R = (2 * S) / (a + b + c)
s = (a + b + c) / 2
d = (((- a + b + c) / 2) ** 2 + R ** 2) ** 0.5
e = (((a - b + c) / 2) ** 2 + R ** 2) ** 0.5
f = (((a + b - c) / 2) ** 2 + R ** 2) ** 0.5
print(R / (2 * (s - c)) * (s + f - R - e - d), end=" ")
print(R / (2 * (s - b)) * (s + e - R - d - f), end=" ")
print(R / (2 * (s - a)) * (s + d - R - e - f))
``` | output | 1 | 15,001 | 23 | 30,003 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ujan has finally cleaned up his house and now wants to decorate the interior. He decided to place a beautiful carpet that would really tie the guest room together.
He is interested in carpets that are made up of polygonal patches such that each side of a patch is either a side of another (different) patch, or is an exterior side of the whole carpet. In other words, the carpet can be represented as a planar graph, where each patch corresponds to a face of the graph, each face is a simple polygon. The perimeter of the carpet is the number of the exterior sides.
Ujan considers a carpet beautiful if it consists of f patches, where the i-th patch has exactly a_i sides, and the perimeter is the smallest possible. Find an example of such a carpet, so that Ujan can order it!
Input
The first line of input contains a single integer f (1 ≤ f ≤ 10^5), the number of patches in the carpet.
The next line contains f integers a_1, …, a_f (3 ≤ a_i ≤ 3⋅ 10^5), the number of sides of the patches. The total number of the sides of the patches a_1 + … + a_f does not exceed 3⋅10^5.
Output
Output the description of the carpet as a graph.
First, output a single integer n (3 ≤ n ≤ 3 ⋅ 10^5), the total number of vertices in your graph (the vertices must be numbered from 1 to n).
Then output f lines containing the description of the faces. The i-th line should describe the i-th face and contain a_i distinct integers v_{i,1}, …, v_{i,a_i} (1 ≤ v_{i,j} ≤ n), which means that the vertices v_{i,j} and v_{i,(j mod{a_i})+1} are connected by an edge for any 1 ≤ j ≤ a_i.
The graph should be planar and satisfy the restrictions described in the problem statement. Its perimeter should be the smallest possible. There should be no double edges or self-loops in the graph. The graph should be connected. Note that a solution always exists; if there are multiple solutions, output any of them.
Examples
Input
2
3 3
Output
4
2 1 4
1 2 3
Input
3
5 3 5
Output
6
1 2 3 4 5
4 5 6
1 3 4 6 5
Note
In the first sample, the two triangular faces are connected by a single edge, which results in the minimum perimeter 4.
The figure shows one possible configuration for the second sample. The minimum perimeter in this case is 3.
<image>
Submitted Solution:
```
print('121232134')
``` | instruction | 0 | 15,180 | 23 | 30,360 |
No | output | 1 | 15,180 | 23 | 30,361 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Each segment has one of two colors: the i-th segment's color is t_i.
Let's call a pair of segments i and j bad if the following two conditions are met:
* t_i ≠ t_j;
* the segments [l_i, r_i] and [l_j, r_j] intersect, embed or touch, i. e. there exists an integer x such that x ∈ [l_i, r_i] and x ∈ [l_j, r_j].
Calculate the maximum number of segments that can be selected from the given ones, so that there is no bad pair among the selected ones.
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — number of segments.
The next n lines contains three integers l_i, r_i, t_i (1 ≤ l_i ≤ r_i ≤ 10^9; t_i ∈ \{1, 2\}) — description of the i-th segment.
Output
Print the maximum number of segments that can be selected, so that there is no bad pair among the selected segments.
Examples
Input
3
1 3 1
4 6 2
2 5 1
Output
2
Input
5
5 8 1
1 3 2
3 4 2
6 6 1
2 10 2
Output
4
Input
7
19 20 1
13 15 2
6 11 2
4 10 1
14 17 1
13 13 2
5 9 1
Output
5
Submitted Solution:
```
from sys import stdin
def gcd(x, y):
for i in range(2, int(x**0.5)+2):
if x % i == 0 and y % i == 0:
return gcd(x//i, y//i) * i
return 1
def choose2(n):
n = int(n)
if n <= 1:
return 0
return int(n * (n-1) / 2)
t = int(stdin.readline().strip())
for _ in range(t):
m,d,w = list(map(int, stdin.readline().strip().split(' ')))
# count 1 <= x < y <= min(m,d) s.t. w | (d-1)(y-x)
n = w / gcd(w, d-1)
m = min(m,d)
# count 1 <= x < y <= m s.t. n | (y-x)
ans = choose2((m//n)+1) * (m%n) + choose2(m//n) * (n-m%n)
if ans != int(ans):
raise "Shouldn't happen"
print(int(ans))
``` | instruction | 0 | 15,248 | 23 | 30,496 |
No | output | 1 | 15,248 | 23 | 30,497 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Each segment has one of two colors: the i-th segment's color is t_i.
Let's call a pair of segments i and j bad if the following two conditions are met:
* t_i ≠ t_j;
* the segments [l_i, r_i] and [l_j, r_j] intersect, embed or touch, i. e. there exists an integer x such that x ∈ [l_i, r_i] and x ∈ [l_j, r_j].
Calculate the maximum number of segments that can be selected from the given ones, so that there is no bad pair among the selected ones.
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — number of segments.
The next n lines contains three integers l_i, r_i, t_i (1 ≤ l_i ≤ r_i ≤ 10^9; t_i ∈ \{1, 2\}) — description of the i-th segment.
Output
Print the maximum number of segments that can be selected, so that there is no bad pair among the selected segments.
Examples
Input
3
1 3 1
4 6 2
2 5 1
Output
2
Input
5
5 8 1
1 3 2
3 4 2
6 6 1
2 10 2
Output
4
Input
7
19 20 1
13 15 2
6 11 2
4 10 1
14 17 1
13 13 2
5 9 1
Output
5
Submitted Solution:
```
n = int(input())
strips = []
for i in range(n):
strips.append(list(map(int, input().split())))
strips.sort(key = lambda a: a[1])
new_strips = []
for index, strip in enumerate(strips):
if index == 0:
new_strips.append(strip)
continue
prev = strips[index - 1]
if not (prev[1] > strip[0] and prev[2] != strip[2]):
new_strips.append(strip)
print(len(new_strips))
``` | instruction | 0 | 15,249 | 23 | 30,498 |
No | output | 1 | 15,249 | 23 | 30,499 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Each segment has one of two colors: the i-th segment's color is t_i.
Let's call a pair of segments i and j bad if the following two conditions are met:
* t_i ≠ t_j;
* the segments [l_i, r_i] and [l_j, r_j] intersect, embed or touch, i. e. there exists an integer x such that x ∈ [l_i, r_i] and x ∈ [l_j, r_j].
Calculate the maximum number of segments that can be selected from the given ones, so that there is no bad pair among the selected ones.
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — number of segments.
The next n lines contains three integers l_i, r_i, t_i (1 ≤ l_i ≤ r_i ≤ 10^9; t_i ∈ \{1, 2\}) — description of the i-th segment.
Output
Print the maximum number of segments that can be selected, so that there is no bad pair among the selected segments.
Examples
Input
3
1 3 1
4 6 2
2 5 1
Output
2
Input
5
5 8 1
1 3 2
3 4 2
6 6 1
2 10 2
Output
4
Input
7
19 20 1
13 15 2
6 11 2
4 10 1
14 17 1
13 13 2
5 9 1
Output
5
Submitted Solution:
```
from sys import stdin, stdout
import bisect
def main():
n = int(stdin.readline())
one_l = []
one_r = []
two_l = []
two_r = []
for _ in range(n):
a,b,z = list(map(int, stdin.readline().split()))
if z == 1:
one_l.append(a)
one_r.append(b)
else:
two_l.append(a)
two_r.append(b)
indexes = list(range(len(two_r)))
indexes.sort(key=two_r.__getitem__)
two_l = list(map(two_l.__getitem__, indexes))
two_r = list(map(two_r.__getitem__, indexes))
indexes = list(range(len(one_r)))
indexes.sort(key=one_r.__getitem__)
one_l = list(map(one_l.__getitem__, indexes))
one_r = list(map(one_r.__getitem__, indexes))
o,t = 0,0
mx = -1
val_dp = dict()
val_dp[0] = 0
val_bi = [0]
while o < len(one_l) or t < len(two_l):
if o == len(one_l):
while t < len(two_l):
left = two_l[t]
right = two_r[t]
pos = bisect.bisect_left(val_bi, left) - 1
pos_bi = val_bi[pos]
mx_val = val_dp[pos_bi]
addi = t - bisect.bisect_left(two_r, left) + 1
val_bi.append(right)
val_dp[right] = max(mx, mx_val+addi)
mx = max(mx, val_dp[right])
t+=1
continue
if t == len(two_l):
while o < len(one_l):
left = one_l[o]
right = one_r[o]
pos = bisect.bisect_left(val_bi, left) - 1
pos_bi = val_bi[pos]
mx_val = val_dp[pos_bi]
addi = o - bisect.bisect_left(one_r, left) + 1
val_bi.append(right)
val_dp[right] = max(mx, mx_val+addi)
mx = max(mx, val_dp[right])
o+=1
continue
is_p = False
while o < len(one_l) and one_r[o] <= two_r[t]:
is_p = True
left = one_l[o]
right = one_r[o]
pos = bisect.bisect_left(val_bi, left) - 1
pos_bi = val_bi[pos]
mx_val = val_dp[pos_bi]
addi = o - bisect.bisect_left(one_r, left) + 1
val_bi.append(right)
val_dp[right] = max(mx, mx_val+addi)
mx = max(mx, val_dp[right])
o+=1
if is_p:
continue
while t < len(two_l) and two_r[t] <= one_r[o]:
left = two_l[t]
right = two_r[t]
pos = bisect.bisect_left(val_bi, left) - 1
pos_bi = val_bi[pos]
mx_val = val_dp[pos_bi]
addi = t - bisect.bisect_left(two_r, left) + 1
val_bi.append(right)
val_dp[right] = max(mx, mx_val+addi)
mx = max(mx, val_dp[right])
t+=1
stdout.write(str(mx))
main()
``` | instruction | 0 | 15,250 | 23 | 30,500 |
No | output | 1 | 15,250 | 23 | 30,501 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Each segment has one of two colors: the i-th segment's color is t_i.
Let's call a pair of segments i and j bad if the following two conditions are met:
* t_i ≠ t_j;
* the segments [l_i, r_i] and [l_j, r_j] intersect, embed or touch, i. e. there exists an integer x such that x ∈ [l_i, r_i] and x ∈ [l_j, r_j].
Calculate the maximum number of segments that can be selected from the given ones, so that there is no bad pair among the selected ones.
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — number of segments.
The next n lines contains three integers l_i, r_i, t_i (1 ≤ l_i ≤ r_i ≤ 10^9; t_i ∈ \{1, 2\}) — description of the i-th segment.
Output
Print the maximum number of segments that can be selected, so that there is no bad pair among the selected segments.
Examples
Input
3
1 3 1
4 6 2
2 5 1
Output
2
Input
5
5 8 1
1 3 2
3 4 2
6 6 1
2 10 2
Output
4
Input
7
19 20 1
13 15 2
6 11 2
4 10 1
14 17 1
13 13 2
5 9 1
Output
5
Submitted Solution:
```
n = int(input())
strips = []
for i in range(n):
strips.append(list(map(int, input().split())))
strips.sort(key = lambda a: a[1])
new_strips = []
for index, strip in enumerate(strips):
if index == 0:
new_strips.append(strip)
continue
prev = new_strips[-1]
if not (prev[1] > strip[0] and prev[2] != strip[2]):
new_strips.append(strip)
print(len(new_strips))
``` | instruction | 0 | 15,251 | 23 | 30,502 |
No | output | 1 | 15,251 | 23 | 30,503 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow likes solving puzzles.
One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.
The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.
You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.
Input
The first line of input will contain two integers n and m (1 ≤ n, m ≤ 500), the dimensions of the puzzle piece.
The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space.
It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.
Output
Output "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.
Examples
Input
2 3
XXX
XXX
Output
YES
Input
2 2
.X
XX
Output
NO
Input
5 5
.....
..X..
.....
.....
.....
Output
YES
Note
For the first sample, one example of a rectangle we can form is as follows
111222
111222
For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.
In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle:
.....
..XX.
.....
.....
.....
| instruction | 0 | 15,573 | 23 | 31,146 |
Tags: implementation
Correct Solution:
```
m, n=[int(i) for i in input().split()]
started=False
failed=False
finished=False
t=[-5, -5]
blank="."*n
for i in range(m):
s=input()
# print(t, finished, started, failed, s)
if "X" in s:
if finished:
failed=True
break
if not started:
started=True
first=False
second=False
for j in range(len(s)):
if first:
if s[j]!="X":
second=True
t[1]=j
break
else:
if s[j]=="X":
first=True
t[0]=j
if not second:
t[1]=len(s)
#print(s, "."*t[0]+"X"*(t[1]-t[0])+"."*(n-t[1]))
if s!="."*t[0]+"X"*(t[1]-t[0])+"."*(n-t[1]):
failed=True
break
elif started:
finished=True
if failed:
print("NO")
else:
print("YES")
``` | output | 1 | 15,573 | 23 | 31,147 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow likes solving puzzles.
One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.
The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.
You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.
Input
The first line of input will contain two integers n and m (1 ≤ n, m ≤ 500), the dimensions of the puzzle piece.
The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space.
It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.
Output
Output "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.
Examples
Input
2 3
XXX
XXX
Output
YES
Input
2 2
.X
XX
Output
NO
Input
5 5
.....
..X..
.....
.....
.....
Output
YES
Note
For the first sample, one example of a rectangle we can form is as follows
111222
111222
For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.
In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle:
.....
..XX.
.....
.....
.....
| instruction | 0 | 15,574 | 23 | 31,148 |
Tags: implementation
Correct Solution:
```
n, m = map(int, input().split())
a = [input() for i in range(n)]
minx = m
miny = n
maxx = -1
maxy = -1
for i in range(n):
for j in range(m):
if a[i][j] == 'X':
if i > maxy:
maxy = i
if i < miny:
miny = i
if j > maxx:
maxx = j
if j < minx:
minx = j
for i in range(miny, maxy+1):
for j in range(minx, maxx+1):
if a[i][j] != 'X':
print('NO')
break
if a[i][j] != 'X':
break
else:
print('YES')
``` | output | 1 | 15,574 | 23 | 31,149 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow likes solving puzzles.
One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.
The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.
You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.
Input
The first line of input will contain two integers n and m (1 ≤ n, m ≤ 500), the dimensions of the puzzle piece.
The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space.
It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.
Output
Output "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.
Examples
Input
2 3
XXX
XXX
Output
YES
Input
2 2
.X
XX
Output
NO
Input
5 5
.....
..X..
.....
.....
.....
Output
YES
Note
For the first sample, one example of a rectangle we can form is as follows
111222
111222
For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.
In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle:
.....
..XX.
.....
.....
.....
| instruction | 0 | 15,575 | 23 | 31,150 |
Tags: implementation
Correct Solution:
```
#!/usr/bin/env python3
from sys import stdin,stdout
def ri():
return map(int, input().split())
n, m = ri()
found = 0
for i in range(n):
r = input()
if found == 0 and 'X' in r:
r0 = r
found = 1
continue
if found and 'X' in r:
if r != r0:
print("NO")
exit()
print("YES")
``` | output | 1 | 15,575 | 23 | 31,151 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow likes solving puzzles.
One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.
The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.
You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.
Input
The first line of input will contain two integers n and m (1 ≤ n, m ≤ 500), the dimensions of the puzzle piece.
The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space.
It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.
Output
Output "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.
Examples
Input
2 3
XXX
XXX
Output
YES
Input
2 2
.X
XX
Output
NO
Input
5 5
.....
..X..
.....
.....
.....
Output
YES
Note
For the first sample, one example of a rectangle we can form is as follows
111222
111222
For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.
In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle:
.....
..XX.
.....
.....
.....
| instruction | 0 | 15,576 | 23 | 31,152 |
Tags: implementation
Correct Solution:
```
n, m = map(int, input().split())
ss = ""
for i in range(n):
s = str(input())
if 'X' in s:
if ss == "":
ss = s
else:
if s == ss:
pass
else:
print("NO")
exit()
print("YES")
``` | output | 1 | 15,576 | 23 | 31,153 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow likes solving puzzles.
One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.
The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.
You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.
Input
The first line of input will contain two integers n and m (1 ≤ n, m ≤ 500), the dimensions of the puzzle piece.
The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space.
It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.
Output
Output "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.
Examples
Input
2 3
XXX
XXX
Output
YES
Input
2 2
.X
XX
Output
NO
Input
5 5
.....
..X..
.....
.....
.....
Output
YES
Note
For the first sample, one example of a rectangle we can form is as follows
111222
111222
For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.
In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle:
.....
..XX.
.....
.....
.....
| instruction | 0 | 15,577 | 23 | 31,154 |
Tags: implementation
Correct Solution:
```
def fail():
print('NO')
exit()
read = lambda: map(int, input().split())
n, m = read()
a = [input() for i in range(n)]
fst = None
for i in range(n):
for j in range(m):
if a[i][j] == 'X':
fst = i, j
break
if fst != None:
break
scd = None
for i in range(n - 1, -1, -1):
for j in range(m - 1, -1, -1):
if a[i][j] == 'X':
scd = i, j
break
if scd != None:
break
flag = True
for i in range(n):
for j in range(m):
if fst[0] <= i <= scd[0] and fst[1] <= j <= scd[1]:
if a[i][j] == '.':
fail()
else:
if a[i][j] == 'X':
fail()
print('YES')
``` | output | 1 | 15,577 | 23 | 31,155 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow likes solving puzzles.
One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.
The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.
You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.
Input
The first line of input will contain two integers n and m (1 ≤ n, m ≤ 500), the dimensions of the puzzle piece.
The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space.
It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.
Output
Output "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.
Examples
Input
2 3
XXX
XXX
Output
YES
Input
2 2
.X
XX
Output
NO
Input
5 5
.....
..X..
.....
.....
.....
Output
YES
Note
For the first sample, one example of a rectangle we can form is as follows
111222
111222
For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.
In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle:
.....
..XX.
.....
.....
.....
| instruction | 0 | 15,578 | 23 | 31,156 |
Tags: implementation
Correct Solution:
```
import sys
n, m = map(int, input().split())
a = [input() for _ in range(n)]
min_i, min_j = n, m
max_i, max_j = 0, 0
for i in range(n):
for j in range(m):
if a[i][j] == 'X':
min_i, min_j = min(min_i, i), min(min_j, j)
max_i, max_j = max(max_i, i), max(max_j, j)
for i in range(min_i, max_i + 1):
for j in range(min_j, max_j + 1):
if a[i][j] != 'X':
print("NO")
sys.exit(0)
print("YES")
``` | output | 1 | 15,578 | 23 | 31,157 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow likes solving puzzles.
One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.
The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.
You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.
Input
The first line of input will contain two integers n and m (1 ≤ n, m ≤ 500), the dimensions of the puzzle piece.
The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space.
It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.
Output
Output "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.
Examples
Input
2 3
XXX
XXX
Output
YES
Input
2 2
.X
XX
Output
NO
Input
5 5
.....
..X..
.....
.....
.....
Output
YES
Note
For the first sample, one example of a rectangle we can form is as follows
111222
111222
For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.
In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle:
.....
..XX.
.....
.....
.....
| instruction | 0 | 15,579 | 23 | 31,158 |
Tags: implementation
Correct Solution:
```
n, m = [int(i) for i in input().split()]
pattern_dict = dict()
pattern_0 = '.'*m
no_flag = False
for i in range(n):
s = input()
position = [j for j in range(m) if s[j]=='X']
if s != pattern_0:
if s not in pattern_dict:
pattern_dict[s] = [i]
else:
pattern_dict[s].append(i)
if len(pattern_dict) > 1 or position[-1]-position[0]+1 != len(position):
no_flag = True
print("NO")
break
if not no_flag:
for j in pattern_dict:
s = pattern_dict[j]
if s[-1]- s[0]+1 != len(s):
print("NO")
else:
print("YES")
``` | output | 1 | 15,579 | 23 | 31,159 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow likes solving puzzles.
One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.
The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.
You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.
Input
The first line of input will contain two integers n and m (1 ≤ n, m ≤ 500), the dimensions of the puzzle piece.
The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space.
It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.
Output
Output "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.
Examples
Input
2 3
XXX
XXX
Output
YES
Input
2 2
.X
XX
Output
NO
Input
5 5
.....
..X..
.....
.....
.....
Output
YES
Note
For the first sample, one example of a rectangle we can form is as follows
111222
111222
For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.
In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle:
.....
..XX.
.....
.....
.....
| instruction | 0 | 15,580 | 23 | 31,160 |
Tags: implementation
Correct Solution:
```
n, m = map(int, input().split())
a = []
for i in range(n):
a.append(input())
inf = 10 ** 9
p, q = inf, inf
r, s = -1, -1
for i in range(n):
for j in range(m):
if a[i][j] == 'X':
p = min(p, i)
q = min(q, j)
r = max(r, i)
s = max(s, j)
ok = True
for i in range(n):
for j in range(m):
if a[i][j] == 'X':
ok &= p <= i <= r and q <= j <= s
if a[i][j] == '.':
ok &= not (p <= i <= r and q <= j <= s)
if ok:
print('YES')
if not ok:
print('NO')
``` | output | 1 | 15,580 | 23 | 31,161 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow likes solving puzzles.
One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.
The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.
You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.
Input
The first line of input will contain two integers n and m (1 ≤ n, m ≤ 500), the dimensions of the puzzle piece.
The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space.
It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.
Output
Output "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.
Examples
Input
2 3
XXX
XXX
Output
YES
Input
2 2
.X
XX
Output
NO
Input
5 5
.....
..X..
.....
.....
.....
Output
YES
Note
For the first sample, one example of a rectangle we can form is as follows
111222
111222
For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.
In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle:
.....
..XX.
.....
.....
.....
Submitted Solution:
```
n,m=map(int,input().split())
osn=' '
iter=-1
p=-1
for i in range(n):
y=input()
if 'X' in y and osn==' ':
k=y.count('X')
f=y.index('X')
for j in range(f,f+k):
if y[j]!='X':
p=0
osn=y
iter=i
elif osn==y and osn!=' ':
if i==iter+1:
iter+=1
else:
p=0
elif 'X' in y and osn!=' ':
p=0
if p==0:
print('NO')
else:
print('YES')
``` | instruction | 0 | 15,581 | 23 | 31,162 |
Yes | output | 1 | 15,581 | 23 | 31,163 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow likes solving puzzles.
One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.
The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.
You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.
Input
The first line of input will contain two integers n and m (1 ≤ n, m ≤ 500), the dimensions of the puzzle piece.
The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space.
It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.
Output
Output "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.
Examples
Input
2 3
XXX
XXX
Output
YES
Input
2 2
.X
XX
Output
NO
Input
5 5
.....
..X..
.....
.....
.....
Output
YES
Note
For the first sample, one example of a rectangle we can form is as follows
111222
111222
For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.
In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle:
.....
..XX.
.....
.....
.....
Submitted Solution:
```
def f():
s=input().split()
m=int(s[0])
n=int(s[1])
ss=[]
for i in range(m):
ss.append(input())
for i in range(m):
for j in range(n):
if ss[i][j]=='X':
return (ss,m,n,i,j)
def ff(ss,m,n):
for k in range(m-1,-1,-1):
for l in range(n-1,-1,-1):
if ss[k][l]=='X':
return (k,l)
ss,m,n,i,j=f()
k,l=ff(ss,m,n)
sss=[]
for x in range(m):
s=""
for y in range(n):
if (i<=x and x<=k and j<=y and y<=l):
s+="X"
else:
s+="."
sss.append(s)
if(ss==sss):
print("YES")
else:
print("NO")
``` | instruction | 0 | 15,582 | 23 | 31,164 |
Yes | output | 1 | 15,582 | 23 | 31,165 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow likes solving puzzles.
One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.
The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.
You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.
Input
The first line of input will contain two integers n and m (1 ≤ n, m ≤ 500), the dimensions of the puzzle piece.
The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space.
It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.
Output
Output "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.
Examples
Input
2 3
XXX
XXX
Output
YES
Input
2 2
.X
XX
Output
NO
Input
5 5
.....
..X..
.....
.....
.....
Output
YES
Note
For the first sample, one example of a rectangle we can form is as follows
111222
111222
For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.
In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle:
.....
..XX.
.....
.....
.....
Submitted Solution:
```
n, m = map(int, input().split())
g = [input() for _ in range(n)]
r, c = set(), set()
for i in range(n):
for j in range(m):
if g[i][j] == 'X':
r.add(i)
c.add(j)
g = g[min(r):max(r)+1]
g = list(map(lambda x: x[min(c): max(c) + 1], g))
good = True
for i in range(len(g)):
for j in range(len(g[0])):
if g[i][j] != 'X':
good = False
break
print('YES' if good else 'NO')
``` | instruction | 0 | 15,583 | 23 | 31,166 |
Yes | output | 1 | 15,583 | 23 | 31,167 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow likes solving puzzles.
One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.
The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.
You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.
Input
The first line of input will contain two integers n and m (1 ≤ n, m ≤ 500), the dimensions of the puzzle piece.
The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space.
It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.
Output
Output "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.
Examples
Input
2 3
XXX
XXX
Output
YES
Input
2 2
.X
XX
Output
NO
Input
5 5
.....
..X..
.....
.....
.....
Output
YES
Note
For the first sample, one example of a rectangle we can form is as follows
111222
111222
For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.
In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle:
.....
..XX.
.....
.....
.....
Submitted Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
# from fractions import *
# from heapq import*
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz/'
M=998244353
EPS=1e-6
def Ceil(a,b): return a//b+int(a%b>0)
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
def isRectangle():
leftUp = [inf,inf]
rightDown = [-1,-1]
tot = 0
for i in range(n):
for j in range(m):
if(a[i][j] == 'X'):
leftUp[0] = min( leftUp[0] , i)
leftUp[1] = min( leftUp[1] , j)
rightDown[0] = max( rightDown[0], i)
rightDown[1] = max( rightDown[1], j)
tot += 1
l = abs(leftUp[0] - rightDown[0]) + 1
r = abs(leftUp[1] - rightDown[1]) + 1
# print(l,r,tot)
return "YES" if l*r == tot else "NO"
n,m = value()
a = []
for i in range(n): a.append(input())
print(isRectangle())
``` | instruction | 0 | 15,584 | 23 | 31,168 |
Yes | output | 1 | 15,584 | 23 | 31,169 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow likes solving puzzles.
One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.
The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.
You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.
Input
The first line of input will contain two integers n and m (1 ≤ n, m ≤ 500), the dimensions of the puzzle piece.
The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space.
It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.
Output
Output "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.
Examples
Input
2 3
XXX
XXX
Output
YES
Input
2 2
.X
XX
Output
NO
Input
5 5
.....
..X..
.....
.....
.....
Output
YES
Note
For the first sample, one example of a rectangle we can form is as follows
111222
111222
For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.
In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle:
.....
..XX.
.....
.....
.....
Submitted Solution:
```
n, m = map(int, input().split())
num = 0
for i in range(n):
a = input()
num += a.count('X')
if num % n == 0 or num % m == 0 or num <= max(n, m):
print('YES')
else:
print('NO')
``` | instruction | 0 | 15,585 | 23 | 31,170 |
No | output | 1 | 15,585 | 23 | 31,171 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow likes solving puzzles.
One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.
The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.
You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.
Input
The first line of input will contain two integers n and m (1 ≤ n, m ≤ 500), the dimensions of the puzzle piece.
The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space.
It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.
Output
Output "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.
Examples
Input
2 3
XXX
XXX
Output
YES
Input
2 2
.X
XX
Output
NO
Input
5 5
.....
..X..
.....
.....
.....
Output
YES
Note
For the first sample, one example of a rectangle we can form is as follows
111222
111222
For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.
In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle:
.....
..XX.
.....
.....
.....
Submitted Solution:
```
from sys import exit
n, m = map(int, input().split())
a = []
for i in range(n):
a.append(input())
left, right, top, bot = m, 0, m, 0
for i in range(n):
for j in range(m):
if a[i][j] == "X":
left = min(left, j)
right = max(right, j)
top = min(top, i)
bot = max(bot, i)
for i in range(n):
for j in range(m):
if a[i][j] == "X":
if (left <= j <= right) and (top <= i <= bot):
continue
else:
print("NO")
exit()
else:
if (left <= j <= right) and (top <= i <= bot):
print("NO")
exit()
print("YES")
``` | instruction | 0 | 15,586 | 23 | 31,172 |
No | output | 1 | 15,586 | 23 | 31,173 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow likes solving puzzles.
One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.
The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.
You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.
Input
The first line of input will contain two integers n and m (1 ≤ n, m ≤ 500), the dimensions of the puzzle piece.
The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space.
It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.
Output
Output "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.
Examples
Input
2 3
XXX
XXX
Output
YES
Input
2 2
.X
XX
Output
NO
Input
5 5
.....
..X..
.....
.....
.....
Output
YES
Note
For the first sample, one example of a rectangle we can form is as follows
111222
111222
For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.
In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle:
.....
..XX.
.....
.....
.....
Submitted Solution:
```
# You lost the game.
n,m = map(int, input().split())
L = [str(input()) for _ in range(n)]
x = y = ok = 0
for i in range(n):
for j in range(m):
if L[i][j] == 'X':
x = i
y = j
ok = 1
break
if ok:
break
l = y
while l < m and L[x][l] == 'X':
l += 1
ok = 0
for i in range(x+1, n):
vu = 0
for j in range(m):
if L[i][j] == 'X':
vu = 1
if j < y or j >= l:
ok = -1
break
else:
if vu and j >= y and j < l:
ok = -1
break
if ok:
break
if ok == -1:
print("NO")
else:
print("YES")
``` | instruction | 0 | 15,587 | 23 | 31,174 |
No | output | 1 | 15,587 | 23 | 31,175 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow likes solving puzzles.
One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.
The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.
You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.
Input
The first line of input will contain two integers n and m (1 ≤ n, m ≤ 500), the dimensions of the puzzle piece.
The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space.
It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.
Output
Output "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.
Examples
Input
2 3
XXX
XXX
Output
YES
Input
2 2
.X
XX
Output
NO
Input
5 5
.....
..X..
.....
.....
.....
Output
YES
Note
For the first sample, one example of a rectangle we can form is as follows
111222
111222
For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.
In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle:
.....
..XX.
.....
.....
.....
Submitted Solution:
```
'''input
5 5
.....
..X..
.....
.....
.....
'''
s1, e1, s2, e2 = 500, -1, 500, -1
n, m = map(int, input().split())
l = []
for a in range(n):
i = input()
if "X" in i:
s1 = min(s1, i.index("X"))
e1 = max(e1, m - 1 - i[::-1].index("X"))
s2 = min(s2, a)
e2 = max(e2, a)
l.append(i)
if "".join(l).count("X") == 1:
print("YES")
quit()
for r in range(n):
if "." in l[r][s1:e1+1]:
print("NO")
break
else:
print("YES")
``` | instruction | 0 | 15,588 | 23 | 31,176 |
No | output | 1 | 15,588 | 23 | 31,177 |
Provide a correct Python 3 solution for this coding contest problem.
Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \leq N \leq 1000
* 0 \leq D \leq 10^9
* 0 \leq X_i < Y_i \leq 10^9
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print `No` if it is impossible to place N flags.
If it is possible, print `Yes` first. After that, print N lines. i-th line of them should contain the coodinate of flag i.
Examples
Input
3 2
1 4
2 5
0 6
Output
Yes
4
2
0
Input
3 3
1 4
2 5
0 6
Output
No | instruction | 0 | 15,699 | 23 | 31,398 |
"Correct Solution:
```
from collections import defaultdict
class TwoSat:
def __init__(self, V):
self.N = len(V)
self.ans = None
self.__e = []
self.__v = V
def add_clause(self, i, f, j, g):
self.__e.append((2*i + (0 if f else 1), 2*j + (1 if g else 0)))
self.__e.append((2*j + (0 if g else 1), 2*i + (1 if f else 0)))
@staticmethod
def scc(V, E):
g = defaultdict(list)
rg = defaultdict(list)
for u, v in E:
g[u].append(v)
rg[v].append(u)
o = []
done = set()
for u in V:
if u in done:
continue
s = [(u, True)]
while s:
u, f = s.pop()
if f:
if u in done:
continue
done.add(u)
s.append((u, False))
for v in g[u]:
if v in done:
continue
s.append((v, True))
else:
o.append(u)
done = set()
ans = []
while o:
u = o.pop()
if u in done:
continue
s = [u]
vv = [u]
done.add(u)
while s:
u = s.pop()
for v in rg[u]:
if v in done:
continue
vv.append(v)
s.append(v)
done.add(v)
ans.append(vv)
return ans
def satisfiable(self):
scc = TwoSat.scc(self.__v, self.__e)
cid = [-1] * (self.N)
for i, s in enumerate(scc):
for v in s:
cid[v] = i
for i in range(self.N//2):
if cid[2*i] == cid[2*i+1]:
self.ans = None
return False
self.ans = []
for i in range(self.N//2):
self.ans.append(cid[2*i] < cid[2*i+1])
return True
def atcoder_practice2_h():
# https://atcoder.jp/contests/practice2/submissions/16823214
N, D = map(int, input().split())
XY = [list(map(int, input().split())) for _ in range(N)]
ts = TwoSat(list(range(2*N)))
for i, (x1, y1) in enumerate(XY):
for j in range(i+1, N):
x2, y2 = XY[j]
if abs(x1 - x2) < D:
ts.add_clause(i, False, j, False)
if abs(y1 - y2) < D:
ts.add_clause(i, True, j, True)
if abs(x1 - y2) < D:
ts.add_clause(i, False, j, True)
if abs(y1 - x2) < D:
ts.add_clause(i, True, j, False)
if not ts.satisfiable():
print('No')
else:
print('Yes')
for i, b in enumerate(ts.ans):
print(XY[i][0 if b else 1])
if __name__ == "__main__":
atcoder_practice2_h()
``` | output | 1 | 15,699 | 23 | 31,399 |
Provide a correct Python 3 solution for this coding contest problem.
Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \leq N \leq 1000
* 0 \leq D \leq 10^9
* 0 \leq X_i < Y_i \leq 10^9
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print `No` if it is impossible to place N flags.
If it is possible, print `Yes` first. After that, print N lines. i-th line of them should contain the coodinate of flag i.
Examples
Input
3 2
1 4
2 5
0 6
Output
Yes
4
2
0
Input
3 3
1 4
2 5
0 6
Output
No | instruction | 0 | 15,700 | 23 | 31,400 |
"Correct Solution:
```
class CSR:
def __init__(self, n: int, edges: list):
self.start = [0] * (n + 1)
self.elist = [0] * len(edges)
for e in edges:
self.start[e[0] + 1] += 1
for i in range(1, n + 1):
self.start[i] += self.start[i - 1]
counter = self.start[::] # copy
for e in edges:
self.elist[counter[e[0]]] = e[1]
counter[e[0]] += 1
class SccGraph:
def __init__(self, n: int = 0):
self.__n = n
self.__edges = []
def __len__(self):
return self.__n
def add_edge(self, s: int, t: int):
assert 0 <= s < self.__n and 0 <= t < self.__n
self.__edges.append([s, t])
def scc_ids(self):
g = CSR(self.__n, self.__edges)
now_ord = group_num = 0
visited = []
low = [0] * self.__n
order = [-1] * self.__n
ids = [0] * self.__n
parent = [-1] * self.__n
for root in range(self.__n):
if order[root] == -1:
stack = [root, root]
while stack:
v = stack.pop()
if order[v] == -1:
visited.append(v)
low[v] = order[v] = now_ord
now_ord += 1
for i in range(g.start[v], g.start[v + 1]):
t = g.elist[i]
if order[t] == -1:
stack += [t, t]
parent[t] = v
else:
low[v] = min(low[v], order[t])
else:
if low[v] == order[v]:
while True:
u = visited.pop()
order[u] = self.__n
ids[u] = group_num
if u == v:
break
group_num += 1
if parent[v] != -1:
low[parent[v]] = min(low[parent[v]], low[v])
for i, x in enumerate(ids):
ids[i] = group_num - 1 - x
return group_num, ids
def scc(self):
"""
強連結成分のリストを返す。この時、リストはトポロジカルソートされている
[[強連結成分のリスト], [強連結成分のリスト], ...]
"""
group_num, ids = self.scc_ids()
counts = [0] * group_num
for x in ids:
counts[x] += 1
groups = [[] for _ in range(group_num)]
for i, x in enumerate(ids):
groups[x].append(i)
return groups
class TwoSAT():
def __init__(self, n):
self.n = n
self.res = [0]*self.n
self.scc = SccGraph(2*n)
def add_clause(self, i, f, j, g):
# assert 0 <= i < self.n
# assert 0 <= j < self.n
self.scc.add_edge(2*i + (not f), 2*j + g)
self.scc.add_edge(2*j + (not g), 2*i + f)
def satisfiable(self):
"""
条件を足す割当が存在するかどうかを判定する。割当が存在するならばtrue、そうでないならfalseを返す。
"""
group_num, ids = self.scc.scc_ids()
for i in range(self.n):
if ids[2*i] == ids[2*i + 1]: return False
self.res[i] = (ids[2*i] < ids[2*i+1])
return True
def result(self):
"""
最後に呼んだ satisfiable の、クローズを満たす割当を返す。
"""
return self.res
#############################################################################
import sys
input = sys.stdin.buffer.readline
N, D = map(int, input().split())
XY = []
for _ in range(N):
X, Y = map(int, input().split())
XY.append((X, Y))
ts = TwoSAT(N)
for i in range(N-1):
x0, y0 = XY[i]
for j in range(i+1, N):
x1, y1 = XY[j]
if abs(x0 - x1) < D:
ts.add_clause(i, 1, j, 1)
if abs(x0 - y1) < D:
ts.add_clause(i, 1, j, 0)
if abs(y0 - x1) < D:
ts.add_clause(i, 0, j, 1)
if abs(y0 - y1) < D:
ts.add_clause(i, 0, j, 0)
if ts.satisfiable():
print('Yes')
print('\n'.join(map(str, (xy[r] for r, xy in zip(ts.result(), XY)))))
else:
print('No')
``` | output | 1 | 15,700 | 23 | 31,401 |
Provide a correct Python 3 solution for this coding contest problem.
Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \leq N \leq 1000
* 0 \leq D \leq 10^9
* 0 \leq X_i < Y_i \leq 10^9
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print `No` if it is impossible to place N flags.
If it is possible, print `Yes` first. After that, print N lines. i-th line of them should contain the coodinate of flag i.
Examples
Input
3 2
1 4
2 5
0 6
Output
Yes
4
2
0
Input
3 3
1 4
2 5
0 6
Output
No | instruction | 0 | 15,701 | 23 | 31,402 |
"Correct Solution:
```
#-------最強ライブラリ2-SAT(Python)------
#最強ライブラリSCC(Python)が必要
class two_sat:
def __init__(s):
s._n = 0
s.scc = scc_graph(0)
def __init__(s, n):
s._n = n
s._answer = [False] * n
s.scc = scc_graph(2 * n)
# クローズを足す
# クローズってなに
def add_clause(s, i, f, j, g):
s.scc.add_edge(2 * i + (not f), 2 * j + (g))
s.scc.add_edge(2 * j + (not g), 2 * i + (f))
# 判定
# O(n + m)
def satisfiable(s):
id = s.scc.scc_ids()[1]
for i in range(s._n):
if id[2 * i] == id[2 * i + 1]: return False
s._answer[i] = id[2 * i] < id[2 * i + 1]
return True
# クローズを満たす割当を返す
# satisfiableがTrueとなった後に呼ばないと意味ない
# O(1だよね?)
def answer(s): return s._answer
#-------最強ライブラリここまで------
#-------最強ライブラリSCC(Python)ver25252------
import copy
import sys
sys.setrecursionlimit(1000000)
class csr:
# start 頂点iまでの頂点が、矢元として現れた回数
# elist 矢先のリストを矢元の昇順にしたもの
def __init__(s, n, edges):
s.start = [0] * (n + 1)
s.elist = [[] for _ in range(len(edges))]
for e in edges:
s.start[e[0] + 1] += 1
for i in range(1, n + 1):
s.start[i] += s.start[i - 1]
counter = copy.deepcopy(s.start)
for e in edges:
s.elist[counter[e[0]]] = e[1]
counter[e[0]] += 1
class scc_graph:
edges = []
# n 頂点数
def __init__(s, n): s._n = n
def num_vertices(s): return s._n
# 辺を追加 frm 矢元 to 矢先
# O(1)
def add_edge(s, frm, to): s.edges.append([frm, [to]])
# グループの個数と各頂点のグループidを返す
def scc_ids(s):
g = csr(s._n, s.edges)
now_ord = group_num = 0
visited = []
low = [0] * s._n
ord = [-1] * s._n
ids = [0] * s._n
# 再帰関数
def dfs(self, v, now_ord, group_num):
low[v] = ord[v] = now_ord
now_ord += 1
visited.append(v)
for i in range(g.start[v], g.start[v + 1]):
to = g.elist[i][0]
if ord[to] == -1:
now_ord, group_num = self(self, to, now_ord, group_num)
low[v] = min(low[v], low[to])
else:
low[v] = min(low[v], ord[to])
if low[v] == ord[v]:
while True:
u = visited.pop()
ord[u] = s._n
ids[u] = group_num
if u == v: break
group_num += 1
return now_ord, group_num
for i in range(s._n):
if ord[i] == -1: now_ord, group_num = dfs(dfs, i, now_ord, group_num)
for i in range(s._n):
ids[i] = group_num - 1 - ids[i]
return [group_num, ids]
# 強連結成分となっている頂点のリストのリスト トポロジカルソート済み
# O(n + m)
def scc(s):
ids = s.scc_ids()
group_num = ids[0]
counts = [0] * group_num
for x in ids[1]: counts[x] += 1
groups = [[] for _ in range(group_num)]
for i in range(s._n):
groups[ids[1][i]].append(i)
return groups
#-------最強ライブラリここまで------
def main():
input = sys.stdin.readline
N, D = list(map(int, input().split()))
XY = [list(map(int, input().split())) for _ in range(N)]
ts = two_sat(N)
for i in range(N):
for j in range(i + 1, N):
xi, yi = XY[i]
xj, yj = XY[j]
# 距離がD未満の組み合わせに関して、
# 少なくとも一つは使用しない
# → 少なくとも一つは別の座標を使用する
# というルールを追加する
if (abs(xi - xj) < D):
ts.add_clause(i, False, j, False)
if (abs(xi - yj) < D):
ts.add_clause(i, False, j, True)
if (abs(yi - xj) < D):
ts.add_clause(i, True, j, False)
if (abs(yi - yj) < D):
ts.add_clause(i, True, j, True)
if not ts.satisfiable():
print("No")
exit()
print("Yes")
answer = ts.answer()
for i in range(N):
x, y = XY[i]
if answer[i]:
print(x)
else:
print(y)
main()
``` | output | 1 | 15,701 | 23 | 31,403 |
Provide a correct Python 3 solution for this coding contest problem.
Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \leq N \leq 1000
* 0 \leq D \leq 10^9
* 0 \leq X_i < Y_i \leq 10^9
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print `No` if it is impossible to place N flags.
If it is possible, print `Yes` first. After that, print N lines. i-th line of them should contain the coodinate of flag i.
Examples
Input
3 2
1 4
2 5
0 6
Output
Yes
4
2
0
Input
3 3
1 4
2 5
0 6
Output
No | instruction | 0 | 15,702 | 23 | 31,404 |
"Correct Solution:
```
from itertools import product
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 6 + 100)
class StronglyConnectedComponets:
def __init__(self, n: int) -> None:
self.n = n
self.edges = [[] for _ in range(n)]
self.rev_edeges = [[] for _ in range(n)]
self.vs = []
self.order = [0] * n
self.used = [False] * n
def add_edge(self, from_v: int, to_v: int) -> None:
self.edges[from_v].append(to_v)
self.rev_edeges[to_v].append(from_v)
def dfs(self, v: int) -> None:
self.used[v] = True
for child in self.edges[v]:
if not self.used[child]:
self.dfs(child)
self.vs.append(v)
def rdfs(self, v: int, k: int) -> None:
self.used[v] = True
self.order[v] = k
for child in self.rev_edeges[v]:
if not self.used[child]:
self.rdfs(child, k)
def run(self) -> int:
self.used = [False] * self.n
self.vs.clear()
for v in range(self.n):
if not self.used[v]:
self.dfs(v)
self.used = [False] * self.n
k = 0
for v in reversed(self.vs):
if not self.used[v]:
self.rdfs(v, k)
k += 1
return k
class TwoSat(StronglyConnectedComponets):
def __init__(self, num_var: int) -> None:
super().__init__(2 * num_var + 1)
self.num_var = num_var
self.ans = []
def add_constraint(self, a: int, b: int) -> None:
super().add_edge(self._neg(a), self._pos(b))
super().add_edge(self._neg(b), self._pos(a))
def _pos(self, v: int) -> int:
return v if v > 0 else self.num_var - v
def _neg(self, v: int) -> int:
return self.num_var + v if v > 0 else -v
def run(self) -> bool:
super().run()
self.ans.clear()
for i in range(self.num_var):
if self.order[i + 1] == self.order[i + self.num_var + 1]:
return False
self.ans.append(self.order[i + 1] > self.order[i + self.num_var + 1])
return True
def main() -> None:
N, D = map(int, input().split())
flags = [tuple(int(x) for x in input().split()) for _ in range(N)]
# (X_i, Y_i) -> (i, -i) (i=1, ..., N) と考える
sat = TwoSat(N)
# 節 a, b の距離が D 以下の場合,
# a -> -b つまり -a or -b が成立しなければならない
for i, (x_i, y_i) in enumerate(flags, 1):
for j, (x_j, y_j) in enumerate(flags[i:], i+1):
if abs(x_i - x_j) < D:
sat.add_constraint(-i, -j)
if abs(y_i - x_j) < D:
sat.add_constraint(i, -j)
if abs(x_i - y_j) < D:
sat.add_constraint(-i, j)
if abs(y_i - y_j) < D:
sat.add_constraint(i, j)
if sat.run():
print("Yes")
print(*[x_i if sat.ans[i] else y_i for i, (x_i, y_i) in enumerate(flags)], sep="\n")
else:
print("No")
if __name__ == "__main__":
main()
``` | output | 1 | 15,702 | 23 | 31,405 |
Provide a correct Python 3 solution for this coding contest problem.
Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \leq N \leq 1000
* 0 \leq D \leq 10^9
* 0 \leq X_i < Y_i \leq 10^9
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print `No` if it is impossible to place N flags.
If it is possible, print `Yes` first. After that, print N lines. i-th line of them should contain the coodinate of flag i.
Examples
Input
3 2
1 4
2 5
0 6
Output
Yes
4
2
0
Input
3 3
1 4
2 5
0 6
Output
No | instruction | 0 | 15,703 | 23 | 31,406 |
"Correct Solution:
```
# AC Library Python版
# Author Koki_tkg
'''
internal_type_traits以外は翻訳しました。
practiceは一応全部ACしていますが,
practiceで使っていない関数などの動作は未確認なので保証はしません。
また,C++版をほぼそのまま書き換えているので速度は出ません。 (2020/09/13 by Koki_tkg)
'''
# --------------------<< Library Start >>-------------------- #
# convolution.py
class convolution:
def __init__(self, a: list, b: list, mod: int):
self.a, self.b = a, b
self.n, self.m = len(a), len(b)
self.MOD = mod
self.g = primitive_root_constexpr(self.MOD)
def convolution(self) -> list:
n, m = self.n, self.m
a, b = self.a, self.b
if not n or not m: return []
if min(n, m) <= 60:
if n < m:
n, m = m, n
a, b = b, a
ans = [0] * (n + m - 1)
for i in range(n):
for j in range(m):
ans[i + j] += a[i] * b[j] % self.MOD
ans[i + j] %= self.MOD
return ans
z = 1 << ceil_pow2(n + m - 1)
a = self.resize(a, z)
a = self.butterfly(a)
b = self.resize(b, z)
b = self.butterfly(b)
for i in range(z): a[i] = a[i] * b[i] % self.MOD
a = self.butterfly_inv(a)
a = a[:n + m - 1]
iz = self.inv(z)
a = [x * iz % self.MOD for x in a]
return a
def butterfly(self, a: list) -> list:
n = len(a)
h = ceil_pow2(n)
first = True
sum_e = [0] * 30
m = self.MOD
if first:
first = False
es, ies = [0] * 30, [0] * 30
cnt2 = bsf(m - 1)
e = self.mypow(self.g, (m - 1) >> cnt2); ie = self.inv(e)
for i in range(cnt2, 1, -1):
es[i - 2] = e
ies[i - 2] = ie
e = e * e % m
ie = ie * ie % m
now = 1
for i in range(cnt2 - 2):
sum_e[i] = es[i] * now % m
now = now * ies[i] % m
for ph in range(1, h + 1):
w = 1 << (ph - 1); p = 1 << (h - ph)
now = 1
for s in range(w):
offset = s << (h - ph + 1)
for i in range(p):
l = a[i + offset] % m
r = a[i + offset + p] * now % m
a[i + offset] = (l + r) % m
a[i + offset + p] = (l - r) % m
now = now * sum_e[bsf(~s)] % m
return a
def butterfly_inv(self, a: list) -> list:
n = len(a)
h = ceil_pow2(n)
first = True
sum_ie = [0] * 30
m = self.MOD
if first:
first = False
es, ies = [0] * 30, [0] * 30
cnt2 = bsf(m - 1)
e = self.mypow(self.g, (m - 1) >> cnt2); ie = self.inv(e)
for i in range(cnt2, 1, -1):
es[i - 2] = e
ies[i - 2] = ie
e = e * e % m
ie = ie * ie % m
now = 1
for i in range(cnt2 - 2):
sum_ie[i] = ies[i] * now % m
now = es[i] * now % m
for ph in range(h, 0, -1):
w = 1 << (ph - 1); p = 1 << (h - ph)
inow = 1
for s in range(w):
offset = s << (h - ph + 1)
for i in range(p):
l = a[i + offset] % m
r = a[i + offset + p] % m
a[i + offset] = (l + r) % m
a[i + offset + p] = (m + l - r) * inow % m
inow = sum_ie[bsf(~s)] * inow % m
return a
@staticmethod
def resize(array: list, sz: int) -> list:
new_array = array + [0] * (sz - len(array))
return new_array
def inv(self, x: int):
if is_prime_constexpr(self.MOD):
assert x
return self.mypow(x, self.MOD - 2)
else:
eg = inv_gcd(x)
assert eg[0] == 1
return eg[1]
def mypow(self, x: int, n: int) -> int:
assert 0 <= n
r = 1; m = self.MOD
while n:
if n & 1: r = r * x % m
x = x * x % m
n >>= 1
return r
# dsu.py
class dsu:
def __init__(self, n: int):
self._n = n
self.parent_or_size = [-1] * self._n
def merge(self, a: int, b: int) -> int:
assert 0 <= a and a < self._n
assert 0 <= b and a < self._n
x = self.leader(a); y = self.leader(b)
if x == y: return x
if -self.parent_or_size[x] < -self.parent_or_size[y]: x, y = y, x
self.parent_or_size[x] += self.parent_or_size[y]
self.parent_or_size[y] = x
return x
def same(self, a: int, b: int) -> bool:
assert 0 <= a and a < self._n
assert 0 <= b and a < self._n
return self.leader(a) == self.leader(b)
def leader(self, a: int) -> int:
assert 0 <= a and a < self._n
if self.parent_or_size[a] < 0: return a
self.parent_or_size[a] = self.leader(self.parent_or_size[a])
return self.parent_or_size[a]
def size(self, a: int) -> int:
assert 0 <= a and a < self._n
return -self.parent_or_size[self.leader(a)]
def groups(self):
leader_buf = [0] * self._n; group_size = [0] * self._n
for i in range(self._n):
leader_buf[i] = self.leader(i)
group_size[leader_buf[i]] += 1
result = [[] for _ in range(self._n)]
for i in range(self._n):
result[leader_buf[i]].append(i)
result = [v for v in result if v]
return result
# fenwicktree.py
class fenwick_tree:
def __init__(self, n):
self._n = n
self.data = [0] * n
def add(self, p: int, x: int):
assert 0 <= p and p <= self._n
p += 1
while p <= self._n:
self.data[p - 1] += x
p += p & -p
def sum(self, l: int, r: int) -> int:
assert 0 <= l and l <= r and r <= self._n
return self.__sum(r) - self.__sum(l)
def __sum(self, r: int) -> int:
s = 0
while r > 0:
s += self.data[r - 1]
r -= r & -r
return s
# internal_bit.py
def ceil_pow2(n: int) -> int:
x = 0
while (1 << x) < n: x += 1
return x
def bsf(n: int) -> int:
return (n & -n).bit_length() - 1
# internal_math.py
def safe_mod(x: int, m: int) -> int:
x %= m
if x < 0: x += m
return x
class barrett:
def __init__(self, m: int):
self._m = m
self.im = -1 // (m + 1)
def umod(self): return self._m
def mul(self, a: int, b: int) -> int:
z = a
z *= b
x = (z * im) >> 64
v = z - x * self._m
if self._m <= v: v += self._m
return v
def pow_mod_constexpr(x: int, n: int, m: int) -> int:
if m == 1: return 0
_m = m; r = 1; y = safe_mod(x, m)
while n:
if n & 1: r = (r * y) % _m
y = (y * y) % _m
n >>= 1
return r
def is_prime_constexpr(n: int) -> bool:
if n <= 1: return False
if n == 2 or n == 7 or n == 61: return True
if n % 2 == 0: return False
d = n - 1
while d % 2 == 0: d //= 2
for a in [2, 7, 61]:
t = d
y = pow_mod_constexpr(a, t, n)
while t != n - 1 and y != 1 and y != n - 1:
y = y * y % n
t <<= 1
if y != n - 1 and t % 2 == 0: return False
return True
def inv_gcd(self, a: int, b: int) -> tuple:
a = safe_mod(a, b)
if a == 0: return (b, 0)
s = b; t = a; m0 = 0; m1 = 1
while t:
u = s // t
s -= t * u
m0 -= m1 * u
tmp = s; s = t; t = tmp; tmp = m0; m0 = m1; m1 = tmp
if m0 < 0: m0 += b // s
return (s, m0)
def primitive_root_constexpr(m: int) -> int:
if m == 2: return 1
if m == 167772161: return 3
if m == 469762049: return 3
if m == 754974721: return 11
if m == 998244353: return 3
divs = [0] * 20
divs[0] = 2
cnt = 1
x = (m - 1) // 2
while x % 2 == 0: x //= 2
i = 3
while i * i <= x:
if x % i == 0:
divs[cnt] = i; cnt += 1
while x % i == 0:
x //= i
i += 2
if x > 1: divs[cnt] = x; cnt += 1
g = 2
while True:
ok = True
for i in range(cnt):
if pow_mod_constexpr(g, (m - 1) // div[i], m) == 1:
ok = False
break
if ok: return g
g += 1
# internal_queue.py
class simple_queue:
def __init__(self):
self.payload = []
self.pos = 0
def size(self): return len(self.payload) - self.pos
def empty(self): return self.pos == len(self.payload)
def push(self, t: int): self.payload.append(t)
def front(self): return self.payload[self.pos]
def clear(self): self.payload.clear(); pos = 0
def pop(self): self.pos += 1
def pop_front(self): self.pos += 1; return self.payload[~-self.pos]
# internal_scc.py
class csr:
def __init__(self, n: int, edges: list):
from copy import deepcopy
self.start = [0] * (n + 1)
self.elist = [[] for _ in range(len(edges))]
for e in edges:
self.start[e[0] + 1] += 1
for i in range(1, n + 1):
self.start[i] += self.start[i - 1]
counter = deepcopy(self.start)
for e in edges:
self.elist[counter[e[0]]] = e[1]; counter[e[0]] += 1
class scc_graph:
# private
edges = []
# public
def __init__(self, n: int):
self._n = n
self.now_ord = 0; self.group_num = 0
def num_vertices(self): return self._n
def add_edge(self, _from: int, _to: int): self.edges.append((_from, [_to]))
def scc_ids(self):
g = csr(self._n, self.edges)
visited = []; low = [0] * self._n; ord = [-1] * self._n; ids = [0] * self._n
def dfs(s, v: int):
low[v] = ord[v] = self.now_ord; self.now_ord += 1
visited.append(v)
for i in range(g.start[v], g.start[v + 1]):
to = g.elist[i][0]
if ord[to] == -1:
s(s, to)
low[v] = min(low[v], low[to])
else:
low[v] = min(low[v], ord[to])
if low[v] == ord[v]:
while True:
u = visited.pop()
ord[u] = self._n
ids[u] = self.group_num
if u == v: break
self.group_num += 1
for i in range(self._n):
if ord[i] == -1: dfs(dfs, i)
for i in range(self._n):
ids[i] = self.group_num - 1 - ids[i]
return (self.group_num, ids)
def scc(self):
ids = self.scc_ids()
group_num = ids[0]
counts = [0] * group_num
for x in ids[1]: counts[x] += 1
groups = [[] for _ in range(group_num)]
for i in range(self._n):
groups[ids[1][i]].append(i)
return groups
# internal_type_traits.py
# lazysegtree.py
'''
def op(l, r): return
def e(): return
def mapping(l, r): return
def composition(l, r): return
def id(): return 0
'''
class lazy_segtree:
def __init__(self, op, e, mapping, composition, id, v: list):
self.op = op; self.e = e; self.mapping = mapping; self.composition = composition; self.id = id
self._n = len(v)
self.log = ceil_pow2(self._n)
self.size = 1 << self.log
self.lz = [self.id()] * self.size
self.d = [self.e()] * (2 * self.size)
for i in range(self._n): self.d[self.size + i] = v[i]
for i in range(self.size - 1, 0, -1): self.__update(i)
def set_(self, p: int, x: int):
assert 0 <= p and p < self._n
p += self.size
for i in range(self.log, 0, -1): self.__push(p >> i)
self.d[p] = x
for i in range(1, self.log + 1): self.__update(p >> 1)
def get(self, p: int):
assert 0 <= p and p < self._n
p += self.size
for i in range(self.log, 0, -1): self.__push(p >> i)
return self.d[p]
def prod(self, l: int, r: int):
assert 0 <= l and l <= r and r <= self._n
if l == r: return self.e()
l += self.size; r += self.size
for i in range(self.log, 0, -1):
if ((l >> i) << i) != l: self.__push(l >> i)
if ((r >> i) << i) != r: self.__push(r >> i)
sml, smr = self.e(), self.e()
while l < r:
if l & 1: sml = self.op(sml, self.d[l]); l += 1
if r & 1: r -= 1; smr = self.op(self.d[r], smr)
l >>= 1; r >>= 1
return self.op(sml, smr)
def all_prod(self): return self.d[1]
def apply(self, p: int, f):
assert 0 <= p and p < self._n
p += self.size
for i in range(self.log, 0, -1): self.__push(p >> i)
self.d[p] = self.mapping(f, self.d[p])
for i in range(1, self.log + 1): self.__update(p >> 1)
def apply(self, l: int, r: int, f):
assert 0 <= l and l <= r and r <= self._n
if l == r: return
l += self.size; r += self.size
for i in range(self.log, 0, -1):
if ((l >> i) << i) != l: self.__push(l >> i)
if ((r >> i) << i) != r: self.__push((r - 1) >> i)
l2, r2 = l, r
while l < r:
if l & 1: self.__all_apply(l, f); l += 1
if r & 1: r -= 1; self.__all_apply(r, f)
l >>= 1; r >>= 1
l, r = l2, r2
for i in range(1, self.log + 1):
if ((l >> i) << i) != l: self.__update(l >> i)
if ((r >> i) << i) != r: self.__update(r >> i)
def max_right(self, l: int, g):
assert 0 <= l and l <= self._n
if l == self._n: return self._n
l += self.size
for i in range(self.log, 0, -1): self.__push(l >> i)
sm = self.e()
while True:
while l % 2 == 0: l >>= 1
if not g(self.op(sm, self.d[l])):
while l < self.size:
self.__push(l)
l = 2 * l
if g(self.op(sm, self.d[l])):
sm = self.op(sm, self.d[l])
l += 1
return l - self.size
sm = self.op(sm, self.d[l])
l += 1
if (l & -l) == l: break
return self._n
def min_left(self, r: int, g):
assert 0 <= r and r <= self._n
if r == 0: return 0
r += self.size
for i in range(self.log, 0, -1): self.__push(r >> i)
sm = self.e()
while True:
r -= 1
while r > 1 and r % 2: r >>= 1
if not g(self.op(self.d[r], sm)):
while r < self.size:
self.__push(r)
r = 2 * r + 1
if g(self.op(self.d[r], sm)):
sm = self.op(self.d[r], sm)
r -= 1
return r + 1 - self.size
sm = self.op(self.d[r], sm)
if (r & -r) == r: break
return 0
# private
def __update(self, k: int): self.d[k] = self.op(self.d[k * 2], self.d[k * 2 + 1])
def __all_apply(self, k: int, f):
self.d[k] = self.mapping(f, self.d[k])
if k < self.size: self.lz[k] = self.composition(f, self.lz[k])
def __push(self, k: int):
self.__all_apply(2 * k, self.lz[k])
self.__all_apply(2 * k + 1, self.lz[k])
self.lz[k] = self.id()
# math
def pow_mod(x: int, n: int, m: int) -> int:
assert 0 <= n and 1 <= m
if m == 1: return 0
bt = barrett(m)
r = 1; y = safe_mod(x, m)
while n:
if n & 1: r = bt.mul(r, y)
y = bt.mul(y, y)
n >>= 1
return n
def inv_mod(x: int, m: int) -> int:
assert 1 <= m
z = inv_gcd(x, m)
assert z[0] == 1
return z[1]
def crt(r: list, m: list) -> tuple:
assert len(r) == len(m)
n = len(r)
r0 = 0; m0 = 1
for i in range(n):
assert 1 <= m[i]
r1 = safe_mod(r[i], m[i]); m1 = m[i]
if m0 < m1:
r0, r1 = r1, r0
m0, m1 = m1, m0
if m0 % m1 == 0:
if r0 % m1 != r1: return (0, 0)
continue
g, im = inv_gcd(m0, m1)
u1 = m1 // g
if (r1 - r0) % g: return (0, 0)
x = (r1 - r0) // g % u1 * im % u1
r0 += x * m0
m0 *= u1
if r0 < 0: r0 += m0
return (r0, m0)
def floor_sum(n: int, m: int, a: int, b: int) -> int:
ans = 0
if a >= m:
ans += (n - 1) * n * (a // m) // 2
a %= m
if b >= m:
ans += n * (b // m)
bb %= m
y_max = (a * n + b) // m; x_max = (y_max * m - b)
if y_max == 0: return ans
ans += (n - (x_max + a - 1) // a) * y_max
ans += floor_sum(y_max, a, m, (a - x_max % a) % a)
return ans
# maxflow.py
# from collections import deque
class mf_graph:
numeric_limits_max = 10 ** 18
def __init__(self, n: int):
self._n = n
self.g = [[] for _ in range(self._n)]
self.pos = []
def add_edge(self, _from: int, _to: int, cap: int) -> int:
assert 0 <= _from and _from < self._n
assert 0 <= _to and _to < self._n
assert 0 <= cap
m = len(self.pos)
self.pos.append((_from, len(self.g[_from])))
self.g[_from].append(self._edge(_to, len(self.g[_to]), cap))
self.g[_to].append(self._edge(_from, len(self.g[_from]) - 1, 0))
return m
class edge:
def __init__(s, _from: int, _to: int, cap: int, flow: int):
s._from = _from; s._to = _to; s.cap = cap; s.flow = flow
def get_edge(self, i: int) -> edge:
m = len(self.pos)
assert 0 <= i and i < m
_e = self.g[self.pos[i][0]][self.pos[i][1]]
_re = self.g[_e.to][_e.rev]
return self.edge(self.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap)
def edges(self) -> list:
m = len(self.pos)
result = [self.get_edge(i) for i in range(m)]
return result
def change_edge(self, i: int, new_cap: int, new_flow: int):
m = len(self.pos)
assert 0 <= i and i < m
assert 0 <= new_flow and new_flow <= new_cap
_e = self.g[self.pos[i][0]][self.pos[i][1]]
_re = self.g[_e.to][_e.rev]
_e.cap = new_cap - new_flow
_re.cap = new_flow
def flow(self, s: int, t: int):
return self.flow_(s, t, self.numeric_limits_max)
def flow_(self, s: int, t: int, flow_limit: int) -> int:
assert 0 <= s and s < self._n
assert 0 <= t and t < self._n
level = [0] * self._n; it = [0] * self._n
def bfs():
for i in range(self._n): level[i] = -1
level[s] = 0
que = deque([s])
while que:
v = que.popleft()
for e in self.g[v]:
if e.cap == 0 or level[e.to] >= 0: continue
level[e.to] = level[v] + 1
if e.to == t: return
que.append(e.to)
def dfs(self_, v: int, up: int) -> int:
if v == s: return up
res = 0
level_v = level[v]
for i in range(it[v], len(self.g[v])):
it[v] = i
e = self.g[v][i]
if level_v <= level[e.to] or self.g[e.to][e.rev].cap == 0: continue
d = self_(self_, e.to, min(up - res, self.g[e.to][e.rev].cap))
if d <= 0: continue
self.g[v][i].cap += d
self.g[e.to][e.rev].cap -= d
res += d
if res == up: break
return res
flow = 0
while flow < flow_limit:
bfs()
if level[t] == -1: break
for i in range(self._n): it[i] = 0
while flow < flow_limit:
f = dfs(dfs, t, flow_limit - flow)
if not f: break
flow += f
return flow
def min_cut(self, s: int) -> list:
visited = [False] * self._n
que = deque([s])
while que:
p = que.popleft()
visited[p] = True
for e in self.g[p]:
if e.cap and not visited[e.to]:
visited[e.to] = True
que.append(e.to)
return visited
class _edge:
def __init__(s, to: int, rev: int, cap: int):
s.to = to; s.rev = rev; s.cap = cap
# mincostflow.py
# from heapq import heappop, heappush
class mcf_graph:
numeric_limits_max = 10 ** 18
def __init__(self, n: int):
self._n = n
self.g = [[] for _ in range(n)]
self.pos = []
def add_edge(self, _from: int, _to: int, cap: int, cost: int) -> int:
assert 0 <= _from and _from < self._n
assert 0 <= _to and _to < self._n
m = len(self.pos)
self.pos.append((_from, len(self.g[_from])))
self.g[_from].append(self._edge(_to, len(self.g[_to]), cap, cost))
self.g[_to].append(self._edge(_from, len(self.g[_from]) - 1, 0, -cost))
return m
class edge:
def __init__(s, _from: int, _to: int, cap: int, flow: int, cost: int):
s._from = _from; s._to = _to; s.cap = cap; s.flow = flow; s.cost = cost
def get_edge(self, i: int) -> edge:
m = len(self.pos)
assert 0 <= i and i < m
_e = self.g[self.pos[i][0]][self.pos[i][1]]
_re = self.g[_e.to][_e.rev]
return self.edge(self.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap, _e.cost)
def edges(self) -> list:
m = len(self.pos)
result = [self.get_edge(i) for i in range(m)]
return result
def flow(self, s: int, t: int) -> edge:
return self.flow_(s, t, self.numeric_limits_max)
def flow_(self, s: int, t: int, flow_limit: int) -> edge:
return self.__slope(s, t, flow_limit)[-1]
def slope(self, s: int, t: int) -> list:
return self.slope_(s, t, self.numeric_limits_max)
def slope_(self, s: int, t: int, flow_limit: int) -> list:
return self.__slope(s, t, flow_limit)
def __slope(self, s: int, t: int, flow_limit: int) -> list:
assert 0 <= s and s < self._n
assert 0 <= t and t < self._n
assert s != t
dual = [0] * self._n; dist = [0] * self._n
pv, pe = [-1] * self._n, [-1] * self._n
vis = [False] * self._n
def dual_ref():
for i in range(self._n):
dist[i] = self.numeric_limits_max
pv[i] = -1
pe[i] = -1
vis[i] = False
class Q:
def __init__(s, key: int, to: int):
s.key = key; s.to = to
def __lt__(s, r): return s.key < r.key
que = []
dist[s] = 0
heappush(que, Q(0, s))
while que:
v = heappop(que).to
if vis[v]: continue
vis[v] = True
if v == t: break
for i in range(len(self.g[v])):
e = self.g[v][i]
if vis[e.to] or not e.cap: continue
cost = e.cost - dual[e.to] + dual[v]
if dist[e.to] - dist[v] > cost:
dist[e.to] = dist[v] + cost
pv[e.to] = v
pe[e.to] = i
heappush(que, Q(dist[e.to], e.to))
if not vis[t]: return False
for v in range(self._n):
if not vis[v]: continue
dual[v] -= dist[t] - dist[v]
return True
flow = 0
cost = 0; prev_cost = -1
result = []
result.append((flow, cost))
while flow < flow_limit:
if not dual_ref(): break
c = flow_limit - flow
v = t
while v != s:
c = min(c, self.g[pv[v]][pe[v]].cap)
v = pv[v]
v = t
while v != s:
e = self.g[pv[v]][pe[v]]
e.cap -= c
self.g[v][e.rev].cap += c
v = pv[v]
d = -dual[s]
flow += c
cost += c * d
if prev_cost == d:
result.pop()
result.append((flow, cost))
prev_cost = cost
return result
class _edge:
def __init__(s, to: int, rev: int, cap: int, cost: int):
s.to = to; s.rev = rev; s.cap = cap; s.cost = cost
# modint.py
class Mint:
modint1000000007 = 1000000007
modint998244353 = 998244353
def __init__(self, v: int = 0):
self.m = self.modint1000000007
# self.m = self.modint998244353
self.x = v % self.__umod()
def inv(self):
if is_prime_constexpr(self.__umod()):
assert self.x
return self.pow_(self.__umod() - 2)
else:
eg = inv_gcd(self.x, self.m)
assert eg[0] == 1
return eg[2]
def __str__(self): return str(self.x)
def __le__(self, other): return self.x <= Mint.__get_val(other)
def __lt__(self, other): return self.x < Mint.__get_val(other)
def __ge__(self, other): return self.x >= Mint.__get_val(other)
def __gt(self, other): return self.x > Mint.__get_val(other)
def __eq__(self, other): return self.x == Mint.__get_val(other)
def __iadd__(self, other):
self.x += Mint.__get_val(other)
if self.x >= self.__umod(): self.x -= self.__umod()
return self
def __add__(self, other):
_v = Mint(self.x); _v += other
return _v
def __isub__(self, other):
self.x -= Mint.__get_val(other)
if self.x >= self.__umod(): self.x += self.__umod()
return self
def __sub__(self, other):
_v = Mint(self.x); _v -= other
return _v
def __rsub__(self, other):
_v = Mint(Mint.__get_val(other)); _v -= self
return _v
def __imul__(self, other):
self.x =self.x * Mint.__get_val(other) % self.__umod()
return self
def __mul__(self, other):
_v = Mint(self.x); _v *= other
return _v
def __itruediv__(self, other):
self.x = self.x / Mint.__get_val(other) % self.__umod()
return self
def __truediv__(self, other):
_v = Mint(self.x); _v /= other
return _v
def __rtruediv__(self, other):
_v = Mint(Mint.__get_val(other)); _v /= self
return _v
def __ifloordiv__(self, other):
other = other if isinstance(other, Mint) else Mint(other)
self *= other.inv()
return self
def __floordiv__(self, other):
_v = Mint(self.x); _v //= other
return _v
def __rfloordiv__(self, other):
_v = Mint(Mint.__get_val(other)); _v //= self
return _v
def __pow__(self, other):
_v = Mint(pow(self.x, Mint.__get_val(other), self.__umod()))
return _v
def __rpow__(self, other):
_v = Mint(pow(Mint.__get_val(other), self.x, self.__umod()))
return _v
def __imod__(self, other):
self.x %= Mint.__get_val(other)
return self
def __mod__(self, other):
_v = Mint(self.x); _v %= other
return _v
def __rmod__(self, other):
_v = Mint(Mint.__get_val(other)); _v %= self
return _v
def __ilshift__(self, other):
self.x <<= Mint.__get_val(other)
return self
def __irshift__(self, other):
self.x >>= Mint.__get_val(other)
return self
def __lshift__(self, other):
_v = Mint(self.x); _v <<= other
return _v
def __rshift__(self, other):
_v = Mint(self.x); _v >>= other
return _v
def __rlshift__(self, other):
_v = Mint(Mint.__get_val(other)); _v <<= self
return _v
def __rrshift__(self, other):
_v = Mint(Mint.__get_val(other)); _v >>= self
return _v
__repr__ = __str__
__radd__ = __add__
__rmul__ = __mul__
def __umod(self): return self.m
@staticmethod
def __get_val(val): return val.x if isinstance(val, Mint) else val
def pow_(self, n: int):
assert 0 <= n
x = Mint(self.x); r = 1
while n:
if n & 1: r *= x
x *= x
n >>= 1
return r
def val(self): return self.x
def mod(self): return self.m
def raw(self, v):
x = Mint()
x.x = v
return x
# scc.py
class scc_graph_sub:
# public
def __init__(self, n):
self.internal = scc_graph(n)
def add_edge(self, _from, _to):
n = self.internal.num_vertices()
assert 0 <= _from and _from < n
assert 0 <= _to and _to < n
self.internal.add_edge(_from, _to)
def scc(self): return self.internal.scc()
# segtree.py
'''
def e(): return
def op(l, r): return
def f(): return
'''
class segtree:
def __init__(self, op, e, v: list):
self._n = len(v)
self.log = ceil_pow2(self._n)
self.size = 1 << self.log
self.op = op; self.e = e
self.d = [self.e()] * (self.size * 2)
for i in range(self._n): self.d[self.size + i] = v[i]
for i in range(self.size - 1, 0, -1): self.__update(i)
def set_(self, p: int, x: int):
assert 0 <= p and p < self._n
p += self.size
self.d[p] = x
for i in range(1, self.log + 1): self.__update(p >> i)
def get(self, p: int):
assert 0 <= p and p < self._n
return self.d[p + self.size]
def prod(self, l: int, r: int):
assert 0 <= l and l <= r and r <= self._n
l += self.size; r += self.size
sml, smr = self.e(), self.e()
while l < r:
if l & 1: sml = self.op(sml, self.d[l]); l += 1
if r & 1: r -= 1; smr = self.op(self.d[r], smr)
l >>= 1; r >>= 1
return self.op(sml, smr)
def all_prod(self): return self.d[1]
def max_right(self, l: int, f):
assert 0 <= l and l <= self._n
assert f(self.e())
if l == self._n: return self._n
l += self.size
sm = self.e()
while True:
while l % 2 == 0: l >>= 1
if not f(self.op(sm, self.d[l])):
while l < self.size:
l = 2 * l
if f(self.op(sm, self.d[l])):
sm = self.op(sm, self.d[l])
l += 1
return l - self.size
sm = self.op(sm, self.d[l])
l += 1
if (l & -l) == l: break
return self._n
def min_left(self, r: int, f):
assert 0 <= r and r <= self._n
assert f(self.e())
if r == 0: return 0
r += self.size
sm = self.e()
while True:
r -= 1
while r > 1 and r % 2: r >>= 1
if not f(self.op(self.d[r], sm)):
while r < self.size:
r = 2 * r + 1
if f(self.op(self.d[r], sm)):
sm = self.op(self.d[r], sm)
r -= 1
return r + 1 - self.size
sm = self.op(self.d[r], sm)
if (r & -r) == r: break
return 0
def __update(self, k: int): self.d[k] = self.op(self.d[k * 2], self.d[k * 2 + 1])
# string.py
def sa_native(s: list):
from functools import cmp_to_key
def mycmp(r, l):
if l == r: return -1
while l < n and r < n:
if s[l] != s[r]: return 1 if s[l] < s[r] else -1
l += 1
r += 1
return 1 if l == n else -1
n = len(s)
sa = [i for i in range(n)]
sa.sort(key=cmp_to_key(mycmp))
return sa
def sa_doubling(s: list):
from functools import cmp_to_key
def mycmp(y, x):
if rnk[x] != rnk[y]: return 1 if rnk[x] < rnk[y] else -1
rx = rnk[x + k] if x + k < n else - 1
ry = rnk[y + k] if y + k < n else - 1
return 1 if rx < ry else -1
n = len(s)
sa = [i for i in range(n)]; rnk = s; tmp = [0] * n; k = 1
while k < n:
sa.sort(key=cmp_to_key(mycmp))
tmp[sa[0]] = 0
for i in range(1, n):
tmp[sa[i]] = tmp[sa[i - 1]]
if mycmp(sa[i], sa[i - 1]): tmp[sa[i]] += 1
tmp, rnk = rnk, tmp
k *= 2
return sa
def sa_is(s: list, upper: int):
THRESHOLD_NATIVE = 10
THRESHOLD_DOUBLING = 40
n = len(s)
if n == 0: return []
if n == 1: return [0]
if n == 2:
if s[0] < s[1]:
return [0, 1]
else:
return [1, 0]
if n < THRESHOLD_NATIVE:
return sa_native(s)
if n < THRESHOLD_DOUBLING:
return sa_doubling(s)
sa = [0] * n
ls = [False] * n
for i in range(n - 2, -1, -1):
ls[i] = ls[i + 1] if s[i] == s[i + 1] else s[i] < s[i + 1]
sum_l = [0] * (upper + 1); sum_s = [0] * (upper + 1)
for i in range(n):
if not ls[i]:
sum_s[s[i]] += 1
else:
sum_l[s[i] + 1] += 1
for i in range(upper + 1):
sum_s[i] += sum_l[i]
if i < upper: sum_l[i + 1] += sum_s[i]
def induce(lms: list):
from copy import copy
for i in range(n): sa[i] = -1
buf = copy(sum_s)
for d in lms:
if d == n: continue
sa[buf[s[d]]] = d; buf[s[d]] += 1
buf = copy(sum_l)
sa[buf[s[n - 1]]] = n - 1; buf[s[n - 1]] += 1
for i in range(n):
v = sa[i]
if v >= 1 and not ls[v - 1]:
sa[buf[s[v - 1]]] = v - 1; buf[s[v - 1]] += 1
buf = copy(sum_l)
for i in range(n - 1, -1, -1):
v = sa[i]
if v >= 1 and ls[v - 1]:
buf[s[v - 1] + 1] -= 1; sa[buf[s[v - 1] + 1]] = v - 1
lms_map = [-1] * (n + 1)
m = 0
for i in range(1, n):
if not ls[i - 1] and ls[i]:
lms_map[i] = m; m += 1
lms = [i for i in range(1, n) if not ls[i - 1] and ls[i]]
induce(lms)
if m:
sorted_lms = [v for v in sa if lms_map[v] != -1]
rec_s = [0] * m
rec_upper = 0
rec_s[lms_map[sorted_lms[0]]] = 0
for i in range(1, m):
l = sorted_lms[i - 1]; r = sorted_lms[i]
end_l = lms[lms_map[l] + 1] if lms_map[l] + 1 < m else n
end_r = lms[lms_map[r] + 1] if lms_map[r] + 1 < m else n
same = True
if end_l - l != end_r - r:
same = False
else:
while l < end_l:
if s[l] != s[r]: break
l += 1
r += 1
if l == n or s[l] != s[r]: same = False
if not same: rec_upper += 1
rec_s[lms_map[sorted_lms[i]]] = rec_upper
rec_sa = sa_is(rec_s, rec_upper)
for i in range(m):
sorted_lms[i] = lms[rec_sa[i]]
induce(sorted_lms)
return sa
def suffix_array(s: list, upper: int):
assert 0 <= upper
for d in s:
assert 0 <= d and d <= upper
sa = sa_is(s, upper)
return sa
def suffix_array2(s: list):
from functools import cmp_to_key
n = len(s)
idx = [i for i in range(n)]
idx.sort(key=cmp_to_key(lambda l, r: s[l] < s[r]))
s2 = [0] * n
now = 0
for i in range(n):
if i and s[idx[i - 1]] != s[idx[i]]: now += 1
s2[idx[i]] = now
return sa_is(s2, now)
def suffix_array3(s: str):
n = len(s)
s2 = list(map(ord, s))
return sa_is(s2, 255)
def lcp_array(s: list, sa: list):
n = len(s)
assert n >= 1
rnk = [0] * n
for i in range(n):
rnk[sa[i]] = i
lcp = [0] * (n - 1)
h = 0
for i in range(n):
if h > 0: h -= 1
if rnk[i] == 0: continue
j = sa[rnk[i] - 1]
while j + h < n and i + h < n:
if s[j + h] != s[i + h]: break
h += 1
lcp[rnk[i] - 1] = h
return lcp
def lcp_array2(s: str, sa: list):
n = len(s)
s2 = list(map(ord, s))
return lcp_array(s2, sa)
def z_algorithm(s: list):
n = len(s)
if n == 0: return []
z = [-1] * n
z[0] = 0; j = 0
for i in range(1, n):
k = z[i] = 0 if j + z[j] <= i else min(j + z[j] - i, z[i - j])
while i + k < n and s[k] == s[i + k]: k += 1
z[i] = k
if j + z[j] < i + z[i]: j = i
z[0] = n
return z
def z_algorithm2(s: str):
n = len(s)
s2 = list(map(ord, s))
return z_algorithm(s2)
# twosat.py
class two_sat:
def __init__(self, n: int):
self._n = n
self.scc = scc_graph(2 * n)
self._answer = [False] * n
def add_clause(self, i: int, f: bool, j: int, g: bool):
assert 0 <= i and i < self._n
assert 0 <= j and j < self._n
self.scc.add_edge(2 * i + (not f), 2 * j + g)
self.scc.add_edge(2 * j + (not g), 2 * i + f)
def satisfiable(self) -> bool:
_id = self.scc.scc_ids()[1]
for i in range(self._n):
if _id[2 * i] == _id[2 * i + 1]: return False
self._answer[i] = _id[2 * i] < _id[2 * i + 1]
return True
def answer(self): return self._answer
# --------------------<< Library End >>-------------------- #
import sys
sys.setrecursionlimit(10 ** 6)
MOD = 10 ** 9 + 7
INF = 10 ** 9
PI = 3.14159265358979323846
def read_str(): return sys.stdin.readline().strip()
def read_int(): return int(sys.stdin.readline().strip())
def read_ints(): return map(int, sys.stdin.readline().strip().split())
def read_ints2(x): return map(lambda num: int(num) - x, sys.stdin.readline().strip().split())
def read_str_list(): return list(sys.stdin.readline().strip().split())
def read_int_list(): return list(map(int, sys.stdin.readline().strip().split()))
def GCD(a: int, b: int) -> int: return b if a%b==0 else GCD(b, a%b)
def LCM(a: int, b: int) -> int: return (a * b) // GCD(a, b)
def Main_A():
n, q = read_ints()
d = dsu(n)
for _ in range(q):
t, u, v = read_ints()
if t == 0:
d.merge(u, v)
else:
print(int(d.same(u, v)))
def Main_B():
n, q = read_ints()
a = read_int_list()
fw = fenwick_tree(n)
for i, x in enumerate(a):
fw.add(i, x)
for _ in range(q):
query = read_int_list()
if query[0] == 0:
fw.add(query[1], query[2])
else:
print(fw.sum(query[1], query[2]))
def Main_C():
for _ in range(read_int()):
n, m, a, b = read_ints()
print(floor_sum(n, m, a, b))
#from collections import deque
def Main_D():
n, m = read_ints()
grid = [list(read_str()) for _ in range(n)]
mf = mf_graph(n * m + 2)
start = n * m
end = start + 1
dir = [(1, 0), (0, 1)]
for y in range(n):
for x in range(m):
if (y + x) % 2 == 0:
mf.add_edge(start, m*y + x, 1)
else:
mf.add_edge(m*y + x, end, 1)
if grid[y][x] == '.':
for dy, dx in dir:
ny = y + dy; nx = x + dx
if ny < n and nx < m and grid[ny][nx] == '.':
f, t = y*m + x, ny*m + nx
if (y + x) % 2: f, t = t, f
mf.add_edge(f, t, 1)
ans = mf.flow(start, end)
for y in range(n):
for x in range(m):
for e in mf.g[y * m + x]:
to, rev, cap = e.to, e.rev, e.cap
ny, nx = divmod(to, m)
if (y + x) % 2 == 0 and cap == 0 and to != start and to != end and (y*m+x) != start and (y*m+x) != end:
if y + 1 == ny: grid[y][x] = 'v'; grid[ny][nx] = '^'
elif y == ny + 1: grid[y][x] = '^'; grid[ny][nx] = 'v'
elif x + 1 == nx: grid[y][x] = '>'; grid[ny][nx] = '<'
elif x == nx + 1: grid[y][x] = '<'; grid[ny][nx] = '>'
print(ans)
print(*[''.join(ret) for ret in grid], sep='\n')
#from heapq import heappop, heappush
def Main_E():
n, k = read_ints()
a = [read_int_list() for _ in range(n)]
mcf = mcf_graph(n * 2 + 2)
s = n * 2
t = n * 2 + 1
for i in range(n):
mcf.add_edge(s, i, k, 0)
mcf.add_edge(i + n, t, k, 0)
mcf.add_edge(s, t, n * k, INF)
for i in range(n):
for j in range(n):
mcf.add_edge(i, n + j, 1, INF - a[i][j])
result = mcf.flow_(s, t, n * k)
print(n * k * INF - result[1])
grid = [['.'] * n for _ in range(n)]
edges = mcf.edges()
for e in edges:
if e._from == s or e._to == t or e.flow == 0: continue
grid[e._from][e._to - n] = 'X'
print(*[''.join(g) for g in grid], sep='\n')
def Main_F():
MOD = 998244353
n, m = read_ints()
a = read_int_list()
b = read_int_list()
a = [x % MOD for x in a]
b = [x % MOD for x in b]
cnv = convolution(a,b,MOD)
ans = cnv.convolution()
print(*ans)
def Main_G():
sys.setrecursionlimit(10 ** 6)
n, m = read_ints()
scc = scc_graph(n)
for _ in range(m):
a, b = read_ints()
scc.add_edge(a, b)
ans = scc.scc()
print(len(ans))
for v in ans:
print(len(v), ' '.join(map(str, v[::-1])))
def Main_H():
n, d = read_ints()
xy = [read_int_list() for _ in range(n)]
tw = two_sat(n)
for i in range(n):
for j in range(i + 1, n):
for x in range(2):
if abs(xy[i][0] - xy[j][0]) < d: tw.add_clause(i, False, j, False)
if abs(xy[i][0] - xy[j][1]) < d: tw.add_clause(i, False, j, True)
if abs(xy[i][1] - xy[j][0]) < d: tw.add_clause(i, True, j, False)
if abs(xy[i][1] - xy[j][1]) < d: tw.add_clause(i, True, j, True)
if not tw.satisfiable():
print('No')
exit()
print('Yes')
ans = tw.answer()
for i, flag in enumerate(ans):
print(xy[i][0] if flag else xy[i][1])
def Main_I():
s = read_str()
sa = suffix_array3(s)
ans = len(s) * (len(s) + 1) // 2
for x in lcp_array2(s, sa):
ans -= x
print(ans)
def Main_J():
def op(l, r): return max(l, r)
def e(): return -1
def f(n): return n < r
n, q = read_ints()
a = read_int_list()
seg = segtree(op, e, a)
query = [(read_ints()) for _ in range(q)]
for i in range(q):
t, l, r = query[i]
if t == 1:
seg.set_(~-l, r)
elif t == 2:
print(seg.prod(~-l, r))
else:
print(seg.max_right(~-l, f) + 1)
def Main_K():
p = 998244353
def op(l, r):
l1, l2 = l >> 32, l % (1 << 32)
r1, r2 = r >> 32, r % (1 << 32)
return (((l1 + r1) % p) << 32) + l2 + r2
def e(): return 0
def mapping(l, r):
l1, l2 = l >> 32, l % (1 << 32)
r1, r2 = r >> 32, r % (1 << 32)
return (((l1 * r1 + l2 * r2) % p) << 32) + r2
def composition(l, r):
l1, l2 = l >> 32, l % (1 << 32)
r1, r2 = r >> 32, r % (1 << 32)
return ((l1 * r1 % p) << 32) + (l1 * r2 + l2) % p
def id(): return 1 << 32
n, q = read_ints()
A = read_int_list()
A = [(x << 32) + 1 for x in A]
seg = lazy_segtree(op, e, mapping, composition, id, A)
ans = []
for _ in range(q):
query = read_int_list()
if query[0] == 0:
l, r, b, c = query[1:]
seg.apply(l, r, (b << 32) + c)
else:
l, r = query[1:]
print(seg.prod(l, r) >> 32)
def Main_L():
def op(l: tuple, r: tuple): return (l[0] + r[0], l[1] + r[1], l[2] + r[2] + l[1] * r[0])
def e(): return (0, 0, 0)
def mapping(l:bool, r: tuple):
if not l: return r
return (r[1], r[0], r[1] * r[0] - r[2])
def composition(l: bool, r: bool): return l ^ r
def id(): return False
n, q = read_ints()
A = read_int_list()
query = [(read_ints()) for _ in range(q)]
a = [(1, 0, 0) if i == 0 else (0, 1, 0) for i in A]
seg = lazy_segtree(op, e, mapping, composition, id, a)
for t, l, r in query:
if t == 1:
seg.apply(~-l, r, True)
else:
print(seg.prod(~-l, r)[2])
if __name__ == '__main__':
Main_H()
``` | output | 1 | 15,703 | 23 | 31,407 |
Provide a correct Python 3 solution for this coding contest problem.
Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \leq N \leq 1000
* 0 \leq D \leq 10^9
* 0 \leq X_i < Y_i \leq 10^9
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print `No` if it is impossible to place N flags.
If it is possible, print `Yes` first. After that, print N lines. i-th line of them should contain the coodinate of flag i.
Examples
Input
3 2
1 4
2 5
0 6
Output
Yes
4
2
0
Input
3 3
1 4
2 5
0 6
Output
No | instruction | 0 | 15,704 | 23 | 31,408 |
"Correct Solution:
```
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**6)
INF = 10 ** 9 + 1 # sys.maxsize # float("inf")
MOD = 10 ** 9 + 7
# Strongly connected component
# derived from https://atcoder.jp/contests/practice2/submissions/16645774
def get_strongly_connected_components(edges, num_vertex):
"""
edges: {v: [v]}
"""
from collections import defaultdict
reverse_edges = defaultdict(list)
for v1 in edges:
for v2 in edges[v1]:
reverse_edges[v2].append(v1)
terminate_order = []
done = [0] * num_vertex # 0 -> 1 -> 2
count = 0
for i0 in range(num_vertex):
if done[i0]:
continue
queue = [~i0, i0]
# dfs
while queue:
i = queue.pop()
if i < 0:
if done[~i] == 2:
continue
done[~i] = 2
terminate_order.append(~i)
count += 1
continue
if i >= 0:
if done[i]:
continue
done[i] = 1
for j in edges[i]:
if done[j]:
continue
queue.append(~j)
queue.append(j)
done = [0] * num_vertex
result = []
for i0 in terminate_order[::-1]:
if done[i0]:
continue
component = []
queue = [~i0, i0]
while queue:
i = queue.pop()
if i < 0:
if done[~i] == 2:
continue
done[~i] = 2
component.append(~i)
continue
if i >= 0:
if done[i]:
continue
done[i] = 1
for j in reverse_edges[i]:
if done[j]:
continue
queue.append(~j)
queue.append(j)
result.append(component)
return result
def debug(*x):
print(*x, file=sys.stderr)
def solve(N, D, data):
# edges = [[] for i in range(N * 2)]
# edges = []
from collections import defaultdict
edges = defaultdict(list)
def add_then_edge(i, bool_i, j, bool_j):
edges[i * 2 + int(bool_i)].append(j * 2 + int(bool_j))
# edges.append((i * 2 + int(bool_i), j * 2 + int(bool_j)))
for i in range(N):
xi, yi = data[i]
for j in range(i + 1, N):
xj, yj = data[j]
if abs(xi - xj) < D:
add_then_edge(i, 0, j, 1)
add_then_edge(j, 0, i, 1)
if abs(xi - yj) < D:
add_then_edge(i, 0, j, 0)
add_then_edge(j, 1, i, 1)
if abs(yi - xj) < D:
add_then_edge(i, 1, j, 1)
add_then_edge(j, 0, i, 0)
if abs(yi - yj) < D:
add_then_edge(i, 1, j, 0)
add_then_edge(j, 1, i, 0)
scc = get_strongly_connected_components(edges, N * 2)
group_id = [0] * (2 * N)
for i, xs in enumerate(scc):
for x in xs:
group_id[x] = i
ret = [0] * N
for i in range(N):
if group_id[2 * i] == group_id[2 * i + 1]:
print("No")
return
ret[i] = (group_id[2 * i] < group_id[2 * i + 1])
print("Yes")
for i in range(N):
print(data[i][ret[i]])
def main():
# parse input
N, D = map(int, input().split())
data = []
for _i in range(N):
data.append(tuple(map(int, input().split())))
solve(N, D, data)
# tests
T1 = """
3 2
1 4
2 5
0 6
"""
TEST_T1 = """
>>> as_input(T1)
>>> main()
Yes
4
2
6
"""
T2 = """
3 3
1 4
2 5
0 6
"""
TEST_T2 = """
>>> as_input(T2)
>>> main()
No
"""
def _test():
import doctest
doctest.testmod()
g = globals()
for k in sorted(g):
if k.startswith("TEST_"):
doctest.run_docstring_examples(g[k], g, name=k)
def as_input(s):
"use in test, use given string as input file"
import io
f = io.StringIO(s.strip())
g = globals()
g["input"] = lambda: bytes(f.readline(), "ascii")
g["read"] = lambda: bytes(f.read(), "ascii")
input = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
if sys.argv[-1] == "-t":
print("testing")
_test()
sys.exit()
main()
``` | output | 1 | 15,704 | 23 | 31,409 |
Provide a correct Python 3 solution for this coding contest problem.
Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \leq N \leq 1000
* 0 \leq D \leq 10^9
* 0 \leq X_i < Y_i \leq 10^9
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print `No` if it is impossible to place N flags.
If it is possible, print `Yes` first. After that, print N lines. i-th line of them should contain the coodinate of flag i.
Examples
Input
3 2
1 4
2 5
0 6
Output
Yes
4
2
0
Input
3 3
1 4
2 5
0 6
Output
No | instruction | 0 | 15,705 | 23 | 31,410 |
"Correct Solution:
```
from operator import itemgetter
from itertools import *
from bisect import *
from collections import *
from heapq import *
import sys
sys.setrecursionlimit(10**6)
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def SI(): return sys.stdin.readline()[:-1]
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def LLI1(rows_number): return [LI1() for _ in range(rows_number)]
int1 = lambda x: int(x)-1
def MI1(): return map(int1, sys.stdin.readline().split())
def LI1(): return list(map(int1, sys.stdin.readline().split()))
p2D = lambda x: print(*x, sep="\n")
dij = [(1, 0), (0, 1), (-1, 0), (0, -1)]
def SCC(to, ot):
n = len(to)
def dfs(u):
for v in to[u]:
if com[v]: continue
com[v] = 1
dfs(v)
top.append(u)
top = []
com = [0]*n
for u in range(n):
if com[u]: continue
com[u] = 1
dfs(u)
def rdfs(u, k):
for v in ot[u]:
if com[v] != -1: continue
com[v] = k
rdfs(v, k)
com = [-1]*n
k = 0
for u in top[::-1]:
if com[u] != -1: continue
com[u] = k
rdfs(u, k)
k += 1
return k, com
class TwoSat:
def __init__(self, n):
# to[v][u]...頂点uの値がvのときの遷移先と反転の有無
self.n = n
self.to = [[] for _ in range(n*2)]
self.ot = [[] for _ in range(n*2)]
self.vals = []
# uがu_val(0 or 1)ならばvはv_val(0 or 1)
def add_edge(self, u, u_val, v, v_val):
self.to[u*2+u_val].append(v*2+v_val)
self.ot[v*2+v_val].append(u*2+u_val)
# 条件を満たすかどうかをboolで返す。構成はself.valsに入る
def satisfy(self):
k, com = SCC(self.to, self.ot)
for u in range(self.n):
if com[u*2]==com[u*2+1]:return False
self.vals.append(com[u*2]<com[u*2+1])
return True
n, d = MI()
xy = LLI(n)
ts = TwoSat(n)
for i in range(n):
x1, y1 = xy[i]
for j in range(i):
x2, y2 = xy[j]
if abs(x1-x2) < d:
ts.add_edge(i, 0, j, 1)
ts.add_edge(j, 0, i, 1)
if abs(x1-y2) < d:
ts.add_edge(i, 0, j, 0)
ts.add_edge(j, 1, i, 1)
if abs(y1-x2) < d:
ts.add_edge(i, 1, j, 1)
ts.add_edge(j, 0, i, 0)
if abs(y1-y2) < d:
ts.add_edge(i, 1, j, 0)
ts.add_edge(j, 1, i, 0)
if ts.satisfy():
print("Yes")
for j,xyi in zip(ts.vals,xy):print(xyi[j])
else:print("No")
``` | output | 1 | 15,705 | 23 | 31,411 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.