message stringlengths 2 45.8k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 254 108k | cluster float64 3 3 | __index_level_0__ int64 508 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well.
This time Igor K. got disappointed in one of his hobbies: editing and voicing videos. Moreover, he got disappointed in it so much, that he decided to destroy his secret archive for good.
Igor K. use Pindows XR operation system which represents files and folders by small icons. At that, m icons can fit in a horizontal row in any window.
Igor K.'s computer contains n folders in the D: disk's root catalog. The folders are numbered from 1 to n in the order from the left to the right and from top to bottom (see the images). At that the folders with secret videos have numbers from a to b inclusive. Igor K. wants to delete them forever, at that making as few frame selections as possible, and then pressing Shift+Delete exactly once. What is the minimum number of times Igor K. will have to select the folder in order to select folders from a to b and only them? Let us note that if some selected folder is selected repeatedly, then it is deselected. Each selection possesses the shape of some rectangle with sides parallel to the screen's borders.
Input
The only line contains four integers n, m, a, b (1 ≤ n, m ≤ 109, 1 ≤ a ≤ b ≤ n). They are the number of folders in Igor K.'s computer, the width of a window and the numbers of the first and the last folders that need to be deleted.
Output
Print a single number: the least possible number of times Igor K. will have to select the folders using frames to select only the folders with numbers from a to b.
Examples
Input
11 4 3 9
Output
3
Input
20 5 2 20
Output
2
Note
The images below illustrate statement tests.
The first test:
<image>
In this test we can select folders 3 and 4 with out first selection, folders 5, 6, 7, 8 with our second selection and folder 9 with our third, last selection.
The second test:
<image>
In this test we can first select all folders in the first row (2, 3, 4, 5), then — all other ones.
Submitted Solution:
```
from math import ceil
n,c,st,end = [int(i) for i in input().split()]
reme =end%c
rems = st%c
dive = ceil(end/c)
divs = ceil(st/c)
if rems==0:
rems = c
if (reme==0 and rems==1) or (divs==dive ) or end-st+1==n or (rems==1 and end==n):
print(str(1))
elif reme==rems-1 or dive-divs<2 or (reme==0 or rems==1) or end==n :
print(str(2))
else:
print(str(3))
``` | instruction | 0 | 47,654 | 3 | 95,308 |
Yes | output | 1 | 47,654 | 3 | 95,309 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well.
This time Igor K. got disappointed in one of his hobbies: editing and voicing videos. Moreover, he got disappointed in it so much, that he decided to destroy his secret archive for good.
Igor K. use Pindows XR operation system which represents files and folders by small icons. At that, m icons can fit in a horizontal row in any window.
Igor K.'s computer contains n folders in the D: disk's root catalog. The folders are numbered from 1 to n in the order from the left to the right and from top to bottom (see the images). At that the folders with secret videos have numbers from a to b inclusive. Igor K. wants to delete them forever, at that making as few frame selections as possible, and then pressing Shift+Delete exactly once. What is the minimum number of times Igor K. will have to select the folder in order to select folders from a to b and only them? Let us note that if some selected folder is selected repeatedly, then it is deselected. Each selection possesses the shape of some rectangle with sides parallel to the screen's borders.
Input
The only line contains four integers n, m, a, b (1 ≤ n, m ≤ 109, 1 ≤ a ≤ b ≤ n). They are the number of folders in Igor K.'s computer, the width of a window and the numbers of the first and the last folders that need to be deleted.
Output
Print a single number: the least possible number of times Igor K. will have to select the folders using frames to select only the folders with numbers from a to b.
Examples
Input
11 4 3 9
Output
3
Input
20 5 2 20
Output
2
Note
The images below illustrate statement tests.
The first test:
<image>
In this test we can select folders 3 and 4 with out first selection, folders 5, 6, 7, 8 with our second selection and folder 9 with our third, last selection.
The second test:
<image>
In this test we can first select all folders in the first row (2, 3, 4, 5), then — all other ones.
Submitted Solution:
```
n, m, a, b = map(int, input().split())
a -= 1
x, y = a % m, b % m if b < n else 0
i, j = a // m, b // m + (b == n)
print((x > 0) + (y > 0) + (i != j) - (x == y != 0))
``` | instruction | 0 | 47,655 | 3 | 95,310 |
No | output | 1 | 47,655 | 3 | 95,311 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well.
This time Igor K. got disappointed in one of his hobbies: editing and voicing videos. Moreover, he got disappointed in it so much, that he decided to destroy his secret archive for good.
Igor K. use Pindows XR operation system which represents files and folders by small icons. At that, m icons can fit in a horizontal row in any window.
Igor K.'s computer contains n folders in the D: disk's root catalog. The folders are numbered from 1 to n in the order from the left to the right and from top to bottom (see the images). At that the folders with secret videos have numbers from a to b inclusive. Igor K. wants to delete them forever, at that making as few frame selections as possible, and then pressing Shift+Delete exactly once. What is the minimum number of times Igor K. will have to select the folder in order to select folders from a to b and only them? Let us note that if some selected folder is selected repeatedly, then it is deselected. Each selection possesses the shape of some rectangle with sides parallel to the screen's borders.
Input
The only line contains four integers n, m, a, b (1 ≤ n, m ≤ 109, 1 ≤ a ≤ b ≤ n). They are the number of folders in Igor K.'s computer, the width of a window and the numbers of the first and the last folders that need to be deleted.
Output
Print a single number: the least possible number of times Igor K. will have to select the folders using frames to select only the folders with numbers from a to b.
Examples
Input
11 4 3 9
Output
3
Input
20 5 2 20
Output
2
Note
The images below illustrate statement tests.
The first test:
<image>
In this test we can select folders 3 and 4 with out first selection, folders 5, 6, 7, 8 with our second selection and folder 9 with our third, last selection.
The second test:
<image>
In this test we can first select all folders in the first row (2, 3, 4, 5), then — all other ones.
Submitted Solution:
```
n,m,a,b=map(int,input().split())
a-=1
if a//m==b//m:
print(1)
elif a%m==0 and b%m==0:
print(1)
elif a%m==0 and b==n:
print(1)
elif a%m==0 or b%m==0:
print(2)
elif abs(a//m-b//m)==1:
print(2)
elif a%m==b%m:
print(2)
else:
print(3)
``` | instruction | 0 | 47,656 | 3 | 95,312 |
No | output | 1 | 47,656 | 3 | 95,313 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well.
This time Igor K. got disappointed in one of his hobbies: editing and voicing videos. Moreover, he got disappointed in it so much, that he decided to destroy his secret archive for good.
Igor K. use Pindows XR operation system which represents files and folders by small icons. At that, m icons can fit in a horizontal row in any window.
Igor K.'s computer contains n folders in the D: disk's root catalog. The folders are numbered from 1 to n in the order from the left to the right and from top to bottom (see the images). At that the folders with secret videos have numbers from a to b inclusive. Igor K. wants to delete them forever, at that making as few frame selections as possible, and then pressing Shift+Delete exactly once. What is the minimum number of times Igor K. will have to select the folder in order to select folders from a to b and only them? Let us note that if some selected folder is selected repeatedly, then it is deselected. Each selection possesses the shape of some rectangle with sides parallel to the screen's borders.
Input
The only line contains four integers n, m, a, b (1 ≤ n, m ≤ 109, 1 ≤ a ≤ b ≤ n). They are the number of folders in Igor K.'s computer, the width of a window and the numbers of the first and the last folders that need to be deleted.
Output
Print a single number: the least possible number of times Igor K. will have to select the folders using frames to select only the folders with numbers from a to b.
Examples
Input
11 4 3 9
Output
3
Input
20 5 2 20
Output
2
Note
The images below illustrate statement tests.
The first test:
<image>
In this test we can select folders 3 and 4 with out first selection, folders 5, 6, 7, 8 with our second selection and folder 9 with our third, last selection.
The second test:
<image>
In this test we can first select all folders in the first row (2, 3, 4, 5), then — all other ones.
Submitted Solution:
```
import sys
sys.setrecursionlimit(10000000)
def solve():
n, m, a, b, = rv()
a -= 1
b -= 1
if a // m == b // m or m == 1:
print(1)
return
# now only way it is one is if it is one big square
first = m - (a - (a // m) * m)
last = b - (b // m) * m + 1
# print(first, last)
if first == m and last == m:
print(1)
return
if a // m + 1 == b // m or first + last == m:
print(2)
return
if first == m or last == m:
print(2)
return
print(3)
# print(a, b)
# firstrow = m - a % m
# lastrow = b - ()
# print(firstrow, lastrow)
def prt(l): return print(' '.join(l))
def rv(): return map(int, input().split())
def rl(n): return [list(map(int, input().split())) for _ in range(n)]
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
solve()
``` | instruction | 0 | 47,657 | 3 | 95,314 |
No | output | 1 | 47,657 | 3 | 95,315 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well.
This time Igor K. got disappointed in one of his hobbies: editing and voicing videos. Moreover, he got disappointed in it so much, that he decided to destroy his secret archive for good.
Igor K. use Pindows XR operation system which represents files and folders by small icons. At that, m icons can fit in a horizontal row in any window.
Igor K.'s computer contains n folders in the D: disk's root catalog. The folders are numbered from 1 to n in the order from the left to the right and from top to bottom (see the images). At that the folders with secret videos have numbers from a to b inclusive. Igor K. wants to delete them forever, at that making as few frame selections as possible, and then pressing Shift+Delete exactly once. What is the minimum number of times Igor K. will have to select the folder in order to select folders from a to b and only them? Let us note that if some selected folder is selected repeatedly, then it is deselected. Each selection possesses the shape of some rectangle with sides parallel to the screen's borders.
Input
The only line contains four integers n, m, a, b (1 ≤ n, m ≤ 109, 1 ≤ a ≤ b ≤ n). They are the number of folders in Igor K.'s computer, the width of a window and the numbers of the first and the last folders that need to be deleted.
Output
Print a single number: the least possible number of times Igor K. will have to select the folders using frames to select only the folders with numbers from a to b.
Examples
Input
11 4 3 9
Output
3
Input
20 5 2 20
Output
2
Note
The images below illustrate statement tests.
The first test:
<image>
In this test we can select folders 3 and 4 with out first selection, folders 5, 6, 7, 8 with our second selection and folder 9 with our third, last selection.
The second test:
<image>
In this test we can first select all folders in the first row (2, 3, 4, 5), then — all other ones.
Submitted Solution:
```
def solve(n, m, a, b):
if ((a - 1) % m == 0 and b % m == 0) or (b - a + 1) == n:
return 1
elif a == 1 or b == n or b % m == 0 or a % m + b % m == m:
return 2
else:
return 3
ans = solve(*map(int, input().split()))
print(ans)
``` | instruction | 0 | 47,658 | 3 | 95,316 |
No | output | 1 | 47,658 | 3 | 95,317 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A lot of frogs want to cross a river. A river is w units width, but frogs can only jump l units long, where l < w. Frogs can also jump on lengths shorter than l. but can't jump longer. Hopefully, there are some stones in the river to help them.
The stones are located at integer distances from the banks. There are a_i stones at the distance of i units from the bank the frogs are currently at. Each stone can only be used once by one frog, after that it drowns in the water.
What is the maximum number of frogs that can cross the river, given that then can only jump on the stones?
Input
The first line contains two integers w and l (1 ≤ l < w ≤ 10^5) — the width of the river and the maximum length of a frog's jump.
The second line contains w - 1 integers a_1, a_2, …, a_{w-1} (0 ≤ a_i ≤ 10^4), where a_i is the number of stones at the distance i from the bank the frogs are currently at.
Output
Print a single integer — the maximum number of frogs that can cross the river.
Examples
Input
10 5
0 0 1 0 2 0 0 1 0
Output
3
Input
10 3
1 1 1 1 2 1 1 1 1
Output
3
Note
In the first sample two frogs can use the different stones at the distance 5, and one frog can use the stones at the distances 3 and then 8.
In the second sample although there are two stones at the distance 5, that does not help. The three paths are: 0 → 3 → 6 → 9 → 10, 0 → 2 → 5 → 8 → 10, 0 → 1 → 4 → 7 → 10. | instruction | 0 | 47,659 | 3 | 95,318 |
Tags: binary search, flows, greedy, two pointers
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**51, func=lambda a, b: a & b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
n, k = map(int, input().split())
l = list(map(int, input().split()))
def check(mid):
cur=0
for i in range(k-1):
cur+=l[i]
for i in range(n):
if i+k-1<n-1:
cur+=l[i+k-1]
else:
break
if i>0:
cur-=l[i-1]
#print(cur,l[i+k-1])
if cur>=mid:
continue
else:
return False
return True
#print(check(1))
st=0
end=sum(l)
ans=st
while(st<=end):
mid=(st+end)//2
#print(mid,check(mid))
if check(mid)==True:
#print(mid)
ans=mid
st=mid+1
else:
end=mid-1
print(ans)
``` | output | 1 | 47,659 | 3 | 95,319 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A lot of frogs want to cross a river. A river is w units width, but frogs can only jump l units long, where l < w. Frogs can also jump on lengths shorter than l. but can't jump longer. Hopefully, there are some stones in the river to help them.
The stones are located at integer distances from the banks. There are a_i stones at the distance of i units from the bank the frogs are currently at. Each stone can only be used once by one frog, after that it drowns in the water.
What is the maximum number of frogs that can cross the river, given that then can only jump on the stones?
Input
The first line contains two integers w and l (1 ≤ l < w ≤ 10^5) — the width of the river and the maximum length of a frog's jump.
The second line contains w - 1 integers a_1, a_2, …, a_{w-1} (0 ≤ a_i ≤ 10^4), where a_i is the number of stones at the distance i from the bank the frogs are currently at.
Output
Print a single integer — the maximum number of frogs that can cross the river.
Examples
Input
10 5
0 0 1 0 2 0 0 1 0
Output
3
Input
10 3
1 1 1 1 2 1 1 1 1
Output
3
Note
In the first sample two frogs can use the different stones at the distance 5, and one frog can use the stones at the distances 3 and then 8.
In the second sample although there are two stones at the distance 5, that does not help. The three paths are: 0 → 3 → 6 → 9 → 10, 0 → 2 → 5 → 8 → 10, 0 → 1 → 4 → 7 → 10. | instruction | 0 | 47,660 | 3 | 95,320 |
Tags: binary search, flows, greedy, two pointers
Correct Solution:
```
def read_nums():
return list(map(int, input().split()))
w, l = read_nums()
rocks = read_nums()
cur_sum = sum(rocks[0: l])
min_sum = cur_sum
for i in range(l, len(rocks)):
cur_sum -= rocks[i - l]
cur_sum += rocks[i]
min_sum = min(min_sum, cur_sum)
print(min_sum)
``` | output | 1 | 47,660 | 3 | 95,321 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A lot of frogs want to cross a river. A river is w units width, but frogs can only jump l units long, where l < w. Frogs can also jump on lengths shorter than l. but can't jump longer. Hopefully, there are some stones in the river to help them.
The stones are located at integer distances from the banks. There are a_i stones at the distance of i units from the bank the frogs are currently at. Each stone can only be used once by one frog, after that it drowns in the water.
What is the maximum number of frogs that can cross the river, given that then can only jump on the stones?
Input
The first line contains two integers w and l (1 ≤ l < w ≤ 10^5) — the width of the river and the maximum length of a frog's jump.
The second line contains w - 1 integers a_1, a_2, …, a_{w-1} (0 ≤ a_i ≤ 10^4), where a_i is the number of stones at the distance i from the bank the frogs are currently at.
Output
Print a single integer — the maximum number of frogs that can cross the river.
Examples
Input
10 5
0 0 1 0 2 0 0 1 0
Output
3
Input
10 3
1 1 1 1 2 1 1 1 1
Output
3
Note
In the first sample two frogs can use the different stones at the distance 5, and one frog can use the stones at the distances 3 and then 8.
In the second sample although there are two stones at the distance 5, that does not help. The three paths are: 0 → 3 → 6 → 9 → 10, 0 → 2 → 5 → 8 → 10, 0 → 1 → 4 → 7 → 10. | instruction | 0 | 47,661 | 3 | 95,322 |
Tags: binary search, flows, greedy, two pointers
Correct Solution:
```
# Author: Sudam Kalpage
# College: University of Peradeniya
# Date: 15/11/2020
# Contact: sudamkalpag4@gmail.com
from math import *
from itertools import permutations
from itertools import combinations
from itertools import combinations_with_replacement
import copy
def ii(): return int(input())
def si(): return input()
def mi(): return map(int, input().split())
def li(): return list(mi()) # a=[int(x) for x in input().split()]
def Function():
w,l = li()
a= li()
a.reverse()
s=sum(a[:l])
min=s
for i in range(l,w-1):
# print(s)
# print(i)
s+=a[i]
s-=a[i-l]
if s<min:
min=s
print(min)
for _ in range(1):
# for _ in range(int(input())):
# print("Case #{}: ".format(_+1),end="")
Function()
``` | output | 1 | 47,661 | 3 | 95,323 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A lot of frogs want to cross a river. A river is w units width, but frogs can only jump l units long, where l < w. Frogs can also jump on lengths shorter than l. but can't jump longer. Hopefully, there are some stones in the river to help them.
The stones are located at integer distances from the banks. There are a_i stones at the distance of i units from the bank the frogs are currently at. Each stone can only be used once by one frog, after that it drowns in the water.
What is the maximum number of frogs that can cross the river, given that then can only jump on the stones?
Input
The first line contains two integers w and l (1 ≤ l < w ≤ 10^5) — the width of the river and the maximum length of a frog's jump.
The second line contains w - 1 integers a_1, a_2, …, a_{w-1} (0 ≤ a_i ≤ 10^4), where a_i is the number of stones at the distance i from the bank the frogs are currently at.
Output
Print a single integer — the maximum number of frogs that can cross the river.
Examples
Input
10 5
0 0 1 0 2 0 0 1 0
Output
3
Input
10 3
1 1 1 1 2 1 1 1 1
Output
3
Note
In the first sample two frogs can use the different stones at the distance 5, and one frog can use the stones at the distances 3 and then 8.
In the second sample although there are two stones at the distance 5, that does not help. The three paths are: 0 → 3 → 6 → 9 → 10, 0 → 2 → 5 → 8 → 10, 0 → 1 → 4 → 7 → 10. | instruction | 0 | 47,662 | 3 | 95,324 |
Tags: binary search, flows, greedy, two pointers
Correct Solution:
```
from collections import Counter
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
##########################################################
#for _ in range(int(input())):
#import math
import sys
# from collections import deque
#from collections import Counter
# ls=list(map(int,input().split()))
# for i in range(m):
# for i in range(int(input())):
#n,k= map(int, input().split())
#arr=list(map(int,input().split()))
#n=sys.stdin.readline()
#n=int(n)
#n,k= map(int, input().split())
#arr=list(map(int,input().split()))
import sys
import math
#for _ in range(int(input())):
#a=rest,b=gym,c=code
#n,m= map(int, input().split())
#n=int(input())
n, l = map(int, input().split())
arr=list(map(int,input().split()))
ptr=l
var=1
m=sum(arr[:ptr])
val=m
ptr+=1
while ptr<n:
val=val-arr[var-1]+arr[ptr-1]
m=min(m,val)
ptr+=1
var+=1
print(m)
``` | output | 1 | 47,662 | 3 | 95,325 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A lot of frogs want to cross a river. A river is w units width, but frogs can only jump l units long, where l < w. Frogs can also jump on lengths shorter than l. but can't jump longer. Hopefully, there are some stones in the river to help them.
The stones are located at integer distances from the banks. There are a_i stones at the distance of i units from the bank the frogs are currently at. Each stone can only be used once by one frog, after that it drowns in the water.
What is the maximum number of frogs that can cross the river, given that then can only jump on the stones?
Input
The first line contains two integers w and l (1 ≤ l < w ≤ 10^5) — the width of the river and the maximum length of a frog's jump.
The second line contains w - 1 integers a_1, a_2, …, a_{w-1} (0 ≤ a_i ≤ 10^4), where a_i is the number of stones at the distance i from the bank the frogs are currently at.
Output
Print a single integer — the maximum number of frogs that can cross the river.
Examples
Input
10 5
0 0 1 0 2 0 0 1 0
Output
3
Input
10 3
1 1 1 1 2 1 1 1 1
Output
3
Note
In the first sample two frogs can use the different stones at the distance 5, and one frog can use the stones at the distances 3 and then 8.
In the second sample although there are two stones at the distance 5, that does not help. The three paths are: 0 → 3 → 6 → 9 → 10, 0 → 2 → 5 → 8 → 10, 0 → 1 → 4 → 7 → 10. | instruction | 0 | 47,663 | 3 | 95,326 |
Tags: binary search, flows, greedy, two pointers
Correct Solution:
```
w, l = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
s = res = sum(a[:l])
for i in range(l, w - 1):
s += a[i] - a[i - l]
res = min(res, s)
print(res)
``` | output | 1 | 47,663 | 3 | 95,327 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A lot of frogs want to cross a river. A river is w units width, but frogs can only jump l units long, where l < w. Frogs can also jump on lengths shorter than l. but can't jump longer. Hopefully, there are some stones in the river to help them.
The stones are located at integer distances from the banks. There are a_i stones at the distance of i units from the bank the frogs are currently at. Each stone can only be used once by one frog, after that it drowns in the water.
What is the maximum number of frogs that can cross the river, given that then can only jump on the stones?
Input
The first line contains two integers w and l (1 ≤ l < w ≤ 10^5) — the width of the river and the maximum length of a frog's jump.
The second line contains w - 1 integers a_1, a_2, …, a_{w-1} (0 ≤ a_i ≤ 10^4), where a_i is the number of stones at the distance i from the bank the frogs are currently at.
Output
Print a single integer — the maximum number of frogs that can cross the river.
Examples
Input
10 5
0 0 1 0 2 0 0 1 0
Output
3
Input
10 3
1 1 1 1 2 1 1 1 1
Output
3
Note
In the first sample two frogs can use the different stones at the distance 5, and one frog can use the stones at the distances 3 and then 8.
In the second sample although there are two stones at the distance 5, that does not help. The three paths are: 0 → 3 → 6 → 9 → 10, 0 → 2 → 5 → 8 → 10, 0 → 1 → 4 → 7 → 10. | instruction | 0 | 47,664 | 3 | 95,328 |
Tags: binary search, flows, greedy, two pointers
Correct Solution:
```
# D - Single-use Stones
w,l = [int(i) for i in input().split(' ')]
a = [1E9]*(w+1)
entrada = [int(i) for i in input().split(' ')]
for i in range (1, w):
a[i] = entrada[i-1]
aux = [0]*len(a)
num = 0
for j in range (1, w+1):
if(a[j] <= 0):
continue
if(j <= l):
aux[j] = a[j]
continue
d = j
for k in range(j - l, d):
if(aux[k] < (a[j] - aux[j])):
num = aux[k]
else:
num = a[j] - aux[j]
aux[k] = aux[k] - num
aux[j] = aux[j] + num
if(aux[j]>= a[j]):
break
print(aux[-1])
# print (w)
# print (l)
# print (a)
#############CPP################
#include <cstdio>
#include <vector>
# int main(){
# long w, l; scanf("%ld %ld", &w, &l);
# std::vector<long> a(w + 1, 2e9);
# for(long p = 1; p < w; p++){scanf("%ld", &a[p]);}
# std::vector<long> b(w + 1, 0);
# for(long p = 1; p <= w; p++){
# if(a[p] <= 0){continue;}
# if(p <= l){b[p] = a[p]; continue;}
# for(long u = p - l; u < p; u++){
# long num = (b[u] < (a[p] - b[p])) ? b[u] : (a[p] - b[p]);
# b[u] -= mv; b[p] += mv;
# if(b[p] >= a[p]){break;}
# }
# }
# printf("%ld\n", b.back());
# return 0;
# }
``` | output | 1 | 47,664 | 3 | 95,329 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A lot of frogs want to cross a river. A river is w units width, but frogs can only jump l units long, where l < w. Frogs can also jump on lengths shorter than l. but can't jump longer. Hopefully, there are some stones in the river to help them.
The stones are located at integer distances from the banks. There are a_i stones at the distance of i units from the bank the frogs are currently at. Each stone can only be used once by one frog, after that it drowns in the water.
What is the maximum number of frogs that can cross the river, given that then can only jump on the stones?
Input
The first line contains two integers w and l (1 ≤ l < w ≤ 10^5) — the width of the river and the maximum length of a frog's jump.
The second line contains w - 1 integers a_1, a_2, …, a_{w-1} (0 ≤ a_i ≤ 10^4), where a_i is the number of stones at the distance i from the bank the frogs are currently at.
Output
Print a single integer — the maximum number of frogs that can cross the river.
Examples
Input
10 5
0 0 1 0 2 0 0 1 0
Output
3
Input
10 3
1 1 1 1 2 1 1 1 1
Output
3
Note
In the first sample two frogs can use the different stones at the distance 5, and one frog can use the stones at the distances 3 and then 8.
In the second sample although there are two stones at the distance 5, that does not help. The three paths are: 0 → 3 → 6 → 9 → 10, 0 → 2 → 5 → 8 → 10, 0 → 1 → 4 → 7 → 10. | instruction | 0 | 47,665 | 3 | 95,330 |
Tags: binary search, flows, greedy, two pointers
Correct Solution:
```
I=lambda:map(int,input().split())
w,l=I()
a=list(I())
c=s=sum(a[:l])
for i in range(w-l-1):
s=s-a[i]+a[i+l]
c=min(c,s)
print(c)
``` | output | 1 | 47,665 | 3 | 95,331 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A lot of frogs want to cross a river. A river is w units width, but frogs can only jump l units long, where l < w. Frogs can also jump on lengths shorter than l. but can't jump longer. Hopefully, there are some stones in the river to help them.
The stones are located at integer distances from the banks. There are a_i stones at the distance of i units from the bank the frogs are currently at. Each stone can only be used once by one frog, after that it drowns in the water.
What is the maximum number of frogs that can cross the river, given that then can only jump on the stones?
Input
The first line contains two integers w and l (1 ≤ l < w ≤ 10^5) — the width of the river and the maximum length of a frog's jump.
The second line contains w - 1 integers a_1, a_2, …, a_{w-1} (0 ≤ a_i ≤ 10^4), where a_i is the number of stones at the distance i from the bank the frogs are currently at.
Output
Print a single integer — the maximum number of frogs that can cross the river.
Examples
Input
10 5
0 0 1 0 2 0 0 1 0
Output
3
Input
10 3
1 1 1 1 2 1 1 1 1
Output
3
Note
In the first sample two frogs can use the different stones at the distance 5, and one frog can use the stones at the distances 3 and then 8.
In the second sample although there are two stones at the distance 5, that does not help. The three paths are: 0 → 3 → 6 → 9 → 10, 0 → 2 → 5 → 8 → 10, 0 → 1 → 4 → 7 → 10. | instruction | 0 | 47,666 | 3 | 95,332 |
Tags: binary search, flows, greedy, two pointers
Correct Solution:
```
# input segment
w,l = map(int,input().split())
a=list(map(int,input().split()))
# computer minimal segemnt of length l, and a temp variable
minsegment=s=sum(a[:l])
# calculate every l segment min value,
for i in range(1,w-l):
s=s-a[i-1]+a[i+l-1]
minsegment = min(s,minsegment)
print(minsegment)
``` | output | 1 | 47,666 | 3 | 95,333 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A lot of frogs want to cross a river. A river is w units width, but frogs can only jump l units long, where l < w. Frogs can also jump on lengths shorter than l. but can't jump longer. Hopefully, there are some stones in the river to help them.
The stones are located at integer distances from the banks. There are a_i stones at the distance of i units from the bank the frogs are currently at. Each stone can only be used once by one frog, after that it drowns in the water.
What is the maximum number of frogs that can cross the river, given that then can only jump on the stones?
Input
The first line contains two integers w and l (1 ≤ l < w ≤ 10^5) — the width of the river and the maximum length of a frog's jump.
The second line contains w - 1 integers a_1, a_2, …, a_{w-1} (0 ≤ a_i ≤ 10^4), where a_i is the number of stones at the distance i from the bank the frogs are currently at.
Output
Print a single integer — the maximum number of frogs that can cross the river.
Examples
Input
10 5
0 0 1 0 2 0 0 1 0
Output
3
Input
10 3
1 1 1 1 2 1 1 1 1
Output
3
Note
In the first sample two frogs can use the different stones at the distance 5, and one frog can use the stones at the distances 3 and then 8.
In the second sample although there are two stones at the distance 5, that does not help. The three paths are: 0 → 3 → 6 → 9 → 10, 0 → 2 → 5 → 8 → 10, 0 → 1 → 4 → 7 → 10.
Submitted Solution:
```
n,l = list(map(int,input().split()))
stones = list(map(int,input().split()))
summ = sum(stones[:l])
#print(summ)
minn = summ
for i in range(n-l-1) :
#print(i,l+i)
summ = summ + stones[l+i] - stones[i]
if(summ<minn) :
minn = summ
print(minn)
``` | instruction | 0 | 47,667 | 3 | 95,334 |
Yes | output | 1 | 47,667 | 3 | 95,335 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A lot of frogs want to cross a river. A river is w units width, but frogs can only jump l units long, where l < w. Frogs can also jump on lengths shorter than l. but can't jump longer. Hopefully, there are some stones in the river to help them.
The stones are located at integer distances from the banks. There are a_i stones at the distance of i units from the bank the frogs are currently at. Each stone can only be used once by one frog, after that it drowns in the water.
What is the maximum number of frogs that can cross the river, given that then can only jump on the stones?
Input
The first line contains two integers w and l (1 ≤ l < w ≤ 10^5) — the width of the river and the maximum length of a frog's jump.
The second line contains w - 1 integers a_1, a_2, …, a_{w-1} (0 ≤ a_i ≤ 10^4), where a_i is the number of stones at the distance i from the bank the frogs are currently at.
Output
Print a single integer — the maximum number of frogs that can cross the river.
Examples
Input
10 5
0 0 1 0 2 0 0 1 0
Output
3
Input
10 3
1 1 1 1 2 1 1 1 1
Output
3
Note
In the first sample two frogs can use the different stones at the distance 5, and one frog can use the stones at the distances 3 and then 8.
In the second sample although there are two stones at the distance 5, that does not help. The three paths are: 0 → 3 → 6 → 9 → 10, 0 → 2 → 5 → 8 → 10, 0 → 1 → 4 → 7 → 10.
Submitted Solution:
```
n,jump=map(int,input().split())
arr=list(map(int,input().split()))
pt1,pt2=0,jump
while pt2 <n-1:
count=0
flag=0
while pt1 <pt2:
if count +arr[pt1] <=arr[pt2]:
count +=arr[pt1]
arr[pt1] =0
pt1+=1
else:
arr[pt1] -=max(0,(arr[pt2]-count))
flag=1
break
if flag==0:
arr[pt2] =count
pt2+=1
pt1=max(pt1,pt2 -jump)
print(sum(arr[n-jump-1:]))
``` | instruction | 0 | 47,668 | 3 | 95,336 |
Yes | output | 1 | 47,668 | 3 | 95,337 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A lot of frogs want to cross a river. A river is w units width, but frogs can only jump l units long, where l < w. Frogs can also jump on lengths shorter than l. but can't jump longer. Hopefully, there are some stones in the river to help them.
The stones are located at integer distances from the banks. There are a_i stones at the distance of i units from the bank the frogs are currently at. Each stone can only be used once by one frog, after that it drowns in the water.
What is the maximum number of frogs that can cross the river, given that then can only jump on the stones?
Input
The first line contains two integers w and l (1 ≤ l < w ≤ 10^5) — the width of the river and the maximum length of a frog's jump.
The second line contains w - 1 integers a_1, a_2, …, a_{w-1} (0 ≤ a_i ≤ 10^4), where a_i is the number of stones at the distance i from the bank the frogs are currently at.
Output
Print a single integer — the maximum number of frogs that can cross the river.
Examples
Input
10 5
0 0 1 0 2 0 0 1 0
Output
3
Input
10 3
1 1 1 1 2 1 1 1 1
Output
3
Note
In the first sample two frogs can use the different stones at the distance 5, and one frog can use the stones at the distances 3 and then 8.
In the second sample although there are two stones at the distance 5, that does not help. The three paths are: 0 → 3 → 6 → 9 → 10, 0 → 2 → 5 → 8 → 10, 0 → 1 → 4 → 7 → 10.
Submitted Solution:
```
from collections import deque
w, l = map(int, input().split())
a = [0] + list(map(int, input().split())) + [0]
removable_que = deque([])
cnt = [0]*(w)
ans = 0
for pos in range(w-l, w):
cnt[pos] = a[pos]
for pos in range(w-1, 0, -1):
if pos <= l:
ans += cnt[pos]
continue
#pos > l
removable_que.appendleft(pos - l)
val = cnt[pos]
while removable_que and removable_que[-1] >= pos:
removable_que.pop()
while val > 0 and removable_que:
poped_index = removable_que.popleft()
d = a[poped_index] - cnt[poped_index]
if d == 0:
continue
if d >= val:
cnt[poped_index] += val
val = 0
removable_que.appendleft(poped_index)
continue
else:
cnt[poped_index] += d
val -= d
continue
print(ans)
``` | instruction | 0 | 47,669 | 3 | 95,338 |
Yes | output | 1 | 47,669 | 3 | 95,339 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A lot of frogs want to cross a river. A river is w units width, but frogs can only jump l units long, where l < w. Frogs can also jump on lengths shorter than l. but can't jump longer. Hopefully, there are some stones in the river to help them.
The stones are located at integer distances from the banks. There are a_i stones at the distance of i units from the bank the frogs are currently at. Each stone can only be used once by one frog, after that it drowns in the water.
What is the maximum number of frogs that can cross the river, given that then can only jump on the stones?
Input
The first line contains two integers w and l (1 ≤ l < w ≤ 10^5) — the width of the river and the maximum length of a frog's jump.
The second line contains w - 1 integers a_1, a_2, …, a_{w-1} (0 ≤ a_i ≤ 10^4), where a_i is the number of stones at the distance i from the bank the frogs are currently at.
Output
Print a single integer — the maximum number of frogs that can cross the river.
Examples
Input
10 5
0 0 1 0 2 0 0 1 0
Output
3
Input
10 3
1 1 1 1 2 1 1 1 1
Output
3
Note
In the first sample two frogs can use the different stones at the distance 5, and one frog can use the stones at the distances 3 and then 8.
In the second sample although there are two stones at the distance 5, that does not help. The three paths are: 0 → 3 → 6 → 9 → 10, 0 → 2 → 5 → 8 → 10, 0 → 1 → 4 → 7 → 10.
Submitted Solution:
```
w, l = map(int,input().split())
a = tuple(map(int,input().split()))
sumat = sum(a[:l])
mini = sumat
for i in range(w-l-1):
sumat = sumat - a[i] +a[i+l]
mini = min(mini, sumat)
print(mini)
``` | instruction | 0 | 47,670 | 3 | 95,340 |
Yes | output | 1 | 47,670 | 3 | 95,341 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A lot of frogs want to cross a river. A river is w units width, but frogs can only jump l units long, where l < w. Frogs can also jump on lengths shorter than l. but can't jump longer. Hopefully, there are some stones in the river to help them.
The stones are located at integer distances from the banks. There are a_i stones at the distance of i units from the bank the frogs are currently at. Each stone can only be used once by one frog, after that it drowns in the water.
What is the maximum number of frogs that can cross the river, given that then can only jump on the stones?
Input
The first line contains two integers w and l (1 ≤ l < w ≤ 10^5) — the width of the river and the maximum length of a frog's jump.
The second line contains w - 1 integers a_1, a_2, …, a_{w-1} (0 ≤ a_i ≤ 10^4), where a_i is the number of stones at the distance i from the bank the frogs are currently at.
Output
Print a single integer — the maximum number of frogs that can cross the river.
Examples
Input
10 5
0 0 1 0 2 0 0 1 0
Output
3
Input
10 3
1 1 1 1 2 1 1 1 1
Output
3
Note
In the first sample two frogs can use the different stones at the distance 5, and one frog can use the stones at the distances 3 and then 8.
In the second sample although there are two stones at the distance 5, that does not help. The three paths are: 0 → 3 → 6 → 9 → 10, 0 → 2 → 5 → 8 → 10, 0 → 1 → 4 → 7 → 10.
Submitted Solution:
```
T = input().split(' ')
w = int(T[0])
l = int(T[1])
S = input().split(' ')
for i in range(len(S)):
S[i] = [int(S[i]), 0]
for i in range(l):
S[i][1] = S[i][0]
for i in range((w-1)//l - 1):
ix = (i+1) * l - 1
iy = (i+2) * l - 1
while ix > i * l - 1 and iy > (i+1) * l - 1:
if iy - ix > l:
iy -= 1
elif S[ix][1] >= S[iy][0]:
S[ix][1] -= S[iy][0]
S[iy][1] += S[iy][0]
S[iy][0] = 0
iy -= 1
if S[ix][1] == 0:
ix -= 1
else:
S[iy][0] -= S[ix][1]
S[iy][1] += S[ix][1]
S[ix][1] = 0
ix -= 1
ix = (i+2) * l - 1
iy = (i+2) * l - 1
while ix > (i+1) * l - 1 and iy > (i+1) * l - 1:
if iy == ix:
ix -= 1
elif S[ix][1] >= S[iy][0]:
S[ix][1] -= S[iy][0]
S[iy][1] += S[iy][0]
S[iy][0] = 0
iy -= 1
if S[ix][1] == 0:
ix -= 1
else:
S[iy][0] -= S[ix][1]
S[iy][1] += S[ix][1]
S[ix][1] = 0
ix -= 1
if (w-1) % l != 0:
ix = w-2-l
iy = w-2
while ix > ((w-1)//l - 1) * l - 1 and iy > w-2-l:
if iy - ix > l:
iy -= 1
elif S[ix][1] >= S[iy][0]:
S[ix][1] -= S[iy][0]
S[iy][1] += S[iy][0]
S[iy][0] = 0
iy -= 1
if S[ix][1] == 0:
ix -= 1
else:
S[iy][0] -= S[ix][1]
S[iy][1] += S[ix][1]
S[ix][1] = 0
ix -= 1
sol = 0
rs = (w-1) % l
if rs == 0:
rs += l
for i in range(w-1-l, w-1):
sol += S[i][1]
print(sol)
``` | instruction | 0 | 47,671 | 3 | 95,342 |
No | output | 1 | 47,671 | 3 | 95,343 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A lot of frogs want to cross a river. A river is w units width, but frogs can only jump l units long, where l < w. Frogs can also jump on lengths shorter than l. but can't jump longer. Hopefully, there are some stones in the river to help them.
The stones are located at integer distances from the banks. There are a_i stones at the distance of i units from the bank the frogs are currently at. Each stone can only be used once by one frog, after that it drowns in the water.
What is the maximum number of frogs that can cross the river, given that then can only jump on the stones?
Input
The first line contains two integers w and l (1 ≤ l < w ≤ 10^5) — the width of the river and the maximum length of a frog's jump.
The second line contains w - 1 integers a_1, a_2, …, a_{w-1} (0 ≤ a_i ≤ 10^4), where a_i is the number of stones at the distance i from the bank the frogs are currently at.
Output
Print a single integer — the maximum number of frogs that can cross the river.
Examples
Input
10 5
0 0 1 0 2 0 0 1 0
Output
3
Input
10 3
1 1 1 1 2 1 1 1 1
Output
3
Note
In the first sample two frogs can use the different stones at the distance 5, and one frog can use the stones at the distances 3 and then 8.
In the second sample although there are two stones at the distance 5, that does not help. The three paths are: 0 → 3 → 6 → 9 → 10, 0 → 2 → 5 → 8 → 10, 0 → 1 → 4 → 7 → 10.
Submitted Solution:
```
w, l = [int(item) for item in input().split()]
a = [int(item) for item in input().split()]
b = a[:l]
i = l
for i in range(l, w - l, l):
for j in range(l-1, 0, -1):
if b[j] > a[i+j]:
b[j-1] += b[j] - a[i+j]
b[j] = a[i+j]
b[0] = min(b[0], a[i])
i += l
for k in range(w-2, i-1, -1):
if b[k - i] > a[k]:
if k > i:
b[k - i -1] += b[k - i] - a[k]
b[k - i] = a[k]
print(sum(b))
``` | instruction | 0 | 47,672 | 3 | 95,344 |
No | output | 1 | 47,672 | 3 | 95,345 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A lot of frogs want to cross a river. A river is w units width, but frogs can only jump l units long, where l < w. Frogs can also jump on lengths shorter than l. but can't jump longer. Hopefully, there are some stones in the river to help them.
The stones are located at integer distances from the banks. There are a_i stones at the distance of i units from the bank the frogs are currently at. Each stone can only be used once by one frog, after that it drowns in the water.
What is the maximum number of frogs that can cross the river, given that then can only jump on the stones?
Input
The first line contains two integers w and l (1 ≤ l < w ≤ 10^5) — the width of the river and the maximum length of a frog's jump.
The second line contains w - 1 integers a_1, a_2, …, a_{w-1} (0 ≤ a_i ≤ 10^4), where a_i is the number of stones at the distance i from the bank the frogs are currently at.
Output
Print a single integer — the maximum number of frogs that can cross the river.
Examples
Input
10 5
0 0 1 0 2 0 0 1 0
Output
3
Input
10 3
1 1 1 1 2 1 1 1 1
Output
3
Note
In the first sample two frogs can use the different stones at the distance 5, and one frog can use the stones at the distances 3 and then 8.
In the second sample although there are two stones at the distance 5, that does not help. The three paths are: 0 → 3 → 6 → 9 → 10, 0 → 2 → 5 → 8 → 10, 0 → 1 → 4 → 7 → 10.
Submitted Solution:
```
w,h = map(int,input().split())
ai = list(map(int,input().split()))
fenTree = [0]*(w-h+1)
for i in range(h):
fenTree[0] += ai[i]
for i in range(1,w-2*h):
ai[i+h-1] = min(ai[i+h-1],fenTree[i-1])
fenTree[i] = max(min(fenTree[i-1],fenTree[i-1] + ai[i+h-1]- ai[i-1]),0)
summ = 0
for i in range(w-h-1,w-1):
summ += ai[i]
print(min(fenTree[max(w-2*h-1,0)],summ))
``` | instruction | 0 | 47,673 | 3 | 95,346 |
No | output | 1 | 47,673 | 3 | 95,347 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A lot of frogs want to cross a river. A river is w units width, but frogs can only jump l units long, where l < w. Frogs can also jump on lengths shorter than l. but can't jump longer. Hopefully, there are some stones in the river to help them.
The stones are located at integer distances from the banks. There are a_i stones at the distance of i units from the bank the frogs are currently at. Each stone can only be used once by one frog, after that it drowns in the water.
What is the maximum number of frogs that can cross the river, given that then can only jump on the stones?
Input
The first line contains two integers w and l (1 ≤ l < w ≤ 10^5) — the width of the river and the maximum length of a frog's jump.
The second line contains w - 1 integers a_1, a_2, …, a_{w-1} (0 ≤ a_i ≤ 10^4), where a_i is the number of stones at the distance i from the bank the frogs are currently at.
Output
Print a single integer — the maximum number of frogs that can cross the river.
Examples
Input
10 5
0 0 1 0 2 0 0 1 0
Output
3
Input
10 3
1 1 1 1 2 1 1 1 1
Output
3
Note
In the first sample two frogs can use the different stones at the distance 5, and one frog can use the stones at the distances 3 and then 8.
In the second sample although there are two stones at the distance 5, that does not help. The three paths are: 0 → 3 → 6 → 9 → 10, 0 → 2 → 5 → 8 → 10, 0 → 1 → 4 → 7 → 10.
Submitted Solution:
```
w,l=map(int,input().split())
a=list(map(int,input().split()))
#print (a)
def fill(a1,a2):
#each len l
a3=[0]*l
for i in range(l-1,-1,-1):
num=a1[i]
j=i
while num>0 and j>=0:
if num>=a2[j]:
a3[j]+=a2[j]
num-=a2[j]
else:
a3[j] += num
num = 0
j-=1
return a3
a_current = a[:l]
r=(w-1)%l
for i in range((w-1)//l):
if i==0:
continue
a_current = fill(a_current, a[i*l:(i+1)*l])
ans=0
ans+=sum(a_current[-l+r:])
ans+=sum(fill([0]*(l-r)+a_current[:-l+r],[0]*(l-r)+a[-r:]))
print(ans)
``` | instruction | 0 | 47,674 | 3 | 95,348 |
No | output | 1 | 47,674 | 3 | 95,349 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dr. A of the Aizu Institute of Biological Research discovered a mysterious insect on a certain southern island. The shape is elongated like a hornworm, but since one segment is shaped like a ball, it looks like a beaded ball connected by a thread. What was strange was that there were many variations in body color, and some insects changed their body color over time. It seems that the color of the somites of all insects is limited to either red, green or blue, but the color of the somites changes every second, and finally all the somites become the same color and settle down. In some cases, the color seemed to keep changing no matter how long I waited.
<image>
As I investigated, I found that all the body segments usually have the same color, but after being surprised or excited by something, the color of the body segments changes without permission. It turns out that once the color of the segment changes, it will continue to change until all the segment are the same color again.
Dr. A was curiously observing how the color changed when he caught and excited many of these insects, but the way the color changed during the color change is as follows. I noticed that there is regularity.
* The color changes only in one pair of two adjacent somites of different colors, and the colors of the other somites do not change. However, when there are multiple such pairs, it is not possible to predict in advance which pair will change color.
* Such a pair will change to a color that is neither of the colors of the two segmentes at the same time (for example, if the green and red segment are adjacent, they will change to blue at the same time).
<image>
The figure above shows all the changes in the color of the insects up to 2 seconds later. Suppose you have an insect that has the color shown in the upper part of the figure. At this time, there are 3 pairs of adjacent somites of different colors, so after 1 second, it will change to one of the 3 colors drawn side by side in the middle row. After 1 second, all the segments can turn green after 2 seconds (second from the left in the lower row of the figure) when they change to the two on the left side of the middle row. On the other hand, when it changes like the one on the far right in the middle row after 1 second, all the segments do not change to the same color after 2 seconds.
He decided to predict if all the insect segments in front of him could be the same color, and if so, at the earliest, how many seconds later.
Create a program that takes the color sequence of the insect body segments in front of you as input and outputs the shortest time required for all the insect body segments to have the same color in seconds. However, if there is no possibility that the colors will be the same, output "NA (half-width uppercase letters)". In addition, the color sequence of the insect body segment is represented by a character string consisting of r (red), g (green), and b (blue) of 2 or more and 10 or less.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. For each dataset, one string is given on one line that represents information about the insect's somites.
The number of datasets does not exceed 100.
Output
For each dataset, the minimum time (integer in seconds) or NA required for all segment colors to be the same is output on one line.
Example
Input
rbgrg
rbbgbbr
bgr
bgrbrgbr
bggrgbgrr
gbrggrbggr
rrrrr
bgbr
0
Output
5
7
1
6
NA
8
0
4
Submitted Solution:
```
from collections import deque
def only_color(s):
temp = s[0]
for i in range(1, len(s)):
c = s[i]
if temp != c:
return False
temp = c
return True
def new_color(s, i):
color = [c for c in ("r", "g", "b") if c not in (s[i], s[i + 1])][0]
return s[:i] + color * 2 + s[i + 2:]
def solve(s):
if only_color(s):
print(0)
return
length = len(s)
dic = {}
que = deque()
que.append((s, 0))
while que:
colors, score = que.popleft()
score += 1
temp = colors[0]
for i in range(1, length):
ci = colors[i]
if ci != temp:
new = new_color(colors, i - 1)
if only_color(new):
print(score)
return
if new not in dic:
dic[new] = score
que.append((new, score))
temp = ci
else:
print("NA")
def main():
while True:
s = input()
if s == "0":
break
solve(s)
main()
``` | instruction | 0 | 47,862 | 3 | 95,724 |
Yes | output | 1 | 47,862 | 3 | 95,725 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dr. A of the Aizu Institute of Biological Research discovered a mysterious insect on a certain southern island. The shape is elongated like a hornworm, but since one segment is shaped like a ball, it looks like a beaded ball connected by a thread. What was strange was that there were many variations in body color, and some insects changed their body color over time. It seems that the color of the somites of all insects is limited to either red, green or blue, but the color of the somites changes every second, and finally all the somites become the same color and settle down. In some cases, the color seemed to keep changing no matter how long I waited.
<image>
As I investigated, I found that all the body segments usually have the same color, but after being surprised or excited by something, the color of the body segments changes without permission. It turns out that once the color of the segment changes, it will continue to change until all the segment are the same color again.
Dr. A was curiously observing how the color changed when he caught and excited many of these insects, but the way the color changed during the color change is as follows. I noticed that there is regularity.
* The color changes only in one pair of two adjacent somites of different colors, and the colors of the other somites do not change. However, when there are multiple such pairs, it is not possible to predict in advance which pair will change color.
* Such a pair will change to a color that is neither of the colors of the two segmentes at the same time (for example, if the green and red segment are adjacent, they will change to blue at the same time).
<image>
The figure above shows all the changes in the color of the insects up to 2 seconds later. Suppose you have an insect that has the color shown in the upper part of the figure. At this time, there are 3 pairs of adjacent somites of different colors, so after 1 second, it will change to one of the 3 colors drawn side by side in the middle row. After 1 second, all the segments can turn green after 2 seconds (second from the left in the lower row of the figure) when they change to the two on the left side of the middle row. On the other hand, when it changes like the one on the far right in the middle row after 1 second, all the segments do not change to the same color after 2 seconds.
He decided to predict if all the insect segments in front of him could be the same color, and if so, at the earliest, how many seconds later.
Create a program that takes the color sequence of the insect body segments in front of you as input and outputs the shortest time required for all the insect body segments to have the same color in seconds. However, if there is no possibility that the colors will be the same, output "NA (half-width uppercase letters)". In addition, the color sequence of the insect body segment is represented by a character string consisting of r (red), g (green), and b (blue) of 2 or more and 10 or less.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. For each dataset, one string is given on one line that represents information about the insect's somites.
The number of datasets does not exceed 100.
Output
For each dataset, the minimum time (integer in seconds) or NA required for all segment colors to be the same is output on one line.
Example
Input
rbgrg
rbbgbbr
bgr
bgrbrgbr
bggrgbgrr
gbrggrbggr
rrrrr
bgbr
0
Output
5
7
1
6
NA
8
0
4
Submitted Solution:
```
from collections import deque
import copy
def another_color(a, b):
if a == 'r' and b == 'g' or a == 'g' and b == 'r':
return 'b'
if a == 'r' and b == 'b' or a == 'b' and b == 'r':
return 'g'
if a == 'g' and b == 'b' or a == 'b' and b == 'g':
return 'r'
return None
def is_all_same_elements(es):
return all([e == es[0] for e in es[1:]]) if es else False
class State:
def __init__(self, sequence):
self.colors = list(sequence)
self.label = sequence
self.depth = 0
def nextStates(self):
nextStates = []
for i in range(1, len(self.colors)):
if self.colors[i] != self.colors[i - 1]:
c = another_color(self.colors[i], self.colors[i - 1])
if c is None:
continue
newColors = copy.copy(self.colors)
newColors[i] = c
newColors[i - 1] = c
nextStates.append(State(''.join(newColors)))
return nextStates
def print(self):
print(self.depth)
# for debug
# print("{} {}".format(self.label, self.depth))
sequence = input()
while sequence != '0':
root = State(sequence)
printed = False
visited = [root.label]
queue = deque([])
queue.append(root)
# BFS
while queue:
state = queue.popleft()
if is_all_same_elements(state.colors):
state.print()
printed = True
break
for nextState in state.nextStates():
if not nextState.label in visited:
visited.append(nextState.label)
nextState.depth = state.depth + 1
queue.append(nextState)
if not printed:
print("NA")
# 次の行へ
sequence = input()
``` | instruction | 0 | 47,863 | 3 | 95,726 |
No | output | 1 | 47,863 | 3 | 95,727 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dr. A of the Aizu Institute of Biological Research discovered a mysterious insect on a certain southern island. The shape is elongated like a hornworm, but since one segment is shaped like a ball, it looks like a beaded ball connected by a thread. What was strange was that there were many variations in body color, and some insects changed their body color over time. It seems that the color of the somites of all insects is limited to either red, green or blue, but the color of the somites changes every second, and finally all the somites become the same color and settle down. In some cases, the color seemed to keep changing no matter how long I waited.
<image>
As I investigated, I found that all the body segments usually have the same color, but after being surprised or excited by something, the color of the body segments changes without permission. It turns out that once the color of the segment changes, it will continue to change until all the segment are the same color again.
Dr. A was curiously observing how the color changed when he caught and excited many of these insects, but the way the color changed during the color change is as follows. I noticed that there is regularity.
* The color changes only in one pair of two adjacent somites of different colors, and the colors of the other somites do not change. However, when there are multiple such pairs, it is not possible to predict in advance which pair will change color.
* Such a pair will change to a color that is neither of the colors of the two segmentes at the same time (for example, if the green and red segment are adjacent, they will change to blue at the same time).
<image>
The figure above shows all the changes in the color of the insects up to 2 seconds later. Suppose you have an insect that has the color shown in the upper part of the figure. At this time, there are 3 pairs of adjacent somites of different colors, so after 1 second, it will change to one of the 3 colors drawn side by side in the middle row. After 1 second, all the segments can turn green after 2 seconds (second from the left in the lower row of the figure) when they change to the two on the left side of the middle row. On the other hand, when it changes like the one on the far right in the middle row after 1 second, all the segments do not change to the same color after 2 seconds.
He decided to predict if all the insect segments in front of him could be the same color, and if so, at the earliest, how many seconds later.
Create a program that takes the color sequence of the insect body segments in front of you as input and outputs the shortest time required for all the insect body segments to have the same color in seconds. However, if there is no possibility that the colors will be the same, output "NA (half-width uppercase letters)". In addition, the color sequence of the insect body segment is represented by a character string consisting of r (red), g (green), and b (blue) of 2 or more and 10 or less.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. For each dataset, one string is given on one line that represents information about the insect's somites.
The number of datasets does not exceed 100.
Output
For each dataset, the minimum time (integer in seconds) or NA required for all segment colors to be the same is output on one line.
Example
Input
rbgrg
rbbgbbr
bgr
bgrbrgbr
bggrgbgrr
gbrggrbggr
rrrrr
bgbr
0
Output
5
7
1
6
NA
8
0
4
Submitted Solution:
```
from collections import deque
import copy
def another_color(a, b):
if not a == 'r' and not b == 'r':
return 'r'
if not a == 'g' and not b == 'g':
return 'g'
return 'b'
def is_all_same_elements(es):
return all([e == es[0] for e in es[1:]]) if es else False
class State:
def __init__(self, sequence):
self.colors = list(sequence)
self.label = sequence
self.depth = 0
def nextStates(self):
nextStates = []
for i in range(1, len(self.colors)):
if self.colors[i] != self.colors[i - 1]:
c = another_color(self.colors[i], self.colors[i - 1])
newColors = copy.copy(self.colors)
newColors[i] = c
newColors[i - 1] = c
nextStates.append(State(''.join(newColors)))
return nextStates
def print(self):
print(self.depth)
# for debug
# print("{} {}".format(self.label, self.depth))
sequence = input()
while sequence != '0':
root = State(sequence)
printed = False
visited = [root.label]
queue = deque([])
queue.append(root)
# BFS
while queue:
state = queue.popleft()
if is_all_same_elements(state.colors):
state.print()
printed = True
break
for nextState in state.nextStates():
if not nextState.label in visited:
visited.append(nextState.label)
nextState.depth = state.depth + 1
queue.append(nextState)
if not printed:
print("NA")
# 次の行へ
sequence = input()
``` | instruction | 0 | 47,864 | 3 | 95,728 |
No | output | 1 | 47,864 | 3 | 95,729 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dr. A of the Aizu Institute of Biological Research discovered a mysterious insect on a certain southern island. The shape is elongated like a hornworm, but since one segment is shaped like a ball, it looks like a beaded ball connected by a thread. What was strange was that there were many variations in body color, and some insects changed their body color over time. It seems that the color of the somites of all insects is limited to either red, green or blue, but the color of the somites changes every second, and finally all the somites become the same color and settle down. In some cases, the color seemed to keep changing no matter how long I waited.
<image>
As I investigated, I found that all the body segments usually have the same color, but after being surprised or excited by something, the color of the body segments changes without permission. It turns out that once the color of the segment changes, it will continue to change until all the segment are the same color again.
Dr. A was curiously observing how the color changed when he caught and excited many of these insects, but the way the color changed during the color change is as follows. I noticed that there is regularity.
* The color changes only in one pair of two adjacent somites of different colors, and the colors of the other somites do not change. However, when there are multiple such pairs, it is not possible to predict in advance which pair will change color.
* Such a pair will change to a color that is neither of the colors of the two segmentes at the same time (for example, if the green and red segment are adjacent, they will change to blue at the same time).
<image>
The figure above shows all the changes in the color of the insects up to 2 seconds later. Suppose you have an insect that has the color shown in the upper part of the figure. At this time, there are 3 pairs of adjacent somites of different colors, so after 1 second, it will change to one of the 3 colors drawn side by side in the middle row. After 1 second, all the segments can turn green after 2 seconds (second from the left in the lower row of the figure) when they change to the two on the left side of the middle row. On the other hand, when it changes like the one on the far right in the middle row after 1 second, all the segments do not change to the same color after 2 seconds.
He decided to predict if all the insect segments in front of him could be the same color, and if so, at the earliest, how many seconds later.
Create a program that takes the color sequence of the insect body segments in front of you as input and outputs the shortest time required for all the insect body segments to have the same color in seconds. However, if there is no possibility that the colors will be the same, output "NA (half-width uppercase letters)". In addition, the color sequence of the insect body segment is represented by a character string consisting of r (red), g (green), and b (blue) of 2 or more and 10 or less.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. For each dataset, one string is given on one line that represents information about the insect's somites.
The number of datasets does not exceed 100.
Output
For each dataset, the minimum time (integer in seconds) or NA required for all segment colors to be the same is output on one line.
Example
Input
rbgrg
rbbgbbr
bgr
bgrbrgbr
bggrgbgrr
gbrggrbggr
rrrrr
bgbr
0
Output
5
7
1
6
NA
8
0
4
Submitted Solution:
```
import sys
sys.setrecursionlimit(100000)
from collections import deque
import copy
def another_color(a, b):
if not a == 'r' and not b == 'r':
return 'r'
if not a == 'g' and not b == 'g':
return 'g'
return 'b'
def is_all_same_elements(es):
return all([e == es[0] for e in es[1:]]) if es else False
class State:
def __init__(self, sequence):
self.colors = list(sequence)
self.label = sequence
self.depth = 0
def nextStates(self):
nextStates = []
for i in range(1, len(self.colors)):
if self.colors[i] != self.colors[i - 1]:
c = another_color(self.colors[i], self.colors[i - 1])
newColors = copy.copy(self.colors)
newColors[i] = c
newColors[i - 1] = c
nextStates.append(State(''.join(newColors)))
return nextStates
def print(self):
print(self.depth)
# for debug
# print("{} {}".format(self.label, self.depth))
sequence = input()
while sequence != '0':
root = State(sequence)
printed = False
visited = [root.label]
queue = deque([])
queue.append(root)
# BFS
while queue:
state = queue.popleft()
if is_all_same_elements(state.colors):
state.print()
printed = True
break
for nextState in state.nextStates():
if not nextState.label in visited:
visited.append(nextState.label)
nextState.depth = state.depth + 1
queue.append(nextState)
if not printed:
print("NA")
# 次の行へ
sequence = input()
``` | instruction | 0 | 47,865 | 3 | 95,730 |
No | output | 1 | 47,865 | 3 | 95,731 |
Provide a correct Python 3 solution for this coding contest problem.
In the good old days, the Internet was free from fears and terrorism. People did not have to worry about any cyber criminals or mad computer scientists. Today, however, you are facing atrocious crackers wherever you are, unless being disconnected. You have to protect yourselves against their attacks.
Counting upon your excellent talent for software construction and strong sense of justice, you are invited to work as a cyber guardian. Your ultimate mission is to create a perfect firewall system that can completely shut out any intruders invading networks and protect children from harmful information exposed on the Net. However, it is extremely difficult and none have ever achieved it before. As the first step, instead, you are now requested to write a software simulator under much simpler assumptions.
In general, a firewall system works at the entrance of a local network of an organization (e.g., a company or a university) and enforces its local administrative policy. It receives both inbound and outbound packets (note: data transmitted on the Net are divided into small segments called packets) and carefully inspects them one by one whether or not each of them is legal. The definition of the legality may vary from site to site or depend upon the local administrative policy of an organization. Your simulator should accept data representing not only received packets but also the local administrative policy.
For simplicity in this problem we assume that each network packet consists of three fields: its source address, destination address, and message body. The source address specifies the computer or appliance that transmits the packet and the destination address specifies the computer or appliance to which the packet is transmitted. An address in your simulator is represented as eight digits such as 03214567 or 31415926, instead of using the standard notation of IP addresses such as 192.168.1.1. Administrative policy is described in filtering rules, each of which specifies some collection of source-destination address pairs and defines those packets with the specified address pairs either legal or illegal.
Input
The input consists of several data sets, each of which represents filtering rules and received packets in the following format:
n m
rule1
rule2
...
rulen
packet1
packet2
...
packetm
The first line consists of two non-negative integers n and m. If both n and m are zeros, this means the end of input. Otherwise, n lines, each representing a filtering rule, and m lines, each representing an arriving packet, follow in this order. You may assume that n and m are less than or equal to 1,024.
Each rulei is in one of the following formats:
permit source-pattern destination-pattern
deny source-pattern destination-pattern
A source-pattern or destination-pattern is a character string of length eight, where each character is either a digit ('0' to '9') or a wildcard character '?'. For instance, "1????5??" matches any address whose first and fifth digits are '1' and '5', respectively. In general, a wildcard character matches any single digit while a digit matches only itself.
With the keywords "permit" and "deny", filtering rules specify legal and illegal packets, respectively. That is, if the source and destination addresses of a packed are matched with source-pattern and destination-pattern, respectively, it is permitted to pass the firewall or the request is denied according to the keyword. Note that a permit rule and a deny rule can contradict since they may share the same source and destination address pair. For the purpose of conflict resolution, we define a priority rule: rulei has a higher priority over rulej if and only if i > j. For completeness, we define the default rule: any packet is illegal unless being explicitly specified legal by some given rule.
A packet is in the following format:
source-address destination-address message-body
Each of the first two is a character string of length eight that consists solely of digits. The last one is a character string consisting solely of alphanumeric characters ('a' to 'z', 'A' to 'Z', and '0' to '9'). Neither whitespaces nor special characters can occur in a message body. You may assume that it is not empty and that its length is at most 50.
You may also assume that there is exactly one space character between any two adjacent fields in an input line representing a rule or a packet.
Output
For each data set, print the number of legal packets in the first line, followed by all legal packets in the same order as they occur in the data set. Each packet must be written exactly in one line. If the data set includes two packets consisting of the same source and destination addresses and the same message body, you should consider them different packets and so they must be written in different lines. Any extra whitespaces or extra empty lines must not be written.
Example
Input
2 5
permit 192168?? ?12??34?
deny 19216899 012343?5
19216711 11233340 HiIamACracker
19216891 01234345 Hello
19216899 01234345 HiIamAlsoACracker
19216809 11200340 World
00000000 99999999 TheEndOfTheWorld
1 2
permit 12345678 23456789
19216891 01234345 Hello
12345678 23456789 Hello
0 0
Output
2
19216891 01234345 Hello
19216809 11200340 World
1
12345678 23456789 Hello | instruction | 0 | 47,887 | 3 | 95,774 |
"Correct Solution:
```
# AOJ 1111: Cyber Guardian
# Python3 2018.7.15 bal4u
import re
while True:
n, m = map(int, input().split())
if (n|m) == 0: break
rule, ans = [], []
for i in range(n):
g, s, d = input().split()
rule.append((g[0] == 'p', re.compile((s+d).replace("?", "[0-9]"))))
for i in range(m):
s, d, m = input().split()
sd = s+d
for G, SD in rule[::-1]:
if re.match(SD, sd):
if G: ans.append((s, d, m))
break
print(len(ans))
for a in ans: print(*a)
``` | output | 1 | 47,887 | 3 | 95,775 |
Provide a correct Python 3 solution for this coding contest problem.
In the good old days, the Internet was free from fears and terrorism. People did not have to worry about any cyber criminals or mad computer scientists. Today, however, you are facing atrocious crackers wherever you are, unless being disconnected. You have to protect yourselves against their attacks.
Counting upon your excellent talent for software construction and strong sense of justice, you are invited to work as a cyber guardian. Your ultimate mission is to create a perfect firewall system that can completely shut out any intruders invading networks and protect children from harmful information exposed on the Net. However, it is extremely difficult and none have ever achieved it before. As the first step, instead, you are now requested to write a software simulator under much simpler assumptions.
In general, a firewall system works at the entrance of a local network of an organization (e.g., a company or a university) and enforces its local administrative policy. It receives both inbound and outbound packets (note: data transmitted on the Net are divided into small segments called packets) and carefully inspects them one by one whether or not each of them is legal. The definition of the legality may vary from site to site or depend upon the local administrative policy of an organization. Your simulator should accept data representing not only received packets but also the local administrative policy.
For simplicity in this problem we assume that each network packet consists of three fields: its source address, destination address, and message body. The source address specifies the computer or appliance that transmits the packet and the destination address specifies the computer or appliance to which the packet is transmitted. An address in your simulator is represented as eight digits such as 03214567 or 31415926, instead of using the standard notation of IP addresses such as 192.168.1.1. Administrative policy is described in filtering rules, each of which specifies some collection of source-destination address pairs and defines those packets with the specified address pairs either legal or illegal.
Input
The input consists of several data sets, each of which represents filtering rules and received packets in the following format:
n m
rule1
rule2
...
rulen
packet1
packet2
...
packetm
The first line consists of two non-negative integers n and m. If both n and m are zeros, this means the end of input. Otherwise, n lines, each representing a filtering rule, and m lines, each representing an arriving packet, follow in this order. You may assume that n and m are less than or equal to 1,024.
Each rulei is in one of the following formats:
permit source-pattern destination-pattern
deny source-pattern destination-pattern
A source-pattern or destination-pattern is a character string of length eight, where each character is either a digit ('0' to '9') or a wildcard character '?'. For instance, "1????5??" matches any address whose first and fifth digits are '1' and '5', respectively. In general, a wildcard character matches any single digit while a digit matches only itself.
With the keywords "permit" and "deny", filtering rules specify legal and illegal packets, respectively. That is, if the source and destination addresses of a packed are matched with source-pattern and destination-pattern, respectively, it is permitted to pass the firewall or the request is denied according to the keyword. Note that a permit rule and a deny rule can contradict since they may share the same source and destination address pair. For the purpose of conflict resolution, we define a priority rule: rulei has a higher priority over rulej if and only if i > j. For completeness, we define the default rule: any packet is illegal unless being explicitly specified legal by some given rule.
A packet is in the following format:
source-address destination-address message-body
Each of the first two is a character string of length eight that consists solely of digits. The last one is a character string consisting solely of alphanumeric characters ('a' to 'z', 'A' to 'Z', and '0' to '9'). Neither whitespaces nor special characters can occur in a message body. You may assume that it is not empty and that its length is at most 50.
You may also assume that there is exactly one space character between any two adjacent fields in an input line representing a rule or a packet.
Output
For each data set, print the number of legal packets in the first line, followed by all legal packets in the same order as they occur in the data set. Each packet must be written exactly in one line. If the data set includes two packets consisting of the same source and destination addresses and the same message body, you should consider them different packets and so they must be written in different lines. Any extra whitespaces or extra empty lines must not be written.
Example
Input
2 5
permit 192168?? ?12??34?
deny 19216899 012343?5
19216711 11233340 HiIamACracker
19216891 01234345 Hello
19216899 01234345 HiIamAlsoACracker
19216809 11200340 World
00000000 99999999 TheEndOfTheWorld
1 2
permit 12345678 23456789
19216891 01234345 Hello
12345678 23456789 Hello
0 0
Output
2
19216891 01234345 Hello
19216809 11200340 World
1
12345678 23456789 Hello | instruction | 0 | 47,888 | 3 | 95,776 |
"Correct Solution:
```
# AOJ 1111: Cyber Guardian
# Python3 2018.7.15 bal4u
import re
while True:
n, m = map(int, input().split())
if (n|m) == 0: break
rule, ans = [], []
for i in range(n):
g, s, d = input().split()
rule.append((g[0] == 'p', s.replace("?", "[0-9]"), d.replace("?", "[0-9]")))
for i in range(m):
s, d, m = input().split()
for G, S, D in rule[::-1]:
if re.match(S, s) and re.match(D, d):
if G: ans.append((s, d, m))
break
print(len(ans))
for a in ans: print(*a)
``` | output | 1 | 47,888 | 3 | 95,777 |
Provide a correct Python 3 solution for this coding contest problem.
In the good old days, the Internet was free from fears and terrorism. People did not have to worry about any cyber criminals or mad computer scientists. Today, however, you are facing atrocious crackers wherever you are, unless being disconnected. You have to protect yourselves against their attacks.
Counting upon your excellent talent for software construction and strong sense of justice, you are invited to work as a cyber guardian. Your ultimate mission is to create a perfect firewall system that can completely shut out any intruders invading networks and protect children from harmful information exposed on the Net. However, it is extremely difficult and none have ever achieved it before. As the first step, instead, you are now requested to write a software simulator under much simpler assumptions.
In general, a firewall system works at the entrance of a local network of an organization (e.g., a company or a university) and enforces its local administrative policy. It receives both inbound and outbound packets (note: data transmitted on the Net are divided into small segments called packets) and carefully inspects them one by one whether or not each of them is legal. The definition of the legality may vary from site to site or depend upon the local administrative policy of an organization. Your simulator should accept data representing not only received packets but also the local administrative policy.
For simplicity in this problem we assume that each network packet consists of three fields: its source address, destination address, and message body. The source address specifies the computer or appliance that transmits the packet and the destination address specifies the computer or appliance to which the packet is transmitted. An address in your simulator is represented as eight digits such as 03214567 or 31415926, instead of using the standard notation of IP addresses such as 192.168.1.1. Administrative policy is described in filtering rules, each of which specifies some collection of source-destination address pairs and defines those packets with the specified address pairs either legal or illegal.
Input
The input consists of several data sets, each of which represents filtering rules and received packets in the following format:
n m
rule1
rule2
...
rulen
packet1
packet2
...
packetm
The first line consists of two non-negative integers n and m. If both n and m are zeros, this means the end of input. Otherwise, n lines, each representing a filtering rule, and m lines, each representing an arriving packet, follow in this order. You may assume that n and m are less than or equal to 1,024.
Each rulei is in one of the following formats:
permit source-pattern destination-pattern
deny source-pattern destination-pattern
A source-pattern or destination-pattern is a character string of length eight, where each character is either a digit ('0' to '9') or a wildcard character '?'. For instance, "1????5??" matches any address whose first and fifth digits are '1' and '5', respectively. In general, a wildcard character matches any single digit while a digit matches only itself.
With the keywords "permit" and "deny", filtering rules specify legal and illegal packets, respectively. That is, if the source and destination addresses of a packed are matched with source-pattern and destination-pattern, respectively, it is permitted to pass the firewall or the request is denied according to the keyword. Note that a permit rule and a deny rule can contradict since they may share the same source and destination address pair. For the purpose of conflict resolution, we define a priority rule: rulei has a higher priority over rulej if and only if i > j. For completeness, we define the default rule: any packet is illegal unless being explicitly specified legal by some given rule.
A packet is in the following format:
source-address destination-address message-body
Each of the first two is a character string of length eight that consists solely of digits. The last one is a character string consisting solely of alphanumeric characters ('a' to 'z', 'A' to 'Z', and '0' to '9'). Neither whitespaces nor special characters can occur in a message body. You may assume that it is not empty and that its length is at most 50.
You may also assume that there is exactly one space character between any two adjacent fields in an input line representing a rule or a packet.
Output
For each data set, print the number of legal packets in the first line, followed by all legal packets in the same order as they occur in the data set. Each packet must be written exactly in one line. If the data set includes two packets consisting of the same source and destination addresses and the same message body, you should consider them different packets and so they must be written in different lines. Any extra whitespaces or extra empty lines must not be written.
Example
Input
2 5
permit 192168?? ?12??34?
deny 19216899 012343?5
19216711 11233340 HiIamACracker
19216891 01234345 Hello
19216899 01234345 HiIamAlsoACracker
19216809 11200340 World
00000000 99999999 TheEndOfTheWorld
1 2
permit 12345678 23456789
19216891 01234345 Hello
12345678 23456789 Hello
0 0
Output
2
19216891 01234345 Hello
19216809 11200340 World
1
12345678 23456789 Hello | instruction | 0 | 47,889 | 3 | 95,778 |
"Correct Solution:
```
# AOJ 1111: Cyber Guardian
# Python3 2018.7.15 bal4u
import re
while True:
n, m = map(int, input().split())
if (n|m) == 0: break
rule, ans = [], []
for i in range(n):
g, s, d = input().split()
rule.append((g[0] == 'p', \
re.compile(s.replace("?", "[0-9]")), \
re.compile(d.replace("?", "[0-9]"))))
for i in range(m):
s, d, m = input().split()
for G, S, D in rule[::-1]:
if re.match(S, s) and re.match(D, d):
if G: ans.append((s, d, m))
break
print(len(ans))
for a in ans: print(*a)
``` | output | 1 | 47,889 | 3 | 95,779 |
Provide a correct Python 3 solution for this coding contest problem.
In the good old days, the Internet was free from fears and terrorism. People did not have to worry about any cyber criminals or mad computer scientists. Today, however, you are facing atrocious crackers wherever you are, unless being disconnected. You have to protect yourselves against their attacks.
Counting upon your excellent talent for software construction and strong sense of justice, you are invited to work as a cyber guardian. Your ultimate mission is to create a perfect firewall system that can completely shut out any intruders invading networks and protect children from harmful information exposed on the Net. However, it is extremely difficult and none have ever achieved it before. As the first step, instead, you are now requested to write a software simulator under much simpler assumptions.
In general, a firewall system works at the entrance of a local network of an organization (e.g., a company or a university) and enforces its local administrative policy. It receives both inbound and outbound packets (note: data transmitted on the Net are divided into small segments called packets) and carefully inspects them one by one whether or not each of them is legal. The definition of the legality may vary from site to site or depend upon the local administrative policy of an organization. Your simulator should accept data representing not only received packets but also the local administrative policy.
For simplicity in this problem we assume that each network packet consists of three fields: its source address, destination address, and message body. The source address specifies the computer or appliance that transmits the packet and the destination address specifies the computer or appliance to which the packet is transmitted. An address in your simulator is represented as eight digits such as 03214567 or 31415926, instead of using the standard notation of IP addresses such as 192.168.1.1. Administrative policy is described in filtering rules, each of which specifies some collection of source-destination address pairs and defines those packets with the specified address pairs either legal or illegal.
Input
The input consists of several data sets, each of which represents filtering rules and received packets in the following format:
n m
rule1
rule2
...
rulen
packet1
packet2
...
packetm
The first line consists of two non-negative integers n and m. If both n and m are zeros, this means the end of input. Otherwise, n lines, each representing a filtering rule, and m lines, each representing an arriving packet, follow in this order. You may assume that n and m are less than or equal to 1,024.
Each rulei is in one of the following formats:
permit source-pattern destination-pattern
deny source-pattern destination-pattern
A source-pattern or destination-pattern is a character string of length eight, where each character is either a digit ('0' to '9') or a wildcard character '?'. For instance, "1????5??" matches any address whose first and fifth digits are '1' and '5', respectively. In general, a wildcard character matches any single digit while a digit matches only itself.
With the keywords "permit" and "deny", filtering rules specify legal and illegal packets, respectively. That is, if the source and destination addresses of a packed are matched with source-pattern and destination-pattern, respectively, it is permitted to pass the firewall or the request is denied according to the keyword. Note that a permit rule and a deny rule can contradict since they may share the same source and destination address pair. For the purpose of conflict resolution, we define a priority rule: rulei has a higher priority over rulej if and only if i > j. For completeness, we define the default rule: any packet is illegal unless being explicitly specified legal by some given rule.
A packet is in the following format:
source-address destination-address message-body
Each of the first two is a character string of length eight that consists solely of digits. The last one is a character string consisting solely of alphanumeric characters ('a' to 'z', 'A' to 'Z', and '0' to '9'). Neither whitespaces nor special characters can occur in a message body. You may assume that it is not empty and that its length is at most 50.
You may also assume that there is exactly one space character between any two adjacent fields in an input line representing a rule or a packet.
Output
For each data set, print the number of legal packets in the first line, followed by all legal packets in the same order as they occur in the data set. Each packet must be written exactly in one line. If the data set includes two packets consisting of the same source and destination addresses and the same message body, you should consider them different packets and so they must be written in different lines. Any extra whitespaces or extra empty lines must not be written.
Example
Input
2 5
permit 192168?? ?12??34?
deny 19216899 012343?5
19216711 11233340 HiIamACracker
19216891 01234345 Hello
19216899 01234345 HiIamAlsoACracker
19216809 11200340 World
00000000 99999999 TheEndOfTheWorld
1 2
permit 12345678 23456789
19216891 01234345 Hello
12345678 23456789 Hello
0 0
Output
2
19216891 01234345 Hello
19216809 11200340 World
1
12345678 23456789 Hello | instruction | 0 | 47,890 | 3 | 95,780 |
"Correct Solution:
```
# AOJ 1111: Cyber Guardian
# Python3 2018.7.15 bal4u
import re
while True:
n, m = map(int, input().split())
if (n|m) == 0: break
rule, ans = [], []
for i in range(n):
g, s, d = input().split()
rule.append((g[0] == 'p', re.compile((s+d).replace("?", "\d"))))
for i in range(m):
s, d, m = input().split()
sd = s+d
for G, SD in rule[::-1]:
if re.match(SD, sd):
if G: ans.append((s, d, m))
break
print(len(ans))
for a in ans: print(*a)
``` | output | 1 | 47,890 | 3 | 95,781 |
Provide a correct Python 3 solution for this coding contest problem.
In the year 2xxx, an expedition team landing on a planet found strange objects made by an ancient species living on that planet. They are transparent boxes containing opaque solid spheres (Figure 1). There are also many lithographs which seem to contain positions and radiuses of spheres.
<image>
Figure 1: A strange object
Initially their objective was unknown, but Professor Zambendorf found the cross section formed by a horizontal plane plays an important role. For example, the cross section of an object changes as in Figure 2 by sliding the plane from bottom to top.
<image>
Figure 2: Cross sections at different positions
He eventually found that some information is expressed by the transition of the number of connected figures in the cross section, where each connected figure is a union of discs intersecting or touching each other, and each disc is a cross section of the corresponding solid sphere. For instance, in Figure 2, whose geometry is described in the first sample dataset later, the number of connected figures changes as 0, 1, 2, 1, 2, 3, 2, 1, and 0, at z = 0.0000, 162.0000, 167.0000, 173.0004, 185.0000, 191.9996, 198.0000, 203.0000, and 205.0000, respectively. By assigning 1 for increment and 0 for decrement, the transitions of this sequence can be expressed by an 8-bit binary number 11011000.
For helping further analysis, write a program to determine the transitions when sliding the horizontal plane from bottom (z = 0) to top (z = 36000).
Input
The input consists of a series of datasets. Each dataset begins with a line containing a positive integer, which indicates the number of spheres N in the dataset. It is followed by N lines describing the centers and radiuses of the spheres. Each of the N lines has four positive integers Xi, Yi, Zi, and Ri (i = 1, . . . , N) describing the center and the radius of the i-th sphere, respectively.
You may assume 1 ≤ N ≤ 100, 1 ≤ Ri ≤ 2000, 0 < Xi - Ri < Xi + Ri < 4000, 0 < Yi - Ri < Yi + Ri < 16000, and 0 < Zi - Ri < Zi + Ri < 36000. Each solid sphere is defined as the set of all points (x, y, z) satisfying (x - Xi)2 + (y - Yi)2 + (z - Zi)2 ≤ Ri2.
A sphere may contain other spheres. No two spheres are mutually tangent. Every Zi ± Ri and minimum/maximum z coordinates of a circle formed by the intersection of any two spheres differ from each other by at least 0.01.
The end of the input is indicated by a line with one zero.
Output
For each dataset, your program should output two lines. The first line should contain an integer M indicating the number of transitions. The second line should contain an M-bit binary number that expresses the transitions of the number of connected figures as specified above.
Example
Input
3
95 20 180 18
125 20 185 18
40 27 195 10
1
5 5 5 4
2
5 5 5 4
5 5 5 3
2
5 5 5 4
5 7 5 3
16
2338 3465 29034 710
1571 14389 25019 842
1706 8015 11324 1155
1899 4359 33815 888
2160 10364 20511 1264
2048 8835 23706 1906
2598 13041 23679 618
1613 11112 8003 1125
1777 4754 25986 929
2707 9945 11458 617
1153 10358 4305 755
2462 8450 21838 934
1822 11539 10025 1639
1473 11939 12924 638
1388 8519 18653 834
2239 7384 32729 862
0
Output
8
11011000
2
10
2
10
2
10
28
1011100100110101101000101100 | instruction | 0 | 47,891 | 3 | 95,782 |
"Correct Solution:
```
from collections import defaultdict, deque
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N = int(readline())
if N == 0:
return False
C0 = [list(map(int, readline().split())) for i in range(N)]
U = [1]*N
D = defaultdict(list)
for i in range(N):
xi, yi, zi, ri = C0[i]
for j in range(i):
xj, yj, zj, rj = C0[j]
dd = (xi - xj)**2 + (yi - yj)**2 + (zi - zj)**2
if dd <= (ri - rj)**2:
if ri < rj:
U[i] = 0
else:
U[j] = 0
C = [e for i, e in enumerate(C0) if U[i]]
N = len(C)
EPS = 1e-9
for i in range(N):
xi, yi, zi, ri = C[i]
D[zi+ri].append((0, i, 0))
D[zi-ri].append((0, i, 0))
for j in range(i):
xj, yj, zj, rj = C[j]
dd = (xi - xj)**2 + (yi - yj)**2 + (zi - zj)**2
if dd > (ri + rj)**2:
continue
def check(z):
si = (ri**2 - (z - zi)**2)**.5
sj = (rj**2 - (z - zj)**2)**.5
return (xi - xj)**2 + (yi - yj)**2 <= (si + sj)**2
z0 = zi + (zj - zi) * (ri**2 + dd - rj**2) / (2 * dd)
zm = min(zi+ri, zj+rj)
if check(zm):
z1 = zm
else:
left = 0; right = zm - z0
while right - left > EPS:
mid = (left + right) / 2
# xi, yi, sqrt(ri**2 - (mid - zi)**2)
if check(z0 + mid):
left = mid
else:
right = mid
z1 = z0 + left
zm = max(zi-ri, zj-rj)
if check(zm):
z2 = zm
else:
left = 0; right = z0 - max(zi-ri, zj-rj)
while right - left > EPS:
mid = (left + right) / 2
# xi, yi, sqrt(ri**2 - (mid - zi)**2)
if check(z0 - mid):
left = mid
else:
right = mid
z2 = z0 - left
D[z1].append((1, i, j))
D[z2].append((1, i, j))
res = [0]
E = [[0]*N for i in range(N)]
U = [0]*N
*zs, = D.items()
zs.sort()
for z, es in zs:
for t, a, b in es:
if t:
E[a][b] = E[b][a] = E[a][b] ^ 1
else:
U[a] ^= 1
c = 0
que = deque()
used = [0]*N
for i in range(N):
if used[i] or not U[i]:
continue
c += 1
v = 0
used[i] = 1
que.append(i)
while que:
v = que.popleft()
for w in range(N):
if not E[v][w] or used[w]:
continue
used[w] = 1
que.append(w)
if res[-1] != c:
res.append(c)
ans = []
for i in range(len(res)-1):
if res[i] < res[i+1]:
ans.append("1")
else:
ans.append("0")
write("%d\n" % len(ans))
write("".join(ans))
write("\n")
return True
while solve():
...
``` | output | 1 | 47,891 | 3 | 95,783 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are wandering in the explorer space of the 2050 Conference.
The explorer space can be viewed as an undirected weighted grid graph with size n× m. The set of vertices is \{(i, j)|1≤ i≤ n, 1≤ j≤ m\}. Two vertices (i_1,j_1) and (i_2, j_2) are connected by an edge if and only if |i_1-i_2|+|j_1-j_2|=1.
At each step, you can walk to any vertex connected by an edge with your current vertex. On each edge, there are some number of exhibits. Since you already know all the exhibits, whenever you go through an edge containing x exhibits, your boredness increases by x.
For each starting vertex (i, j), please answer the following question: What is the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps?
You can use any edge for multiple times but the boredness on those edges are also counted for multiple times. At each step, you cannot stay on your current vertex. You also cannot change direction while going through an edge. Before going back to your starting vertex (i, j) after k steps, you can visit (i, j) (or not) freely.
Input
The first line contains three integers n, m and k (2≤ n, m≤ 500, 1≤ k≤ 20).
The j-th number (1≤ j ≤ m - 1) in the i-th line of the following n lines is the number of exibits on the edge between vertex (i, j) and vertex (i, j+1).
The j-th number (1≤ j≤ m) in the i-th line of the following n-1 lines is the number of exibits on the edge between vertex (i, j) and vertex (i+1, j).
The number of exhibits on each edge is an integer between 1 and 10^6.
Output
Output n lines with m numbers each. The j-th number in the i-th line, answer_{ij}, should be the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps.
If you cannot go back to vertex (i, j) after exactly k steps, answer_{ij} should be -1.
Examples
Input
3 3 10
1 1
1 1
1 1
1 1 1
1 1 1
Output
10 10 10
10 10 10
10 10 10
Input
2 2 4
1
3
4 2
Output
4 4
10 6
Input
2 2 3
1
2
3 4
Output
-1 -1
-1 -1
Note
In the first example, the answer is always 10 no matter how you walk.
In the second example, answer_{21} = 10, the path is (2,1) → (1,1) → (1,2) → (2,2) → (2,1), the boredness is 4 + 1 + 2 + 3 = 10. | instruction | 0 | 48,151 | 3 | 96,302 |
Tags: dp, graphs, shortest paths
Correct Solution:
```
import sys
def get_ints(): return list(map(int, sys.stdin.readline().strip().split()))
def print_result(ans):
for i in range(len(ans)):
print((" ").join(map(str, ans[i])))
def solve(N, M, K, hor, ver):
if K & 1:
print_result([[-1 for i in range(N)] for j in range(M)])
return
grid = [[0 for i in range(N)] for j in range((M))]
def cal(i, j):
can = set()
if j > 0:
can.add(
2 * hor[i][j - 1] + grid[i][j - 1]
)
if j + 1 < N:
can.add(
2 * hor[i][j] + grid[i][j + 1]
)
if i > 0:
can.add(
2 * ver[i - 1][j] + grid[i - 1][j]
)
if i + 1 < M:
can.add(
2 * ver[i][j] + grid[i + 1][j]
)
return min(can)
for _ in range(K // 2):
next_grid = [[0 for i in range(N)] for j in range(M)]
for i in range(M):
for j in range(N):
next_grid[i][j] = cal(i, j)
grid = next_grid
print_result(grid)
M, N, K = map(int, input().split())
hor = []
ver = []
for i in range(M):
nums = get_ints()
hor.append(nums)
for i in range(M - 1):
nums = get_ints()
ver.append(nums)
solve(N, M, K, hor, ver)
``` | output | 1 | 48,151 | 3 | 96,303 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are wandering in the explorer space of the 2050 Conference.
The explorer space can be viewed as an undirected weighted grid graph with size n× m. The set of vertices is \{(i, j)|1≤ i≤ n, 1≤ j≤ m\}. Two vertices (i_1,j_1) and (i_2, j_2) are connected by an edge if and only if |i_1-i_2|+|j_1-j_2|=1.
At each step, you can walk to any vertex connected by an edge with your current vertex. On each edge, there are some number of exhibits. Since you already know all the exhibits, whenever you go through an edge containing x exhibits, your boredness increases by x.
For each starting vertex (i, j), please answer the following question: What is the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps?
You can use any edge for multiple times but the boredness on those edges are also counted for multiple times. At each step, you cannot stay on your current vertex. You also cannot change direction while going through an edge. Before going back to your starting vertex (i, j) after k steps, you can visit (i, j) (or not) freely.
Input
The first line contains three integers n, m and k (2≤ n, m≤ 500, 1≤ k≤ 20).
The j-th number (1≤ j ≤ m - 1) in the i-th line of the following n lines is the number of exibits on the edge between vertex (i, j) and vertex (i, j+1).
The j-th number (1≤ j≤ m) in the i-th line of the following n-1 lines is the number of exibits on the edge between vertex (i, j) and vertex (i+1, j).
The number of exhibits on each edge is an integer between 1 and 10^6.
Output
Output n lines with m numbers each. The j-th number in the i-th line, answer_{ij}, should be the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps.
If you cannot go back to vertex (i, j) after exactly k steps, answer_{ij} should be -1.
Examples
Input
3 3 10
1 1
1 1
1 1
1 1 1
1 1 1
Output
10 10 10
10 10 10
10 10 10
Input
2 2 4
1
3
4 2
Output
4 4
10 6
Input
2 2 3
1
2
3 4
Output
-1 -1
-1 -1
Note
In the first example, the answer is always 10 no matter how you walk.
In the second example, answer_{21} = 10, the path is (2,1) → (1,1) → (1,2) → (2,2) → (2,1), the boredness is 4 + 1 + 2 + 3 = 10. | instruction | 0 | 48,152 | 3 | 96,304 |
Tags: dp, graphs, shortest paths
Correct Solution:
```
from sys import stdin,stdout
from math import gcd,sqrt,factorial,pi,inf
from collections import deque,defaultdict
from bisect import bisect,bisect_left
from time import time
from itertools import permutations as per
input=stdin.readline
R=lambda:map(int,input().split())
I=lambda:int(input())
S=lambda:input().rstrip('\r\n')
L=lambda:list(R())
P=lambda x:stdout.write(str(x)+'\n')
lcm=lambda x,y:(x*y)//gcd(x,y)
nCr=lambda x,y:(f[x]*inv((f[y]*f[x-y])%N))%N
inv=lambda x:pow(x,N-2,N)
sm=lambda x:(x**2+x)//2
N=10**9+7
n,m,k=R()
A=[L() for i in range(n)]
B=[L() for i in range(n-1)]
if k&1:
for i in range(n):
print('-1 '*m)
exit()
X=[[0]*m for i in range(n)]
for _ in range(k//2):
Y=[[inf]*m for i in range(n)]
for i in range(n):
for j in range(m):
if i:
Y[i][j]=X[i-1][j]+2*B[i-1][j]
if i<n-1:
Y[i][j]=min(Y[i][j],X[i+1][j]+2*B[i][j])
if j:
Y[i][j]=min(Y[i][j],X[i][j-1]+2*A[i][j-1])
if j<m-1:
Y[i][j]=min(Y[i][j],X[i][j+1]+2*A[i][j])
X=Y
for i in X:
print(*i)
``` | output | 1 | 48,152 | 3 | 96,305 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are wandering in the explorer space of the 2050 Conference.
The explorer space can be viewed as an undirected weighted grid graph with size n× m. The set of vertices is \{(i, j)|1≤ i≤ n, 1≤ j≤ m\}. Two vertices (i_1,j_1) and (i_2, j_2) are connected by an edge if and only if |i_1-i_2|+|j_1-j_2|=1.
At each step, you can walk to any vertex connected by an edge with your current vertex. On each edge, there are some number of exhibits. Since you already know all the exhibits, whenever you go through an edge containing x exhibits, your boredness increases by x.
For each starting vertex (i, j), please answer the following question: What is the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps?
You can use any edge for multiple times but the boredness on those edges are also counted for multiple times. At each step, you cannot stay on your current vertex. You also cannot change direction while going through an edge. Before going back to your starting vertex (i, j) after k steps, you can visit (i, j) (or not) freely.
Input
The first line contains three integers n, m and k (2≤ n, m≤ 500, 1≤ k≤ 20).
The j-th number (1≤ j ≤ m - 1) in the i-th line of the following n lines is the number of exibits on the edge between vertex (i, j) and vertex (i, j+1).
The j-th number (1≤ j≤ m) in the i-th line of the following n-1 lines is the number of exibits on the edge between vertex (i, j) and vertex (i+1, j).
The number of exhibits on each edge is an integer between 1 and 10^6.
Output
Output n lines with m numbers each. The j-th number in the i-th line, answer_{ij}, should be the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps.
If you cannot go back to vertex (i, j) after exactly k steps, answer_{ij} should be -1.
Examples
Input
3 3 10
1 1
1 1
1 1
1 1 1
1 1 1
Output
10 10 10
10 10 10
10 10 10
Input
2 2 4
1
3
4 2
Output
4 4
10 6
Input
2 2 3
1
2
3 4
Output
-1 -1
-1 -1
Note
In the first example, the answer is always 10 no matter how you walk.
In the second example, answer_{21} = 10, the path is (2,1) → (1,1) → (1,2) → (2,2) → (2,1), the boredness is 4 + 1 + 2 + 3 = 10. | instruction | 0 | 48,153 | 3 | 96,306 |
Tags: dp, graphs, shortest paths
Correct Solution:
```
from copy import deepcopy
def sol(n,m,k,aa,bb):
if k&1:
return [[-1] * m] * n
ans = [[float('inf')]*(m+2) for _ in range(n+2)]
k >>= 1
for i in range(1,n+1):
for j in range(1,m+1):
ans[i][j] = min(aa[i][j], aa[i][j-1], bb[i][j], bb[i-1][j])
for _ in range(k-1):
oans = deepcopy(ans)
for i in range(1,n+1):
for j in range(1,m+1):
ans[i][j] = min(
aa[i][j]+oans[i][j+1],
aa[i][j-1]+oans[i][j-1],
bb[i][j]+oans[i+1][j],
bb[i-1][j]+oans[i-1][j])
ans = ans[1:-1]
ans = [x[1:-1] for x in ans]
ans = [[2*x for x in a] for a in ans]
return ans
n,m,k = map(int, input().split())
aa = [list(map(int, input().split())) for _ in range(n)]
inf = float('inf')
bb = [list(map(int, input().split())) for _ in range(n-1)]
aa = [[inf, *x, inf] for x in aa]
bb = [[inf, *x, inf] for x in bb]
pad = [inf] * (m+1)
aa = [pad, *aa, pad]
pad = [inf] * (m+2)
bb = [pad, *bb, pad]
ans = sol(n,m,k,aa,bb)
print('\n'.join(' '.join(map(str, a)) for a in ans))
``` | output | 1 | 48,153 | 3 | 96,307 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are wandering in the explorer space of the 2050 Conference.
The explorer space can be viewed as an undirected weighted grid graph with size n× m. The set of vertices is \{(i, j)|1≤ i≤ n, 1≤ j≤ m\}. Two vertices (i_1,j_1) and (i_2, j_2) are connected by an edge if and only if |i_1-i_2|+|j_1-j_2|=1.
At each step, you can walk to any vertex connected by an edge with your current vertex. On each edge, there are some number of exhibits. Since you already know all the exhibits, whenever you go through an edge containing x exhibits, your boredness increases by x.
For each starting vertex (i, j), please answer the following question: What is the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps?
You can use any edge for multiple times but the boredness on those edges are also counted for multiple times. At each step, you cannot stay on your current vertex. You also cannot change direction while going through an edge. Before going back to your starting vertex (i, j) after k steps, you can visit (i, j) (or not) freely.
Input
The first line contains three integers n, m and k (2≤ n, m≤ 500, 1≤ k≤ 20).
The j-th number (1≤ j ≤ m - 1) in the i-th line of the following n lines is the number of exibits on the edge between vertex (i, j) and vertex (i, j+1).
The j-th number (1≤ j≤ m) in the i-th line of the following n-1 lines is the number of exibits on the edge between vertex (i, j) and vertex (i+1, j).
The number of exhibits on each edge is an integer between 1 and 10^6.
Output
Output n lines with m numbers each. The j-th number in the i-th line, answer_{ij}, should be the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps.
If you cannot go back to vertex (i, j) after exactly k steps, answer_{ij} should be -1.
Examples
Input
3 3 10
1 1
1 1
1 1
1 1 1
1 1 1
Output
10 10 10
10 10 10
10 10 10
Input
2 2 4
1
3
4 2
Output
4 4
10 6
Input
2 2 3
1
2
3 4
Output
-1 -1
-1 -1
Note
In the first example, the answer is always 10 no matter how you walk.
In the second example, answer_{21} = 10, the path is (2,1) → (1,1) → (1,2) → (2,2) → (2,1), the boredness is 4 + 1 + 2 + 3 = 10. | instruction | 0 | 48,154 | 3 | 96,308 |
Tags: dp, graphs, shortest paths
Correct Solution:
```
import sys, os
if os.environ['USERNAME']=='kissz':
inp=open('in.txt','r').readline
def debug(*args):
print(*args,file=sys.stderr)
else:
inp=sys.stdin.readline
def debug(*args):
pass
# SCRIPT STARTS HERE
n,m,k=map(int,inp().split())
A=[[*map(int,inp().split())] for _ in range(n)]
B=[[*map(int,inp().split())] for _ in range(n-1)]
if k%2==0:
O=[[[1e12]*m for _ in range(n)] for _ in range(k//2)]
for i in range(n):
for j in range(m):
if i>0:
O[0][i][j]=min(O[0][i][j],B[i-1][j])
if i<n-1:
O[0][i][j]=min(O[0][i][j],B[i][j])
if j>0:
O[0][i][j]=min(O[0][i][j],A[i][j-1])
if j<m-1:
O[0][i][j]=min(O[0][i][j],A[i][j])
#for i in range(n):
# debug(*O[0][i])
for l in range(1,k//2):
for i in range(n):
for j in range(m):
if i>0:
O[l][i][j]=min(O[l][i][j],B[i-1][j]+O[l-1][i-1][j])
if i<n-1:
O[l][i][j]=min(O[l][i][j],B[i][j]+O[l-1][i+1][j])
if j>0:
O[l][i][j]=min(O[l][i][j],A[i][j-1]+O[l-1][i][j-1])
if j<m-1:
O[l][i][j]=min(O[l][i][j],A[i][j]+O[l-1][i][j+1])
#for i in range(n):
# debug(*O[l][i])
for i in range(n):
print(*[O[-1][i][j]*2 for j in range(m)])
else:
for i in range(n):
print(*[-1]*m)
``` | output | 1 | 48,154 | 3 | 96,309 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are wandering in the explorer space of the 2050 Conference.
The explorer space can be viewed as an undirected weighted grid graph with size n× m. The set of vertices is \{(i, j)|1≤ i≤ n, 1≤ j≤ m\}. Two vertices (i_1,j_1) and (i_2, j_2) are connected by an edge if and only if |i_1-i_2|+|j_1-j_2|=1.
At each step, you can walk to any vertex connected by an edge with your current vertex. On each edge, there are some number of exhibits. Since you already know all the exhibits, whenever you go through an edge containing x exhibits, your boredness increases by x.
For each starting vertex (i, j), please answer the following question: What is the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps?
You can use any edge for multiple times but the boredness on those edges are also counted for multiple times. At each step, you cannot stay on your current vertex. You also cannot change direction while going through an edge. Before going back to your starting vertex (i, j) after k steps, you can visit (i, j) (or not) freely.
Input
The first line contains three integers n, m and k (2≤ n, m≤ 500, 1≤ k≤ 20).
The j-th number (1≤ j ≤ m - 1) in the i-th line of the following n lines is the number of exibits on the edge between vertex (i, j) and vertex (i, j+1).
The j-th number (1≤ j≤ m) in the i-th line of the following n-1 lines is the number of exibits on the edge between vertex (i, j) and vertex (i+1, j).
The number of exhibits on each edge is an integer between 1 and 10^6.
Output
Output n lines with m numbers each. The j-th number in the i-th line, answer_{ij}, should be the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps.
If you cannot go back to vertex (i, j) after exactly k steps, answer_{ij} should be -1.
Examples
Input
3 3 10
1 1
1 1
1 1
1 1 1
1 1 1
Output
10 10 10
10 10 10
10 10 10
Input
2 2 4
1
3
4 2
Output
4 4
10 6
Input
2 2 3
1
2
3 4
Output
-1 -1
-1 -1
Note
In the first example, the answer is always 10 no matter how you walk.
In the second example, answer_{21} = 10, the path is (2,1) → (1,1) → (1,2) → (2,2) → (2,1), the boredness is 4 + 1 + 2 + 3 = 10. | instruction | 0 | 48,155 | 3 | 96,310 |
Tags: dp, graphs, shortest paths
Correct Solution:
```
def aburrimin(x, y, n, m, costder, costaba, dp):
dists = []
vals = []
if x != 0: # izq
dis = costder[y][x-1]
dists.append(dis)
vals.append(dis+dp[y][x-1])
if y != 0: # arri
dis = costaba[y-1][x]
dists.append(dis)
vals.append(dis+dp[y-1][x])
if y < n-1: # aba
dis = costaba[y][x]
dists.append(dis)
vals.append(dis+dp[y+1][x])
if x < m-1: # der
dis = costder[y][x]
dists.append(dis)
vals.append(dis+dp[y][x+1])
mindis = min(dists)
return min(mindis+dp[y][x],min(vals))
def solvecaso():
n,m,k = map(int,input().split())
costder = [[int(x) for x in input().split()] for _ in range(n)]
costaba = [[int(x) for x in input().split()] for _ in range(n-1)]
if k%2:
for i in range(n):
for j in range(m):
print(-1, end=' ')
print()
return -1
k //= 2
for ren in range(len(costder)):
for col in range(len(costder[ren])):
costder[ren][col] *= 2
for ren in range(len(costaba)):
for col in range(len(costaba[ren])):
costaba[ren][col] *= 2
dp = [[0 for _ in range(m)] for _ in range(n)]
dptemp = [[0 for _ in range(m)] for _ in range(n)]
# print(dp) # debug
for i in range(k):
for y in range(n):
for x in range(m):
dptemp[y][x] = aburrimin(x, y, n, m, costder, costaba, dp)
dp, dptemp = dptemp, dp
# print(dp) # debug
for ren in dp:
for num in ren:
print(num, end=' ')
print()
return 0
if __name__ == "__main__":
# casos = int(input()) #dbug
# for caso in range(1,casos+1):#dbug
# result = solvecaso()#dbug
solvecaso() #dbug
``` | output | 1 | 48,155 | 3 | 96,311 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are wandering in the explorer space of the 2050 Conference.
The explorer space can be viewed as an undirected weighted grid graph with size n× m. The set of vertices is \{(i, j)|1≤ i≤ n, 1≤ j≤ m\}. Two vertices (i_1,j_1) and (i_2, j_2) are connected by an edge if and only if |i_1-i_2|+|j_1-j_2|=1.
At each step, you can walk to any vertex connected by an edge with your current vertex. On each edge, there are some number of exhibits. Since you already know all the exhibits, whenever you go through an edge containing x exhibits, your boredness increases by x.
For each starting vertex (i, j), please answer the following question: What is the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps?
You can use any edge for multiple times but the boredness on those edges are also counted for multiple times. At each step, you cannot stay on your current vertex. You also cannot change direction while going through an edge. Before going back to your starting vertex (i, j) after k steps, you can visit (i, j) (or not) freely.
Input
The first line contains three integers n, m and k (2≤ n, m≤ 500, 1≤ k≤ 20).
The j-th number (1≤ j ≤ m - 1) in the i-th line of the following n lines is the number of exibits on the edge between vertex (i, j) and vertex (i, j+1).
The j-th number (1≤ j≤ m) in the i-th line of the following n-1 lines is the number of exibits on the edge between vertex (i, j) and vertex (i+1, j).
The number of exhibits on each edge is an integer between 1 and 10^6.
Output
Output n lines with m numbers each. The j-th number in the i-th line, answer_{ij}, should be the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps.
If you cannot go back to vertex (i, j) after exactly k steps, answer_{ij} should be -1.
Examples
Input
3 3 10
1 1
1 1
1 1
1 1 1
1 1 1
Output
10 10 10
10 10 10
10 10 10
Input
2 2 4
1
3
4 2
Output
4 4
10 6
Input
2 2 3
1
2
3 4
Output
-1 -1
-1 -1
Note
In the first example, the answer is always 10 no matter how you walk.
In the second example, answer_{21} = 10, the path is (2,1) → (1,1) → (1,2) → (2,2) → (2,1), the boredness is 4 + 1 + 2 + 3 = 10. | instruction | 0 | 48,156 | 3 | 96,312 |
Tags: dp, graphs, shortest paths
Correct Solution:
```
from sys import stdin
readline = stdin.readline
def readInt():
return int(readline())
def readInts():
return list(map(int,readline().split()))
U, D, L, R = 0, 1, 2, 3
DIR = [(-1,0), (1,0), (0,-1), (0,1)]
n, m, k = readInts()
moves = [[[-1 for _ in range(4)] for _ in range(m)] for _ in range(n)]
right = []
down = []
for i in range(n):
row = readInts()
right.append(row)
# for j in range(m-1):
# e = row[j]
# moves[i][j][R] = e
# moves[i][j+1][L] = e
for i in range(n-1):
row = readInts()
down.append(row)
# for j in range(m):
# e = row[j]
# moves[i][j][D] = e
# moves[i+1][j][U] = e
if k % 2 == 1:
for _ in range(n):
for _ in range(m):
print(-1, end=" ")
print()
exit()
k //= 2
dp = [[[0 for _ in range(k+1)] for _ in range(m)] for _ in range(n)]
for l in range(k):
for i in range(n):
for j in range(m):
dp[i][j][l+1] = float("inf")
if i > 0:
dp[i][j][l+1] = min(dp[i][j][l+1], dp[i-1][j][l] + down[i-1][j])
if j > 0:
dp[i][j][l+1] = min(dp[i][j][l+1], dp[i][j-1][l] + right[i][j-1])
if i < n - 1:
dp[i][j][l+1] = min(dp[i][j][l+1], dp[i+1][j][l] + down[i][j])
if j < m - 1:
dp[i][j][l+1] = min(dp[i][j][l+1], dp[i][j+1][l] + right[i][j])
# for d, (di, dj) in enumerate(DIR):
# if moves[i][j][d] != -1:
# dp[i][j][l+1] = min(dp[i][j][l+1], dp[i+di][j+dj][l] + moves[i][j][d])
for i in range(n):
for j in range(m):
print(2*dp[i][j][k], end=" ")
print()
``` | output | 1 | 48,156 | 3 | 96,313 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are wandering in the explorer space of the 2050 Conference.
The explorer space can be viewed as an undirected weighted grid graph with size n× m. The set of vertices is \{(i, j)|1≤ i≤ n, 1≤ j≤ m\}. Two vertices (i_1,j_1) and (i_2, j_2) are connected by an edge if and only if |i_1-i_2|+|j_1-j_2|=1.
At each step, you can walk to any vertex connected by an edge with your current vertex. On each edge, there are some number of exhibits. Since you already know all the exhibits, whenever you go through an edge containing x exhibits, your boredness increases by x.
For each starting vertex (i, j), please answer the following question: What is the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps?
You can use any edge for multiple times but the boredness on those edges are also counted for multiple times. At each step, you cannot stay on your current vertex. You also cannot change direction while going through an edge. Before going back to your starting vertex (i, j) after k steps, you can visit (i, j) (or not) freely.
Input
The first line contains three integers n, m and k (2≤ n, m≤ 500, 1≤ k≤ 20).
The j-th number (1≤ j ≤ m - 1) in the i-th line of the following n lines is the number of exibits on the edge between vertex (i, j) and vertex (i, j+1).
The j-th number (1≤ j≤ m) in the i-th line of the following n-1 lines is the number of exibits on the edge between vertex (i, j) and vertex (i+1, j).
The number of exhibits on each edge is an integer between 1 and 10^6.
Output
Output n lines with m numbers each. The j-th number in the i-th line, answer_{ij}, should be the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps.
If you cannot go back to vertex (i, j) after exactly k steps, answer_{ij} should be -1.
Examples
Input
3 3 10
1 1
1 1
1 1
1 1 1
1 1 1
Output
10 10 10
10 10 10
10 10 10
Input
2 2 4
1
3
4 2
Output
4 4
10 6
Input
2 2 3
1
2
3 4
Output
-1 -1
-1 -1
Note
In the first example, the answer is always 10 no matter how you walk.
In the second example, answer_{21} = 10, the path is (2,1) → (1,1) → (1,2) → (2,2) → (2,1), the boredness is 4 + 1 + 2 + 3 = 10. | instruction | 0 | 48,157 | 3 | 96,314 |
Tags: dp, graphs, shortest paths
Correct Solution:
```
import sys
n,m,k = map(int,input().split())
if k%2:
ans = [[-1]*m for _ in range(n)]
for row in ans:
print(*row)
exit()
A = []
B = []
inf = float('inf')
for _ in range(n):
A.append(list(map(int,input().split())))
for _ in range(n-1):
B.append(list(map(int,input().split())))
# dp = [[[inf for _ in range(k//2+1)] for _ in range(m)] for _ in range(n)]
# new
dp = [[inf]*m for _ in range(n)]
ans = [[None]*m for _ in range(n)]
for l in range(k//2+1):
new_dp = [[inf]*m for _ in range(n)]
for i in range(n):
for j in range(m):
if l == 0:
new_dp[i][j] = 0
continue
up = B[i-1][j]*2 + dp[i-1][j] if i-1>=0 else inf
right = A[i][j]*2 + dp[i][j+1] if j+1<m else inf
left = A[i][j-1]*2 + dp[i][j-1] if j-1>=0 else inf
down = B[i][j]*2 + dp[i+1][j] if i+1<n else inf
new_dp[i][j] = min(up,right,left,down)
if l == k//2:
ans[i][j] = new_dp[i][j]
dp = new_dp
for row in ans:
print(*row)
``` | output | 1 | 48,157 | 3 | 96,315 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are wandering in the explorer space of the 2050 Conference.
The explorer space can be viewed as an undirected weighted grid graph with size n× m. The set of vertices is \{(i, j)|1≤ i≤ n, 1≤ j≤ m\}. Two vertices (i_1,j_1) and (i_2, j_2) are connected by an edge if and only if |i_1-i_2|+|j_1-j_2|=1.
At each step, you can walk to any vertex connected by an edge with your current vertex. On each edge, there are some number of exhibits. Since you already know all the exhibits, whenever you go through an edge containing x exhibits, your boredness increases by x.
For each starting vertex (i, j), please answer the following question: What is the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps?
You can use any edge for multiple times but the boredness on those edges are also counted for multiple times. At each step, you cannot stay on your current vertex. You also cannot change direction while going through an edge. Before going back to your starting vertex (i, j) after k steps, you can visit (i, j) (or not) freely.
Input
The first line contains three integers n, m and k (2≤ n, m≤ 500, 1≤ k≤ 20).
The j-th number (1≤ j ≤ m - 1) in the i-th line of the following n lines is the number of exibits on the edge between vertex (i, j) and vertex (i, j+1).
The j-th number (1≤ j≤ m) in the i-th line of the following n-1 lines is the number of exibits on the edge between vertex (i, j) and vertex (i+1, j).
The number of exhibits on each edge is an integer between 1 and 10^6.
Output
Output n lines with m numbers each. The j-th number in the i-th line, answer_{ij}, should be the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps.
If you cannot go back to vertex (i, j) after exactly k steps, answer_{ij} should be -1.
Examples
Input
3 3 10
1 1
1 1
1 1
1 1 1
1 1 1
Output
10 10 10
10 10 10
10 10 10
Input
2 2 4
1
3
4 2
Output
4 4
10 6
Input
2 2 3
1
2
3 4
Output
-1 -1
-1 -1
Note
In the first example, the answer is always 10 no matter how you walk.
In the second example, answer_{21} = 10, the path is (2,1) → (1,1) → (1,2) → (2,2) → (2,1), the boredness is 4 + 1 + 2 + 3 = 10. | instruction | 0 | 48,158 | 3 | 96,316 |
Tags: dp, graphs, shortest paths
Correct Solution:
```
import sys
input = sys.stdin.readline
n,m,k=map(int,input().split())
YOKO=[list(map(int,input().split())) for i in range(n)]
TATE=[list(map(int,input().split())) for i in range(n-1)]
if k%2==1:
for i in range(n):
print(*[-1]*m)
exit()
DP=[[0]*m for i in range(n)]
for i in range(n):
for j in range(m):
MIN=1<<30
if j-1>=0:
MIN=min(MIN,YOKO[i][j-1]*2)
if j<m-1:
MIN=min(MIN,YOKO[i][j]*2)
if i-1>=0:
MIN=min(MIN,TATE[i-1][j]*2)
if i<n-1:
MIN=min(MIN,TATE[i][j]*2)
DP[i][j]=MIN
DP0=DP[:]
#print(DP)
for tests in range(k//2-1):
NDP=[[0]*m for i in range(n)]
for i in range(n):
for j in range(m):
MIN=DP[i][j]+DP0[i][j]
if 0<=i+1<n:
MIN=min(MIN,TATE[i][j]*2+DP[i+1][j])
if 0<=i-1<n:
MIN=min(MIN,TATE[i-1][j]*2+DP[i-1][j])
if 0<=j+1<m:
MIN=min(MIN,YOKO[i][j]*2+DP[i][j+1])
if 0<=j-1<m:
MIN=min(MIN,YOKO[i][j-1]*2+DP[i][j-1])
NDP[i][j]=MIN
DP=NDP
for dp in DP:
print(*dp)
``` | output | 1 | 48,158 | 3 | 96,317 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are wandering in the explorer space of the 2050 Conference.
The explorer space can be viewed as an undirected weighted grid graph with size n× m. The set of vertices is \{(i, j)|1≤ i≤ n, 1≤ j≤ m\}. Two vertices (i_1,j_1) and (i_2, j_2) are connected by an edge if and only if |i_1-i_2|+|j_1-j_2|=1.
At each step, you can walk to any vertex connected by an edge with your current vertex. On each edge, there are some number of exhibits. Since you already know all the exhibits, whenever you go through an edge containing x exhibits, your boredness increases by x.
For each starting vertex (i, j), please answer the following question: What is the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps?
You can use any edge for multiple times but the boredness on those edges are also counted for multiple times. At each step, you cannot stay on your current vertex. You also cannot change direction while going through an edge. Before going back to your starting vertex (i, j) after k steps, you can visit (i, j) (or not) freely.
Input
The first line contains three integers n, m and k (2≤ n, m≤ 500, 1≤ k≤ 20).
The j-th number (1≤ j ≤ m - 1) in the i-th line of the following n lines is the number of exibits on the edge between vertex (i, j) and vertex (i, j+1).
The j-th number (1≤ j≤ m) in the i-th line of the following n-1 lines is the number of exibits on the edge between vertex (i, j) and vertex (i+1, j).
The number of exhibits on each edge is an integer between 1 and 10^6.
Output
Output n lines with m numbers each. The j-th number in the i-th line, answer_{ij}, should be the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps.
If you cannot go back to vertex (i, j) after exactly k steps, answer_{ij} should be -1.
Examples
Input
3 3 10
1 1
1 1
1 1
1 1 1
1 1 1
Output
10 10 10
10 10 10
10 10 10
Input
2 2 4
1
3
4 2
Output
4 4
10 6
Input
2 2 3
1
2
3 4
Output
-1 -1
-1 -1
Note
In the first example, the answer is always 10 no matter how you walk.
In the second example, answer_{21} = 10, the path is (2,1) → (1,1) → (1,2) → (2,2) → (2,1), the boredness is 4 + 1 + 2 + 3 = 10.
Submitted Solution:
```
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
import threading
from bisect import bisect_right
from math import gcd,log
from collections import Counter,defaultdict,deque
from pprint import pprint
from itertools import permutations
from bisect import bisect_right
from random import randint as rti
# import deque
n,m=0,0
def main(tnum):
global n,m,d
n,m,k=map(int,input().split())
if k%2:
ans=[[-1]*m for i in range(n)]
for li in ans:
print(*li)
return
cost=dict()
dp=[[float('inf')]*m for i in range(n)]
crr=[]
rrr=[]
for i in range(n):
arr=list(map(int,input().split()))
for j in range(m-1):
dp[i][j]=min(dp[i][j],arr[j])
dp[i][j+1]=min(dp[i][j+1],arr[j])
crr.append(arr)
for i in range(n-1):
arr=list(map(int,input().split()))
for j in range(m):
dp[i][j]=min(dp[i][j],arr[j])
dp[i+1][j]=min(dp[i+1][j],arr[j])
rrr.append(arr)
for i in range(1,k//2):
ndp=[[float('inf')]*m for i in range(n)]
for i in range(n):
for j in range(m):
x,y=i,j
if x>0:
ndp[i][j]=min(ndp[i][j],dp[x-1][y]+rrr[x-1][y])
if x<n-1:
ndp[i][j]=min(ndp[i][j],dp[x+1][y]+rrr[x][y])
if y>0:
ndp[i][j]=min(ndp[i][j],dp[x][y-1]+crr[x][y-1])
if y<m-1:
ndp[i][j]=min(ndp[i][j],dp[x][y+1]+crr[x][y])
dp=ndp
for li in dp:
li=[2*x for x in li]
print(*li)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
for _ in range(1):
main(_+1)
``` | instruction | 0 | 48,159 | 3 | 96,318 |
Yes | output | 1 | 48,159 | 3 | 96,319 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are wandering in the explorer space of the 2050 Conference.
The explorer space can be viewed as an undirected weighted grid graph with size n× m. The set of vertices is \{(i, j)|1≤ i≤ n, 1≤ j≤ m\}. Two vertices (i_1,j_1) and (i_2, j_2) are connected by an edge if and only if |i_1-i_2|+|j_1-j_2|=1.
At each step, you can walk to any vertex connected by an edge with your current vertex. On each edge, there are some number of exhibits. Since you already know all the exhibits, whenever you go through an edge containing x exhibits, your boredness increases by x.
For each starting vertex (i, j), please answer the following question: What is the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps?
You can use any edge for multiple times but the boredness on those edges are also counted for multiple times. At each step, you cannot stay on your current vertex. You also cannot change direction while going through an edge. Before going back to your starting vertex (i, j) after k steps, you can visit (i, j) (or not) freely.
Input
The first line contains three integers n, m and k (2≤ n, m≤ 500, 1≤ k≤ 20).
The j-th number (1≤ j ≤ m - 1) in the i-th line of the following n lines is the number of exibits on the edge between vertex (i, j) and vertex (i, j+1).
The j-th number (1≤ j≤ m) in the i-th line of the following n-1 lines is the number of exibits on the edge between vertex (i, j) and vertex (i+1, j).
The number of exhibits on each edge is an integer between 1 and 10^6.
Output
Output n lines with m numbers each. The j-th number in the i-th line, answer_{ij}, should be the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps.
If you cannot go back to vertex (i, j) after exactly k steps, answer_{ij} should be -1.
Examples
Input
3 3 10
1 1
1 1
1 1
1 1 1
1 1 1
Output
10 10 10
10 10 10
10 10 10
Input
2 2 4
1
3
4 2
Output
4 4
10 6
Input
2 2 3
1
2
3 4
Output
-1 -1
-1 -1
Note
In the first example, the answer is always 10 no matter how you walk.
In the second example, answer_{21} = 10, the path is (2,1) → (1,1) → (1,2) → (2,2) → (2,1), the boredness is 4 + 1 + 2 + 3 = 10.
Submitted Solution:
```
n,m,k=list(map(int,input().split()))
p=[]
for _ in range(n):
p.append(list(map(int,input().split())))
q=[]
for _ in range(n-1):
q.append(list(map(int,input().split())))
def f(g):
r=[[0]*m for _ in range(n)]
for i in range(n):
for j in range(m):
l=[]
if i-1>=0:
l.append(g[i-1][j]+q[i-1][j])
if i+1<n:
#print(i,j)
l.append(g[i+1][j]+q[i][j])
if j-1>=0:
l.append(g[i][j-1]+p[i][j-1])
if j+1<m:
l.append(g[i][j+1]+p[i][j])
r[i][j]=min(l)
return r
g=[[0]*m for _ in range(n)]
if k%2!=0:
for i in range(n):
for j in range(m):
g[i][j]=-1
print(*g[i])
else:
for _ in range(k//2):
g=f(g)
for i in range(n):
for j in range(m):
g[i][j]*=2
print(*g[i])
``` | instruction | 0 | 48,160 | 3 | 96,320 |
Yes | output | 1 | 48,160 | 3 | 96,321 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are wandering in the explorer space of the 2050 Conference.
The explorer space can be viewed as an undirected weighted grid graph with size n× m. The set of vertices is \{(i, j)|1≤ i≤ n, 1≤ j≤ m\}. Two vertices (i_1,j_1) and (i_2, j_2) are connected by an edge if and only if |i_1-i_2|+|j_1-j_2|=1.
At each step, you can walk to any vertex connected by an edge with your current vertex. On each edge, there are some number of exhibits. Since you already know all the exhibits, whenever you go through an edge containing x exhibits, your boredness increases by x.
For each starting vertex (i, j), please answer the following question: What is the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps?
You can use any edge for multiple times but the boredness on those edges are also counted for multiple times. At each step, you cannot stay on your current vertex. You also cannot change direction while going through an edge. Before going back to your starting vertex (i, j) after k steps, you can visit (i, j) (or not) freely.
Input
The first line contains three integers n, m and k (2≤ n, m≤ 500, 1≤ k≤ 20).
The j-th number (1≤ j ≤ m - 1) in the i-th line of the following n lines is the number of exibits on the edge between vertex (i, j) and vertex (i, j+1).
The j-th number (1≤ j≤ m) in the i-th line of the following n-1 lines is the number of exibits on the edge between vertex (i, j) and vertex (i+1, j).
The number of exhibits on each edge is an integer between 1 and 10^6.
Output
Output n lines with m numbers each. The j-th number in the i-th line, answer_{ij}, should be the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps.
If you cannot go back to vertex (i, j) after exactly k steps, answer_{ij} should be -1.
Examples
Input
3 3 10
1 1
1 1
1 1
1 1 1
1 1 1
Output
10 10 10
10 10 10
10 10 10
Input
2 2 4
1
3
4 2
Output
4 4
10 6
Input
2 2 3
1
2
3 4
Output
-1 -1
-1 -1
Note
In the first example, the answer is always 10 no matter how you walk.
In the second example, answer_{21} = 10, the path is (2,1) → (1,1) → (1,2) → (2,2) → (2,1), the boredness is 4 + 1 + 2 + 3 = 10.
Submitted Solution:
```
import sys, os
from io import BytesIO, IOBase
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
# 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")
stdin, stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
mod = pow(10, 9) + 7
mod2 = 998244353
def inp(): return stdin.readline().strip()
def iinp(): return int(inp())
def out(var, end="\n"): stdout.write(str(var)+"\n")
def outa(*var, end="\n"): stdout.write(' '.join(map(str, var)) + end)
def lmp(): return list(mp())
def mp(): return map(int, inp().split())
def smp(): return map(str, inp().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(m, val) for j in range(n)]
def remadd(x, y): return 1 if x%y else 0
def ceil(a,b): return (a+b-1)//b
S1 = 'abcdefghijklmnopqrstuvwxyz'
S2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def isprime(x):
if x<=1: return False
if x in (2, 3): return True
if x%2 == 0: return False
for i in range(3, int(sqrt(x))+1, 2):
if x%i == 0: return False
return True
n, m, k = mp()
hor = [lmp() for i in range(n)]
ver = [lmp() for i in range(n-1)]
if k%2:
ml = l2d(n, m, -1)
for i in ml: print(*i)
exit()
k//=2
dp = [l2d(n, m) for i in range(k+1)]
for f in range(1, k+1):
for i in range(n):
for j in range(m):
a = inf
if i!=0:
a = min(a, 2*ver[i-1][j]+dp[f-1][i-1][j])
if i!=n-1:
a = min(a, 2*ver[i][j]+dp[f-1][i+1][j])
if j!=0:
a = min(a, 2*hor[i][j-1]+dp[f-1][i][j-1])
if j!=m-1:
a = min(a, 2*hor[i][j]+dp[f-1][i][j+1])
dp[f][i][j] = a
for i in dp[-1]:
print(*i)
``` | instruction | 0 | 48,161 | 3 | 96,322 |
Yes | output | 1 | 48,161 | 3 | 96,323 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are wandering in the explorer space of the 2050 Conference.
The explorer space can be viewed as an undirected weighted grid graph with size n× m. The set of vertices is \{(i, j)|1≤ i≤ n, 1≤ j≤ m\}. Two vertices (i_1,j_1) and (i_2, j_2) are connected by an edge if and only if |i_1-i_2|+|j_1-j_2|=1.
At each step, you can walk to any vertex connected by an edge with your current vertex. On each edge, there are some number of exhibits. Since you already know all the exhibits, whenever you go through an edge containing x exhibits, your boredness increases by x.
For each starting vertex (i, j), please answer the following question: What is the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps?
You can use any edge for multiple times but the boredness on those edges are also counted for multiple times. At each step, you cannot stay on your current vertex. You also cannot change direction while going through an edge. Before going back to your starting vertex (i, j) after k steps, you can visit (i, j) (or not) freely.
Input
The first line contains three integers n, m and k (2≤ n, m≤ 500, 1≤ k≤ 20).
The j-th number (1≤ j ≤ m - 1) in the i-th line of the following n lines is the number of exibits on the edge between vertex (i, j) and vertex (i, j+1).
The j-th number (1≤ j≤ m) in the i-th line of the following n-1 lines is the number of exibits on the edge between vertex (i, j) and vertex (i+1, j).
The number of exhibits on each edge is an integer between 1 and 10^6.
Output
Output n lines with m numbers each. The j-th number in the i-th line, answer_{ij}, should be the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps.
If you cannot go back to vertex (i, j) after exactly k steps, answer_{ij} should be -1.
Examples
Input
3 3 10
1 1
1 1
1 1
1 1 1
1 1 1
Output
10 10 10
10 10 10
10 10 10
Input
2 2 4
1
3
4 2
Output
4 4
10 6
Input
2 2 3
1
2
3 4
Output
-1 -1
-1 -1
Note
In the first example, the answer is always 10 no matter how you walk.
In the second example, answer_{21} = 10, the path is (2,1) → (1,1) → (1,2) → (2,2) → (2,1), the boredness is 4 + 1 + 2 + 3 = 10.
Submitted Solution:
```
from sys import stdin
input=stdin.readline
rn=lambda:int(input())
rns=lambda:map(int,input().split())
rl=lambda:list(map(int,input().split()))
rs=lambda:input()
YN=lambda x:print('YES') if x else print('NO')
mod=10**9+7
n,m,k=rns()
rows=[rl() for i in range(n)]
cols=[rl() for i in range(n-1)]
def solve():
if k%2==1:
return [m*[-1] for i in range(n)]
dp=[[[0 for i in range(k//2+1)] for j in range(m)] for l in range(n)]
for i in range(1,k//2+1):
for a in range(n):
for b in range(m):
mins=[]
if b>0:
mins.append(dp[a][b-1][i-1] + 2*rows[a][b-1])
if b<m-1:
mins.append(dp[a][b + 1][i - 1] + 2 * rows[a][b])
if a>0:
mins.append(dp[a-1][b][i - 1] + 2 * cols[a-1][b])
if a<n-1:
mins.append(dp[a+1][b][i - 1] + 2 * cols[a][b])
dp[a][b][i]=min(mins)
ans=[[dp[i][j][-1] for j in range(m)] for i in range(n)]
return ans
ans = solve()
for i in ans:
print(*i)
``` | instruction | 0 | 48,162 | 3 | 96,324 |
Yes | output | 1 | 48,162 | 3 | 96,325 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are wandering in the explorer space of the 2050 Conference.
The explorer space can be viewed as an undirected weighted grid graph with size n× m. The set of vertices is \{(i, j)|1≤ i≤ n, 1≤ j≤ m\}. Two vertices (i_1,j_1) and (i_2, j_2) are connected by an edge if and only if |i_1-i_2|+|j_1-j_2|=1.
At each step, you can walk to any vertex connected by an edge with your current vertex. On each edge, there are some number of exhibits. Since you already know all the exhibits, whenever you go through an edge containing x exhibits, your boredness increases by x.
For each starting vertex (i, j), please answer the following question: What is the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps?
You can use any edge for multiple times but the boredness on those edges are also counted for multiple times. At each step, you cannot stay on your current vertex. You also cannot change direction while going through an edge. Before going back to your starting vertex (i, j) after k steps, you can visit (i, j) (or not) freely.
Input
The first line contains three integers n, m and k (2≤ n, m≤ 500, 1≤ k≤ 20).
The j-th number (1≤ j ≤ m - 1) in the i-th line of the following n lines is the number of exibits on the edge between vertex (i, j) and vertex (i, j+1).
The j-th number (1≤ j≤ m) in the i-th line of the following n-1 lines is the number of exibits on the edge between vertex (i, j) and vertex (i+1, j).
The number of exhibits on each edge is an integer between 1 and 10^6.
Output
Output n lines with m numbers each. The j-th number in the i-th line, answer_{ij}, should be the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps.
If you cannot go back to vertex (i, j) after exactly k steps, answer_{ij} should be -1.
Examples
Input
3 3 10
1 1
1 1
1 1
1 1 1
1 1 1
Output
10 10 10
10 10 10
10 10 10
Input
2 2 4
1
3
4 2
Output
4 4
10 6
Input
2 2 3
1
2
3 4
Output
-1 -1
-1 -1
Note
In the first example, the answer is always 10 no matter how you walk.
In the second example, answer_{21} = 10, the path is (2,1) → (1,1) → (1,2) → (2,2) → (2,1), the boredness is 4 + 1 + 2 + 3 = 10.
Submitted Solution:
```
# SHRi GANESHA author: Kunal Verma #
import os
import sys
from io import BytesIO, IOBase
from math import gcd, inf, sqrt, ceil
def lcm(a, b):
return (a * b) // gcd(a, b)
'''
mod = 10 ** 9 + 7
fac = [1]
for i in range(1, 2 * 10 ** 5 + 1):
fac.append((fac[-1] * i) % mod)
fac_in = [pow(fac[-1], mod - 2, mod)]
for i in range(2 * 10 ** 5, 0, -1):
fac_in.append((fac_in[-1] * i) % mod)
fac_in.reverse()
def comb(a, b):
if a < b:
return 0
return (fac[a] * fac_in[b] * fac_in[a - b]) % mod
'''
#MAXN = 16000000
#spf = [0 for i in range(MAXN)]
def sieve():
spf[1] = 1
for i in range(2, MAXN):
spf[i] = i
for i in range(4, MAXN, 2):
spf[i] = 2
for i in range(3, ceil(sqrt(MAXN))):
if (spf[i] == i):
for j in range(i * i, MAXN, i):
if (spf[j] == j):
spf[j] = i
def getFactorization(x):
ret = set()
while (x != 1):
ret.add(spf[x])
x = x // spf[x]
return ret
def printDivisors(n):
i = 2
z = [1, n]
while i <= sqrt(n):
if (n % i == 0):
if (n / i == i):
z.append(i)
else:
z.append(i)
z.append(n // i)
i = i + 1
return z
def create(n, x, f):
pq = len(bin(n)[2:])
if f == 0:
tt = min
else:
tt = max
dp = [[inf] * n for _ in range(pq)]
dp[0] = x
for i in range(1, pq):
for j in range(n - (1 << i) + 1):
dp[i][j] = tt(dp[i - 1][j], dp[i - 1][j + (1 << (i - 1))])
return dp
def enquiry(l, r, dp, f):
if l > r:
return inf if not f else -inf
if f == 1:
tt = max
else:
tt = min
pq1 = len(bin(r - l + 1)[2:]) - 1
return tt(dp[pq1][l], dp[pq1][r - (1 << pq1) + 1])
def SieveOfEratosthenes(n):
prime = [True for i in range(n + 1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n + 1, p):
prime[i] = False
p += 1
x = []
for i in range(2, n + 1):
if prime[i]:
x.append(i)
return x
def main():
n,m,k=map(int,input().split())
cosp=[]
cosv=[]
for i in range(n):
cosp.append([int(x) for x in input().split()])
for i in range(n-1):
cosv.append([int(x) for x in input().split()])
dp=[[[-1]*20 for i in range(m)] for j in range(n)]
# print(cosp)
# print(cosv)
if k%2==1:
matx=[[-1 for i in range(m) ] for j in range(n)]
for i in range(n):
print(*matx[i])
exit()
def func(i,j,mm):
an=inf
if mm==0:
return 0
if dp[i][j][mm]!=-1:
return dp[i][j][mm]
if i-1>=0:
an=min(2*cosv[i-1][j]+func(i-1,j,mm-2),an)
if j-1>=0:
an=min(2*cosp[i][j-1]+func(i,j-1,mm-2),an)
if i+1<n:
an=min(2*cosv[i][j]+func(i+1,j,mm-2),an)
if j+1<m:
an=min(2*cosp[i][j]+func(i,j+1,mm-2),an)
dp[i][j][m]=an
return an
matx=[[0 for i in range(m) ] for j in range(n)]
for i in range(n):
for j in range(m):
matx[i][j]=func(i,j,k)
for i in range(n):
print(*matx[i])
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == '__main__':
main()
``` | instruction | 0 | 48,163 | 3 | 96,326 |
No | output | 1 | 48,163 | 3 | 96,327 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are wandering in the explorer space of the 2050 Conference.
The explorer space can be viewed as an undirected weighted grid graph with size n× m. The set of vertices is \{(i, j)|1≤ i≤ n, 1≤ j≤ m\}. Two vertices (i_1,j_1) and (i_2, j_2) are connected by an edge if and only if |i_1-i_2|+|j_1-j_2|=1.
At each step, you can walk to any vertex connected by an edge with your current vertex. On each edge, there are some number of exhibits. Since you already know all the exhibits, whenever you go through an edge containing x exhibits, your boredness increases by x.
For each starting vertex (i, j), please answer the following question: What is the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps?
You can use any edge for multiple times but the boredness on those edges are also counted for multiple times. At each step, you cannot stay on your current vertex. You also cannot change direction while going through an edge. Before going back to your starting vertex (i, j) after k steps, you can visit (i, j) (or not) freely.
Input
The first line contains three integers n, m and k (2≤ n, m≤ 500, 1≤ k≤ 20).
The j-th number (1≤ j ≤ m - 1) in the i-th line of the following n lines is the number of exibits on the edge between vertex (i, j) and vertex (i, j+1).
The j-th number (1≤ j≤ m) in the i-th line of the following n-1 lines is the number of exibits on the edge between vertex (i, j) and vertex (i+1, j).
The number of exhibits on each edge is an integer between 1 and 10^6.
Output
Output n lines with m numbers each. The j-th number in the i-th line, answer_{ij}, should be the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps.
If you cannot go back to vertex (i, j) after exactly k steps, answer_{ij} should be -1.
Examples
Input
3 3 10
1 1
1 1
1 1
1 1 1
1 1 1
Output
10 10 10
10 10 10
10 10 10
Input
2 2 4
1
3
4 2
Output
4 4
10 6
Input
2 2 3
1
2
3 4
Output
-1 -1
-1 -1
Note
In the first example, the answer is always 10 no matter how you walk.
In the second example, answer_{21} = 10, the path is (2,1) → (1,1) → (1,2) → (2,2) → (2,1), the boredness is 4 + 1 + 2 + 3 = 10.
Submitted Solution:
```
# by the authority of GOD author: manhar singh sachdev #
def some_random_function():
"""due to the fast IO template, my code gets caught in
plag check for no reason. That is why, I am making
random functions"""
x = 10
x *= 100
i_dont_know = x
why_am_i_writing_this = x*x
print(i_dont_know)
print(why_am_i_writing_this)
def some_random_function5():
"""due to the fast IO template, my code gets caught in
plag check for no reason. That is why, I am making
random functions"""
x = 10
x *= 100
i_dont_know = x
why_am_i_writing_this = x*x
print(i_dont_know)
print(why_am_i_writing_this)
import os,sys
from io import BytesIO,IOBase
from collections import defaultdict,deque
# from array import array
def main():
n,m,k = map(int,input().split())
hor = [list(map(int,input().split()))+[10**20+1] for _ in range(n)]
ver = [list(map(int,input().split())) for _ in range(n-1)]+[[10**20+1]*m]
dp = [[10**20]*m for _ in range(n)]
dx,dy = [0,0,1,-1],[1,-1,0,0]
for i in range(n):
for j in range(m):
dist = defaultdict(lambda:10**20)
dist[(i,j)] = 0
curr = deque([(0,0,i,j)])
while len(curr):
d,s,x,y = curr.popleft()
if s > k//2:
continue
if s and not k%s and not (k//s)&1:
dp[i][j] = min(dp[i][j],d*(k//s))
for kk in range(4):
x1,y1 = x+dx[kk],y+dy[kk]
if kk < 2:
ed = hor[x][y-(kk==1)]
else:
ed = ver[x-(kk==3)][y]
if not (k-2*s)&1:
dp[i][j] = min(dp[i][j],2*d+ed*(k-2*s))
zz = ed+d
if dist[(x1,y1)] > zz:
dist[(x1,y1)] = zz
curr.append((zz,s+1,x1,y1))
if dp[i][j] == 10**20:
for _ in range(n):
print(*[-1]*m)
exit()
for i in dp:
print(*i)
#Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def some_random_function1():
"""due to the fast IO template, my code gets caught in
plag check for no reason. That is why, I am making
random functions"""
x = 10
x *= 100
i_dont_know = x
why_am_i_writing_this = x*x
print(i_dont_know)
print(why_am_i_writing_this)
def some_random_function2():
"""due to the fast IO template, my code gets caught in
plag check for no reason. That is why, I am making
random functions"""
x = 10
x *= 100
i_dont_know = x
why_am_i_writing_this = x*x
print(i_dont_know)
print(why_am_i_writing_this)
def some_random_function3():
"""due to the fast IO template, my code gets caught in
plag check for no reason. That is why, I am making
random functions"""
x = 10
x *= 100
i_dont_know = x
why_am_i_writing_this = x*x
print(i_dont_know)
print(why_am_i_writing_this)
def some_random_function4():
"""due to the fast IO template, my code gets caught in
plag check for no reason. That is why, I am making
random functions"""
x = 10
x *= 100
i_dont_know = x
why_am_i_writing_this = x*x
print(i_dont_know)
print(why_am_i_writing_this)
def some_random_function6():
"""due to the fast IO template, my code gets caught in
plag check for no reason. That is why, I am making
random functions"""
x = 10
x *= 100
i_dont_know = x
why_am_i_writing_this = x*x
print(i_dont_know)
print(why_am_i_writing_this)
def some_random_function7():
"""due to the fast IO template, my code gets caught in
plag check for no reason. That is why, I am making
random functions"""
x = 10
x *= 100
i_dont_know = x
why_am_i_writing_this = x*x
print(i_dont_know)
print(why_am_i_writing_this)
def some_random_function8():
"""due to the fast IO template, my code gets caught in
plag check for no reason. That is why, I am making
random functions"""
x = 10
x *= 100
i_dont_know = x
why_am_i_writing_this = x*x
print(i_dont_know)
print(why_am_i_writing_this)
if __name__ == '__main__':
main()
``` | instruction | 0 | 48,164 | 3 | 96,328 |
No | output | 1 | 48,164 | 3 | 96,329 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are wandering in the explorer space of the 2050 Conference.
The explorer space can be viewed as an undirected weighted grid graph with size n× m. The set of vertices is \{(i, j)|1≤ i≤ n, 1≤ j≤ m\}. Two vertices (i_1,j_1) and (i_2, j_2) are connected by an edge if and only if |i_1-i_2|+|j_1-j_2|=1.
At each step, you can walk to any vertex connected by an edge with your current vertex. On each edge, there are some number of exhibits. Since you already know all the exhibits, whenever you go through an edge containing x exhibits, your boredness increases by x.
For each starting vertex (i, j), please answer the following question: What is the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps?
You can use any edge for multiple times but the boredness on those edges are also counted for multiple times. At each step, you cannot stay on your current vertex. You also cannot change direction while going through an edge. Before going back to your starting vertex (i, j) after k steps, you can visit (i, j) (or not) freely.
Input
The first line contains three integers n, m and k (2≤ n, m≤ 500, 1≤ k≤ 20).
The j-th number (1≤ j ≤ m - 1) in the i-th line of the following n lines is the number of exibits on the edge between vertex (i, j) and vertex (i, j+1).
The j-th number (1≤ j≤ m) in the i-th line of the following n-1 lines is the number of exibits on the edge between vertex (i, j) and vertex (i+1, j).
The number of exhibits on each edge is an integer between 1 and 10^6.
Output
Output n lines with m numbers each. The j-th number in the i-th line, answer_{ij}, should be the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps.
If you cannot go back to vertex (i, j) after exactly k steps, answer_{ij} should be -1.
Examples
Input
3 3 10
1 1
1 1
1 1
1 1 1
1 1 1
Output
10 10 10
10 10 10
10 10 10
Input
2 2 4
1
3
4 2
Output
4 4
10 6
Input
2 2 3
1
2
3 4
Output
-1 -1
-1 -1
Note
In the first example, the answer is always 10 no matter how you walk.
In the second example, answer_{21} = 10, the path is (2,1) → (1,1) → (1,2) → (2,2) → (2,1), the boredness is 4 + 1 + 2 + 3 = 10.
Submitted Solution:
```
from sys import stdin, stdout, setrecursionlimit
input = stdin.readline
# setrecursionlimit(int(1e6))
inf = float('inf')
from collections import defaultdict as dd
from collections import Counter, deque
from heapq import *
import math
from math import floor, ceil, sqrt
def geti(): return map(int, input().strip().split())
def getl(): return list(map(int, input().strip().split()))
def getis(): return map(str, input().strip().split())
def getls(): return list(map(str, input().strip().split()))
def gets(): return input().strip()
def geta(): return int(input())
def print_s(s): stdout.write(s+'\n')
dir = [0,1,0,-1,0]
def solve():
n, m, k = geti()
maxi = [k]
cost_col = []
for i in range(n):
cost_col.append(getl())
cost_row = []
for i in range(n-1):
cost_row.append(getl())
mat = [[inf]*m for _ in range(n)]
def cost(r,c,k,start,end,res=0):
if vis[r][c]==maxi[0]*maxi[0]+1:
return
vis[r][c]+=1
temp = inf
if abs(start-r) + abs(end-c) > k:
return
for d in range(4):
i = r + dir[d]
j = c + dir[d+1]
if 0<=i<n and 0<=j<m:
if i>r:
now = cost_row[r][j]
elif r>i:
now = cost_row[i][j]
elif j>c:
now = cost_col[i][c]
elif j<c:
now = cost_col[i][j]
if i==start and j==end and k==1:
mat[i][j] = min(mat[i][j], res+now)
if k!=1:
cost(i,j,k-1,start,end,res+now)
return
for i in range(n):
for j in range(m):
vis = [[0]*m for _ in range(n)]
cost(i,j,k,i,j)
for i in mat:
for j in range(len(i)):
if i[j]==inf:
i[j]=-1
print(*i)
if __name__=='__main__':
solve()
``` | instruction | 0 | 48,165 | 3 | 96,330 |
No | output | 1 | 48,165 | 3 | 96,331 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are wandering in the explorer space of the 2050 Conference.
The explorer space can be viewed as an undirected weighted grid graph with size n× m. The set of vertices is \{(i, j)|1≤ i≤ n, 1≤ j≤ m\}. Two vertices (i_1,j_1) and (i_2, j_2) are connected by an edge if and only if |i_1-i_2|+|j_1-j_2|=1.
At each step, you can walk to any vertex connected by an edge with your current vertex. On each edge, there are some number of exhibits. Since you already know all the exhibits, whenever you go through an edge containing x exhibits, your boredness increases by x.
For each starting vertex (i, j), please answer the following question: What is the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps?
You can use any edge for multiple times but the boredness on those edges are also counted for multiple times. At each step, you cannot stay on your current vertex. You also cannot change direction while going through an edge. Before going back to your starting vertex (i, j) after k steps, you can visit (i, j) (or not) freely.
Input
The first line contains three integers n, m and k (2≤ n, m≤ 500, 1≤ k≤ 20).
The j-th number (1≤ j ≤ m - 1) in the i-th line of the following n lines is the number of exibits on the edge between vertex (i, j) and vertex (i, j+1).
The j-th number (1≤ j≤ m) in the i-th line of the following n-1 lines is the number of exibits on the edge between vertex (i, j) and vertex (i+1, j).
The number of exhibits on each edge is an integer between 1 and 10^6.
Output
Output n lines with m numbers each. The j-th number in the i-th line, answer_{ij}, should be the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps.
If you cannot go back to vertex (i, j) after exactly k steps, answer_{ij} should be -1.
Examples
Input
3 3 10
1 1
1 1
1 1
1 1 1
1 1 1
Output
10 10 10
10 10 10
10 10 10
Input
2 2 4
1
3
4 2
Output
4 4
10 6
Input
2 2 3
1
2
3 4
Output
-1 -1
-1 -1
Note
In the first example, the answer is always 10 no matter how you walk.
In the second example, answer_{21} = 10, the path is (2,1) → (1,1) → (1,2) → (2,2) → (2,1), the boredness is 4 + 1 + 2 + 3 = 10.
Submitted Solution:
```
def solve(n,m,k,h,v):
ans = [[-1]*m for i in range(n)]
for _i in range(n):
for _j in range(m):
dp = [[[10*8]*(k+1) for _ in range(21)] for _ in range(21)]
dp[10][10][0] = 0
for t in range(1, k+1):
for i_ in range(max(_i-10, 0), min(_i+10, n)):
for j_ in range(max(_j-10, 0), min(_j+10, m)):
i = i_ - _i + 10
j = j_ - _j + 10
# print(i)
# print(v)
if i_ < n-1 and i < 20:
dp[i+1][j][t] = min(dp[i][j][t-1]+v[i_][j_], dp[i+1][j][t])
if i_ > 0 and i > 0:
dp[i-1][j][t] = min(dp[i][j][t-1]+v[i_-1][j_], dp[i-1][j][t])
if j_ < m-1 and j < 20:
dp[i][j+1][t] = min(dp[i][j][t-1]+h[i_][j_], dp[i][j+1][t])
if j_ > 0 and j > 0:
dp[i][j-1][t] = min(dp[i][j][t-1]+h[i_][j_-1], dp[i][j-1][t])
if (dp[10][10][k]) < 10*8:
ans[_i][_j] = dp[10][10][k]
return ans
def main():
n,m,k=list(map(int, input().split(' ')))
h = [list(map(int, input().split(' '))) for i in range(n)]
v = [list(map(int, input().split(' '))) for i in range(n-1)]
# B = [list(map(int, input().split(' '))) for i in range(n)]
ans = solve(n,m,k,h,v)
for i in range(n):
print(' '.join(list(map(str, ans[i]))))
if __name__ == '__main__':
main()
``` | instruction | 0 | 48,166 | 3 | 96,332 |
No | output | 1 | 48,166 | 3 | 96,333 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 ≤ u, v ≤ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.
In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.
Input
The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 ≤ a, b ≤ n and a ≠ b).
Output
Print one number – the brain latency.
Examples
Input
4 3
1 2
1 3
1 4
Output
2
Input
5 4
1 2
2 3
3 4
3 5
Output
3 | instruction | 0 | 48,402 | 3 | 96,804 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
# https://www.youtube.com/watch?v=_q7aMi-5Uos
import sys
from collections import defaultdict
n,m = list(map(int,sys.stdin.readline().lstrip().rstrip().split()))
graph = defaultdict(list)
for i in range(m):
u,v = list(map(int,sys.stdin.readline().lstrip().rstrip().split()))
graph[u-1].append(v-1)
graph[v-1].append(u-1)
visited = [False for i in range(n)]
q = [[0,0]]
temp = []
visited[0] = True
while q!=[]:
node,dist = q[0][0],q[0][1]
q.pop(0)
leaf = True
for v in graph[node]:
if visited[v]==False:
visited[v] = True
q.append([v,dist+1])
leaf = False
if leaf:
temp.append([dist,node])
temp.sort()
visited = [False for i in range(n)]
q = [[temp[-1][1],0]]
temp = []
visited[q[0][0]] = True
while q!=[]:
node,dist = q[0][0],q[0][1]
q.pop(0)
leaf = True
for v in graph[node]:
if visited[v]==False:
visited[v] = True
q.append([v,dist+1])
leaf = False
if leaf:
temp.append(dist)
sys.stdout.write(str(max(temp))+'\n')
``` | output | 1 | 48,402 | 3 | 96,805 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 ≤ u, v ≤ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.
In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.
Input
The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 ≤ a, b ≤ n and a ≠ b).
Output
Print one number – the brain latency.
Examples
Input
4 3
1 2
1 3
1 4
Output
2
Input
5 4
1 2
2 3
3 4
3 5
Output
3 | instruction | 0 | 48,403 | 3 | 96,806 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
f = lambda: map(int, input().split())
n, m = f()
p = [[] for i in range(n)]
for j in range(m):
a, b = f()
p[a - 1].append(b - 1)
p[b - 1].append(a - 1)
def g(i):
u, t = [1] * n, (0, i)
s = [t]
while s:
d, i = s.pop()
u[i] = 0
if d > t[0]: t = (d, i)
s += [(d + 1, j) for j in p[i] if u[j]]
return t
print(g(g(0)[1])[0])
``` | output | 1 | 48,403 | 3 | 96,807 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 ≤ u, v ≤ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.
In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.
Input
The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 ≤ a, b ≤ n and a ≠ b).
Output
Print one number – the brain latency.
Examples
Input
4 3
1 2
1 3
1 4
Output
2
Input
5 4
1 2
2 3
3 4
3 5
Output
3 | instruction | 0 | 48,404 | 3 | 96,808 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
n,m=map(int,input().split())
gr=[[] for i in range(n)]
for i in range(m):
u,v=map(int,input().split())
gr[v-1].append(u-1)
gr[u-1].append(v-1)
v=[False for i in range(n)]
s=[0]
tr={}
tr[0]=0
while s:
x=s.pop()
v[x]=True
for j in gr[x]:
if v[j]:continue
s.append(j)
tr[j]=tr[x]+1
va=0
ma=0
for j in tr.keys():
if ma<tr[j]:
ma=tr[j]
va=j
v=[False for i in range(n)]
s=[va]
tr={}
tr[va]=0
while s:
x=s.pop()
v[x]=True
for i in gr[x]:
if v[i]:continue
s.append(i)
tr[i]=tr[x]+1
print(max(tr.values()))
``` | output | 1 | 48,404 | 3 | 96,809 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 ≤ u, v ≤ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.
In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.
Input
The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 ≤ a, b ≤ n and a ≠ b).
Output
Print one number – the brain latency.
Examples
Input
4 3
1 2
1 3
1 4
Output
2
Input
5 4
1 2
2 3
3 4
3 5
Output
3 | instruction | 0 | 48,405 | 3 | 96,810 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
import sys
#with open(filename, 'r') as f:
with sys.stdin as f:
for i, line in enumerate(f):
if i == 0:
N, M = line.split(' ')
N, M = int(N), int(M)
graph = [[] for _ in range(N)] # [[]] * N not working, no deepcopy
else:
fromVertex, toVertex = line.split(' ')
fromVertex, toVertex = int(fromVertex)-1, int(toVertex)-1
graph[fromVertex].append(toVertex)
graph[toVertex].append(fromVertex)
# code is too slow, O(N^3)
#~ INFINITY = 9999999
#~ from queue import Queue
#~ def bfs(start_node, graph):
#~ N = len(graph)
#~ distances = [INFINITY for _ in range(N)]
#~ distances[start_node] = 0
#~ nodes_queue = Queue()
#~ nodes_queue.put(start_node)
#~ while not nodes_queue.empty():
#~ node = nodes_queue.get()
#~ for neigh in graph[node]:
#~ if distances[neigh] == INFINITY:
#~ # not yet visited
#~ distances[neigh] = distances[node] + 1
#~ nodes_queue.put(neigh)
#~ return distances
# use tree structure
from queue import Queue
def farthest_node_distance(start_node, graph):
""" returns farthest node from start node and its distance """
N = len(graph)
visited = [False for _ in range(N)]
distances = [-1 for _ in range(N)]
visited[start_node] = True
distances[start_node] = 0
nodes_queue = Queue()
nodes_queue.put(start_node)
while not nodes_queue.empty():
node = nodes_queue.get()
#print("Taking {}: {}".format(node, distances[node]))
for neigh in graph[node]:
if not visited[neigh]:
#print("Found {}".format(neigh))
visited[neigh] = True
distances[neigh] = distances[node] + 1
nodes_queue.put(neigh)
#print("{}: {}".format(neigh, distances[neigh]))
return node, distances[node]
u, dist_u = farthest_node_distance(0, graph)
#print("Done")
v, dist_uv = farthest_node_distance(u, graph)
print(dist_uv)
#print("u: {}, {}".format(u, dist_u))
#print("v: {}, {}".format(v, dist_uv))
``` | output | 1 | 48,405 | 3 | 96,811 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.