message stringlengths 2 19.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 322 108k | cluster float64 15 15 | __index_level_0__ int64 644 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Petya loves playing with rectangles. Mom bought Petya a rectangle divided into cells n Γ m in size (containing n rows, m columns). Petya marked two different cells of the rectangle and now he is solving the following task:
Let's define a simple path between those two cells as a sequence of distinct cells a1, a2, ..., ak, where a1 and ak are the two marked cells. Besides, ai and ai + 1 are side-neighboring cells of the path (1 β€ i < k). Let's denote the path length as number k (the sequence length).
Petya's task is to find the longest simple path's length and to print the path. Help him.
Input
The first line contains space-separated integers n and m (4 β€ n, m β€ 1000) β the number of rows and the number of columns in the rectangle, correspondingly. The second line contains space-separated integers x1 and y1 β the coordinates of the first marked cell. The third line contains space-separated integers x2 y2 β the coordinates of the second marked cell (1 < x1, x2 < n, 1 < y1, y2 < m, x1 β x2, y1 β y2).
The coordinates of a marked cell are a pair of integers x y, where x represents the row's number and y represents the column's number. The rows are numbered from top to bottom with consecutive integers from 1 to n. The columns are numbered from the left to the right by consecutive integers from 1 to m.
It is guaranteed that the marked cells are not positioned in one row or column.
Output
In the first line print the length of the found path β k. In the next lines print k pairs of integers, one per line β coordinates of the cells that constitute the found path in the order, in which they follow in the path (the path must go from cell (x1, y1) to cell (x2, y2)). If there are several solutions, print any of them.
Examples
Input
4 4
2 2
3 3
Output
15
2 2
1 2
1 1
2 1
3 1
4 1
4 2
4 3
4 4
3 4
2 4
1 4
1 3
2 3
3 3
Note
The statement test is described in the picture:
<image>
Submitted Solution:
```
#!/usr/bin/env python3
import itertools
class Position:
def __init__(self,x,y):
self.x = x
self.y = y
def __add__(self, other):
if isinstance(other, Position):
return Position(self.x + other.x, self.y + other.y)
else:
(dx,dy) = other
return Position(self.x + dx, self.y + dy)
def __eq__(self, other):
return (self.x == other.x) and (self.y == other.y)
def __sub__(self, other):
return Position(self.x - other.x, self.y - other.y)
def __str__(self):
return "(%d,%d)" % (self.x, self.y)
def left(self):
return Position(self.x-1, self.y)
def right(self):
return Position(self.x+1, self.y)
def up(self):
return Position(self.x, self.y-1)
def down(self):
return Position(self.x, self.y+1)
def adjacent(self):
return [self.up(), self.right(), self.down(), self.left()]
class Cell:
def __init__(self, pos):
self.pos = pos
self.next = None
self.group = None
self.is_finish = False
def __str__(self):
if (self.is_finish):
return "*"
elif (self.next == None):
return "."
else:
distance = self.next.pos - self.pos
if (distance.x == 1):
return ">"
elif (distance.x == -1):
return "<"
elif (distance.y == 1):
return "v"
elif (distance.y == -1):
return "^"
else:
raise("Wrong direction %s" % distance)
def move_left(self):
self.next = self.group.grid.cell(self.pos.left())
def move_right(self):
self.next = self.group.grid.cell(self.pos.right())
def move_up(self):
self.next = self.group.grid.cell(self.pos.up())
def move_down(self):
self.next = self.group.grid.cell(self.pos.down())
def is_empty(self):
# Returns whether the cell is already filled
return (not self.is_finish) and (self.next == None)
def adjacent(self):
# Return cells adjacent to this cell
neighbors = [self.group.grid.cell(pos) for pos in self.pos.adjacent()]
neighbors = [cell for cell in neighbors if cell != None]
return neighbors
def prev(self):
# Returns the previous cell on the route,
# or None if there is none
prev = [cell for cell in self.adjacent() if cell.next == self]
return None if len(prev) == 0 else prev[0]
class Group:
def __init__(self, grid, pos):
self.grid = grid
self.pos = pos
self.cellsx = 2 if ((2*pos.x+3) != self.grid.m) else 3
self.cellsy = 2 if ((2*pos.y+3) != self.grid.n) else 3
self.cells = [[self.grid.cells[y][x] for x in range(pos.x*2, pos.x*2 + self.cellsx)] for y in range(pos.y*2, pos.y*2 + self.cellsy)]
for row in self.cells:
for cell in row:
cell.group = self
def __str__(self):
result = []
for row in self.cells:
line = []
for cell in row:
line.append("%s" % cell)
result.append("".join(line))
return "\n".join(result)
def fill_clock_wise(self):
# Fill the group with a clock-wise ring
for x in range(self.cellsx-1):
self.cells[0][x].move_right()
for y in range(self.cellsy-1):
self.cells[y][-1].move_down()
for x in range(self.cellsx-1, 0, -1):
self.cells[-1][x].move_left()
for y in range(self.cellsy-1, 0, -1):
self.cells[y][0].move_up()
def fill_counter_clock_wise(self):
# Fill the group with a counter clock-wise ring
for x in range(self.cellsx-1, 0, -1):
self.cells[0][x].move_left()
for y in range(self.cellsy-1):
self.cells[y][0].move_down()
for x in range(self.cellsx-1):
self.cells[-1][x].move_right()
for y in range(self.cellsy-1, 0, -1):
self.cells[y][-1].move_up()
def is_cell_adjacent(self, cell):
# Checks if a certain cell is adjacent to this group
neighbors = cell.adjacent()
return any(c in neighbors for c in itertools.chain.from_iterable(self.cells))
def solve_path(self, entry_cell, next_group):
# Solve the current group; make a path from the entry_cell to one of the cells in the next group,
# and use all cells in the group
direction = next_group.pos-self.pos
self.fill_clock_wise()
exit_candidate = entry_cell.next
if next_group.is_cell_adjacent(exit_candidate):
self.fill_counter_clock_wise()
exit_candidate.next = self.grid.cell(exit_candidate.pos+direction)
return exit_candidate.next
self.fill_counter_clock_wise()
exit_candidate = entry_cell.next
if next_group.is_cell_adjacent(exit_candidate):
self.fill_clock_wise()
exit_candidate.next = self.grid.cell(exit_candidate.pos+direction)
return exit_candidate.next
# FIXME: We can only get here for some of the 3x2/2x3/3x3 cases
raise("Unhandled case")
def nr_filled(self):
return sum(1 for c in itertools.chain.from_iterable(self.cells) if (c.next != None) or (c.is_finish))
def nr_unfilled(self):
return (self.cellsx * self.cellsy) - self.nr_filled()
def solve_end(self, entry_cell, destination_cell):
# Solve the current group; make a path from the entry_cell to the destination cell.
# This fuction will return the number of cells in the group that have not been used (ideally 0)
if (entry_cell != destination_cell):
self.fill_clock_wise()
if (entry_cell.next == destination_cell):
self.fill_counter_clock_wise()
destination_cell.next = None
return self.nr_unfilled()
self.fill_counter_clock_wise()
if (entry_cell.next == destination_cell):
self.fill_clock_wise()
destination_cell.next = None
return self.nr_unfilled()
if (self.cellsx == 2) and (self.cellsy == 2):
# The destination cell is in the opposite corner of the entry cell
self.fill_clock_wise() # TODO: Does it matter whether we go clock-wise or counter clock-wise? I don't think so...
assert(entry_cell.next.next == destination_cell)
entry_cell.next.next.next.next = None # Clear the unused cell
entry_cell.next.next.next = None # Clear the destination cell
return self.nr_unfilled()
# FIXME: We can only get here for some of the 3x2/2x3/3x3 cases
raise("Unhandled case")
else:
# We enter at the location where we need to finish
if (self.cellsx == 3) and (self.cellsy == 3) and (entry_cell == self.cells[0][0]):
# We enter and at the top left corner of the 3x3 cell, leaving a nice L shape with an even number of empty cells
# that will be filled automatically by the extend part of the algorithm
# TODO: Is this true? We have a probelm if it possible that none of the adjoining 3x2/2x3 cells have an extension option
return 0
# There might be a solution by slightly altering the previous group to exit that group a bit earlier:
if (self.is_cell_adjacent(entry_cell.prev().prev())):
redirect = entry_cell.prev().prev()
direction = self.pos-redirect.group.pos
entry_cell.prev().next = None
redirect.next = self.grid.cell(redirect.pos+direction)
# Now solve for the new problem
return self.solve_end(redirect.next, destination_cell)+1
else:
# No local solution, perhaps a different route will help?
return self.nr_unfilled()
class Grid:
def __init__(self, n, m, x1, y1, x2, y2):
self.n = n
self.m = m
self.cells = [[Cell(Position(x,y)) for x in range(m)] for y in range(n)]
self.groups = [[Group(self, Position(x, y)) for x in range(m//2)] for y in range(n//2)]
self.c1 = self.cell(Position(x1-1,y1-1))
self.c2 = self.cell(Position(x2-1,y2-1))
self.c2.is_finish = True
self.g1 = self.group(Position((x1-1)//2,(y1-1)//2))
self.g2 = self.group(Position((x2-1)//2,(y2-1)//2))
def __str__(self):
result = []
for row in self.groups:
divider = []
lines = [[],[],[]]
for group in row:
group_lines = group.__str__().split("\n")
divider.append("-" * group.cellsx)
for (index, line) in enumerate(group_lines):
lines[index].append(line)
for line in lines:
if len(line) > 0:
result.append("|%s|" % ("|".join(line)))
divider = "+%s+" % "+".join(divider)
result.append(divider)
result.insert(0, divider)
return "\n".join(result)
def cell(self, pos):
if (0 <= pos.x) and (pos.x < self.m) and (0 <= pos.y) and (pos.y < self.n):
return self.cells[pos.y][pos.x]
else:
return None
def group(self, pos):
return self.groups[pos.y][pos.x]
def extend(self):
# Given an available route from start to finish, fill in the rest of the groups
cell = self.c1
while (cell != self.c2):
# Find any pair of empty adjacent cells that are also adjacent to the path
adjacent_to_cell = [c for c in cell.adjacent() if (c != cell.next) and (c.is_empty())]
adjacent_to_next = [c for c in cell.next.adjacent() if (c != cell) and (c.is_empty())]
candidates = [(c1, c2) for (c1,c2) in itertools.product(adjacent_to_cell, adjacent_to_next) if (c1 in c2.adjacent())]
if len(candidates) > 0:
temp = cell.next
(a1, a2) = candidates[0]
cell.next = a1
a1.next = a2
a2.next = temp
else:
cell = cell.next
def solve(self):
# Find route from starting group to ending group
current_group = self.g1
route = []
while (current_group != self.g2):
distance = self.g2.pos - current_group.pos
if (distance.x > 0):
current_group = self.group(current_group.pos.right())
elif (distance.x < 0):
current_group = self.group(current_group.pos.left())
elif (distance.y > 0):
current_group = self.group(current_group.pos.down())
else: #(distance.y < 0)
current_group = self.group(current_group.pos.up())
route.append(current_group)
#print(",".join([group.pos.__str__() for group in route]))
current_cell = self.c1
for next_group in route:
current_cell = current_cell.group.solve_path(current_cell, next_group)
missed = current_cell.group.solve_end(current_cell, self.c2)
#print(missed)
# FIXME: Adjust route if missed > 1
self.extend()
def print_answer(self):
cell = self.c1
route = [cell]
while (cell != self.c2):
cell = cell.next
route.append(cell)
print(len(route))
print("\n".join([cell.pos.__str__() for cell in route]))
(n,m) = map(int, input().split())
(x1,y1) = map(int, input().split())
(x2,y2) = map(int, input().split())
g = Grid(n,m,x1,y1,x2,y2)
g.solve()
g.print_answer()
#print(g)
``` | instruction | 0 | 31,810 | 15 | 63,620 |
No | output | 1 | 31,810 | 15 | 63,621 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Petya loves playing with rectangles. Mom bought Petya a rectangle divided into cells n Γ m in size (containing n rows, m columns). Petya marked two different cells of the rectangle and now he is solving the following task:
Let's define a simple path between those two cells as a sequence of distinct cells a1, a2, ..., ak, where a1 and ak are the two marked cells. Besides, ai and ai + 1 are side-neighboring cells of the path (1 β€ i < k). Let's denote the path length as number k (the sequence length).
Petya's task is to find the longest simple path's length and to print the path. Help him.
Input
The first line contains space-separated integers n and m (4 β€ n, m β€ 1000) β the number of rows and the number of columns in the rectangle, correspondingly. The second line contains space-separated integers x1 and y1 β the coordinates of the first marked cell. The third line contains space-separated integers x2 y2 β the coordinates of the second marked cell (1 < x1, x2 < n, 1 < y1, y2 < m, x1 β x2, y1 β y2).
The coordinates of a marked cell are a pair of integers x y, where x represents the row's number and y represents the column's number. The rows are numbered from top to bottom with consecutive integers from 1 to n. The columns are numbered from the left to the right by consecutive integers from 1 to m.
It is guaranteed that the marked cells are not positioned in one row or column.
Output
In the first line print the length of the found path β k. In the next lines print k pairs of integers, one per line β coordinates of the cells that constitute the found path in the order, in which they follow in the path (the path must go from cell (x1, y1) to cell (x2, y2)). If there are several solutions, print any of them.
Examples
Input
4 4
2 2
3 3
Output
15
2 2
1 2
1 1
2 1
3 1
4 1
4 2
4 3
4 4
3 4
2 4
1 4
1 3
2 3
3 3
Note
The statement test is described in the picture:
<image>
Submitted Solution:
```
#!/usr/bin/env python3
import sys
import itertools
class Position:
def __init__(self,x,y):
self.x = x
self.y = y
def __add__(self, other):
if isinstance(other, Position):
return Position(self.x + other.x, self.y + other.y)
else:
(dx,dy) = other
return Position(self.x + dx, self.y + dy)
def __eq__(self, other):
return (self.x == other.x) and (self.y == other.y)
def __sub__(self, other):
return Position(self.x - other.x, self.y - other.y)
def __str__(self):
return "(%d,%d)" % (self.x, self.y)
def left(self):
return Position(self.x-1, self.y)
def right(self):
return Position(self.x+1, self.y)
def up(self):
return Position(self.x, self.y-1)
def down(self):
return Position(self.x, self.y+1)
def adjacent(self):
return [self.up(), self.right(), self.down(), self.left()]
class Cell:
def __init__(self, pos):
self.pos = pos
self.next = None
self.group = None
self.is_finish = False
def __str__(self):
if (self.is_finish):
return "*"
elif (self.next == None):
return "."
else:
distance = self.next.pos - self.pos
if (distance.x == 1):
return ">"
elif (distance.x == -1):
return "<"
elif (distance.y == 1):
return "v"
elif (distance.y == -1):
return "^"
else:
raise("Wrong direction %s" % distance)
def move_left(self):
self.next = self.group.grid.cell(self.pos.left())
return self.next
def move_right(self):
self.next = self.group.grid.cell(self.pos.right())
return self.next
def move_up(self):
self.next = self.group.grid.cell(self.pos.up())
return self.next
def move_down(self):
self.next = self.group.grid.cell(self.pos.down())
return self.next
def is_empty(self):
# Returns whether the cell is already filled
return (not self.is_finish) and (self.next == None)
def adjacent(self):
# Return cells adjacent to this cell
neighbors = [self.group.grid.cell(pos) for pos in self.pos.adjacent()]
neighbors = [cell for cell in neighbors if cell != None]
return neighbors
def prev(self):
# Returns the previous cell on the route,
# or None if there is none
prev = [cell for cell in self.adjacent() if cell.next == self]
return None if len(prev) == 0 else prev[0]
class Group:
def __init__(self, grid, pos):
self.grid = grid
self.pos = pos
self.cellsx = 2 if ((2*pos.x+3) != self.grid.n) else 3
self.cellsy = 2 if ((2*pos.y+3) != self.grid.m) else 3
self.cells = [[self.grid.cells[y][x] for x in range(pos.x*2, pos.x*2 + self.cellsx)] for y in range(pos.y*2, pos.y*2 + self.cellsy)]
for row in self.cells:
for cell in row:
cell.group = self
def __str__(self):
result = []
for row in self.cells:
line = []
for cell in row:
line.append("%s" % cell)
result.append("".join(line))
return "\n".join(result)
def fill_clock_wise(self):
# Fill the group with a clock-wise ring
for x in range(self.cellsx-1):
self.cells[0][x].move_right()
for y in range(self.cellsy-1):
self.cells[y][-1].move_down()
for x in range(self.cellsx-1, 0, -1):
self.cells[-1][x].move_left()
for y in range(self.cellsy-1, 0, -1):
self.cells[y][0].move_up()
def fill_counter_clock_wise(self):
# Fill the group with a counter clock-wise ring
for x in range(self.cellsx-1, 0, -1):
self.cells[0][x].move_left()
for y in range(self.cellsy-1):
self.cells[y][0].move_down()
for x in range(self.cellsx-1):
self.cells[-1][x].move_right()
for y in range(self.cellsy-1, 0, -1):
self.cells[y][-1].move_up()
def nr_filled(self):
return sum(1 for c in itertools.chain.from_iterable(self.cells) if (c.next != None) or (c.is_finish))
def nr_unfilled(self):
return (self.cellsx * self.cellsy) - self.nr_filled()
def is_cell_adjacent(self, cell):
# Checks if a certain cell is adjacent to this group
neighbors = cell.adjacent()
return any(c in neighbors for c in itertools.chain.from_iterable(self.cells))
def solve_path(self, entry_cell, next_group):
# Solve the current group; make a path from the entry_cell to one of the cells in the next group,
# and use all cells in the group
direction = next_group.pos-self.pos
self.fill_clock_wise()
exit_candidate = entry_cell.next
if next_group.is_cell_adjacent(exit_candidate):
self.fill_counter_clock_wise()
exit_candidate.next = self.grid.cell(exit_candidate.pos+direction)
return exit_candidate.next
self.fill_counter_clock_wise()
exit_candidate = entry_cell.next
if next_group.is_cell_adjacent(exit_candidate):
self.fill_clock_wise()
exit_candidate.next = self.grid.cell(exit_candidate.pos+direction)
return exit_candidate.next
# FIXME: We can only get here for some of the 3x2/2x3 cases
print(self.pos.__str__())
print(next_group.pos.__str__())
print(entry_cell.pos.__str__())
print(self.__str__())
print(self.grid.__str__())
raise("Unhandled case")
def solve_end_via_cycle(self, entry_cell, destination_cell):
# Solve the current group; make a path from the entry_cell to the destination cell by cycling around the cell
# This fuction will return the number of cells in the group that have not been used (ideally 0)
# Pre: entry_cell != destination_cell
# Choose between clock-wise and counter clock-wise:
self.fill_clock_wise()
clock_wise_path = self.grid.get_path(entry_cell, destination_cell)
self.fill_counter_clock_wise()
counter_clock_wise_path = self.grid.get_path(entry_cell, destination_cell)
if (len(clock_wise_path) > len(counter_clock_wise_path)):
self.fill_clock_wise()
path = clock_wise_path
else:
path = counter_clock_wise_path
# Clear any cells that are not part of the path
for cell in itertools.chain.from_iterable(self.cells):
if (cell not in path):
cell.next = None
destination_cell.next = None
return self.nr_unfilled()
def solve_end_via_changed_entry(self, entry_cell, destination_cell):
# Solve the current group; make a path from the entry_cell to the destination cell by attempting backtracking and entering the group from another cell
# This fuction will return the number of cells in the group that have not been used (will be at least 1)
if (self.is_cell_adjacent(entry_cell.prev().prev())):
redirect = entry_cell.prev().prev()
direction = self.pos-redirect.group.pos
entry_cell.prev().next = None
redirect.next = self.grid.cell(redirect.pos+direction)
# Now solve for the new problem
return self.solve_end(redirect.next, destination_cell)+1
else:
# No local solution, perhaps a different route will help?
return self.nr_unfilled()
def solve_end(self, entry_cell, destination_cell):
# Solve the current group; make a path from the entry_cell to the destination cell.
# This fuction will return the number of cells in the group that have not been used (ideally 0)
if (entry_cell == destination_cell):
# We enter at the location where we need to finish
# There might be a solution by slightly altering the previous group to exit that group a bit earlier:
return self.solve_end_via_changed_entry(entry_cell, destination_cell)
else:
# Solve it by running around the outside of the cell
return self.solve_end_via_cycle(entry_cell, destination_cell)
class Group2x2(Group):
pass
class Group2x3(Group):
pass
class Group3x2(Group):
pass
class Group3x3(Group):
def solve_path(self, entry_cell, next_group):
# Solve the current group; make a path from the entry_cell to one of the cells in the next group,
# and try to use all cells in the group (not always possible)
distance = next_group.pos - self.pos
if (distance.y == -1):
# We entered the group from the left and have to leave it upwards
# Figure out the relative y position where we entered
y = 0
while (self.cells[y][0] != entry_cell):
y+=1
# Go all the way down
cell = entry_cell
for i in range(2-y):
cell = entry_cell.move_down()
# Now zig-zag up
cell = cell.move_right()
cell = cell.move_right()
cell = cell.move_up()
cell = cell.move_left()
if (y == 2):
# The zig-zag to the left can do one extra move
cell = cell.move_left()
cell = cell.move_up()
cell = cell.move_right()
if (y == 2):
# The zig-zag to the right can do one extra move
cell = cell.move_right()
cell = cell.move_up()
else:
# We entered the group from the top and have to leave it towards the left
# Figure out the relative x position where we entered
x = 0
while (self.cells[0][x] != entry_cell):
x+=1
# Go all the way to the right
cell = entry_cell
for i in range(2-y):
cell = entry_cell.move_right()
# Now zig-zag left
cell = cell.move_down()
cell = cell.move_down()
cell = cell.move_left()
cell = cell.move_up()
if (x == 2):
# The zig-zag to the left can do one extra move
cell = cell.move_up()
cell = cell.move_left()
cell = cell.move_down()
if (y == 2):
# The zig-zag to the right can do one extra move
cell = cell.move_down()
cell = cell.move_left()
return cell
def solve_end(self, entry_cell, destination_cell):
# Solve the current group; make a path from the entry_cell to the destination cell.
# This fuction will return the number of cells in the group that have not been used (ideally 0)
if (entry_cell == destination_cell):
if (entry_cell == self.cells[0][0]):
# We enter and at the top left corner of the 3x3 cell, leaving a nice L shape with an even number of empty cells
# that will be filled automatically by the extend part of the algorithm
# TODO: Is this true? We have a problem if it is possible that none of the adjoining 3x2/2x3 cells have an extension option
return 0
else:
# There might be a solution by slightly altering the previous group to exit that group a bit earlier:
return self.solve_end_via_changed_entry(entry_cell, destination_cell)
else:
# Make a path from entry to destination, the extend part of the algorithm will fill out the missing parts
cell = entry_cell
while (cell != destination_cell):
distance = destination_cell.pos - cell.pos
if (distance.x > 0):
cell.move_right()
elif (distance.x < 0):
cell.move_left()
elif (distance.y > 0):
cell.move_down()
else: #(distance.y < 0)
cell.move_up()
cell = cell.next
return self.nr_unfilled()
class Grid:
def __init__(self, n, m, x1, y1, x2, y2):
self.n = n
self.m = m
self.cells = [[Cell(Position(x,y)) for x in range(n)] for y in range(m)]
self.groups = [[self._group_factory_method(Position(x, y)) for x in range(n//2)] for y in range(m//2)]
self.c1 = self.cell(Position(x1-1,y1-1))
self.c2 = self.cell(Position(x2-1,y2-1))
self.c2.is_finish = True
self.g1 = self.group(Position((x1-1)//2,(y1-1)//2))
self.g2 = self.group(Position((x2-1)//2,(y2-1)//2))
def _group_factory_method(self, pos):
cellsx = 2 if ((2*pos.x+3) != self.n) else 3
cellsy = 2 if ((2*pos.y+3) != self.m) else 3
if (cellsx == 2) and (cellsy == 2):
return Group2x2(self, pos)
elif (cellsx == 3) and (cellsy == 3):
return Group3x3(self, pos)
elif (cellsx == 3):
return Group2x3(self, pos)
else:
return Group3x2(self, pos)
def __str__(self):
result = []
for row in self.groups:
divider = []
lines = [[],[],[]]
for group in row:
group_lines = group.__str__().split("\n")
divider.append("-" * group.cellsx)
for (index, line) in enumerate(group_lines):
lines[index].append(line)
for line in lines:
if len(line) > 0:
result.append("|%s|" % ("|".join(line)))
divider = "+%s+" % "+".join(divider)
result.append(divider)
result.insert(0, divider)
result[self.c1.pos.y+self.g1.pos.y+1] += "S"
result.append(" "*(self.c1.pos.x+self.g1.pos.x+1)+"S")
return "\n".join(result)
def cell(self, pos):
if (0 <= pos.x) and (pos.x < self.n) and (0 <= pos.y) and (pos.y < self.m):
return self.cells[pos.y][pos.x]
else:
return None
def group(self, pos):
return self.groups[pos.y][pos.x]
def extend(self):
# Given an available route from start to finish, fill in the rest of the groups
cell = self.c1
while (cell != self.c2):
# Find any pair of empty adjacent cells that are also adjacent to the path
adjacent_to_cell = [c for c in cell.adjacent() if (c != cell.next) and (c.is_empty())]
adjacent_to_next = [c for c in cell.next.adjacent() if (c != cell) and (c.is_empty())]
candidates = [(c1, c2) for (c1,c2) in itertools.product(adjacent_to_cell, adjacent_to_next) if (c1 in c2.adjacent())]
if len(candidates) > 0:
temp = cell.next
(a1, a2) = candidates[0]
cell.next = a1
a1.next = a2
a2.next = temp
else:
cell = cell.next
def solve(self):
# Find route from starting group to ending group
current_group = self.g1
route = []
while (current_group != self.g2):
distance = self.g2.pos - current_group.pos
if (distance.x > 0):
current_group = self.group(current_group.pos.right())
elif (distance.x < 0):
current_group = self.group(current_group.pos.left())
elif (distance.y > 0):
current_group = self.group(current_group.pos.down())
else: #(distance.y < 0)
current_group = self.group(current_group.pos.up())
route.append(current_group)
#print(",".join([group.pos.__str__() for group in route]))
current_cell = self.c1
for next_group in route:
current_cell = current_cell.group.solve_path(current_cell, next_group)
missed = current_cell.group.solve_end(current_cell, self.c2)
#print(missed)
# FIXME: Adjust route if missed > 1
self.extend()
def get_path(self, start=None, finish=None):
# Returns a list of all cells on the path
# If no start and end cell are given it will return the path from the starting cell (c1),
# until the path ends (for a finished solution that is cell c2)
cell = start if (start) else self.c1
path = [cell]
while (cell.next != finish):
cell = cell.next
path.append(cell)
return path
def print_answer(self):
path = self.get_path()
print(len(path))
print("\n".join(["%d %d" % (cell.pos.x+1, cell.pos.y+1) for cell in path]))
(n,m) = map(int, input().split())
(x1,y1) = map(int, input().split())
(x2,y2) = map(int, input().split())
g = Grid(n,m,x1,y1,x2,y2)
g.solve()
g.print_answer()
if (len(sys.argv)>1):
print(g)
print(len(g.get_path()))
``` | instruction | 0 | 31,811 | 15 | 63,622 |
No | output | 1 | 31,811 | 15 | 63,623 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Petya loves playing with rectangles. Mom bought Petya a rectangle divided into cells n Γ m in size (containing n rows, m columns). Petya marked two different cells of the rectangle and now he is solving the following task:
Let's define a simple path between those two cells as a sequence of distinct cells a1, a2, ..., ak, where a1 and ak are the two marked cells. Besides, ai and ai + 1 are side-neighboring cells of the path (1 β€ i < k). Let's denote the path length as number k (the sequence length).
Petya's task is to find the longest simple path's length and to print the path. Help him.
Input
The first line contains space-separated integers n and m (4 β€ n, m β€ 1000) β the number of rows and the number of columns in the rectangle, correspondingly. The second line contains space-separated integers x1 and y1 β the coordinates of the first marked cell. The third line contains space-separated integers x2 y2 β the coordinates of the second marked cell (1 < x1, x2 < n, 1 < y1, y2 < m, x1 β x2, y1 β y2).
The coordinates of a marked cell are a pair of integers x y, where x represents the row's number and y represents the column's number. The rows are numbered from top to bottom with consecutive integers from 1 to n. The columns are numbered from the left to the right by consecutive integers from 1 to m.
It is guaranteed that the marked cells are not positioned in one row or column.
Output
In the first line print the length of the found path β k. In the next lines print k pairs of integers, one per line β coordinates of the cells that constitute the found path in the order, in which they follow in the path (the path must go from cell (x1, y1) to cell (x2, y2)). If there are several solutions, print any of them.
Examples
Input
4 4
2 2
3 3
Output
15
2 2
1 2
1 1
2 1
3 1
4 1
4 2
4 3
4 4
3 4
2 4
1 4
1 3
2 3
3 3
Note
The statement test is described in the picture:
<image>
Submitted Solution:
```
#!/usr/bin/env python3
import itertools
class Position:
def __init__(self,x,y):
self.x = x
self.y = y
def __add__(self, other):
if isinstance(other, Position):
return Position(self.x + other.x, self.y + other.y)
else:
(dx,dy) = other
return Position(self.x + dx, self.y + dy)
def __eq__(self, other):
return (self.x == other.x) and (self.y == other.y)
def __sub__(self, other):
return Position(self.x - other.x, self.y - other.y)
def __str__(self):
return "(%d,%d)" % (self.x, self.y)
def left(self):
return Position(self.x-1, self.y)
def right(self):
return Position(self.x+1, self.y)
def up(self):
return Position(self.x, self.y-1)
def down(self):
return Position(self.x, self.y+1)
def adjacent(self):
return [self.up(), self.right(), self.down(), self.left()]
class Cell:
def __init__(self, pos):
self.pos = pos
self.next = None
self.group = None
self.is_finish = False
def __str__(self):
if (self.is_finish):
return "*"
elif (self.next == None):
return "."
else:
distance = self.next.pos - self.pos
if (distance.x == 1):
return ">"
elif (distance.x == -1):
return "<"
elif (distance.y == 1):
return "v"
elif (distance.y == -1):
return "^"
else:
raise("Wrong direction %s" % distance)
def move_left(self):
self.next = self.group.grid.cell(self.pos.left())
def move_right(self):
self.next = self.group.grid.cell(self.pos.right())
def move_up(self):
self.next = self.group.grid.cell(self.pos.up())
def move_down(self):
self.next = self.group.grid.cell(self.pos.down())
def is_empty(self):
# Returns whether the cell is already filled
return (not self.is_finish) and (self.next == None)
def adjacent(self):
# Return cells adjacent to this cell
neighbors = [self.group.grid.cell(pos) for pos in self.pos.adjacent()]
neighbors = [cell for cell in neighbors if cell != None]
return neighbors
def prev(self):
# Returns the previous cell on the route,
# or None if there is none
prev = [cell for cell in self.adjacent() if cell.next == self]
return None if len(prev) == 0 else prev[0]
class Group:
def __init__(self, grid, pos):
self.grid = grid
self.pos = pos
self.cellsx = 2 if ((2*pos.x+3) != self.grid.m) else 3
self.cellsy = 2 if ((2*pos.y+3) != self.grid.n) else 3
self.cells = [[self.grid.cells[y][x] for x in range(pos.x*2, pos.x*2 + self.cellsx)] for y in range(pos.y*2, pos.y*2 + self.cellsy)]
for row in self.cells:
for cell in row:
cell.group = self
def __str__(self):
result = []
for row in self.cells:
line = []
for cell in row:
line.append("%s" % cell)
result.append("".join(line))
return "\n".join(result)
def fill_clock_wise(self):
# Fill the group with a clock-wise ring
for x in range(self.cellsx-1):
self.cells[0][x].move_right()
for y in range(self.cellsy-1):
self.cells[y][-1].move_down()
for x in range(self.cellsx-1, 0, -1):
self.cells[-1][x].move_left()
for y in range(self.cellsy-1, 0, -1):
self.cells[y][0].move_up()
def fill_counter_clock_wise(self):
# Fill the group with a counter clock-wise ring
for x in range(self.cellsx-1, 0, -1):
self.cells[0][x].move_left()
for y in range(self.cellsy-1):
self.cells[y][0].move_down()
for x in range(self.cellsx-1):
self.cells[-1][x].move_right()
for y in range(self.cellsy-1, 0, -1):
self.cells[y][-1].move_up()
def nr_filled(self):
return sum(1 for c in itertools.chain.from_iterable(self.cells) if (c.next != None) or (c.is_finish))
def nr_unfilled(self):
return (self.cellsx * self.cellsy) - self.nr_filled()
def is_cell_adjacent(self, cell):
# Checks if a certain cell is adjacent to this group
neighbors = cell.adjacent()
return any(c in neighbors for c in itertools.chain.from_iterable(self.cells))
def solve_path(self, entry_cell, next_group):
# Solve the current group; make a path from the entry_cell to one of the cells in the next group,
# and use all cells in the group
direction = next_group.pos-self.pos
self.fill_clock_wise()
exit_candidate = entry_cell.next
if next_group.is_cell_adjacent(exit_candidate):
self.fill_counter_clock_wise()
exit_candidate.next = self.grid.cell(exit_candidate.pos+direction)
return exit_candidate.next
self.fill_counter_clock_wise()
exit_candidate = entry_cell.next
if next_group.is_cell_adjacent(exit_candidate):
self.fill_clock_wise()
exit_candidate.next = self.grid.cell(exit_candidate.pos+direction)
return exit_candidate.next
# FIXME: We can only get here for some of the 3x2/2x3/3x3 cases
raise("Unhandled case")
def solve_end_via_cycle(self, entry_cell, destination_cell):
# Solve the current group; make a path from the entry_cell to the destination cell by cycling around the cell
# This fuction will return the number of cells in the group that have not been used (ideally 0)
# Pre: entry_cell != destination_cell
# Choose between clock-wise and counter clock-wise:
self.fill_clock_wise()
clock_wise_path = self.grid.get_path(entry_cell, destination_cell)
self.fill_counter_clock_wise()
counter_clock_wise_path = self.grid.get_path(entry_cell, destination_cell)
if (len(clock_wise_path) > len(counter_clock_wise_path)):
self.fill_clock_wise()
path = clock_wise_path
else:
path = counter_clock_wise_path
# Clear any cells that are not part of the path
for cell in itertools.chain.from_iterable(self.cells):
if (cell not in path):
cell.next = None
destination_cell.next = None
return self.nr_unfilled()
def solve_end_via_changed_entry(self, entry_cell, destination_cell):
# Solve the current group; make a path from the entry_cell to the destination cell by attempting backtracking and entering the group from another cell
# This fuction will return the number of cells in the group that have not been used (will be at least 1)
if (self.is_cell_adjacent(entry_cell.prev().prev())):
redirect = entry_cell.prev().prev()
direction = self.pos-redirect.group.pos
entry_cell.prev().next = None
redirect.next = self.grid.cell(redirect.pos+direction)
# Now solve for the new problem
return self.solve_end(redirect.next, destination_cell)+1
else:
# No local solution, perhaps a different route will help?
return self.nr_unfilled()
def solve_end(self, entry_cell, destination_cell):
# Solve the current group; make a path from the entry_cell to the destination cell.
# This fuction will return the number of cells in the group that have not been used (ideally 0)
if (entry_cell == destination_cell):
# We enter at the location where we need to finish
# There might be a solution by slightly altering the previous group to exit that group a bit earlier:
return self.solve_end_via_changed_entry(entry_cell, destination_cell)
else:
# Solve it by running around the outside of the cell
return self.solve_end_via_cycle(entry_cell, destination_cell)
class Group2x2(Group):
pass
class Group2x3(Group):
pass
class Group3x2(Group):
pass
class Group3x3(Group):
def solve_end(self, entry_cell, destination_cell):
# Solve the current group; make a path from the entry_cell to the destination cell.
# This fuction will return the number of cells in the group that have not been used (ideally 0)
if (entry_cell == destination_cell):
if (entry_cell == self.cells[0][0]):
# We enter and at the top left corner of the 3x3 cell, leaving a nice L shape with an even number of empty cells
# that will be filled automatically by the extend part of the algorithm
# TODO: Is this true? We have a problem if it is possible that none of the adjoining 3x2/2x3 cells have an extension option
return 0
else:
# There might be a solution by slightly altering the previous group to exit that group a bit earlier:
return self.solve_end_via_changed_entry(entry_cell, destination_cell)
else:
# Make a path from entry to destination, the extend part of the algorithm will fill out the missing parts
cell = entry_cell
while (cell != destination_cell):
distance = destination_cell.pos - cell.pos
if (distance.x > 0):
cell.move_right()
elif (distance.x < 0):
cell.move_left()
elif (distance.y > 0):
cell.move_down()
else: #(distance.y < 0)
cell.move_up()
cell = cell.next
class Grid:
def __init__(self, n, m, x1, y1, x2, y2):
self.n = n
self.m = m
self.cells = [[Cell(Position(x,y)) for x in range(m)] for y in range(n)]
self.groups = [[self._group_factory_method(Position(x, y)) for x in range(m//2)] for y in range(n//2)]
self.c1 = self.cell(Position(x1-1,y1-1))
self.c2 = self.cell(Position(x2-1,y2-1))
self.c2.is_finish = True
self.g1 = self.group(Position((x1-1)//2,(y1-1)//2))
self.g2 = self.group(Position((x2-1)//2,(y2-1)//2))
def _group_factory_method(self, pos):
cellsx = 2 if ((2*pos.x+3) != self.m) else 3
cellsy = 2 if ((2*pos.y+3) != self.n) else 3
if (cellsx == 2) and (cellsy == 2):
return Group2x2(self, pos)
elif (cellsx == 3) and (cellsy == 3):
return Group3x3(self, pos)
elif (cellsx == 3):
return Group2x3(self, pos)
else:
return Group3x2(self, pos)
def __str__(self):
result = []
for row in self.groups:
divider = []
lines = [[],[],[]]
for group in row:
group_lines = group.__str__().split("\n")
divider.append("-" * group.cellsx)
for (index, line) in enumerate(group_lines):
lines[index].append(line)
for line in lines:
if len(line) > 0:
result.append("|%s|" % ("|".join(line)))
divider = "+%s+" % "+".join(divider)
result.append(divider)
result.insert(0, divider)
return "\n".join(result)
def cell(self, pos):
if (0 <= pos.x) and (pos.x < self.m) and (0 <= pos.y) and (pos.y < self.n):
return self.cells[pos.y][pos.x]
else:
return None
def group(self, pos):
return self.groups[pos.y][pos.x]
def extend(self):
# Given an available route from start to finish, fill in the rest of the groups
cell = self.c1
while (cell != self.c2):
# Find any pair of empty adjacent cells that are also adjacent to the path
adjacent_to_cell = [c for c in cell.adjacent() if (c != cell.next) and (c.is_empty())]
adjacent_to_next = [c for c in cell.next.adjacent() if (c != cell) and (c.is_empty())]
candidates = [(c1, c2) for (c1,c2) in itertools.product(adjacent_to_cell, adjacent_to_next) if (c1 in c2.adjacent())]
if len(candidates) > 0:
temp = cell.next
(a1, a2) = candidates[0]
cell.next = a1
a1.next = a2
a2.next = temp
else:
cell = cell.next
def solve(self):
# Find route from starting group to ending group
current_group = self.g1
route = []
while (current_group != self.g2):
distance = self.g2.pos - current_group.pos
if (distance.x > 0):
current_group = self.group(current_group.pos.right())
elif (distance.x < 0):
current_group = self.group(current_group.pos.left())
elif (distance.y > 0):
current_group = self.group(current_group.pos.down())
else: #(distance.y < 0)
current_group = self.group(current_group.pos.up())
route.append(current_group)
#print(",".join([group.pos.__str__() for group in route]))
current_cell = self.c1
for next_group in route:
current_cell = current_cell.group.solve_path(current_cell, next_group)
missed = current_cell.group.solve_end(current_cell, self.c2)
#print(missed)
# FIXME: Adjust route if missed > 1
self.extend()
def get_path(self, start=None, finish=None):
# Returns a list of all cells on the path
# If no start and end cell are given it will return the path from the starting cell (c1),
# until the path ends (for a finished solution that is cell c2)
cell = start if (start) else self.c1
path = [cell]
while (cell.next != finish):
cell = cell.next
path.append(cell)
return path
def print_answer(self):
path = self.get_path()
print(len(path))
print("\n".join(["%d %d" % (cell.pos.x+1, cell.pos.y+1) for cell in path]))
(n,m) = map(int, input().split())
(x1,y1) = map(int, input().split())
(x2,y2) = map(int, input().split())
g = Grid(n,m,x1,y1,x2,y2)
g.solve()
g.print_answer()
#print(g)
#print(len(g.get_path()))
``` | instruction | 0 | 31,812 | 15 | 63,624 |
No | output | 1 | 31,812 | 15 | 63,625 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Petya loves playing with rectangles. Mom bought Petya a rectangle divided into cells n Γ m in size (containing n rows, m columns). Petya marked two different cells of the rectangle and now he is solving the following task:
Let's define a simple path between those two cells as a sequence of distinct cells a1, a2, ..., ak, where a1 and ak are the two marked cells. Besides, ai and ai + 1 are side-neighboring cells of the path (1 β€ i < k). Let's denote the path length as number k (the sequence length).
Petya's task is to find the longest simple path's length and to print the path. Help him.
Input
The first line contains space-separated integers n and m (4 β€ n, m β€ 1000) β the number of rows and the number of columns in the rectangle, correspondingly. The second line contains space-separated integers x1 and y1 β the coordinates of the first marked cell. The third line contains space-separated integers x2 y2 β the coordinates of the second marked cell (1 < x1, x2 < n, 1 < y1, y2 < m, x1 β x2, y1 β y2).
The coordinates of a marked cell are a pair of integers x y, where x represents the row's number and y represents the column's number. The rows are numbered from top to bottom with consecutive integers from 1 to n. The columns are numbered from the left to the right by consecutive integers from 1 to m.
It is guaranteed that the marked cells are not positioned in one row or column.
Output
In the first line print the length of the found path β k. In the next lines print k pairs of integers, one per line β coordinates of the cells that constitute the found path in the order, in which they follow in the path (the path must go from cell (x1, y1) to cell (x2, y2)). If there are several solutions, print any of them.
Examples
Input
4 4
2 2
3 3
Output
15
2 2
1 2
1 1
2 1
3 1
4 1
4 2
4 3
4 4
3 4
2 4
1 4
1 3
2 3
3 3
Note
The statement test is described in the picture:
<image>
Submitted Solution:
```
#!/usr/bin/env python3
import itertools
class Position:
def __init__(self,x,y):
self.x = x
self.y = y
def __add__(self, other):
if isinstance(other, Position):
return Position(self.x + other.x, self.y + other.y)
else:
(dx,dy) = other
return Position(self.x + dx, self.y + dy)
def __eq__(self, other):
return (self.x == other.x) and (self.y == other.y)
def __sub__(self, other):
return Position(self.x - other.x, self.y - other.y)
def __str__(self):
return "(%d,%d)" % (self.x, self.y)
def left(self):
return Position(self.x-1, self.y)
def right(self):
return Position(self.x+1, self.y)
def up(self):
return Position(self.x, self.y-1)
def down(self):
return Position(self.x, self.y+1)
def adjacent(self):
return [self.up(), self.right(), self.down(), self.left()]
class Cell:
def __init__(self, pos):
self.pos = pos
self.next = None
self.group = None
self.is_finish = False
def __str__(self):
if (self.is_finish):
return "*"
elif (self.next == None):
return "."
else:
distance = self.next.pos - self.pos
if (distance.x == 1):
return ">"
elif (distance.x == -1):
return "<"
elif (distance.y == 1):
return "v"
elif (distance.y == -1):
return "^"
else:
raise("Wrong direction %s" % distance)
def move_left(self):
self.next = self.group.grid.cell(self.pos.left())
return self.next
def move_right(self):
self.next = self.group.grid.cell(self.pos.right())
return self.next
def move_up(self):
self.next = self.group.grid.cell(self.pos.up())
return self.next
def move_down(self):
self.next = self.group.grid.cell(self.pos.down())
return self.next
def is_empty(self):
# Returns whether the cell is already filled
return (not self.is_finish) and (self.next == None)
def adjacent(self):
# Return cells adjacent to this cell
neighbors = [self.group.grid.cell(pos) for pos in self.pos.adjacent()]
neighbors = [cell for cell in neighbors if cell != None]
return neighbors
def prev(self):
# Returns the previous cell on the route,
# or None if there is none
prev = [cell for cell in self.adjacent() if cell.next == self]
return None if len(prev) == 0 else prev[0]
class Group:
def __init__(self, grid, pos):
self.grid = grid
self.pos = pos
self.cellsx = 2 if ((2*pos.x+3) != self.grid.n) else 3
self.cellsy = 2 if ((2*pos.y+3) != self.grid.m) else 3
self.cells = [[self.grid.cells[y][x] for x in range(pos.x*2, pos.x*2 + self.cellsx)] for y in range(pos.y*2, pos.y*2 + self.cellsy)]
for row in self.cells:
for cell in row:
cell.group = self
def __str__(self):
result = []
for row in self.cells:
line = []
for cell in row:
line.append("%s" % cell)
result.append("".join(line))
return "\n".join(result)
def fill_clock_wise(self):
# Fill the group with a clock-wise ring
for x in range(self.cellsx-1):
self.cells[0][x].move_right()
for y in range(self.cellsy-1):
self.cells[y][-1].move_down()
for x in range(self.cellsx-1, 0, -1):
self.cells[-1][x].move_left()
for y in range(self.cellsy-1, 0, -1):
self.cells[y][0].move_up()
def fill_counter_clock_wise(self):
# Fill the group with a counter clock-wise ring
for x in range(self.cellsx-1, 0, -1):
self.cells[0][x].move_left()
for y in range(self.cellsy-1):
self.cells[y][0].move_down()
for x in range(self.cellsx-1):
self.cells[-1][x].move_right()
for y in range(self.cellsy-1, 0, -1):
self.cells[y][-1].move_up()
def nr_filled(self):
return sum(1 for c in itertools.chain.from_iterable(self.cells) if (c.next != None) or (c.is_finish))
def nr_unfilled(self):
return (self.cellsx * self.cellsy) - self.nr_filled()
def is_cell_adjacent(self, cell):
# Checks if a certain cell is adjacent to this group
neighbors = cell.adjacent()
return any(c in neighbors for c in itertools.chain.from_iterable(self.cells))
def solve_path(self, entry_cell, next_group):
# Solve the current group; make a path from the entry_cell to one of the cells in the next group,
# and use all cells in the group
direction = next_group.pos-self.pos
self.fill_clock_wise()
exit_candidate = entry_cell.next
if next_group.is_cell_adjacent(exit_candidate):
self.fill_counter_clock_wise()
exit_candidate.next = self.grid.cell(exit_candidate.pos+direction)
return exit_candidate.next
self.fill_counter_clock_wise()
exit_candidate = entry_cell.next
if next_group.is_cell_adjacent(exit_candidate):
self.fill_clock_wise()
exit_candidate.next = self.grid.cell(exit_candidate.pos+direction)
return exit_candidate.next
# FIXME: We can only get here for some of the 3x2/2x3 cases
print(self.pos.__str__())
print(next_group.pos.__str__())
print(entry_cell.pos.__str__())
print(self.__str__())
print(self.grid.__str__())
raise("Unhandled case")
def solve_end_via_cycle(self, entry_cell, destination_cell):
# Solve the current group; make a path from the entry_cell to the destination cell by cycling around the cell
# This fuction will return the number of cells in the group that have not been used (ideally 0)
# Pre: entry_cell != destination_cell
# Choose between clock-wise and counter clock-wise:
self.fill_clock_wise()
clock_wise_path = self.grid.get_path(entry_cell, destination_cell)
self.fill_counter_clock_wise()
counter_clock_wise_path = self.grid.get_path(entry_cell, destination_cell)
if (len(clock_wise_path) > len(counter_clock_wise_path)):
self.fill_clock_wise()
path = clock_wise_path
else:
path = counter_clock_wise_path
# Clear any cells that are not part of the path
for cell in itertools.chain.from_iterable(self.cells):
if (cell not in path):
cell.next = None
destination_cell.next = None
return self.nr_unfilled()
def solve_end_via_changed_entry(self, entry_cell, destination_cell):
# Solve the current group; make a path from the entry_cell to the destination cell by attempting backtracking and entering the group from another cell
# This fuction will return the number of cells in the group that have not been used (will be at least 1)
if (self.is_cell_adjacent(entry_cell.prev().prev())):
redirect = entry_cell.prev().prev()
direction = self.pos-redirect.group.pos
entry_cell.prev().next = None
redirect.next = self.grid.cell(redirect.pos+direction)
# Now solve for the new problem
return self.solve_end(redirect.next, destination_cell)+1
else:
# No local solution, perhaps a different route will help?
return self.nr_unfilled()
def solve_end(self, entry_cell, destination_cell):
# Solve the current group; make a path from the entry_cell to the destination cell.
# This fuction will return the number of cells in the group that have not been used (ideally 0)
if (entry_cell == destination_cell):
# We enter at the location where we need to finish
# There might be a solution by slightly altering the previous group to exit that group a bit earlier:
return self.solve_end_via_changed_entry(entry_cell, destination_cell)
else:
# Solve it by running around the outside of the cell
return self.solve_end_via_cycle(entry_cell, destination_cell)
class Group2x2(Group):
pass
class Group2x3(Group):
pass
class Group3x2(Group):
pass
class Group3x3(Group):
def solve_path(self, entry_cell, next_group):
# Solve the current group; make a path from the entry_cell to one of the cells in the next group,
# and try to use all cells in the group (not always possible)
distance = next_group.pos - self.pos
if (distance.y == -1):
# We entered the group from the left and have to leave it upwards
# Figure out the relative y position where we entered
y = 0
while (self.cells[y][0] != entry_cell):
y+=1
# Go all the way down
cell = entry_cell
for i in range(2-y):
cell = entry_cell.move_down()
# Now zig-zag up
cell = cell.move_right()
cell = cell.move_right()
cell = cell.move_up()
cell = cell.move_left()
if (y == 2):
# The zig-zag to the left can do one extra move
cell = cell.move_left()
cell = cell.move_up()
cell = cell.move_right()
if (y == 2):
# The zig-zag to the right can do one extra move
cell = cell.move_left()
cell = cell.move_up()
else:
# We entered the group from the top and have to leave it towards the left
# Figure out the relative x position where we entered
x = 0
while (self.cells[0][x] != entry_cell):
x+=1
# Go all the way to the right
cell = entry_cell
for i in range(2-y):
cell = entry_cell.move_right()
# Now zig-zag left
cell = cell.move_down()
cell = cell.move_down()
cell = cell.move_left()
cell = cell.move_up()
if (x == 2):
# The zig-zag to the left can do one extra move
cell = cell.move_up()
cell = cell.move_left()
cell = cell.move_down()
if (y == 2):
# The zig-zag to the right can do one extra move
cell = cell.move_down()
cell = cell.move_left()
return cell
def solve_end(self, entry_cell, destination_cell):
# Solve the current group; make a path from the entry_cell to the destination cell.
# This fuction will return the number of cells in the group that have not been used (ideally 0)
if (entry_cell == destination_cell):
if (entry_cell == self.cells[0][0]):
# We enter and at the top left corner of the 3x3 cell, leaving a nice L shape with an even number of empty cells
# that will be filled automatically by the extend part of the algorithm
# TODO: Is this true? We have a problem if it is possible that none of the adjoining 3x2/2x3 cells have an extension option
return 0
else:
# There might be a solution by slightly altering the previous group to exit that group a bit earlier:
return self.solve_end_via_changed_entry(entry_cell, destination_cell)
else:
# Make a path from entry to destination, the extend part of the algorithm will fill out the missing parts
cell = entry_cell
while (cell != destination_cell):
distance = destination_cell.pos - cell.pos
if (distance.x > 0):
cell.move_right()
elif (distance.x < 0):
cell.move_left()
elif (distance.y > 0):
cell.move_down()
else: #(distance.y < 0)
cell.move_up()
cell = cell.next
return self.nr_unfilled()
class Grid:
def __init__(self, n, m, x1, y1, x2, y2):
self.n = n
self.m = m
self.cells = [[Cell(Position(x,y)) for x in range(n)] for y in range(m)]
self.groups = [[self._group_factory_method(Position(x, y)) for x in range(n//2)] for y in range(m//2)]
self.c1 = self.cell(Position(x1-1,y1-1))
self.c2 = self.cell(Position(x2-1,y2-1))
self.c2.is_finish = True
self.g1 = self.group(Position((x1-1)//2,(y1-1)//2))
self.g2 = self.group(Position((x2-1)//2,(y2-1)//2))
def _group_factory_method(self, pos):
cellsx = 2 if ((2*pos.x+3) != self.n) else 3
cellsy = 2 if ((2*pos.y+3) != self.m) else 3
if (cellsx == 2) and (cellsy == 2):
return Group2x2(self, pos)
elif (cellsx == 3) and (cellsy == 3):
return Group3x3(self, pos)
elif (cellsx == 3):
return Group2x3(self, pos)
else:
return Group3x2(self, pos)
def __str__(self):
result = []
for row in self.groups:
divider = []
lines = [[],[],[]]
for group in row:
group_lines = group.__str__().split("\n")
divider.append("-" * group.cellsx)
for (index, line) in enumerate(group_lines):
lines[index].append(line)
for line in lines:
if len(line) > 0:
result.append("|%s|" % ("|".join(line)))
divider = "+%s+" % "+".join(divider)
result.append(divider)
result.insert(0, divider)
return "\n".join(result)
def cell(self, pos):
if (0 <= pos.x) and (pos.x < self.n) and (0 <= pos.y) and (pos.y < self.m):
return self.cells[pos.y][pos.x]
else:
return None
def group(self, pos):
return self.groups[pos.y][pos.x]
def extend(self):
# Given an available route from start to finish, fill in the rest of the groups
cell = self.c1
while (cell != self.c2):
# Find any pair of empty adjacent cells that are also adjacent to the path
adjacent_to_cell = [c for c in cell.adjacent() if (c != cell.next) and (c.is_empty())]
adjacent_to_next = [c for c in cell.next.adjacent() if (c != cell) and (c.is_empty())]
candidates = [(c1, c2) for (c1,c2) in itertools.product(adjacent_to_cell, adjacent_to_next) if (c1 in c2.adjacent())]
if len(candidates) > 0:
temp = cell.next
(a1, a2) = candidates[0]
cell.next = a1
a1.next = a2
a2.next = temp
else:
cell = cell.next
def solve(self):
# Find route from starting group to ending group
current_group = self.g1
route = []
while (current_group != self.g2):
distance = self.g2.pos - current_group.pos
if (distance.x > 0):
current_group = self.group(current_group.pos.right())
elif (distance.x < 0):
current_group = self.group(current_group.pos.left())
elif (distance.y > 0):
current_group = self.group(current_group.pos.down())
else: #(distance.y < 0)
current_group = self.group(current_group.pos.up())
route.append(current_group)
#print(",".join([group.pos.__str__() for group in route]))
current_cell = self.c1
for next_group in route:
current_cell = current_cell.group.solve_path(current_cell, next_group)
missed = current_cell.group.solve_end(current_cell, self.c2)
#print(missed)
# FIXME: Adjust route if missed > 1
self.extend()
def get_path(self, start=None, finish=None):
# Returns a list of all cells on the path
# If no start and end cell are given it will return the path from the starting cell (c1),
# until the path ends (for a finished solution that is cell c2)
cell = start if (start) else self.c1
path = [cell]
while (cell.next != finish):
cell = cell.next
path.append(cell)
return path
def print_answer(self):
path = self.get_path()
print(len(path))
print("\n".join(["%d %d" % (cell.pos.x+1, cell.pos.y+1) for cell in path]))
(n,m) = map(int, input().split())
(x1,y1) = map(int, input().split())
(x2,y2) = map(int, input().split())
g = Grid(n,m,x1,y1,x2,y2)
g.solve()
g.print_answer()
print(g)
print(len(g.get_path()))
``` | instruction | 0 | 31,813 | 15 | 63,626 |
No | output | 1 | 31,813 | 15 | 63,627 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has got a magic matrix a of size n Γ m. The rows of the matrix are numbered from 1 to n from top to bottom, the columns are numbered from 1 to m from left to right. Let a_{ij} be the element in the intersection of the i-th row and the j-th column.
Vasya has also got a chip. Initially, the chip is in the intersection of the r-th row and the c-th column (that is, in the element a_{rc}). Vasya performs the following process as long as possible: among all elements of the matrix having their value less than the value of the element with the chip in it, Vasya randomly and equiprobably chooses one element and moves his chip to this element.
After moving the chip, he adds to his score the square of the Euclidean distance between these elements (that is, between the element in which the chip is now and the element the chip was moved from). The process ends when there are no elements having their values less than the value of the element with the chip in it.
Euclidean distance between matrix elements with coordinates (i_1, j_1) and (i_2, j_2) is equal to β{(i_1-i_2)^2 + (j_1-j_2)^2}.
Calculate the expected value of the Vasya's final score.
It can be shown that the answer can be represented as P/Q, where P and Q are coprime integer numbers, and Q notβ‘ 0~(mod ~ 998244353). Print the value P β
Q^{-1} modulo 998244353.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 1 000) β the number of rows and the number of columns in the matrix a.
The following n lines contain description of the matrix a. The i-th line contains m integers a_{i1}, a_{i2}, ..., a_{im} ~ (0 β€ a_{ij} β€ 10^9).
The following line contains two integers r and c (1 β€ r β€ n, 1 β€ c β€ m) β the index of row and the index of column where the chip is now.
Output
Print the expected value of Vasya's final score in the format described in the problem statement.
Examples
Input
1 4
1 1 2 1
1 3
Output
2
Input
2 3
1 5 7
2 3 1
1 2
Output
665496238
Note
In the first example, Vasya will move his chip exactly once. The expected value of the final score is equal to (1^2 + 2^2+ 1^2)/(3) = 2. | instruction | 0 | 32,508 | 15 | 65,016 |
Tags: dp, math, probabilities
Correct Solution:
```
import io, os,sys
# Trying to speed up meooows submission
a = os.read(0, os.fstat(0).st_size)
# Speed
inp = []
i = 0
numb = 0
try:
while True:
if a[i] >= b'0'[0]:
numb = 10 * numb + a[i] - 48
elif a[i] != b'\r'[0]:
inp.append(numb)
numb = 0
i += 1
except:
pass
if a and a[-1] >= b'0'[0]:
inp.append(numb)
ii = 0
import heapq
def heapsorted(iterable):
h = [value for value in iterable]
heapq.heapify(h)
return [heapq.heappop(h) for i in range(len(h))]
def heapsort(h):
heapq.heapify(h)
h += [heapq.heappop(h) for i in range(len(h))]
# Using pajenegod's floating point mod mul
MOD = 998244353
MODF = float(MOD)
MAGIC = 6755399441055744.0
SHRT = 65536.0
MODF_INV = 1.0 / MODF
SHRT_INV = 1.0 / SHRT
fround = lambda x: (x + MAGIC) - MAGIC
fmod = lambda a: a - MODF * fround(MODF_INV * a)
fmul = lambda a, b, c=0.0: fmod(fmod(a * SHRT) * fround(SHRT_INV * b) + a * (b - SHRT * fround(b * SHRT_INV)) + c)
def fpow(x, y):
if y == 0:
return 1.0
res = 1.0
while y > 1:
if y & 1 == 1:
res = fmul(res, x)
x = fmul(x, x)
y >>= 1
return fmul(res, x)
n, m = inp[ii], inp[ii+1]
ii += 2
a = inp[ii:ii+n*m]
ii += n*m
# stable sort FTW
a = [(a[i],i) for i in range(n*m)]
heapsort(a)
sx, sy = inp[ii], inp[ii+1]
ii += 2
MX = n*m+1
inv = [0.0]*MX
inv[1] = 1.0
for i in range(2, MX):
inv[i] = fmul(-1.0*(MOD // i), inv[MOD % i])
fsum = isum = i2sum = jsum = j2sum = 0
cnt = 0
inv_cnt = 0.0
i = 0
fa = [0] * (n * m)
while i < n * m:
j = i + 1
while j < n * m and a[i][0] == a[j][0]:
j += 1
for k in range(i, j):
x,y = divmod(a[k][1],m)
x += 1
y += 1
f = fmul(1.0*cnt,1.0*(x * x + y * y), i2sum + j2sum + fsum - 2.0 * (x * isum + y * jsum))
f = fmul(f, inv_cnt)
if sx == x and sy == y:
print(int(f + MODF) % MOD)
sys.exit()
fa[k] = int(f)
for k in range(i, j):
x,y = divmod(a[k][1],m)
x += 1.0
y += 1.0
fsum = (fa[k] + fsum)%MOD
isum += x
i2sum += x * x
jsum += y
j2sum += y * y
cnt += j - i
inv_cnt = inv[cnt]
i = j
``` | output | 1 | 32,508 | 15 | 65,017 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has got a magic matrix a of size n Γ m. The rows of the matrix are numbered from 1 to n from top to bottom, the columns are numbered from 1 to m from left to right. Let a_{ij} be the element in the intersection of the i-th row and the j-th column.
Vasya has also got a chip. Initially, the chip is in the intersection of the r-th row and the c-th column (that is, in the element a_{rc}). Vasya performs the following process as long as possible: among all elements of the matrix having their value less than the value of the element with the chip in it, Vasya randomly and equiprobably chooses one element and moves his chip to this element.
After moving the chip, he adds to his score the square of the Euclidean distance between these elements (that is, between the element in which the chip is now and the element the chip was moved from). The process ends when there are no elements having their values less than the value of the element with the chip in it.
Euclidean distance between matrix elements with coordinates (i_1, j_1) and (i_2, j_2) is equal to β{(i_1-i_2)^2 + (j_1-j_2)^2}.
Calculate the expected value of the Vasya's final score.
It can be shown that the answer can be represented as P/Q, where P and Q are coprime integer numbers, and Q notβ‘ 0~(mod ~ 998244353). Print the value P β
Q^{-1} modulo 998244353.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 1 000) β the number of rows and the number of columns in the matrix a.
The following n lines contain description of the matrix a. The i-th line contains m integers a_{i1}, a_{i2}, ..., a_{im} ~ (0 β€ a_{ij} β€ 10^9).
The following line contains two integers r and c (1 β€ r β€ n, 1 β€ c β€ m) β the index of row and the index of column where the chip is now.
Output
Print the expected value of Vasya's final score in the format described in the problem statement.
Examples
Input
1 4
1 1 2 1
1 3
Output
2
Input
2 3
1 5 7
2 3 1
1 2
Output
665496238
Note
In the first example, Vasya will move his chip exactly once. The expected value of the final score is equal to (1^2 + 2^2+ 1^2)/(3) = 2. | instruction | 0 | 32,509 | 15 | 65,018 |
Tags: dp, math, probabilities
Correct Solution:
```
import io, os,sys
# Trying to speed up meooows submission
a = os.read(0, os.fstat(0).st_size)
# Speed
inp = []
i = 0
numb = 0
try:
while True:
if a[i] >= b'0'[0]:
numb = 10 * numb + a[i] - 48
elif a[i] != b'\r'[0]:
inp.append(numb)
numb = 0
i += 1
except:
pass
if a and a[-1] >= b'0'[0]:
inp.append(numb)
ii = 0
def merge(a,b):
s = []
# Make so that b will end first
ma = a[0]
mb = b[0]
if ma > mb:
a,b = b,a
while b:
if a[-1] > b[-1]:
s.append(a.pop())
else:
s.append(b.pop())
while a:
s.append(a.pop())
s.reverse()
return s
def mergesort(A):
if len(A) == 1:
return A
a = mergesort(A[:len(A)//2])
b = mergesort(A[len(A)//2:])
c = merge(a,b)
return c
# Using pajenegod's floating point mod mul
MOD = 998244353
MODF = float(MOD)
MAGIC = 6755399441055744.0
SHRT = 65536.0
MODF_INV = 1.0 / MODF
SHRT_INV = 1.0 / SHRT
fround = lambda x: (x + MAGIC) - MAGIC
fmod = lambda a: a - MODF * fround(MODF_INV * a)
fmul = lambda a, b, c=0.0: fmod(fmod(a * SHRT) * fround(SHRT_INV * b) + a * (b - SHRT * fround(b * SHRT_INV)) + c)
def fpow(x, y):
if y == 0:
return 1.0
res = 1.0
while y > 1:
if y & 1 == 1:
res = fmul(res, x)
x = fmul(x, x)
y >>= 1
return fmul(res, x)
n, m = inp[ii], inp[ii+1]
ii += 2
a = inp[ii:ii+n*m]
ii += n*m
# stable sort FTW
a = [(a[i],i) for i in range(n*m)]
a = mergesort(a)
sx, sy = inp[ii], inp[ii+1]
ii += 2
MX = n*m+1
inv = [0.0]*MX
inv[1] = 1.0
for i in range(2, MX):
inv[i] = fmul(-1.0*(MOD // i), inv[MOD % i])
fsum = isum = i2sum = jsum = j2sum = 0
cnt = 0
inv_cnt = 0.0
i = 0
fa = [0] * (n * m)
while i < n * m:
j = i + 1
while j < n * m and a[i][0] == a[j][0]:
j += 1
for k in range(i, j):
x,y = divmod(a[k][1],m)
x += 1
y += 1
f = fmul(1.0*cnt,1.0*(x * x + y * y), i2sum + j2sum + fsum - 2.0 * (x * isum + y * jsum))
f = fmul(f, inv_cnt)
if sx == x and sy == y:
print(int(f + MODF) % MOD)
sys.exit()
fa[k] = int(f)
for k in range(i, j):
x,y = divmod(a[k][1],m)
x += 1.0
y += 1.0
fsum = (fa[k] + fsum)%MOD
isum += x
i2sum += x * x
jsum += y
j2sum += y * y
cnt += j - i
inv_cnt = inv[cnt]
i = j
``` | output | 1 | 32,509 | 15 | 65,019 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has got a magic matrix a of size n Γ m. The rows of the matrix are numbered from 1 to n from top to bottom, the columns are numbered from 1 to m from left to right. Let a_{ij} be the element in the intersection of the i-th row and the j-th column.
Vasya has also got a chip. Initially, the chip is in the intersection of the r-th row and the c-th column (that is, in the element a_{rc}). Vasya performs the following process as long as possible: among all elements of the matrix having their value less than the value of the element with the chip in it, Vasya randomly and equiprobably chooses one element and moves his chip to this element.
After moving the chip, he adds to his score the square of the Euclidean distance between these elements (that is, between the element in which the chip is now and the element the chip was moved from). The process ends when there are no elements having their values less than the value of the element with the chip in it.
Euclidean distance between matrix elements with coordinates (i_1, j_1) and (i_2, j_2) is equal to β{(i_1-i_2)^2 + (j_1-j_2)^2}.
Calculate the expected value of the Vasya's final score.
It can be shown that the answer can be represented as P/Q, where P and Q are coprime integer numbers, and Q notβ‘ 0~(mod ~ 998244353). Print the value P β
Q^{-1} modulo 998244353.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 1 000) β the number of rows and the number of columns in the matrix a.
The following n lines contain description of the matrix a. The i-th line contains m integers a_{i1}, a_{i2}, ..., a_{im} ~ (0 β€ a_{ij} β€ 10^9).
The following line contains two integers r and c (1 β€ r β€ n, 1 β€ c β€ m) β the index of row and the index of column where the chip is now.
Output
Print the expected value of Vasya's final score in the format described in the problem statement.
Examples
Input
1 4
1 1 2 1
1 3
Output
2
Input
2 3
1 5 7
2 3 1
1 2
Output
665496238
Note
In the first example, Vasya will move his chip exactly once. The expected value of the final score is equal to (1^2 + 2^2+ 1^2)/(3) = 2. | instruction | 0 | 32,510 | 15 | 65,020 |
Tags: dp, math, probabilities
Correct Solution:
```
import io
import os
import sys
# Trying to speed up c1729, which in turn is trying to speed up pajenegod's submissions
# which in turn is trying to speed up meooows code
a = os.read(0, os.fstat(0).st_size)
# Speed
inp = []
i = 0
numb = 0
try:
while True:
if a[i] >= b'0' [0]:
numb = 10 * numb + a[i] - 48
elif a[i] != b'\r' [0]:
inp.append(numb)
numb = 0
i += 1
except:
pass
if a and a[-1] >= b'0' [0]:
inp.append(numb)
ii = 0
# Homemade stable mergesort
def mergesort(A, key=None, reverse=False):
if key is None:
key = lambda x: x
B, n = A[:], len(A)
for i in range(0, n - 1, 2):
if key(A[i]) > key(A[i ^ 1]):
A[i], A[i ^ 1] = A[i ^ 1], A[i]
width = 2
while width < n:
for i in range(0, n, 2 * width):
R1 = j = min(i + width, n)
R2 = min(i + 2 * width, n)
k = i
while i < R1 and j < R2:
if key(A[i]) > key(A[j]):
B[k] = A[j]
j += 1
else:
B[k] = A[i]
i += 1
k += 1
while i < R1:
B[k] = A[i]
k += 1
i += 1
while k < R2:
B[k] = A[k]
k += 1
A, B = B, A
width *= 2
if reverse:
A.reverse()
return A
# Using pajenegod's floating point mod mul
MOD = 998244353
MODF = float(MOD)
MAGIC = 6755399441055744.0
SHRT = 65536.0
MODF_INV = 1.0 / MODF
SHRT_INV = 1.0 / SHRT
fround = lambda x: (x + MAGIC) - MAGIC
fmod = lambda a: a - MODF * fround(MODF_INV * a)
fmul = lambda a, b, c=0.0: fmod(fmod(a * SHRT) * fround(SHRT_INV * b) + a * (b - SHRT * fround(b * SHRT_INV)) + c)
def fpow(x, y):
if y == 0:
return 1.0
res = 1.0
while y > 1:
if y & 1 == 1:
res = fmul(res, x)
x = fmul(x, x)
y >>= 1
return fmul(res, x)
n, m = inp[ii], inp[ii + 1]
ii += 2
a = inp[ii:ii + n * m]
ii += n * m
# try this against vanilla sort
order = mergesort(list(range(n * m)), key=lambda x: a[x])
sx, sy = inp[ii], inp[ii + 1]
ii += 2
MX = n * m + 1
inv = [0.0] * MX
inv[1] = 1.0
for i in range(2, MX):
inv[i] = fmul(-1.0 * (MOD // i), inv[MOD % i])
fsum = isum = i2sum = jsum = j2sum = 0
cnt = 0
inv_cnt = 0.0
i = 0
fa = [0] * (n * m)
while i < n * m:
j = i + 1
while j < n * m and a[order[i]] == a[order[j]]:
j += 1
for k in range(i, j):
x, y = divmod(order[k], m)
x += 1
y += 1
f = fmul(1.0 * cnt, 1.0 * (x * x + y * y), i2sum + j2sum + fsum - 2.0 * (x * isum + y * jsum))
f = fmul(f, inv_cnt)
if sx == x and sy == y:
print(int(f + MODF) % MOD)
sys.exit()
fa[k] = int(f)
for k in range(i, j):
x, y = divmod(order[k], m)
x += 1.0
y += 1.0
fsum = (fa[k] + fsum) % MOD
isum += x
i2sum += x * x
jsum += y
j2sum += y * y
cnt += j - i
inv_cnt = inv[cnt]
i = j
``` | output | 1 | 32,510 | 15 | 65,021 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has got a magic matrix a of size n Γ m. The rows of the matrix are numbered from 1 to n from top to bottom, the columns are numbered from 1 to m from left to right. Let a_{ij} be the element in the intersection of the i-th row and the j-th column.
Vasya has also got a chip. Initially, the chip is in the intersection of the r-th row and the c-th column (that is, in the element a_{rc}). Vasya performs the following process as long as possible: among all elements of the matrix having their value less than the value of the element with the chip in it, Vasya randomly and equiprobably chooses one element and moves his chip to this element.
After moving the chip, he adds to his score the square of the Euclidean distance between these elements (that is, between the element in which the chip is now and the element the chip was moved from). The process ends when there are no elements having their values less than the value of the element with the chip in it.
Euclidean distance between matrix elements with coordinates (i_1, j_1) and (i_2, j_2) is equal to β{(i_1-i_2)^2 + (j_1-j_2)^2}.
Calculate the expected value of the Vasya's final score.
It can be shown that the answer can be represented as P/Q, where P and Q are coprime integer numbers, and Q notβ‘ 0~(mod ~ 998244353). Print the value P β
Q^{-1} modulo 998244353.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 1 000) β the number of rows and the number of columns in the matrix a.
The following n lines contain description of the matrix a. The i-th line contains m integers a_{i1}, a_{i2}, ..., a_{im} ~ (0 β€ a_{ij} β€ 10^9).
The following line contains two integers r and c (1 β€ r β€ n, 1 β€ c β€ m) β the index of row and the index of column where the chip is now.
Output
Print the expected value of Vasya's final score in the format described in the problem statement.
Examples
Input
1 4
1 1 2 1
1 3
Output
2
Input
2 3
1 5 7
2 3 1
1 2
Output
665496238
Note
In the first example, Vasya will move his chip exactly once. The expected value of the final score is equal to (1^2 + 2^2+ 1^2)/(3) = 2. | instruction | 0 | 32,511 | 15 | 65,022 |
Tags: dp, math, probabilities
Correct Solution:
```
import io, os,sys
# Trying to speed up meooows submission
a = os.read(0, os.fstat(0).st_size)
# Speed
inp = []
i = 0
numb = 0
try:
while True:
if a[i] >= b'0'[0]:
numb = 10 * numb + a[i] - 48
elif a[i] != b'\r'[0]:
inp.append(numb)
numb = 0
i += 1
except:
pass
if a and a[-1] >= b'0'[0]:
inp.append(numb)
ii = 0
def merge(a,b):
s = []
while a and b:
if a[-1] > b[-1]:
s.append(a.pop())
else:
s.append(b.pop())
while a:
s.append(a.pop())
while b:
s.append(b.pop())
s.reverse()
return s
def mergesort(A):
if len(A) == 1:
return A
a = mergesort(A[:len(A)//2])
b = mergesort(A[len(A)//2:])
c = merge(a,b)
return c
# Using pajenegod's floating point mod mul
MOD = 998244353
MODF = float(MOD)
MAGIC = 6755399441055744.0
SHRT = 65536.0
MODF_INV = 1.0 / MODF
SHRT_INV = 1.0 / SHRT
fround = lambda x: (x + MAGIC) - MAGIC
fmod = lambda a: a - MODF * fround(MODF_INV * a)
fmul = lambda a, b, c=0.0: fmod(fmod(a * SHRT) * fround(SHRT_INV * b) + a * (b - SHRT * fround(b * SHRT_INV)) + c)
def fpow(x, y):
if y == 0:
return 1.0
res = 1.0
while y > 1:
if y & 1 == 1:
res = fmul(res, x)
x = fmul(x, x)
y >>= 1
return fmul(res, x)
n, m = inp[ii], inp[ii+1]
ii += 2
a = inp[ii:ii+n*m]
ii += n*m
# stable sort FTW
a = [(a[i],i) for i in range(n*m)]
a = mergesort(a)
sx, sy = inp[ii], inp[ii+1]
ii += 2
MX = n*m+1
inv = [0.0]*MX
inv[1] = 1.0
for i in range(2, MX):
inv[i] = fmul(-1.0*(MOD // i), inv[MOD % i])
fsum = isum = i2sum = jsum = j2sum = 0
cnt = 0
inv_cnt = 0.0
i = 0
fa = [0] * (n * m)
while i < n * m:
j = i + 1
while j < n * m and a[i][0] == a[j][0]:
j += 1
for k in range(i, j):
x,y = divmod(a[k][1],m)
x += 1
y += 1
f = fmul(1.0*cnt,1.0*(x * x + y * y), i2sum + j2sum + fsum - 2.0 * (x * isum + y * jsum))
f = fmul(f, inv_cnt)
if sx == x and sy == y:
print(int(f + MODF) % MOD)
sys.exit()
fa[k] = int(f)
for k in range(i, j):
x,y = divmod(a[k][1],m)
x += 1.0
y += 1.0
fsum = (fa[k] + fsum)%MOD
isum += x
i2sum += x * x
jsum += y
j2sum += y * y
cnt += j - i
inv_cnt = inv[cnt]
i = j
``` | output | 1 | 32,511 | 15 | 65,023 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has got a magic matrix a of size n Γ m. The rows of the matrix are numbered from 1 to n from top to bottom, the columns are numbered from 1 to m from left to right. Let a_{ij} be the element in the intersection of the i-th row and the j-th column.
Vasya has also got a chip. Initially, the chip is in the intersection of the r-th row and the c-th column (that is, in the element a_{rc}). Vasya performs the following process as long as possible: among all elements of the matrix having their value less than the value of the element with the chip in it, Vasya randomly and equiprobably chooses one element and moves his chip to this element.
After moving the chip, he adds to his score the square of the Euclidean distance between these elements (that is, between the element in which the chip is now and the element the chip was moved from). The process ends when there are no elements having their values less than the value of the element with the chip in it.
Euclidean distance between matrix elements with coordinates (i_1, j_1) and (i_2, j_2) is equal to β{(i_1-i_2)^2 + (j_1-j_2)^2}.
Calculate the expected value of the Vasya's final score.
It can be shown that the answer can be represented as P/Q, where P and Q are coprime integer numbers, and Q notβ‘ 0~(mod ~ 998244353). Print the value P β
Q^{-1} modulo 998244353.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 1 000) β the number of rows and the number of columns in the matrix a.
The following n lines contain description of the matrix a. The i-th line contains m integers a_{i1}, a_{i2}, ..., a_{im} ~ (0 β€ a_{ij} β€ 10^9).
The following line contains two integers r and c (1 β€ r β€ n, 1 β€ c β€ m) β the index of row and the index of column where the chip is now.
Output
Print the expected value of Vasya's final score in the format described in the problem statement.
Examples
Input
1 4
1 1 2 1
1 3
Output
2
Input
2 3
1 5 7
2 3 1
1 2
Output
665496238
Note
In the first example, Vasya will move his chip exactly once. The expected value of the final score is equal to (1^2 + 2^2+ 1^2)/(3) = 2. | instruction | 0 | 32,512 | 15 | 65,024 |
Tags: dp, math, probabilities
Correct Solution:
```
import io
import os
import sys
# Trying to speed up c1729, which in turn is trying to speed up pajenegod's submissions
# which in turn is trying to speed up meooows code
a = os.read(0, os.fstat(0).st_size)
# Speed
inp = []
i = 0
numb = 0
try:
while True:
if a[i] >= b'0' [0]:
numb = 10 * numb + a[i] - 48
elif a[i] != b'\r' [0]:
inp.append(numb)
numb = 0
i += 1
except:
pass
if a and a[-1] >= b'0' [0]:
inp.append(numb)
ii = 0
def mergesort(A):
B, n = A[:], len(A)
for i in range(0,n-1,2):
if A[i^1]<A[i]:
A[i],A[i^1] = A[i^1],A[i]
width = 2
while width < n:
for i in range(0, n, 2*width):
R1 = j = i + width
if R1>=n:
B[i:] = A[i:]
continue
R2 = min(i + 2 * width, n)
k = i
while i<R1 and j<R2:
if A[i] < A[j]:
B[k] = A[i]
i += 1
k += 1
else:
B[k] = A[j]
j += 1
k += 1
if i<R1:
B[k:R2] = A[i:R1]
else:
B[k:R2] = A[k:R2]
A,B = B,A
width *= 2
return A
# Using pajenegod's floating point mod mul
MOD = 998244353
MODF = float(MOD)
MAGIC = 6755399441055744.0
SHRT = 65536.0
MODF_INV = 1.0 / MODF
SHRT_INV = 1.0 / SHRT
fround = lambda x: (x + MAGIC) - MAGIC
fmod = lambda a: a - MODF * fround(MODF_INV * a)
fmul = lambda a, b, c=0.0: fmod(fmod(a * SHRT) * fround(SHRT_INV * b) + a * (b - SHRT * fround(b * SHRT_INV)) + c)
def fpow(x, y):
if y == 0:
return 1.0
res = 1.0
while y > 1:
if y & 1 == 1:
res = fmul(res, x)
x = fmul(x, x)
y >>= 1
return fmul(res, x)
n, m = inp[ii], inp[ii + 1]
ii += 2
a = inp[ii:ii + n * m]
ii += n * m
# try this against vanilla sort
a = [(a[i], i) for i in range(n * m)]
a = mergesort(a)
sx, sy = inp[ii], inp[ii + 1]
ii += 2
MX = n * m + 1
inv = [0.0] * MX
inv[1] = 1.0
for i in range(2, MX):
inv[i] = fmul(-1.0 * (MOD // i), inv[MOD % i])
fsum = isum = i2sum = jsum = j2sum = 0
cnt = 0
inv_cnt = 0.0
i = 0
fa = [0] * (n * m)
while i < n * m:
j = i + 1
while j < n * m and a[i][0] == a[j][0]:
j += 1
for k in range(i, j):
x, y = divmod(a[k][1], m)
x += 1
y += 1
f = fmul(1.0 * cnt, 1.0 * (x * x + y * y), i2sum + j2sum + fsum - 2.0 * (x * isum + y * jsum))
f = fmul(f, inv_cnt)
if sx == x and sy == y:
print(int(f + MODF) % MOD)
sys.exit()
fa[k] = int(f)
for k in range(i, j):
x, y = divmod(a[k][1], m)
x += 1.0
y += 1.0
fsum = (fa[k] + fsum) % MOD
isum += x
i2sum += x * x
jsum += y
j2sum += y * y
cnt += j - i
inv_cnt = inv[cnt]
i = j
``` | output | 1 | 32,512 | 15 | 65,025 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has got a magic matrix a of size n Γ m. The rows of the matrix are numbered from 1 to n from top to bottom, the columns are numbered from 1 to m from left to right. Let a_{ij} be the element in the intersection of the i-th row and the j-th column.
Vasya has also got a chip. Initially, the chip is in the intersection of the r-th row and the c-th column (that is, in the element a_{rc}). Vasya performs the following process as long as possible: among all elements of the matrix having their value less than the value of the element with the chip in it, Vasya randomly and equiprobably chooses one element and moves his chip to this element.
After moving the chip, he adds to his score the square of the Euclidean distance between these elements (that is, between the element in which the chip is now and the element the chip was moved from). The process ends when there are no elements having their values less than the value of the element with the chip in it.
Euclidean distance between matrix elements with coordinates (i_1, j_1) and (i_2, j_2) is equal to β{(i_1-i_2)^2 + (j_1-j_2)^2}.
Calculate the expected value of the Vasya's final score.
It can be shown that the answer can be represented as P/Q, where P and Q are coprime integer numbers, and Q notβ‘ 0~(mod ~ 998244353). Print the value P β
Q^{-1} modulo 998244353.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 1 000) β the number of rows and the number of columns in the matrix a.
The following n lines contain description of the matrix a. The i-th line contains m integers a_{i1}, a_{i2}, ..., a_{im} ~ (0 β€ a_{ij} β€ 10^9).
The following line contains two integers r and c (1 β€ r β€ n, 1 β€ c β€ m) β the index of row and the index of column where the chip is now.
Output
Print the expected value of Vasya's final score in the format described in the problem statement.
Examples
Input
1 4
1 1 2 1
1 3
Output
2
Input
2 3
1 5 7
2 3 1
1 2
Output
665496238
Note
In the first example, Vasya will move his chip exactly once. The expected value of the final score is equal to (1^2 + 2^2+ 1^2)/(3) = 2. | instruction | 0 | 32,513 | 15 | 65,026 |
Tags: dp, math, probabilities
Correct Solution:
```
import io
import os
import sys
# Trying to speed up c1729, which in turn is trying to speed up pajenegod's submissions
# which in turn is trying to speed up meooows code
a = os.read(0, os.fstat(0).st_size)
# Speed
inp = []
i = 0
numb = 0
try:
while True:
if a[i] >= b'0' [0]:
numb = 10 * numb + a[i] - 48
elif a[i] != b'\r' [0]:
inp.append(numb)
numb = 0
i += 1
except:
pass
if a and a[-1] >= b'0' [0]:
inp.append(numb)
ii = 0
# Best local
def mergesort(A):
B, n = A[:], len(A)
for i in range(0,n-1,2):
if A[i^1]<A[i]:
A[i],A[i^1] = A[i^1],A[i]
width = 2
while width < n:
for i in range(0, n, 2*width):
R1 = j = i + width
if R1>=n:
while i<n:
B[i] = A[i]
i += 1
break
R2 = min(i + 2 * width, n)
k = i
while i<R1 and j<R2:
if A[i] < A[j]:
B[k] = A[i]
i += 1
else:
B[k] = A[j]
j += 1
k += 1
while i<R1:
B[k] = A[i]
i += 1
k += 1
while k<R2:
B[k] = A[k]
k += 1
A,B = B,A
width *= 2
return A
# Using pajenegod's floating point mod mul
MOD = 998244353
MODF = float(MOD)
MAGIC = 6755399441055744.0
SHRT = 65536.0
MODF_INV = 1.0 / MODF
SHRT_INV = 1.0 / SHRT
fround = lambda x: (x + MAGIC) - MAGIC
fmod = lambda a: a - MODF * fround(MODF_INV * a)
fmul = lambda a, b, c=0.0: fmod(fmod(a * SHRT) * fround(SHRT_INV * b) + a * (b - SHRT * fround(b * SHRT_INV)) + c)
def fpow(x, y):
if y == 0:
return 1.0
res = 1.0
while y > 1:
if y & 1 == 1:
res = fmul(res, x)
x = fmul(x, x)
y >>= 1
return fmul(res, x)
n, m = inp[ii], inp[ii + 1]
ii += 2
a = inp[ii:ii + n * m]
ii += n * m
# try this against vanilla sort
a = [(a[i], i) for i in range(n * m)]
a = mergesort(a)
sx, sy = inp[ii], inp[ii + 1]
ii += 2
MX = n * m + 1
inv = [0.0] * MX
inv[1] = 1.0
for i in range(2, MX):
inv[i] = fmul(-1.0 * (MOD // i), inv[MOD % i])
fsum = isum = i2sum = jsum = j2sum = 0
cnt = 0
inv_cnt = 0.0
i = 0
fa = [0] * (n * m)
while i < n * m:
j = i + 1
while j < n * m and a[i][0] == a[j][0]:
j += 1
for k in range(i, j):
x, y = divmod(a[k][1], m)
x += 1
y += 1
f = fmul(1.0 * cnt, 1.0 * (x * x + y * y), i2sum + j2sum + fsum - 2.0 * (x * isum + y * jsum))
f = fmul(f, inv_cnt)
if sx == x and sy == y:
print(int(f + MODF) % MOD)
sys.exit()
fa[k] = int(f)
for k in range(i, j):
x, y = divmod(a[k][1], m)
x += 1.0
y += 1.0
fsum = (fa[k] + fsum) % MOD
isum += x
i2sum += x * x
jsum += y
j2sum += y * y
cnt += j - i
inv_cnt = inv[cnt]
i = j
``` | output | 1 | 32,513 | 15 | 65,027 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has got a magic matrix a of size n Γ m. The rows of the matrix are numbered from 1 to n from top to bottom, the columns are numbered from 1 to m from left to right. Let a_{ij} be the element in the intersection of the i-th row and the j-th column.
Vasya has also got a chip. Initially, the chip is in the intersection of the r-th row and the c-th column (that is, in the element a_{rc}). Vasya performs the following process as long as possible: among all elements of the matrix having their value less than the value of the element with the chip in it, Vasya randomly and equiprobably chooses one element and moves his chip to this element.
After moving the chip, he adds to his score the square of the Euclidean distance between these elements (that is, between the element in which the chip is now and the element the chip was moved from). The process ends when there are no elements having their values less than the value of the element with the chip in it.
Euclidean distance between matrix elements with coordinates (i_1, j_1) and (i_2, j_2) is equal to β{(i_1-i_2)^2 + (j_1-j_2)^2}.
Calculate the expected value of the Vasya's final score.
It can be shown that the answer can be represented as P/Q, where P and Q are coprime integer numbers, and Q notβ‘ 0~(mod ~ 998244353). Print the value P β
Q^{-1} modulo 998244353.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 1 000) β the number of rows and the number of columns in the matrix a.
The following n lines contain description of the matrix a. The i-th line contains m integers a_{i1}, a_{i2}, ..., a_{im} ~ (0 β€ a_{ij} β€ 10^9).
The following line contains two integers r and c (1 β€ r β€ n, 1 β€ c β€ m) β the index of row and the index of column where the chip is now.
Output
Print the expected value of Vasya's final score in the format described in the problem statement.
Examples
Input
1 4
1 1 2 1
1 3
Output
2
Input
2 3
1 5 7
2 3 1
1 2
Output
665496238
Note
In the first example, Vasya will move his chip exactly once. The expected value of the final score is equal to (1^2 + 2^2+ 1^2)/(3) = 2. | instruction | 0 | 32,514 | 15 | 65,028 |
Tags: dp, math, probabilities
Correct Solution:
```
import io, os,sys
# Trying to speed up meooows submission
a = os.read(0, os.fstat(0).st_size)
# Speed
inp = []
i = 0
numb = 0
try:
while True:
if a[i] >= b'0'[0]:
numb = 10 * numb + a[i] - 48
elif a[i] != b'\r'[0]:
inp.append(numb)
numb = 0
i += 1
except:
pass
if a and a[-1] >= b'0'[0]:
inp.append(numb)
ii = 0
def merge(a,b):
if len(b)==1:
if a[0] > b[0]:
return [b[0],a[0]]
else:
return [a[0],b[0]]
s = []
while a and b:
if a[-1] > b[-1]:
s.append(a.pop())
else:
s.append(b.pop())
while a:
s.append(a.pop())
while b:
s.append(b.pop())
s.reverse()
return s
def mergesort(A):
if len(A) == 1:
return A
a = mergesort(A[:len(A)//2])
b = mergesort(A[len(A)//2:])
c = merge(a,b)
return c
# Using pajenegod's floating point mod mul
MOD = 998244353
MODF = float(MOD)
MAGIC = 6755399441055744.0
SHRT = 65536.0
MODF_INV = 1.0 / MODF
SHRT_INV = 1.0 / SHRT
fround = lambda x: (x + MAGIC) - MAGIC
fmod = lambda a: a - MODF * fround(MODF_INV * a)
fmul = lambda a, b, c=0.0: fmod(fmod(a * SHRT) * fround(SHRT_INV * b) + a * (b - SHRT * fround(b * SHRT_INV)) + c)
def fpow(x, y):
if y == 0:
return 1.0
res = 1.0
while y > 1:
if y & 1 == 1:
res = fmul(res, x)
x = fmul(x, x)
y >>= 1
return fmul(res, x)
n, m = inp[ii], inp[ii+1]
ii += 2
a = inp[ii:ii+n*m]
ii += n*m
# stable sort FTW
a = [(a[i],i) for i in range(n*m)]
a = mergesort(a)
sx, sy = inp[ii], inp[ii+1]
ii += 2
MX = n*m+1
inv = [0.0]*MX
inv[1] = 1.0
for i in range(2, MX):
inv[i] = fmul(-1.0*(MOD // i), inv[MOD % i])
fsum = isum = i2sum = jsum = j2sum = 0
cnt = 0
inv_cnt = 0.0
i = 0
fa = [0] * (n * m)
while i < n * m:
j = i + 1
while j < n * m and a[i][0] == a[j][0]:
j += 1
for k in range(i, j):
x,y = divmod(a[k][1],m)
x += 1
y += 1
f = fmul(1.0*cnt,1.0*(x * x + y * y), i2sum + j2sum + fsum - 2.0 * (x * isum + y * jsum))
f = fmul(f, inv_cnt)
if sx == x and sy == y:
print(int(f + MODF) % MOD)
sys.exit()
fa[k] = int(f)
for k in range(i, j):
x,y = divmod(a[k][1],m)
x += 1.0
y += 1.0
fsum = (fa[k] + fsum)%MOD
isum += x
i2sum += x * x
jsum += y
j2sum += y * y
cnt += j - i
inv_cnt = inv[cnt]
i = j
``` | output | 1 | 32,514 | 15 | 65,029 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has got a magic matrix a of size n Γ m. The rows of the matrix are numbered from 1 to n from top to bottom, the columns are numbered from 1 to m from left to right. Let a_{ij} be the element in the intersection of the i-th row and the j-th column.
Vasya has also got a chip. Initially, the chip is in the intersection of the r-th row and the c-th column (that is, in the element a_{rc}). Vasya performs the following process as long as possible: among all elements of the matrix having their value less than the value of the element with the chip in it, Vasya randomly and equiprobably chooses one element and moves his chip to this element.
After moving the chip, he adds to his score the square of the Euclidean distance between these elements (that is, between the element in which the chip is now and the element the chip was moved from). The process ends when there are no elements having their values less than the value of the element with the chip in it.
Euclidean distance between matrix elements with coordinates (i_1, j_1) and (i_2, j_2) is equal to β{(i_1-i_2)^2 + (j_1-j_2)^2}.
Calculate the expected value of the Vasya's final score.
It can be shown that the answer can be represented as P/Q, where P and Q are coprime integer numbers, and Q notβ‘ 0~(mod ~ 998244353). Print the value P β
Q^{-1} modulo 998244353.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 1 000) β the number of rows and the number of columns in the matrix a.
The following n lines contain description of the matrix a. The i-th line contains m integers a_{i1}, a_{i2}, ..., a_{im} ~ (0 β€ a_{ij} β€ 10^9).
The following line contains two integers r and c (1 β€ r β€ n, 1 β€ c β€ m) β the index of row and the index of column where the chip is now.
Output
Print the expected value of Vasya's final score in the format described in the problem statement.
Examples
Input
1 4
1 1 2 1
1 3
Output
2
Input
2 3
1 5 7
2 3 1
1 2
Output
665496238
Note
In the first example, Vasya will move his chip exactly once. The expected value of the final score is equal to (1^2 + 2^2+ 1^2)/(3) = 2. | instruction | 0 | 32,515 | 15 | 65,030 |
Tags: dp, math, probabilities
Correct Solution:
```
import io, os,sys
# Trying to speed up meooows submission
a = os.read(0, os.fstat(0).st_size)
# Speed
inp = []
i = 0
numb = 0
try:
while True:
if a[i] >= b'0'[0]:
numb = 10 * numb + a[i] - 48
elif a[i] != b'\r'[0]:
inp.append(numb)
numb = 0
i += 1
except:
pass
if a and a[-1] >= b'0'[0]:
inp.append(numb)
ii = 0
def sorter(A):
def merge(a,b):
if len(b)==1:
if a[0] > b[0]:
return [b[0],a[0]]
else:
return [a[0],b[0]]
s = []
while a and b:
if a[-1] > b[-1]:
s.append(a.pop())
else:
s.append(b.pop())
while a:
s.append(a.pop())
while b:
s.append(b.pop())
s.reverse()
return s
def mergesort(A):
if len(A) == 1:
return A
a = mergesort(A[:len(A)//2])
b = mergesort(A[len(A)//2:])
c = merge(a,b)
return c
return mergesort(A)
# Using pajenegod's floating point mod mul
MOD = 998244353
MODF = float(MOD)
MAGIC = 6755399441055744.0
SHRT = 65536.0
MODF_INV = 1.0 / MODF
SHRT_INV = 1.0 / SHRT
fround = lambda x: (x + MAGIC) - MAGIC
fmod = lambda a: a - MODF * fround(MODF_INV * a)
fmul = lambda a, b, c=0.0: fmod(fmod(a * SHRT) * fround(SHRT_INV * b) + a * (b - SHRT * fround(b * SHRT_INV)) + c)
def fpow(x, y):
if y == 0:
return 1.0
res = 1.0
while y > 1:
if y & 1 == 1:
res = fmul(res, x)
x = fmul(x, x)
y >>= 1
return fmul(res, x)
n, m = inp[ii], inp[ii+1]
ii += 2
a = inp[ii:ii+n*m]
ii += n*m
# stable sort FTW
a = [(a[i],i) for i in range(n*m)]
a = sorter(a)
sx, sy = inp[ii], inp[ii+1]
ii += 2
MX = n*m+1
inv = [0.0]*MX
inv[1] = 1.0
for i in range(2, MX):
inv[i] = fmul(-1.0*(MOD // i), inv[MOD % i])
fsum = isum = i2sum = jsum = j2sum = 0
cnt = 0
inv_cnt = 0.0
i = 0
fa = [0] * (n * m)
while i < n * m:
j = i + 1
while j < n * m and a[i][0] == a[j][0]:
j += 1
for k in range(i, j):
x,y = divmod(a[k][1],m)
x += 1
y += 1
f = fmul(1.0*cnt,1.0*(x * x + y * y), i2sum + j2sum + fsum - 2.0 * (x * isum + y * jsum))
f = fmul(f, inv_cnt)
if sx == x and sy == y:
print(int(f + MODF) % MOD)
sys.exit()
fa[k] = int(f)
for k in range(i, j):
x,y = divmod(a[k][1],m)
x += 1.0
y += 1.0
fsum = (fa[k] + fsum)%MOD
isum += x
i2sum += x * x
jsum += y
j2sum += y * y
cnt += j - i
inv_cnt = inv[cnt]
i = j
``` | output | 1 | 32,515 | 15 | 65,031 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You stumbled upon a new kind of chess puzzles. The chessboard you are given is not necesserily 8 Γ 8, but it still is N Γ N. Each square has some number written on it, all the numbers are from 1 to N^2 and all the numbers are pairwise distinct. The j-th square in the i-th row has a number A_{ij} written on it.
In your chess set you have only three pieces: a knight, a bishop and a rook. At first, you put one of them on the square with the number 1 (you can choose which one). Then you want to reach square 2 (possibly passing through some other squares in process), then square 3 and so on until you reach square N^2. In one step you are allowed to either make a valid move with the current piece or replace it with some other piece. Each square can be visited arbitrary number of times.
A knight can move to a square that is two squares away horizontally and one square vertically, or two squares vertically and one square horizontally. A bishop moves diagonally. A rook moves horizontally or vertically. The move should be performed to a different square from the one a piece is currently standing on.
You want to minimize the number of steps of the whole traversal. Among all the paths to have the same number of steps you want to choose the one with the lowest number of piece replacements.
What is the path you should take to satisfy all conditions?
Input
The first line contains a single integer N (3 β€ N β€ 10) β the size of the chessboard.
Each of the next N lines contains N integers A_{i1}, A_{i2}, ..., A_{iN} (1 β€ A_{ij} β€ N^2) β the numbers written on the squares of the i-th row of the board.
It is guaranteed that all A_{ij} are pairwise distinct.
Output
The only line should contain two integers β the number of steps in the best answer and the number of replacement moves in it.
Example
Input
3
1 9 3
8 6 7
4 2 5
Output
12 1
Note
Here are the steps for the first example (the starting piece is a knight):
1. Move to (3, 2)
2. Move to (1, 3)
3. Move to (3, 2)
4. Replace the knight with a rook
5. Move to (3, 1)
6. Move to (3, 3)
7. Move to (3, 2)
8. Move to (2, 2)
9. Move to (2, 3)
10. Move to (2, 1)
11. Move to (1, 1)
12. Move to (1, 2) | instruction | 0 | 32,524 | 15 | 65,048 |
Tags: dfs and similar, dp, shortest paths
Correct Solution:
```
n=int(input())
graph=[{},{},{}]
for i in range(n):
for j in range(n):
graph[0][(i,j)]=[(k,j) for k in range(n)]+[(i,k) for k in range(n)]
graph[0][(i,j)].remove((i,j))
graph[0][(i,j)].remove((i,j))
graph[1][(i,j)]=[]
for k in range(n):
for l in range(n):
if abs(k-i)==abs(l-j)!=0:
graph[1][(i,j)].append((k,l))
graph[2][(i,j)]=[]
for k in range(n):
for l in range(n):
if {abs(k-i),abs(l-j)}=={1,2}:
graph[2][(i,j)].append((k,l))
dists=[[{},{},{}],[{},{},{}],[{},{},{}]]
for i in range(n):
for j in range(n):
for k in range(3):
dists[k][k][(i,j,i,j)]=0
for i in range(n):
for j in range(n):
for k in range(3):
layers=[[(i,j,k,0)],[],[],[],[]]
for l in range(4):
for guy in layers[l]:
for m in range(3):
if m!=guy[2]:
if (i,j,guy[0],guy[1]) not in dists[k][m]:
layers[l+1].append((guy[0],guy[1],m,guy[3]+1))
dists[k][m][(i,j,guy[0],guy[1])]=1000*(l+1)+guy[3]+1
for boi in graph[guy[2]][(guy[0],guy[1])]:
if (i,j,boi[0],boi[1]) not in dists[k][guy[2]]:
layers[l+1].append((boi[0],boi[1],guy[2],guy[3]))
dists[k][guy[2]][(i,j,boi[0],boi[1])]=1000*(l+1)+guy[3]
elif 1000*(l+1)+guy[3]<dists[k][guy[2]][(i,j,boi[0],boi[1])]:
layers[l+1].append((boi[0],boi[1],guy[2],guy[3]))
dists[k][guy[2]][(i,j,boi[0],boi[1])]=1000*(l+1)+guy[3]
locs=[None]*(n**2)
for i in range(n):
a=list(map(int,input().split()))
for j in range(n):
locs[a[j]-1]=(i,j)
best=(0,0,0)
for i in range(n**2-1):
tup=(locs[i][0],locs[i][1],locs[i+1][0],locs[i+1][1])
new0=min(best[0]+dists[0][0][tup],best[1]+dists[1][0][tup],best[2]+dists[2][0][tup])
new1=min(best[0]+dists[0][1][tup],best[1]+dists[1][1][tup],best[2]+dists[2][1][tup])
new2=min(best[0]+dists[0][2][tup],best[1]+dists[1][2][tup],best[2]+dists[2][2][tup])
best=(new0,new1,new2)
a=min(best)
print(a//1000,a%1000)
``` | output | 1 | 32,524 | 15 | 65,049 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You stumbled upon a new kind of chess puzzles. The chessboard you are given is not necesserily 8 Γ 8, but it still is N Γ N. Each square has some number written on it, all the numbers are from 1 to N^2 and all the numbers are pairwise distinct. The j-th square in the i-th row has a number A_{ij} written on it.
In your chess set you have only three pieces: a knight, a bishop and a rook. At first, you put one of them on the square with the number 1 (you can choose which one). Then you want to reach square 2 (possibly passing through some other squares in process), then square 3 and so on until you reach square N^2. In one step you are allowed to either make a valid move with the current piece or replace it with some other piece. Each square can be visited arbitrary number of times.
A knight can move to a square that is two squares away horizontally and one square vertically, or two squares vertically and one square horizontally. A bishop moves diagonally. A rook moves horizontally or vertically. The move should be performed to a different square from the one a piece is currently standing on.
You want to minimize the number of steps of the whole traversal. Among all the paths to have the same number of steps you want to choose the one with the lowest number of piece replacements.
What is the path you should take to satisfy all conditions?
Input
The first line contains a single integer N (3 β€ N β€ 10) β the size of the chessboard.
Each of the next N lines contains N integers A_{i1}, A_{i2}, ..., A_{iN} (1 β€ A_{ij} β€ N^2) β the numbers written on the squares of the i-th row of the board.
It is guaranteed that all A_{ij} are pairwise distinct.
Output
The only line should contain two integers β the number of steps in the best answer and the number of replacement moves in it.
Example
Input
3
1 9 3
8 6 7
4 2 5
Output
12 1
Note
Here are the steps for the first example (the starting piece is a knight):
1. Move to (3, 2)
2. Move to (1, 3)
3. Move to (3, 2)
4. Replace the knight with a rook
5. Move to (3, 1)
6. Move to (3, 3)
7. Move to (3, 2)
8. Move to (2, 2)
9. Move to (2, 3)
10. Move to (2, 1)
11. Move to (1, 1)
12. Move to (1, 2) | instruction | 0 | 32,525 | 15 | 65,050 |
Tags: dfs and similar, dp, shortest paths
Correct Solution:
```
import sys
from math import *
def minp():
return sys.stdin.readline().strip()
n = int(minp())
m = [None]*n
k = [None]*3
dp = [None]*3
dp[0] = [None]*(n*n)
dp[1] = [None]*(n*n)
dp[2] = [None]*(n*n)
path = [None]*(n*n)
for i in range(n):
m[i] = list(map(int, minp().split()))
for j in range(n):
path[m[i][j]-1] = (i,j)
for z in range(3):
k_ = [None]*n
for i in range(n):
kk = [None]*n
for j in range(n):
kkk_ = [None]*3
for zz in range(3):
kkk = [None]*n
for w in range(n):
kkk[w] = [(1000000,0)]*n
kkk_[zz] = kkk
kk[j] = kkk_
k_[i] = kk
k[z] = k_
q = [0]*(10*n*n)
qr = 0
km = [(1,2),(1,-2),(-1,2),(-1,-2),(2,1),(2,-1),(-2,1),(-2,-1)]
sm = [(1,1),(1,-1),(-1,1),(-1,-1)]
lm = [(0,1),(0,-1),(-1,0),(1,0)]
mm = [km,sm,lm]
for z in range(3):
for i in range(n):
for j in range(n):
#print('========')
ql = 0
qr = 1
q[0] = (z, i, j, (0,0))
kc = k[z][i][j]
kc[z][i][j] = (0, 0)
while ql < qr:
t, x, y, dd = q[ql]
#print(t,x,y,dd)
d = kc[t][x][y]
ql += 1
if d != dd:
continue
dd = (d[0]+1, d[1]+1)
for tt in range(3):
if t != tt and kc[tt][x][y] > dd:
kc[tt][x][y] = dd
q[qr] = (tt,x,y,dd)
qr += 1
dd = (d[0]+1,d[1])
if t == 0:
for w in mm[t]:
xx,yy = w[0]+x,w[1]+y
if xx >= 0 and xx < n and yy >= 0 and yy < n:
if kc[t][xx][yy] > dd:
kc[t][xx][yy] = dd
q[qr] = (t,xx,yy,dd)
qr += 1
else:
for w in mm[t]:
for hm in range(n*2):
xx,yy = w[0]*hm+x,w[1]*hm+y
if xx >= 0 and xx < n and yy >= 0 and yy < n:
if kc[t][xx][yy] > dd:
kc[t][xx][yy] = dd
q[qr] = (t,xx,yy,dd)
qr += 1
else:
break
dp[0][0] = (0,0)
dp[1][0] = (0,0)
dp[2][0] = (0,0)
for i in range(0,n*n-1):
x,y = path[i]
xx,yy = path[i+1]
for z in range(3):
for j in range(3):
dist = k[j][x][y][z][xx][yy]
if dp[j][i] != None:
nd = (dp[j][i][0]+dist[0],dp[j][i][1]+dist[1])
if dp[z][i+1] == None:
dp[z][i+1] = nd
else:
dp[z][i+1] = min(dp[z][i+1],nd)
for j in range(n*n-1,n*n):
qq = [dp[i][j] if dp[i][j] != None else (1000000,0) for i in range(3)]
qm = min(qq)
#print(j,qm)
print(qm[0], qm[1])
``` | output | 1 | 32,525 | 15 | 65,051 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You stumbled upon a new kind of chess puzzles. The chessboard you are given is not necesserily 8 Γ 8, but it still is N Γ N. Each square has some number written on it, all the numbers are from 1 to N^2 and all the numbers are pairwise distinct. The j-th square in the i-th row has a number A_{ij} written on it.
In your chess set you have only three pieces: a knight, a bishop and a rook. At first, you put one of them on the square with the number 1 (you can choose which one). Then you want to reach square 2 (possibly passing through some other squares in process), then square 3 and so on until you reach square N^2. In one step you are allowed to either make a valid move with the current piece or replace it with some other piece. Each square can be visited arbitrary number of times.
A knight can move to a square that is two squares away horizontally and one square vertically, or two squares vertically and one square horizontally. A bishop moves diagonally. A rook moves horizontally or vertically. The move should be performed to a different square from the one a piece is currently standing on.
You want to minimize the number of steps of the whole traversal. Among all the paths to have the same number of steps you want to choose the one with the lowest number of piece replacements.
What is the path you should take to satisfy all conditions?
Input
The first line contains a single integer N (3 β€ N β€ 10) β the size of the chessboard.
Each of the next N lines contains N integers A_{i1}, A_{i2}, ..., A_{iN} (1 β€ A_{ij} β€ N^2) β the numbers written on the squares of the i-th row of the board.
It is guaranteed that all A_{ij} are pairwise distinct.
Output
The only line should contain two integers β the number of steps in the best answer and the number of replacement moves in it.
Example
Input
3
1 9 3
8 6 7
4 2 5
Output
12 1
Note
Here are the steps for the first example (the starting piece is a knight):
1. Move to (3, 2)
2. Move to (1, 3)
3. Move to (3, 2)
4. Replace the knight with a rook
5. Move to (3, 1)
6. Move to (3, 3)
7. Move to (3, 2)
8. Move to (2, 2)
9. Move to (2, 3)
10. Move to (2, 1)
11. Move to (1, 1)
12. Move to (1, 2)
Submitted Solution:
```
N = int(input())
numCoord = {}
for i in range(N):
a = list(map(int,input().split()))
for j in range(N):
numCoord[a[j] - 1] = (i,j)
DPN = []
DPB = []
DPR = []
coordNum = N ** 2
DPN.append((0,0))
DPB.append((0,0))
DPR.append((0,0))
def rightCoordinate(x,y):
if x >= 0 and y >= 0 and x < N and y < N:
return True
return False
for i in range(1,coordNum):
currentCoord = numCoord[i]
lastCoord = numCoord[i-1]
if currentCoord[0] == lastCoord[0] or currentCoord[1] == lastCoord[1]:
rDist = 1
else:
rDist = 2
if currentCoord[0] + lastCoord[0] == currentCoord[1] + lastCoord[1] or currentCoord[0] - lastCoord[0] == currentCoord[1] - lastCoord[1]:
bDist = 1
elif (currentCoord[0] + lastCoord[0] + currentCoord[1] + lastCoord[1]) % 2 == 0:
bDist = 2
else:
bDist = 100
NDistMatrix = []
for _ in range(N):
NDistMatrix.append([100] * N)
NDistMatrix[lastCoord[0]][lastCoord[1]] = 0
NQueue = [(lastCoord[0],lastCoord[1],0)]
queueIndex = 0
while len(NQueue) > queueIndex:
curElem = NQueue[queueIndex]
queueIndex += 1
x = curElem[0]
y = curElem[1]
d = curElem[2]
if rightCoordinate(x + 2,y - 1):
if NDistMatrix[x + 2][y - 1] == 100:
NDistMatrix[x + 2][y - 1] = d + 1
if d < 4:
NQueue.append((x + 2, y - 1, d + 1))
if rightCoordinate(x - 2,y - 1):
if NDistMatrix[x - 2][y - 1] == 100:
NDistMatrix[x - 2][y - 1] = d + 1
if d < 4:
NQueue.append((x - 2, y - 1, d + 1))
if rightCoordinate(x + 2,y + 1):
if NDistMatrix[x + 2][y + 1] == 100:
NDistMatrix[x + 2][y + 1] = d + 1
if d < 4:
NQueue.append((x + 2, y + 1, d + 1))
if rightCoordinate(x - 2,y + 1):
if NDistMatrix[x - 2][y + 1] == 100:
NDistMatrix[x - 2][y + 1] = d + 1
if d < 4:
NQueue.append((x - 2, y + 1, d + 1))
if rightCoordinate(x + 1,y - 2):
if NDistMatrix[x + 1][y - 2] == 100:
NDistMatrix[x + 1][y - 2] = d + 1
if d < 4:
NQueue.append((x + 1, y - 2, d + 1))
if rightCoordinate(x - 1,y - 2):
if NDistMatrix[x - 1][y - 2] == 100:
NDistMatrix[x - 1][y - 2] = d + 1
if d < 4:
NQueue.append((x - 1, y - 2, d + 1))
if rightCoordinate(x + 1,y + 2):
if NDistMatrix[x + 1][y + 2] == 100:
NDistMatrix[x + 1][y + 2] = d + 1
if d < 4:
NQueue.append((x + 1, y + 2, d + 1))
if rightCoordinate(x - 1,y + 2):
if NDistMatrix[x - 1][y + 2] == 100:
NDistMatrix[x - 1][y + 2] = d + 1
if d < 4:
NQueue.append((x - 1, y + 2, d + 1))
nDist = NDistMatrix[currentCoord[0]][currentCoord[1]]
DPNCur = (DPN[i - 1][0] + nDist, DPN[i - 1][1])
if DPB[i - 1][0] + bDist + 1 < DPNCur[0] or (DPB[i - 1][0] + bDist + 1 == DPNCur[0] and DPB[i-1][1] + 1 < DPNCur[1]):
DPNCur = (DPB[i - 1][0] + bDist + 1, DPB[i-1][1] + 1)
if DPR[i - 1][0] + rDist + 1 < DPNCur[0] or (DPR[i - 1][0] + rDist + 1 == DPNCur[0] and DPR[i-1][1] + 1 < DPNCur[1]):
DPNCur = (DPR[i - 1][0] + rDist + 1, DPR[i-1][1] + 1)
DPBCur = (DPB[i - 1][0] + bDist, DPB[i - 1][1])
if DPN[i - 1][0] + nDist + 1 < DPBCur[0] or (DPN[i - 1][0] + nDist + 1 == DPBCur[0] and DPN[i-1][1] + 1 < DPBCur[1]):
DPBCur = (DPN[i - 1][0] + nDist + 1, DPN[i-1][1] + 1)
if DPR[i - 1][0] + rDist + 1 < DPBCur[0] or (DPR[i - 1][0] + rDist + 1 == DPBCur[0] and DPR[i-1][1] + 1 < DPBCur[1]):
DPBCur = (DPR[i - 1][0] + rDist + 1, DPR[i-1][1] + 1)
DPRCur = (DPR[i - 1][0] + rDist, DPR[i - 1][1])
if DPB[i - 1][0] + bDist + 1 < DPRCur[0] or (DPB[i - 1][0] + bDist + 1 == DPRCur[0] and DPB[i-1][1] + 1 < DPRCur[1]):
DPRCur = (DPB[i - 1][0] + bDist + 1, DPB[i-1][1] + 1)
if DPN[i - 1][0] + nDist + 1 < DPRCur[0] or (DPN[i - 1][0] + nDist + 1 == DPRCur[0] and DPN[i-1][1] + 1 < DPRCur[1]):
DPRCur = (DPN[i - 1][0] + nDist + 1, DPN[i-1][1] + 1)
DPN.append(DPNCur)
DPB.append(DPBCur)
DPR.append(DPRCur)
minDist = DPN[coordNum-1]
if DPB[coordNum - 1][0] < minDist[0] or DPB[coordNum - 1][0] == minDist[0] and DPB[coordNum - 1][1] < minDist[1]:
minDist = DPB[coordNum - 1]
if DPR[coordNum - 1][0] < minDist[0] or DPR[coordNum - 1][0] == minDist[0] and DPR[coordNum - 1][1] < minDist[1]:
minDist = DPR[coordNum - 1]
print(str(minDist[0]) + ' ' + str(minDist[1]))
``` | instruction | 0 | 32,526 | 15 | 65,052 |
No | output | 1 | 32,526 | 15 | 65,053 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You stumbled upon a new kind of chess puzzles. The chessboard you are given is not necesserily 8 Γ 8, but it still is N Γ N. Each square has some number written on it, all the numbers are from 1 to N^2 and all the numbers are pairwise distinct. The j-th square in the i-th row has a number A_{ij} written on it.
In your chess set you have only three pieces: a knight, a bishop and a rook. At first, you put one of them on the square with the number 1 (you can choose which one). Then you want to reach square 2 (possibly passing through some other squares in process), then square 3 and so on until you reach square N^2. In one step you are allowed to either make a valid move with the current piece or replace it with some other piece. Each square can be visited arbitrary number of times.
A knight can move to a square that is two squares away horizontally and one square vertically, or two squares vertically and one square horizontally. A bishop moves diagonally. A rook moves horizontally or vertically. The move should be performed to a different square from the one a piece is currently standing on.
You want to minimize the number of steps of the whole traversal. Among all the paths to have the same number of steps you want to choose the one with the lowest number of piece replacements.
What is the path you should take to satisfy all conditions?
Input
The first line contains a single integer N (3 β€ N β€ 10) β the size of the chessboard.
Each of the next N lines contains N integers A_{i1}, A_{i2}, ..., A_{iN} (1 β€ A_{ij} β€ N^2) β the numbers written on the squares of the i-th row of the board.
It is guaranteed that all A_{ij} are pairwise distinct.
Output
The only line should contain two integers β the number of steps in the best answer and the number of replacement moves in it.
Example
Input
3
1 9 3
8 6 7
4 2 5
Output
12 1
Note
Here are the steps for the first example (the starting piece is a knight):
1. Move to (3, 2)
2. Move to (1, 3)
3. Move to (3, 2)
4. Replace the knight with a rook
5. Move to (3, 1)
6. Move to (3, 3)
7. Move to (3, 2)
8. Move to (2, 2)
9. Move to (2, 3)
10. Move to (2, 1)
11. Move to (1, 1)
12. Move to (1, 2)
Submitted Solution:
```
n=int(input())
lookup={}
for i in range(n):
x=list(map(int,input().split()))
for j in range(n):
lookup[x[j]]=(i,j)
bestrook=[0,0]
bestbish=[0,0]
bestknight=[0,0]
for i in range(1,n**2):
x=abs(lookup[i][0]-lookup[i+1][0])
y=abs(lookup[i][1]-lookup[i+1][1])
if x==0 or y==0:
bestrook[0]+=1
else:
bestrook[0]+=2
if x==y:
bestbish[0]+=1
elif (x-y)%2==0:
bestbish[0]+=2
else:
bestbish[0]+=1000
if {x,y}=={1,2}:
bestknight[0]+=1
elif x**2+y**2 in [4,16,20,10,18]:
bestknight[0]+=2
elif x**2+y**2==2 and lookup[i] not in [(0,0),(n-1,0),(0,n-1),(n-1,n-1)] and lookup[i+1] not in [(0,0),(n-1,0),(0,n-1),(n-1,n-1)]:
bestknight[0]+=2
elif {x,y} in [{5,0},{3,0},{1,0},{6,1},{4,1},{5,2},{3,2},{6,3},{4,3},{5,4}]:
bestknight[0]+=3
else:
bestknight[0]+=1000
bestrook[0]=min(bestrook[0],bestbish[0]+1,bestknight[0]+1)
bestbish[0]=min(bestrook[0]+1,bestbish[0],bestknight[0]+1)
bestknight[0]=min(bestrook[0]+1,bestbish[0]+1,bestknight[0])
best=(bestrook[0],bestbish[0],bestknight[0])
if min(best)==best[0]:
print(bestrook[0],bestrook[1])
elif min(best)==best[1]:
print(bestbish[0],bestbish[1])
else:
print(bestknight[0],bestknight[1])
``` | instruction | 0 | 32,527 | 15 | 65,054 |
No | output | 1 | 32,527 | 15 | 65,055 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You stumbled upon a new kind of chess puzzles. The chessboard you are given is not necesserily 8 Γ 8, but it still is N Γ N. Each square has some number written on it, all the numbers are from 1 to N^2 and all the numbers are pairwise distinct. The j-th square in the i-th row has a number A_{ij} written on it.
In your chess set you have only three pieces: a knight, a bishop and a rook. At first, you put one of them on the square with the number 1 (you can choose which one). Then you want to reach square 2 (possibly passing through some other squares in process), then square 3 and so on until you reach square N^2. In one step you are allowed to either make a valid move with the current piece or replace it with some other piece. Each square can be visited arbitrary number of times.
A knight can move to a square that is two squares away horizontally and one square vertically, or two squares vertically and one square horizontally. A bishop moves diagonally. A rook moves horizontally or vertically. The move should be performed to a different square from the one a piece is currently standing on.
You want to minimize the number of steps of the whole traversal. Among all the paths to have the same number of steps you want to choose the one with the lowest number of piece replacements.
What is the path you should take to satisfy all conditions?
Input
The first line contains a single integer N (3 β€ N β€ 10) β the size of the chessboard.
Each of the next N lines contains N integers A_{i1}, A_{i2}, ..., A_{iN} (1 β€ A_{ij} β€ N^2) β the numbers written on the squares of the i-th row of the board.
It is guaranteed that all A_{ij} are pairwise distinct.
Output
The only line should contain two integers β the number of steps in the best answer and the number of replacement moves in it.
Example
Input
3
1 9 3
8 6 7
4 2 5
Output
12 1
Note
Here are the steps for the first example (the starting piece is a knight):
1. Move to (3, 2)
2. Move to (1, 3)
3. Move to (3, 2)
4. Replace the knight with a rook
5. Move to (3, 1)
6. Move to (3, 3)
7. Move to (3, 2)
8. Move to (2, 2)
9. Move to (2, 3)
10. Move to (2, 1)
11. Move to (1, 1)
12. Move to (1, 2)
Submitted Solution:
```
N = int(input())
INF = 1000000
A = [[None] * N for _ in range(N)]
d = {}
for i in range(N):
line = map(int, input().split())
for j, s in enumerate(line):
d[s] = (i, j)
A[i][j] = s
res = [[None, None, None] for _ in range(N * N)]
res[-1] = [(0, 0), (0, 0), (0, 0)]
def check_1(idx, t):
curr_i, curr_j = d[idx]
next_i, next_j = d[idx + 1]
if (abs(curr_i - next_i) == 2 and abs(curr_j - next_j) == 1) \
or (abs(curr_i - next_i) == 1 and abs(curr_j - next_j) == 2):
if t == 1:
return 1, 0
else:
return 2, 1
return INF, INF
def check_2(idx, t):
curr_i, curr_j = d[idx]
next_i, next_j = d[idx + 1]
if abs(curr_i - next_i) == abs(curr_j - next_j):
if t == 2:
return 1, 0
else:
return 2, 1
if (curr_i + curr_j) % 2 == (next_i + next_j) % 2:
if t == 2:
return 2, 0
else:
return 3, 1
return INF, INF
def check_3(idx, t):
curr_i, curr_j = d[idx]
next_i, next_j = d[idx + 1]
if curr_i == next_i or curr_j == next_j:
if t == 3:
return 1, 0
else:
return 2, 1
if t == 3:
return 2, 0
else:
return 3, 1
def sum_t(t1, t2):
return (t1[0] + t2[0], t1[1] + t2[1])
for idx in range(N * N - 2, -1, -1):
res11 = check_1(idx + 1, 1)
res31 = res21 = check_1(idx + 1, 2)
res22 = check_2(idx + 1, 2)
res12 = res32 = check_2(idx + 1, 1)
res33 = check_3(idx + 1, 3)
res13 = res23 = check_3(idx + 1, 1)
res[idx] = [
min(sum_t(res11, res[idx + 1][0]),
sum_t(res12, res[idx + 1][1]),
sum_t(res13, res[idx + 1][2])),
min(sum_t(res21, res[idx + 1][0]),
sum_t(res22, res[idx + 1][1]),
sum_t(res23, res[idx + 1][2])),
min(sum_t(res31, res[idx + 1][0]),
sum_t(res32, res[idx + 1][1]),
sum_t(res33, res[idx + 1][2])),
]
print(*min(res[0]))
# for i, r in enumerate(res):
# print(i + 1, r)
``` | instruction | 0 | 32,528 | 15 | 65,056 |
No | output | 1 | 32,528 | 15 | 65,057 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You stumbled upon a new kind of chess puzzles. The chessboard you are given is not necesserily 8 Γ 8, but it still is N Γ N. Each square has some number written on it, all the numbers are from 1 to N^2 and all the numbers are pairwise distinct. The j-th square in the i-th row has a number A_{ij} written on it.
In your chess set you have only three pieces: a knight, a bishop and a rook. At first, you put one of them on the square with the number 1 (you can choose which one). Then you want to reach square 2 (possibly passing through some other squares in process), then square 3 and so on until you reach square N^2. In one step you are allowed to either make a valid move with the current piece or replace it with some other piece. Each square can be visited arbitrary number of times.
A knight can move to a square that is two squares away horizontally and one square vertically, or two squares vertically and one square horizontally. A bishop moves diagonally. A rook moves horizontally or vertically. The move should be performed to a different square from the one a piece is currently standing on.
You want to minimize the number of steps of the whole traversal. Among all the paths to have the same number of steps you want to choose the one with the lowest number of piece replacements.
What is the path you should take to satisfy all conditions?
Input
The first line contains a single integer N (3 β€ N β€ 10) β the size of the chessboard.
Each of the next N lines contains N integers A_{i1}, A_{i2}, ..., A_{iN} (1 β€ A_{ij} β€ N^2) β the numbers written on the squares of the i-th row of the board.
It is guaranteed that all A_{ij} are pairwise distinct.
Output
The only line should contain two integers β the number of steps in the best answer and the number of replacement moves in it.
Example
Input
3
1 9 3
8 6 7
4 2 5
Output
12 1
Note
Here are the steps for the first example (the starting piece is a knight):
1. Move to (3, 2)
2. Move to (1, 3)
3. Move to (3, 2)
4. Replace the knight with a rook
5. Move to (3, 1)
6. Move to (3, 3)
7. Move to (3, 2)
8. Move to (2, 2)
9. Move to (2, 3)
10. Move to (2, 1)
11. Move to (1, 1)
12. Move to (1, 2)
Submitted Solution:
```
n=int(input())
a=[0,0]*(n**2+1)
for i in range(n):
listx=list(map(int,input().split()))
for j in range(n):
a[listx[j]]=[i,j]
cnt=1
cntmohre=0
if (abs(a[2][0]-a[1][0])==2 and abs(a[2][1]-a[1][1])==1) or (abs(a[2][0]-a[1][0])==1 and abs(a[2][1]-a[1][1])==2):
mohre="A"
elif abs(a[2][0]-a[1][0])==abs(a[2][1]-a[1][1]):
mohre="F"
else:
mohre="R"
for i in range(3,n**2+1):
if ((abs(a[i][0]-a[i-1][0])==2 and abs(a[i][1]-a[i-1][1])==1) or (abs(a[i][0]-a[i-1][0])==1 and abs(a[i][1]-a[i-1][1])==2)) and mohre=="A":
cnt+=1
if mohre=="F":
cnt+=1
cntmohre+=1
mohre="A"
elif mohre=="A":
cnt+=1
mohre="R"
cntmohre+=1
if abs(a[i][0]-a[i-1][0])==0 or abs(a[i][1]-a[i-1][1])==0:
cnt+=1
else:
cnt+=2
elif abs(a[i][0]-a[i-1][0])==3 and abs(a[i][1]-a[i-1][1])==3 and mohre=="A":
cnt+=2
elif abs(a[i][0]-a[i-1][0])==abs(a[i][1]-a[i-1][1]) and mohre!="R":
cnt+=1
if mohre=="A":
cnt+=1
cntmohre+=1
mohre="F"
elif (a[i][0]+a[i][1])%2==(a[i-1][0]+a[i-1][1])%2 and mohre=="F":
cnt+=2
elif mohre=="F":
cnt+=1
mohre="R"
cntmohre+=1
if abs(a[i][0]-a[i-1][0])==0 or abs(a[i][1]-a[i-1][1])==0:
cnt+=1
else:
cnt+=2
else:
if abs(a[i][0]-a[i-1][0])==0 or abs(a[i][1]-a[i-1][1])==0:
cnt+=1
else:
cnt+=2
print(str(cnt)+" "+str(cntmohre))
``` | instruction | 0 | 32,529 | 15 | 65,058 |
No | output | 1 | 32,529 | 15 | 65,059 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are three cells on an infinite 2-dimensional grid, labeled A, B, and F. Find the length of the shortest path from A to B if:
* in one move you can go to any of the four adjacent cells sharing a side;
* visiting the cell F is forbidden (it is an obstacle).
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first one contains two integers x_A, y_A (1 β€ x_A, y_A β€ 1000) β coordinates of the start cell A. The second one contains two integers x_B, y_B (1 β€ x_B, y_B β€ 1000) β coordinates of the finish cell B. The third one contains two integers x_F, y_F (1 β€ x_F, y_F β€ 1000) β coordinates of the forbidden cell F. All cells are distinct.
Coordinate x corresponds to the column number and coordinate y corresponds to the row number (see the pictures below).
Output
Output t lines. The i-th line should contain the answer for the i-th test case: the length of the shortest path from the cell A to the cell B if the cell F is not allowed to be visited.
Example
Input
7
1 1
3 3
2 2
2 5
2 1
2 3
1000 42
1000 1
1000 1000
1 10
3 10
2 10
3 8
7 8
3 7
2 1
4 1
1 1
1 344
1 10
1 1
Output
4
6
41
4
4
2
334
Note
<image> An example of a possible shortest path for the first test case. <image> An example of a possible shortest path for the second test case. | instruction | 0 | 32,771 | 15 | 65,542 |
Tags: implementation, math
Correct Solution:
```
t = int(input())
while t:
input()
xa, ya = map(int, input().split())
xb, yb = map(int, input().split())
xf, yf = map(int, input().split())
if xa == xb == xf and min(ya, yb) < yf and max(ya, yb) > yf:
print(abs(ya-yb)+2)
elif ya == yb == yf and min(xa,xb) < xf and max(xa,xb) > xf:
print(abs(xa-xb)+2)
else:
print(abs(xa-xb) + abs(ya-yb))
t-=1
``` | output | 1 | 32,771 | 15 | 65,543 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are three cells on an infinite 2-dimensional grid, labeled A, B, and F. Find the length of the shortest path from A to B if:
* in one move you can go to any of the four adjacent cells sharing a side;
* visiting the cell F is forbidden (it is an obstacle).
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first one contains two integers x_A, y_A (1 β€ x_A, y_A β€ 1000) β coordinates of the start cell A. The second one contains two integers x_B, y_B (1 β€ x_B, y_B β€ 1000) β coordinates of the finish cell B. The third one contains two integers x_F, y_F (1 β€ x_F, y_F β€ 1000) β coordinates of the forbidden cell F. All cells are distinct.
Coordinate x corresponds to the column number and coordinate y corresponds to the row number (see the pictures below).
Output
Output t lines. The i-th line should contain the answer for the i-th test case: the length of the shortest path from the cell A to the cell B if the cell F is not allowed to be visited.
Example
Input
7
1 1
3 3
2 2
2 5
2 1
2 3
1000 42
1000 1
1000 1000
1 10
3 10
2 10
3 8
7 8
3 7
2 1
4 1
1 1
1 344
1 10
1 1
Output
4
6
41
4
4
2
334
Note
<image> An example of a possible shortest path for the first test case. <image> An example of a possible shortest path for the second test case. | instruction | 0 | 32,772 | 15 | 65,544 |
Tags: implementation, math
Correct Solution:
```
from sys import stdin, stdout
def solve(ax,ay,bx,by,fx,fy):
rx= abs(ax-bx)
ry=abs(ay-by)
if ax==bx or ay==by:
e=0
if fx in range(min(ax,bx),max(ax,bx)+1):
if fy==ay:
e+=2
if fy in range(min(ay,by), max(ay, by)+1):
if fx==ax:
e+=2
return rx+ry+e
return rx+ry
t= int(input())
for _ in range(t):
blank=input()
if blank!= "":
break
ax, ay = [int(c) for c in input().split()]
bx,by =[int(c) for c in input().split()]
fx,fy =[int(c) for c in input().split()]
print(solve(ax,ay,bx,by,fx,fy))
``` | output | 1 | 32,772 | 15 | 65,545 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are three cells on an infinite 2-dimensional grid, labeled A, B, and F. Find the length of the shortest path from A to B if:
* in one move you can go to any of the four adjacent cells sharing a side;
* visiting the cell F is forbidden (it is an obstacle).
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first one contains two integers x_A, y_A (1 β€ x_A, y_A β€ 1000) β coordinates of the start cell A. The second one contains two integers x_B, y_B (1 β€ x_B, y_B β€ 1000) β coordinates of the finish cell B. The third one contains two integers x_F, y_F (1 β€ x_F, y_F β€ 1000) β coordinates of the forbidden cell F. All cells are distinct.
Coordinate x corresponds to the column number and coordinate y corresponds to the row number (see the pictures below).
Output
Output t lines. The i-th line should contain the answer for the i-th test case: the length of the shortest path from the cell A to the cell B if the cell F is not allowed to be visited.
Example
Input
7
1 1
3 3
2 2
2 5
2 1
2 3
1000 42
1000 1
1000 1000
1 10
3 10
2 10
3 8
7 8
3 7
2 1
4 1
1 1
1 344
1 10
1 1
Output
4
6
41
4
4
2
334
Note
<image> An example of a possible shortest path for the first test case. <image> An example of a possible shortest path for the second test case. | instruction | 0 | 32,773 | 15 | 65,546 |
Tags: implementation, math
Correct Solution:
```
a = int(input())
sol = []
for i in range(a):
input()
ax, ay = input().split()
bx, by = input().split()
fx, fy = input().split()
y_dist = abs(int(ay) - int(by))
x_dist = abs(int(ax) - int(bx))
sum_dist = x_dist + y_dist
if(y_dist == 0 and int(fy) == int(ay) and int(fx)> min(int(ax), int(bx)) and int(fx) < max(int(ax), int(bx))):
sum_dist = sum_dist + 2
elif(x_dist == 0 and int(fx) == int(ax) and int(fy)> min(int(ay), int(by)) and int(fy) < max(int(ay), int(by))):
sum_dist = sum_dist + 2
sol.append(sum_dist)
for item in sol:
print(item)
``` | output | 1 | 32,773 | 15 | 65,547 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are three cells on an infinite 2-dimensional grid, labeled A, B, and F. Find the length of the shortest path from A to B if:
* in one move you can go to any of the four adjacent cells sharing a side;
* visiting the cell F is forbidden (it is an obstacle).
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first one contains two integers x_A, y_A (1 β€ x_A, y_A β€ 1000) β coordinates of the start cell A. The second one contains two integers x_B, y_B (1 β€ x_B, y_B β€ 1000) β coordinates of the finish cell B. The third one contains two integers x_F, y_F (1 β€ x_F, y_F β€ 1000) β coordinates of the forbidden cell F. All cells are distinct.
Coordinate x corresponds to the column number and coordinate y corresponds to the row number (see the pictures below).
Output
Output t lines. The i-th line should contain the answer for the i-th test case: the length of the shortest path from the cell A to the cell B if the cell F is not allowed to be visited.
Example
Input
7
1 1
3 3
2 2
2 5
2 1
2 3
1000 42
1000 1
1000 1000
1 10
3 10
2 10
3 8
7 8
3 7
2 1
4 1
1 1
1 344
1 10
1 1
Output
4
6
41
4
4
2
334
Note
<image> An example of a possible shortest path for the first test case. <image> An example of a possible shortest path for the second test case. | instruction | 0 | 32,774 | 15 | 65,548 |
Tags: implementation, math
Correct Solution:
```
res = []
tests = int(input())
for j in range(tests):
a = input().split()
b = input().split()
c = input().split()
d = input().split()
a1, a2, b1, b2, f1, f2 = int(b[0]), int(b[1]), int(c[0]), int(c[1]), int(d[0]), int(d[1]),
if a1 == b1 == f1 and f2 != min(a2, b2, f2) and f2 != max(a2, b2, f2):
res.append(abs(a2 - b2) + 2)
elif a2 == b2 == f2 and f1 != min(a1, b1, f1) and f1 != max(a1, b1, f1):
res.append(abs(a1 - b1) + 2)
else:
res.append(abs(a1 - b1) + abs(a2 - b2))
for i in res:
print(i)
``` | output | 1 | 32,774 | 15 | 65,549 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are three cells on an infinite 2-dimensional grid, labeled A, B, and F. Find the length of the shortest path from A to B if:
* in one move you can go to any of the four adjacent cells sharing a side;
* visiting the cell F is forbidden (it is an obstacle).
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first one contains two integers x_A, y_A (1 β€ x_A, y_A β€ 1000) β coordinates of the start cell A. The second one contains two integers x_B, y_B (1 β€ x_B, y_B β€ 1000) β coordinates of the finish cell B. The third one contains two integers x_F, y_F (1 β€ x_F, y_F β€ 1000) β coordinates of the forbidden cell F. All cells are distinct.
Coordinate x corresponds to the column number and coordinate y corresponds to the row number (see the pictures below).
Output
Output t lines. The i-th line should contain the answer for the i-th test case: the length of the shortest path from the cell A to the cell B if the cell F is not allowed to be visited.
Example
Input
7
1 1
3 3
2 2
2 5
2 1
2 3
1000 42
1000 1
1000 1000
1 10
3 10
2 10
3 8
7 8
3 7
2 1
4 1
1 1
1 344
1 10
1 1
Output
4
6
41
4
4
2
334
Note
<image> An example of a possible shortest path for the first test case. <image> An example of a possible shortest path for the second test case. | instruction | 0 | 32,775 | 15 | 65,550 |
Tags: implementation, math
Correct Solution:
```
t=int(input())
for _ in range(t):
input()
arr = list(map(int, input().split()))
xa=arr[0]
ya=arr[1]
arr = list(map(int, input().split()))
xb=arr[0]
yb=arr[1]
arr = list(map(int, input().split()))
xf=arr[0]
yf=arr[1]
if(xa==xb):
if(xa==xf and yf>min(ya,yb) and yf<max(ya,yb)):
print(abs(ya-yb)+2)
else:
print(abs(ya-yb))
elif(ya==yb):
if(yf==ya and xf>min(xa,xb) and xf<max(xa,xb)):
print(abs(xa-xb)+2)
else:
print(abs(xa-xb))
else:
print(abs(xa-xb)+abs(ya-yb))
``` | output | 1 | 32,775 | 15 | 65,551 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are three cells on an infinite 2-dimensional grid, labeled A, B, and F. Find the length of the shortest path from A to B if:
* in one move you can go to any of the four adjacent cells sharing a side;
* visiting the cell F is forbidden (it is an obstacle).
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first one contains two integers x_A, y_A (1 β€ x_A, y_A β€ 1000) β coordinates of the start cell A. The second one contains two integers x_B, y_B (1 β€ x_B, y_B β€ 1000) β coordinates of the finish cell B. The third one contains two integers x_F, y_F (1 β€ x_F, y_F β€ 1000) β coordinates of the forbidden cell F. All cells are distinct.
Coordinate x corresponds to the column number and coordinate y corresponds to the row number (see the pictures below).
Output
Output t lines. The i-th line should contain the answer for the i-th test case: the length of the shortest path from the cell A to the cell B if the cell F is not allowed to be visited.
Example
Input
7
1 1
3 3
2 2
2 5
2 1
2 3
1000 42
1000 1
1000 1000
1 10
3 10
2 10
3 8
7 8
3 7
2 1
4 1
1 1
1 344
1 10
1 1
Output
4
6
41
4
4
2
334
Note
<image> An example of a possible shortest path for the first test case. <image> An example of a possible shortest path for the second test case. | instruction | 0 | 32,776 | 15 | 65,552 |
Tags: implementation, math
Correct Solution:
```
t=int(input())
for i in range(t):
n=input()
a,b=[int(j) for j in input().split()]
c,d=[int(j) for j in input().split()]
e,f=[int(j) for j in input().split()]
path=abs(a-c)+abs(b-d)+2*((a==c==e)*(b-f)*(d-f)|(b==d==f)*(a-e)*(c-e)<0)
print(path)
``` | output | 1 | 32,776 | 15 | 65,553 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are three cells on an infinite 2-dimensional grid, labeled A, B, and F. Find the length of the shortest path from A to B if:
* in one move you can go to any of the four adjacent cells sharing a side;
* visiting the cell F is forbidden (it is an obstacle).
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first one contains two integers x_A, y_A (1 β€ x_A, y_A β€ 1000) β coordinates of the start cell A. The second one contains two integers x_B, y_B (1 β€ x_B, y_B β€ 1000) β coordinates of the finish cell B. The third one contains two integers x_F, y_F (1 β€ x_F, y_F β€ 1000) β coordinates of the forbidden cell F. All cells are distinct.
Coordinate x corresponds to the column number and coordinate y corresponds to the row number (see the pictures below).
Output
Output t lines. The i-th line should contain the answer for the i-th test case: the length of the shortest path from the cell A to the cell B if the cell F is not allowed to be visited.
Example
Input
7
1 1
3 3
2 2
2 5
2 1
2 3
1000 42
1000 1
1000 1000
1 10
3 10
2 10
3 8
7 8
3 7
2 1
4 1
1 1
1 344
1 10
1 1
Output
4
6
41
4
4
2
334
Note
<image> An example of a possible shortest path for the first test case. <image> An example of a possible shortest path for the second test case. | instruction | 0 | 32,777 | 15 | 65,554 |
Tags: implementation, math
Correct Solution:
```
# cook your code here
import os
import sys
from math import ceil, floor, sqrt, gcd, factorial
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def main():
for _ in range(int(input())):
input()
xa,ya=map(int,input().split())
xb,yb=map(int,input().split())
xf,yf=map(int,input().split())
# xa,xb = xa,yb = yb,yb
# xa,xb = ya,xb = ya,yb
if xa==xb==xf and yf<max(yb,ya) and yf>min(yb,ya):
print(abs(xb-xa)+abs(yb-ya)+2)
elif ya==yb==yf and xf<max(xb,xa) and xf>min(xb,xa):
print(abs(xb-xa)+abs(yb-ya)+2)
else:print(abs(xb-xa)+abs(yb-ya))
# n=int(input())
# n,k=map(int,input().split())
# a=list(map(int,input().split()))
if __name__ == "__main__":
main()
``` | output | 1 | 32,777 | 15 | 65,555 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are three cells on an infinite 2-dimensional grid, labeled A, B, and F. Find the length of the shortest path from A to B if:
* in one move you can go to any of the four adjacent cells sharing a side;
* visiting the cell F is forbidden (it is an obstacle).
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first one contains two integers x_A, y_A (1 β€ x_A, y_A β€ 1000) β coordinates of the start cell A. The second one contains two integers x_B, y_B (1 β€ x_B, y_B β€ 1000) β coordinates of the finish cell B. The third one contains two integers x_F, y_F (1 β€ x_F, y_F β€ 1000) β coordinates of the forbidden cell F. All cells are distinct.
Coordinate x corresponds to the column number and coordinate y corresponds to the row number (see the pictures below).
Output
Output t lines. The i-th line should contain the answer for the i-th test case: the length of the shortest path from the cell A to the cell B if the cell F is not allowed to be visited.
Example
Input
7
1 1
3 3
2 2
2 5
2 1
2 3
1000 42
1000 1
1000 1000
1 10
3 10
2 10
3 8
7 8
3 7
2 1
4 1
1 1
1 344
1 10
1 1
Output
4
6
41
4
4
2
334
Note
<image> An example of a possible shortest path for the first test case. <image> An example of a possible shortest path for the second test case. | instruction | 0 | 32,778 | 15 | 65,556 |
Tags: implementation, math
Correct Solution:
```
#from functools import reduce
#mod=int(1e9+7)
#import resource
#resource.setrlimit(resource.RLIMIT_STACK, [0x100000000, resource.RLIM_INFINITY])
#import threading
#threading.stack_size(2**26)
"""fact=[1]
#for i in range(1,100001):
# fact.append((fact[-1]*i)%mod)
#ifact=[0]*100001
#ifact[100000]=pow(fact[100000],mod-2,mod)
"""
from collections import deque, defaultdict, Counter, OrderedDict
#from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
#from heapq import heappush, heappop, heapify, nlargest, nsmallest
# sys.setrecursionlimit(10**6)
from sys import stdin, stdout
import bisect #c++ upperbound
from bisect import bisect_left as bl #c++ lowerbound bl(array,element)
from bisect import bisect_right as br #c++ upperbound
import itertools
from collections import Counter
from math import sqrt
import collections
import math
import heapq
import re
from statistics import mode
def nCr(n, r):
return (fact(n) // (fact(r)
* fact(n - r)))
# Returns factorial of n
def fact(n):
res = 1
for i in range(2, n+1):
res = res * i
return res
def modinv(n,p):
return pow(n,p-2,p)
def cin():
return map(int,sin().split())
def ain(): #takes array as input
return list(map(int,sin().split()))
def sin():
return input()
def inin():
return int(input())
def Divisors(n) :
l = []
for i in range(1, int(math.sqrt(n) + 1)) :
if (n % i == 0) :
if (n // i == i) :
l.append(i)
else :
l.append(i)
l.append(n//i)
return l
def most_frequent(list):
return max(set(list), key = list.count)
def GCD(x,y):
while(y):
x, y = y, x % y
return x
def ncr(n,r): #To use this, Uncomment 9-14
return fact[n]*pow(fact[r]*fact[n - r], mod - 2, mod) % mod
def Convert(string):
li = list(string.split(""))
return li
def SieveOfEratosthenes(n):
global prime
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
f=[]
for p in range(2, n):
if prime[p]:
f.append(p)
return f
prime=[]
def dfs(n,d,v,c):
global q
v[n]=1
x=d[n]
q.append(n)
j=c
for i in x:
if i not in v:
f=dfs(i,d,v,c+1)
j=max(j,f)
# print(f)
return j
#Implement heapq
#grades = [110, 25, 38, 49, 20, 95, 33, 87, 80, 90]
#print(heapq.nlargest(3, grades)) #top 3 largest
#print(heapq.nsmallest(4, grades))
#Always make a variable of predefined function for ex- fn=len
#n,k=map(int,input().split())
"""*******************************************************"""
def main():
for _ in range(inin()):
lol=input()
x1,y1=map(int,input().split())
x2,y2=map(int,input().split())
x3,y3=map(int,input().split())
if x1==x2 and x2==x3 and y3>min(y1,y2) and y3<max(y1,y2):
print(abs(y2-y1)+abs(x2-x1)+2)
elif y1==y2 and y2==y3 and x3>min(x1,x2) and x3<max(x2,x1):
print(abs(y2-y1)+abs(x2-x1)+2)
else:
print(abs(y2-y1)+abs(x2-x1))
"""*******************************************************"""
######## Python 2 and 3 footer by Pajenegod and c1729
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192
class FastIO(BytesIO):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.writable = "x" in file.mode or "w" in file.mode
self.write = super(FastIO, self).write if self.writable else None
def _fill(self):
s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
return s
def read(self):
while self._fill(): pass
return super(FastIO,self).read()
def readline(self):
while self.newlines == 0:
s = self._fill(); self.newlines = s.count(b"\n") + (not s)
self.newlines -= 1
return super(FastIO, self).readline()
def flush(self):
if self.writable:
os.write(self._fd, self.getvalue())
self.truncate(0), self.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
if py2:
self.write = self.buffer.write
self.read = self.buffer.read
self.readline = self.buffer.readline
else:
self.write = lambda s:self.buffer.write(s.encode('ascii'))
self.read = lambda:self.buffer.read().decode('ascii')
self.readline = lambda:self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
if __name__== "__main__":
main()
#threading.Thread(target=main).start()
``` | output | 1 | 32,778 | 15 | 65,557 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are three cells on an infinite 2-dimensional grid, labeled A, B, and F. Find the length of the shortest path from A to B if:
* in one move you can go to any of the four adjacent cells sharing a side;
* visiting the cell F is forbidden (it is an obstacle).
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first one contains two integers x_A, y_A (1 β€ x_A, y_A β€ 1000) β coordinates of the start cell A. The second one contains two integers x_B, y_B (1 β€ x_B, y_B β€ 1000) β coordinates of the finish cell B. The third one contains two integers x_F, y_F (1 β€ x_F, y_F β€ 1000) β coordinates of the forbidden cell F. All cells are distinct.
Coordinate x corresponds to the column number and coordinate y corresponds to the row number (see the pictures below).
Output
Output t lines. The i-th line should contain the answer for the i-th test case: the length of the shortest path from the cell A to the cell B if the cell F is not allowed to be visited.
Example
Input
7
1 1
3 3
2 2
2 5
2 1
2 3
1000 42
1000 1
1000 1000
1 10
3 10
2 10
3 8
7 8
3 7
2 1
4 1
1 1
1 344
1 10
1 1
Output
4
6
41
4
4
2
334
Note
<image> An example of a possible shortest path for the first test case. <image> An example of a possible shortest path for the second test case.
Submitted Solution:
```
for t in range(int(input())):
input()
xa, ya = map(int, input().split())
xb, yb = map(int, input().split())
xf, yf = map(int, input().split())
res = abs(xa-xb) + abs(ya-yb)
if xa == xb == xf:
if yf in range(min(ya, yb), max(ya, yb)):
res += 2
if ya == yb == yf:
if xf in range(min(xa, xb), max(xa, xb)):
res += 2
print(res)
``` | instruction | 0 | 32,779 | 15 | 65,558 |
Yes | output | 1 | 32,779 | 15 | 65,559 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are three cells on an infinite 2-dimensional grid, labeled A, B, and F. Find the length of the shortest path from A to B if:
* in one move you can go to any of the four adjacent cells sharing a side;
* visiting the cell F is forbidden (it is an obstacle).
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first one contains two integers x_A, y_A (1 β€ x_A, y_A β€ 1000) β coordinates of the start cell A. The second one contains two integers x_B, y_B (1 β€ x_B, y_B β€ 1000) β coordinates of the finish cell B. The third one contains two integers x_F, y_F (1 β€ x_F, y_F β€ 1000) β coordinates of the forbidden cell F. All cells are distinct.
Coordinate x corresponds to the column number and coordinate y corresponds to the row number (see the pictures below).
Output
Output t lines. The i-th line should contain the answer for the i-th test case: the length of the shortest path from the cell A to the cell B if the cell F is not allowed to be visited.
Example
Input
7
1 1
3 3
2 2
2 5
2 1
2 3
1000 42
1000 1
1000 1000
1 10
3 10
2 10
3 8
7 8
3 7
2 1
4 1
1 1
1 344
1 10
1 1
Output
4
6
41
4
4
2
334
Note
<image> An example of a possible shortest path for the first test case. <image> An example of a possible shortest path for the second test case.
Submitted Solution:
```
n = int(input())
for i in range(n):
x_A=0
x_B=0
y_A=0
y_B=0
x_F=0
y_F=0
s=input()
s=input().split()
x_A=int(s[0])
y_A=int(s[1])
s=input().split()
x_B=int(s[0])
y_B=int(s[1])
s=input().split()
x_F=int(s[0])
y_F=int(s[1])
if(x_A == x_B == x_F and (y_A > y_F > y_B or y_B > y_F > y_A)):
print(abs(y_A-y_B)+2)
elif(y_A == y_B == y_F and (x_A > x_F > x_B or x_B > x_F > x_A)):
print(abs(x_A-x_B)+2)
else:
print(abs(x_A-x_B)+abs(y_A-y_B))
``` | instruction | 0 | 32,780 | 15 | 65,560 |
Yes | output | 1 | 32,780 | 15 | 65,561 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are three cells on an infinite 2-dimensional grid, labeled A, B, and F. Find the length of the shortest path from A to B if:
* in one move you can go to any of the four adjacent cells sharing a side;
* visiting the cell F is forbidden (it is an obstacle).
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first one contains two integers x_A, y_A (1 β€ x_A, y_A β€ 1000) β coordinates of the start cell A. The second one contains two integers x_B, y_B (1 β€ x_B, y_B β€ 1000) β coordinates of the finish cell B. The third one contains two integers x_F, y_F (1 β€ x_F, y_F β€ 1000) β coordinates of the forbidden cell F. All cells are distinct.
Coordinate x corresponds to the column number and coordinate y corresponds to the row number (see the pictures below).
Output
Output t lines. The i-th line should contain the answer for the i-th test case: the length of the shortest path from the cell A to the cell B if the cell F is not allowed to be visited.
Example
Input
7
1 1
3 3
2 2
2 5
2 1
2 3
1000 42
1000 1
1000 1000
1 10
3 10
2 10
3 8
7 8
3 7
2 1
4 1
1 1
1 344
1 10
1 1
Output
4
6
41
4
4
2
334
Note
<image> An example of a possible shortest path for the first test case. <image> An example of a possible shortest path for the second test case.
Submitted Solution:
```
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
input()
xa, ya = map(int, input().split())
xb, yb = map(int, input().split())
xf, yf = map(int, input().split())
if xa ^ xb and ya ^ yb:
ans = abs(xa - xb) + abs(ya - yb)
else:
ans = abs(xa - xb) + abs(ya - yb)
if xa == xb == xf:
if ya < yf < yb or yb < yf < ya:
ans += 2
if ya == yb == yf:
if xa < xf < xb or xb < xf < xa:
ans += 2
print(ans)
``` | instruction | 0 | 32,781 | 15 | 65,562 |
Yes | output | 1 | 32,781 | 15 | 65,563 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are three cells on an infinite 2-dimensional grid, labeled A, B, and F. Find the length of the shortest path from A to B if:
* in one move you can go to any of the four adjacent cells sharing a side;
* visiting the cell F is forbidden (it is an obstacle).
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first one contains two integers x_A, y_A (1 β€ x_A, y_A β€ 1000) β coordinates of the start cell A. The second one contains two integers x_B, y_B (1 β€ x_B, y_B β€ 1000) β coordinates of the finish cell B. The third one contains two integers x_F, y_F (1 β€ x_F, y_F β€ 1000) β coordinates of the forbidden cell F. All cells are distinct.
Coordinate x corresponds to the column number and coordinate y corresponds to the row number (see the pictures below).
Output
Output t lines. The i-th line should contain the answer for the i-th test case: the length of the shortest path from the cell A to the cell B if the cell F is not allowed to be visited.
Example
Input
7
1 1
3 3
2 2
2 5
2 1
2 3
1000 42
1000 1
1000 1000
1 10
3 10
2 10
3 8
7 8
3 7
2 1
4 1
1 1
1 344
1 10
1 1
Output
4
6
41
4
4
2
334
Note
<image> An example of a possible shortest path for the first test case. <image> An example of a possible shortest path for the second test case.
Submitted Solution:
```
for _ in range(int(input())):
arr=[]
input()
for i in range(3):
arr.append(list(map(int,input().split())))
x1,y1=arr[0]
x2, y2 =arr[1]
x3, y3 =arr[2]
ans=abs(x2-x1)+abs(y1-y2)
if (x1==x2==x3 and (y1<y3<y2 or y2<y3<y1)) or (y1==y2==y3 and (x1<x3<x2 or x2<x3<x1)):
ans+=2
print(ans)
``` | instruction | 0 | 32,782 | 15 | 65,564 |
Yes | output | 1 | 32,782 | 15 | 65,565 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are three cells on an infinite 2-dimensional grid, labeled A, B, and F. Find the length of the shortest path from A to B if:
* in one move you can go to any of the four adjacent cells sharing a side;
* visiting the cell F is forbidden (it is an obstacle).
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first one contains two integers x_A, y_A (1 β€ x_A, y_A β€ 1000) β coordinates of the start cell A. The second one contains two integers x_B, y_B (1 β€ x_B, y_B β€ 1000) β coordinates of the finish cell B. The third one contains two integers x_F, y_F (1 β€ x_F, y_F β€ 1000) β coordinates of the forbidden cell F. All cells are distinct.
Coordinate x corresponds to the column number and coordinate y corresponds to the row number (see the pictures below).
Output
Output t lines. The i-th line should contain the answer for the i-th test case: the length of the shortest path from the cell A to the cell B if the cell F is not allowed to be visited.
Example
Input
7
1 1
3 3
2 2
2 5
2 1
2 3
1000 42
1000 1
1000 1000
1 10
3 10
2 10
3 8
7 8
3 7
2 1
4 1
1 1
1 344
1 10
1 1
Output
4
6
41
4
4
2
334
Note
<image> An example of a possible shortest path for the first test case. <image> An example of a possible shortest path for the second test case.
Submitted Solution:
```
for _ in range(int(input())):
input()
colList=[]
rowList=[]
xsum=0
ysum=0
fsum=0
x=list(map(int,input().split()))[:2]
y=list(map(int,input().split()))[:2]
f=list(map(int,input().split()))[:2]
colList.append(x[0])
colList.append(y[0])
colList.append(f[0])
rowList.append(x[1])
rowList.append(y[1])
rowList.append(f[1])
xsum=sum(x)
ysum=sum(y)
fsum=sum(f)
if colList[0]==colList[1]==colList[2]:
if (rowList[2]>rowList[0] and rowList[2]>rowList[1]):
print(abs(xsum-ysum))
elif(rowList[2]<rowList[0] and rowList[2]<rowList[1]):
print(abs(xsum-ysum))
else:
val=abs((xsum-ysum))+2
print(val)
elif rowList[0]==rowList[1]==rowList[2]:
if colList[2]>colList[0] and colList[0]>colList[1]:
print(abs(xsum-ysum))
elif(colList[2]<colList[0] and colList[2]<colList[1]):
print(abs(xsum-ysum))
else:
val=abs((xsum-ysum))+2
print(val)
else:
print(abs(xsum-ysum))
``` | instruction | 0 | 32,783 | 15 | 65,566 |
No | output | 1 | 32,783 | 15 | 65,567 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are three cells on an infinite 2-dimensional grid, labeled A, B, and F. Find the length of the shortest path from A to B if:
* in one move you can go to any of the four adjacent cells sharing a side;
* visiting the cell F is forbidden (it is an obstacle).
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first one contains two integers x_A, y_A (1 β€ x_A, y_A β€ 1000) β coordinates of the start cell A. The second one contains two integers x_B, y_B (1 β€ x_B, y_B β€ 1000) β coordinates of the finish cell B. The third one contains two integers x_F, y_F (1 β€ x_F, y_F β€ 1000) β coordinates of the forbidden cell F. All cells are distinct.
Coordinate x corresponds to the column number and coordinate y corresponds to the row number (see the pictures below).
Output
Output t lines. The i-th line should contain the answer for the i-th test case: the length of the shortest path from the cell A to the cell B if the cell F is not allowed to be visited.
Example
Input
7
1 1
3 3
2 2
2 5
2 1
2 3
1000 42
1000 1
1000 1000
1 10
3 10
2 10
3 8
7 8
3 7
2 1
4 1
1 1
1 344
1 10
1 1
Output
4
6
41
4
4
2
334
Note
<image> An example of a possible shortest path for the first test case. <image> An example of a possible shortest path for the second test case.
Submitted Solution:
```
import math
num = (int)(input())
while(num>0):
a=input()
if(a==''):
a=(input()).split(" ")
else:
a=a.split(" ")
b=(input()).split(" ")
c=(input()).split(" ")
a1 = (int)(a[0])
a2 = (int)(a[1])
b1 = (int)(b[0])
b2 = (int)(b[1])
c1 = (int)(c[0])
c2 = (int)(c[1])
if ( (a1==b1) & (a1==c1)) :
y = (int)(math.fabs(b2 - a2))
print(y)
elif ( a2==b2 & a2==c2):
y = (int)(math.fabs(b1-a1))
print(y)
else :
y=(int)(math.fabs(b2-a2)+math.fabs(b1-a1))
print(y)
num=num-1
``` | instruction | 0 | 32,784 | 15 | 65,568 |
No | output | 1 | 32,784 | 15 | 65,569 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are three cells on an infinite 2-dimensional grid, labeled A, B, and F. Find the length of the shortest path from A to B if:
* in one move you can go to any of the four adjacent cells sharing a side;
* visiting the cell F is forbidden (it is an obstacle).
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first one contains two integers x_A, y_A (1 β€ x_A, y_A β€ 1000) β coordinates of the start cell A. The second one contains two integers x_B, y_B (1 β€ x_B, y_B β€ 1000) β coordinates of the finish cell B. The third one contains two integers x_F, y_F (1 β€ x_F, y_F β€ 1000) β coordinates of the forbidden cell F. All cells are distinct.
Coordinate x corresponds to the column number and coordinate y corresponds to the row number (see the pictures below).
Output
Output t lines. The i-th line should contain the answer for the i-th test case: the length of the shortest path from the cell A to the cell B if the cell F is not allowed to be visited.
Example
Input
7
1 1
3 3
2 2
2 5
2 1
2 3
1000 42
1000 1
1000 1000
1 10
3 10
2 10
3 8
7 8
3 7
2 1
4 1
1 1
1 344
1 10
1 1
Output
4
6
41
4
4
2
334
Note
<image> An example of a possible shortest path for the first test case. <image> An example of a possible shortest path for the second test case.
Submitted Solution:
```
import sys
input = sys.stdin.readline
import sys
input = sys.stdin.readline
for _ in range(int(input())):
input()
xa, ya = map(int, input().split())
xb, yb = map(int, input().split())
xf, yf = map(int, input().split())
ans = abs(xa - xb) + abs(ya - yb)
tmp = 0
if xa == xb and (yf - ya) * (yf - yb) < 0: tmp = 2
if ya == yb and (xf - xa) * (xf - xb) < 0: tmp = 2
print(ans + tmp)
``` | instruction | 0 | 32,785 | 15 | 65,570 |
No | output | 1 | 32,785 | 15 | 65,571 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are three cells on an infinite 2-dimensional grid, labeled A, B, and F. Find the length of the shortest path from A to B if:
* in one move you can go to any of the four adjacent cells sharing a side;
* visiting the cell F is forbidden (it is an obstacle).
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first one contains two integers x_A, y_A (1 β€ x_A, y_A β€ 1000) β coordinates of the start cell A. The second one contains two integers x_B, y_B (1 β€ x_B, y_B β€ 1000) β coordinates of the finish cell B. The third one contains two integers x_F, y_F (1 β€ x_F, y_F β€ 1000) β coordinates of the forbidden cell F. All cells are distinct.
Coordinate x corresponds to the column number and coordinate y corresponds to the row number (see the pictures below).
Output
Output t lines. The i-th line should contain the answer for the i-th test case: the length of the shortest path from the cell A to the cell B if the cell F is not allowed to be visited.
Example
Input
7
1 1
3 3
2 2
2 5
2 1
2 3
1000 42
1000 1
1000 1000
1 10
3 10
2 10
3 8
7 8
3 7
2 1
4 1
1 1
1 344
1 10
1 1
Output
4
6
41
4
4
2
334
Note
<image> An example of a possible shortest path for the first test case. <image> An example of a possible shortest path for the second test case.
Submitted Solution:
```
t = int(input())
while t:
input()
xa, ya = map(int, input().split())
xb, yb = map(int, input().split())
xf, yf = map(int, input().split())
if xa == xb == xf and min(ya, yb) < yf and max(ya, yb) > yf:
print(abs(xa-xb)+2)
elif ya == yb == yf and min(xa,xb) < xf and max(xa,xb) > xf:
print(abs(ya-yb)+2)
else:
print(abs(xa-xb) + abs(ya-yb))
t-=1
``` | instruction | 0 | 32,786 | 15 | 65,572 |
No | output | 1 | 32,786 | 15 | 65,573 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.
Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.
Input
The first line of the input contains n (1 β€ n β€ 200 000) β the number of bishops.
Each of next n lines contains two space separated integers xi and yi (1 β€ xi, yi β€ 1000) β the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.
Output
Output one integer β the number of pairs of bishops which attack each other.
Examples
Input
5
1 1
1 5
3 3
5 1
5 5
Output
6
Input
3
1 1
2 3
3 5
Output
0
Note
In the first sample following pairs of bishops attack each other: (1, 3), (1, 5), (2, 3), (2, 4), (3, 4) and (3, 5). Pairs (1, 2), (1, 4), (2, 5) and (4, 5) do not attack each other because they do not share the same diagonal. | instruction | 0 | 32,981 | 15 | 65,962 |
Tags: combinatorics, implementation
Correct Solution:
```
n=int(input())
res=[0]*2000
resT=[0]*2000
while n!=0:
x,y=[int(p) for p in input().split()]
x-=1
y-=1
res[x+y]+=1
resT[x+999-y]+=1
n-=1
s=0
for x in range(2000):
if res[x]>1:
s+=res[x]*(res[x]-1)//2
if resT[x]>1:
s+=resT[x]*(resT[x]-1)//2
print(s)
``` | output | 1 | 32,981 | 15 | 65,963 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.
Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.
Input
The first line of the input contains n (1 β€ n β€ 200 000) β the number of bishops.
Each of next n lines contains two space separated integers xi and yi (1 β€ xi, yi β€ 1000) β the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.
Output
Output one integer β the number of pairs of bishops which attack each other.
Examples
Input
5
1 1
1 5
3 3
5 1
5 5
Output
6
Input
3
1 1
2 3
3 5
Output
0
Note
In the first sample following pairs of bishops attack each other: (1, 3), (1, 5), (2, 3), (2, 4), (3, 4) and (3, 5). Pairs (1, 2), (1, 4), (2, 5) and (4, 5) do not attack each other because they do not share the same diagonal. | instruction | 0 | 32,982 | 15 | 65,964 |
Tags: combinatorics, implementation
Correct Solution:
```
n = int(input())
a = [[*map(int, input().split())] for i in range(n)]
d1 = {}
d2 = {}
for i in a:
wk1 = i[0] + i[1]
wk2 = i[0] - i[1]
if not wk1 in d1:
d1[wk1] = 0
d1[wk1] += 1
if not wk2 in d2:
d2[wk2] = 0
d2[wk2] += 1
ans = 0
for i in d1:
ans += (d1[i] - 1) * d1[i] // 2
for i in d2:
ans += (d2[i] - 1) * d2[i] // 2
print(ans)
``` | output | 1 | 32,982 | 15 | 65,965 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.
Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.
Input
The first line of the input contains n (1 β€ n β€ 200 000) β the number of bishops.
Each of next n lines contains two space separated integers xi and yi (1 β€ xi, yi β€ 1000) β the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.
Output
Output one integer β the number of pairs of bishops which attack each other.
Examples
Input
5
1 1
1 5
3 3
5 1
5 5
Output
6
Input
3
1 1
2 3
3 5
Output
0
Note
In the first sample following pairs of bishops attack each other: (1, 3), (1, 5), (2, 3), (2, 4), (3, 4) and (3, 5). Pairs (1, 2), (1, 4), (2, 5) and (4, 5) do not attack each other because they do not share the same diagonal. | instruction | 0 | 32,983 | 15 | 65,966 |
Tags: combinatorics, implementation
Correct Solution:
```
dic1={}
dic2={}
x=int(input())
for n in range(x):
a,b=map(int,input().split())
if a+b not in dic1:
dic1[a+b]=1
else: dic1[a+b]+=1
if a-b not in dic2: dic2[a-b]=1
else: dic2[a-b]+=1
res=0
for n in dic1:
res+=dic1[n]*(dic1[n]-1)//2
for n in dic2:
res+=dic2[n]*(dic2[n]-1)//2
print(res)
``` | output | 1 | 32,983 | 15 | 65,967 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.
Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.
Input
The first line of the input contains n (1 β€ n β€ 200 000) β the number of bishops.
Each of next n lines contains two space separated integers xi and yi (1 β€ xi, yi β€ 1000) β the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.
Output
Output one integer β the number of pairs of bishops which attack each other.
Examples
Input
5
1 1
1 5
3 3
5 1
5 5
Output
6
Input
3
1 1
2 3
3 5
Output
0
Note
In the first sample following pairs of bishops attack each other: (1, 3), (1, 5), (2, 3), (2, 4), (3, 4) and (3, 5). Pairs (1, 2), (1, 4), (2, 5) and (4, 5) do not attack each other because they do not share the same diagonal. | instruction | 0 | 32,984 | 15 | 65,968 |
Tags: combinatorics, implementation
Correct Solution:
```
d={}
d1={}
sm=0
sh=[]
n=int(input())
for i in range(n):
sh.append(list(map(int,input().split())))
for i in range(n):
x=sh[i][0]
y=sh[i][1]
sm+=d.get(x+y,0)
sm+=d1.get(x-y,0)
d[x+y]=d.get(x+y,0)+1
d1[x-y]=d1.get(x-y,0)+1
print(sm)
``` | output | 1 | 32,984 | 15 | 65,969 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.
Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.
Input
The first line of the input contains n (1 β€ n β€ 200 000) β the number of bishops.
Each of next n lines contains two space separated integers xi and yi (1 β€ xi, yi β€ 1000) β the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.
Output
Output one integer β the number of pairs of bishops which attack each other.
Examples
Input
5
1 1
1 5
3 3
5 1
5 5
Output
6
Input
3
1 1
2 3
3 5
Output
0
Note
In the first sample following pairs of bishops attack each other: (1, 3), (1, 5), (2, 3), (2, 4), (3, 4) and (3, 5). Pairs (1, 2), (1, 4), (2, 5) and (4, 5) do not attack each other because they do not share the same diagonal. | instruction | 0 | 32,985 | 15 | 65,970 |
Tags: combinatorics, implementation
Correct Solution:
```
n = int(input())
grid = [[0 for x in range(1000)] for x in range(1000)]
ans, tmpAns = 0, 0
def getNS(n):
if n < 2:
return 0
return (n * (n - 1)) / 2
for i in range(n):
x, y = [int(i) for i in input().split()]
grid[x - 1][y - 1] = 1
for i in range(1000):
for j in range(1000 - i):
k = j + i
if grid[j][k] == 1:
tmpAns += 1
ans += getNS(tmpAns)
tmpAns = 0
for i in range(1, 1000):
for j in range(1000 - i):
k = j + i
if grid[k][j] == 1:
tmpAns += 1
ans += getNS(tmpAns)
tmpAns = 0
for i in range(1000):
for j in range(i, -1, -1):
k = i - j
if grid[j][k] == 1:
tmpAns += 1
ans += getNS(tmpAns)
tmpAns = 0
for i in range(1, 1000):
for j in range(999, i - 1, -1):
k = 999 - j + i
if grid[j][k] == 1:
tmpAns += 1
ans += getNS(tmpAns)
tmpAns = 0
print(int(ans))
``` | output | 1 | 32,985 | 15 | 65,971 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.
Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.
Input
The first line of the input contains n (1 β€ n β€ 200 000) β the number of bishops.
Each of next n lines contains two space separated integers xi and yi (1 β€ xi, yi β€ 1000) β the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.
Output
Output one integer β the number of pairs of bishops which attack each other.
Examples
Input
5
1 1
1 5
3 3
5 1
5 5
Output
6
Input
3
1 1
2 3
3 5
Output
0
Note
In the first sample following pairs of bishops attack each other: (1, 3), (1, 5), (2, 3), (2, 4), (3, 4) and (3, 5). Pairs (1, 2), (1, 4), (2, 5) and (4, 5) do not attack each other because they do not share the same diagonal. | instruction | 0 | 32,986 | 15 | 65,972 |
Tags: combinatorics, implementation
Correct Solution:
```
p, m = dict(), dict()
attacks = 0
for _ in range(int(input())):
x, y = map(int, input().split())
if x + y not in p:
p[x + y] = 0
if x - y not in m:
m[x - y] = 0
attacks += p[x + y] + m[x - y]
p[x + y] += 1
m[x - y] += 1
print(attacks)
``` | output | 1 | 32,986 | 15 | 65,973 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.
Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.
Input
The first line of the input contains n (1 β€ n β€ 200 000) β the number of bishops.
Each of next n lines contains two space separated integers xi and yi (1 β€ xi, yi β€ 1000) β the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.
Output
Output one integer β the number of pairs of bishops which attack each other.
Examples
Input
5
1 1
1 5
3 3
5 1
5 5
Output
6
Input
3
1 1
2 3
3 5
Output
0
Note
In the first sample following pairs of bishops attack each other: (1, 3), (1, 5), (2, 3), (2, 4), (3, 4) and (3, 5). Pairs (1, 2), (1, 4), (2, 5) and (4, 5) do not attack each other because they do not share the same diagonal. | instruction | 0 | 32,987 | 15 | 65,974 |
Tags: combinatorics, implementation
Correct Solution:
```
p,m=[0]*2100,[0]*2100
a=0
for _ in range(int(input())):
x,y = map(int,input().split())
a+=p[x+y]+m[x-y]
p[x+y]+=1
m[x-y]+=1
print(a)
``` | output | 1 | 32,987 | 15 | 65,975 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.
Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.
Input
The first line of the input contains n (1 β€ n β€ 200 000) β the number of bishops.
Each of next n lines contains two space separated integers xi and yi (1 β€ xi, yi β€ 1000) β the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.
Output
Output one integer β the number of pairs of bishops which attack each other.
Examples
Input
5
1 1
1 5
3 3
5 1
5 5
Output
6
Input
3
1 1
2 3
3 5
Output
0
Note
In the first sample following pairs of bishops attack each other: (1, 3), (1, 5), (2, 3), (2, 4), (3, 4) and (3, 5). Pairs (1, 2), (1, 4), (2, 5) and (4, 5) do not attack each other because they do not share the same diagonal. | instruction | 0 | 32,988 | 15 | 65,976 |
Tags: combinatorics, implementation
Correct Solution:
```
#Wet Shark and Bishops
n = int(input())
cnt = 0
dictt ={}
dictt2={}
for i in range(n):
a,b = map(int,input().split())
try:dictt[a+b]+=1
except :dictt[a+b]=1
try:dictt2[a-b]+=1
except:dictt2[a-b]=1
for i,j in dictt.items():
if (j>1):
cnt+=(j*(j-1))//2
for i,j in dictt2.items():
if (j>1):
cnt += (j * (j - 1)) // 2
print(cnt)
``` | output | 1 | 32,988 | 15 | 65,977 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.
Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.
Input
The first line of the input contains n (1 β€ n β€ 200 000) β the number of bishops.
Each of next n lines contains two space separated integers xi and yi (1 β€ xi, yi β€ 1000) β the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.
Output
Output one integer β the number of pairs of bishops which attack each other.
Examples
Input
5
1 1
1 5
3 3
5 1
5 5
Output
6
Input
3
1 1
2 3
3 5
Output
0
Note
In the first sample following pairs of bishops attack each other: (1, 3), (1, 5), (2, 3), (2, 4), (3, 4) and (3, 5). Pairs (1, 2), (1, 4), (2, 5) and (4, 5) do not attack each other because they do not share the same diagonal.
Submitted Solution:
```
import sys
n=int(sys.stdin.readline())
a=[]
b=[]
res=0
for i in range(n):
_a, _b = list(map(int, sys.stdin.readline().split()))
a.append(_a+_b)
b.append(_a-_b)
a.sort()
b.sort()
i=0
while i<n:
cnt=1
while i+1<len(a) and a[i]==a[i+1]:
cnt+=1
i+=1
res+=cnt*(cnt-1)//2
i+=1
i=0
while i<n:
cnt=1
while i+1<len(b) and b[i]==b[i+1]:
cnt+=1
i+=1
res+=cnt*(cnt-1)//2
i+=1
print(res)
``` | instruction | 0 | 32,989 | 15 | 65,978 |
Yes | output | 1 | 32,989 | 15 | 65,979 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.
Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.
Input
The first line of the input contains n (1 β€ n β€ 200 000) β the number of bishops.
Each of next n lines contains two space separated integers xi and yi (1 β€ xi, yi β€ 1000) β the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.
Output
Output one integer β the number of pairs of bishops which attack each other.
Examples
Input
5
1 1
1 5
3 3
5 1
5 5
Output
6
Input
3
1 1
2 3
3 5
Output
0
Note
In the first sample following pairs of bishops attack each other: (1, 3), (1, 5), (2, 3), (2, 4), (3, 4) and (3, 5). Pairs (1, 2), (1, 4), (2, 5) and (4, 5) do not attack each other because they do not share the same diagonal.
Submitted Solution:
```
a=[0]*2222
b=[0]*2222
r=0
for _ in range(int(input())):
x,y=map(int,input().split())
r+=a[x+y]+b[x-y+1111]
a[x+y]+=1
b[x-y+1111]+=1
print(r)
``` | instruction | 0 | 32,990 | 15 | 65,980 |
Yes | output | 1 | 32,990 | 15 | 65,981 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.
Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.
Input
The first line of the input contains n (1 β€ n β€ 200 000) β the number of bishops.
Each of next n lines contains two space separated integers xi and yi (1 β€ xi, yi β€ 1000) β the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.
Output
Output one integer β the number of pairs of bishops which attack each other.
Examples
Input
5
1 1
1 5
3 3
5 1
5 5
Output
6
Input
3
1 1
2 3
3 5
Output
0
Note
In the first sample following pairs of bishops attack each other: (1, 3), (1, 5), (2, 3), (2, 4), (3, 4) and (3, 5). Pairs (1, 2), (1, 4), (2, 5) and (4, 5) do not attack each other because they do not share the same diagonal.
Submitted Solution:
```
n = int(input())
def main(n):
p = []
q = []
for i in range(2):
p.append([0] * 1000)
for i in range(2):
q.append([0] * 1000)
for i in range(n):
x, y = map(int, input().split())
x1, y1, x2, y2 = x - 1, y - 1, x - 1, y - 1
x1, y1 = x1 - min(x1, y1), y1 - min(x1, y1)
if x1 == 0:
p[1][y1] += 1
else:
p[0][x1] += 1
while y2 < 999 and x2 > 0:
x2 -= 1
y2 += 1
if y2 == 999:
q[1][x2] += 1
else:
q[0][y2] += 1
sum = 0
for i in range(2):
for t in range(1000):
sum += (p[i][t] * (p[i][t] - 1)) // 2
for i in range(2):
for t in range(1000):
sum += (q[i][t] * (q[i][t] - 1)) // 2
print(sum)
main(n)
``` | instruction | 0 | 32,991 | 15 | 65,982 |
Yes | output | 1 | 32,991 | 15 | 65,983 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.
Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.
Input
The first line of the input contains n (1 β€ n β€ 200 000) β the number of bishops.
Each of next n lines contains two space separated integers xi and yi (1 β€ xi, yi β€ 1000) β the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.
Output
Output one integer β the number of pairs of bishops which attack each other.
Examples
Input
5
1 1
1 5
3 3
5 1
5 5
Output
6
Input
3
1 1
2 3
3 5
Output
0
Note
In the first sample following pairs of bishops attack each other: (1, 3), (1, 5), (2, 3), (2, 4), (3, 4) and (3, 5). Pairs (1, 2), (1, 4), (2, 5) and (4, 5) do not attack each other because they do not share the same diagonal.
Submitted Solution:
```
a, b, res = [0] * 2003, [0] * 2003, 0
for _ in range(int(input())):
x, y = map(int, input().split())
res += a[x + y] + b[x - y]
a[x + y] += 1
b[x - y] += 1
print(res)
``` | instruction | 0 | 32,992 | 15 | 65,984 |
Yes | output | 1 | 32,992 | 15 | 65,985 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.
Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.
Input
The first line of the input contains n (1 β€ n β€ 200 000) β the number of bishops.
Each of next n lines contains two space separated integers xi and yi (1 β€ xi, yi β€ 1000) β the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.
Output
Output one integer β the number of pairs of bishops which attack each other.
Examples
Input
5
1 1
1 5
3 3
5 1
5 5
Output
6
Input
3
1 1
2 3
3 5
Output
0
Note
In the first sample following pairs of bishops attack each other: (1, 3), (1, 5), (2, 3), (2, 4), (3, 4) and (3, 5). Pairs (1, 2), (1, 4), (2, 5) and (4, 5) do not attack each other because they do not share the same diagonal.
Submitted Solution:
```
# Description of the problem can be found at http://codeforces.com/problemset/problem/621/B
d_p = {}
n_p = int(input())
t = 0
for i in range(n_p):
x, y = map(int, input().split())
if y != 1:
d_n = 1 - y
d = -(1 - y)
s_n1 = x - d_n
s_1 = x - d
if s_n1 not in d_p:
d_p[s_n1] = 0
if s_1 not in d_p:
d_p[s_1] = 0
d_p[s_n1] += 1
d_p[s_1] += 1
t += d_p[s_n1] + d_p[s_1] - 2
else:
if x not in d_p:
d_p[x] = 0
d_p[x] += 1
t += d_p[x] - 1
print(t)
``` | instruction | 0 | 32,993 | 15 | 65,986 |
No | output | 1 | 32,993 | 15 | 65,987 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.
Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.
Input
The first line of the input contains n (1 β€ n β€ 200 000) β the number of bishops.
Each of next n lines contains two space separated integers xi and yi (1 β€ xi, yi β€ 1000) β the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.
Output
Output one integer β the number of pairs of bishops which attack each other.
Examples
Input
5
1 1
1 5
3 3
5 1
5 5
Output
6
Input
3
1 1
2 3
3 5
Output
0
Note
In the first sample following pairs of bishops attack each other: (1, 3), (1, 5), (2, 3), (2, 4), (3, 4) and (3, 5). Pairs (1, 2), (1, 4), (2, 5) and (4, 5) do not attack each other because they do not share the same diagonal.
Submitted Solution:
```
#Wet Shark and Bishops
n = int(input())
cnt = 0
dictt ={}
for i in range(n):
a,b = map(int,input().split())
try:dictt[a+b]+=1
except :dictt[a+b]=1
try:dictt[a-b]+=1
except:dictt[a-b]=1
for i,j in dictt.items():
if (j>1):
cnt+=j
print(cnt)
``` | instruction | 0 | 32,994 | 15 | 65,988 |
No | output | 1 | 32,994 | 15 | 65,989 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.
Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.
Input
The first line of the input contains n (1 β€ n β€ 200 000) β the number of bishops.
Each of next n lines contains two space separated integers xi and yi (1 β€ xi, yi β€ 1000) β the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.
Output
Output one integer β the number of pairs of bishops which attack each other.
Examples
Input
5
1 1
1 5
3 3
5 1
5 5
Output
6
Input
3
1 1
2 3
3 5
Output
0
Note
In the first sample following pairs of bishops attack each other: (1, 3), (1, 5), (2, 3), (2, 4), (3, 4) and (3, 5). Pairs (1, 2), (1, 4), (2, 5) and (4, 5) do not attack each other because they do not share the same diagonal.
Submitted Solution:
```
g = [[0] * 1000 for _ in range(1000)]
for _ in range(int(input())):
i, j = map(int, input().split())
g[i - 1][j - 1] = 1
h, w = len(g), len(g[0])
diagonal = [[g[h - p + q - 1][q] for q in range(max(p - h + 1, 0),
min(p + 1, w))] for p in range(h + w - 1)]
antidiagonal = [[g[h - p + q - 1][q] for q in range(max(p - h + 1, 0),
min(p + 1, w))] for p in range(h + w - 1)]
ans = 0
for i, j in zip(diagonal, antidiagonal):
d, a = i.count(1), j.count(1)
ans += (d * (d - 1)) // 2 + (a * (a - 1)) // 2
print(ans)
``` | instruction | 0 | 32,995 | 15 | 65,990 |
No | output | 1 | 32,995 | 15 | 65,991 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.
Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.
Input
The first line of the input contains n (1 β€ n β€ 200 000) β the number of bishops.
Each of next n lines contains two space separated integers xi and yi (1 β€ xi, yi β€ 1000) β the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.
Output
Output one integer β the number of pairs of bishops which attack each other.
Examples
Input
5
1 1
1 5
3 3
5 1
5 5
Output
6
Input
3
1 1
2 3
3 5
Output
0
Note
In the first sample following pairs of bishops attack each other: (1, 3), (1, 5), (2, 3), (2, 4), (3, 4) and (3, 5). Pairs (1, 2), (1, 4), (2, 5) and (4, 5) do not attack each other because they do not share the same diagonal.
Submitted Solution:
```
from itertools import combinations, accumulate, groupby, count
from sys import stdout, stdin, setrecursionlimit
from collections import *
from random import *
from bisect import *
from string import *
from queue import *
from heapq import *
from math import *
from re import *
def fast(): return stdin.readline().strip()
def zzz(): return [int(i) for i in fast().split()]
z, zz = input, lambda: list(map(int, z().split()))
szz, graph, mod, szzz = lambda: sorted(
zz()), {}, 10**9 + 7, lambda: sorted(zzz())
def lcd(xnum1, xnum2): return (xnum1 * xnum2 // gcd(xnum1, xnum2))
def output(answer): stdout.write(str(answer))
dx = [-1, 1, 0, 0, 1, -1, 1, -1]
dy = [0, 0, 1, -1, 1, -1, -1, 1]
###########################---Some Rule For Me To Follow---#################################
"""
--instants of Reading problem continuously try to understand them.
--If you Know some , Then you probably don't know him !
"""
###########################---START-CODING---###############################################
# num = int(z())
# lst = []
# for _ in range(num):
# arr = zzz()
# lst.append(arr)
# left = 0
# right = 10**9 + 1
# while right - left > 1:
# curr = (right + left) // 2
# currSet = set()
# for i in range(num):
# msk = 0
# for j in range(5):
# if lst[i][j] >= curr:
# msk |= 1 << j
# currSet.add(msk)
# flag = False
# for x in currSet:
# for y in currSet:
# for k in currSet:
# if x | y | k == 31:
# flag = True
# if flag:
# left = curr
# else:
# right = curr
# print(left)
num = int(z())
lst = {}
for i in range(num):
x, y = zzz()
try:
lst[x - y + 1000]
except:
lst[x - y + 1000] = 0
try:
lst[x + y]
except:
lst[x + y] = 0
lst[x - y + 1000] += 1
lst[x + y] += 1
ans = 0
def solve(x):
return x * (x - 1) // 2
for i in lst:
ans += solve(lst[i])
print(ans)
``` | instruction | 0 | 32,996 | 15 | 65,992 |
No | output | 1 | 32,996 | 15 | 65,993 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.