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.
We have a grid of H rows and W columns. Initially, there is a stone in the top left cell. Shik is trying to move the stone to the bottom right cell. In each step, he can move the stone one cell to its left, up, right, or down (if such cell exists). It is possible that the stone visits a cell multiple times (including the bottom right and the top left cell).
You are given a matrix of characters a_{ij} (1 \leq i \leq H, 1 \leq j \leq W). After Shik completes all moving actions, a_{ij} is `#` if the stone had ever located at the i-th row and the j-th column during the process of moving. Otherwise, a_{ij} is `.`. Please determine whether it is possible that Shik only uses right and down moves in all steps.
Constraints
* 2 \leq H, W \leq 8
* a_{i,j} is either `#` or `.`.
* There exists a valid sequence of moves for Shik to generate the map a.
Input
The input is given from Standard Input in the following format:
H W
a_{11}a_{12}...a_{1W}
:
a_{H1}a_{H2}...a_{HW}
Output
If it is possible that Shik only uses right and down moves, print `Possible`. Otherwise, print `Impossible`.
Examples
Input
4 5
##...
.##..
..##.
...##
Output
Possible
Input
4 5
...
.##..
..##.
...##
Output
Possible
Input
5 3
..#
..
Output
Impossible
Input
4 5
...
.###.
.###.
...##
Output
Impossible
Submitted Solution:
```
h,w = map(int,input().split())
cnt = 0
for i in range(h):
A = list(input())
cnt += A.count('#')
if cnt == h+w-1:
print("Possible")
else:
print("Impossible")
``` | instruction | 0 | 66,363 | 15 | 132,726 |
Yes | output | 1 | 66,363 | 15 | 132,727 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a grid of H rows and W columns. Initially, there is a stone in the top left cell. Shik is trying to move the stone to the bottom right cell. In each step, he can move the stone one cell to its left, up, right, or down (if such cell exists). It is possible that the stone visits a cell multiple times (including the bottom right and the top left cell).
You are given a matrix of characters a_{ij} (1 \leq i \leq H, 1 \leq j \leq W). After Shik completes all moving actions, a_{ij} is `#` if the stone had ever located at the i-th row and the j-th column during the process of moving. Otherwise, a_{ij} is `.`. Please determine whether it is possible that Shik only uses right and down moves in all steps.
Constraints
* 2 \leq H, W \leq 8
* a_{i,j} is either `#` or `.`.
* There exists a valid sequence of moves for Shik to generate the map a.
Input
The input is given from Standard Input in the following format:
H W
a_{11}a_{12}...a_{1W}
:
a_{H1}a_{H2}...a_{HW}
Output
If it is possible that Shik only uses right and down moves, print `Possible`. Otherwise, print `Impossible`.
Examples
Input
4 5
##...
.##..
..##.
...##
Output
Possible
Input
4 5
...
.##..
..##.
...##
Output
Possible
Input
5 3
..#
..
Output
Impossible
Input
4 5
...
.###.
.###.
...##
Output
Impossible
Submitted Solution:
```
H, W = map(int, input().split())
A = [input() for _ in range(H)]
cnt = 0
for i in range(H):
cnt += A[i].count("#")
print("Possible" if cnt == H + W - 1 else "Impossible")
``` | instruction | 0 | 66,364 | 15 | 132,728 |
Yes | output | 1 | 66,364 | 15 | 132,729 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a grid of H rows and W columns. Initially, there is a stone in the top left cell. Shik is trying to move the stone to the bottom right cell. In each step, he can move the stone one cell to its left, up, right, or down (if such cell exists). It is possible that the stone visits a cell multiple times (including the bottom right and the top left cell).
You are given a matrix of characters a_{ij} (1 \leq i \leq H, 1 \leq j \leq W). After Shik completes all moving actions, a_{ij} is `#` if the stone had ever located at the i-th row and the j-th column during the process of moving. Otherwise, a_{ij} is `.`. Please determine whether it is possible that Shik only uses right and down moves in all steps.
Constraints
* 2 \leq H, W \leq 8
* a_{i,j} is either `#` or `.`.
* There exists a valid sequence of moves for Shik to generate the map a.
Input
The input is given from Standard Input in the following format:
H W
a_{11}a_{12}...a_{1W}
:
a_{H1}a_{H2}...a_{HW}
Output
If it is possible that Shik only uses right and down moves, print `Possible`. Otherwise, print `Impossible`.
Examples
Input
4 5
##...
.##..
..##.
...##
Output
Possible
Input
4 5
...
.##..
..##.
...##
Output
Possible
Input
5 3
..#
..
Output
Impossible
Input
4 5
...
.###.
.###.
...##
Output
Impossible
Submitted Solution:
```
h,w = map(int,input().split())
count = 0
for i in range(h):
a = input()
count += a.count('#')
if count == h+w-1:print('Possible')
else:print('Impossible')
``` | instruction | 0 | 66,365 | 15 | 132,730 |
Yes | output | 1 | 66,365 | 15 | 132,731 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a grid of H rows and W columns. Initially, there is a stone in the top left cell. Shik is trying to move the stone to the bottom right cell. In each step, he can move the stone one cell to its left, up, right, or down (if such cell exists). It is possible that the stone visits a cell multiple times (including the bottom right and the top left cell).
You are given a matrix of characters a_{ij} (1 \leq i \leq H, 1 \leq j \leq W). After Shik completes all moving actions, a_{ij} is `#` if the stone had ever located at the i-th row and the j-th column during the process of moving. Otherwise, a_{ij} is `.`. Please determine whether it is possible that Shik only uses right and down moves in all steps.
Constraints
* 2 \leq H, W \leq 8
* a_{i,j} is either `#` or `.`.
* There exists a valid sequence of moves for Shik to generate the map a.
Input
The input is given from Standard Input in the following format:
H W
a_{11}a_{12}...a_{1W}
:
a_{H1}a_{H2}...a_{HW}
Output
If it is possible that Shik only uses right and down moves, print `Possible`. Otherwise, print `Impossible`.
Examples
Input
4 5
##...
.##..
..##.
...##
Output
Possible
Input
4 5
...
.##..
..##.
...##
Output
Possible
Input
5 3
..#
..
Output
Impossible
Input
4 5
...
.###.
.###.
...##
Output
Impossible
Submitted Solution:
```
h, w = map(int, input().split())
table = []
for _ in range(h):
table.append(list(input()))
if table[0][0] == "." or table[h - 1][w - 1] == ".":
print("Impossible")
exit()
stack = [[0, 0]]
flag = False
while len(stack) > 0 and not flag:
cur = stack.pop()
table[cur[0]][cur[1]] = "."
for step in [[0, 1], [1, 0]]:
x, y = cur[1] + step[1], cur[0] + step[0]
if x < w and y < h and table[y][x] == "#":
table[cur[0]][cur[1]] = "."
if y == h - 1 and x == w - 1:
table[y][x] = "."
flag = True
break
stack.append([y, x])
for y in range(h):
for x in range(w):
if table[y][x] == "#":
print("Impossible")
exit()
print("Possible")
``` | instruction | 0 | 66,366 | 15 | 132,732 |
No | output | 1 | 66,366 | 15 | 132,733 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a grid of H rows and W columns. Initially, there is a stone in the top left cell. Shik is trying to move the stone to the bottom right cell. In each step, he can move the stone one cell to its left, up, right, or down (if such cell exists). It is possible that the stone visits a cell multiple times (including the bottom right and the top left cell).
You are given a matrix of characters a_{ij} (1 \leq i \leq H, 1 \leq j \leq W). After Shik completes all moving actions, a_{ij} is `#` if the stone had ever located at the i-th row and the j-th column during the process of moving. Otherwise, a_{ij} is `.`. Please determine whether it is possible that Shik only uses right and down moves in all steps.
Constraints
* 2 \leq H, W \leq 8
* a_{i,j} is either `#` or `.`.
* There exists a valid sequence of moves for Shik to generate the map a.
Input
The input is given from Standard Input in the following format:
H W
a_{11}a_{12}...a_{1W}
:
a_{H1}a_{H2}...a_{HW}
Output
If it is possible that Shik only uses right and down moves, print `Possible`. Otherwise, print `Impossible`.
Examples
Input
4 5
##...
.##..
..##.
...##
Output
Possible
Input
4 5
...
.##..
..##.
...##
Output
Possible
Input
5 3
..#
..
Output
Impossible
Input
4 5
...
.###.
.###.
...##
Output
Impossible
Submitted Solution:
```
import sys
import math
from collections import deque
inint = lambda: int(sys.stdin.readline())
inintm = lambda: map(int, sys.stdin.readline().split())
inintl = lambda: list(inintm())
instrm = lambda: map(str, sys.stdin.readline().split())
instrl = lambda: list(instrm())
h, w = inintm()
grid = []
gl = []
now = [0,0]
nowl = [[0,0]]
for i in range(h):
grid.append(input())
while now != [h-1,w-1]:
if now[0] == h-1:
if grid[h-1][now[1]+1] == "#":
now = [h-1, now[1]+1]
continue
else:
print("Impossible")
exit()
elif now[1] == w-1:
if grid[now[0]+1][w-1] == "#":
now = [now[0]+1, w-1]
continue
else:
print("Impossible")
exit()
else:
if grid[now[0]+1][now[1]] == "#" and grid[now[0]][now[1]+1] == ".":
now = [now[0]+1, now[1]]
elif grid[now[0]+1][now[1]] == "." and grid[now[0]][now[1]+1] == "#":
now = [now[0], now[1]+1]
else:
print("Impossible")
exit()
nowl.append(now)
nowl.append([h-1,w-1])
for i in range(h):
for j in range(w):
if grid[i][j] == "#":
gl.append([i,j])
if gl == nowl:
print("Possible")
else:
print("Impossible")
``` | instruction | 0 | 66,367 | 15 | 132,734 |
No | output | 1 | 66,367 | 15 | 132,735 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a grid of H rows and W columns. Initially, there is a stone in the top left cell. Shik is trying to move the stone to the bottom right cell. In each step, he can move the stone one cell to its left, up, right, or down (if such cell exists). It is possible that the stone visits a cell multiple times (including the bottom right and the top left cell).
You are given a matrix of characters a_{ij} (1 \leq i \leq H, 1 \leq j \leq W). After Shik completes all moving actions, a_{ij} is `#` if the stone had ever located at the i-th row and the j-th column during the process of moving. Otherwise, a_{ij} is `.`. Please determine whether it is possible that Shik only uses right and down moves in all steps.
Constraints
* 2 \leq H, W \leq 8
* a_{i,j} is either `#` or `.`.
* There exists a valid sequence of moves for Shik to generate the map a.
Input
The input is given from Standard Input in the following format:
H W
a_{11}a_{12}...a_{1W}
:
a_{H1}a_{H2}...a_{HW}
Output
If it is possible that Shik only uses right and down moves, print `Possible`. Otherwise, print `Impossible`.
Examples
Input
4 5
##...
.##..
..##.
...##
Output
Possible
Input
4 5
...
.##..
..##.
...##
Output
Possible
Input
5 3
..#
..
Output
Impossible
Input
4 5
...
.###.
.###.
...##
Output
Impossible
Submitted Solution:
```
h, w = map(int, input().split())
a = [input() for _ in range(h)]
i = 0
j = 0
prev = (0, 0)
while True:
if i == h-1 and j == w-1:
print('Possible')
exit()
if j != 0:
if (i, j-1) != prev:
if a[i][j-1] == '#':
print('Impossible')
exit()
if i != 0:
if (i-1, j) != prev:
if a[i-1][j] == '#':
print('Impossible')
exit()
if j != w-1 and a[i][j+1] == '#':
prev = (i, j)
j += 1
elif i != h-1 and a[i+1][j] == '#':
prev = (i, j)
i += 1
``` | instruction | 0 | 66,368 | 15 | 132,736 |
No | output | 1 | 66,368 | 15 | 132,737 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a grid of H rows and W columns. Initially, there is a stone in the top left cell. Shik is trying to move the stone to the bottom right cell. In each step, he can move the stone one cell to its left, up, right, or down (if such cell exists). It is possible that the stone visits a cell multiple times (including the bottom right and the top left cell).
You are given a matrix of characters a_{ij} (1 \leq i \leq H, 1 \leq j \leq W). After Shik completes all moving actions, a_{ij} is `#` if the stone had ever located at the i-th row and the j-th column during the process of moving. Otherwise, a_{ij} is `.`. Please determine whether it is possible that Shik only uses right and down moves in all steps.
Constraints
* 2 \leq H, W \leq 8
* a_{i,j} is either `#` or `.`.
* There exists a valid sequence of moves for Shik to generate the map a.
Input
The input is given from Standard Input in the following format:
H W
a_{11}a_{12}...a_{1W}
:
a_{H1}a_{H2}...a_{HW}
Output
If it is possible that Shik only uses right and down moves, print `Possible`. Otherwise, print `Impossible`.
Examples
Input
4 5
##...
.##..
..##.
...##
Output
Possible
Input
4 5
...
.##..
..##.
...##
Output
Possible
Input
5 3
..#
..
Output
Impossible
Input
4 5
...
.###.
.###.
...##
Output
Impossible
Submitted Solution:
```
H, W = map(int, input().split())
A = [['.'] + [c for c in input()] + ['.'] for _ in range(H)]
A = [['.']*(W+2)] + A + [['.']*(W+2)]
x, y = 1, 1
goal = [H, W]
def printA(A):
for r in A:
print(''.join(r))
while [x, y] != goal:
A[x][y] = 'f'
#printA(A)
#print()
if A[x-1][y]=='#' or A[x][y-1]=='#':
print('Impossible')
exit()
elif A[x+1][y]=='#' and A[x][y+1]=='#':
print('Impossible')
exit()
elif A[x+1][y]=='#':
x +=1
else:
y += 1
print('Possible')
``` | instruction | 0 | 66,369 | 15 | 132,738 |
No | output | 1 | 66,369 | 15 | 132,739 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n integers. In one move, you can jump from the position i to the position i - a_i (if 1 β€ i - a_i) or to the position i + a_i (if i + a_i β€ n).
For each position i from 1 to n you want to know the minimum the number of moves required to reach any position j such that a_j has the opposite parity from a_i (i.e. if a_i is odd then a_j has to be even and vice versa).
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of elements in a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ n), where a_i is the i-th element of a.
Output
Print n integers d_1, d_2, ..., d_n, where d_i is the minimum the number of moves required to reach any position j such that a_j has the opposite parity from a_i (i.e. if a_i is odd then a_j has to be even and vice versa) or -1 if it is impossible to reach such a position.
Example
Input
10
4 5 7 6 7 5 4 4 6 4
Output
1 1 1 2 -1 1 1 3 1 1 | instruction | 0 | 66,548 | 15 | 133,096 |
Tags: dfs and similar, graphs, shortest paths
Correct Solution:
```
from collections import deque
n = int(input())
A = [int(x) for x in input().strip().split()]
distance = [-1] * n
edge = [[] for i in range(n)]
def bfs():
queue = deque()
for v in range(n):
if distance[v] != -1:
queue.append(v)
while len(queue) > 0:
v = queue.popleft()
for e in edge[v]:
if distance[e] == -1:
queue.append(e)
distance[e] = distance[v] + 1
for i in range(n):
for m in [i - A[i], i + A[i]]:
if 0 <= m < n:
if (A[i] & 1) == (A[m] & 1):
edge[m].append(i)
else:
distance[i] = 1
bfs()
print(*distance)
``` | output | 1 | 66,548 | 15 | 133,097 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a consisting of n integers. In one move, you can jump from the position i to the position i - a_i (if 1 β€ i - a_i) or to the position i + a_i (if i + a_i β€ n).
For each position i from 1 to n you want to know the minimum the number of moves required to reach any position j such that a_j has the opposite parity from a_i (i.e. if a_i is odd then a_j has to be even and vice versa).
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of elements in a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ n), where a_i is the i-th element of a.
Output
Print n integers d_1, d_2, ..., d_n, where d_i is the minimum the number of moves required to reach any position j such that a_j has the opposite parity from a_i (i.e. if a_i is odd then a_j has to be even and vice versa) or -1 if it is impossible to reach such a position.
Example
Input
10
4 5 7 6 7 5 4 4 6 4
Output
1 1 1 2 -1 1 1 3 1 1
Submitted Solution:
```
class Graph:
def __init__(self, V):
self.V = V
self.adj_list = [[] for u in range(V)]
self.edges = []
def add_edge(self, edge):
self.edges.append(edge)
def add_neighdor(self, v1, v2):
self.adj_list[v1].append(v2)
def get_neighdor(self, v):
return self.adj_list[v]
input()
n = map(int, input().split())
n = list(n)
ans = len(n)*[-1]
queue=[]
graph = Graph(len(n))
for i in range(len(n)):
for v in (i - n[i], i + n[i]):
if(0 <= v < len(n)):
if(n[i] % 2 != n[v] % 2):
ans[i] = 1
#graph.add_edge((i, v))
#graph.add_neighdor(i, v)
queue.append(i)
else:
graph.add_edge((v, i))
graph.add_neighdor(v, i)
index = 0
while len(queue) > index:
v = queue[index]
for i in graph.get_neighdor(v):
if ans[i] == -1:
ans[i] = ans[v] + 1
queue.append(i)
index+=1
print(*ans)
``` | instruction | 0 | 66,557 | 15 | 133,114 |
Yes | output | 1 | 66,557 | 15 | 133,115 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a consisting of n integers. In one move, you can jump from the position i to the position i - a_i (if 1 β€ i - a_i) or to the position i + a_i (if i + a_i β€ n).
For each position i from 1 to n you want to know the minimum the number of moves required to reach any position j such that a_j has the opposite parity from a_i (i.e. if a_i is odd then a_j has to be even and vice versa).
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of elements in a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ n), where a_i is the i-th element of a.
Output
Print n integers d_1, d_2, ..., d_n, where d_i is the minimum the number of moves required to reach any position j such that a_j has the opposite parity from a_i (i.e. if a_i is odd then a_j has to be even and vice versa) or -1 if it is impossible to reach such a position.
Example
Input
10
4 5 7 6 7 5 4 4 6 4
Output
1 1 1 2 -1 1 1 3 1 1
Submitted Solution:
```
from collections import defaultdict
import threading
from sys import setrecursionlimit
setrecursionlimit(10**8)
def dfs(node,parent,cnt,vis,val,g):
if val[node]&1!=val[parent]&1:
# print(cnt)
return cnt
vis[node]=1
for edge in g[node]:
if vis[edge]==0:
cnt=dfs(edge,parent,cnt+1,vis,val,g)
return cnt
def main():
def f(a):
n=len(a)
a=[None]+a
g=defaultdict(list)
for i in range(1,len(a)):
if a[i]+i<=n:
g[i].append(a[i]+i)
if i-a[i]>=1:
g[i].append(i-a[i])
ans=[]
for i in range(1,n+1):
vis=[0]*(n+2)
cnt=0
cnt=dfs(i,i,cnt,vis,a,g)
if cnt==0:
ans.append(-1)
else:
ans.append(cnt)
return ans
a=input()
lst=list(map(int,input().strip().split()))
print(*f(lst))
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()
``` | instruction | 0 | 66,563 | 15 | 133,126 |
No | output | 1 | 66,563 | 15 | 133,127 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little penguin Polo has an n Γ m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.
In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.
Input
The first line contains three integers n, m and d (1 β€ n, m β€ 100, 1 β€ d β€ 104) β the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element aij (1 β€ aij β€ 104).
Output
In a single line print a single integer β the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).
Examples
Input
2 2 2
2 4
6 8
Output
4
Input
1 2 7
6 7
Output
-1 | instruction | 0 | 66,714 | 15 | 133,428 |
Tags: brute force, dp, implementation, sortings, ternary search
Correct Solution:
```
n,m,d = map(int,input().split())
a = []
ans = []
for _ in range(n):
inn = list(map(int,input().split()))
a = a+inn
a.sort()
meanSet = [a[len(a)//2],a[(len(a)//2)-1]]
for m in meanSet:
temp = 0
for v in a:
ret = abs(m - v)// d
if abs(m - v)%d !=0:
ans.append(-1)
break
temp += ret
ans.append(temp)
print(min(ans))
``` | output | 1 | 66,714 | 15 | 133,429 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little penguin Polo has an n Γ m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.
In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.
Input
The first line contains three integers n, m and d (1 β€ n, m β€ 100, 1 β€ d β€ 104) β the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element aij (1 β€ aij β€ 104).
Output
In a single line print a single integer β the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).
Examples
Input
2 2 2
2 4
6 8
Output
4
Input
1 2 7
6 7
Output
-1 | instruction | 0 | 66,715 | 15 | 133,430 |
Tags: brute force, dp, implementation, sortings, ternary search
Correct Solution:
```
a,b,d=map(int,input().split())
ans=[]
if(a==1 and b==1):
print(0)
exit()
for i in range(a):
z=list(map(int,input().split()))
ans.extend(z)
ans.sort()
arr=[]
total=0
for i in range(1,len(ans)):
arr.append(ans[i]-ans[i-1])
for i in range(len(arr)):
if(arr[i]%d!=0):
print(-1)
exit()
tr=ans[len(ans)//2]
for i in range(len(ans)):
total+=((abs(ans[i]-tr))//d)
print(total)
``` | output | 1 | 66,715 | 15 | 133,431 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little penguin Polo has an n Γ m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.
In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.
Input
The first line contains three integers n, m and d (1 β€ n, m β€ 100, 1 β€ d β€ 104) β the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element aij (1 β€ aij β€ 104).
Output
In a single line print a single integer β the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).
Examples
Input
2 2 2
2 4
6 8
Output
4
Input
1 2 7
6 7
Output
-1 | instruction | 0 | 66,716 | 15 | 133,432 |
Tags: brute force, dp, implementation, sortings, ternary search
Correct Solution:
```
import itertools
n, m, d = map(int, input().split())
a = []
for _ in range(n):
a += list(map(int, input().split()))
a.sort()
# print(a)
a = list((a[i] - a[0]) for i in range(n * m))
# print(a)
if any([a[i] % d != 0 for i in range(n * m)]):
print(-1)
else:
ps = list(itertools.accumulate(a))
ans = [(a[i] * (i + 1) - ps[i] + (ps[n * m - 1] - ps[i]) - a[i] * (n * m - i - 1)) // d for i in range(n * m)]
# print(ps)
print(min(ans))
``` | output | 1 | 66,716 | 15 | 133,433 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little penguin Polo has an n Γ m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.
In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.
Input
The first line contains three integers n, m and d (1 β€ n, m β€ 100, 1 β€ d β€ 104) β the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element aij (1 β€ aij β€ 104).
Output
In a single line print a single integer β the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).
Examples
Input
2 2 2
2 4
6 8
Output
4
Input
1 2 7
6 7
Output
-1 | instruction | 0 | 66,717 | 15 | 133,434 |
Tags: brute force, dp, implementation, sortings, ternary search
Correct Solution:
```
import sys
n, m, d = map(int, input().split())
a = []
for _ in range(n):
a += [int(x) for x in input().split()]
a.sort()
for i in range(n*m-1, -1, -1):
a[i] -= a[0]
if a[i]%d!=0:
print("-1")
break
else:
k = (n*m)//2
t = a[k]
ans = 0
for x in a:
ans += abs(x-t)//d
print(ans)
``` | output | 1 | 66,717 | 15 | 133,435 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little penguin Polo has an n Γ m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.
In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.
Input
The first line contains three integers n, m and d (1 β€ n, m β€ 100, 1 β€ d β€ 104) β the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element aij (1 β€ aij β€ 104).
Output
In a single line print a single integer β the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).
Examples
Input
2 2 2
2 4
6 8
Output
4
Input
1 2 7
6 7
Output
-1 | instruction | 0 | 66,718 | 15 | 133,436 |
Tags: brute force, dp, implementation, sortings, ternary search
Correct Solution:
```
matrix = []
m, n, d = map(int, input().split())
for i in range(m):
row = list(map(int, input().split()))
for i in range(n):
matrix.append(row[i])
matrix.sort()
f = 0
z = matrix[0]%d
for i in range(1,m*n):
if(z != matrix[i]%d):
print(-1)
f = 1
break
steps = 0
median = matrix[(n*m)//2]
for i in range(m*n):
steps += abs(median-matrix[i])//d
if(not f):
print(steps)
``` | output | 1 | 66,718 | 15 | 133,437 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little penguin Polo has an n Γ m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.
In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.
Input
The first line contains three integers n, m and d (1 β€ n, m β€ 100, 1 β€ d β€ 104) β the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element aij (1 β€ aij β€ 104).
Output
In a single line print a single integer β the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).
Examples
Input
2 2 2
2 4
6 8
Output
4
Input
1 2 7
6 7
Output
-1 | instruction | 0 | 66,719 | 15 | 133,438 |
Tags: brute force, dp, implementation, sortings, ternary search
Correct Solution:
```
"""
Author: Sagar Pandey
"""
# ---------------------------------------------------Import Libraries---------------------------------------------------
import sys
import time
import os
from math import sqrt, log, log2, ceil, log10, gcd, floor, pow, sin, cos, tan, pi, inf, factorial
from copy import copy, deepcopy
from sys import exit, stdin, stdout
from collections import Counter, defaultdict, deque
from itertools import permutations
import heapq
from bisect import bisect_left as bl
# If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
# If the element is already present in the list,
# the right most position where element has to be inserted is r
# ---------------------------------------------------Global Variables---------------------------------------------------
# sys.setrecursionlimit(100000000)
mod = 1000000007
# ---------------------------------------------------Helper Functions---------------------------------------------------
iinp = lambda: int(sys.stdin.readline())
inp = lambda: sys.stdin.readline().strip()
strl = lambda: list(inp().strip().split(" "))
intl = lambda: list(map(int, inp().split(" ")))
mint = lambda: map(int, inp().split())
flol = lambda: list(map(float, inp().split(" ")))
flush = lambda: stdout.flush()
def permute(nums):
def fun(arr, nums, cur, v):
if len(cur) == len(nums):
arr.append(cur.copy())
i = 0
while i < len(nums):
if v[i]:
i += 1
continue
else:
cur.append(nums[i])
v[i] = 1
fun(arr, nums, cur, v)
cur.pop()
v[i] = 0
i += 1
# while i<len(nums) and nums[i]==nums[i-1]:i+=1 # Uncomment for unique permutations
return arr
res = []
nums.sort()
v = [0] * len(nums)
return fun(res, nums, [], v)
def subsets(res, index, arr, cur):
res.append(cur.copy())
for i in range(index, len(arr)):
cur.append(arr[i])
subsets(res, i + 1, arr, cur)
cur.pop()
return res
def sieve(N):
root = int(sqrt(N))
primes = [1] * (N + 1)
primes[0], primes[1] = 0, 0
for i in range(2, root + 1):
if primes[i]:
for j in range(i * i, N + 1, i):
primes[j] = 0
return primes
def bs(arr, l, r, x):
if x < arr[0] or x > arr[len(arr) - 1]:
return -1
while l <= r:
mid = l + (r - l) // 2
if arr[mid] == x:
return mid
elif arr[mid] < x:
l = mid + 1
else:
r = mid - 1
return -1
def isPrime(n):
if n <= 1: return False
if n <= 3: return True
if n % 2 == 0 or n % 3 == 0: return False
p = int(sqrt(n))
for i in range(5, p + 1, 6):
if n % i == 0 or n % (i + 2) == 0:
return False
return True
# -------------------------------------------------------Functions------------------------------------------------------
def solve():
n,m,d=mint()
arr=[]
for i in range(n):
arr.extend(intl())
arr.sort()
#print(arr)
flag=0
ans=0
median=(n*m)//2
for i in range(n*m):
if abs(arr[median]-arr[i])%d!=0:
flag=1
break
else:
ans+=abs(arr[median]-arr[i])//d
print(ans) if not flag else print(-1)
# -------------------------------------------------------Main Code------------------------------------------------------
start_time = time.time()
# for _ in range(iinp()):
solve()
# print("--- %s seconds ---" % (time.time() - start_time))
``` | output | 1 | 66,719 | 15 | 133,439 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little penguin Polo has an n Γ m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.
In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.
Input
The first line contains three integers n, m and d (1 β€ n, m β€ 100, 1 β€ d β€ 104) β the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element aij (1 β€ aij β€ 104).
Output
In a single line print a single integer β the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).
Examples
Input
2 2 2
2 4
6 8
Output
4
Input
1 2 7
6 7
Output
-1 | instruction | 0 | 66,720 | 15 | 133,440 |
Tags: brute force, dp, implementation, sortings, ternary search
Correct Solution:
```
def PoloMatrix(eles,n,m,d):
x = int((n*m -1)/2)
for i in range(n*m):
y = eles[-1] - eles[i]
if y%d != 0:
print("-1")
return
ans = sum(eles[x+1:])-sum(eles[:x+1])
if n*m %2 == 1:
ans += eles[x]
print(int(ans/d))
n,m,d = [int(x) for x in input().split()]
eles = []
for i in range(n):
eles+=[int(x) for x in input().split()]
eles1 = sorted(eles)
PoloMatrix(eles1,n,m,d)
``` | output | 1 | 66,720 | 15 | 133,441 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little penguin Polo has an n Γ m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.
In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.
Input
The first line contains three integers n, m and d (1 β€ n, m β€ 100, 1 β€ d β€ 104) β the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element aij (1 β€ aij β€ 104).
Output
In a single line print a single integer β the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).
Examples
Input
2 2 2
2 4
6 8
Output
4
Input
1 2 7
6 7
Output
-1 | instruction | 0 | 66,721 | 15 | 133,442 |
Tags: brute force, dp, implementation, sortings, ternary search
Correct Solution:
```
n,m,d=map(int,input().split())
a=[]
for i in range(n):
a+=(list(map(int,input().split())))
ans=0
a.sort()
mid=a[len(a)//2]
for i in a:
x=abs(i-mid)
if x%d!=0:
print(-1)
exit()
ans+=x//d
print(ans)
``` | output | 1 | 66,721 | 15 | 133,443 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little penguin Polo has an n Γ m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.
In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.
Input
The first line contains three integers n, m and d (1 β€ n, m β€ 100, 1 β€ d β€ 104) β the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element aij (1 β€ aij β€ 104).
Output
In a single line print a single integer β the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).
Examples
Input
2 2 2
2 4
6 8
Output
4
Input
1 2 7
6 7
Output
-1
Submitted Solution:
```
# maa chudaaye duniya
n, m, d = map(int, input().split())
a = []
for i in range(n):
a.extend(map(int, input().split()))
a.sort()
n = len(a)
c = 0
j = a[n//2]
for i in a:
t = abs(i-j)
if t % d:
c = -1
break
else:
c += t // d
print(c)
``` | instruction | 0 | 66,722 | 15 | 133,444 |
Yes | output | 1 | 66,722 | 15 | 133,445 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little penguin Polo has an n Γ m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.
In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.
Input
The first line contains three integers n, m and d (1 β€ n, m β€ 100, 1 β€ d β€ 104) β the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element aij (1 β€ aij β€ 104).
Output
In a single line print a single integer β the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).
Examples
Input
2 2 2
2 4
6 8
Output
4
Input
1 2 7
6 7
Output
-1
Submitted Solution:
```
######### ## ## ## #### ##### ## # ## # ##
# # # # # # # # # # # # # # # # # # #
# # # # ### # # # # # # # # # # # #
# ##### # # # # ### # # # # # # # # #####
# # # # # # # # # # # # # # # # # #
######### # # # # ##### # ##### # ## # ## # #
"""
PPPPPPP RRRRRRR OOOO VV VV EEEEEEEEEE
PPPPPPPP RRRRRRRR OOOOOO VV VV EE
PPPPPPPPP RRRRRRRRR OOOOOOOO VV VV EE
PPPPPPPP RRRRRRRR OOOOOOOO VV VV EEEEEE
PPPPPPP RRRRRRR OOOOOOOO VV VV EEEEEEE
PP RRRR OOOOOOOO VV VV EEEEEE
PP RR RR OOOOOOOO VV VV EE
PP RR RR OOOOOO VV VV EE
PP RR RR OOOO VVVV EEEEEEEEEE
"""
"""
Perfection is achieved not when there is nothing more to add, but rather when there is nothing more to take away.
"""
import sys
input = sys.stdin.readline
read = lambda: map(int, input().split())
read_float = lambda: map(float, input().split())
# from bisect import bisect_left as lower_bound;
# from bisect import bisect_right as upper_bound;
# from math import ceil, factorial;
def ceil(x):
if x != int(x):
x = int(x) + 1
return x
def factorial(x, m):
val = 1
while x>0:
val = (val * x) % m
x -= 1
return val
def fact(x):
val = 1
while x > 0:
val *= x
x -= 1
return val
# swap_array function
def swaparr(arr, a,b):
temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
## gcd function
def gcd(a,b):
if b == 0:
return a;
return gcd(b, a % b);
## lcm function
def lcm(a, b):
return (a * b) // math.gcd(a, b)
## nCr function efficient using Binomial Cofficient
def nCr(n, k):
if k > n:
return 0
if(k > n - k):
k = n - k
res = 1
for i in range(k):
res = res * (n - i)
res = res / (i + 1)
return int(res)
## upper bound function code -- such that e in a[:i] e < x;
## prime factorization
def primefs(n):
## if n == 1 ## calculating primes
primes = {}
while(n%2 == 0 and n > 0):
primes[2] = primes.get(2, 0) + 1
n = n//2
for i in range(3, int(n**0.5)+2, 2):
while(n%i == 0 and n > 0):
primes[i] = primes.get(i, 0) + 1
n = n//i
if n > 2:
primes[n] = primes.get(n, 0) + 1
## prime factoriazation of n is stored in dictionary
## primes and can be accesed. O(sqrt n)
return primes
## MODULAR EXPONENTIATION FUNCTION
def power(x, y, p):
res = 1
x = x % p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) :
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
temp = a
a = b
b = temp
return a,b;
# find function with path compression included (recursive)
# def find(x, link):
# if link[x] == x:
# return x
# link[x] = find(link[x], link);
# return link[x];
# find function with path compression (ITERATIVE)
def find(x, link):
p = x;
while( p != link[p]):
p = link[p];
while( x != p):
nex = link[x];
link[x] = p;
x = nex;
return p;
# the union function which makes union(x,y)
# of two nodes x and y
def union(x, y, link, size):
x = find(x, link)
y = find(y, link)
if size[x] < size[y]:
x,y = swap(x,y)
if x != y:
size[x] += size[y]
link[y] = x
## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
def sieve(n):
prime = [True for i in range(n+1)]
prime[0], prime[1] = False, False
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
# Euler's Toitent Function phi
def phi(n) :
result = n
p = 2
while(p * p<= n) :
if (n % p == 0) :
while (n % p == 0) :
n = n // p
result = result * (1.0 - (1.0 / (float) (p)))
p = p + 1
if (n > 1) :
result = result * (1.0 - (1.0 / (float)(n)))
return (int)(result)
def is_prime(n):
if n == 0:
return False
if n == 1:
return True
for i in range(2, int(n ** (1 / 2)) + 1):
if not n % i:
return False
return True
def next_prime(n, primes):
while primes[n] != True:
n += 1
return n
#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e5 + 5)
def spf_sieve():
spf[1] = 1;
for i in range(2, MAXN):
spf[i] = i;
for i in range(4, MAXN, 2):
spf[i] = 2;
for i in range(3, ceil(MAXN ** 0.5), 2):
if spf[i] == i:
for j in range(i*i, MAXN, i):
if spf[j] == j:
spf[j] = i;
## function for storing smallest prime factors (spf) in the array
################## un-comment below 2 lines when using factorization #################
spf = [0 for i in range(MAXN)]
# spf_sieve();
def factoriazation(x):
res = []
for i in range(2, int(x ** 0.5) + 1):
while x % i == 0:
res.append(i)
x //= i
if x != 1:
res.append(x)
return res
## this function is useful for multiple queries only, o/w use
## primefs function above. complexity O(log n)
def factors(n):
res = []
for i in range(1, int(n ** 0.5) + 1):
if n % i == 0:
res.append(i)
res.append(n // i)
return list(set(res))
## taking integer array input
def int_array():
return list(map(int, input().strip().split()));
def float_array():
return list(map(float, input().strip().split()));
## taking string array input
def str_array():
return input().strip().split();
def binary_search(low, high, w, h, n):
while low < high:
mid = low + (high - low) // 2
# print(low, mid, high)
if check(mid, w, h, n):
low = mid + 1
else:
high = mid
return low
## for checking any conditions
def check(l, ps, n, t):
for i in range(n - l + 1):
# print(i, l)
# print(a[i:i + l])
if ps[i + l] - ps[i] <= t:
return True
return False
#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');
################### ---------------- TEMPLATE ENDS HERE ---------------- ###################
from itertools import permutations
import math
import bisect as bis
import random
import sys
def solve():
n, m, d = read()
penguin_matrix = [list(read()) for x in range(n)]
new_mat = []
for i in penguin_matrix:
for j in i:
new_mat.append(j)
new_mat.sort()
z = new_mat[0] % d
for x in new_mat:
if x % d != z:
print(-1)
return
# print(new_mat)
comp = new_mat[n * m // 2]
# print(comp)
summ = 0
for x in new_mat:
diff = abs(comp - x)
summ += diff // d
print(summ)
if __name__ == '__main__':
for _ in range(1):
solve()
# fin_time = datetime.now()
# print("Execution time (for loop): ", (fin_time-init_time))
``` | instruction | 0 | 66,723 | 15 | 133,446 |
Yes | output | 1 | 66,723 | 15 | 133,447 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little penguin Polo has an n Γ m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.
In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.
Input
The first line contains three integers n, m and d (1 β€ n, m β€ 100, 1 β€ d β€ 104) β the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element aij (1 β€ aij β€ 104).
Output
In a single line print a single integer β the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).
Examples
Input
2 2 2
2 4
6 8
Output
4
Input
1 2 7
6 7
Output
-1
Submitted Solution:
```
import sys
n,m,d=map(int,input().split())
mat=list()
for i in range(0,n):
x=list(map(int,input().split()))
mat.append(x)
flat=list()
for i in mat:
for j in i:
flat.append(j)
flat.sort()
rem=flat[0]%d
for i in flat:
remd=i%d
if(remd!=rem):
print('-1')
sys.exit()
mid=flat[len(flat)//2]
count=0
for i in flat:
diff=abs(i-mid)
count+=diff/d
print(int(count))
``` | instruction | 0 | 66,724 | 15 | 133,448 |
Yes | output | 1 | 66,724 | 15 | 133,449 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little penguin Polo has an n Γ m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.
In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.
Input
The first line contains three integers n, m and d (1 β€ n, m β€ 100, 1 β€ d β€ 104) β the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element aij (1 β€ aij β€ 104).
Output
In a single line print a single integer β the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).
Examples
Input
2 2 2
2 4
6 8
Output
4
Input
1 2 7
6 7
Output
-1
Submitted Solution:
```
from statistics import median
n, m, d = map(int, input().split())
numbers = []
for _ in range(n):
row = list(map(int, input().split()))
numbers += row
numbers.sort()
total = 0
med = median(numbers)
for i in numbers:
to_add = (med - i) / d
total += abs(to_add)
print(int(total) if int(total) == total else -1)
``` | instruction | 0 | 66,725 | 15 | 133,450 |
Yes | output | 1 | 66,725 | 15 | 133,451 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little penguin Polo has an n Γ m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.
In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.
Input
The first line contains three integers n, m and d (1 β€ n, m β€ 100, 1 β€ d β€ 104) β the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element aij (1 β€ aij β€ 104).
Output
In a single line print a single integer β the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).
Examples
Input
2 2 2
2 4
6 8
Output
4
Input
1 2 7
6 7
Output
-1
Submitted Solution:
```
#B. Polo the Penguin and Matrix
n,m,d = map(int,input().split())
a = []
b = []
for i in range(n):
tmp = list(map(int,input().split()))
a.append(tmp)
b = b + tmp
flag = True
x = a[0][0]%d
for i in range(n):
for j in range(m):
if a[i][j]%d!=x:
flag = False
break
b.sort()
print(b)
k = len(b)
k = (k//2)
s = 0
for i in b:
s += abs(i-b[k])
s /= d
if flag:
print(int(s))
else:
print(-1)
``` | instruction | 0 | 66,726 | 15 | 133,452 |
No | output | 1 | 66,726 | 15 | 133,453 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little penguin Polo has an n Γ m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.
In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.
Input
The first line contains three integers n, m and d (1 β€ n, m β€ 100, 1 β€ d β€ 104) β the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element aij (1 β€ aij β€ 104).
Output
In a single line print a single integer β the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).
Examples
Input
2 2 2
2 4
6 8
Output
4
Input
1 2 7
6 7
Output
-1
Submitted Solution:
```
'''input
2 2 2
2 4
6 8
'''
from sys import stdin,stdout
I = lambda: stdin.readline().strip()
read = lambda: map(int,stdin.readline().split())
n,m,d = read()
arr = []
for i in range(n):
arr.extend(list(read()))
base = arr[0]
for i in arr:
if (i-base)%d:
print(-1)
quit()
arr.sort()
s = n*m
Sum = 0
dev1 = dev2 = 0
if s%2:
median = s//2
for i in arr:
Sum+=abs(i-median)
else:
m1,m2 = (s//2)-1,s//2
Sum2 = 0
for i in arr:
Sum+=abs(i-m1)
Sum2+=abs(i-m2)
Sum = min(Sum,Sum2)
print(Sum//d)
``` | instruction | 0 | 66,727 | 15 | 133,454 |
No | output | 1 | 66,727 | 15 | 133,455 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little penguin Polo has an n Γ m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.
In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.
Input
The first line contains three integers n, m and d (1 β€ n, m β€ 100, 1 β€ d β€ 104) β the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element aij (1 β€ aij β€ 104).
Output
In a single line print a single integer β the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).
Examples
Input
2 2 2
2 4
6 8
Output
4
Input
1 2 7
6 7
Output
-1
Submitted Solution:
```
def fastio():
import sys
from io import StringIO
from atexit import register
global input
sys.stdin = StringIO(sys.stdin.read())
input = lambda : sys.stdin.readline().rstrip('\r\n')
sys.stdout = StringIO()
register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()
MOD = 10**9 + 7
I = lambda:list(map(int,input().split()))
n, m, d = I()
a = []
mod = -1
for i in range(n):
l = I()
if mod == -1:
mod = l[0]%d
for j in range(m):
if l[j]%d != mod:
print(-1)
exit()
l[j] -= mod
a.append(l)
s = 0
for i in a:
s += sum(i)
p = [s//(n*m), s//(n*m) + d, s//(n*m) - d]
p = [i - i%d for i in p]
ans = MOD
num = p[0]
for x in p:
cost = 0
for i in range(n):
for j in range(m):
cost += abs(x - a[i][j])//d
ans = min(ans, cost)
# print(cost, x)
print(ans)
``` | instruction | 0 | 66,728 | 15 | 133,456 |
No | output | 1 | 66,728 | 15 | 133,457 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little penguin Polo has an n Γ m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.
In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.
Input
The first line contains three integers n, m and d (1 β€ n, m β€ 100, 1 β€ d β€ 104) β the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element aij (1 β€ aij β€ 104).
Output
In a single line print a single integer β the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).
Examples
Input
2 2 2
2 4
6 8
Output
4
Input
1 2 7
6 7
Output
-1
Submitted Solution:
```
n, m, d = [int(i) for i in input().split()]
M = []
for i in range(n):
M += [int(j) for j in input().split()]
mod = M[0] % d
r = 1
for i in M:
if i % d != mod:
r = 0
print(-1)
break
if r:
M.sort()
medium = M[n * m // 2 - 1]
count = 0
for i in M:
count += abs(medium - i)
print(count/d)
``` | instruction | 0 | 66,729 | 15 | 133,458 |
No | output | 1 | 66,729 | 15 | 133,459 |
Provide a correct Python 3 solution for this coding contest problem.
We have a grid of squares with N rows and M columns. Let (i, j) denote the square at the i-th row from the top and j-th column from the left. We will choose K of the squares and put a piece on each of them.
If we place the K pieces on squares (x_1, y_1), (x_2, y_2), ..., and (x_K, y_K), the cost of this arrangement is computed as:
\sum_{i=1}^{K-1} \sum_{j=i+1}^K (|x_i - x_j| + |y_i - y_j|)
Find the sum of the costs of all possible arrangements of the pieces. Since this value can be tremendous, print it modulo 10^9+7.
We consider two arrangements of the pieces different if and only if there is a square that contains a piece in one of the arrangements but not in the other.
Constraints
* 2 \leq N \times M \leq 2 \times 10^5
* 2 \leq K \leq N \times M
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M K
Output
Print the sum of the costs of all possible arrangements of the pieces, modulo 10^9+7.
Examples
Input
2 2 2
Output
8
Input
4 5 4
Output
87210
Input
100 100 5000
Output
817260251 | instruction | 0 | 67,037 | 15 | 134,074 |
"Correct Solution:
```
def comb(n, k):
x, y = 1, 1
k = min(k, n-k)
for i in range(k):
x *= n - i
x %= MOD
y *= i + 1
y %= MOD
return x*pow(y, MOD-2, MOD) % MOD
def modinv(a):
b=MOD
(x, lastx) = (0, 1)
(y, lasty) = (1, 0)
while b != 0:
q = a // b
(a, b) = (b, a % b)
(x, lastx) = (lastx - q * x, x)
(y, lasty) = (lasty - q * y, y)
return lastx%MOD
MOD=10**9+7
N,M,K=map(int,input().split())
x=0
for i in range(1,N):
x=x+i*(N-i)
x=(x*M*M)%MOD
y=0
for j in range(1,M):
y=y+j*(M-j)
y=(y*N*N)%MOD
ans=comb(N*M-2,K-2)*(x+y)%MOD
print(ans)
``` | output | 1 | 67,037 | 15 | 134,075 |
Provide a correct Python 3 solution for this coding contest problem.
We have a grid of squares with N rows and M columns. Let (i, j) denote the square at the i-th row from the top and j-th column from the left. We will choose K of the squares and put a piece on each of them.
If we place the K pieces on squares (x_1, y_1), (x_2, y_2), ..., and (x_K, y_K), the cost of this arrangement is computed as:
\sum_{i=1}^{K-1} \sum_{j=i+1}^K (|x_i - x_j| + |y_i - y_j|)
Find the sum of the costs of all possible arrangements of the pieces. Since this value can be tremendous, print it modulo 10^9+7.
We consider two arrangements of the pieces different if and only if there is a square that contains a piece in one of the arrangements but not in the other.
Constraints
* 2 \leq N \times M \leq 2 \times 10^5
* 2 \leq K \leq N \times M
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M K
Output
Print the sum of the costs of all possible arrangements of the pieces, modulo 10^9+7.
Examples
Input
2 2 2
Output
8
Input
4 5 4
Output
87210
Input
100 100 5000
Output
817260251 | instruction | 0 | 67,038 | 15 | 134,076 |
"Correct Solution:
```
n, m, k = map(int, input().split())
mod = 10**9+7
N = 2*10**5+50
fac = [1]*(N+1)
finv = [1]*(N+1)
for i in range(N):
fac[i+1] = fac[i] * (i+1) % mod
finv[-1] = pow(fac[-1], mod-2, mod)
for i in reversed(range(N)):
finv[i] = finv[i+1] * (i+1) % mod
def cmb1(n, r, mod):
if r <0 or r > n:
return 0
r = min(r, n-r)
return fac[n] * finv[r] * finv[n-r] % mod
ans = 0
for i in range(n*m):
x, y = divmod(i, m)
# x
ans += x*m*cmb1(n*m-2, k-2, mod)*x
ans -= (n-1-x)*m*cmb1(n*m-2, k-2, mod)*x
# y
ans += y*n*cmb1(n*m-2, k-2, mod)*y
ans -= (m-1-y)*n*cmb1(n*m-2, k-2, mod)*y
ans %= mod
print(ans)
``` | output | 1 | 67,038 | 15 | 134,077 |
Provide a correct Python 3 solution for this coding contest problem.
We have a grid of squares with N rows and M columns. Let (i, j) denote the square at the i-th row from the top and j-th column from the left. We will choose K of the squares and put a piece on each of them.
If we place the K pieces on squares (x_1, y_1), (x_2, y_2), ..., and (x_K, y_K), the cost of this arrangement is computed as:
\sum_{i=1}^{K-1} \sum_{j=i+1}^K (|x_i - x_j| + |y_i - y_j|)
Find the sum of the costs of all possible arrangements of the pieces. Since this value can be tremendous, print it modulo 10^9+7.
We consider two arrangements of the pieces different if and only if there is a square that contains a piece in one of the arrangements but not in the other.
Constraints
* 2 \leq N \times M \leq 2 \times 10^5
* 2 \leq K \leq N \times M
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M K
Output
Print the sum of the costs of all possible arrangements of the pieces, modulo 10^9+7.
Examples
Input
2 2 2
Output
8
Input
4 5 4
Output
87210
Input
100 100 5000
Output
817260251 | instruction | 0 | 67,039 | 15 | 134,078 |
"Correct Solution:
```
MOD = 10**9 + 7
N, M, K = map(int, input().split())
def getComb(n, k, MOD):
if n < k:
return 0
if n-k < k:
k = n-k
comb = 1
for x in range(n-k+1, n+1):
comb = (comb * x) % MOD
d = 1
for x in range(1, k+1):
d = (d * x) % MOD
comb *= pow(d, MOD-2, MOD)
return comb % MOD
comb = getComb(N*M-2, K-2, MOD)
ans = 0
for i in range(N):
ans += i*(N-i)*M*M
ans %= MOD
for j in range(M):
ans += j*(M-j)*N*N
ans %= MOD
ans *= comb
ans %= MOD
print(ans)
``` | output | 1 | 67,039 | 15 | 134,079 |
Provide a correct Python 3 solution for this coding contest problem.
For a dynamic list $L$ of integers, perform a sequence of the following operations. $L$ has a special element called END at the end of the list and an element of $L$ is indicated by a cursor.
* insert($x$): Insert $x$ before the element indicated by the cursor. After this operation, the cursor points the inserted element.
* move($d$): Move the cursor to the end by $d$, if $d$ is positive. Move the cursor to the front by $d$, if $d$ is negative.
* erase(): Delete the element indicated by the cursor. After this operation, the cursor points the element next to the deleted element. In case there is no such element, the cursor should point END.
In the initial state, $L$ is empty and the cursor points END.
Constraints
* $1 \leq q \leq 500,000$
* The cursor indicates an element of $L$ or END during the operations
* Erase operation will not given when the cursor points END
* $-1,000,000,000 \leq x \leq 1,000,000,000$
* Moving distance of the cursor ($\sum{|d|}$) does not exceed 1,000,000
* $L$ is not empty after performing all operations
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $x$
or
1 $d$
or
2
where the first digits 0, 1 and 2 represent insert, move and erase operations respectively.
Output
Print all elements of the list in order after performing given operations. Print an element in a line.
Example
Input
5
0 1
0 2
0 3
1 1
2
Output
3
1 | instruction | 0 | 67,240 | 15 | 134,480 |
"Correct Solution:
```
import collections
class CursorList():
def __init__(self):
self.vector = collections.deque()
self.cursor = 0
def insert(self, x):
self.vector.appendleft(x)
return self
def move(self, d):
self.vector.rotate(-d)
self.cursor += d
return self
def erase(self):
self.vector.popleft()
return self
num_queue = int((input()))
L = CursorList()
for i in range(0, num_queue):
queue = tuple(map(int, input().split(' ')))
if queue[0] == 0:
L.insert(queue[1])
elif queue[0] == 1:
L.move(queue[1])
elif queue[0] == 2:
L.erase()
L.vector.rotate(L.cursor)
print('\n'.join(map(str, L.vector)))
``` | output | 1 | 67,240 | 15 | 134,481 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number.
Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner β a cell with coordinates (1,1). But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely β on the upper side of the field (that is, in any cell that is in the row with number 10^9).
Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells:
* Vertical. Each of these is defined by one number x. Such spells create an infinite blocking line between the columns x and x+1.
* Horizontal. Each of these is defined by three numbers x_1, x_2, y. Such spells create a blocking segment that passes through the top side of the cells, which are in the row y and in columns from x_1 to x_2 inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.
<image> An example of a chessboard.
Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell (r_0,c_0) into the cell (r_1,c_1) only under the condition that r_1 = r_0 or c_1 = c_0 and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).
Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!
Input
The first line contains two integers n and m (0 β€ n,m β€ 10^5) β the number of vertical and horizontal spells.
Each of the following n lines contains one integer x (1 β€ x < 10^9) β the description of the vertical spell. It will create a blocking line between the columns of x and x+1.
Each of the following m lines contains three integers x_1, x_2 and y (1 β€ x_{1} β€ x_{2} β€ 10^9, 1 β€ y < 10^9) β the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number y, in columns from x_1 to x_2 inclusive.
It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.
Output
In a single line print one integer β the minimum number of spells the rook needs to remove so it can get from the cell (1,1) to at least one cell in the row with the number 10^9
Examples
Input
2 3
6
8
1 5 6
1 9 4
2 4 2
Output
1
Input
1 3
4
1 5 3
1 9 4
4 6 6
Output
1
Input
0 2
1 1000000000 4
1 1000000000 2
Output
2
Input
0 0
Output
0
Input
2 3
4
6
1 4 3
1 5 2
1 6 5
Output
2
Note
In the first sample, in order for the rook return home, it is enough to remove the second horizontal spell.
<image> Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home.
In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell.
<image> Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home.
In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them.
<image> Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home.
In the fourth sample, we have no spells, which means that we do not need to remove anything.
In the fifth example, we can remove the first vertical and third horizontal spells.
<image> Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home. | instruction | 0 | 67,251 | 15 | 134,502 |
Tags: binary search, two pointers
Correct Solution:
```
import sys
import math
MAXNUM = math.inf
MINNUM = -1 * math.inf
ASCIILOWER = 97
ASCIIUPPER = 65
MAXRIGHT = 10 ** 9
def getInt():
return int(sys.stdin.readline().rstrip())
def getInts():
return map(int, sys.stdin.readline().rstrip().split(" "))
def getString():
return sys.stdin.readline().rstrip()
def printOutput(ans):
sys.stdout.write()
pass
def solve(v, h):
vertdict = []
h.sort()
v.sort()
hcur = 0
for vert in v:
while hcur < len(h) and h[hcur][1] < vert:
hcur += 1
vertdict.append(len(h) - hcur)
minmoves = vertdict[0]
for i in range(len(vertdict)):
minmoves = min(minmoves, vertdict[i] + i)
return minmoves
def readinput():
v, h = getInts()
vert = []
horiz = []
for _ in range(v):
vert.append(getInt())
vert.append(MAXRIGHT)
for _ in range(h):
x1, x2, y = getInts()
if x1 == 1:
horiz.append((x1, x2, y))
print(solve(vert, horiz))
readinput()
``` | output | 1 | 67,251 | 15 | 134,503 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number.
Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner β a cell with coordinates (1,1). But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely β on the upper side of the field (that is, in any cell that is in the row with number 10^9).
Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells:
* Vertical. Each of these is defined by one number x. Such spells create an infinite blocking line between the columns x and x+1.
* Horizontal. Each of these is defined by three numbers x_1, x_2, y. Such spells create a blocking segment that passes through the top side of the cells, which are in the row y and in columns from x_1 to x_2 inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.
<image> An example of a chessboard.
Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell (r_0,c_0) into the cell (r_1,c_1) only under the condition that r_1 = r_0 or c_1 = c_0 and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).
Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!
Input
The first line contains two integers n and m (0 β€ n,m β€ 10^5) β the number of vertical and horizontal spells.
Each of the following n lines contains one integer x (1 β€ x < 10^9) β the description of the vertical spell. It will create a blocking line between the columns of x and x+1.
Each of the following m lines contains three integers x_1, x_2 and y (1 β€ x_{1} β€ x_{2} β€ 10^9, 1 β€ y < 10^9) β the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number y, in columns from x_1 to x_2 inclusive.
It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.
Output
In a single line print one integer β the minimum number of spells the rook needs to remove so it can get from the cell (1,1) to at least one cell in the row with the number 10^9
Examples
Input
2 3
6
8
1 5 6
1 9 4
2 4 2
Output
1
Input
1 3
4
1 5 3
1 9 4
4 6 6
Output
1
Input
0 2
1 1000000000 4
1 1000000000 2
Output
2
Input
0 0
Output
0
Input
2 3
4
6
1 4 3
1 5 2
1 6 5
Output
2
Note
In the first sample, in order for the rook return home, it is enough to remove the second horizontal spell.
<image> Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home.
In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell.
<image> Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home.
In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them.
<image> Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home.
In the fourth sample, we have no spells, which means that we do not need to remove anything.
In the fifth example, we can remove the first vertical and third horizontal spells.
<image> Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home. | instruction | 0 | 67,252 | 15 | 134,504 |
Tags: binary search, two pointers
Correct Solution:
```
from collections import namedtuple
import sys
HS = namedtuple('HS', 'x1 x2 y')
n, m = [int(w) for w in input().split()]
vs = [int(input()) for _ in range(n)]
hs = [HS(*[int(w) for w in input().split()]) for _ in range(m)]
vs.sort()
hr = len([s for s in hs if s.x1 == 1 and s.x2 == 10**9])
hs = [s.x2 for s in hs if s.x1 == 1 and s.x2 < 10**9]
hs.sort()
r = hc = len(hs)
hi = vi = 0
for hi in range(hc):
while vi < n and hs[hi] >= vs[vi]:
vi += 1
c = (hc - hi - 1) + vi
if c < r:
r = c
print(r + hr)
``` | output | 1 | 67,252 | 15 | 134,505 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number.
Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner β a cell with coordinates (1,1). But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely β on the upper side of the field (that is, in any cell that is in the row with number 10^9).
Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells:
* Vertical. Each of these is defined by one number x. Such spells create an infinite blocking line between the columns x and x+1.
* Horizontal. Each of these is defined by three numbers x_1, x_2, y. Such spells create a blocking segment that passes through the top side of the cells, which are in the row y and in columns from x_1 to x_2 inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.
<image> An example of a chessboard.
Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell (r_0,c_0) into the cell (r_1,c_1) only under the condition that r_1 = r_0 or c_1 = c_0 and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).
Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!
Input
The first line contains two integers n and m (0 β€ n,m β€ 10^5) β the number of vertical and horizontal spells.
Each of the following n lines contains one integer x (1 β€ x < 10^9) β the description of the vertical spell. It will create a blocking line between the columns of x and x+1.
Each of the following m lines contains three integers x_1, x_2 and y (1 β€ x_{1} β€ x_{2} β€ 10^9, 1 β€ y < 10^9) β the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number y, in columns from x_1 to x_2 inclusive.
It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.
Output
In a single line print one integer β the minimum number of spells the rook needs to remove so it can get from the cell (1,1) to at least one cell in the row with the number 10^9
Examples
Input
2 3
6
8
1 5 6
1 9 4
2 4 2
Output
1
Input
1 3
4
1 5 3
1 9 4
4 6 6
Output
1
Input
0 2
1 1000000000 4
1 1000000000 2
Output
2
Input
0 0
Output
0
Input
2 3
4
6
1 4 3
1 5 2
1 6 5
Output
2
Note
In the first sample, in order for the rook return home, it is enough to remove the second horizontal spell.
<image> Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home.
In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell.
<image> Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home.
In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them.
<image> Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home.
In the fourth sample, we have no spells, which means that we do not need to remove anything.
In the fifth example, we can remove the first vertical and third horizontal spells.
<image> Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home. | instruction | 0 | 67,253 | 15 | 134,506 |
Tags: binary search, two pointers
Correct Solution:
```
n,m=map(int, input().split())
cols=[]
for i in range(n):
cols.append(int(input()))
rows=[]
for i in range(m):
k=list(map(int, input().split()))
if k[0]==1:
rows.append(k[1])
ans=n+m
cols.sort()
rows.sort()
cols.append(int(1e9))
j=0
rem=0
# print(rows, cols)
for i in cols:
while j<len(rows) and rows[j]<i:
j+=1
ans=min(ans, len(rows)-j+rem)
rem+=1
print(ans)
#for i in d:
``` | output | 1 | 67,253 | 15 | 134,507 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number.
Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner β a cell with coordinates (1,1). But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely β on the upper side of the field (that is, in any cell that is in the row with number 10^9).
Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells:
* Vertical. Each of these is defined by one number x. Such spells create an infinite blocking line between the columns x and x+1.
* Horizontal. Each of these is defined by three numbers x_1, x_2, y. Such spells create a blocking segment that passes through the top side of the cells, which are in the row y and in columns from x_1 to x_2 inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.
<image> An example of a chessboard.
Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell (r_0,c_0) into the cell (r_1,c_1) only under the condition that r_1 = r_0 or c_1 = c_0 and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).
Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!
Input
The first line contains two integers n and m (0 β€ n,m β€ 10^5) β the number of vertical and horizontal spells.
Each of the following n lines contains one integer x (1 β€ x < 10^9) β the description of the vertical spell. It will create a blocking line between the columns of x and x+1.
Each of the following m lines contains three integers x_1, x_2 and y (1 β€ x_{1} β€ x_{2} β€ 10^9, 1 β€ y < 10^9) β the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number y, in columns from x_1 to x_2 inclusive.
It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.
Output
In a single line print one integer β the minimum number of spells the rook needs to remove so it can get from the cell (1,1) to at least one cell in the row with the number 10^9
Examples
Input
2 3
6
8
1 5 6
1 9 4
2 4 2
Output
1
Input
1 3
4
1 5 3
1 9 4
4 6 6
Output
1
Input
0 2
1 1000000000 4
1 1000000000 2
Output
2
Input
0 0
Output
0
Input
2 3
4
6
1 4 3
1 5 2
1 6 5
Output
2
Note
In the first sample, in order for the rook return home, it is enough to remove the second horizontal spell.
<image> Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home.
In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell.
<image> Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home.
In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them.
<image> Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home.
In the fourth sample, we have no spells, which means that we do not need to remove anything.
In the fifth example, we can remove the first vertical and third horizontal spells.
<image> Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home. | instruction | 0 | 67,254 | 15 | 134,508 |
Tags: binary search, two pointers
Correct Solution:
```
from bisect import bisect_left
def readint():
return int(input())
def readline():
return [int(c) for c in input().split()]
# similar to 45311982
def main():
MAX = 10**9
n, m = readline()
v = sorted([readint() for _ in range(n)])
h = []
for _ in range(m):
x1, x2, _ = readline()
if x1 == 1:
h.append(x2)
h.sort()
lh = len(h)
if lh == 0:
print(0)
elif n == 0:
print(lh - bisect_left(h, MAX))
else:
mn = n + lh - bisect_left(h, MAX)
for i in range(n):
mn = min(mn, lh - bisect_left(h, v[i]) + i)
print(mn)
if __name__ == '__main__':
main()
``` | output | 1 | 67,254 | 15 | 134,509 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number.
Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner β a cell with coordinates (1,1). But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely β on the upper side of the field (that is, in any cell that is in the row with number 10^9).
Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells:
* Vertical. Each of these is defined by one number x. Such spells create an infinite blocking line between the columns x and x+1.
* Horizontal. Each of these is defined by three numbers x_1, x_2, y. Such spells create a blocking segment that passes through the top side of the cells, which are in the row y and in columns from x_1 to x_2 inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.
<image> An example of a chessboard.
Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell (r_0,c_0) into the cell (r_1,c_1) only under the condition that r_1 = r_0 or c_1 = c_0 and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).
Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!
Input
The first line contains two integers n and m (0 β€ n,m β€ 10^5) β the number of vertical and horizontal spells.
Each of the following n lines contains one integer x (1 β€ x < 10^9) β the description of the vertical spell. It will create a blocking line between the columns of x and x+1.
Each of the following m lines contains three integers x_1, x_2 and y (1 β€ x_{1} β€ x_{2} β€ 10^9, 1 β€ y < 10^9) β the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number y, in columns from x_1 to x_2 inclusive.
It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.
Output
In a single line print one integer β the minimum number of spells the rook needs to remove so it can get from the cell (1,1) to at least one cell in the row with the number 10^9
Examples
Input
2 3
6
8
1 5 6
1 9 4
2 4 2
Output
1
Input
1 3
4
1 5 3
1 9 4
4 6 6
Output
1
Input
0 2
1 1000000000 4
1 1000000000 2
Output
2
Input
0 0
Output
0
Input
2 3
4
6
1 4 3
1 5 2
1 6 5
Output
2
Note
In the first sample, in order for the rook return home, it is enough to remove the second horizontal spell.
<image> Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home.
In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell.
<image> Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home.
In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them.
<image> Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home.
In the fourth sample, we have no spells, which means that we do not need to remove anything.
In the fifth example, we can remove the first vertical and third horizontal spells.
<image> Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home. | instruction | 0 | 67,255 | 15 | 134,510 |
Tags: binary search, two pointers
Correct Solution:
```
from bisect import bisect
n, m = map(int, input().split())
vv = sorted([int(input()) for _ in range(n)])
hh = [0] * n
rr = 0
for _ in range(m):
one, x, _ = map(int, input().split())
if one == 1:
if x == 1000000000:
rr += 1
else:
ind = bisect(vv, x)
if ind:
hh[ind-1] += 1
r = n
s = 0
#print(*vv)
#print(*hh)
for i, h in reversed(list(enumerate(hh))):
s += h
#print("~", r, s)
r = min(r, s+i)
print(r+rr)
``` | output | 1 | 67,255 | 15 | 134,511 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number.
Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner β a cell with coordinates (1,1). But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely β on the upper side of the field (that is, in any cell that is in the row with number 10^9).
Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells:
* Vertical. Each of these is defined by one number x. Such spells create an infinite blocking line between the columns x and x+1.
* Horizontal. Each of these is defined by three numbers x_1, x_2, y. Such spells create a blocking segment that passes through the top side of the cells, which are in the row y and in columns from x_1 to x_2 inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.
<image> An example of a chessboard.
Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell (r_0,c_0) into the cell (r_1,c_1) only under the condition that r_1 = r_0 or c_1 = c_0 and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).
Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!
Input
The first line contains two integers n and m (0 β€ n,m β€ 10^5) β the number of vertical and horizontal spells.
Each of the following n lines contains one integer x (1 β€ x < 10^9) β the description of the vertical spell. It will create a blocking line between the columns of x and x+1.
Each of the following m lines contains three integers x_1, x_2 and y (1 β€ x_{1} β€ x_{2} β€ 10^9, 1 β€ y < 10^9) β the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number y, in columns from x_1 to x_2 inclusive.
It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.
Output
In a single line print one integer β the minimum number of spells the rook needs to remove so it can get from the cell (1,1) to at least one cell in the row with the number 10^9
Examples
Input
2 3
6
8
1 5 6
1 9 4
2 4 2
Output
1
Input
1 3
4
1 5 3
1 9 4
4 6 6
Output
1
Input
0 2
1 1000000000 4
1 1000000000 2
Output
2
Input
0 0
Output
0
Input
2 3
4
6
1 4 3
1 5 2
1 6 5
Output
2
Note
In the first sample, in order for the rook return home, it is enough to remove the second horizontal spell.
<image> Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home.
In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell.
<image> Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home.
In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them.
<image> Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home.
In the fourth sample, we have no spells, which means that we do not need to remove anything.
In the fifth example, we can remove the first vertical and third horizontal spells.
<image> Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home. | instruction | 0 | 67,256 | 15 | 134,512 |
Tags: binary search, two pointers
Correct Solution:
```
n,m = map(int,input().split())
x = [0]*(n+1)
for i in range(n):
x[i] = int(input())
x[n] = 1000000000
vert = []
for i in range(m):
x1,x2,y = map(int,input().split())
if x1 == 1:
vert.append(x2)
vert.sort()
x.sort()
cur = 0
minicount = n+m
k = len(vert)
for i in range(n+1):
while cur < k:
if x[i] <= vert[cur]:
break
cur += 1
minicount = min(minicount,k-cur+i)
print(minicount)
``` | output | 1 | 67,256 | 15 | 134,513 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number.
Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner β a cell with coordinates (1,1). But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely β on the upper side of the field (that is, in any cell that is in the row with number 10^9).
Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells:
* Vertical. Each of these is defined by one number x. Such spells create an infinite blocking line between the columns x and x+1.
* Horizontal. Each of these is defined by three numbers x_1, x_2, y. Such spells create a blocking segment that passes through the top side of the cells, which are in the row y and in columns from x_1 to x_2 inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.
<image> An example of a chessboard.
Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell (r_0,c_0) into the cell (r_1,c_1) only under the condition that r_1 = r_0 or c_1 = c_0 and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).
Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!
Input
The first line contains two integers n and m (0 β€ n,m β€ 10^5) β the number of vertical and horizontal spells.
Each of the following n lines contains one integer x (1 β€ x < 10^9) β the description of the vertical spell. It will create a blocking line between the columns of x and x+1.
Each of the following m lines contains three integers x_1, x_2 and y (1 β€ x_{1} β€ x_{2} β€ 10^9, 1 β€ y < 10^9) β the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number y, in columns from x_1 to x_2 inclusive.
It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.
Output
In a single line print one integer β the minimum number of spells the rook needs to remove so it can get from the cell (1,1) to at least one cell in the row with the number 10^9
Examples
Input
2 3
6
8
1 5 6
1 9 4
2 4 2
Output
1
Input
1 3
4
1 5 3
1 9 4
4 6 6
Output
1
Input
0 2
1 1000000000 4
1 1000000000 2
Output
2
Input
0 0
Output
0
Input
2 3
4
6
1 4 3
1 5 2
1 6 5
Output
2
Note
In the first sample, in order for the rook return home, it is enough to remove the second horizontal spell.
<image> Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home.
In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell.
<image> Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home.
In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them.
<image> Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home.
In the fourth sample, we have no spells, which means that we do not need to remove anything.
In the fifth example, we can remove the first vertical and third horizontal spells.
<image> Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home. | instruction | 0 | 67,257 | 15 | 134,514 |
Tags: binary search, two pointers
Correct Solution:
```
#n=int(input())
n,m=map(int,input().split())
vert=[]
for i in range(n):
v=int(input())
vert.append(v)
horz=[]
for i in range(m):
x1,x2,y=map(int,input().split())
if x1==1:
horz.append(x2)
vert.sort()
horz.sort()
vert.append(1000000000)
def next(k,a,x):
while k<len(a) and a[k]<x:
k+=1
return k
num=next(0,horz,vert[0])
ans=len(horz)-num
for i in range(1,len(vert)):
num2=next(num,horz,vert[i])
t=i+len(horz)-num2
if t<ans: ans=t
num=num2
print(ans)
``` | output | 1 | 67,257 | 15 | 134,515 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number.
Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner β a cell with coordinates (1,1). But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely β on the upper side of the field (that is, in any cell that is in the row with number 10^9).
Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells:
* Vertical. Each of these is defined by one number x. Such spells create an infinite blocking line between the columns x and x+1.
* Horizontal. Each of these is defined by three numbers x_1, x_2, y. Such spells create a blocking segment that passes through the top side of the cells, which are in the row y and in columns from x_1 to x_2 inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.
<image> An example of a chessboard.
Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell (r_0,c_0) into the cell (r_1,c_1) only under the condition that r_1 = r_0 or c_1 = c_0 and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).
Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!
Input
The first line contains two integers n and m (0 β€ n,m β€ 10^5) β the number of vertical and horizontal spells.
Each of the following n lines contains one integer x (1 β€ x < 10^9) β the description of the vertical spell. It will create a blocking line between the columns of x and x+1.
Each of the following m lines contains three integers x_1, x_2 and y (1 β€ x_{1} β€ x_{2} β€ 10^9, 1 β€ y < 10^9) β the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number y, in columns from x_1 to x_2 inclusive.
It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.
Output
In a single line print one integer β the minimum number of spells the rook needs to remove so it can get from the cell (1,1) to at least one cell in the row with the number 10^9
Examples
Input
2 3
6
8
1 5 6
1 9 4
2 4 2
Output
1
Input
1 3
4
1 5 3
1 9 4
4 6 6
Output
1
Input
0 2
1 1000000000 4
1 1000000000 2
Output
2
Input
0 0
Output
0
Input
2 3
4
6
1 4 3
1 5 2
1 6 5
Output
2
Note
In the first sample, in order for the rook return home, it is enough to remove the second horizontal spell.
<image> Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home.
In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell.
<image> Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home.
In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them.
<image> Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home.
In the fourth sample, we have no spells, which means that we do not need to remove anything.
In the fifth example, we can remove the first vertical and third horizontal spells.
<image> Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home. | instruction | 0 | 67,258 | 15 | 134,516 |
Tags: binary search, two pointers
Correct Solution:
```
n, m = map(int, input().split())
ver = [int(input()) for _ in range(n)]
ver.append(10 ** 9)
hor = []
for _ in range(m):
x1, x2, y = map(int, input().split())
if x1 == 1:
hor.append(x2)
hor.sort()
ver.sort()
j = 0
ans = 10 ** 18
for i in range(n + 1):
while j < len(hor) and ver[i] > hor[j]:
j += 1
ans = min(ans, i + len(hor) - j)
if j == len(hor):
break
print(ans)
``` | output | 1 | 67,258 | 15 | 134,517 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number.
Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner β a cell with coordinates (1,1). But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely β on the upper side of the field (that is, in any cell that is in the row with number 10^9).
Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells:
* Vertical. Each of these is defined by one number x. Such spells create an infinite blocking line between the columns x and x+1.
* Horizontal. Each of these is defined by three numbers x_1, x_2, y. Such spells create a blocking segment that passes through the top side of the cells, which are in the row y and in columns from x_1 to x_2 inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.
<image> An example of a chessboard.
Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell (r_0,c_0) into the cell (r_1,c_1) only under the condition that r_1 = r_0 or c_1 = c_0 and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).
Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!
Input
The first line contains two integers n and m (0 β€ n,m β€ 10^5) β the number of vertical and horizontal spells.
Each of the following n lines contains one integer x (1 β€ x < 10^9) β the description of the vertical spell. It will create a blocking line between the columns of x and x+1.
Each of the following m lines contains three integers x_1, x_2 and y (1 β€ x_{1} β€ x_{2} β€ 10^9, 1 β€ y < 10^9) β the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number y, in columns from x_1 to x_2 inclusive.
It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.
Output
In a single line print one integer β the minimum number of spells the rook needs to remove so it can get from the cell (1,1) to at least one cell in the row with the number 10^9
Examples
Input
2 3
6
8
1 5 6
1 9 4
2 4 2
Output
1
Input
1 3
4
1 5 3
1 9 4
4 6 6
Output
1
Input
0 2
1 1000000000 4
1 1000000000 2
Output
2
Input
0 0
Output
0
Input
2 3
4
6
1 4 3
1 5 2
1 6 5
Output
2
Note
In the first sample, in order for the rook return home, it is enough to remove the second horizontal spell.
<image> Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home.
In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell.
<image> Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home.
In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them.
<image> Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home.
In the fourth sample, we have no spells, which means that we do not need to remove anything.
In the fifth example, we can remove the first vertical and third horizontal spells.
<image> Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home.
Submitted Solution:
```
val=10**9
n,m=map(int,input().split())
arr1=[]
for i in range(n):
x=int(input())
arr1.append(x)
arr1.append(val)
arr2=[]
ans=val
finalval=0
arr1.sort()
for i in range(m):
x1,x2,y=map(int,input().split())
if(x1==1):
if(x2==val):
finalval+=1
else:
if(len(arr1)>0 and x2>=arr1[0]):
arr2.append(x2)
arr2.sort()
i=0
j=0
while(i<len(arr1) and j<len(arr2)):
if(arr1[i]>arr2[j]):
j+=1
elif(arr1[i]==arr2[j]):
temp1=len(arr2)-j
#print(temp1,'1')
ans=min(i+temp1,ans)
i+=1
else:
temp1=len(arr2)-j
#print(temp1,'2')
ans=min(i+temp1,ans)
i+=1
#print(ans+finalval)
ans=min(i,ans)
print(ans+finalval)
``` | instruction | 0 | 67,259 | 15 | 134,518 |
Yes | output | 1 | 67,259 | 15 | 134,519 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number.
Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner β a cell with coordinates (1,1). But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely β on the upper side of the field (that is, in any cell that is in the row with number 10^9).
Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells:
* Vertical. Each of these is defined by one number x. Such spells create an infinite blocking line between the columns x and x+1.
* Horizontal. Each of these is defined by three numbers x_1, x_2, y. Such spells create a blocking segment that passes through the top side of the cells, which are in the row y and in columns from x_1 to x_2 inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.
<image> An example of a chessboard.
Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell (r_0,c_0) into the cell (r_1,c_1) only under the condition that r_1 = r_0 or c_1 = c_0 and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).
Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!
Input
The first line contains two integers n and m (0 β€ n,m β€ 10^5) β the number of vertical and horizontal spells.
Each of the following n lines contains one integer x (1 β€ x < 10^9) β the description of the vertical spell. It will create a blocking line between the columns of x and x+1.
Each of the following m lines contains three integers x_1, x_2 and y (1 β€ x_{1} β€ x_{2} β€ 10^9, 1 β€ y < 10^9) β the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number y, in columns from x_1 to x_2 inclusive.
It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.
Output
In a single line print one integer β the minimum number of spells the rook needs to remove so it can get from the cell (1,1) to at least one cell in the row with the number 10^9
Examples
Input
2 3
6
8
1 5 6
1 9 4
2 4 2
Output
1
Input
1 3
4
1 5 3
1 9 4
4 6 6
Output
1
Input
0 2
1 1000000000 4
1 1000000000 2
Output
2
Input
0 0
Output
0
Input
2 3
4
6
1 4 3
1 5 2
1 6 5
Output
2
Note
In the first sample, in order for the rook return home, it is enough to remove the second horizontal spell.
<image> Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home.
In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell.
<image> Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home.
In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them.
<image> Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home.
In the fourth sample, we have no spells, which means that we do not need to remove anything.
In the fifth example, we can remove the first vertical and third horizontal spells.
<image> Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home.
Submitted Solution:
```
n, m = map(int, input().split())
y = []
for i in range(n):
y.append(int(input()))
y.append(10 ** 9)
x = []
for i in range(m):
a, b, c = map(int, input().split())
if a == 1:
x.append(b)
y.sort(); x.sort()
m = len(x)
ans = m
k = 0
for i in range(n + 1):
ok = True
for j in range(k, m):
if y[i] <= x[j]:
k = j
ok = False
break
if ok:
k = m
ans = min(ans, m - k + i)
break
ans = min(ans, m - k + i)
print(ans)
#
``` | instruction | 0 | 67,260 | 15 | 134,520 |
Yes | output | 1 | 67,260 | 15 | 134,521 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number.
Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner β a cell with coordinates (1,1). But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely β on the upper side of the field (that is, in any cell that is in the row with number 10^9).
Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells:
* Vertical. Each of these is defined by one number x. Such spells create an infinite blocking line between the columns x and x+1.
* Horizontal. Each of these is defined by three numbers x_1, x_2, y. Such spells create a blocking segment that passes through the top side of the cells, which are in the row y and in columns from x_1 to x_2 inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.
<image> An example of a chessboard.
Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell (r_0,c_0) into the cell (r_1,c_1) only under the condition that r_1 = r_0 or c_1 = c_0 and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).
Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!
Input
The first line contains two integers n and m (0 β€ n,m β€ 10^5) β the number of vertical and horizontal spells.
Each of the following n lines contains one integer x (1 β€ x < 10^9) β the description of the vertical spell. It will create a blocking line between the columns of x and x+1.
Each of the following m lines contains three integers x_1, x_2 and y (1 β€ x_{1} β€ x_{2} β€ 10^9, 1 β€ y < 10^9) β the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number y, in columns from x_1 to x_2 inclusive.
It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.
Output
In a single line print one integer β the minimum number of spells the rook needs to remove so it can get from the cell (1,1) to at least one cell in the row with the number 10^9
Examples
Input
2 3
6
8
1 5 6
1 9 4
2 4 2
Output
1
Input
1 3
4
1 5 3
1 9 4
4 6 6
Output
1
Input
0 2
1 1000000000 4
1 1000000000 2
Output
2
Input
0 0
Output
0
Input
2 3
4
6
1 4 3
1 5 2
1 6 5
Output
2
Note
In the first sample, in order for the rook return home, it is enough to remove the second horizontal spell.
<image> Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home.
In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell.
<image> Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home.
In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them.
<image> Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home.
In the fourth sample, we have no spells, which means that we do not need to remove anything.
In the fifth example, we can remove the first vertical and third horizontal spells.
<image> Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home.
Submitted Solution:
```
# -*- coding:utf-8 -*-
"""
created by shuangquan.huang at 11/20/18
"""
import collections
import bisect
N, M = map(int, input().split())
vlines = []
for i in range(N):
x = int(input())
vlines.append(x)
vlines.sort()
vlines.append(10**9)
yxs = collections.defaultdict(list)
ys = set()
for i in range(M):
l, r, y = map(int, input().split())
yxs[y].append((l, r))
if l <= 1:
ys.add(y)
def merge(segs):
segs.sort()
ans = [segs[0]]
for s in segs[1:]:
pre = ans[-1]
if s[0] > pre[1]:
# ans.append(s)
return ans[0]
else:
ans[-1] = (pre[0], s[1])
return ans[0]
xs = [merge(yxs[y])[1] for y in ys]
xs.sort()
ans = float('inf')
for i, x in enumerate(vlines):
if i >= ans:
break
# count = i + sum([1 if u >= x else 0 for u in xs])
count = i + len(xs) - bisect.bisect_left(xs, x)
ans = min(ans, count)
print(ans)
``` | instruction | 0 | 67,261 | 15 | 134,522 |
Yes | output | 1 | 67,261 | 15 | 134,523 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number.
Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner β a cell with coordinates (1,1). But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely β on the upper side of the field (that is, in any cell that is in the row with number 10^9).
Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells:
* Vertical. Each of these is defined by one number x. Such spells create an infinite blocking line between the columns x and x+1.
* Horizontal. Each of these is defined by three numbers x_1, x_2, y. Such spells create a blocking segment that passes through the top side of the cells, which are in the row y and in columns from x_1 to x_2 inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.
<image> An example of a chessboard.
Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell (r_0,c_0) into the cell (r_1,c_1) only under the condition that r_1 = r_0 or c_1 = c_0 and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).
Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!
Input
The first line contains two integers n and m (0 β€ n,m β€ 10^5) β the number of vertical and horizontal spells.
Each of the following n lines contains one integer x (1 β€ x < 10^9) β the description of the vertical spell. It will create a blocking line between the columns of x and x+1.
Each of the following m lines contains three integers x_1, x_2 and y (1 β€ x_{1} β€ x_{2} β€ 10^9, 1 β€ y < 10^9) β the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number y, in columns from x_1 to x_2 inclusive.
It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.
Output
In a single line print one integer β the minimum number of spells the rook needs to remove so it can get from the cell (1,1) to at least one cell in the row with the number 10^9
Examples
Input
2 3
6
8
1 5 6
1 9 4
2 4 2
Output
1
Input
1 3
4
1 5 3
1 9 4
4 6 6
Output
1
Input
0 2
1 1000000000 4
1 1000000000 2
Output
2
Input
0 0
Output
0
Input
2 3
4
6
1 4 3
1 5 2
1 6 5
Output
2
Note
In the first sample, in order for the rook return home, it is enough to remove the second horizontal spell.
<image> Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home.
In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell.
<image> Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home.
In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them.
<image> Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home.
In the fourth sample, we have no spells, which means that we do not need to remove anything.
In the fifth example, we can remove the first vertical and third horizontal spells.
<image> Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home.
Submitted Solution:
```
import sys
input = sys.stdin.readline
def bs(num):
low=0
high=len(rows)-1
while low<high:
mid=(low+high)//2
if rows[mid]>=num:
high=mid-1
else:
low=mid+1
if rows[low]<num:
return len(rows)-(low+1)
else:
return len(rows)-low
n,m=map(int,input().split())
if n==0 and m==0:
print (0)
exit(0)
col=[]
rows=[]
for i in range(n):
col.append(int(input()))
col.append(10**9)
for i in range(m):
temp = list(map(int,input().split()))
if temp[0]==1:
rows.append(temp[1])
col.sort()
rows.sort()
ans=10**9
if len(rows)==0:
print (0)
exit(0)
for i in range(n+1):
count1 = bs(col[i])
ans=min(ans,count1+i)
print (ans)
``` | instruction | 0 | 67,262 | 15 | 134,524 |
Yes | output | 1 | 67,262 | 15 | 134,525 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number.
Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner β a cell with coordinates (1,1). But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely β on the upper side of the field (that is, in any cell that is in the row with number 10^9).
Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells:
* Vertical. Each of these is defined by one number x. Such spells create an infinite blocking line between the columns x and x+1.
* Horizontal. Each of these is defined by three numbers x_1, x_2, y. Such spells create a blocking segment that passes through the top side of the cells, which are in the row y and in columns from x_1 to x_2 inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.
<image> An example of a chessboard.
Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell (r_0,c_0) into the cell (r_1,c_1) only under the condition that r_1 = r_0 or c_1 = c_0 and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).
Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!
Input
The first line contains two integers n and m (0 β€ n,m β€ 10^5) β the number of vertical and horizontal spells.
Each of the following n lines contains one integer x (1 β€ x < 10^9) β the description of the vertical spell. It will create a blocking line between the columns of x and x+1.
Each of the following m lines contains three integers x_1, x_2 and y (1 β€ x_{1} β€ x_{2} β€ 10^9, 1 β€ y < 10^9) β the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number y, in columns from x_1 to x_2 inclusive.
It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.
Output
In a single line print one integer β the minimum number of spells the rook needs to remove so it can get from the cell (1,1) to at least one cell in the row with the number 10^9
Examples
Input
2 3
6
8
1 5 6
1 9 4
2 4 2
Output
1
Input
1 3
4
1 5 3
1 9 4
4 6 6
Output
1
Input
0 2
1 1000000000 4
1 1000000000 2
Output
2
Input
0 0
Output
0
Input
2 3
4
6
1 4 3
1 5 2
1 6 5
Output
2
Note
In the first sample, in order for the rook return home, it is enough to remove the second horizontal spell.
<image> Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home.
In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell.
<image> Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home.
In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them.
<image> Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home.
In the fourth sample, we have no spells, which means that we do not need to remove anything.
In the fifth example, we can remove the first vertical and third horizontal spells.
<image> Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home.
Submitted Solution:
```
import bisect
[n,m] = [int(x) for x in input().split()]
v = []
h = []
num_v = [0 for i in range(0,n)]
num_h = [0 for i in range(0,m)]
for i in range(0,n):
v.append(int(input()))
for j in range(0,m):
h.append([int(x) for x in input().split()])
for i in range(0,m):
if h[i][0] == 1:
f = bisect.bisect_right(v, h[i][1])
num_h[i] = f
for j in range(0,f):
num_v[j] = num_v[j] + 1
s = 0
k = 0
p = 0
i = 0
j = 0
while True:
if i < len(num_v) and num_v[i]-p != 0:
if num_h[j] == 0:
j = j + 1
else:
if num_v[i]-p >= num_h[j]-k:
s = s + 1
k = k + 1
i = i + 1
else:
s = s + 1
p = p + 1
j = j + 1
else:
break
for e in h:
if e[1] == 1000000000:
s = s + 1
print(s)
``` | instruction | 0 | 67,263 | 15 | 134,526 |
No | output | 1 | 67,263 | 15 | 134,527 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number.
Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner β a cell with coordinates (1,1). But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely β on the upper side of the field (that is, in any cell that is in the row with number 10^9).
Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells:
* Vertical. Each of these is defined by one number x. Such spells create an infinite blocking line between the columns x and x+1.
* Horizontal. Each of these is defined by three numbers x_1, x_2, y. Such spells create a blocking segment that passes through the top side of the cells, which are in the row y and in columns from x_1 to x_2 inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.
<image> An example of a chessboard.
Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell (r_0,c_0) into the cell (r_1,c_1) only under the condition that r_1 = r_0 or c_1 = c_0 and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).
Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!
Input
The first line contains two integers n and m (0 β€ n,m β€ 10^5) β the number of vertical and horizontal spells.
Each of the following n lines contains one integer x (1 β€ x < 10^9) β the description of the vertical spell. It will create a blocking line between the columns of x and x+1.
Each of the following m lines contains three integers x_1, x_2 and y (1 β€ x_{1} β€ x_{2} β€ 10^9, 1 β€ y < 10^9) β the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number y, in columns from x_1 to x_2 inclusive.
It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.
Output
In a single line print one integer β the minimum number of spells the rook needs to remove so it can get from the cell (1,1) to at least one cell in the row with the number 10^9
Examples
Input
2 3
6
8
1 5 6
1 9 4
2 4 2
Output
1
Input
1 3
4
1 5 3
1 9 4
4 6 6
Output
1
Input
0 2
1 1000000000 4
1 1000000000 2
Output
2
Input
0 0
Output
0
Input
2 3
4
6
1 4 3
1 5 2
1 6 5
Output
2
Note
In the first sample, in order for the rook return home, it is enough to remove the second horizontal spell.
<image> Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home.
In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell.
<image> Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home.
In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them.
<image> Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home.
In the fourth sample, we have no spells, which means that we do not need to remove anything.
In the fifth example, we can remove the first vertical and third horizontal spells.
<image> Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home.
Submitted Solution:
```
import bisect
n, m = map(int, input().split())
ar1 = [1] + [int(input()) for _ in range(n)]
ar1.append(10 ** 9)
ar2 = [list(map(int, input().split())) for _ in range(m)]
kek = list()
for x in ar2:
j1 = bisect.bisect_left(ar1, x[0])
j2 = bisect.bisect_right(ar1, x[1])
if j2 - j1 > 1 and j1 == 0:
kek.append(j2)
res = [0] * (len(ar1) + 1)
res[0] = len(kek)
for x in kek:
res[x] -= 1
for i in range(1, len(res)):
res[i] += res[i - 1]
min_ = float('inf')
for i in range(1, len(res) - 1):
min_ = min(min_, res[i] + i - 1)
print(min_)
``` | instruction | 0 | 67,264 | 15 | 134,528 |
No | output | 1 | 67,264 | 15 | 134,529 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number.
Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner β a cell with coordinates (1,1). But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely β on the upper side of the field (that is, in any cell that is in the row with number 10^9).
Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells:
* Vertical. Each of these is defined by one number x. Such spells create an infinite blocking line between the columns x and x+1.
* Horizontal. Each of these is defined by three numbers x_1, x_2, y. Such spells create a blocking segment that passes through the top side of the cells, which are in the row y and in columns from x_1 to x_2 inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.
<image> An example of a chessboard.
Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell (r_0,c_0) into the cell (r_1,c_1) only under the condition that r_1 = r_0 or c_1 = c_0 and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).
Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!
Input
The first line contains two integers n and m (0 β€ n,m β€ 10^5) β the number of vertical and horizontal spells.
Each of the following n lines contains one integer x (1 β€ x < 10^9) β the description of the vertical spell. It will create a blocking line between the columns of x and x+1.
Each of the following m lines contains three integers x_1, x_2 and y (1 β€ x_{1} β€ x_{2} β€ 10^9, 1 β€ y < 10^9) β the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number y, in columns from x_1 to x_2 inclusive.
It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.
Output
In a single line print one integer β the minimum number of spells the rook needs to remove so it can get from the cell (1,1) to at least one cell in the row with the number 10^9
Examples
Input
2 3
6
8
1 5 6
1 9 4
2 4 2
Output
1
Input
1 3
4
1 5 3
1 9 4
4 6 6
Output
1
Input
0 2
1 1000000000 4
1 1000000000 2
Output
2
Input
0 0
Output
0
Input
2 3
4
6
1 4 3
1 5 2
1 6 5
Output
2
Note
In the first sample, in order for the rook return home, it is enough to remove the second horizontal spell.
<image> Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home.
In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell.
<image> Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home.
In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them.
<image> Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home.
In the fourth sample, we have no spells, which means that we do not need to remove anything.
In the fifth example, we can remove the first vertical and third horizontal spells.
<image> Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home.
Submitted Solution:
```
def go():
C = 1000000000
n, m = [int(i) for i in input().split(' ')]
k = {}
v = 0
o = 0
too_many = False
for i in range(n):
k[int(input())] = 0
len_k = len(k)
for i in range(m):
x1, x2, y = [int(i) for i in input().split(' ')]
if x1 == 1 and x2 == C:
v += 1
elif not too_many:
for i in k:
if x1 <= i <= x2 and x1 == 1:
k[i] += 1
if k[i] > len_k:
too_many = True
break
if len_k == 0:
return v
k = sorted(k.values(), reverse=True)
k.append(0)
o = 0
x = k[0] + v
for i in range(len_k + 1):
import code
code.interact(local=locals())
x = min(i + k[i] + v, x)
return x
print(go())
``` | instruction | 0 | 67,265 | 15 | 134,530 |
No | output | 1 | 67,265 | 15 | 134,531 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number.
Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner β a cell with coordinates (1,1). But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely β on the upper side of the field (that is, in any cell that is in the row with number 10^9).
Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells:
* Vertical. Each of these is defined by one number x. Such spells create an infinite blocking line between the columns x and x+1.
* Horizontal. Each of these is defined by three numbers x_1, x_2, y. Such spells create a blocking segment that passes through the top side of the cells, which are in the row y and in columns from x_1 to x_2 inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.
<image> An example of a chessboard.
Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell (r_0,c_0) into the cell (r_1,c_1) only under the condition that r_1 = r_0 or c_1 = c_0 and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).
Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!
Input
The first line contains two integers n and m (0 β€ n,m β€ 10^5) β the number of vertical and horizontal spells.
Each of the following n lines contains one integer x (1 β€ x < 10^9) β the description of the vertical spell. It will create a blocking line between the columns of x and x+1.
Each of the following m lines contains three integers x_1, x_2 and y (1 β€ x_{1} β€ x_{2} β€ 10^9, 1 β€ y < 10^9) β the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number y, in columns from x_1 to x_2 inclusive.
It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.
Output
In a single line print one integer β the minimum number of spells the rook needs to remove so it can get from the cell (1,1) to at least one cell in the row with the number 10^9
Examples
Input
2 3
6
8
1 5 6
1 9 4
2 4 2
Output
1
Input
1 3
4
1 5 3
1 9 4
4 6 6
Output
1
Input
0 2
1 1000000000 4
1 1000000000 2
Output
2
Input
0 0
Output
0
Input
2 3
4
6
1 4 3
1 5 2
1 6 5
Output
2
Note
In the first sample, in order for the rook return home, it is enough to remove the second horizontal spell.
<image> Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home.
In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell.
<image> Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home.
In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them.
<image> Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home.
In the fourth sample, we have no spells, which means that we do not need to remove anything.
In the fifth example, we can remove the first vertical and third horizontal spells.
<image> Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home.
Submitted Solution:
```
n, m = map(int, input().split())
vert = []
for i in range(n):
vert.append(int(input()))
vert.sort()
vert.append(10**9)
hor = [100000000000]
count1 = 0
for i in range(m):
l = [int(x) for x in input().split()]
if l[0] == 1 and not l[1] == 1000000000:
hor.append(l[1])
if l[1] == 1000000000:
count1 += 1
hor.sort(reverse=True)
j = len(hor) - 1
minimum = 10**18
for i in range(len(vert)):
while hor[j] < vert[i] and j:
j -= 1
if j + i + count1 < minimum:
minimum = j + i + count1
print(minimum if len(vert) != 1 else count1)
``` | instruction | 0 | 67,266 | 15 | 134,532 |
No | output | 1 | 67,266 | 15 | 134,533 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Maksim walks on a Cartesian plane. Initially, he stands at the point (0, 0) and in one move he can go to any of four adjacent points (left, right, up, down). For example, if Maksim is currently at the point (0, 0), he can go to any of the following points in one move:
* (1, 0);
* (0, 1);
* (-1, 0);
* (0, -1).
There are also n distinct key points at this plane. The i-th point is p_i = (x_i, y_i). It is guaranteed that 0 β€ x_i and 0 β€ y_i and there is no key point (0, 0).
Let the first level points be such points that max(x_i, y_i) = 1, the second level points be such points that max(x_i, y_i) = 2 and so on. Maksim wants to visit all the key points. But he shouldn't visit points of level i + 1 if he does not visit all the points of level i. He starts visiting the points from the minimum level of point from the given set.
The distance between two points (x_1, y_1) and (x_2, y_2) is |x_1 - x_2| + |y_1 - y_2| where |v| is the absolute value of v.
Maksim wants to visit all the key points in such a way that the total distance he walks will be minimum possible. Your task is to find this distance.
If you are Python programmer, consider using PyPy instead of Python when you submit your code.
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of key points.
Each of the next n lines contains two integers x_i, y_i (0 β€ x_i, y_i β€ 10^9) β x-coordinate of the key point p_i and y-coordinate of the key point p_i. It is guaranteed that all the points are distinct and the point (0, 0) is not in this set.
Output
Print one integer β the minimum possible total distance Maksim has to travel if he needs to visit all key points in a way described above.
Examples
Input
8
2 2
1 4
2 3
3 1
3 4
1 1
4 3
1 2
Output
15
Input
5
2 1
1 0
2 0
3 2
0 3
Output
9
Note
The picture corresponding to the first example: <image>
There is one of the possible answers of length 15.
The picture corresponding to the second example: <image>
There is one of the possible answers of length 9. | instruction | 0 | 67,267 | 15 | 134,534 |
Tags: dp
Correct Solution:
```
def f(x, m):
if x < m:
return (m, x)
else:
return (m * 2 - x, m)
n = int(input())
d = {0 : [0]}
for i in range(n):
x, y = map(int, input().split())
m = max(x, y)
if m in d:
if x == m:
d[m].append(y)
else:
d[m].append(m * 2 - x)
else:
if x == m:
d[m] = [y]
else:
d[m] = [m * 2 - x]
t = sorted(d.keys())
ans = 0
for k in t:
d[k].sort()
ans += d[k][-1] - d[k][0]
dp1 = [0] * len(t)
dp2 = [0] * len(t)
for i in range(len(t) - 1):
k = t[i]
k2 = t[i + 1]
x11, y11 = f(d[k][0], k)
x12, y12 = f(d[k][-1], k)
x21, y21 = f(d[k2][0], k2)
x22, y22 = f(d[k2][-1], k2)
dp1[i + 1] = min(dp1[i] + abs(x11 - x22) + abs(y11 - y22), dp2[i] + abs(x12 - x22) + abs(y12 - y22))
dp2[i + 1] = min(dp1[i] + abs(x11 - x21) + abs(y11 - y21), dp2[i] + abs(x12 - x21) + abs(y12 - y21))
print(min(dp1[-1], dp2[-1]) + ans)
``` | output | 1 | 67,267 | 15 | 134,535 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Maksim walks on a Cartesian plane. Initially, he stands at the point (0, 0) and in one move he can go to any of four adjacent points (left, right, up, down). For example, if Maksim is currently at the point (0, 0), he can go to any of the following points in one move:
* (1, 0);
* (0, 1);
* (-1, 0);
* (0, -1).
There are also n distinct key points at this plane. The i-th point is p_i = (x_i, y_i). It is guaranteed that 0 β€ x_i and 0 β€ y_i and there is no key point (0, 0).
Let the first level points be such points that max(x_i, y_i) = 1, the second level points be such points that max(x_i, y_i) = 2 and so on. Maksim wants to visit all the key points. But he shouldn't visit points of level i + 1 if he does not visit all the points of level i. He starts visiting the points from the minimum level of point from the given set.
The distance between two points (x_1, y_1) and (x_2, y_2) is |x_1 - x_2| + |y_1 - y_2| where |v| is the absolute value of v.
Maksim wants to visit all the key points in such a way that the total distance he walks will be minimum possible. Your task is to find this distance.
If you are Python programmer, consider using PyPy instead of Python when you submit your code.
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of key points.
Each of the next n lines contains two integers x_i, y_i (0 β€ x_i, y_i β€ 10^9) β x-coordinate of the key point p_i and y-coordinate of the key point p_i. It is guaranteed that all the points are distinct and the point (0, 0) is not in this set.
Output
Print one integer β the minimum possible total distance Maksim has to travel if he needs to visit all key points in a way described above.
Examples
Input
8
2 2
1 4
2 3
3 1
3 4
1 1
4 3
1 2
Output
15
Input
5
2 1
1 0
2 0
3 2
0 3
Output
9
Note
The picture corresponding to the first example: <image>
There is one of the possible answers of length 15.
The picture corresponding to the second example: <image>
There is one of the possible answers of length 9. | instruction | 0 | 67,268 | 15 | 134,536 |
Tags: dp
Correct Solution:
```
import collections, heapq
def dijkstra(g, st):
"""Dijkstra method"""
n = len(g)
d = [float('inf')] * n
d[st] = 0
que = [(0, st)] # (min_dist, vertex)
heapq.heapify(que)
while len(que) > 0:
dist, v0 = heapq.heappop(que)
if d[v0] < dist: continue
for v1, dist in g[v0]:
if d[v1] > d[v0] + dist:
d[v1] = d[v0] + dist
heapq.heappush(que, (d[v1], v1))
return d
n = int(input())
p = [tuple(map(int, input().split())) for _ in range(n)]
d = collections.defaultdict(list)
for pi in p:
d[max(pi[0],pi[1])].append(pi)
levels = list(d.keys())
levels.sort()
g = [[] for _ in range(2*(len(levels)+1))]
ans = 0
last = [(0,0)]
for k, l in enumerate(levels):
d[l].sort(key=lambda x: (x[0], -x[1]))
if d[l][0][0] == d[l][-1][0]:
ans += d[l][0][1] - d[l][-1][1]
elif d[l][0][1] == d[l][-1][1]:
ans += d[l][-1][0] - d[l][0][0]
else:
ans += (l-d[l][0][0]) + (l-d[l][-1][1])
cand = [d[l][0]]
if len(d[l]) > 1:
cand.append(d[l][-1])
for i, vi in enumerate(last):
for j, vj in enumerate(cand):
dist = abs(last[i-1][0]-vj[0]) + abs(last[i-1][1]-vj[1])
g[2*k+i].append((2*k+2+j, dist))
g[2*k+2+j].append((2*k+i, dist))
last = cand
# print(g)
res = dijkstra(g, 0)
print(ans+min(res[-2:]))
``` | output | 1 | 67,268 | 15 | 134,537 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Maksim walks on a Cartesian plane. Initially, he stands at the point (0, 0) and in one move he can go to any of four adjacent points (left, right, up, down). For example, if Maksim is currently at the point (0, 0), he can go to any of the following points in one move:
* (1, 0);
* (0, 1);
* (-1, 0);
* (0, -1).
There are also n distinct key points at this plane. The i-th point is p_i = (x_i, y_i). It is guaranteed that 0 β€ x_i and 0 β€ y_i and there is no key point (0, 0).
Let the first level points be such points that max(x_i, y_i) = 1, the second level points be such points that max(x_i, y_i) = 2 and so on. Maksim wants to visit all the key points. But he shouldn't visit points of level i + 1 if he does not visit all the points of level i. He starts visiting the points from the minimum level of point from the given set.
The distance between two points (x_1, y_1) and (x_2, y_2) is |x_1 - x_2| + |y_1 - y_2| where |v| is the absolute value of v.
Maksim wants to visit all the key points in such a way that the total distance he walks will be minimum possible. Your task is to find this distance.
If you are Python programmer, consider using PyPy instead of Python when you submit your code.
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of key points.
Each of the next n lines contains two integers x_i, y_i (0 β€ x_i, y_i β€ 10^9) β x-coordinate of the key point p_i and y-coordinate of the key point p_i. It is guaranteed that all the points are distinct and the point (0, 0) is not in this set.
Output
Print one integer β the minimum possible total distance Maksim has to travel if he needs to visit all key points in a way described above.
Examples
Input
8
2 2
1 4
2 3
3 1
3 4
1 1
4 3
1 2
Output
15
Input
5
2 1
1 0
2 0
3 2
0 3
Output
9
Note
The picture corresponding to the first example: <image>
There is one of the possible answers of length 15.
The picture corresponding to the second example: <image>
There is one of the possible answers of length 9. | instruction | 0 | 67,269 | 15 | 134,538 |
Tags: dp
Correct Solution:
```
def get_input_list():
return list(map(int, input().split()))
def sort_(p):
np = []
for i in p:
np.append([i[0],-i[1]])
np.sort()
return np
def distance(A,B):
return abs(B[0] - A[0]) + abs(B[1] - A[1])
n = int(input())
p_ = []
for _ in range(n):
p_.append(get_input_list())
d = {}
for i in p_:
if (str(max(i))) in d:
d[str(max(i))].append(i)
else:
d[str(max(i))] = [i]
l = [int(i) for i in d]
l.sort()
p1 = [0,0]
p2 = [0,0]
s1 = 0 # Path to p2
s2 = 0 # Path to p1
for i_ in l:
i = str(i_)
p = sort_(d[i])
a1 = distance(p1,p[0])
b1 = distance(p1,p[-1])
a2 = distance(p2,p[0])
b2 = distance(p2,p[-1])
c = distance(p[0],p[-1])
s1_ = s1
s2_ = s2
s1 = min(s2_+a1,s1_+a2) + c
s2 = min(s2_+b1,s1_+b2) + c
p1 = p[0]
p2 = p[-1]
print(min(s1,s2))
``` | output | 1 | 67,269 | 15 | 134,539 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Maksim walks on a Cartesian plane. Initially, he stands at the point (0, 0) and in one move he can go to any of four adjacent points (left, right, up, down). For example, if Maksim is currently at the point (0, 0), he can go to any of the following points in one move:
* (1, 0);
* (0, 1);
* (-1, 0);
* (0, -1).
There are also n distinct key points at this plane. The i-th point is p_i = (x_i, y_i). It is guaranteed that 0 β€ x_i and 0 β€ y_i and there is no key point (0, 0).
Let the first level points be such points that max(x_i, y_i) = 1, the second level points be such points that max(x_i, y_i) = 2 and so on. Maksim wants to visit all the key points. But he shouldn't visit points of level i + 1 if he does not visit all the points of level i. He starts visiting the points from the minimum level of point from the given set.
The distance between two points (x_1, y_1) and (x_2, y_2) is |x_1 - x_2| + |y_1 - y_2| where |v| is the absolute value of v.
Maksim wants to visit all the key points in such a way that the total distance he walks will be minimum possible. Your task is to find this distance.
If you are Python programmer, consider using PyPy instead of Python when you submit your code.
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of key points.
Each of the next n lines contains two integers x_i, y_i (0 β€ x_i, y_i β€ 10^9) β x-coordinate of the key point p_i and y-coordinate of the key point p_i. It is guaranteed that all the points are distinct and the point (0, 0) is not in this set.
Output
Print one integer β the minimum possible total distance Maksim has to travel if he needs to visit all key points in a way described above.
Examples
Input
8
2 2
1 4
2 3
3 1
3 4
1 1
4 3
1 2
Output
15
Input
5
2 1
1 0
2 0
3 2
0 3
Output
9
Note
The picture corresponding to the first example: <image>
There is one of the possible answers of length 15.
The picture corresponding to the second example: <image>
There is one of the possible answers of length 9. | instruction | 0 | 67,270 | 15 | 134,540 |
Tags: dp
Correct Solution:
```
from collections import defaultdict
n = int(input())
points = defaultdict(list)
points[0].append((0,0))
for i in range(n):
x,y = map(int,input().split())
points[max(x,y)].append((x,y))
for level in points:
points[level].sort(key=lambda x:(x[0],-x[1]))
levels = sorted(points.keys())
dp = [[0,0] for i in levels]
dist = lambda a,b:abs(a[0]-b[0])+abs(a[1]-b[1])
for i in range(1,len(levels)):
start = points[levels[i]][0]
end = points[levels[i]][-1]
prevstart = points[levels[i-1]][0]
prevend = points[levels[i-1]][-1]
dp[i][0] = min(dp[i-1][0]+dist(prevstart,end), dp[i-1][1]+dist(prevend,end)) + dist(start,end)
dp[i][1] = min(dp[i-1][0]+dist(prevstart,start), dp[i-1][1]+dist(prevend,start)) + dist(start,end)
# print(points)
print(min(dp[-1]))
``` | output | 1 | 67,270 | 15 | 134,541 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.