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 |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.
In order to lose weight, Bashar is going to run for k kilometers. Bashar is going to run in a place that looks like a grid of n rows and m columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4 n m - 2n - 2m) roads.
Let's take, for example, n = 3 and m = 4. In this case, there are 34 roads. It is the picture of this case (arrows describe roads):
<image>
Bashar wants to run by these rules:
* He starts at the top-left cell in the grid;
* In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row i and in the column j, i.e. in the cell (i, j) he will move to:
* in the case 'U' to the cell (i-1, j);
* in the case 'D' to the cell (i+1, j);
* in the case 'L' to the cell (i, j-1);
* in the case 'R' to the cell (i, j+1);
* He wants to run exactly k kilometers, so he wants to make exactly k moves;
* Bashar can finish in any cell of the grid;
* He can't go out of the grid so at any moment of the time he should be on some cell;
* Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times.
Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.
You should give him a steps to do and since Bashar can't remember too many steps, a should not exceed 3000. In every step, you should give him an integer f and a string of moves s of length at most 4 which means that he should repeat the moves in the string s for f times. He will perform the steps in the order you print them.
For example, if the steps are 2 RUD, 3 UUL then the moves he is going to move are RUD + RUD + UUL + UUL + UUL = RUDRUDUULUULUUL.
Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to k kilometers or say, that it is impossible?
Input
The only line contains three integers n, m and k (1 ≤ n, m ≤ 500, 1 ≤ k ≤ 10 ^{9}), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
Output
If there is no possible way to run k kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.
If the answer is "YES", on the second line print an integer a (1 ≤ a ≤ 3000) — the number of steps, then print a lines describing the steps.
To describe a step, print an integer f (1 ≤ f ≤ 10^{9}) and a string of moves s of length at most 4. Every character in s should be 'U', 'D', 'L' or 'R'.
Bashar will start from the top-left cell. Make sure to move exactly k moves without visiting the same road twice and without going outside the grid. He can finish at any cell.
We can show that if it is possible to run exactly k kilometers, then it is possible to describe the path under such output constraints.
Examples
Input
3 3 4
Output
YES
2
2 R
2 L
Input
3 3 1000000000
Output
NO
Input
3 3 8
Output
YES
3
2 R
2 D
1 LLRR
Input
4 4 9
Output
YES
1
3 RLD
Input
3 4 16
Output
YES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
Note
The moves Bashar is going to move in the first example are: "RRLL".
It is not possible to run 1000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.
The moves Bashar is going to move in the third example are: "RRDDLLRR".
The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
<image> | instruction | 0 | 98,009 | 15 | 196,018 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
# -*- coding: utf-8 -*-
import math
import collections
import bisect
import heapq
import time
import random
import itertools
import sys
from typing import List
"""
created by shhuan at 2020/3/23 11:04
"""
def solve(N, M, K):
if K > 4 * N * M - 2 * N - 2 * M:
print('NO')
return
ans = []
if M == 1:
if K <= N-1:
ans.append('{} {}'.format(K, 'D'))
else:
ans.append('{} {}'.format(N-1, 'D'))
ans.append('{} {}'.format(K-N+1, 'U'))
elif K <= M-1:
ans.append('{} {}'.format(K, 'R'))
elif K <= 2 * (M-1):
ans.append('{} {}'.format(M-1, 'R'))
ans.append('{} {}'.format(K - M + 1, 'L'))
else:
ans.append('{} {}'.format(M - 1, 'R'))
ans.append('{} {}'.format(M - 1, 'L'))
d = 2 * (M-1)
row = 1
while row < N and d < K:
row += 1
# down
if d + 1 <= K:
ans.append('{} {}'.format(1, 'D'))
d += 1
# right
if d < K:
dd = min(M-1, K-d)
ans.append('{} {}'.format(dd, 'R'))
d += dd
# up, down, left
if d < K:
dd = min((K-d)//3, M-1)
if dd > 0:
ans.append('{} {}'.format(dd, 'UDL'))
d += dd * 3
if dd < M-1 and 0 < K-d < 3:
ans.append('{} {}'.format(1, 'UDL'[:K-d]))
d = K
if d < K:
ans.append('{} {}'.format(K-d, 'U'))
print('YES')
print(len(ans))
print('\n'.join(ans))
N, M, K = map(int, input().split())
solve(N, M, K)
``` | output | 1 | 98,009 | 15 | 196,019 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number a_{i, j} is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1.
A chip is initially in the cell (1, 1), and it will be moved to the cell (n, m). During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is (x, y), then after the move it can be either (x + 1, y) or (x, y + 1)). The chip cannot leave the matrix.
Consider each path of the chip from (1, 1) to (n, m). A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.
Your goal is to change the values in the minimum number of cells so that every path is palindromic.
Input
The first line contains one integer t (1 ≤ t ≤ 200) — the number of test cases.
The first line of each test case contains two integers n and m (2 ≤ n, m ≤ 30) — the dimensions of the matrix.
Then n lines follow, the i-th line contains m integers a_{i, 1}, a_{i, 2}, ..., a_{i, m} (0 ≤ a_{i, j} ≤ 1).
Output
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
Example
Input
4
2 2
1 1
0 1
2 3
1 1 0
1 0 0
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
3 5
1 0 1 0 0
1 1 1 1 0
0 0 1 0 0
Output
0
3
4
4
Note
The resulting matrices in the first three test cases:
\begin{pmatrix} 1 & 1\\\ 0 & 1 \end{pmatrix} \begin{pmatrix} 0 & 0 & 0\\\ 0 & 0 & 0 \end{pmatrix} \begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix} | instruction | 0 | 98,050 | 15 | 196,100 |
Tags: greedy, math
Correct Solution:
```
import sys
input = sys.stdin.readline
import math
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input().strip()
return(list(s[:len(s)]))
def invr():
return(map(int,input().strip().split()))
def from_file(f):
return f.readline
def solution(n, m, A):
# max path length
L = n + m - 1
T = []
for l in range(1,L+1):
c = [0, 0]
for i in range(min(l, n)):
# i + j + 1 = path lenght
j = l - i - 1
if j >= m:
continue
c[A[i][j]] += 1
T.append(c)
res = 0
for l in range(1, L//2+1):
res += min(T[l-1][0] + T[m+n-l-1][0], T[l-1][1] + T[n+m-l-1][1])
return res
# with open('3.txt') as f:
# input = from_file(f)
t = inp()
for _ in range(t):
n, m = invr()
A = []
for _ in range(n):
A.append(inlt())
print(solution(n, m, A))
``` | output | 1 | 98,050 | 15 | 196,101 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number a_{i, j} is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1.
A chip is initially in the cell (1, 1), and it will be moved to the cell (n, m). During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is (x, y), then after the move it can be either (x + 1, y) or (x, y + 1)). The chip cannot leave the matrix.
Consider each path of the chip from (1, 1) to (n, m). A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.
Your goal is to change the values in the minimum number of cells so that every path is palindromic.
Input
The first line contains one integer t (1 ≤ t ≤ 200) — the number of test cases.
The first line of each test case contains two integers n and m (2 ≤ n, m ≤ 30) — the dimensions of the matrix.
Then n lines follow, the i-th line contains m integers a_{i, 1}, a_{i, 2}, ..., a_{i, m} (0 ≤ a_{i, j} ≤ 1).
Output
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
Example
Input
4
2 2
1 1
0 1
2 3
1 1 0
1 0 0
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
3 5
1 0 1 0 0
1 1 1 1 0
0 0 1 0 0
Output
0
3
4
4
Note
The resulting matrices in the first three test cases:
\begin{pmatrix} 1 & 1\\\ 0 & 1 \end{pmatrix} \begin{pmatrix} 0 & 0 & 0\\\ 0 & 0 & 0 \end{pmatrix} \begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix} | instruction | 0 | 98,051 | 15 | 196,102 |
Tags: greedy, math
Correct Solution:
```
t = int(input())
for _ in range(t):
nm = list(map(int, input().split()))
n, m = nm
mat = []
for i in range(n):
mat.append(list(map(int, input().split()))[::-1])
res = 0
diags = []
for i in range(2 * max(n, m) - 1):
diag = []
for j in range(i+1):
if max(n, m)-j-1 < 0 or i-j < 0:
continue
try:
diag.append(mat[max(n, m)-j-1][i-j])
except IndexError:
pass
if diag:
diags.append(diag)
for i in range(len(diags) // 2):
ones = diags[i].count(1) + diags[-i-1].count(1)
zeros = diags[i].count(0) + diags[-i-1].count(0)
res += min(ones, zeros)
print(res)
``` | output | 1 | 98,051 | 15 | 196,103 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number a_{i, j} is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1.
A chip is initially in the cell (1, 1), and it will be moved to the cell (n, m). During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is (x, y), then after the move it can be either (x + 1, y) or (x, y + 1)). The chip cannot leave the matrix.
Consider each path of the chip from (1, 1) to (n, m). A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.
Your goal is to change the values in the minimum number of cells so that every path is palindromic.
Input
The first line contains one integer t (1 ≤ t ≤ 200) — the number of test cases.
The first line of each test case contains two integers n and m (2 ≤ n, m ≤ 30) — the dimensions of the matrix.
Then n lines follow, the i-th line contains m integers a_{i, 1}, a_{i, 2}, ..., a_{i, m} (0 ≤ a_{i, j} ≤ 1).
Output
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
Example
Input
4
2 2
1 1
0 1
2 3
1 1 0
1 0 0
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
3 5
1 0 1 0 0
1 1 1 1 0
0 0 1 0 0
Output
0
3
4
4
Note
The resulting matrices in the first three test cases:
\begin{pmatrix} 1 & 1\\\ 0 & 1 \end{pmatrix} \begin{pmatrix} 0 & 0 & 0\\\ 0 & 0 & 0 \end{pmatrix} \begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix} | instruction | 0 | 98,052 | 15 | 196,104 |
Tags: greedy, math
Correct Solution:
```
for _ in range(int(input())):
n,m=map(int,input().split())
l=[]
for i in range(n):
l.append(list(map(int,input().split())))
a1=[0]*(m+n-1)
a2=[0]*(m+n-1)
for i in range(n):
for j in range(m):
a2[i+j]+=1
for i in range(n):
for j in range(m):
a1[i+j]+=l[i][j]
ans=0
vi=n+m-1
for i in range(vi//2):
t=a1[i]+a1[vi-i-1]
ans+=min(t,(2*a2[i])-t)
print(ans)
``` | output | 1 | 98,052 | 15 | 196,105 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number a_{i, j} is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1.
A chip is initially in the cell (1, 1), and it will be moved to the cell (n, m). During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is (x, y), then after the move it can be either (x + 1, y) or (x, y + 1)). The chip cannot leave the matrix.
Consider each path of the chip from (1, 1) to (n, m). A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.
Your goal is to change the values in the minimum number of cells so that every path is palindromic.
Input
The first line contains one integer t (1 ≤ t ≤ 200) — the number of test cases.
The first line of each test case contains two integers n and m (2 ≤ n, m ≤ 30) — the dimensions of the matrix.
Then n lines follow, the i-th line contains m integers a_{i, 1}, a_{i, 2}, ..., a_{i, m} (0 ≤ a_{i, j} ≤ 1).
Output
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
Example
Input
4
2 2
1 1
0 1
2 3
1 1 0
1 0 0
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
3 5
1 0 1 0 0
1 1 1 1 0
0 0 1 0 0
Output
0
3
4
4
Note
The resulting matrices in the first three test cases:
\begin{pmatrix} 1 & 1\\\ 0 & 1 \end{pmatrix} \begin{pmatrix} 0 & 0 & 0\\\ 0 & 0 & 0 \end{pmatrix} \begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix} | instruction | 0 | 98,053 | 15 | 196,106 |
Tags: greedy, math
Correct Solution:
```
for t in range(int(input())):
n, m = [int(x) for x in input().split()]
data = [(0, 0)] * (m + n - 1)
for i in range(n):
a = [int(x) for x in input().split()]
for j in range(m):
data[i + j] = (data[i + j][0] + 1, data[i + j][1] + a[j])
ans = 0
for i in range((m + n - 1) // 2):
ans += min(data[i][1] + data[m + n - 2 - i][1], data[i][0] + data[m + n - 2 - i][0] - data[i][1] - data[m + n - 2 - i][1])
print(ans)
``` | output | 1 | 98,053 | 15 | 196,107 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number a_{i, j} is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1.
A chip is initially in the cell (1, 1), and it will be moved to the cell (n, m). During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is (x, y), then after the move it can be either (x + 1, y) or (x, y + 1)). The chip cannot leave the matrix.
Consider each path of the chip from (1, 1) to (n, m). A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.
Your goal is to change the values in the minimum number of cells so that every path is palindromic.
Input
The first line contains one integer t (1 ≤ t ≤ 200) — the number of test cases.
The first line of each test case contains two integers n and m (2 ≤ n, m ≤ 30) — the dimensions of the matrix.
Then n lines follow, the i-th line contains m integers a_{i, 1}, a_{i, 2}, ..., a_{i, m} (0 ≤ a_{i, j} ≤ 1).
Output
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
Example
Input
4
2 2
1 1
0 1
2 3
1 1 0
1 0 0
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
3 5
1 0 1 0 0
1 1 1 1 0
0 0 1 0 0
Output
0
3
4
4
Note
The resulting matrices in the first three test cases:
\begin{pmatrix} 1 & 1\\\ 0 & 1 \end{pmatrix} \begin{pmatrix} 0 & 0 & 0\\\ 0 & 0 & 0 \end{pmatrix} \begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix} | instruction | 0 | 98,054 | 15 | 196,108 |
Tags: greedy, math
Correct Solution:
```
from sys import stdin
input = stdin.buffer.readline
for _ in range(int(input())):
n, m = map(int, input().split())
a = [[int(i) for i in input().split()] for j in range(n)]
s, l = [0] * (n + m - 2), [0] * (n + m - 2)
for i in range(n):
for j in range(m):
if i + j == n + m - i - j - 2:
continue
x = min(i + j, n + m - 2 - i - j)
s[x] += a[i][j] == 1
l[x] += 1
#print(s, l, a)
print(sum(min(s[x], l[x] - s[x]) for x in range(n + m - 2)))
``` | output | 1 | 98,054 | 15 | 196,109 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number a_{i, j} is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1.
A chip is initially in the cell (1, 1), and it will be moved to the cell (n, m). During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is (x, y), then after the move it can be either (x + 1, y) or (x, y + 1)). The chip cannot leave the matrix.
Consider each path of the chip from (1, 1) to (n, m). A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.
Your goal is to change the values in the minimum number of cells so that every path is palindromic.
Input
The first line contains one integer t (1 ≤ t ≤ 200) — the number of test cases.
The first line of each test case contains two integers n and m (2 ≤ n, m ≤ 30) — the dimensions of the matrix.
Then n lines follow, the i-th line contains m integers a_{i, 1}, a_{i, 2}, ..., a_{i, m} (0 ≤ a_{i, j} ≤ 1).
Output
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
Example
Input
4
2 2
1 1
0 1
2 3
1 1 0
1 0 0
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
3 5
1 0 1 0 0
1 1 1 1 0
0 0 1 0 0
Output
0
3
4
4
Note
The resulting matrices in the first three test cases:
\begin{pmatrix} 1 & 1\\\ 0 & 1 \end{pmatrix} \begin{pmatrix} 0 & 0 & 0\\\ 0 & 0 & 0 \end{pmatrix} \begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix} | instruction | 0 | 98,055 | 15 | 196,110 |
Tags: greedy, math
Correct Solution:
```
from sys import stdin
from collections import defaultdict as dd
from collections import deque as dq
import itertools as it
from math import sqrt, log, log2
from fractions import Fraction
t = int(input())
for _ in range(t):
n, m = map(int, input().split())
matrix = []
for r in range(n):
row = list(map(int, input().split()))
matrix.append(row)
ans = 0
for dist in range(1 + (m+n-2)//2):
beg = {0: 0, 1: 0}
end = {0: 0, 1: 0}
visited = []
for i in range(min(dist + 1, n)):
j = dist - i
if j < m :
beg[matrix[0 + i][0 + j]] += 1
end[matrix[n-1 - i][m-1 - j]] += 1
visited.append((i, j))
visited.append((n-1-i, m-1-j))
# print(i, n-1-i, j, m-1-j)
# print(visited)
if len(visited)!= 2*len(set(visited)):
if beg[0] + end[0] >= beg[1] + end[1]:
ans += beg[1] + end[1]
else:
ans += beg[0] + end[0]
# print(dist, beg, end, ans)
print(ans)
``` | output | 1 | 98,055 | 15 | 196,111 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number a_{i, j} is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1.
A chip is initially in the cell (1, 1), and it will be moved to the cell (n, m). During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is (x, y), then after the move it can be either (x + 1, y) or (x, y + 1)). The chip cannot leave the matrix.
Consider each path of the chip from (1, 1) to (n, m). A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.
Your goal is to change the values in the minimum number of cells so that every path is palindromic.
Input
The first line contains one integer t (1 ≤ t ≤ 200) — the number of test cases.
The first line of each test case contains two integers n and m (2 ≤ n, m ≤ 30) — the dimensions of the matrix.
Then n lines follow, the i-th line contains m integers a_{i, 1}, a_{i, 2}, ..., a_{i, m} (0 ≤ a_{i, j} ≤ 1).
Output
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
Example
Input
4
2 2
1 1
0 1
2 3
1 1 0
1 0 0
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
3 5
1 0 1 0 0
1 1 1 1 0
0 0 1 0 0
Output
0
3
4
4
Note
The resulting matrices in the first three test cases:
\begin{pmatrix} 1 & 1\\\ 0 & 1 \end{pmatrix} \begin{pmatrix} 0 & 0 & 0\\\ 0 & 0 & 0 \end{pmatrix} \begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix} | instruction | 0 | 98,056 | 15 | 196,112 |
Tags: greedy, math
Correct Solution:
```
import sys
input=lambda: sys.stdin.readline().rstrip()
t=int(input())
for _ in range(t):
n,m=map(int,input().split())
Z=[0]*(n+m-1)
O=[0]*(n+m-1)
for i in range(n):
A=[int(j) for j in input().split()]
for j,a in enumerate(A):
if a==0:
Z[i+j]+=1
else:
O[i+j]+=1
ans=0
for i in range((n+m-1)//2):
x,y=Z[i]+Z[n+m-2-i],O[i]+O[n+m-2-i]
ans+=min(x,y)
print(ans)
``` | output | 1 | 98,056 | 15 | 196,113 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number a_{i, j} is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1.
A chip is initially in the cell (1, 1), and it will be moved to the cell (n, m). During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is (x, y), then after the move it can be either (x + 1, y) or (x, y + 1)). The chip cannot leave the matrix.
Consider each path of the chip from (1, 1) to (n, m). A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.
Your goal is to change the values in the minimum number of cells so that every path is palindromic.
Input
The first line contains one integer t (1 ≤ t ≤ 200) — the number of test cases.
The first line of each test case contains two integers n and m (2 ≤ n, m ≤ 30) — the dimensions of the matrix.
Then n lines follow, the i-th line contains m integers a_{i, 1}, a_{i, 2}, ..., a_{i, m} (0 ≤ a_{i, j} ≤ 1).
Output
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
Example
Input
4
2 2
1 1
0 1
2 3
1 1 0
1 0 0
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
3 5
1 0 1 0 0
1 1 1 1 0
0 0 1 0 0
Output
0
3
4
4
Note
The resulting matrices in the first three test cases:
\begin{pmatrix} 1 & 1\\\ 0 & 1 \end{pmatrix} \begin{pmatrix} 0 & 0 & 0\\\ 0 & 0 & 0 \end{pmatrix} \begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix} | instruction | 0 | 98,057 | 15 | 196,114 |
Tags: greedy, math
Correct Solution:
```
from sys import *
input = stdin.readline
for _ in range(int(input())):
n,m = map(int,input().split())
a = []
for _ in range(n):
b = list(map(int,input().split()))
a.append(b)
sn = 0
if(a[0][0] != a[n-1][m-1]):
sn += 1
a[0][0] = 0
a[n-1][m-1] = 0
q1 = [(0,0)]
q2 = [(n-1,m-1)]
x1,y1 = [0,1],[1,0]
x2,y2 = [-1,0],[0,-1]
level = 0
while(q1 and q2):
# level += 1
# print(level,q1,q2,sn)
l1 = set()
while(q1):
c,d = q1.pop()
for i in range(2):
c1,d1 = c+x1[i],d+y1[i]
if(0<=c1<=n-1 and 0<=d1<=m-1):
l1.add((c1,d1))
l2 = set()
while(q2):
c,d = q2.pop()
for i in range(2):
c2,d2 = c+x2[i],d+y2[i]
if(0<=c2<=n-1 and 0<=d2<=m-1):
l2.add((c2,d2))
q1 = list(l1)
q2 = list(l2)
s = set()
s = s.union((l1-l2),(l2-l1))
s = list(s)
zero,one = 0,0
for i in range(len(s)):
u,v = s[i][0],s[i][1]
if(a[u][v] == 0):
zero += 1
else:
one += 1
if(zero>one):
ch = 0
else:
ch = 1
for i in range(len(s)):
u,v = s[i][0],s[i][1]
if(a[u][v] != ch):
a[u][v] = (a[u][v]+1)%2
sn += 1
# print(s,s1,s2)
# print()
print(sn)
``` | output | 1 | 98,057 | 15 | 196,115 |
Provide tags and a correct Python 2 solution for this coding contest problem.
You are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number a_{i, j} is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1.
A chip is initially in the cell (1, 1), and it will be moved to the cell (n, m). During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is (x, y), then after the move it can be either (x + 1, y) or (x, y + 1)). The chip cannot leave the matrix.
Consider each path of the chip from (1, 1) to (n, m). A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.
Your goal is to change the values in the minimum number of cells so that every path is palindromic.
Input
The first line contains one integer t (1 ≤ t ≤ 200) — the number of test cases.
The first line of each test case contains two integers n and m (2 ≤ n, m ≤ 30) — the dimensions of the matrix.
Then n lines follow, the i-th line contains m integers a_{i, 1}, a_{i, 2}, ..., a_{i, m} (0 ≤ a_{i, j} ≤ 1).
Output
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
Example
Input
4
2 2
1 1
0 1
2 3
1 1 0
1 0 0
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
3 5
1 0 1 0 0
1 1 1 1 0
0 0 1 0 0
Output
0
3
4
4
Note
The resulting matrices in the first three test cases:
\begin{pmatrix} 1 & 1\\\ 0 & 1 \end{pmatrix} \begin{pmatrix} 0 & 0 & 0\\\ 0 & 0 & 0 \end{pmatrix} \begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix} | instruction | 0 | 98,058 | 15 | 196,116 |
Tags: greedy, math
Correct Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
mod=10**9+7
def ni():
return int(raw_input())
def li():
return map(int,raw_input().split())
def pn(n):
stdout.write(str(n)+'\n')
def pa(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return map(int,stdin.read().split())
range = xrange # not for python 3.0+
for t in range(ni()):
n,m=li()
d=defaultdict(Counter)
for i in range(n):
arr=li()
for j in range(m):
d1=i+j
d2=n+m-2-i-j
if d1!=d2:
d[min(i+j,n+m-i-j-2)][arr[j]]+=1
ans=0
for i in d:
#print i,d[i]
ans+=min(d[i][0],d[i][1])
pn(ans)
``` | output | 1 | 98,058 | 15 | 196,117 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number a_{i, j} is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1.
A chip is initially in the cell (1, 1), and it will be moved to the cell (n, m). During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is (x, y), then after the move it can be either (x + 1, y) or (x, y + 1)). The chip cannot leave the matrix.
Consider each path of the chip from (1, 1) to (n, m). A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.
Your goal is to change the values in the minimum number of cells so that every path is palindromic.
Input
The first line contains one integer t (1 ≤ t ≤ 200) — the number of test cases.
The first line of each test case contains two integers n and m (2 ≤ n, m ≤ 30) — the dimensions of the matrix.
Then n lines follow, the i-th line contains m integers a_{i, 1}, a_{i, 2}, ..., a_{i, m} (0 ≤ a_{i, j} ≤ 1).
Output
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
Example
Input
4
2 2
1 1
0 1
2 3
1 1 0
1 0 0
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
3 5
1 0 1 0 0
1 1 1 1 0
0 0 1 0 0
Output
0
3
4
4
Note
The resulting matrices in the first three test cases:
\begin{pmatrix} 1 & 1\\\ 0 & 1 \end{pmatrix} \begin{pmatrix} 0 & 0 & 0\\\ 0 & 0 & 0 \end{pmatrix} \begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}
Submitted Solution:
```
#!/usr/bin/env python3
import sys
from math import *
from collections import defaultdict
from queue import deque # Queues
from heapq import heappush, heappop # Priority Queues
# parse
lines = [line.strip() for line in sys.stdin.readlines()]
T = int(lines[0])
cur = 1
for t in range(T):
n, m = map(int, lines[cur].split())
A = [list(map(int, line.split())) for line in lines[cur+1:cur+1+n]]
cur += 1 + n
ret = 0
for s in range((n + m - 3) // 2 + 1):
t = n + m - 2 - s
a, b = 0, 0
for i in range(n):
for j in [s-i, t-i]:
if 0 <= j < m:
if A[i][j] == 0:
a += 1
else:
b += 1
ret += min(a, b)
print(ret)
``` | instruction | 0 | 98,059 | 15 | 196,118 |
Yes | output | 1 | 98,059 | 15 | 196,119 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number a_{i, j} is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1.
A chip is initially in the cell (1, 1), and it will be moved to the cell (n, m). During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is (x, y), then after the move it can be either (x + 1, y) or (x, y + 1)). The chip cannot leave the matrix.
Consider each path of the chip from (1, 1) to (n, m). A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.
Your goal is to change the values in the minimum number of cells so that every path is palindromic.
Input
The first line contains one integer t (1 ≤ t ≤ 200) — the number of test cases.
The first line of each test case contains two integers n and m (2 ≤ n, m ≤ 30) — the dimensions of the matrix.
Then n lines follow, the i-th line contains m integers a_{i, 1}, a_{i, 2}, ..., a_{i, m} (0 ≤ a_{i, j} ≤ 1).
Output
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
Example
Input
4
2 2
1 1
0 1
2 3
1 1 0
1 0 0
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
3 5
1 0 1 0 0
1 1 1 1 0
0 0 1 0 0
Output
0
3
4
4
Note
The resulting matrices in the first three test cases:
\begin{pmatrix} 1 & 1\\\ 0 & 1 \end{pmatrix} \begin{pmatrix} 0 & 0 & 0\\\ 0 & 0 & 0 \end{pmatrix} \begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}
Submitted Solution:
```
tests = int (input())
for test in range (tests):
rows, cols = map (int, input().split())
a = []
for i in range (rows):
b = list(map (int, input().split()))
a.append (b)
cnt = [[0 for j in range (2)] for i in range (rows + cols)]
for r in range (rows):
for c in range (cols):
if r + c != rows + cols - r - c - 2:
cnt[min (r + c, rows + cols - r - c - 2)][a[r][c]] += 1
res = 0
for i in cnt:
res += min (i[0], i[1])
print (res)
``` | instruction | 0 | 98,060 | 15 | 196,120 |
Yes | output | 1 | 98,060 | 15 | 196,121 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number a_{i, j} is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1.
A chip is initially in the cell (1, 1), and it will be moved to the cell (n, m). During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is (x, y), then after the move it can be either (x + 1, y) or (x, y + 1)). The chip cannot leave the matrix.
Consider each path of the chip from (1, 1) to (n, m). A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.
Your goal is to change the values in the minimum number of cells so that every path is palindromic.
Input
The first line contains one integer t (1 ≤ t ≤ 200) — the number of test cases.
The first line of each test case contains two integers n and m (2 ≤ n, m ≤ 30) — the dimensions of the matrix.
Then n lines follow, the i-th line contains m integers a_{i, 1}, a_{i, 2}, ..., a_{i, m} (0 ≤ a_{i, j} ≤ 1).
Output
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
Example
Input
4
2 2
1 1
0 1
2 3
1 1 0
1 0 0
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
3 5
1 0 1 0 0
1 1 1 1 0
0 0 1 0 0
Output
0
3
4
4
Note
The resulting matrices in the first three test cases:
\begin{pmatrix} 1 & 1\\\ 0 & 1 \end{pmatrix} \begin{pmatrix} 0 & 0 & 0\\\ 0 & 0 & 0 \end{pmatrix} \begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}
Submitted Solution:
```
t = int(input())
for i in range(t):
n, m = list(map(int, input().split(' ')))
board = [0] * n
for j in range(n):
row = list(map(int, input().split(' ')))
board[j] = row
zeros = [0] * (m + n - 1)
ones = [0] * (m + n - 1)
for row in range(n):
for col in range(m):
if board[row][col] == 0:
zeros[row + col] += 1
else:
ones[row + col] += 1
changes = 0
for step in range((m + n - 1) // 2):
current_zeros = zeros[step] + zeros[m + n - 2 - step]
current_ones = ones[step] + ones[m + n - 2 - step]
changes += min(current_ones, current_zeros)
print(changes)
``` | instruction | 0 | 98,061 | 15 | 196,122 |
Yes | output | 1 | 98,061 | 15 | 196,123 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number a_{i, j} is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1.
A chip is initially in the cell (1, 1), and it will be moved to the cell (n, m). During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is (x, y), then after the move it can be either (x + 1, y) or (x, y + 1)). The chip cannot leave the matrix.
Consider each path of the chip from (1, 1) to (n, m). A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.
Your goal is to change the values in the minimum number of cells so that every path is palindromic.
Input
The first line contains one integer t (1 ≤ t ≤ 200) — the number of test cases.
The first line of each test case contains two integers n and m (2 ≤ n, m ≤ 30) — the dimensions of the matrix.
Then n lines follow, the i-th line contains m integers a_{i, 1}, a_{i, 2}, ..., a_{i, m} (0 ≤ a_{i, j} ≤ 1).
Output
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
Example
Input
4
2 2
1 1
0 1
2 3
1 1 0
1 0 0
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
3 5
1 0 1 0 0
1 1 1 1 0
0 0 1 0 0
Output
0
3
4
4
Note
The resulting matrices in the first three test cases:
\begin{pmatrix} 1 & 1\\\ 0 & 1 \end{pmatrix} \begin{pmatrix} 0 & 0 & 0\\\ 0 & 0 & 0 \end{pmatrix} \begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}
Submitted Solution:
```
# https://codeforces.com/contest/1366/problem/C
# https://codeforces.com/blog/entry/78735
def solve():
# shovel: 2 a + b
# sword: a + 2 b
# max num. of possible ones
n, m = map(int, input().split())
grid = [list(map(int, input().split())) for _ in range(n)]
# 距離group (0, 1, ..., n + m - 2)
counter = [[0, 0] for _ in range(n + m - 1)]
for i in range(n):
for j in range(m):
counter[i + j][grid[i][j]] += 1
ans = 0
for p in range(n + m - 1):
q = n + m - 2 - p
if p >= q:
continue
# group (p, q) -> 0
c1 = counter[p][0] + counter[q][0]
# group (p, q) -> 1
c2 = counter[p][1] + counter[q][1]
ans += min(c1, c2)
print(ans)
if __name__ == '__main__':
t = int(input())
while t > 0:
t -= 1
solve()
``` | instruction | 0 | 98,062 | 15 | 196,124 |
Yes | output | 1 | 98,062 | 15 | 196,125 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number a_{i, j} is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1.
A chip is initially in the cell (1, 1), and it will be moved to the cell (n, m). During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is (x, y), then after the move it can be either (x + 1, y) or (x, y + 1)). The chip cannot leave the matrix.
Consider each path of the chip from (1, 1) to (n, m). A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.
Your goal is to change the values in the minimum number of cells so that every path is palindromic.
Input
The first line contains one integer t (1 ≤ t ≤ 200) — the number of test cases.
The first line of each test case contains two integers n and m (2 ≤ n, m ≤ 30) — the dimensions of the matrix.
Then n lines follow, the i-th line contains m integers a_{i, 1}, a_{i, 2}, ..., a_{i, m} (0 ≤ a_{i, j} ≤ 1).
Output
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
Example
Input
4
2 2
1 1
0 1
2 3
1 1 0
1 0 0
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
3 5
1 0 1 0 0
1 1 1 1 0
0 0 1 0 0
Output
0
3
4
4
Note
The resulting matrices in the first three test cases:
\begin{pmatrix} 1 & 1\\\ 0 & 1 \end{pmatrix} \begin{pmatrix} 0 & 0 & 0\\\ 0 & 0 & 0 \end{pmatrix} \begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}
Submitted Solution:
```
t = int(input())
for i in range(t):
a,b = map(int,input().split())
arr = []
for i in range(a):
d = list(map(int,input().split()))
arr.append(d)
su1 = 0
su2 = 0
count = 0
if b%2 == 0:
l = b//2
else:
l = b//2+1
for i in range(l):
x = 0
y = i
c1 = 1
c2 = 1
su1 = arr[x][y]
su2 = arr[a-x-1][b-y-1]
r = a-x-1
c = b-y-1
while(x+1<a and y-1>=0):
su1 += arr[x+1][y-1]
x = x+1
y = y-1
c1+=1
while(r-1>=0 and c+1<b):
su2 += arr[r-1][c+1]
r = r-1
c = c+1
c2 +=1
if su1 == 0:
count += su2
elif su2 == 0:
count += su1
else:
count += c1-su1+c2-su2
print(count)
``` | instruction | 0 | 98,063 | 15 | 196,126 |
No | output | 1 | 98,063 | 15 | 196,127 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number a_{i, j} is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1.
A chip is initially in the cell (1, 1), and it will be moved to the cell (n, m). During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is (x, y), then after the move it can be either (x + 1, y) or (x, y + 1)). The chip cannot leave the matrix.
Consider each path of the chip from (1, 1) to (n, m). A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.
Your goal is to change the values in the minimum number of cells so that every path is palindromic.
Input
The first line contains one integer t (1 ≤ t ≤ 200) — the number of test cases.
The first line of each test case contains two integers n and m (2 ≤ n, m ≤ 30) — the dimensions of the matrix.
Then n lines follow, the i-th line contains m integers a_{i, 1}, a_{i, 2}, ..., a_{i, m} (0 ≤ a_{i, j} ≤ 1).
Output
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
Example
Input
4
2 2
1 1
0 1
2 3
1 1 0
1 0 0
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
3 5
1 0 1 0 0
1 1 1 1 0
0 0 1 0 0
Output
0
3
4
4
Note
The resulting matrices in the first three test cases:
\begin{pmatrix} 1 & 1\\\ 0 & 1 \end{pmatrix} \begin{pmatrix} 0 & 0 & 0\\\ 0 & 0 & 0 \end{pmatrix} \begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}
Submitted Solution:
```
import math
#import math
#------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now----------------------------------------------------import math
for i in range(int(input())):
n,m=map(int,input().split())
mat=[]
for i in range(n):
mat.append(list(map(int,input().split())))
ans=0
for i in range((n+m-1)//2):
diff=0
ct=i
if ct>m-1:
rt+=ct-(m-1)
ct=m-1
rt=0
rt1=n-1-i
ct1=m-1
if rt1<0:
ct1+=rt1
rt1=0
#print(rt,ct,rt1,ct1)
for j in range(min(i+1,n,m)):
if rt==rt1 and ct==ct1:
break
#print(rt,ct,rt1,ct1)
diff+=mat[rt][ct]+mat[rt1][ct1]
rt+=1
ct-=1
rt1+=1
ct1-=1
ans+=min(2*min(n,m,(i+1))-diff,diff)
#print(ans,diff)
print(ans)
``` | instruction | 0 | 98,064 | 15 | 196,128 |
No | output | 1 | 98,064 | 15 | 196,129 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number a_{i, j} is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1.
A chip is initially in the cell (1, 1), and it will be moved to the cell (n, m). During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is (x, y), then after the move it can be either (x + 1, y) or (x, y + 1)). The chip cannot leave the matrix.
Consider each path of the chip from (1, 1) to (n, m). A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.
Your goal is to change the values in the minimum number of cells so that every path is palindromic.
Input
The first line contains one integer t (1 ≤ t ≤ 200) — the number of test cases.
The first line of each test case contains two integers n and m (2 ≤ n, m ≤ 30) — the dimensions of the matrix.
Then n lines follow, the i-th line contains m integers a_{i, 1}, a_{i, 2}, ..., a_{i, m} (0 ≤ a_{i, j} ≤ 1).
Output
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
Example
Input
4
2 2
1 1
0 1
2 3
1 1 0
1 0 0
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
3 5
1 0 1 0 0
1 1 1 1 0
0 0 1 0 0
Output
0
3
4
4
Note
The resulting matrices in the first three test cases:
\begin{pmatrix} 1 & 1\\\ 0 & 1 \end{pmatrix} \begin{pmatrix} 0 & 0 & 0\\\ 0 & 0 & 0 \end{pmatrix} \begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}
Submitted Solution:
```
import sys
input = sys.stdin.readline
x = int(input())
for i in range(x):
a,b = list(map(int, input().split()))
mat = []
mat_flip = []
for j in range(a):
temp = list(map(int, input().split()))
mat.append(temp)
mat_flip.append(temp[::-1])
mat_flip = mat_flip[::-1]
p = max(a,b) // 2
ans = 0
if a%2==0 and b%2==0:
p = (b-1) //2
for j in range(p):
a1 = []
a2 = []
ok = 1
for e in range(j+2):
f = j+1-e
if e>=0 and e<a:
if f>=0 and f<b:
a1.append(mat[e][f])
a2.append(mat_flip[e][f])
l= len(a1)
#print(a1,a2)
m = min(sum(a1) + sum(a2), 2*l - (sum(a1) + sum(a2)))
ans +=m
if mat[0][0] != mat_flip[0][0]:
ans += 1
print(ans)
``` | instruction | 0 | 98,065 | 15 | 196,130 |
No | output | 1 | 98,065 | 15 | 196,131 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number a_{i, j} is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1.
A chip is initially in the cell (1, 1), and it will be moved to the cell (n, m). During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is (x, y), then after the move it can be either (x + 1, y) or (x, y + 1)). The chip cannot leave the matrix.
Consider each path of the chip from (1, 1) to (n, m). A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.
Your goal is to change the values in the minimum number of cells so that every path is palindromic.
Input
The first line contains one integer t (1 ≤ t ≤ 200) — the number of test cases.
The first line of each test case contains two integers n and m (2 ≤ n, m ≤ 30) — the dimensions of the matrix.
Then n lines follow, the i-th line contains m integers a_{i, 1}, a_{i, 2}, ..., a_{i, m} (0 ≤ a_{i, j} ≤ 1).
Output
For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.
Example
Input
4
2 2
1 1
0 1
2 3
1 1 0
1 0 0
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
3 5
1 0 1 0 0
1 1 1 1 0
0 0 1 0 0
Output
0
3
4
4
Note
The resulting matrices in the first three test cases:
\begin{pmatrix} 1 & 1\\\ 0 & 1 \end{pmatrix} \begin{pmatrix} 0 & 0 & 0\\\ 0 & 0 & 0 \end{pmatrix} \begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}
Submitted Solution:
```
from sys import stdin
from collections import deque
# https://codeforces.com/contest/1354/status/D
mod = 10**9 + 7
import sys
import random
# sys.setrecursionlimit(10**6)
from queue import PriorityQueue
# def rl():
# return [int(w) for w in stdin.readline().split()]
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt,factorial,gcd,log2,inf,ceil
# map(int,input().split())
# # l = list(map(int,input().split()))
# from itertools import permutations
import heapq
# input = lambda: sys.stdin.readline().rstrip()
input = lambda : sys.stdin.readline().rstrip()
from sys import stdin, stdout
from heapq import heapify, heappush, heappop
from itertools import permutations
from math import factorial as f
# def ncr(x, y):
# return f(x) // (f(y) * f(x - y))
def ncr(n, r, p):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,
p - 2, p)) % p
import sys
# input = sys.stdin.readline
# LCA
# def bfs(na):
#
# queue = [na]
# boo[na] = True
# level[na] = 0
#
# while queue!=[]:
#
# z = queue.pop(0)
#
# for i in hash[z]:
#
# if not boo[i]:
#
# queue.append(i)
# level[i] = level[z] + 1
# boo[i] = True
# dp[i][0] = z
#
#
#
# def prec(n):
#
# for i in range(1,20):
#
# for j in range(1,n+1):
# if dp[j][i-1]!=-1:
# dp[j][i] = dp[dp[j][i-1]][i-1]
#
#
# def lca(u,v):
# if level[v] < level[u]:
# u,v = v,u
#
# diff = level[v] - level[u]
#
#
# for i in range(20):
# if ((diff>>i)&1):
# v = dp[v][i]
#
#
# if u == v:
# return u
#
#
# for i in range(19,-1,-1):
# # print(i)
# if dp[u][i] != dp[v][i]:
#
# u = dp[u][i]
# v = dp[v][i]
#
#
# return dp[u][0]
#
# dp = []
#
#
# n = int(input())
#
# for i in range(n + 10):
#
# ka = [-1]*(20)
# dp.append(ka)
# class FenwickTree:
# def __init__(self, x):
# """transform list into BIT"""
# self.bit = x
# for i in range(len(x)):
# j = i | (i + 1)
# if j < len(x):
# x[j] += x[i]
#
# def update(self, idx, x):
# """updates bit[idx] += x"""
# while idx < len(self.bit):
# self.bit[idx] += x
# idx |= idx + 1
#
# def query(self, end):
# """calc sum(bit[:end])"""
# x = 0
# while end:
# x += self.bit[end - 1]
# end &= end - 1
# return x
#
# def find_kth_smallest(self, k):
# """Find largest idx such that sum(bit[:idx]) <= k"""
# idx = -1
# for d in reversed(range(len(self.bit).bit_length())):
# right_idx = idx + (1 << d)
# if right_idx < len(self.bit) and k >= self.bit[right_idx]:
# idx = right_idx
# k -= self.bit[idx]
# return idx + 1
# import sys
# def rs(): return sys.stdin.readline().strip()
# def ri(): return int(sys.stdin.readline())
# def ria(): return list(map(int, sys.stdin.readline().split()))
# def prn(n): sys.stdout.write(str(n))
# def pia(a): sys.stdout.write(' '.join([str(s) for s in a]))
#
#
# import gc, os
#
# ii = 0
# _inp = b''
#
#
# def getchar():
# global ii, _inp
# if ii >= len(_inp):
# _inp = os.read(0, 100000)
# gc.collect()
# ii = 0
# if not _inp:
# return b' '[0]
# ii += 1
# return _inp[ii - 1]
#
#
# def input():
# c = getchar()
# if c == b'-'[0]:
# x = 0
# sign = 1
# else:
# x = c - b'0'[0]
# sign = 0
# c = getchar()
# while c >= b'0'[0]:
# x = 10 * x + c - b'0'[0]
# c = getchar()
# if c == b'\r'[0]:
# getchar()
# return -x if sign else x
# fenwick Tree
# n,q = map(int,input().split())
#
#
# l1 = list(map(int,input().split()))
#
# l2 = list(map(int,input().split()))
#
# bit = [0]*(10**6 + 1)
#
# def update(i,add,bit):
#
# while i>0 and i<len(bit):
#
# bit[i]+=add
# i = i + (i&(-i))
#
#
# def sum(i,bit):
# ans = 0
# while i>0:
#
# ans+=bit[i]
# i = i - (i & ( -i))
#
#
# return ans
#
# def find_smallest(k,bit):
#
# l = 0
# h = len(bit)
# while l<h:
#
# mid = (l+h)//2
# if k <= sum(mid,bit):
# h = mid
# else:
# l = mid + 1
#
#
# return l
#
#
# def insert(x,bit):
# update(x,1,bit)
#
# def delete(x,bit):
# update(x,-1,bit)
# fa = set()
#
# for i in l1:
# insert(i,bit)
#
#
# for i in l2:
# if i>0:
# insert(i,bit)
#
# else:
# z = find_smallest(-i,bit)
#
# delete(z,bit)
#
#
# # print(bit)
# if len(set(bit)) == 1:
# print(0)
# else:
# for i in range(1,n+1):
# z = find_smallest(i,bit)
# if z!=0:
# print(z)
# break
#
# service time problem
# def solve2(s,a,b,hash,z,cnt):
# temp = cnt.copy()
# x,y = hash[a],hash[b]
# i = 0
# j = len(s)-1
#
# while z:
#
# if s[j] - y>=x-s[i]:
# if temp[s[j]]-1 == 0:
# j-=1
# temp[s[j]]-=1
# z-=1
#
#
# else:
# if temp[s[i]]-1 == 0:
# i+=1
#
# temp[s[i]]-=1
# z-=1
#
# return s[i:j+1]
#
#
#
#
#
# def solve1(l,s,posn,z,hash):
#
# ans = []
# for i in l:
# a,b = i
# ka = solve2(s,a,b,posn,z,hash)
# ans.append(ka)
#
# return ans
#
# def consistent(input, window, min_entries, max_entries, tolerance):
#
# l = input
# n = len(l)
# l.sort()
# s = list(set(l))
# s.sort()
#
# if min_entries<=n<=max_entries:
#
# if s[-1] - s[0]<window:
# return True
# hash = defaultdict(int)
# posn = defaultdict(int)
# for i in l:
# hash[i]+=1
#
# z = (tolerance*(n))//100
# poss_window = set()
#
#
# for i in range(len(s)):
# posn[i] = l[i]
# for j in range(i+1,len(s)):
# if s[j]-s[i] == window:
# poss_window.add((s[i],s[j]))
#
# if poss_window!=set():
# print(poss_window)
# ans = solve1(poss_window,s,posn,z,hash)
# print(ans)
#
#
# else:
# pass
#
# else:
# return False
#
#
#
#
# l = list(map(int,input().split()))
#
# min_ent,max_ent = map(int,input().split())
# w = int(input())
# tol = int(input())
# consistent(l, w, min_ent, max_ent, tol)
# t = int(input())
#
# for i in range(t):
#
# n,x = map(int,input().split())
#
# l = list(map(int,input().split()))
#
# e,o = 0,0
#
# for i in l:
# if i%2 == 0:
# e+=1
# else:
# o+=1
#
# if e+o>=x and o!=0:
# z = e+o - x
# if z == 0:
# if o%2 == 0:
# print('No')
# else:
# print('Yes')
# continue
# if o%2 == 0:
# o-=1
# z-=1
# if e>=z:
# print('Yes')
# else:
# z-=e
# o-=z
# if o%2!=0:
# print('Yes')
# else:
# print('No')
#
# else:
#
# if e>=z:
# print('Yes')
# else:
# z-=e
# o-=z
# if o%2!=0:
# print('Yes')
# else:
# print('No')
# else:
# print('No')
#
#
#
#
#
#
#
# def dfs(n):
# boo[n] = True
# dp2[n] = 1
# for i in hash[n]:
# if not boo[i]:
#
# dfs(i)
# dp2[n] += dp2[i]
# print(seti)
t = int(input())
for _ in range(t):
n,m = map(int,input().split())
la = []
for i in range(n):
k = list(map(int,input().split()))
la.append(k)
i,j = 0,0
x,y = n-1,m-1
cnt = 0
ha = n-1
ans = 0
if n>=m:
cnt = 0
ha = n-1
while cnt<=(n)//2:
if i == n-1 and j == 0 and x == 0 and y == m-1:
break
hash = defaultdict(int)
while i>=0 and j<m:
hash[la[i][j]]+=1
i-=1
j+=1
while x<=n-1 and y>=0:
hash[la[x][y]]+=1
x+=1
y-=1
a,b = hash[0],hash[1]
ans+=min(a,b)
cnt+=1
ha-=1
i = cnt
x = ha
j = 0
y = m-1
else:
cnt = 0
ha = m-1
while cnt<=(m)//2:
hash = defaultdict(int)
while j>=0 and i<n:
# print((i,j))
hash[la[i][j]]+=1
i+=1
j-=1
# print(i,j)
while y<=m-1 and x>=0:
# print(y)
hash[la[x][y]]+=1
x-=1
y+=1
a,b = hash[0],hash[1]
ans+=min(a,b)
cnt+=1
ha-=1
j = cnt
y = ha
i = 0
x = n-1
print(ans)
``` | instruction | 0 | 98,066 | 15 | 196,132 |
No | output | 1 | 98,066 | 15 | 196,133 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is an infinite 2-dimensional grid. The robot stands in cell (0, 0) and wants to reach cell (x, y). Here is a list of possible commands the robot can execute:
* move north from cell (i, j) to (i, j + 1);
* move east from cell (i, j) to (i + 1, j);
* move south from cell (i, j) to (i, j - 1);
* move west from cell (i, j) to (i - 1, j);
* stay in cell (i, j).
The robot wants to reach cell (x, y) in as few commands as possible. However, he can't execute the same command two or more times in a row.
What is the minimum number of commands required to reach (x, y) from (0, 0)?
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of testcases.
Each of the next t lines contains two integers x and y (0 ≤ x, y ≤ 10^4) — the destination coordinates of the robot.
Output
For each testcase print a single integer — the minimum number of commands required for the robot to reach (x, y) from (0, 0) if no command is allowed to be executed two or more times in a row.
Example
Input
5
5 5
3 4
7 1
0 0
2 0
Output
10
7
13
0
3
Note
The explanations for the example test:
We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively.
In the first test case, the robot can use the following sequence: NENENENENE.
In the second test case, the robot can use the following sequence: NENENEN.
In the third test case, the robot can use the following sequence: ESENENE0ENESE.
In the fourth test case, the robot doesn't need to go anywhere at all.
In the fifth test case, the robot can use the following sequence: E0E. | instruction | 0 | 98,099 | 15 | 196,198 |
Tags: math
Correct Solution:
```
for _ in range(0,int(input())):
x,y=map(int,input().split())
print(2*x if x==y else max(x,y)*2-1)
``` | output | 1 | 98,099 | 15 | 196,199 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is an infinite 2-dimensional grid. The robot stands in cell (0, 0) and wants to reach cell (x, y). Here is a list of possible commands the robot can execute:
* move north from cell (i, j) to (i, j + 1);
* move east from cell (i, j) to (i + 1, j);
* move south from cell (i, j) to (i, j - 1);
* move west from cell (i, j) to (i - 1, j);
* stay in cell (i, j).
The robot wants to reach cell (x, y) in as few commands as possible. However, he can't execute the same command two or more times in a row.
What is the minimum number of commands required to reach (x, y) from (0, 0)?
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of testcases.
Each of the next t lines contains two integers x and y (0 ≤ x, y ≤ 10^4) — the destination coordinates of the robot.
Output
For each testcase print a single integer — the minimum number of commands required for the robot to reach (x, y) from (0, 0) if no command is allowed to be executed two or more times in a row.
Example
Input
5
5 5
3 4
7 1
0 0
2 0
Output
10
7
13
0
3
Note
The explanations for the example test:
We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively.
In the first test case, the robot can use the following sequence: NENENENENE.
In the second test case, the robot can use the following sequence: NENENEN.
In the third test case, the robot can use the following sequence: ESENENE0ENESE.
In the fourth test case, the robot doesn't need to go anywhere at all.
In the fifth test case, the robot can use the following sequence: E0E. | instruction | 0 | 98,100 | 15 | 196,200 |
Tags: math
Correct Solution:
```
import sys
# import math
# import re
# from heapq import *
# from collections import defaultdict as dd
# from collections import OrderedDict as odict
# from collections import Counter as cc
# from collections import deque
sys.setrecursionlimit(10**5)#thsis is must
# mod = 10**9+7; md = 998244353
# m = 2**32
input = lambda: sys.stdin.readline().strip()
inp = lambda: list(map(int,sys.stdin.readline().strip().split()))
# def C(n,r,mod):
# if r>n:
# return 0
# num = den = 1
# for i in range(r):
# num = (num*(n-i))%mod
# den = (den*(i+1))%mod
# return (num*pow(den,mod-2,mod))%mod
# def pfcs(M = 100000):
# pfc = [0]*(M+1)
# for i in range(2,M+1):
# if pfc[i]==0:
# for j in range(i,M+1,i):
# pfc[j]+=1
# return pfc
#______________________________________________________
for _ in range(int(input())):
x,y = inp()
if y>x:
x,y = y,x
ans = 2*y+1 if x!=y else 2*y
x = x-y-1 if x!=y else x-y
ans+= 2*x if x!=0 else 0
print(ans)
``` | output | 1 | 98,100 | 15 | 196,201 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is an infinite 2-dimensional grid. The robot stands in cell (0, 0) and wants to reach cell (x, y). Here is a list of possible commands the robot can execute:
* move north from cell (i, j) to (i, j + 1);
* move east from cell (i, j) to (i + 1, j);
* move south from cell (i, j) to (i, j - 1);
* move west from cell (i, j) to (i - 1, j);
* stay in cell (i, j).
The robot wants to reach cell (x, y) in as few commands as possible. However, he can't execute the same command two or more times in a row.
What is the minimum number of commands required to reach (x, y) from (0, 0)?
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of testcases.
Each of the next t lines contains two integers x and y (0 ≤ x, y ≤ 10^4) — the destination coordinates of the robot.
Output
For each testcase print a single integer — the minimum number of commands required for the robot to reach (x, y) from (0, 0) if no command is allowed to be executed two or more times in a row.
Example
Input
5
5 5
3 4
7 1
0 0
2 0
Output
10
7
13
0
3
Note
The explanations for the example test:
We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively.
In the first test case, the robot can use the following sequence: NENENENENE.
In the second test case, the robot can use the following sequence: NENENEN.
In the third test case, the robot can use the following sequence: ESENENE0ENESE.
In the fourth test case, the robot doesn't need to go anywhere at all.
In the fifth test case, the robot can use the following sequence: E0E. | instruction | 0 | 98,101 | 15 | 196,202 |
Tags: math
Correct Solution:
```
t = int(input())
l= []
for i in range(t):
a, b = map(int, input().split())
s = 0
max_ = max(a, b)
min_ = min(a, b)
s += min_ * 2
if max_ - min_ == 0:
l.append(s)
else:
l.append(s + (max_ - min_) * 2 - 1)
for i in l:
print(i)
``` | output | 1 | 98,101 | 15 | 196,203 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is an infinite 2-dimensional grid. The robot stands in cell (0, 0) and wants to reach cell (x, y). Here is a list of possible commands the robot can execute:
* move north from cell (i, j) to (i, j + 1);
* move east from cell (i, j) to (i + 1, j);
* move south from cell (i, j) to (i, j - 1);
* move west from cell (i, j) to (i - 1, j);
* stay in cell (i, j).
The robot wants to reach cell (x, y) in as few commands as possible. However, he can't execute the same command two or more times in a row.
What is the minimum number of commands required to reach (x, y) from (0, 0)?
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of testcases.
Each of the next t lines contains two integers x and y (0 ≤ x, y ≤ 10^4) — the destination coordinates of the robot.
Output
For each testcase print a single integer — the minimum number of commands required for the robot to reach (x, y) from (0, 0) if no command is allowed to be executed two or more times in a row.
Example
Input
5
5 5
3 4
7 1
0 0
2 0
Output
10
7
13
0
3
Note
The explanations for the example test:
We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively.
In the first test case, the robot can use the following sequence: NENENENENE.
In the second test case, the robot can use the following sequence: NENENEN.
In the third test case, the robot can use the following sequence: ESENENE0ENESE.
In the fourth test case, the robot doesn't need to go anywhere at all.
In the fifth test case, the robot can use the following sequence: E0E. | instruction | 0 | 98,102 | 15 | 196,204 |
Tags: math
Correct Solution:
```
for _ in range(int(input())):
x, y = map(int, input().split())
print(x+y+max(abs(x-y)-1, 0))
``` | output | 1 | 98,102 | 15 | 196,205 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is an infinite 2-dimensional grid. The robot stands in cell (0, 0) and wants to reach cell (x, y). Here is a list of possible commands the robot can execute:
* move north from cell (i, j) to (i, j + 1);
* move east from cell (i, j) to (i + 1, j);
* move south from cell (i, j) to (i, j - 1);
* move west from cell (i, j) to (i - 1, j);
* stay in cell (i, j).
The robot wants to reach cell (x, y) in as few commands as possible. However, he can't execute the same command two or more times in a row.
What is the minimum number of commands required to reach (x, y) from (0, 0)?
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of testcases.
Each of the next t lines contains two integers x and y (0 ≤ x, y ≤ 10^4) — the destination coordinates of the robot.
Output
For each testcase print a single integer — the minimum number of commands required for the robot to reach (x, y) from (0, 0) if no command is allowed to be executed two or more times in a row.
Example
Input
5
5 5
3 4
7 1
0 0
2 0
Output
10
7
13
0
3
Note
The explanations for the example test:
We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively.
In the first test case, the robot can use the following sequence: NENENENENE.
In the second test case, the robot can use the following sequence: NENENEN.
In the third test case, the robot can use the following sequence: ESENENE0ENESE.
In the fourth test case, the robot doesn't need to go anywhere at all.
In the fifth test case, the robot can use the following sequence: E0E. | instruction | 0 | 98,103 | 15 | 196,206 |
Tags: math
Correct Solution:
```
def call():
x,y=map(int,input().split())
t=max(x,y)
if(x==y):
reS=t*2
else:
reS=t*2-1
print(reS)
for _ in range(int(input())):
call()
``` | output | 1 | 98,103 | 15 | 196,207 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is an infinite 2-dimensional grid. The robot stands in cell (0, 0) and wants to reach cell (x, y). Here is a list of possible commands the robot can execute:
* move north from cell (i, j) to (i, j + 1);
* move east from cell (i, j) to (i + 1, j);
* move south from cell (i, j) to (i, j - 1);
* move west from cell (i, j) to (i - 1, j);
* stay in cell (i, j).
The robot wants to reach cell (x, y) in as few commands as possible. However, he can't execute the same command two or more times in a row.
What is the minimum number of commands required to reach (x, y) from (0, 0)?
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of testcases.
Each of the next t lines contains two integers x and y (0 ≤ x, y ≤ 10^4) — the destination coordinates of the robot.
Output
For each testcase print a single integer — the minimum number of commands required for the robot to reach (x, y) from (0, 0) if no command is allowed to be executed two or more times in a row.
Example
Input
5
5 5
3 4
7 1
0 0
2 0
Output
10
7
13
0
3
Note
The explanations for the example test:
We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively.
In the first test case, the robot can use the following sequence: NENENENENE.
In the second test case, the robot can use the following sequence: NENENEN.
In the third test case, the robot can use the following sequence: ESENENE0ENESE.
In the fourth test case, the robot doesn't need to go anywhere at all.
In the fifth test case, the robot can use the following sequence: E0E. | instruction | 0 | 98,104 | 15 | 196,208 |
Tags: math
Correct Solution:
```
t = int(input())
for _ in range(t):
x, y = [int(s) for s in input().split() ]
lastMove = ''
moveCount = 0
actualX = 0
actualY = 0
firstMove = 'x' if x > y else 'y'
while actualX!=x or actualY!=y:
if firstMove == 'y':
if (actualX < x and lastMove == 'right' and actualY == y) or (actualY < y and lastMove == 'up' and actualX == x):
lastMove='none'
moveCount+=1
elif (actualY < y and lastMove != 'up') or (actualX < x and lastMove == 'right'):
#se aproximar em Y
lastMove='up'
actualY+=1
moveCount+=1
elif (actualX < x and lastMove != 'right') or (actualY < y and lastMove == 'up'):
#seguir na direção X OU ja andei na direção y, mudar
lastMove='right'
actualX+=1
moveCount+=1
else:
if (actualX < x and lastMove == 'right' and actualY == y) or (actualY < y and lastMove == 'up' and actualX == x):
lastMove='none'
moveCount+=1
elif (actualX < x and lastMove != 'right') or (actualY < y and lastMove == 'up'):
#seguir na direção X OU ja andei na direção y, mudar
lastMove='right'
actualX+=1
moveCount+=1
elif (actualY < y and lastMove != 'up') or (actualX < x and lastMove == 'right'):
#se aproximar em Y
lastMove='up'
actualY+=1
moveCount+=1
print(moveCount)
``` | output | 1 | 98,104 | 15 | 196,209 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is an infinite 2-dimensional grid. The robot stands in cell (0, 0) and wants to reach cell (x, y). Here is a list of possible commands the robot can execute:
* move north from cell (i, j) to (i, j + 1);
* move east from cell (i, j) to (i + 1, j);
* move south from cell (i, j) to (i, j - 1);
* move west from cell (i, j) to (i - 1, j);
* stay in cell (i, j).
The robot wants to reach cell (x, y) in as few commands as possible. However, he can't execute the same command two or more times in a row.
What is the minimum number of commands required to reach (x, y) from (0, 0)?
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of testcases.
Each of the next t lines contains two integers x and y (0 ≤ x, y ≤ 10^4) — the destination coordinates of the robot.
Output
For each testcase print a single integer — the minimum number of commands required for the robot to reach (x, y) from (0, 0) if no command is allowed to be executed two or more times in a row.
Example
Input
5
5 5
3 4
7 1
0 0
2 0
Output
10
7
13
0
3
Note
The explanations for the example test:
We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively.
In the first test case, the robot can use the following sequence: NENENENENE.
In the second test case, the robot can use the following sequence: NENENEN.
In the third test case, the robot can use the following sequence: ESENENE0ENESE.
In the fourth test case, the robot doesn't need to go anywhere at all.
In the fifth test case, the robot can use the following sequence: E0E. | instruction | 0 | 98,105 | 15 | 196,210 |
Tags: math
Correct Solution:
```
t = int(input())
for _ in range(t):
x, y = (abs(int(number)) for number in input().split(" "))
if x > y:
result = 2 * y + 2 * (x - y) - 1
elif y > x:
result = 2 * x + 2 * (y - x) - 1
else:
result = 2 * x
print(result)
``` | output | 1 | 98,105 | 15 | 196,211 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is an infinite 2-dimensional grid. The robot stands in cell (0, 0) and wants to reach cell (x, y). Here is a list of possible commands the robot can execute:
* move north from cell (i, j) to (i, j + 1);
* move east from cell (i, j) to (i + 1, j);
* move south from cell (i, j) to (i, j - 1);
* move west from cell (i, j) to (i - 1, j);
* stay in cell (i, j).
The robot wants to reach cell (x, y) in as few commands as possible. However, he can't execute the same command two or more times in a row.
What is the minimum number of commands required to reach (x, y) from (0, 0)?
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of testcases.
Each of the next t lines contains two integers x and y (0 ≤ x, y ≤ 10^4) — the destination coordinates of the robot.
Output
For each testcase print a single integer — the minimum number of commands required for the robot to reach (x, y) from (0, 0) if no command is allowed to be executed two or more times in a row.
Example
Input
5
5 5
3 4
7 1
0 0
2 0
Output
10
7
13
0
3
Note
The explanations for the example test:
We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively.
In the first test case, the robot can use the following sequence: NENENENENE.
In the second test case, the robot can use the following sequence: NENENEN.
In the third test case, the robot can use the following sequence: ESENENE0ENESE.
In the fourth test case, the robot doesn't need to go anywhere at all.
In the fifth test case, the robot can use the following sequence: E0E. | instruction | 0 | 98,106 | 15 | 196,212 |
Tags: math
Correct Solution:
```
import sys
input=sys.stdin.readline
from collections import defaultdict as dc
from collections import Counter
from bisect import bisect_right, bisect_left
import math
from operator import itemgetter
from heapq import heapify, heappop, heappush
for _ in range(int(input())):
n,m=map(int,input().split())
if n==m:
print(2*n)
else:
print(2*max(n,m)-1)
``` | output | 1 | 98,106 | 15 | 196,213 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is an infinite 2-dimensional grid. The robot stands in cell (0, 0) and wants to reach cell (x, y). Here is a list of possible commands the robot can execute:
* move north from cell (i, j) to (i, j + 1);
* move east from cell (i, j) to (i + 1, j);
* move south from cell (i, j) to (i, j - 1);
* move west from cell (i, j) to (i - 1, j);
* stay in cell (i, j).
The robot wants to reach cell (x, y) in as few commands as possible. However, he can't execute the same command two or more times in a row.
What is the minimum number of commands required to reach (x, y) from (0, 0)?
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of testcases.
Each of the next t lines contains two integers x and y (0 ≤ x, y ≤ 10^4) — the destination coordinates of the robot.
Output
For each testcase print a single integer — the minimum number of commands required for the robot to reach (x, y) from (0, 0) if no command is allowed to be executed two or more times in a row.
Example
Input
5
5 5
3 4
7 1
0 0
2 0
Output
10
7
13
0
3
Note
The explanations for the example test:
We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively.
In the first test case, the robot can use the following sequence: NENENENENE.
In the second test case, the robot can use the following sequence: NENENEN.
In the third test case, the robot can use the following sequence: ESENENE0ENESE.
In the fourth test case, the robot doesn't need to go anywhere at all.
In the fifth test case, the robot can use the following sequence: E0E.
Submitted Solution:
```
""" Educational Codeforces Round 98 (Rated for Div. 2) | A - Robot Program """
try:
for _ in range(int(input())):
a, b = map(int, input().split())
ans = 0
if a == b:
ans = (a + b)
else:
ans = a + b + (abs(a - b) - 1)
print(ans)
except EOFError as e:
pass
``` | instruction | 0 | 98,107 | 15 | 196,214 |
Yes | output | 1 | 98,107 | 15 | 196,215 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is an infinite 2-dimensional grid. The robot stands in cell (0, 0) and wants to reach cell (x, y). Here is a list of possible commands the robot can execute:
* move north from cell (i, j) to (i, j + 1);
* move east from cell (i, j) to (i + 1, j);
* move south from cell (i, j) to (i, j - 1);
* move west from cell (i, j) to (i - 1, j);
* stay in cell (i, j).
The robot wants to reach cell (x, y) in as few commands as possible. However, he can't execute the same command two or more times in a row.
What is the minimum number of commands required to reach (x, y) from (0, 0)?
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of testcases.
Each of the next t lines contains two integers x and y (0 ≤ x, y ≤ 10^4) — the destination coordinates of the robot.
Output
For each testcase print a single integer — the minimum number of commands required for the robot to reach (x, y) from (0, 0) if no command is allowed to be executed two or more times in a row.
Example
Input
5
5 5
3 4
7 1
0 0
2 0
Output
10
7
13
0
3
Note
The explanations for the example test:
We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively.
In the first test case, the robot can use the following sequence: NENENENENE.
In the second test case, the robot can use the following sequence: NENENEN.
In the third test case, the robot can use the following sequence: ESENENE0ENESE.
In the fourth test case, the robot doesn't need to go anywhere at all.
In the fifth test case, the robot can use the following sequence: E0E.
Submitted Solution:
```
for _ in range(int(input())):
n,m=[int(x) for x in input().split()]
print(n+m+max(0,abs(m-n)-1))
``` | instruction | 0 | 98,108 | 15 | 196,216 |
Yes | output | 1 | 98,108 | 15 | 196,217 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is an infinite 2-dimensional grid. The robot stands in cell (0, 0) and wants to reach cell (x, y). Here is a list of possible commands the robot can execute:
* move north from cell (i, j) to (i, j + 1);
* move east from cell (i, j) to (i + 1, j);
* move south from cell (i, j) to (i, j - 1);
* move west from cell (i, j) to (i - 1, j);
* stay in cell (i, j).
The robot wants to reach cell (x, y) in as few commands as possible. However, he can't execute the same command two or more times in a row.
What is the minimum number of commands required to reach (x, y) from (0, 0)?
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of testcases.
Each of the next t lines contains two integers x and y (0 ≤ x, y ≤ 10^4) — the destination coordinates of the robot.
Output
For each testcase print a single integer — the minimum number of commands required for the robot to reach (x, y) from (0, 0) if no command is allowed to be executed two or more times in a row.
Example
Input
5
5 5
3 4
7 1
0 0
2 0
Output
10
7
13
0
3
Note
The explanations for the example test:
We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively.
In the first test case, the robot can use the following sequence: NENENENENE.
In the second test case, the robot can use the following sequence: NENENEN.
In the third test case, the robot can use the following sequence: ESENENE0ENESE.
In the fourth test case, the robot doesn't need to go anywhere at all.
In the fifth test case, the robot can use the following sequence: E0E.
Submitted Solution:
```
import sys
input = sys.stdin.readline
from collections import *
t = int(input())
for _ in range(t):
x, y = map(int, input().split())
m, M = min(x, y), max(x, y)
d = M-m
ans = 2*m
if d>0:
ans += 2*d-1
print(ans)
``` | instruction | 0 | 98,109 | 15 | 196,218 |
Yes | output | 1 | 98,109 | 15 | 196,219 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is an infinite 2-dimensional grid. The robot stands in cell (0, 0) and wants to reach cell (x, y). Here is a list of possible commands the robot can execute:
* move north from cell (i, j) to (i, j + 1);
* move east from cell (i, j) to (i + 1, j);
* move south from cell (i, j) to (i, j - 1);
* move west from cell (i, j) to (i - 1, j);
* stay in cell (i, j).
The robot wants to reach cell (x, y) in as few commands as possible. However, he can't execute the same command two or more times in a row.
What is the minimum number of commands required to reach (x, y) from (0, 0)?
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of testcases.
Each of the next t lines contains two integers x and y (0 ≤ x, y ≤ 10^4) — the destination coordinates of the robot.
Output
For each testcase print a single integer — the minimum number of commands required for the robot to reach (x, y) from (0, 0) if no command is allowed to be executed two or more times in a row.
Example
Input
5
5 5
3 4
7 1
0 0
2 0
Output
10
7
13
0
3
Note
The explanations for the example test:
We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively.
In the first test case, the robot can use the following sequence: NENENENENE.
In the second test case, the robot can use the following sequence: NENENEN.
In the third test case, the robot can use the following sequence: ESENENE0ENESE.
In the fourth test case, the robot doesn't need to go anywhere at all.
In the fifth test case, the robot can use the following sequence: E0E.
Submitted Solution:
```
a=int(input(""))
for i in range(a):
x, y = map(int, input().split())
if x==y:
print(x+y)
else:
print(max(x,y)*2-1)
``` | instruction | 0 | 98,110 | 15 | 196,220 |
Yes | output | 1 | 98,110 | 15 | 196,221 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is an infinite 2-dimensional grid. The robot stands in cell (0, 0) and wants to reach cell (x, y). Here is a list of possible commands the robot can execute:
* move north from cell (i, j) to (i, j + 1);
* move east from cell (i, j) to (i + 1, j);
* move south from cell (i, j) to (i, j - 1);
* move west from cell (i, j) to (i - 1, j);
* stay in cell (i, j).
The robot wants to reach cell (x, y) in as few commands as possible. However, he can't execute the same command two or more times in a row.
What is the minimum number of commands required to reach (x, y) from (0, 0)?
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of testcases.
Each of the next t lines contains two integers x and y (0 ≤ x, y ≤ 10^4) — the destination coordinates of the robot.
Output
For each testcase print a single integer — the minimum number of commands required for the robot to reach (x, y) from (0, 0) if no command is allowed to be executed two or more times in a row.
Example
Input
5
5 5
3 4
7 1
0 0
2 0
Output
10
7
13
0
3
Note
The explanations for the example test:
We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively.
In the first test case, the robot can use the following sequence: NENENENENE.
In the second test case, the robot can use the following sequence: NENENEN.
In the third test case, the robot can use the following sequence: ESENENE0ENESE.
In the fourth test case, the robot doesn't need to go anywhere at all.
In the fifth test case, the robot can use the following sequence: E0E.
Submitted Solution:
```
for _ in range(int(input())):
a,b = map(int,input().split())
print(max(a,b)*2-1)
``` | instruction | 0 | 98,111 | 15 | 196,222 |
No | output | 1 | 98,111 | 15 | 196,223 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is an infinite 2-dimensional grid. The robot stands in cell (0, 0) and wants to reach cell (x, y). Here is a list of possible commands the robot can execute:
* move north from cell (i, j) to (i, j + 1);
* move east from cell (i, j) to (i + 1, j);
* move south from cell (i, j) to (i, j - 1);
* move west from cell (i, j) to (i - 1, j);
* stay in cell (i, j).
The robot wants to reach cell (x, y) in as few commands as possible. However, he can't execute the same command two or more times in a row.
What is the minimum number of commands required to reach (x, y) from (0, 0)?
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of testcases.
Each of the next t lines contains two integers x and y (0 ≤ x, y ≤ 10^4) — the destination coordinates of the robot.
Output
For each testcase print a single integer — the minimum number of commands required for the robot to reach (x, y) from (0, 0) if no command is allowed to be executed two or more times in a row.
Example
Input
5
5 5
3 4
7 1
0 0
2 0
Output
10
7
13
0
3
Note
The explanations for the example test:
We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively.
In the first test case, the robot can use the following sequence: NENENENENE.
In the second test case, the robot can use the following sequence: NENENEN.
In the third test case, the robot can use the following sequence: ESENENE0ENESE.
In the fourth test case, the robot doesn't need to go anywhere at all.
In the fifth test case, the robot can use the following sequence: E0E.
Submitted Solution:
```
def program():
a,b=[int(x) for x in input().split()]
if a >= 2*b:
#print("2a={} and b={}".format(2*a,b))
print(2*a-1)
else:
print(a+b)
if __name__ == "__main__":
test=int(input())
for i in range(test):
program()
``` | instruction | 0 | 98,112 | 15 | 196,224 |
No | output | 1 | 98,112 | 15 | 196,225 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is an infinite 2-dimensional grid. The robot stands in cell (0, 0) and wants to reach cell (x, y). Here is a list of possible commands the robot can execute:
* move north from cell (i, j) to (i, j + 1);
* move east from cell (i, j) to (i + 1, j);
* move south from cell (i, j) to (i, j - 1);
* move west from cell (i, j) to (i - 1, j);
* stay in cell (i, j).
The robot wants to reach cell (x, y) in as few commands as possible. However, he can't execute the same command two or more times in a row.
What is the minimum number of commands required to reach (x, y) from (0, 0)?
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of testcases.
Each of the next t lines contains two integers x and y (0 ≤ x, y ≤ 10^4) — the destination coordinates of the robot.
Output
For each testcase print a single integer — the minimum number of commands required for the robot to reach (x, y) from (0, 0) if no command is allowed to be executed two or more times in a row.
Example
Input
5
5 5
3 4
7 1
0 0
2 0
Output
10
7
13
0
3
Note
The explanations for the example test:
We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively.
In the first test case, the robot can use the following sequence: NENENENENE.
In the second test case, the robot can use the following sequence: NENENEN.
In the third test case, the robot can use the following sequence: ESENENE0ENESE.
In the fourth test case, the robot doesn't need to go anywhere at all.
In the fifth test case, the robot can use the following sequence: E0E.
Submitted Solution:
```
t = int(input())
for i in range(t):
inp = input()
x, y = int(inp[0]), int(inp[2])
if abs(x - y) > 1:
if x > y:
print(2 * x - 1)
else:
print(2 * y - 1)
else:
print(x + y)
``` | instruction | 0 | 98,113 | 15 | 196,226 |
No | output | 1 | 98,113 | 15 | 196,227 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is an infinite 2-dimensional grid. The robot stands in cell (0, 0) and wants to reach cell (x, y). Here is a list of possible commands the robot can execute:
* move north from cell (i, j) to (i, j + 1);
* move east from cell (i, j) to (i + 1, j);
* move south from cell (i, j) to (i, j - 1);
* move west from cell (i, j) to (i - 1, j);
* stay in cell (i, j).
The robot wants to reach cell (x, y) in as few commands as possible. However, he can't execute the same command two or more times in a row.
What is the minimum number of commands required to reach (x, y) from (0, 0)?
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of testcases.
Each of the next t lines contains two integers x and y (0 ≤ x, y ≤ 10^4) — the destination coordinates of the robot.
Output
For each testcase print a single integer — the minimum number of commands required for the robot to reach (x, y) from (0, 0) if no command is allowed to be executed two or more times in a row.
Example
Input
5
5 5
3 4
7 1
0 0
2 0
Output
10
7
13
0
3
Note
The explanations for the example test:
We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively.
In the first test case, the robot can use the following sequence: NENENENENE.
In the second test case, the robot can use the following sequence: NENENEN.
In the third test case, the robot can use the following sequence: ESENENE0ENESE.
In the fourth test case, the robot doesn't need to go anywhere at all.
In the fifth test case, the robot can use the following sequence: E0E.
Submitted Solution:
```
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
# Use a breakpoint in the code line below to debug your sc # Press Ctrl+F8 to toggle the breakpoint.
# Press the green button in the gutter to run t
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
t = int(input())
for i in range(t):
inputValues = input().split()
x = int(inputValues[0])
y = int(inputValues[1])
x = abs(x)
if x != 0:
abc = x+(x-1)
else:
abc = 0
print(abc)
``` | instruction | 0 | 98,114 | 15 | 196,228 |
No | output | 1 | 98,114 | 15 | 196,229 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's a beautiful April day and Wallace is playing football with his friends. But his friends do not know that Wallace actually stayed home with Gromit and sent them his robotic self instead. Robo-Wallace has several advantages over the other guys. For example, he can hit the ball directly to the specified point. And yet, the notion of a giveaway is foreign to him. The combination of these features makes the Robo-Wallace the perfect footballer — as soon as the ball gets to him, he can just aim and hit the goal. He followed this tactics in the first half of the match, but he hit the goal rarely. The opposing team has a very good goalkeeper who catches most of the balls that fly directly into the goal. But Robo-Wallace is a quick thinker, he realized that he can cheat the goalkeeper. After all, they are playing in a football box with solid walls. Robo-Wallace can kick the ball to the other side, then the goalkeeper will not try to catch the ball. Then, if the ball bounces off the wall and flies into the goal, the goal will at last be scored.
Your task is to help Robo-Wallace to detect a spot on the wall of the football box, to which the robot should kick the ball, so that the ball bounces once and only once off this wall and goes straight to the goal. In the first half of the match Robo-Wallace got a ball in the head and was severely hit. As a result, some of the schemes have been damaged. Because of the damage, Robo-Wallace can only aim to his right wall (Robo-Wallace is standing with his face to the opposing team's goal).
The football box is rectangular. Let's introduce a two-dimensional coordinate system so that point (0, 0) lies in the lower left corner of the field, if you look at the box above. Robo-Wallace is playing for the team, whose goal is to the right. It is an improvised football field, so the gate of Robo-Wallace's rivals may be not in the middle of the left wall.
<image>
In the given coordinate system you are given:
* y1, y2 — the y-coordinates of the side pillars of the goalposts of robo-Wallace's opponents;
* yw — the y-coordinate of the wall to which Robo-Wallace is aiming;
* xb, yb — the coordinates of the ball's position when it is hit;
* r — the radius of the ball.
A goal is scored when the center of the ball crosses the OY axis in the given coordinate system between (0, y1) and (0, y2). The ball moves along a straight line. The ball's hit on the wall is perfectly elastic (the ball does not shrink from the hit), the angle of incidence equals the angle of reflection. If the ball bounces off the wall not to the goal, that is, if it hits the other wall or the goal post, then the opposing team catches the ball and Robo-Wallace starts looking for miscalculation and gets dysfunctional. Such an outcome, if possible, should be avoided. We assume that the ball touches an object, if the distance from the center of the ball to the object is no greater than the ball radius r.
Input
The first and the single line contains integers y1, y2, yw, xb, yb, r (1 ≤ y1, y2, yw, xb, yb ≤ 106; y1 < y2 < yw; yb + r < yw; 2·r < y2 - y1).
It is guaranteed that the ball is positioned correctly in the field, doesn't cross any wall, doesn't touch the wall that Robo-Wallace is aiming at. The goal posts can't be located in the field corners.
Output
If Robo-Wallace can't score a goal in the described manner, print "-1" (without the quotes). Otherwise, print a single number xw — the abscissa of his point of aiming.
If there are multiple points of aiming, print the abscissa of any of them. When checking the correctness of the answer, all comparisons are made with the permissible absolute error, equal to 10 - 8.
It is recommended to print as many characters after the decimal point as possible.
Examples
Input
4 10 13 10 3 1
Output
4.3750000000
Input
1 4 6 2 2 1
Output
-1
Input
3 10 15 17 9 2
Output
11.3333333333
Note
Note that in the first and third samples other correct values of abscissa xw are also possible. | instruction | 0 | 98,161 | 15 | 196,322 |
Tags: binary search, geometry
Correct Solution:
```
from math import hypot
y1, y2, yw, xb, yb, r = map(int, input().split())
yw -= r
y1, y2 = yw * 2 - y2, yw * 2 - y1
def xww(y):
return (y - yw) * xb / (y - yb)
def dd(y):
xw = xww(y)
return (y - y1) / hypot(1, (yw - y) / xw)
def binary_search():
a, b = y1 + r, 1e10
for i in range(200):
m = (a + b) / 2
if dd(m) < r:
a = m
else:
b= m
return (a + b) / 2
m = binary_search()
if m + r > y2:
print("-1")
else:
m = (m + y2 - r) / 2
print(xww(m))
``` | output | 1 | 98,161 | 15 | 196,323 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On a number axis directed from the left rightwards, n marbles with coordinates x1, x2, ..., xn are situated. Let's assume that the sizes of the marbles are infinitely small, that is in this task each of them is assumed to be a material point. You can stick pins in some of them and the cost of sticking in the marble number i is equal to ci, number ci may be negative. After you choose and stick the pins you need, the marbles will start to roll left according to the rule: if a marble has a pin stuck in it, then the marble doesn't move, otherwise the marble rolls all the way up to the next marble which has a pin stuck in it and stops moving there. If there is no pinned marble on the left to the given unpinned one, it is concluded that the marble rolls to the left to infinity and you will pay an infinitely large fine for it. If no marble rolled infinitely to the left, then the fine will consist of two summands:
* the sum of the costs of stuck pins;
* the sum of the lengths of the paths of each of the marbles, that is the sum of absolute values of differences between their initial and final positions.
Your task is to choose and pin some marbles in the way that will make the fine for you to pay as little as possible.
Input
The first input line contains an integer n (1 ≤ n ≤ 3000) which is the number of marbles. The next n lines contain the descriptions of the marbles in pairs of integers xi, ci ( - 109 ≤ xi, ci ≤ 109). The numbers are space-separated. Each description is given on a separate line. No two marbles have identical initial positions.
Output
Output the single number — the least fine you will have to pay.
Examples
Input
3
2 3
3 4
1 2
Output
5
Input
4
1 7
3 1
5 10
6 1
Output
11 | instruction | 0 | 98,203 | 15 | 196,406 |
Tags: dp, sortings
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
n=int(input())
d=dict()
b=[]
for j in range(n):
x,y=map(int,input().split())
d[x]=y
b.append(x)
b.sort()
dp=[[float("inf"),float("inf")] for i in range(n)]
dp[0][1]=d[b[0]]
for i in range(1,n):
dp[i][1]=min(dp[i][1],min(dp[i-1])+d[b[i]])
j=i-1
s=b[i]
p=1
while(j>=0):
dp[i][0]=min(dp[i][0],dp[j][1]+s-p*b[j])
s+=b[j]
j+=-1
p+=1
print(min(dp[n-1]))
``` | output | 1 | 98,203 | 15 | 196,407 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On a number axis directed from the left rightwards, n marbles with coordinates x1, x2, ..., xn are situated. Let's assume that the sizes of the marbles are infinitely small, that is in this task each of them is assumed to be a material point. You can stick pins in some of them and the cost of sticking in the marble number i is equal to ci, number ci may be negative. After you choose and stick the pins you need, the marbles will start to roll left according to the rule: if a marble has a pin stuck in it, then the marble doesn't move, otherwise the marble rolls all the way up to the next marble which has a pin stuck in it and stops moving there. If there is no pinned marble on the left to the given unpinned one, it is concluded that the marble rolls to the left to infinity and you will pay an infinitely large fine for it. If no marble rolled infinitely to the left, then the fine will consist of two summands:
* the sum of the costs of stuck pins;
* the sum of the lengths of the paths of each of the marbles, that is the sum of absolute values of differences between their initial and final positions.
Your task is to choose and pin some marbles in the way that will make the fine for you to pay as little as possible.
Input
The first input line contains an integer n (1 ≤ n ≤ 3000) which is the number of marbles. The next n lines contain the descriptions of the marbles in pairs of integers xi, ci ( - 109 ≤ xi, ci ≤ 109). The numbers are space-separated. Each description is given on a separate line. No two marbles have identical initial positions.
Output
Output the single number — the least fine you will have to pay.
Examples
Input
3
2 3
3 4
1 2
Output
5
Input
4
1 7
3 1
5 10
6 1
Output
11 | instruction | 0 | 98,204 | 15 | 196,408 |
Tags: dp, sortings
Correct Solution:
```
n=int(input() )
a=sorted([list(map(int, input().split())) for _ in range(n)])
a.append( [ a[-1][0]+1, 0] )
res=[10**15]*(n+1)
res[0]=a[0][1]
ind=a[0][0]
for i in range(n+1):
acc=0
for j in range(i+1,n+1):
res[j]=min(res[j], res[i]+acc+a[j][1])
acc=acc+a[j][0]-a[i][0]
print(res[-1])
``` | output | 1 | 98,204 | 15 | 196,409 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On a number axis directed from the left rightwards, n marbles with coordinates x1, x2, ..., xn are situated. Let's assume that the sizes of the marbles are infinitely small, that is in this task each of them is assumed to be a material point. You can stick pins in some of them and the cost of sticking in the marble number i is equal to ci, number ci may be negative. After you choose and stick the pins you need, the marbles will start to roll left according to the rule: if a marble has a pin stuck in it, then the marble doesn't move, otherwise the marble rolls all the way up to the next marble which has a pin stuck in it and stops moving there. If there is no pinned marble on the left to the given unpinned one, it is concluded that the marble rolls to the left to infinity and you will pay an infinitely large fine for it. If no marble rolled infinitely to the left, then the fine will consist of two summands:
* the sum of the costs of stuck pins;
* the sum of the lengths of the paths of each of the marbles, that is the sum of absolute values of differences between their initial and final positions.
Your task is to choose and pin some marbles in the way that will make the fine for you to pay as little as possible.
Input
The first input line contains an integer n (1 ≤ n ≤ 3000) which is the number of marbles. The next n lines contain the descriptions of the marbles in pairs of integers xi, ci ( - 109 ≤ xi, ci ≤ 109). The numbers are space-separated. Each description is given on a separate line. No two marbles have identical initial positions.
Output
Output the single number — the least fine you will have to pay.
Examples
Input
3
2 3
3 4
1 2
Output
5
Input
4
1 7
3 1
5 10
6 1
Output
11 | instruction | 0 | 98,205 | 15 | 196,410 |
Tags: dp, sortings
Correct Solution:
```
from typing import Tuple, List
def compute(n: int, m: List[Tuple[int, int]]) -> int:
m = sorted(m)
state = [0] * (n + 1)
state[n - 1] = m[n - 1][1]
for i in range(n - 2, -1, -1):
min_cost = state[i + 1]
acc = 0
for j in range(i + 2, n + 1):
min_cost = min(min_cost, state[j] + abs(m[i][0] - m [j - 1][0]) + acc)
acc += abs(m[i][0] - m [j - 1][0])
state[i] = min_cost + m[i][1]
return state[0]
if __name__ == '__main__':
N = int(input())
M = [input().split() for _ in range(N)]
M = [(int(x), int(c)) for x, c in M]
print(compute(N, M))
``` | output | 1 | 98,205 | 15 | 196,411 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On a number axis directed from the left rightwards, n marbles with coordinates x1, x2, ..., xn are situated. Let's assume that the sizes of the marbles are infinitely small, that is in this task each of them is assumed to be a material point. You can stick pins in some of them and the cost of sticking in the marble number i is equal to ci, number ci may be negative. After you choose and stick the pins you need, the marbles will start to roll left according to the rule: if a marble has a pin stuck in it, then the marble doesn't move, otherwise the marble rolls all the way up to the next marble which has a pin stuck in it and stops moving there. If there is no pinned marble on the left to the given unpinned one, it is concluded that the marble rolls to the left to infinity and you will pay an infinitely large fine for it. If no marble rolled infinitely to the left, then the fine will consist of two summands:
* the sum of the costs of stuck pins;
* the sum of the lengths of the paths of each of the marbles, that is the sum of absolute values of differences between their initial and final positions.
Your task is to choose and pin some marbles in the way that will make the fine for you to pay as little as possible.
Input
The first input line contains an integer n (1 ≤ n ≤ 3000) which is the number of marbles. The next n lines contain the descriptions of the marbles in pairs of integers xi, ci ( - 109 ≤ xi, ci ≤ 109). The numbers are space-separated. Each description is given on a separate line. No two marbles have identical initial positions.
Output
Output the single number — the least fine you will have to pay.
Examples
Input
3
2 3
3 4
1 2
Output
5
Input
4
1 7
3 1
5 10
6 1
Output
11 | instruction | 0 | 98,206 | 15 | 196,412 |
Tags: dp, sortings
Correct Solution:
```
import math
R = lambda: map(int, input().split())
n = int(input())
arr = sorted(list(R()) for i in range(n))
dp = [[math.inf, math.inf] for i in range(n + 1)]
dp[0][0] = arr[0][1]
for i in range(1, n):
dp[i][0] = min(dp[i - 1]) + arr[i][1]
sm = arr[i][0]
for j in range(i - 1, -1, -1):
dp[i][1] = min(dp[i][1], dp[j][0] + sm - (i - j) * arr[j][0])
sm += arr[j][0]
print(min(dp[n - 1]))
``` | output | 1 | 98,206 | 15 | 196,413 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On a number axis directed from the left rightwards, n marbles with coordinates x1, x2, ..., xn are situated. Let's assume that the sizes of the marbles are infinitely small, that is in this task each of them is assumed to be a material point. You can stick pins in some of them and the cost of sticking in the marble number i is equal to ci, number ci may be negative. After you choose and stick the pins you need, the marbles will start to roll left according to the rule: if a marble has a pin stuck in it, then the marble doesn't move, otherwise the marble rolls all the way up to the next marble which has a pin stuck in it and stops moving there. If there is no pinned marble on the left to the given unpinned one, it is concluded that the marble rolls to the left to infinity and you will pay an infinitely large fine for it. If no marble rolled infinitely to the left, then the fine will consist of two summands:
* the sum of the costs of stuck pins;
* the sum of the lengths of the paths of each of the marbles, that is the sum of absolute values of differences between their initial and final positions.
Your task is to choose and pin some marbles in the way that will make the fine for you to pay as little as possible.
Input
The first input line contains an integer n (1 ≤ n ≤ 3000) which is the number of marbles. The next n lines contain the descriptions of the marbles in pairs of integers xi, ci ( - 109 ≤ xi, ci ≤ 109). The numbers are space-separated. Each description is given on a separate line. No two marbles have identical initial positions.
Output
Output the single number — the least fine you will have to pay.
Examples
Input
3
2 3
3 4
1 2
Output
5
Input
4
1 7
3 1
5 10
6 1
Output
11 | instruction | 0 | 98,207 | 15 | 196,414 |
Tags: dp, sortings
Correct Solution:
```
n = int(input())
arr = []
for i in range(n):
p, c = map(int, input().split())
arr += [[p, c]]
arr.sort()
dp = [[10**100, 10**100] for i in range(n)]
dp[0][0] = 10**100
dp[0][1] = arr[0][1]
for i in range(1, n):
dp[i][1] = min(dp[i-1]) + arr[i][1]
tot = arr[i][0]
count = 1
for j in range(i-1, -1, -1):
temp = dp[j][1] + tot - count*arr[j][0]
dp[i][0] = min(dp[i][0], temp)
tot += arr[j][0]
count += 1
print(min(dp[-1]))
``` | output | 1 | 98,207 | 15 | 196,415 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On a number axis directed from the left rightwards, n marbles with coordinates x1, x2, ..., xn are situated. Let's assume that the sizes of the marbles are infinitely small, that is in this task each of them is assumed to be a material point. You can stick pins in some of them and the cost of sticking in the marble number i is equal to ci, number ci may be negative. After you choose and stick the pins you need, the marbles will start to roll left according to the rule: if a marble has a pin stuck in it, then the marble doesn't move, otherwise the marble rolls all the way up to the next marble which has a pin stuck in it and stops moving there. If there is no pinned marble on the left to the given unpinned one, it is concluded that the marble rolls to the left to infinity and you will pay an infinitely large fine for it. If no marble rolled infinitely to the left, then the fine will consist of two summands:
* the sum of the costs of stuck pins;
* the sum of the lengths of the paths of each of the marbles, that is the sum of absolute values of differences between their initial and final positions.
Your task is to choose and pin some marbles in the way that will make the fine for you to pay as little as possible.
Input
The first input line contains an integer n (1 ≤ n ≤ 3000) which is the number of marbles. The next n lines contain the descriptions of the marbles in pairs of integers xi, ci ( - 109 ≤ xi, ci ≤ 109). The numbers are space-separated. Each description is given on a separate line. No two marbles have identical initial positions.
Output
Output the single number — the least fine you will have to pay.
Examples
Input
3
2 3
3 4
1 2
Output
5
Input
4
1 7
3 1
5 10
6 1
Output
11
Submitted Solution:
```
inf = 10**(10)
n = int(input())
p = n
x = []
c = []
ls = []
while(p>0):
p=p-1
a = input()
A = list(map(int,list(a.split())))
ls.append(A)
ls.sort()
for i in range(n):
x.append(ls[i][0])
c.append(ls[i][1])
dp = [[0 for i in range(n)] for j in range(2)]
f = [0]*(n)
dp[0][0] = inf
dp[1][0] = c[0]
if n>1:
dp[0][1] = abs(x[1]-x[0])+c[0]
dp[1][1] = c[0]+c[1]
f[1] = 0
for i in range(2,n):
if dp[0][i-1]+abs(x[i]-x[f[i-1]])<dp[1][i-1]+abs(x[i]-x[i-1]):
dp[0][i] = dp[0][i-1]+abs(x[i]-x[f[i-1]])
f[i] = f[i-1]
else:
dp[0][i] =dp[1][i-1]+abs(x[i]-x[i-1])
f[i] = i-1
dp[1][i] = min(dp[0][i-1],dp[1][i-1])+c[i]
print(min(dp[0][n-1],dp[1][n-1]))
``` | instruction | 0 | 98,209 | 15 | 196,418 |
No | output | 1 | 98,209 | 15 | 196,419 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On a number axis directed from the left rightwards, n marbles with coordinates x1, x2, ..., xn are situated. Let's assume that the sizes of the marbles are infinitely small, that is in this task each of them is assumed to be a material point. You can stick pins in some of them and the cost of sticking in the marble number i is equal to ci, number ci may be negative. After you choose and stick the pins you need, the marbles will start to roll left according to the rule: if a marble has a pin stuck in it, then the marble doesn't move, otherwise the marble rolls all the way up to the next marble which has a pin stuck in it and stops moving there. If there is no pinned marble on the left to the given unpinned one, it is concluded that the marble rolls to the left to infinity and you will pay an infinitely large fine for it. If no marble rolled infinitely to the left, then the fine will consist of two summands:
* the sum of the costs of stuck pins;
* the sum of the lengths of the paths of each of the marbles, that is the sum of absolute values of differences between their initial and final positions.
Your task is to choose and pin some marbles in the way that will make the fine for you to pay as little as possible.
Input
The first input line contains an integer n (1 ≤ n ≤ 3000) which is the number of marbles. The next n lines contain the descriptions of the marbles in pairs of integers xi, ci ( - 109 ≤ xi, ci ≤ 109). The numbers are space-separated. Each description is given on a separate line. No two marbles have identical initial positions.
Output
Output the single number — the least fine you will have to pay.
Examples
Input
3
2 3
3 4
1 2
Output
5
Input
4
1 7
3 1
5 10
6 1
Output
11
Submitted Solution:
```
li=[]
for _ in range(int(input())):
x,y= map(int, input().split())
li.append([x,y])
li.sort(key = lambda x: x[0])
s=li[0][1]
pre=0
for i in range(1, len(li)):
val1= li[i][1]
val2= abs( abs(li[pre][0]) -abs(li[i][0]) )
if val1 <= val2:
pre= i
s= s+ min( val1, val2)
print(s)
``` | instruction | 0 | 98,210 | 15 | 196,420 |
No | output | 1 | 98,210 | 15 | 196,421 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On a number axis directed from the left rightwards, n marbles with coordinates x1, x2, ..., xn are situated. Let's assume that the sizes of the marbles are infinitely small, that is in this task each of them is assumed to be a material point. You can stick pins in some of them and the cost of sticking in the marble number i is equal to ci, number ci may be negative. After you choose and stick the pins you need, the marbles will start to roll left according to the rule: if a marble has a pin stuck in it, then the marble doesn't move, otherwise the marble rolls all the way up to the next marble which has a pin stuck in it and stops moving there. If there is no pinned marble on the left to the given unpinned one, it is concluded that the marble rolls to the left to infinity and you will pay an infinitely large fine for it. If no marble rolled infinitely to the left, then the fine will consist of two summands:
* the sum of the costs of stuck pins;
* the sum of the lengths of the paths of each of the marbles, that is the sum of absolute values of differences between their initial and final positions.
Your task is to choose and pin some marbles in the way that will make the fine for you to pay as little as possible.
Input
The first input line contains an integer n (1 ≤ n ≤ 3000) which is the number of marbles. The next n lines contain the descriptions of the marbles in pairs of integers xi, ci ( - 109 ≤ xi, ci ≤ 109). The numbers are space-separated. Each description is given on a separate line. No two marbles have identical initial positions.
Output
Output the single number — the least fine you will have to pay.
Examples
Input
3
2 3
3 4
1 2
Output
5
Input
4
1 7
3 1
5 10
6 1
Output
11
Submitted Solution:
```
mod=10**9+7
inf= "a"
dp=[[inf for i in range(3001)] for j in range(3001)]
li=[]
N= int(input())
for _ in range(N):
x,y= map(int, input().split())
li.append([x,y])
li.sort(key = lambda x: x[0])
def sol( n , pre):
if n >= N:
return 0
if dp[n][pre]!=inf :
return dp[n][pre]
x= li[n][1] + sol(n+1, n)
x=x%mod
y= abs( li[n][0]-li[pre][0] ) + sol(n+1, pre)
y=y%mod
dp[n][pre] = (min(x,y))%mod
return dp[n][pre]
print( sol(1, 0)+ li[0][1] )
``` | instruction | 0 | 98,211 | 15 | 196,422 |
No | output | 1 | 98,211 | 15 | 196,423 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vivek has encountered a problem. He has a maze that can be represented as an n × m grid. Each of the grid cells may represent the following:
* Empty — '.'
* Wall — '#'
* Good person — 'G'
* Bad person — 'B'
The only escape from the maze is at cell (n, m).
A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.
Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.
It is guaranteed that the cell (n,m) is empty. Vivek can also block this cell.
Input
The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers n, m (1 ≤ n, m ≤ 50) — the number of rows and columns in the maze.
Each of the next n lines contain m characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.
Output
For each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No"
You may print every letter in any case (upper or lower).
Example
Input
6
1 1
.
1 2
G.
2 2
#B
G.
2 3
G.#
B#.
3 3
#B.
#..
GG.
2 2
#B
B.
Output
Yes
Yes
No
No
Yes
Yes
Note
For the first and second test cases, all conditions are already satisfied.
For the third test case, there is only one empty cell (2,2), and if it is replaced with a wall then the good person at (1,2) will not be able to escape.
For the fourth test case, the good person at (1,1) cannot escape.
For the fifth test case, Vivek can block the cells (2,3) and (2,2).
For the last test case, Vivek can block the destination cell (2, 2). | instruction | 0 | 98,790 | 15 | 197,580 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, greedy, implementation, shortest paths
Correct Solution:
```
import sys
import math
sys.setrecursionlimit(1000000) #设置最大递归深度
int1 = lambda x: int(x) - 1 #返回x-1
p2D = lambda x: print(*x, sep="\n") #输出多个元素,以换行符分割
p2S = lambda x: print(*x, sep=" ") #输出多个元素,以空格分割
def II(): return int(sys.stdin.readline()) #读一行(仅一个)整数
def MI(): return map(int, sys.stdin.readline().split()) #读一行数据,转化为int型元组
def LI(): return list(map(int, sys.stdin.readline().split())) #读一行数据,转化为int型列表
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1] #读一行字符串,舍掉换行符
# 好人G = 2 坏人B = 3 墙# = 1 空气. = 0
Canlevel = True
Gnum = 0
def check(s, tag, ns, ms, n, m, f = 'None'):
if n < 0 or n >= ns or m < 0 or m >= ms:
return
elif s[n][m] == 1 or tag[n][m] == True:
return
elif s[n][m] == 0:
s[n][m] = 1
tag[n][m] = True
elif s[n][m] == 3:
tag[n][m] = True
if f != 'Up':
check(s, tag, ns, ms, n + 1, m, 'Down')
if f != 'Down':
check(s, tag, ns, ms, n - 1, m, 'Up')
if f != 'Right':
check(s, tag, ns, ms, n, m + 1, 'Left')
if f != 'Left':
check(s, tag, ns, ms, n, m - 1, 'Right')
elif s[n][m] == 2:
tag[n][m] = True
global Canlevel
Canlevel = False
return
def level(s, t, ns, ms, n, m, f = 'None'):
if n < 0 or n >= ns or m < 0 or m >= ms:
return
elif s[n][m] == 1 or t[n][m] == True:
return
elif s[n][m] == 3:
global Canlevel
Canlevel = False
return
elif s[n][m] == 0 or s[n][m] == 2:
t[n][m] = True
if s[n][m] == 2:
global Gnum
Gnum += 1
if f != 'Up':
level(s, t, ns, ms, n + 1, m, 'Down')
if f != 'Down':
level(s, t, ns, ms, n - 1, m, 'Up')
if f != 'Right':
level(s, t, ns, ms, n, m + 1, 'Left')
if f != 'Left':
level(s, t, ns, ms, n, m - 1, 'Right')
def main():
_v_ = II()
for __ in range(_v_):
global Canlevel, Gnum
Canlevel = True
Gnum = 0
allG = 0
n, m = MI()
s = []
sn = []
tag = []
taglevel = []
for i in range(n):
s.append(SI())
tag.append([])
taglevel.append([])
for j in range(m):
tag[i].append(False)
taglevel[i].append(False)
for i in range(n):
sn.append([])
for j in range(m):
if s[i][j] == '.':
sn[i].append(0)
if s[i][j] == '#':
sn[i].append(1)
if s[i][j] == 'G':
sn[i].append(2)
allG += 1
if s[i][j] == 'B':
sn[i].append(3)
for i in range(n):
for j in range(m):
if sn[i][j] == 3 and tag[i][j] == False:
check(sn, tag, n, m, i, j)
level(sn, taglevel, n, m, n - 1, m - 1)
if Canlevel == False:
print('No')
elif Gnum == allG:
print('Yes')
else:
print('No')
main()
'''
1
7 10
..##.#G..B
G..#B..G..
G........B
......##.B
.###..B.BB
........##
..........
'''
``` | output | 1 | 98,790 | 15 | 197,581 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vivek has encountered a problem. He has a maze that can be represented as an n × m grid. Each of the grid cells may represent the following:
* Empty — '.'
* Wall — '#'
* Good person — 'G'
* Bad person — 'B'
The only escape from the maze is at cell (n, m).
A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.
Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.
It is guaranteed that the cell (n,m) is empty. Vivek can also block this cell.
Input
The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers n, m (1 ≤ n, m ≤ 50) — the number of rows and columns in the maze.
Each of the next n lines contain m characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.
Output
For each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No"
You may print every letter in any case (upper or lower).
Example
Input
6
1 1
.
1 2
G.
2 2
#B
G.
2 3
G.#
B#.
3 3
#B.
#..
GG.
2 2
#B
B.
Output
Yes
Yes
No
No
Yes
Yes
Note
For the first and second test cases, all conditions are already satisfied.
For the third test case, there is only one empty cell (2,2), and if it is replaced with a wall then the good person at (1,2) will not be able to escape.
For the fourth test case, the good person at (1,1) cannot escape.
For the fifth test case, Vivek can block the cells (2,3) and (2,2).
For the last test case, Vivek can block the destination cell (2, 2). | instruction | 0 | 98,791 | 15 | 197,582 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, greedy, implementation, shortest paths
Correct Solution:
```
import sys
input = sys.stdin.readline
t=int(input())
ans=[]
for _ in range(t):
h,w=map(int,input().split())
grid=[list(input()) for _ in range(h)]
good=set()
bad=set()
delta=[(-1,0),(1,0),(0,1),(0,-1)]
for i in range(h):
for j in range(w):
if grid[i][j]=="G":
good.add((i,j))
elif grid[i][j]=="B":
bad.add((i,j))
if not good:
ans.append("Yes")
continue
flg=0
for ci,cj in bad:
for di,dj in delta:
ni,nj=ci+di,cj+dj
if 0<=ni<h and 0<=nj<w:
if grid[ni][nj]==".":
grid[ni][nj]="#"
elif grid[ni][nj]=="G":
flg=1
break
if flg:
break
if flg or grid[h-1][w-1]=="#":
ans.append("No")
continue
q=[(h-1,w-1)]
vis=[[0]*w for _ in range(h)]
vis[-1][-1]=1
while q:
ci,cj=q.pop()
for di,dj in delta:
ni,nj=ci+di,cj+dj
if 0<=ni<h and 0<=nj<w and grid[ni][nj]!="#" and not vis[ni][nj]:
vis[ni][nj]=1
q.append((ni,nj))
if all(vis[i][j] for i,j in good):
ans.append("Yes")
else:
ans.append("No")
print("\n".join(ans))
``` | output | 1 | 98,791 | 15 | 197,583 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vivek has encountered a problem. He has a maze that can be represented as an n × m grid. Each of the grid cells may represent the following:
* Empty — '.'
* Wall — '#'
* Good person — 'G'
* Bad person — 'B'
The only escape from the maze is at cell (n, m).
A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.
Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.
It is guaranteed that the cell (n,m) is empty. Vivek can also block this cell.
Input
The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers n, m (1 ≤ n, m ≤ 50) — the number of rows and columns in the maze.
Each of the next n lines contain m characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.
Output
For each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No"
You may print every letter in any case (upper or lower).
Example
Input
6
1 1
.
1 2
G.
2 2
#B
G.
2 3
G.#
B#.
3 3
#B.
#..
GG.
2 2
#B
B.
Output
Yes
Yes
No
No
Yes
Yes
Note
For the first and second test cases, all conditions are already satisfied.
For the third test case, there is only one empty cell (2,2), and if it is replaced with a wall then the good person at (1,2) will not be able to escape.
For the fourth test case, the good person at (1,1) cannot escape.
For the fifth test case, Vivek can block the cells (2,3) and (2,2).
For the last test case, Vivek can block the destination cell (2, 2). | instruction | 0 | 98,792 | 15 | 197,584 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, greedy, implementation, shortest paths
Correct Solution:
```
def solve(n, m, maze):
for i in range(n):
for j in range(m):
if maze[i][j] != "B":
continue
if i > 0:
if maze[i - 1][j] == "G":
return False
if maze[i - 1][j] == ".":
maze[i - 1][j] = "#"
if j > 0:
if maze[i][j - 1] == "G":
return False
if maze[i][j - 1] == ".":
maze[i][j - 1] = "#"
if i < n - 1:
if maze[i + 1][j] == "G":
return False
if maze[i + 1][j] == ".":
maze[i + 1][j] = "#"
if j < m - 1:
if maze[i][j + 1] == "G":
return False
if maze[i][j + 1] == ".":
maze[i][j + 1] = "#"
reachables = set()
to_visit = {(n - 1, m - 1)} if maze[n - 1][m - 1] != "#" else set()
while to_visit:
i, j = to_visit.pop()
reachables.add((i, j))
if i > 0 and maze[i - 1][j] != '#' and (i - 1, j) not in reachables:
to_visit.add((i - 1, j))
if i < n - 1 and maze[i + 1][j] != '#' and (i + 1, j) not in reachables:
to_visit.add((i + 1, j))
if j > 0 and maze[i][j - 1] != '#' and (i, j - 1) not in reachables:
to_visit.add((i, j - 1))
if j < m - 1 and maze[i][j + 1] != '#' and (i, j + 1) not in reachables:
to_visit.add((i, j + 1))
for i in range(n):
for j in range(m):
if maze[i][j] == "B" and (i, j) in reachables:
return False
if maze[i][j] == "G" and (i, j) not in reachables:
return False
return True
def main():
T = int(input())
for _ in range(T):
n, m = map(int, input().split())
maze = [list(input().strip()) for _ in range(n)]
print("Yes" if solve(n, m, maze) else "No")
if __name__ == "__main__":
main()
``` | output | 1 | 98,792 | 15 | 197,585 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vivek has encountered a problem. He has a maze that can be represented as an n × m grid. Each of the grid cells may represent the following:
* Empty — '.'
* Wall — '#'
* Good person — 'G'
* Bad person — 'B'
The only escape from the maze is at cell (n, m).
A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.
Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.
It is guaranteed that the cell (n,m) is empty. Vivek can also block this cell.
Input
The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers n, m (1 ≤ n, m ≤ 50) — the number of rows and columns in the maze.
Each of the next n lines contain m characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.
Output
For each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No"
You may print every letter in any case (upper or lower).
Example
Input
6
1 1
.
1 2
G.
2 2
#B
G.
2 3
G.#
B#.
3 3
#B.
#..
GG.
2 2
#B
B.
Output
Yes
Yes
No
No
Yes
Yes
Note
For the first and second test cases, all conditions are already satisfied.
For the third test case, there is only one empty cell (2,2), and if it is replaced with a wall then the good person at (1,2) will not be able to escape.
For the fourth test case, the good person at (1,1) cannot escape.
For the fifth test case, Vivek can block the cells (2,3) and (2,2).
For the last test case, Vivek can block the destination cell (2, 2). | instruction | 0 | 98,793 | 15 | 197,586 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, greedy, implementation, shortest paths
Correct Solution:
```
from sys import stdin
from collections import deque
def fun():
n, m = map(int, stdin.readline().split())
lst = [list(stdin.readline()) for _ in range(n)]
good = []
for x in range(n):
for y in range(m):
if lst[x][y] == 'B':
if x != 0:
if lst[x - 1][y] == 'G':
print('No')
return
elif lst[x - 1][y] == '.':
lst[x - 1][y] = '#'
if x != n - 1:
if lst[x + 1][y] == 'G':
print('No')
return
elif lst[x + 1][y] == '.':
lst[x + 1][y] = '#'
if y != 0:
if lst[x][y - 1] == 'G':
print('No')
return
elif lst[x][y - 1] == '.':
lst[x][y - 1] = '#'
if y != m - 1:
if lst[x][y + 1] == 'G':
print('No')
return
elif lst[x][y + 1] == '.':
lst[x][y + 1] = '#'
elif lst[x][y] == 'G':
good.append((x, y))
if lst[n - 1][m - 1] == 'B':
print('No')
return
done = set()
for r in good:
if r in done:
continue
curr = deque([r])
visi = {r}
done.add(r)
fl = 0
while len(curr):
x = curr.popleft()
if x[0] != 0 and (x[0] - 1, x[1]) not in visi and lst[x[0] - 1][x[1]] == '.' or x[0] != 0 and (
x[0] - 1, x[1]) not in visi and lst[x[0] - 1][x[1]] == 'G':
curr.append((x[0] - 1, x[1]))
visi.add((x[0] - 1, x[1]))
if lst[x[0] - 1][x[1]] == 'G':
done.add((x[0]-1,x[1]))
if x[0] != n - 1 and (x[0] + 1, x[1]) not in visi and lst[x[0] + 1][x[1]] == '.' or x[0] != n - 1 and (
x[0] + 1, x[1]) not in visi and lst[x[0] + 1][x[1]] == 'G':
curr.append((x[0] + 1, x[1]))
visi.add((x[0] + 1, x[1]))
if lst[x[0] + 1][x[1]] == 'G':
done.add((x[0]+1,x[1]))
if x[1] != 0 and (x[0], x[1] - 1) not in visi and lst[x[0]][x[1] - 1] == '.' or x[1] != 0 and (
x[0], x[1] - 1) not in visi and lst[x[0]][x[1] - 1] == 'G':
curr.append((x[0], x[1] - 1))
visi.add((x[0], x[1] - 1))
if lst[x[0]][x[1]-1] == 'G':
done.add((x[0],x[1]-1))
if x[1] != m - 1 and (x[0], x[1] + 1) not in visi and lst[x[0]][x[1] + 1] == '.' or x[1] != m - 1 and (
x[0], x[1] + 1) not in visi and lst[x[0]][x[1] + 1] == 'G':
curr.append((x[0], x[1] + 1))
visi.add((x[0], x[1] + 1))
if lst[x[0]][x[1]+1] == 'G':
done.add((x[0],x[1]+1))
if (n - 1, m - 1) in visi:
fl = 1
break
if not fl:
print('No')
return
print('Yes')
for _ in range(int(stdin.readline())):
fun()
``` | output | 1 | 98,793 | 15 | 197,587 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vivek has encountered a problem. He has a maze that can be represented as an n × m grid. Each of the grid cells may represent the following:
* Empty — '.'
* Wall — '#'
* Good person — 'G'
* Bad person — 'B'
The only escape from the maze is at cell (n, m).
A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.
Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.
It is guaranteed that the cell (n,m) is empty. Vivek can also block this cell.
Input
The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers n, m (1 ≤ n, m ≤ 50) — the number of rows and columns in the maze.
Each of the next n lines contain m characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.
Output
For each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No"
You may print every letter in any case (upper or lower).
Example
Input
6
1 1
.
1 2
G.
2 2
#B
G.
2 3
G.#
B#.
3 3
#B.
#..
GG.
2 2
#B
B.
Output
Yes
Yes
No
No
Yes
Yes
Note
For the first and second test cases, all conditions are already satisfied.
For the third test case, there is only one empty cell (2,2), and if it is replaced with a wall then the good person at (1,2) will not be able to escape.
For the fourth test case, the good person at (1,1) cannot escape.
For the fifth test case, Vivek can block the cells (2,3) and (2,2).
For the last test case, Vivek can block the destination cell (2, 2). | instruction | 0 | 98,794 | 15 | 197,588 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, greedy, implementation, shortest paths
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
# ------------------------------
def main():
for _ in range(N()):
n, m = RL()
gp = [list(input()) for _ in range(n)]
nex = [[1, 0], [0, 1], [-1, 0], [0, -1]]
gd = 0
bad = 0
tag = False
for i in range(n):
for j in range(m):
if gp[i][j]=='G': gd+=1
if gp[i][j] == 'B':
bad+=1
for xx, yy in nex:
if -1<xx+i<n and -1<yy+j<m and gp[xx+i][yy+j]=='.':
gp[xx+i][yy+j] = '#'
if -1 < xx + i < n and -1 < yy + j < m and gp[xx + i][yy + j] == 'G':
tag = True
if gp[-1][-1]=='B' or tag:
print('No')
elif gp[-1][-1]=='#':
if gd!=0:
print('No')
else:
print('Yes')
else:
q = deque()
q.append((n-1, m-1))
vis = [[0]*m for _ in range(n)]
vis[-1][-1] = 1
if gp[n-1][m-1]=='G':
gd-=1
while q:
px, py = q.popleft()
bd = 0
for xx, yy in nex:
nx, ny = xx+px, yy+py
if -1<nx<n and -1<ny<m and vis[nx][ny]==0:
vis[nx][ny] = 1
if gp[nx][ny] == 'G':
gd-=1
if gp[nx][ny]=='B':
bd+=1
if gp[nx][ny]=='.' or gp[nx][ny]=='G':
q.append((nx, ny))
print('Yes' if gd==0 and bd==0 else 'No')
if __name__ == "__main__":
main()
``` | output | 1 | 98,794 | 15 | 197,589 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vivek has encountered a problem. He has a maze that can be represented as an n × m grid. Each of the grid cells may represent the following:
* Empty — '.'
* Wall — '#'
* Good person — 'G'
* Bad person — 'B'
The only escape from the maze is at cell (n, m).
A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.
Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.
It is guaranteed that the cell (n,m) is empty. Vivek can also block this cell.
Input
The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers n, m (1 ≤ n, m ≤ 50) — the number of rows and columns in the maze.
Each of the next n lines contain m characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.
Output
For each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No"
You may print every letter in any case (upper or lower).
Example
Input
6
1 1
.
1 2
G.
2 2
#B
G.
2 3
G.#
B#.
3 3
#B.
#..
GG.
2 2
#B
B.
Output
Yes
Yes
No
No
Yes
Yes
Note
For the first and second test cases, all conditions are already satisfied.
For the third test case, there is only one empty cell (2,2), and if it is replaced with a wall then the good person at (1,2) will not be able to escape.
For the fourth test case, the good person at (1,1) cannot escape.
For the fifth test case, Vivek can block the cells (2,3) and (2,2).
For the last test case, Vivek can block the destination cell (2, 2). | instruction | 0 | 98,795 | 15 | 197,590 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, greedy, implementation, shortest paths
Correct Solution:
```
T = int(input().strip())
for t in range(T):
n, m = list(map(int, input().split()))
field = [[1] * (m + 2) for _ in range(n+2)]
bads = []
goods = []
for row in range(n):
cr = input().strip()
for col, cell in enumerate(cr):
if cell == '#':
field[row +1][col +1] = 1
elif cell == 'B':
bads.append((row +1, col +1))
field[row + 1][col + 1] = 0
elif cell == 'G':
goods.append((row +1, col +1))
field[row + 1][col + 1] = 0
else:
field[row +1][col +1] = 0
if len(goods) == 0:
print('Yes')
continue
# print('before:')
# for r in field:
# print("".join(str(c) for c in r))
for b in bads:
for shiftx, shifty in [(1,0), (-1, 0), (0,1), (0, -1)]:
field[b[0]+ shiftx][ b[1] +shifty] = 1
# print('after:')
# for r in field:
# print("".join(str(c) for c in r))
stk = [(n,m)]
if field[n][m] == 1:
print('No')
continue
start = 0
field[n][m] = 2
while start < len(stk):
b = stk[start]
for shiftx, shifty in [(1,0), (-1, 0), (0,1), (0, -1)]:
if field[b[0]+ shiftx] [ b[1] +shifty] == 0:
field[b[0] + shiftx][b[1] + shifty] = 2
stk.append((b[0] + shiftx,b[1] + shifty))
start += 1
good = True
for b in goods:
if field[b[0]][b[1]] != 2:
good = False
break
if good:
print('Yes')
else:
print('No')
# print('passed:')
# for r in field:
# print("".join(str(c) for c in r))
"""
1
5 5
G..#.
.....
..B..
#....
.G...
"""
``` | output | 1 | 98,795 | 15 | 197,591 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vivek has encountered a problem. He has a maze that can be represented as an n × m grid. Each of the grid cells may represent the following:
* Empty — '.'
* Wall — '#'
* Good person — 'G'
* Bad person — 'B'
The only escape from the maze is at cell (n, m).
A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.
Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.
It is guaranteed that the cell (n,m) is empty. Vivek can also block this cell.
Input
The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers n, m (1 ≤ n, m ≤ 50) — the number of rows and columns in the maze.
Each of the next n lines contain m characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.
Output
For each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No"
You may print every letter in any case (upper or lower).
Example
Input
6
1 1
.
1 2
G.
2 2
#B
G.
2 3
G.#
B#.
3 3
#B.
#..
GG.
2 2
#B
B.
Output
Yes
Yes
No
No
Yes
Yes
Note
For the first and second test cases, all conditions are already satisfied.
For the third test case, there is only one empty cell (2,2), and if it is replaced with a wall then the good person at (1,2) will not be able to escape.
For the fourth test case, the good person at (1,1) cannot escape.
For the fifth test case, Vivek can block the cells (2,3) and (2,2).
For the last test case, Vivek can block the destination cell (2, 2). | instruction | 0 | 98,796 | 15 | 197,592 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, greedy, implementation, shortest paths
Correct Solution:
```
from collections import deque
t = int(input())
for _ in range(t):
n, m = map(int, input().split())
g = [["#"]*(m+2)]
for i in range(n):
g.append(["#"] + list(input()) + ["#"])
g.append(["#"]*(m+2))
for i in range(1, n+1):
for j in range(1, m+1):
if g[i][j] == "B":
if g[i+1][j] == ".":
g[i+1][j] = "#"
if g[i-1][j] == ".":
g[i-1][j] = "#"
if g[i][j+1] == ".":
g[i][j+1] = "#"
if g[i][j-1] == ".":
g[i][j-1] = "#"
visit = [[False]*(m+2) for i in range(n+2)]
visit[n][m] = True
ans = "Yes"
q = deque([(n, m)])
while q:
x, y = q.popleft()
for dx, dy in [(1, 0), (-1, 0), (0, -1), (0, 1)]:
if g[x+dx][y+dy] != "#":
if not visit[x+dx][y+dy]:
q.append((x+dx, y+dy))
visit[x+dx][y+dy] = True
for i in range(1, n+1):
for j in range(1, m+1):
if g[i][j] == "G":
if not visit[i][j]:
ans = "No"
if g[i][j] == "B":
if visit[i][j]:
ans = "No"
f = 0
for i in range(1, n+1):
for j in range(1, m+1):
if g[i][j] == "G":
f = 1
if f == 1:
if g[n][m] == "#":
ans = "No"
else:
ans = "Yes"
print(ans)
``` | output | 1 | 98,796 | 15 | 197,593 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.