message
stringlengths
2
19.9k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
322
108k
cluster
float64
15
15
__index_level_0__
int64
644
217k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a grid of squares with H+1 horizontal rows and W vertical columns. You will start at one of the squares in the top row and repeat moving one square right or down. However, for each integer i from 1 through H, you cannot move down from the A_i-th, (A_i + 1)-th, \ldots, B_i-th squares from the left in the i-th row from the top. For each integer k from 1 through H, find the minimum number of moves needed to reach one of the squares in the (k+1)-th row from the top. (The starting square can be chosen individually for each case.) If, starting from any square in the top row, none of the squares in the (k+1)-th row can be reached, print `-1` instead. Constraints * 1 \leq H,W \leq 2\times 10^5 * 1 \leq A_i \leq B_i \leq W Input Input is given from Standard Input in the following format: H W A_1 B_1 A_2 B_2 : A_H B_H Output Print H lines. The i-th line should contain the answer for the case k=i. Example Input 4 4 2 4 1 1 2 3 2 4 Output 1 3 6 -1 Submitted Solution: ``` from heapq import * class MultisetBIT: """ 最大値が小さい数について、その重複を許した集合を管理する。 最大値 maxvalue を受け取り、[0, maxvalue] を管理する。 閉区間で管理する。 """ __slots__ = ["n", "k", "data"] def __init__(self, maxvalue): "内部では [1, maxvalue + 1] でもつ。" self.n = maxvalue + 1 self.k = 1 << ((self.n + 1).bit_length() - 1) self.data = [0] * (self.n + 1) def add(self, value): """ 与えられた引数を Multiset に加える。 計算量は、n を要素の最大値として、 O(log n) となる。 """ value += 1 while value <= self.n: self.data[value] += 1 value += value & -value def pop(self, value): """ Multiset から与えられた引数を取り除く。 与えられた引数が Multiset に入っているかのチェックは行わなず、 単にその個数を 1 減らすだけなので注意。 計算量は、n を要素の最大値として、 O(log n) となる。 """ value += 1 while value <= self.n: self.data[value] -= 1 value += value & -value def count_le(self, value): """ Multiset 内の要素 elem のうち、0 <= elem <= value を満たすものを数える。 計算量は、n を要素の最大値として、 O(log n) となる。 """ value += 1 ret = 0 while value > 0: ret += self.data[value] value -= value & -value return ret def count(self, first, last): """ Multiset 内の要素 elem のうち、first <= elem <= last を満たすものを数える。 計算量は、n を要素の最大値として、 O(log n) となる。 """ last += 1 ret = 0 while first < last: ret += self.data[last] last -= last & -last while last < first: ret -= self.data[first] first -= first & -first return ret def bisect(self, count): """ Multiset 内の要素 elem のうち、count <= count_le(elem) を満たす最小のelemを返す。 計算量は、n を要素の最大値として、 O(log n) となる。 """ ret = 0 k = self.k while k > 0: if ret + k <= self.n and self.data[ret + k] < count: count -= self.data[ret + k] ret += k k >>= 1 return ret def lower_bound(self, value): """ Multiset 内の要素 elem のうち、value <= elem を満たす最小のelemを返す。 計算量は、n を要素の最大値として、 O(log n) となる。 """ return self.bisect(self.count_le(value - 1) + 1) def upper_bound(self, value): """ Multiset 内の要素 elem のうち、value < elem を満たす最小のelemを返す。 計算量は、n を要素の最大値として、 O(log n) となる。 """ return self.bisect(self.count_le(value) + 1) H, W = map(int, input().split()) destination = MultisetBIT(W) for i in range(W): destination.add(i) destination_to_cost = {i:0 for i in range(W)} min_heapq = [0] * W to_delete = [] for k in range(H): # print([i for i in range(W) if destination.count(i, i)]) # print(destination_to_cost) A, B = map(int, input().split()) A -= 1 B -= 1 start_point = destination.lower_bound(A) point = start_point change_dest_flg = False while point < W and point < B + 1: change_dest_flg = True cost = destination_to_cost.pop(point) heappush(to_delete, cost) if B + 1 != W: if (B + 1 in destination_to_cost): if destination_to_cost[B+1] > (B + 1 - point) + cost: heappush(to_delete, destination_to_cost[B+1]) destination_to_cost[B+1] = (B + 1 - point) + cost heappush(min_heapq, (B + 1 - point) + cost) else: destination_to_cost[B+1] = (B + 1 - point) + cost heappush(min_heapq, (B + 1 - point) + cost) destination.add(B+1) destination.pop(point) point = destination.upper_bound(point) while to_delete and min_heapq[0] == to_delete[0]: heappop(min_heapq) heappop(to_delete) if min_heapq: print(k + min_heapq[0] + 1) else: for _ in range(H - k): print(-1) exit() ```
instruction
0
83,956
15
167,912
Yes
output
1
83,956
15
167,913
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a grid of squares with H+1 horizontal rows and W vertical columns. You will start at one of the squares in the top row and repeat moving one square right or down. However, for each integer i from 1 through H, you cannot move down from the A_i-th, (A_i + 1)-th, \ldots, B_i-th squares from the left in the i-th row from the top. For each integer k from 1 through H, find the minimum number of moves needed to reach one of the squares in the (k+1)-th row from the top. (The starting square can be chosen individually for each case.) If, starting from any square in the top row, none of the squares in the (k+1)-th row can be reached, print `-1` instead. Constraints * 1 \leq H,W \leq 2\times 10^5 * 1 \leq A_i \leq B_i \leq W Input Input is given from Standard Input in the following format: H W A_1 B_1 A_2 B_2 : A_H B_H Output Print H lines. The i-th line should contain the answer for the case k=i. Example Input 4 4 2 4 1 1 2 3 2 4 Output 1 3 6 -1 Submitted Solution: ``` from sys import stdin input = stdin.readline class SegTreeFlag(): def segFunc(self, x, y): return x+y def searchIndexFunc(self, val): return val > 0 def __init__(self, ide, init_val): n = len(init_val) self.ide_ele = ide self.num = 2**(n-1).bit_length() self.seg = [self.ide_ele] * 2 * self.num for i in range(n): self.seg[i+self.num-1] = init_val[i] for i in range(self.num-2,-1,-1): self.seg[i] = self.segFunc(self.seg[2*i+1],self.seg[2*i+2]) def update(self, idx, val): idx += self.num-1 self.seg[idx] = val while idx: idx = (idx-1)//2 self.seg[idx] = self.segFunc(self.seg[idx*2+1], self.seg[idx*2+2]) def query(self, begin, end): if end <= begin: return self.ide_ele begin += self.num-1 end += self.num-2 res = self.ide_ele while begin + 1 < end: if begin&1 == 0: res = self.segFunc(res, self.seg[begin]) if end&1 == 1: res = self.segFunc(res, self.seg[end]) end -= 1 begin = begin//2 end = (end-1)//2 if begin == end: res = self.segFunc(res, self.seg[begin]) else: res = self.segFunc(self.segFunc(res, self.seg[begin]), self.seg[end]) return res def getLargestIndex(self, begin, end): L, R = begin, end if not self.searchIndexFunc(self.query(begin, end)): return None while L+1 < R: P = (L+R)//2 if self.searchIndexFunc(self.query(P, R)): L = P else: R = P return L def getSmallestIndex(self, begin, end): L, R = begin, end if not self.searchIndexFunc(self.query(begin, end)): return None while L+1 < R: P = (L+R+1)//2 if self.searchIndexFunc(self.query(L, P)): R = P else: L = P return L class SegTreeMin(): def segFunc(self, x, y): if x < y: return x else: return y def __init__(self, ide, init_val): n = len(init_val) self.ide_ele = ide self.num = 2**(n-1).bit_length() self.seg = [self.ide_ele] * 2 * self.num for i in range(n): self.seg[i+self.num-1] = init_val[i] for i in range(self.num-2,-1,-1): self.seg[i] = self.segFunc(self.seg[2*i+1],self.seg[2*i+2]) def update(self, idx, val): idx += self.num-1 self.seg[idx] = val while idx: idx = (idx-1)//2 self.seg[idx] = self.segFunc(self.seg[idx*2+1], self.seg[idx*2+2]) def query(self, begin, end): if end <= begin: return self.ide_ele begin += self.num-1 end += self.num-2 res = self.ide_ele while begin + 1 < end: if begin&1 == 0: res = self.segFunc(res, self.seg[begin]) if end&1 == 1: res = self.segFunc(res, self.seg[end]) end -= 1 begin = begin//2 end = (end-1)//2 if begin == end: res = self.segFunc(res, self.seg[begin]) else: res = self.segFunc(self.segFunc(res, self.seg[begin]), self.seg[end]) return res h, w = map(int, input().split()) wall = [list(map(int, input().split())) for _ in range(h)] ans = [-1 for _ in range(h)] segflag = SegTreeFlag(0, [1 for _ in range(w+2)]) segmin = SegTreeMin(10**9, [0 for _ in range(w+2)]) segmin.update(0, 10**9) for i in range(h): idx = segflag.getLargestIndex(0, wall[i][1]+2) if idx < wall[i][1]+1: segflag.update(wall[i][1]+1, 1) segmin.update(wall[i][1]+1, segmin.query(idx, idx+1)+(wall[i][1]+1-idx)) cnt = segflag.query(wall[i][0], wall[i][1]+1) for _ in range(cnt): idx = segflag.getSmallestIndex(wall[i][0], wall[i][1]+1) segflag.update(idx, 0) segmin.update(idx, 10**9) tmp = segmin.query(0, w+1) if tmp < 10**9: ans[i] = tmp + i + 1 else: break for v in ans: print(v) ```
instruction
0
83,957
15
167,914
Yes
output
1
83,957
15
167,915
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a grid of squares with H+1 horizontal rows and W vertical columns. You will start at one of the squares in the top row and repeat moving one square right or down. However, for each integer i from 1 through H, you cannot move down from the A_i-th, (A_i + 1)-th, \ldots, B_i-th squares from the left in the i-th row from the top. For each integer k from 1 through H, find the minimum number of moves needed to reach one of the squares in the (k+1)-th row from the top. (The starting square can be chosen individually for each case.) If, starting from any square in the top row, none of the squares in the (k+1)-th row can be reached, print `-1` instead. Constraints * 1 \leq H,W \leq 2\times 10^5 * 1 \leq A_i \leq B_i \leq W Input Input is given from Standard Input in the following format: H W A_1 B_1 A_2 B_2 : A_H B_H Output Print H lines. The i-th line should contain the answer for the case k=i. Example Input 4 4 2 4 1 1 2 3 2 4 Output 1 3 6 -1 Submitted Solution: ``` class LazySegmentTree: __slots__ = ["n", "data", "lazy", "me", "oe", "fmm", "fmo", "foo"] def __init__(self, monoid_data, monoid_identity, operator_identity, func_monoid_monoid, func_monoid_operator, func_operator_operator): self.me = monoid_identity self.oe = operator_identity self.fmm = func_monoid_monoid self.fmo = func_monoid_operator self.foo = func_operator_operator self.n = len(monoid_data) self.data = monoid_data * 2 for i in range(self.n-1, 0, -1): self.data[i] = self.fmm(self.data[2*i], self.data[2*i+1]) self.lazy = [self.oe] * (self.n * 2) def replace(self, index, value): index += self.n # propagation for shift in range(index.bit_length()-1, 0, -1): i = index >> shift self.lazy[2*i] = self.foo(self.lazy[2*i], self.lazy[i]) self.lazy[2*i+1] = self.foo(self.lazy[2*i+1], self.lazy[i]) self.data[i] = self.fmo(self.data[i], self.lazy[i]) self.lazy[i] = self.oe # update self.data[index] = value self.lazy[index] = self.oe # recalculation i = index while i > 1: i //= 2 self.data[i] = self.fmm( self.fmo(self.data[2*i], self.lazy[2*i]), self.fmo(self.data[2*i+1], self.lazy[2*i+1]) ) self.lazy[i] = self.oe def effect(self, l, r, operator): l += self.n r += self.n l0 = l r0 = r - 1 while l0 % 2 == 0: l0 //= 2 while r0 % 2 == 1: r0 //= 2 # propagation for shift in range(l0.bit_length()-1, 0, -1): i = l0 >> shift self.lazy[2*i] = self.foo(self.lazy[2*i], self.lazy[i]) self.lazy[2*i+1] = self.foo(self.lazy[2*i+1], self.lazy[i]) self.data[i] = self.fmo(self.data[i], self.lazy[i]) self.lazy[i] = self.oe for shift in range(r0.bit_length()-1, 0, -1): i = r0 >> shift self.lazy[2*i] = self.foo(self.lazy[2*i], self.lazy[i]) self.lazy[2*i+1] = self.foo(self.lazy[2*i+1], self.lazy[i]) self.data[i] = self.fmo(self.data[i], self.lazy[i]) self.lazy[i] = self.oe # effect while l < r: if l % 2: self.lazy[l] = self.foo(self.lazy[l], operator) l += 1 if r % 2: r -= 1 self.lazy[r] = self.foo(self.lazy[r], operator) l //= 2 r //= 2 # recalculation i = l0 while i > 1: i //= 2 self.data[i] = self.fmm( self.fmo(self.data[2*i], self.lazy[2*i]), self.fmo(self.data[2*i+1], self.lazy[2*i+1]) ) self.lazy[i] = self.oe i = r0 while i > 1: i //= 2 self.data[i] = self.fmm( self.fmo(self.data[2*i], self.lazy[2*i]), self.fmo(self.data[2*i+1], self.lazy[2*i+1]) ) self.lazy[i] = self.oe def folded(self, l, r): l += self.n r += self.n l0 = l r0 = r - 1 while l0 % 2 == 0: l0 //= 2 while r0 % 2 == 1: r0 //= 2 # propagation for shift in range(l0.bit_length()-1, 0, -1): i = l0 >> shift self.lazy[2*i] = self.foo(self.lazy[2*i], self.lazy[i]) self.lazy[2*i+1] = self.foo(self.lazy[2*i+1], self.lazy[i]) self.data[i] = self.fmo(self.data[i], self.lazy[i]) self.lazy[i] = self.oe for shift in range(r0.bit_length()-1, 0, -1): i = r0 >> shift self.lazy[2*i] = self.foo(self.lazy[2*i], self.lazy[i]) self.lazy[2*i+1] = self.foo(self.lazy[2*i+1], self.lazy[i]) self.data[i] = self.fmo(self.data[i], self.lazy[i]) self.lazy[i] = self.oe # fold left_folded = self.me right_folded = self.me while l < r: if l % 2: left_folded = self.fmm(left_folded, self.fmo(self.data[l], self.lazy[l])) l += 1 if r % 2: r -= 1 right_folded = self.fmm(self.fmo(self.data[r], self.lazy[r]), right_folded) l //= 2 r //= 2 return self.fmm(left_folded, right_folded) import sys input = sys.stdin.readline h, w = map(int, input().split()) def fmo(m1, o1): if o1 == -1: return m1 return o1 def foo(o1, o2): if o2 == -1: return o1 return o2 INF = 10**6 lst_max = LazySegmentTree(list(range(w)), -INF, -1, max, fmo, foo) lst_min = LazySegmentTree([0]*w, INF, -1, min, fmo, foo) for i in range(h): a, b = map(int, input().split()) a -= 1 l_max = lst_max.folded(a, b) lst_max.effect(a, b, -INF) lst_min.effect(a, b, INF) if b < w: x = lst_max.folded(b, b+1) lst_max.replace(b, max(l_max, x)) y = lst_min.folded(b, b+1) lst_min.replace(b, min(b-l_max, y)) ans = lst_min.folded(0, w) if ans == INF: print(-1) else: ans += i+1 print(ans) ```
instruction
0
83,958
15
167,916
Yes
output
1
83,958
15
167,917
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a grid of squares with H+1 horizontal rows and W vertical columns. You will start at one of the squares in the top row and repeat moving one square right or down. However, for each integer i from 1 through H, you cannot move down from the A_i-th, (A_i + 1)-th, \ldots, B_i-th squares from the left in the i-th row from the top. For each integer k from 1 through H, find the minimum number of moves needed to reach one of the squares in the (k+1)-th row from the top. (The starting square can be chosen individually for each case.) If, starting from any square in the top row, none of the squares in the (k+1)-th row can be reached, print `-1` instead. Constraints * 1 \leq H,W \leq 2\times 10^5 * 1 \leq A_i \leq B_i \leq W Input Input is given from Standard Input in the following format: H W A_1 B_1 A_2 B_2 : A_H B_H Output Print H lines. The i-th line should contain the answer for the case k=i. Example Input 4 4 2 4 1 1 2 3 2 4 Output 1 3 6 -1 Submitted Solution: ``` import sys input = sys.stdin.readline from collections import defaultdict def DD(arg): return defaultdict(arg) def int_log(n, a): count = 0 while n>=a: n //= a count += 1 return count H,W = list(map(int,input().split())) data = [list(map(int, input().split())) for _ in range(H)] class BIT: def __init__(self, logn): self.n = 1<<logn self.data = [0]*(self.n+1) self.el = [0]*(self.n+1) def sum(self, i): s = 0 while i > 0: s += self.data[i] i -= i & -i return s def add(self, i, x): # assert i > 0 self.el[i] += x while i <= self.n: self.data[i] += x i += i & -i def get(self, i, j=None): if j is None: return self.el[i] return self.sum(j) - self.sum(i) def bisect(self, x): w = i = 0 k = self.n while k: if i+k <= self.n and w + self.data[i+k] < x: w += self.data[i+k] i += k k >>= 1 return i+1 dic = DD(int) for i in range(W): dic[i+1] = i+1 members = DD(int) for i in range(W): members[i+1] = 1 B = BIT(int_log(W,2)+1) for i in range(W): B.add(i+1,1) def calc_prev_valid(x): s = B.sum(x-1) if s == 0: return 0 else: return B.bisect(s) count_score = DD(int) count_score[0] = W score = 0 for i in range(H): a,b = data[i] now = b while now >= a: if B.el[now]: count_score[now-dic[now]] -= members[now] if not B.el[b+1]: dic[b+1] = dic[now] B.add(b+1,1) if b+1 < W+1: count_score[(b+1)-dic[b+1]] += members[now] B.add(now,-1) members[b+1] += members[now] members[now] = 0 now = calc_prev_valid(now) while True: if count_score[score]: print(score+i+1) break else: score += 1 if score == W: for _ in range(H-i): print(-1) exit() ```
instruction
0
83,959
15
167,918
Yes
output
1
83,959
15
167,919
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a grid of squares with H+1 horizontal rows and W vertical columns. You will start at one of the squares in the top row and repeat moving one square right or down. However, for each integer i from 1 through H, you cannot move down from the A_i-th, (A_i + 1)-th, \ldots, B_i-th squares from the left in the i-th row from the top. For each integer k from 1 through H, find the minimum number of moves needed to reach one of the squares in the (k+1)-th row from the top. (The starting square can be chosen individually for each case.) If, starting from any square in the top row, none of the squares in the (k+1)-th row can be reached, print `-1` instead. Constraints * 1 \leq H,W \leq 2\times 10^5 * 1 \leq A_i \leq B_i \leq W Input Input is given from Standard Input in the following format: H W A_1 B_1 A_2 B_2 : A_H B_H Output Print H lines. The i-th line should contain the answer for the case k=i. Example Input 4 4 2 4 1 1 2 3 2 4 Output 1 3 6 -1 Submitted Solution: ``` from sys import setrecursionlimit, stdin from random import random readline = stdin.readline setrecursionlimit(10 ** 6) class TreapNode: def __init__(self, key, value=None): self._key = key self._value = value self._priority = random() self._left = None self._right = None @property def key(self): return self._key @property def value(self): return self._value def treap_rotate_right(n): l = n._left n._left = l._right l._right = n return l def treap_rotate_left(n): r = n._right n._right = r._left r._left = n return r def treap_find(n, key): if n is None: return None if n.key == key: return n if key < n.key: return treap_find(n._left, key) else: return treap_find(n._right, key) def treap_lower_bound(n, key): if n is None: return None if n.key < key: return treap_lower_bound(n._right, key) t = treap_lower_bound(n._left, key) if t is None: return n else: return t def treap_insert(n, key, value=None): if n is None: return TreapNode(key, value) if n.key == key: raise Exception('duplicated key') if n.key > key: n._left = treap_insert(n._left, key, value) if n._priority > n._left._priority: n = treap_rotate_right(n) else: n._right = treap_insert(n._right, key, value) if n._priority > n._right._priority: n = treap_rotate_left(n) return n def treap_delete(n, key): if n is None: raise Exception('non-existent key') if n.key > key: n._left = treap_delete(n._left, key) return n if n.key < key: n._right = treap_delete(n._right, key) return n # n._key == key if n._left is None and n._right is None: return None if n._left is None: n = treap_rotate_left(n) elif n._right is None: n = treap_rotate_right(n) else: # n._left is not None and n._right is not None if n._left._priority < n._right._priority: n = treap_rotate_right(n) else: n = treap_rotate_left(n) return treap_delete(n, key) def treap_size(n): if n is None: return 0 return 1 + treap_size(n._left) + treap_size(n._right) def treap_str(n): if n is None: return "" result = [] if n._left is not None: result.append(treap_str(n._left)) if n.value is None: result.append("%d" % (n.key)) else: result.append("%d:%d" % (n.key, n.value)) if n._right is not None: result.append(treap_str(n._right)) return ' '.join(result) def treap_min(n): if n is None: raise Exception('no nodes') if n._left is None: return n.key else: return treap_min(n._left) def treap_max(n): if n is None: raise Exception('no nodes') if n._right is None: return n.key else: return treap_max(n._right) class Treap: def __init__(self): self._root = None self._size = 0 self._min = None self._max = None def find(self, key): return treap_find(self._root, key) def lower_bound(self, key): return treap_lower_bound(self._root, key) def insert(self, key, value=None): self._root = treap_insert(self._root, key, value) self._size += 1 if self._size == 1: self._min = key self._max = key else: if self._min is not None: self._min = min(self._min, key) if self._max is not None: self._max = max(self._max, key) def delete(self, key): self._root = treap_delete(self._root, key) self._size -= 1 if self._size == 0: self._min = None self._max = None else: if self._min == key: self._min = None if self._max == key: self._max = None def __len__(self): return self._size def __str__(self): return treap_str(self._root) def min(self): if self._min is None: self._min = treap_min(self._root) return self._min def max(self): if self._max is None: self._max = treap_max(self._root) return self._max H, W = map(int, readline().split()) candidates = Treap() moves = Treap() for i in range(W): candidates.insert(i, i) moves.insert(0, W) result = [] for i in range(H): A, B = map(int, readline().split()) A -= 1 r = -1 while True: n = candidates.lower_bound(A) if n is None or n.key > B: break r = max(r, n.value) t = moves.find(n.key - n.value) moves.delete(t.key) if t.value != 1: moves.insert(t.key, t.value - 1) candidates.delete(n.key) if r != -1 and B != W: t = B - r n = moves.find(t) if n is None: moves.insert(t, 1) else: moves.delete(n.key) moves.insert(n.key, n.value + 1) candidates.insert(B, r) if len(moves) == 0: result.append(-1) else: result.append(moves.min() + i + 1) print(*result, sep='\n') ```
instruction
0
83,960
15
167,920
No
output
1
83,960
15
167,921
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a grid of squares with H+1 horizontal rows and W vertical columns. You will start at one of the squares in the top row and repeat moving one square right or down. However, for each integer i from 1 through H, you cannot move down from the A_i-th, (A_i + 1)-th, \ldots, B_i-th squares from the left in the i-th row from the top. For each integer k from 1 through H, find the minimum number of moves needed to reach one of the squares in the (k+1)-th row from the top. (The starting square can be chosen individually for each case.) If, starting from any square in the top row, none of the squares in the (k+1)-th row can be reached, print `-1` instead. Constraints * 1 \leq H,W \leq 2\times 10^5 * 1 \leq A_i \leq B_i \leq W Input Input is given from Standard Input in the following format: H W A_1 B_1 A_2 B_2 : A_H B_H Output Print H lines. The i-th line should contain the answer for the case k=i. Example Input 4 4 2 4 1 1 2 3 2 4 Output 1 3 6 -1 Submitted Solution: ``` import sys input = sys.stdin.readline import time time0=time.time() import random H,W=map(int,input().split()) D=[tuple(map(int,input().split())) for i in range(H)] ANS=[1<<30]*H def start(NOW): SCORE=0 for i in range(H): if D[i][0]<=NOW<=D[i][1]: SCORE+=D[i][1]+1-NOW+1 NOW=D[i][1]+1 else: SCORE+=1 if NOW==W+1: return if ANS[i]>SCORE: ANS[i]=SCORE #else: # return start(1) start(W) while time.time()-time0<1.8: start(random.randint(1,W)) for a in ANS: if a!=1<<30: print(a) else: print(-1) ```
instruction
0
83,961
15
167,922
No
output
1
83,961
15
167,923
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a grid of squares with H+1 horizontal rows and W vertical columns. You will start at one of the squares in the top row and repeat moving one square right or down. However, for each integer i from 1 through H, you cannot move down from the A_i-th, (A_i + 1)-th, \ldots, B_i-th squares from the left in the i-th row from the top. For each integer k from 1 through H, find the minimum number of moves needed to reach one of the squares in the (k+1)-th row from the top. (The starting square can be chosen individually for each case.) If, starting from any square in the top row, none of the squares in the (k+1)-th row can be reached, print `-1` instead. Constraints * 1 \leq H,W \leq 2\times 10^5 * 1 \leq A_i \leq B_i \leq W Input Input is given from Standard Input in the following format: H W A_1 B_1 A_2 B_2 : A_H B_H Output Print H lines. The i-th line should contain the answer for the case k=i. Example Input 4 4 2 4 1 1 2 3 2 4 Output 1 3 6 -1 Submitted Solution: ``` import numpy as np from numba import jit INF = 10**6 H, W = list(map(int, input().split())) A, B = np.zeros(H+2), np.zeros(H+2) for i in range(1, H+1): A[i], B[i] = list(map(int, input().split())) pos = np.array(range(1, W+1)) init = np.array(range(1, W+1)) @jit(nopython=True) def nxt(pos, a, b): lft = np.searchsorted(pos, a, side='left') rgt = np.searchsorted(pos, b, side='right') if b == W: n = INF else: n = b+1 pos[lft:rgt] = n return(np.min(pos-init)) for h in range(1, H+1): s = nxt(pos, A[h], B[h]) if (pos[0]==INF): print (-1) else: print(s+h) ```
instruction
0
83,962
15
167,924
No
output
1
83,962
15
167,925
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a grid of squares with H+1 horizontal rows and W vertical columns. You will start at one of the squares in the top row and repeat moving one square right or down. However, for each integer i from 1 through H, you cannot move down from the A_i-th, (A_i + 1)-th, \ldots, B_i-th squares from the left in the i-th row from the top. For each integer k from 1 through H, find the minimum number of moves needed to reach one of the squares in the (k+1)-th row from the top. (The starting square can be chosen individually for each case.) If, starting from any square in the top row, none of the squares in the (k+1)-th row can be reached, print `-1` instead. Constraints * 1 \leq H,W \leq 2\times 10^5 * 1 \leq A_i \leq B_i \leq W Input Input is given from Standard Input in the following format: H W A_1 B_1 A_2 B_2 : A_H B_H Output Print H lines. The i-th line should contain the answer for the case k=i. Example Input 4 4 2 4 1 1 2 3 2 4 Output 1 3 6 -1 Submitted Solution: ``` H,W=map(int,input().split()) AB=[tuple(map(int,input().split())) for _ in range(H)] ans=[0] pos=0 for i in range(H): if AB[i][0]-1 > pos: ans.append(ans[-1]+1) continue if AB[i][1]==W: ans.extend([-1]*(H-i)) break ans.append(ans[-1]+AB[i][1]-1-pos+2) pos = AB[i][1] print(*ans[1:]) ```
instruction
0
83,963
15
167,926
No
output
1
83,963
15
167,927
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a rectangular grid with n rows and m columns. The cell located on the i-th row from the top and the j-th column from the left has a value a_{ij} written in it. You can perform the following operation any number of times (possibly zero): * Choose any two adjacent cells and multiply the values in them by -1. Two cells are called adjacent if they share a side. Note that you can use a cell more than once in different operations. You are interested in X, the sum of all the numbers in the grid. What is the maximum X you can achieve with these operations? Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100). Description of the test cases follows. The first line of each test case contains two integers n,m (2 ≤ n, m ≤ 10). The following n lines contain m integers each, the j-th element in the i-th line is a_{ij} (-100≤ a_{ij}≤ 100). Output For each testcase, print one integer X, the maximum possible sum of all the values in the grid after applying the operation as many times as you want. Example Input 2 2 2 -1 1 1 1 3 4 0 -1 -2 -3 -1 -2 -3 -4 -2 -3 -4 -5 Output 2 30 Note In the first test case, there will always be at least one -1, so the answer is 2. In the second test case, we can use the operation six times to elements adjacent horizontally and get all numbers to be non-negative. So the answer is: 2× 1 + 3×2 + 3× 3 + 2× 4 + 1× 5 = 30.
instruction
0
84,429
15
168,858
Tags: greedy, math Correct Solution: ``` t = int(input()) for _ in range(t): a = [] k = 0 n, m = map(int,input().split()) for _ in range(n): s = list(map(int,input().split())) a += s for i in range(n*m): if a[i] < 0: k += 1 a[i] *= -1 if k%2==0: print(sum(a)) else: print(sum(a)- 2*min(a)) ```
output
1
84,429
15
168,859
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a rectangular grid with n rows and m columns. The cell located on the i-th row from the top and the j-th column from the left has a value a_{ij} written in it. You can perform the following operation any number of times (possibly zero): * Choose any two adjacent cells and multiply the values in them by -1. Two cells are called adjacent if they share a side. Note that you can use a cell more than once in different operations. You are interested in X, the sum of all the numbers in the grid. What is the maximum X you can achieve with these operations? Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100). Description of the test cases follows. The first line of each test case contains two integers n,m (2 ≤ n, m ≤ 10). The following n lines contain m integers each, the j-th element in the i-th line is a_{ij} (-100≤ a_{ij}≤ 100). Output For each testcase, print one integer X, the maximum possible sum of all the values in the grid after applying the operation as many times as you want. Example Input 2 2 2 -1 1 1 1 3 4 0 -1 -2 -3 -1 -2 -3 -4 -2 -3 -4 -5 Output 2 30 Note In the first test case, there will always be at least one -1, so the answer is 2. In the second test case, we can use the operation six times to elements adjacent horizontally and get all numbers to be non-negative. So the answer is: 2× 1 + 3×2 + 3× 3 + 2× 4 + 1× 5 = 30.
instruction
0
84,432
15
168,864
Tags: greedy, math Correct Solution: ``` for i in range(int(input())): n,m=map(int,input().split()) l,k=[],0 for i in range(n): l+=[*map(int,input().split())] for i in range(n*m): if l[i]<0:k+=1;l[i]*=-1 print(sum(l)-k%2*min(l)*2) ```
output
1
84,432
15
168,865
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a rectangular grid with n rows and m columns. The cell located on the i-th row from the top and the j-th column from the left has a value a_{ij} written in it. You can perform the following operation any number of times (possibly zero): * Choose any two adjacent cells and multiply the values in them by -1. Two cells are called adjacent if they share a side. Note that you can use a cell more than once in different operations. You are interested in X, the sum of all the numbers in the grid. What is the maximum X you can achieve with these operations? Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100). Description of the test cases follows. The first line of each test case contains two integers n,m (2 ≤ n, m ≤ 10). The following n lines contain m integers each, the j-th element in the i-th line is a_{ij} (-100≤ a_{ij}≤ 100). Output For each testcase, print one integer X, the maximum possible sum of all the values in the grid after applying the operation as many times as you want. Example Input 2 2 2 -1 1 1 1 3 4 0 -1 -2 -3 -1 -2 -3 -4 -2 -3 -4 -5 Output 2 30 Note In the first test case, there will always be at least one -1, so the answer is 2. In the second test case, we can use the operation six times to elements adjacent horizontally and get all numbers to be non-negative. So the answer is: 2× 1 + 3×2 + 3× 3 + 2× 4 + 1× 5 = 30.
instruction
0
84,433
15
168,866
Tags: greedy, math Correct Solution: ``` t = int(input()) for _ in range(t): nm = list(map(int, input().split())) n = nm[0] numbers = [] for _ in range(n): data = list(map(int, input().split())) numbers += data neg = 0 zero = 0 for i in numbers: if i < 0: neg += 1 elif i == 0: zero += 1 if neg % 2 == 0 or zero > 0: numbers = list(map(abs, numbers)) result = sum(numbers) else: numbers = list(map(abs, numbers)) minimum = min(numbers) result = sum(numbers) - 2 * minimum print(result) ```
output
1
84,433
15
168,867
Provide tags and a correct Python 3 solution for this coding contest problem. Our bear's forest has a checkered field. The checkered field is an n × n table, the rows are numbered from 1 to n from top to bottom, the columns are numbered from 1 to n from left to right. Let's denote a cell of the field on the intersection of row x and column y by record (x, y). Each cell of the field contains growing raspberry, at that, the cell (x, y) of the field contains x + y raspberry bushes. The bear came out to walk across the field. At the beginning of the walk his speed is (dx, dy). Then the bear spends exactly t seconds on the field. Each second the following takes place: * Let's suppose that at the current moment the bear is in cell (x, y). * First the bear eats the raspberry from all the bushes he has in the current cell. After the bear eats the raspberry from k bushes, he increases each component of his speed by k. In other words, if before eating the k bushes of raspberry his speed was (dx, dy), then after eating the berry his speed equals (dx + k, dy + k). * Let's denote the current speed of the bear (dx, dy) (it was increased after the previous step). Then the bear moves from cell (x, y) to cell (((x + dx - 1) mod n) + 1, ((y + dy - 1) mod n) + 1). * Then one additional raspberry bush grows in each cell of the field. You task is to predict the bear's actions. Find the cell he ends up in if he starts from cell (sx, sy). Assume that each bush has infinitely much raspberry and the bear will never eat all of it. Input The first line of the input contains six space-separated integers: n, sx, sy, dx, dy, t (1 ≤ n ≤ 109; 1 ≤ sx, sy ≤ n; - 100 ≤ dx, dy ≤ 100; 0 ≤ t ≤ 1018). Output Print two integers — the coordinates of the cell the bear will end up in after t seconds. Examples Input 5 1 2 0 1 2 Output 3 1 Input 1 1 1 -1 -1 2 Output 1 1 Note Operation a mod b means taking the remainder after dividing a by b. Note that the result of the operation is always non-negative. For example, ( - 1) mod 3 = 2. In the first sample before the first move the speed vector will equal (3,4) and the bear will get to cell (4,1). Before the second move the speed vector will equal (9,10) and he bear will get to cell (3,1). Don't forget that at the second move, the number of berry bushes increased by 1. In the second sample before the first move the speed vector will equal (1,1) and the bear will get to cell (1,1). Before the second move, the speed vector will equal (4,4) and the bear will get to cell (1,1). Don't forget that at the second move, the number of berry bushes increased by 1.
instruction
0
84,549
15
169,098
Tags: math, matrices Correct Solution: ``` #Simple non-optimized class of matrices. Used with small dense matrices. import functools import itertools import math class NotAMatrixError(Exception): pass class MatrixSizeError(Exception): def __init__(self, s1, s2): print('sizes do not match : ', s1, ', ', s2) class NotSquareError(Exception): pass class Matrix(list): def __init__(self, L): if type(L) == type(self): self = L return n = len(L) m = len(L[0]) for i in range(n): if len(L[i]) != m: raise NotAMatrixError() list.__init__(self, L) self.n = n self.m = m self.degrees = [] def check_size(self, M, mode): n, m = len(M), len(M[0]) for i in range(n): if len(M[i]) != m: raise NotAMatrixError() if mode == 'add' and (self.n != n or self.m != m): raise MatrixSizeError((self.n, self.m), (n,m)) if mode == 'lul' and self.m != n: print(self.m, n, self.m != n) raise MatrixSizeError((self.n, self.m), (n,m)) def __add__(self, M): self.check_size(M, mode = 'add') return Matrix([[self[i][j]+M[i][j] for j in range(self.m)]for i in range(self.n)]) def __iadd__(self, M): self.check_size(M, mode = 'add') for i in range(self.n): for j in range(self,m): self[i][j] += M[i][j] def __mul__(self, M): self.check_size(M, mode = 'mul') l = len(M[0]) return Matrix([[sum(self[i][k]*M[k][j] for k in range(self.m)) for j in range(l)] for i in range(self.n)]) def issquare(self): return self.n == self.m def primary(self): if self.n != self.m: raise NotSquareError() return Matrix([[int(i==j) for j in range(self.m)] for i in range(self.n)]) def __pow__(self, n): if self.n != self.m: raise NotSquareError() if n == 0: return self.primary() elif n == 1: return self if len(self.degrees) == 0: self.degrees.append(self*self) for i in range(n.bit_length() - len(self.degrees) - 1): self.degrees.append(self.degrees[-1] * self.degrees[-1]) s = [(n>>i)&1 for i in range(1,n.bit_length())] res = functools.reduce(lambda x,y:x*y, itertools.compress(self.degrees, s)) return res*self if n%2 else res def drop_degrees(self): self.degrees.clear() class Remainder(int): def __new__(self, n, p): obj = int.__new__(self, n%p) obj.p = p return obj def __mul__(self, m): return Remainder(int.__mul__(self, m), self.p) def __add__(self, m): return Remainder(int.__add__(self, m), self.p) def __sub__(self, m): return Remainder(int.__sub__(self, m), self.p) def __rmul__(self, m): return Remainder(int.__rmul__(self, m), self.p) def __radd__(self, m): return Remainder(int.__radd__(self, m), self.p) def __rsub__(self, m): return Remainder(int.__rsub__(self, m), self.p) def __neg__(self): return Remainder(int.__neg__(self), self.p) def __pow__(self, m): return Remainder(int.__pow__(self, m, self.p), self.p) def solve(n, sx, sy, dx, dy, t): o, l, j = Remainder(0, n), Remainder(1, n), Remainder(2, n) N = [[j, l, l, o, l, o], [l, j, o, l, l, o], [l, l, l, o, l, o], [l, l, o, l, l, o], [o, o, o, o, l, l], [o, o, o, o, o, l]] M = Matrix(N) sx, sy, dx, dy = map(lambda x: Remainder(x, n), [sx, sy, dx, dy]) v = Matrix([[sx], [sy], [dx], [dy], [o], [l]]) return M ** t * v n, sx, sy, dx, dy, t = [int(x) for x in input().split()] ans = solve(n, sx, sy, dx, dy, t) print(int(ans[0][0] - 1) + 1, int(ans[1][0] - 1) + 1) ```
output
1
84,549
15
169,099
Provide tags and a correct Python 3 solution for this coding contest problem. Our bear's forest has a checkered field. The checkered field is an n × n table, the rows are numbered from 1 to n from top to bottom, the columns are numbered from 1 to n from left to right. Let's denote a cell of the field on the intersection of row x and column y by record (x, y). Each cell of the field contains growing raspberry, at that, the cell (x, y) of the field contains x + y raspberry bushes. The bear came out to walk across the field. At the beginning of the walk his speed is (dx, dy). Then the bear spends exactly t seconds on the field. Each second the following takes place: * Let's suppose that at the current moment the bear is in cell (x, y). * First the bear eats the raspberry from all the bushes he has in the current cell. After the bear eats the raspberry from k bushes, he increases each component of his speed by k. In other words, if before eating the k bushes of raspberry his speed was (dx, dy), then after eating the berry his speed equals (dx + k, dy + k). * Let's denote the current speed of the bear (dx, dy) (it was increased after the previous step). Then the bear moves from cell (x, y) to cell (((x + dx - 1) mod n) + 1, ((y + dy - 1) mod n) + 1). * Then one additional raspberry bush grows in each cell of the field. You task is to predict the bear's actions. Find the cell he ends up in if he starts from cell (sx, sy). Assume that each bush has infinitely much raspberry and the bear will never eat all of it. Input The first line of the input contains six space-separated integers: n, sx, sy, dx, dy, t (1 ≤ n ≤ 109; 1 ≤ sx, sy ≤ n; - 100 ≤ dx, dy ≤ 100; 0 ≤ t ≤ 1018). Output Print two integers — the coordinates of the cell the bear will end up in after t seconds. Examples Input 5 1 2 0 1 2 Output 3 1 Input 1 1 1 -1 -1 2 Output 1 1 Note Operation a mod b means taking the remainder after dividing a by b. Note that the result of the operation is always non-negative. For example, ( - 1) mod 3 = 2. In the first sample before the first move the speed vector will equal (3,4) and the bear will get to cell (4,1). Before the second move the speed vector will equal (9,10) and he bear will get to cell (3,1). Don't forget that at the second move, the number of berry bushes increased by 1. In the second sample before the first move the speed vector will equal (1,1) and the bear will get to cell (1,1). Before the second move, the speed vector will equal (4,4) and the bear will get to cell (1,1). Don't forget that at the second move, the number of berry bushes increased by 1.
instruction
0
84,550
15
169,100
Tags: math, matrices Correct Solution: ``` mod, sx, sy, dx, dy, t = map(int, input().split()) class Matrix(): def __init__(self, n): self.n = n self.a = [[0] * n for _ in range(n)] def __mul__(self, b): res = Matrix(self.n) for i in range(self.n): for j in range(self.n): for k in range(self.n): res.a[i][j] += self.a[i][k] * b.a[k][j] % mod res.a[i][j] %= mod return res def __pow__(self, e): res = Matrix(self.n) for i in range(self.n): res.a[i][i] = 1 tmp = self while e: if e & 1: res = res * tmp e >>= 1 tmp = tmp * tmp return res M = Matrix(6) M.a = [[2, 1, 1, 0, 1, 2], [1, 2, 0, 1, 1, 2], [1, 1, 1, 0, 1, 2], [1, 1, 0, 1, 1, 2], [0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1]] sx -= 1 sy -= 1 r = M ** t f = lambda i: (r.a[i][0] * sx + r.a[i][1] * sy + r.a[i][2] * dx + r.a[i][3] * dy + r.a[i][5]) % mod + 1 print(f(0), f(1)) ```
output
1
84,550
15
169,101
Provide tags and a correct Python 3 solution for this coding contest problem. The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a bug — the robot didn't always walk the shortest path. Fortunately, the robot recorded its own movements correctly. Now Draude wants to find out when his robot functions wrong. Heh, if Draude only remembered the map of the field, where he tested the robot, he would easily say if the robot walked in the right direction or not. But the field map was lost never to be found, that's why he asks you to find out if there exist at least one map, where the path recorded by the robot is the shortest. The map is an infinite checkered field, where each square is either empty, or contains an obstruction. It is also known that the robot never tries to run into the obstruction. By the recorded robot's movements find out if there exist at least one such map, that it is possible to choose for the robot a starting square (the starting square should be empty) such that when the robot moves from this square its movements coincide with the recorded ones (the robot doesn't run into anything, moving along empty squares only), and the path from the starting square to the end one is the shortest. In one movement the robot can move into the square (providing there are no obstrutions in this square) that has common sides with the square the robot is currently in. Input The first line of the input file contains the recording of the robot's movements. This recording is a non-empty string, consisting of uppercase Latin letters L, R, U and D, standing for movements left, right, up and down respectively. The length of the string does not exceed 100. Output In the first line output the only word OK (if the above described map exists), or BUG (if such a map does not exist). Examples Input LLUUUR Output OK Input RRUULLDD Output BUG
instruction
0
84,734
15
169,468
Tags: constructive algorithms, graphs, implementation Correct Solution: ``` def main(): path = input() coordinate = [[0 for i in range(2)] for j in range(len(path)+1)] coordinate[0] = [0,0] left = 0 right = 0 up = 0 down = 0 # start = False for direction in path: if direction == 'U': up += 1 elif direction == 'R': right += 1 elif direction == 'D': down += 1 elif direction == 'L': left += 1 allDirections = [left,up,down,right] while 0 in allDirections: allDirections.remove(0) if len(allDirections) >= 3: minDirection = min(allDirections) i = minDirection + 1 repeatingSequences = [] while i < len(path): currentSet = set(path[i-minDirection - 1:i]) if len(currentSet) == 1: repeatingSequences.append(path[i]) i += minDirection + 1 # start = True else: i += 1 # if start: # break if len(set(repeatingSequences)) == 3: print('BUG') return for i in range(2,len(path)): if path[i] != path[i-1] and path[i] != path[i-2] and path[i-1] != path[i-2]: print('BUG') return for i in range(0,len(path)): if i == 0: if path[i] == 'U': coordinate[i + 1][0] = 0 coordinate[i + 1][1] = 1 elif path[i] == 'R': coordinate[i + 1][0] = 1 coordinate[i + 1][1] = 0 elif path[i] == 'D': coordinate[i + 1][0] = 0 coordinate[i + 1][1] = -1 elif path[i] == 'L': coordinate[i + 1][0] = -1 coordinate[i + 1][1] = 0 else: if path[i] == 'U': coordinate[i + 1][0] = coordinate[i][0] coordinate[i + 1][1] += 1 + coordinate[i][1] elif path[i] == 'R': coordinate[i + 1][1] = coordinate[i][1] coordinate[i + 1][0] += 1 + coordinate[i][0] elif path[i] == 'D': coordinate[i + 1][0] = coordinate[i][0] coordinate[i + 1][1] += -1 + coordinate[i][1] elif path[i] == 'L': coordinate[i + 1][1] = coordinate[i][1] coordinate[i + 1][0] += -1 + coordinate[i][0] coordinateSet = list(set(map(tuple,coordinate))) if len(coordinate) == len(coordinateSet): print('OK') else: print('BUG') main() ```
output
1
84,734
15
169,469
Provide tags and a correct Python 3 solution for this coding contest problem. The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a bug — the robot didn't always walk the shortest path. Fortunately, the robot recorded its own movements correctly. Now Draude wants to find out when his robot functions wrong. Heh, if Draude only remembered the map of the field, where he tested the robot, he would easily say if the robot walked in the right direction or not. But the field map was lost never to be found, that's why he asks you to find out if there exist at least one map, where the path recorded by the robot is the shortest. The map is an infinite checkered field, where each square is either empty, or contains an obstruction. It is also known that the robot never tries to run into the obstruction. By the recorded robot's movements find out if there exist at least one such map, that it is possible to choose for the robot a starting square (the starting square should be empty) such that when the robot moves from this square its movements coincide with the recorded ones (the robot doesn't run into anything, moving along empty squares only), and the path from the starting square to the end one is the shortest. In one movement the robot can move into the square (providing there are no obstrutions in this square) that has common sides with the square the robot is currently in. Input The first line of the input file contains the recording of the robot's movements. This recording is a non-empty string, consisting of uppercase Latin letters L, R, U and D, standing for movements left, right, up and down respectively. The length of the string does not exceed 100. Output In the first line output the only word OK (if the above described map exists), or BUG (if such a map does not exist). Examples Input LLUUUR Output OK Input RRUULLDD Output BUG
instruction
0
84,735
15
169,470
Tags: constructive algorithms, graphs, implementation Correct Solution: ``` s=input() a=set() a.add((0,0)) x=0 y=0 dx=[-1,0,1,0,0] dy=[0,1,0,-1,0] d={'L':0,'U':1,'R':2,'D':3} b=False for i in s: x+=dx[d[i]] y+=dy[d[i]] c=0 for j in range(5): if (x+dx[j],y+dy[j]) in a: c+=1 if c>1: b=True break a.add((x,y)) print(['OK','BUG'][b]) ```
output
1
84,735
15
169,471
Provide tags and a correct Python 3 solution for this coding contest problem. The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a bug — the robot didn't always walk the shortest path. Fortunately, the robot recorded its own movements correctly. Now Draude wants to find out when his robot functions wrong. Heh, if Draude only remembered the map of the field, where he tested the robot, he would easily say if the robot walked in the right direction or not. But the field map was lost never to be found, that's why he asks you to find out if there exist at least one map, where the path recorded by the robot is the shortest. The map is an infinite checkered field, where each square is either empty, or contains an obstruction. It is also known that the robot never tries to run into the obstruction. By the recorded robot's movements find out if there exist at least one such map, that it is possible to choose for the robot a starting square (the starting square should be empty) such that when the robot moves from this square its movements coincide with the recorded ones (the robot doesn't run into anything, moving along empty squares only), and the path from the starting square to the end one is the shortest. In one movement the robot can move into the square (providing there are no obstrutions in this square) that has common sides with the square the robot is currently in. Input The first line of the input file contains the recording of the robot's movements. This recording is a non-empty string, consisting of uppercase Latin letters L, R, U and D, standing for movements left, right, up and down respectively. The length of the string does not exceed 100. Output In the first line output the only word OK (if the above described map exists), or BUG (if such a map does not exist). Examples Input LLUUUR Output OK Input RRUULLDD Output BUG
instruction
0
84,736
15
169,472
Tags: constructive algorithms, graphs, implementation Correct Solution: ``` #!/usr/bin/env python ''' ' Author: Cheng-Shih Wong ' Email: mob5566@gmail.com ' Date: 2017-08-07 ''' def main(): walk = { 'L': (0, -1), 'U': (-1, 0), 'R': (0, +1), 'D': (+1, 0) } back = { 'L': 'R', 'R': 'L', 'U': 'D', 'D': 'U' } def update(pos, d): return ( pos[0]+walk[d][0], pos[1]+walk[d][1] ) def check(path): vis = set() pos = (0, 0) vis.add(pos) for c in path: pos = update(pos, c) if pos in vis: return False for nei in 'LURD': if nei != back[c] and update(pos, nei) in vis: return False vis.add(pos) return True path = input() print('OK' if check(path) else 'BUG') if __name__ == '__main__': main() ```
output
1
84,736
15
169,473
Provide tags and a correct Python 3 solution for this coding contest problem. The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a bug — the robot didn't always walk the shortest path. Fortunately, the robot recorded its own movements correctly. Now Draude wants to find out when his robot functions wrong. Heh, if Draude only remembered the map of the field, where he tested the robot, he would easily say if the robot walked in the right direction or not. But the field map was lost never to be found, that's why he asks you to find out if there exist at least one map, where the path recorded by the robot is the shortest. The map is an infinite checkered field, where each square is either empty, or contains an obstruction. It is also known that the robot never tries to run into the obstruction. By the recorded robot's movements find out if there exist at least one such map, that it is possible to choose for the robot a starting square (the starting square should be empty) such that when the robot moves from this square its movements coincide with the recorded ones (the robot doesn't run into anything, moving along empty squares only), and the path from the starting square to the end one is the shortest. In one movement the robot can move into the square (providing there are no obstrutions in this square) that has common sides with the square the robot is currently in. Input The first line of the input file contains the recording of the robot's movements. This recording is a non-empty string, consisting of uppercase Latin letters L, R, U and D, standing for movements left, right, up and down respectively. The length of the string does not exceed 100. Output In the first line output the only word OK (if the above described map exists), or BUG (if such a map does not exist). Examples Input LLUUUR Output OK Input RRUULLDD Output BUG
instruction
0
84,737
15
169,474
Tags: constructive algorithms, graphs, implementation Correct Solution: ``` s = input() x, y = 0, 0 visited = set() visited.add((x, y)) for i in range(len(s)): prev = x, y if s[i] == 'U': y += 1 elif s[i] == 'D': y -= 1 elif s[i] == 'R': x += 1 else: x -= 1 if (x, y) in visited: print("BUG") exit() neighbors = [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)] for n in neighbors: if n != prev and n in visited: print("BUG") exit() visited.add((x, y)) print("OK") ```
output
1
84,737
15
169,475
Provide tags and a correct Python 3 solution for this coding contest problem. The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a bug — the robot didn't always walk the shortest path. Fortunately, the robot recorded its own movements correctly. Now Draude wants to find out when his robot functions wrong. Heh, if Draude only remembered the map of the field, where he tested the robot, he would easily say if the robot walked in the right direction or not. But the field map was lost never to be found, that's why he asks you to find out if there exist at least one map, where the path recorded by the robot is the shortest. The map is an infinite checkered field, where each square is either empty, or contains an obstruction. It is also known that the robot never tries to run into the obstruction. By the recorded robot's movements find out if there exist at least one such map, that it is possible to choose for the robot a starting square (the starting square should be empty) such that when the robot moves from this square its movements coincide with the recorded ones (the robot doesn't run into anything, moving along empty squares only), and the path from the starting square to the end one is the shortest. In one movement the robot can move into the square (providing there are no obstrutions in this square) that has common sides with the square the robot is currently in. Input The first line of the input file contains the recording of the robot's movements. This recording is a non-empty string, consisting of uppercase Latin letters L, R, U and D, standing for movements left, right, up and down respectively. The length of the string does not exceed 100. Output In the first line output the only word OK (if the above described map exists), or BUG (if such a map does not exist). Examples Input LLUUUR Output OK Input RRUULLDD Output BUG
instruction
0
84,738
15
169,476
Tags: constructive algorithms, graphs, implementation Correct Solution: ``` import sys moves = sys.stdin.readline() grid = [] for i in range(500): grid.append([]) for j in range(500): grid[i].append(0) curx, cury = 250, 250 for move in moves: if grid[curx][cury] != 0: print("BUG") sys.exit(0) grid[curx][cury] = 1 if move == 'R': grid[curx][cury+1] = 1 grid[curx-1][cury] = 1 grid[curx][cury-1] = 1 curx += 1 if move == 'L': grid[curx][cury+1] = 1 grid[curx+1][cury] = 1 grid[curx][cury-1] = 1 curx -= 1 if move == 'U': grid[curx+1][cury] = 1 grid[curx-1][cury] = 1 grid[curx][cury-1] = 1 cury += 1 if move == 'D': grid[curx+1][cury] = 1 grid[curx-1][cury] = 1 grid[curx][cury+1] = 1 cury -= 1 print("OK") ```
output
1
84,738
15
169,477
Provide tags and a correct Python 3 solution for this coding contest problem. The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a bug — the robot didn't always walk the shortest path. Fortunately, the robot recorded its own movements correctly. Now Draude wants to find out when his robot functions wrong. Heh, if Draude only remembered the map of the field, where he tested the robot, he would easily say if the robot walked in the right direction or not. But the field map was lost never to be found, that's why he asks you to find out if there exist at least one map, where the path recorded by the robot is the shortest. The map is an infinite checkered field, where each square is either empty, or contains an obstruction. It is also known that the robot never tries to run into the obstruction. By the recorded robot's movements find out if there exist at least one such map, that it is possible to choose for the robot a starting square (the starting square should be empty) such that when the robot moves from this square its movements coincide with the recorded ones (the robot doesn't run into anything, moving along empty squares only), and the path from the starting square to the end one is the shortest. In one movement the robot can move into the square (providing there are no obstrutions in this square) that has common sides with the square the robot is currently in. Input The first line of the input file contains the recording of the robot's movements. This recording is a non-empty string, consisting of uppercase Latin letters L, R, U and D, standing for movements left, right, up and down respectively. The length of the string does not exceed 100. Output In the first line output the only word OK (if the above described map exists), or BUG (if such a map does not exist). Examples Input LLUUUR Output OK Input RRUULLDD Output BUG
instruction
0
84,739
15
169,478
Tags: constructive algorithms, graphs, implementation Correct Solution: ``` import math,sys,bisect,heapq from collections import defaultdict,Counter,deque from itertools import groupby,accumulate #sys.setrecursionlimit(200000000) int1 = lambda x: int(x) - 1 #def input(): return sys.stdin.readline().strip() input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__ ilele = lambda: map(int,input().split()) alele = lambda: list(map(int, input().split())) ilelec = lambda: map(int1,input().split()) alelec = lambda: list(map(int1, input().split())) def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] #MOD = 1000000000 + 7 def Y(c): print(["NO","YES"][c]) def y(c): print(["no","yes"][c]) def Yy(c): print(["No","Yes"][c]) A = [(0,0)] S = input() if len(S) == 1: print('OK') exit(0) def check(A,B): x,y = B #print(x,y,A,A[:-1]) if len(A) >= 2: for i,j in A[:-1]: if (x,y) in [(i+1,j),(i-1,j),(i,j-1),(i,j+1)]: return True return False x,y = 0,0 for i in S: #print(x,y) if i == 'L': x-=1 elif i == 'R': x+=1 elif i == 'U': y+=1 else: y-=1 if (x,y) in A: print('BUG') exit(0) if check(A,(x,y)): print('BUG') exit(0) A.append((x,y)) #print(A) print('OK') ```
output
1
84,739
15
169,479
Provide tags and a correct Python 3 solution for this coding contest problem. The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a bug — the robot didn't always walk the shortest path. Fortunately, the robot recorded its own movements correctly. Now Draude wants to find out when his robot functions wrong. Heh, if Draude only remembered the map of the field, where he tested the robot, he would easily say if the robot walked in the right direction or not. But the field map was lost never to be found, that's why he asks you to find out if there exist at least one map, where the path recorded by the robot is the shortest. The map is an infinite checkered field, where each square is either empty, or contains an obstruction. It is also known that the robot never tries to run into the obstruction. By the recorded robot's movements find out if there exist at least one such map, that it is possible to choose for the robot a starting square (the starting square should be empty) such that when the robot moves from this square its movements coincide with the recorded ones (the robot doesn't run into anything, moving along empty squares only), and the path from the starting square to the end one is the shortest. In one movement the robot can move into the square (providing there are no obstrutions in this square) that has common sides with the square the robot is currently in. Input The first line of the input file contains the recording of the robot's movements. This recording is a non-empty string, consisting of uppercase Latin letters L, R, U and D, standing for movements left, right, up and down respectively. The length of the string does not exceed 100. Output In the first line output the only word OK (if the above described map exists), or BUG (if such a map does not exist). Examples Input LLUUUR Output OK Input RRUULLDD Output BUG
instruction
0
84,740
15
169,480
Tags: constructive algorithms, graphs, implementation Correct Solution: ``` # maa chudaaye duniya d = [[0,1], [0, -1], [1, 0], [-1, 0], [0, 0]] path = input() vis = [] cur = [0, 0] f = True for p in path: prev = cur if p == 'L': index = 0 elif p == 'R' : index = 1 elif p == 'U' : index = 2 else: index = 3 cur = [cur[0] + d[index][0], cur[1] + d[index][1]] if cur in vis: f = False print('BUG') break for dx, dy in d: vis.append([prev[0] + dx, prev[1] + dy]) if f: print('OK') ```
output
1
84,740
15
169,481
Provide tags and a correct Python 3 solution for this coding contest problem. The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a bug — the robot didn't always walk the shortest path. Fortunately, the robot recorded its own movements correctly. Now Draude wants to find out when his robot functions wrong. Heh, if Draude only remembered the map of the field, where he tested the robot, he would easily say if the robot walked in the right direction or not. But the field map was lost never to be found, that's why he asks you to find out if there exist at least one map, where the path recorded by the robot is the shortest. The map is an infinite checkered field, where each square is either empty, or contains an obstruction. It is also known that the robot never tries to run into the obstruction. By the recorded robot's movements find out if there exist at least one such map, that it is possible to choose for the robot a starting square (the starting square should be empty) such that when the robot moves from this square its movements coincide with the recorded ones (the robot doesn't run into anything, moving along empty squares only), and the path from the starting square to the end one is the shortest. In one movement the robot can move into the square (providing there are no obstrutions in this square) that has common sides with the square the robot is currently in. Input The first line of the input file contains the recording of the robot's movements. This recording is a non-empty string, consisting of uppercase Latin letters L, R, U and D, standing for movements left, right, up and down respectively. The length of the string does not exceed 100. Output In the first line output the only word OK (if the above described map exists), or BUG (if such a map does not exist). Examples Input LLUUUR Output OK Input RRUULLDD Output BUG
instruction
0
84,741
15
169,482
Tags: constructive algorithms, graphs, implementation Correct Solution: ``` # import numpy as np s=input() # g=np.zeros((206,206),dtype=int) g=[[0 for i in range(206)] for j in range(206)] x=102 y=102 s=s+'0' i=0 while s[i]: g[x][y]=1 if s[i]=='L': x-=1 elif s[i]=='R': x+=1 elif s[i]=='U': y+=1 elif s[i]=='D': y-=1 if (g[x][y]+g[x-1][y]+g[x+1][y]+g[x][y-1]+g[x][y+1])>1: break i+=1 if s[i]!='0': print('BUG') else: print('OK') ```
output
1
84,741
15
169,483
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a bug — the robot didn't always walk the shortest path. Fortunately, the robot recorded its own movements correctly. Now Draude wants to find out when his robot functions wrong. Heh, if Draude only remembered the map of the field, where he tested the robot, he would easily say if the robot walked in the right direction or not. But the field map was lost never to be found, that's why he asks you to find out if there exist at least one map, where the path recorded by the robot is the shortest. The map is an infinite checkered field, where each square is either empty, or contains an obstruction. It is also known that the robot never tries to run into the obstruction. By the recorded robot's movements find out if there exist at least one such map, that it is possible to choose for the robot a starting square (the starting square should be empty) such that when the robot moves from this square its movements coincide with the recorded ones (the robot doesn't run into anything, moving along empty squares only), and the path from the starting square to the end one is the shortest. In one movement the robot can move into the square (providing there are no obstrutions in this square) that has common sides with the square the robot is currently in. Input The first line of the input file contains the recording of the robot's movements. This recording is a non-empty string, consisting of uppercase Latin letters L, R, U and D, standing for movements left, right, up and down respectively. The length of the string does not exceed 100. Output In the first line output the only word OK (if the above described map exists), or BUG (if such a map does not exist). Examples Input LLUUUR Output OK Input RRUULLDD Output BUG Submitted Solution: ``` a = [] INF = 300 k = 300 for i in range(k): a.append([INF] * k) curx = k // 2 cury = k // 2 way = input() a[curx][cury] = 0 a[curx + 1][cury] = 1 a[curx - 1][cury] = 1 a[curx][cury + 1] = 1 a[curx][cury - 1] = 1 step = 0 for i in way: if i == 'L': curx -= 1 if i == 'U': cury += 1 if i == 'R': curx += 1 if i == 'D': cury -= 1 step += 1 if a[curx][cury] != step: print('BUG') exit(0) else: a[curx][cury] = min(step, a[curx][cury]) a[curx + 1][cury] = min(step + 1, a[curx + 1][cury]) a[curx - 1][cury] = min(step + 1, a[curx - 1][cury]) a[curx][cury + 1] = min(step + 1, a[curx][cury + 1]) a[curx][cury - 1] = min(step + 1, a[curx][cury - 1]) #for i in a: # for j in i: # print(j, end=' ') # print() print('OK') ```
instruction
0
84,743
15
169,486
Yes
output
1
84,743
15
169,487
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a bug — the robot didn't always walk the shortest path. Fortunately, the robot recorded its own movements correctly. Now Draude wants to find out when his robot functions wrong. Heh, if Draude only remembered the map of the field, where he tested the robot, he would easily say if the robot walked in the right direction or not. But the field map was lost never to be found, that's why he asks you to find out if there exist at least one map, where the path recorded by the robot is the shortest. The map is an infinite checkered field, where each square is either empty, or contains an obstruction. It is also known that the robot never tries to run into the obstruction. By the recorded robot's movements find out if there exist at least one such map, that it is possible to choose for the robot a starting square (the starting square should be empty) such that when the robot moves from this square its movements coincide with the recorded ones (the robot doesn't run into anything, moving along empty squares only), and the path from the starting square to the end one is the shortest. In one movement the robot can move into the square (providing there are no obstrutions in this square) that has common sides with the square the robot is currently in. Input The first line of the input file contains the recording of the robot's movements. This recording is a non-empty string, consisting of uppercase Latin letters L, R, U and D, standing for movements left, right, up and down respectively. The length of the string does not exceed 100. Output In the first line output the only word OK (if the above described map exists), or BUG (if such a map does not exist). Examples Input LLUUUR Output OK Input RRUULLDD Output BUG Submitted Solution: ``` at = (0, 0) p = [at] moves = input() funcs = { 'L': lambda _: (_[0] - 1, _[1]), 'R': lambda _: (_[0] + 1, _[1]), 'D': lambda _: (_[0], _[1] - 1), 'U': lambda _: (_[0], _[1] + 1), } for move in moves: at = funcs[move](at) p.append(at) ok = True for i in range(len(moves) + 1): for j in range(len(moves) + 1): if abs(i - j) > 1 and abs(p[i][0] - p[j][0]) + abs(p[i][1] - p[j][1]) < 2: ok = False print('OK' if ok else 'BUG') ```
instruction
0
84,744
15
169,488
Yes
output
1
84,744
15
169,489
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a bug — the robot didn't always walk the shortest path. Fortunately, the robot recorded its own movements correctly. Now Draude wants to find out when his robot functions wrong. Heh, if Draude only remembered the map of the field, where he tested the robot, he would easily say if the robot walked in the right direction or not. But the field map was lost never to be found, that's why he asks you to find out if there exist at least one map, where the path recorded by the robot is the shortest. The map is an infinite checkered field, where each square is either empty, or contains an obstruction. It is also known that the robot never tries to run into the obstruction. By the recorded robot's movements find out if there exist at least one such map, that it is possible to choose for the robot a starting square (the starting square should be empty) such that when the robot moves from this square its movements coincide with the recorded ones (the robot doesn't run into anything, moving along empty squares only), and the path from the starting square to the end one is the shortest. In one movement the robot can move into the square (providing there are no obstrutions in this square) that has common sides with the square the robot is currently in. Input The first line of the input file contains the recording of the robot's movements. This recording is a non-empty string, consisting of uppercase Latin letters L, R, U and D, standing for movements left, right, up and down respectively. The length of the string does not exceed 100. Output In the first line output the only word OK (if the above described map exists), or BUG (if such a map does not exist). Examples Input LLUUUR Output OK Input RRUULLDD Output BUG Submitted Solution: ``` def adjacent(move): return [move, (move[0],move[1]-1),(move[0],move[1]+1),(move[0]-1,move[1]),(move[0]+1,move[1])] moves = [(0,0)] inp = input() for move in inp: if move == "R": moves.append((moves[-1][0]+1,moves[-1][1])) elif move == "L": moves.append((moves[-1][0]-1,moves[-1][1])) elif move == "U": moves.append((moves[-1][0],moves[-1][1]+1)) elif move == "D": moves.append((moves[-1][0],moves[-1][1]-1)) goon = True for move in moves: poss = adjacent(move) for loc in poss: if loc in moves[moves.index(move)+2:]: print("BUG") goon = False break; if not goon: break; if goon: print("OK") ```
instruction
0
84,745
15
169,490
Yes
output
1
84,745
15
169,491
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a bug — the robot didn't always walk the shortest path. Fortunately, the robot recorded its own movements correctly. Now Draude wants to find out when his robot functions wrong. Heh, if Draude only remembered the map of the field, where he tested the robot, he would easily say if the robot walked in the right direction or not. But the field map was lost never to be found, that's why he asks you to find out if there exist at least one map, where the path recorded by the robot is the shortest. The map is an infinite checkered field, where each square is either empty, or contains an obstruction. It is also known that the robot never tries to run into the obstruction. By the recorded robot's movements find out if there exist at least one such map, that it is possible to choose for the robot a starting square (the starting square should be empty) such that when the robot moves from this square its movements coincide with the recorded ones (the robot doesn't run into anything, moving along empty squares only), and the path from the starting square to the end one is the shortest. In one movement the robot can move into the square (providing there are no obstrutions in this square) that has common sides with the square the robot is currently in. Input The first line of the input file contains the recording of the robot's movements. This recording is a non-empty string, consisting of uppercase Latin letters L, R, U and D, standing for movements left, right, up and down respectively. The length of the string does not exceed 100. Output In the first line output the only word OK (if the above described map exists), or BUG (if such a map does not exist). Examples Input LLUUUR Output OK Input RRUULLDD Output BUG Submitted Solution: ``` string = input() geo_map = [[0]*100 for i in range(100)] x = 50 y = 50 geo_map[x][y] = 1 optimal_check = 0 state = True for c in string: optimal_check = 0 if c == 'R': x += 1 elif c == 'L': x -= 1 elif c == 'U': y += 1 else: y -= 1 if geo_map[x][y] == 1: print('BUG') state = False break elif geo_map[x][y] != 1: geo_map[x][y] = 1 if geo_map[x+1][y] == 1: optimal_check += 1 if geo_map[x-1][y] == 1: optimal_check += 1 if geo_map[x][y+1] == 1: optimal_check += 1 if geo_map[x][y-1] == 0: optimal_check += 1 if optimal_check >= 2: print('BUG') state = False break if state: print('OK') ```
instruction
0
84,748
15
169,496
No
output
1
84,748
15
169,497
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a bug — the robot didn't always walk the shortest path. Fortunately, the robot recorded its own movements correctly. Now Draude wants to find out when his robot functions wrong. Heh, if Draude only remembered the map of the field, where he tested the robot, he would easily say if the robot walked in the right direction or not. But the field map was lost never to be found, that's why he asks you to find out if there exist at least one map, where the path recorded by the robot is the shortest. The map is an infinite checkered field, where each square is either empty, or contains an obstruction. It is also known that the robot never tries to run into the obstruction. By the recorded robot's movements find out if there exist at least one such map, that it is possible to choose for the robot a starting square (the starting square should be empty) such that when the robot moves from this square its movements coincide with the recorded ones (the robot doesn't run into anything, moving along empty squares only), and the path from the starting square to the end one is the shortest. In one movement the robot can move into the square (providing there are no obstrutions in this square) that has common sides with the square the robot is currently in. Input The first line of the input file contains the recording of the robot's movements. This recording is a non-empty string, consisting of uppercase Latin letters L, R, U and D, standing for movements left, right, up and down respectively. The length of the string does not exceed 100. Output In the first line output the only word OK (if the above described map exists), or BUG (if such a map does not exist). Examples Input LLUUUR Output OK Input RRUULLDD Output BUG Submitted Solution: ``` from collections import Counter a, b = 0, 0 c = Counter() string = input() for i in string: if c[a, b]: print("BUG") exit() if i == 'R': c[a - 1, b] += 1 c[a, b] += 1 c[a, b - 1] += 1 c[a, b + 1] += 1 a += 1 elif i == 'L': c[a, b] += 1 c[a + 1, b] += 1 c[a, b - 1] += 1 c[a, b + 1] += 1 a -= 1 elif i == 'U': c[a, b] += 1 c[a + 1, b] += 1 c[a - 1, b] += 1 c[a, b - 1] += 1 b += 1 elif i == 'D': c[a + 1, b] += 1 c[a - 1, b] += 1 c[a, b + 1] += 1 c[a, b] += 1 b -= 1 print("OK") ```
instruction
0
84,749
15
169,498
No
output
1
84,749
15
169,499
Provide a correct Python 3 solution for this coding contest problem. In your garden, there is a long and narrow flowerbed that stretches infinitely to the east. You have decided to plant N kinds of flowers in this empty flowerbed. For convenience, we will call these N kinds of flowers Flower 1, 2, …, N. Also, we will call the position that is p centimeters from the west end of the flowerbed Position p. You will plant Flower i (1 ≤ i ≤ N) as follows: first, plant one at Position w_i, then plant one every d_i centimeters endlessly toward the east. That is, Flower i will be planted at the positions w_i, w_i + d_i, w_i + 2 d_i, … Note that more than one flower may be planted at the same position. Find the position at which the K-th flower from the west is planted. If more than one flower is planted at the same position, they are counted individually. Constraints * 1 ≤ N ≤ 10^5 * 1 ≤ K ≤ 10^9 * 1 ≤ w_i ≤ 10^{18} * 1 ≤ d_i ≤ 10^9 * All input values are integers. Input Input is given from Standard Input in the following format: N K w_1 d_1 : w_N d_N Output When the K-th flower from the west is planted at Position X, print the value of X. (The westmost flower is counted as the 1-st flower.) Examples Input 2 6 20 10 25 15 Output 50 Input 3 9 10 10 10 10 10 10 Output 30 Input 1 1000000000 1000000000000000000 1000000000 Output 1999999999000000000
instruction
0
84,885
15
169,770
"Correct Solution: ``` from collections import defaultdict, deque, Counter from heapq import heappush, heappop, heapify import math import bisect import random from itertools import permutations, accumulate, combinations import sys import string from bisect import bisect_left, bisect_right from math import factorial, ceil, floor INF = float('inf') def LI(): return list(map(int, sys.stdin.readline().split())) def I(): return int(sys.stdin.readline()) def LIM(): return list(map(lambda x:int(x) - 1, sys.stdin.readline().split())) def LS(): return sys.stdin.readline().split() def S(): return sys.stdin.readline().strip() def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def LIRM(n): return [LIM() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] def SRL(n): return [list(S()) for i in range(n)] mod = 1000000007 n, k = LI() left = 0 right = 2 * 10 ** 18 L = LIR(n) while left <= right: mid = (left + right) // 2 flag = False ret = 0 for w, d in L: if w == mid: ret += 1 elif w < mid: ret += 1 ret += (mid - w) // d if ret >= k: flag = True right = mid - 1 else: flag = False left = mid + 1 if flag: print(mid) else: print(mid + 1) ```
output
1
84,885
15
169,771
Provide tags and a correct Python 3 solution for this coding contest problem. There are four stones on an infinite line in integer coordinates a_1, a_2, a_3, a_4. The goal is to have the stones in coordinates b_1, b_2, b_3, b_4. The order of the stones does not matter, that is, a stone from any position a_i can end up in at any position b_j, provided there is a required number of stones in each position (that is, if a coordinate x appears k times among numbers b_1, …, b_4, there should be exactly k stones at x in the end). We are allowed to move stones with the following operation: choose two stones at distinct positions x and y with at least one stone each, and move one stone from x to 2y - x. In other words, the operation moves a stone to a symmetric position relative to some other stone. At any moment it is allowed to have any number of stones at the same position. Find any sequence of operations that achieves the goal, or determine that it is impossible. The sequence does not have to be shortest, but it may contain at most 1000 operations. Input The first line contains four integers a_1, …, a_4 (-10^9 ≤ a_i ≤ 10^9) — initial coordinates of the stones. There may be multiple stones sharing the same coordinate. The second line contains four integers b_1, …, b_4 (-10^9 ≤ b_i ≤ 10^9) — target coordinates of the stones. There may be multiple targets sharing the same coordinate. Output If there is no sequence of operations that achieves the goal, print a single integer -1. Otherwise, on the first line print a single integer k (0 ≤ k ≤ 1000) — the number of operations in your sequence. On the next k lines, describe the operations. The i-th of these lines should contain two integers x_i and y_i (x_i ≠ y_i) — coordinates of the moved stone and the center of symmetry stone for the i-th operation. For each operation i, there should at least one stone in each of the coordinates x_i and y_i, and the resulting coordinate 2y_i - x_i must not exceed 10^{18} by absolute value. If there are multiple suitable sequences, print any of them. It is guaranteed that if there is a suitable sequence of operations, then there is also a suitable sequence that satisfies all the additional requirement. Examples Input 0 1 2 3 3 5 6 8 Output 3 1 3 2 5 0 3 Input 0 0 0 0 1 1 1 1 Output -1 Input 0 0 0 1 0 1 0 1 Output -1
instruction
0
85,117
15
170,234
Tags: constructive algorithms Correct Solution: ``` def gcd(a, b): while a and b: a %= b if a: b %= a return a + b def gcd2(A): r = A[1] - A[0] for i in (2, 3): r = gcd(r, A[i] - A[0]) return r def Mir(x, c): return c * 2 - x def Solve(A): A[0].sort() A[1].sort() gcds = [gcd2(A[0]), gcd2(A[1])] I0, I1 = 0, 1 if A[0][-1] - A[0][0] > A[1][-1] - A[1][0]: I0, I1 = I1, I0 if A[I1][-1] == A[I1][0]: if A[I1][0] == A[I0][0]: return [] return None elif A[I0][-1] == A[I0][0]: return None if gcds[0] != gcds[1]: return None if (A[0][0] - A[1][0]) % gcds[0] != 0: return None ops = [[], []] def Op(I, J1, JC): ops[I].append((A[I0][J1], A[I0][JC])) A[I0][J1] = Mir(A[I0][J1], A[I0][JC]) while True: for a in A: a.sort() if max(A[0][-1], A[1][-1]) - min(A[0][0], A[1][0]) <= gcds[0]: break #print('====now', A) gapL = abs(A[0][0] - A[1][0]) gapR = abs(A[0][-1] - A[1][-1]) if gapL > gapR: I0, I1 = (0, 1) if A[0][0] < A[1][0] else (1, 0) view = lambda x: x else: I0, I1 = (0, 1) if A[0][-1] > A[1][-1] else (1, 0) view = lambda x: 3 - x for a in A: a.sort(key=view) lim = max(view(A[I0][-1]), view(A[I1][-1])) B = [view(x) for x in A[I0]] actioned = False for J in (3, 2): if Mir(B[0], B[J]) <= lim: Op(I0, (0), (J)) actioned = True break if actioned: continue if Mir(B[0], B[1]) > lim: Op(I0, (3), (1)) continue if (B[1] - B[0]) * 8 >= lim - B[0]: Op(I0, (0), (1)) continue if (B[3] - B[2]) * 8 >= lim - B[0]: Op(I0, (0), (2)) Op(I0, (0), (3)) continue if B[1] - B[0] < B[3] - B[2]: Op(I0, (1), (2)) Op(I0, (1), (3)) else: Op(I0, (2), (1)) Op(I0, (2), (0)) Op(I0, (0), (1)) if A[0] != A[1]: return None return ops[0] + [(Mir(x, c), c) for x, c in reversed(ops[1])] def Output(ops): if ops is None: print(-1) return print(len(ops)) for x, c in ops: print(x, c) import sys A = [list(map(int, sys.stdin.readline().split())) for _ in range(2)] Output(Solve(A)) ```
output
1
85,117
15
170,235
Provide tags and a correct Python 3 solution for this coding contest problem. There are four stones on an infinite line in integer coordinates a_1, a_2, a_3, a_4. The goal is to have the stones in coordinates b_1, b_2, b_3, b_4. The order of the stones does not matter, that is, a stone from any position a_i can end up in at any position b_j, provided there is a required number of stones in each position (that is, if a coordinate x appears k times among numbers b_1, …, b_4, there should be exactly k stones at x in the end). We are allowed to move stones with the following operation: choose two stones at distinct positions x and y with at least one stone each, and move one stone from x to 2y - x. In other words, the operation moves a stone to a symmetric position relative to some other stone. At any moment it is allowed to have any number of stones at the same position. Find any sequence of operations that achieves the goal, or determine that it is impossible. The sequence does not have to be shortest, but it may contain at most 1000 operations. Input The first line contains four integers a_1, …, a_4 (-10^9 ≤ a_i ≤ 10^9) — initial coordinates of the stones. There may be multiple stones sharing the same coordinate. The second line contains four integers b_1, …, b_4 (-10^9 ≤ b_i ≤ 10^9) — target coordinates of the stones. There may be multiple targets sharing the same coordinate. Output If there is no sequence of operations that achieves the goal, print a single integer -1. Otherwise, on the first line print a single integer k (0 ≤ k ≤ 1000) — the number of operations in your sequence. On the next k lines, describe the operations. The i-th of these lines should contain two integers x_i and y_i (x_i ≠ y_i) — coordinates of the moved stone and the center of symmetry stone for the i-th operation. For each operation i, there should at least one stone in each of the coordinates x_i and y_i, and the resulting coordinate 2y_i - x_i must not exceed 10^{18} by absolute value. If there are multiple suitable sequences, print any of them. It is guaranteed that if there is a suitable sequence of operations, then there is also a suitable sequence that satisfies all the additional requirement. Examples Input 0 1 2 3 3 5 6 8 Output 3 1 3 2 5 0 3 Input 0 0 0 0 1 1 1 1 Output -1 Input 0 0 0 1 0 1 0 1 Output -1
instruction
0
85,118
15
170,236
Tags: constructive algorithms Correct Solution: ``` def Output(ans): if ans is None: print(-1) return print(len(ans)) for x, c in ans: print(x, c) def fun(a, b): while a and b: a %= b if a: b %= a return a + b def fun1(A): r = A[1] - A[0] for i in (2, 3): r = fun(r, A[i] - A[0]) return r def Mir(x, c): return c * 2 - x def findans(A): A[0].sort() A[1].sort() gcds = [fun1(A[0]), fun1(A[1])] I0, I1 = 0, 1 if A[0][-1] - A[0][0] > A[1][-1] - A[1][0]: I0, I1 = I1, I0 if A[I1][-1] == A[I1][0]: if A[I1][0] == A[I0][0]: return [] return None elif A[I0][-1] == A[I0][0]: return None if gcds[0] != gcds[1]: return None if (A[0][0] - A[1][0]) % gcds[0] != 0: return None ops = [[], []] def Op(I, J1, JC): ops[I].append((A[I0][J1], A[I0][JC])) A[I0][J1] = Mir(A[I0][J1], A[I0][JC]) while True: for a in A: a.sort() if max(A[0][-1], A[1][-1]) - min(A[0][0], A[1][0]) <= gcds[0]: break #print('====now', A) gapL = abs(A[0][0] - A[1][0]) gapR = abs(A[0][-1] - A[1][-1]) if gapL > gapR: I0, I1 = (0, 1) if A[0][0] < A[1][0] else (1, 0) view = lambda x: x else: I0, I1 = (0, 1) if A[0][-1] > A[1][-1] else (1, 0) view = lambda x: 3 - x for a in A: a.sort(key=view) lim = max(view(A[I0][-1]), view(A[I1][-1])) B = [view(x) for x in A[I0]] actioned = False for J in (3, 2): if Mir(B[0], B[J]) <= lim: Op(I0, (0), (J)) actioned = True break if actioned: continue if Mir(B[0], B[1]) > lim: Op(I0, (3), (1)) continue if (B[1] - B[0]) * 8 >= lim - B[0]: Op(I0, (0), (1)) continue if (B[3] - B[2]) * 8 >= lim - B[0]: Op(I0, (0), (2)) Op(I0, (0), (3)) continue if B[1] - B[0] < B[3] - B[2]: Op(I0, (1), (2)) Op(I0, (1), (3)) else: Op(I0, (2), (1)) Op(I0, (2), (0)) Op(I0, (0), (1)) if A[0] != A[1]: return None return ops[0] + [(Mir(x, c), c) for x, c in reversed(ops[1])] import sys input = [list(map(int, sys.stdin.readline().split())) for _ in range(2)] Output(findans(input)) ```
output
1
85,118
15
170,237
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a square matrix consisting of n rows and n columns. We assume that the rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to n from left to right. Some cells (n - 1 cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can apply the following operations to the matrix: 1. Swap i-th and j-th rows of the matrix; 2. Swap i-th and j-th columns of the matrix. You are asked to transform the matrix into a special form using these operations. In that special form all the ones must be in the cells that lie below the main diagonal. Cell of the matrix, which is located on the intersection of the i-th row and of the j-th column, lies below the main diagonal if i > j. Input The first line contains an integer n (2 ≤ n ≤ 1000) — the number of rows and columns. Then follow n - 1 lines that contain one's positions, one per line. Each position is described by two integers xk, yk (1 ≤ xk, yk ≤ n), separated by a space. A pair (xk, yk) means that the cell, which is located on the intersection of the xk-th row and of the yk-th column, contains one. It is guaranteed that all positions are distinct. Output Print the description of your actions. These actions should transform the matrix to the described special form. In the first line you should print a non-negative integer m (m ≤ 105) — the number of actions. In each of the next m lines print three space-separated integers t, i, j (1 ≤ t ≤ 2, 1 ≤ i, j ≤ n, i ≠ j), where t = 1 if you want to swap rows, t = 2 if you want to swap columns, and i and j denote the numbers of rows or columns respectively. Please note, that you do not need to minimize the number of operations, but their number should not exceed 105. If there are several solutions, you may print any of them. Examples Input 2 1 2 Output 2 2 1 2 1 1 2 Input 3 3 1 1 3 Output 3 2 2 3 1 1 3 1 1 2 Input 3 2 1 3 2 Output 0 Submitted Solution: ``` def find_all(s, c): s = "".join(str(x) for x in s) c = str(c) index = s.find(c) while index != -1: yield index index = s.find(c, index + 1) n = int(input()) row, col, actions = [], [], [] available = list(range(1, n + 1)) for _ in range(n - 1): (r, c) = map(int, input().split(' ')) row.append(r) col.append(c) for cur in range(n, 1, -1): if not row: break print(row) print(col) # for column if cur in col: idx = col.index(cur) zero = list(set(available) - set(col))[0] col[idx] = zero actions.append([2, cur, zero]) # row try: idx = row.index(cur) indices = list(find_all(row, cur)) indices.reverse() for i in indices: del row[i], col[i] del available[-1] continue except ValueError: val = row[0] indices = list(find_all(row, val)) print(indices) actions.append([1, row[0], cur]) indices.reverse() for i in indices: del row[i], col[i] del available[-1] if not actions: print(0) else: print(len(actions)) for move in actions: print(*move) ```
instruction
0
85,278
15
170,556
No
output
1
85,278
15
170,557
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a square matrix consisting of n rows and n columns. We assume that the rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to n from left to right. Some cells (n - 1 cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can apply the following operations to the matrix: 1. Swap i-th and j-th rows of the matrix; 2. Swap i-th and j-th columns of the matrix. You are asked to transform the matrix into a special form using these operations. In that special form all the ones must be in the cells that lie below the main diagonal. Cell of the matrix, which is located on the intersection of the i-th row and of the j-th column, lies below the main diagonal if i > j. Input The first line contains an integer n (2 ≤ n ≤ 1000) — the number of rows and columns. Then follow n - 1 lines that contain one's positions, one per line. Each position is described by two integers xk, yk (1 ≤ xk, yk ≤ n), separated by a space. A pair (xk, yk) means that the cell, which is located on the intersection of the xk-th row and of the yk-th column, contains one. It is guaranteed that all positions are distinct. Output Print the description of your actions. These actions should transform the matrix to the described special form. In the first line you should print a non-negative integer m (m ≤ 105) — the number of actions. In each of the next m lines print three space-separated integers t, i, j (1 ≤ t ≤ 2, 1 ≤ i, j ≤ n, i ≠ j), where t = 1 if you want to swap rows, t = 2 if you want to swap columns, and i and j denote the numbers of rows or columns respectively. Please note, that you do not need to minimize the number of operations, but their number should not exceed 105. If there are several solutions, you may print any of them. Examples Input 2 1 2 Output 2 2 1 2 1 1 2 Input 3 3 1 1 3 Output 3 2 2 3 1 1 3 1 1 2 Input 3 2 1 3 2 Output 0 Submitted Solution: ``` def find_all(s, c): s = "".join(str(x) for x in s) c = str(c) index = s.find(c) while index != -1: yield index index = s.find(c, index + 1) n = int(input()) row, col, actions = [], [], [] available = list(range(1, n + 1)) for _ in range(n - 1): (r, c) = map(int, input().split(' ')) row.append(r) col.append(c) for cur in range(n, 1, -1): if not row: break # for column if cur in col: idx = col.index(cur) zero = list(set(available) - set(col))[0] col[idx] = zero actions.append([2, cur, zero]) # row try: idx = row.index(cur) indices = list(find_all(row, cur)) indices.reverse() for i in indices: del row[i], col[i] del available[-1] continue except ValueError: val = row[0] indices = list(find_all(row, val)) actions.append([1, row[0], cur]) indices.reverse() for i in indices: del row[i], col[i] del available[-1] if not actions: print(0) else: print(len(actions)) for move in actions: print(*move) ```
instruction
0
85,279
15
170,558
No
output
1
85,279
15
170,559
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a square matrix consisting of n rows and n columns. We assume that the rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to n from left to right. Some cells (n - 1 cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can apply the following operations to the matrix: 1. Swap i-th and j-th rows of the matrix; 2. Swap i-th and j-th columns of the matrix. You are asked to transform the matrix into a special form using these operations. In that special form all the ones must be in the cells that lie below the main diagonal. Cell of the matrix, which is located on the intersection of the i-th row and of the j-th column, lies below the main diagonal if i > j. Input The first line contains an integer n (2 ≤ n ≤ 1000) — the number of rows and columns. Then follow n - 1 lines that contain one's positions, one per line. Each position is described by two integers xk, yk (1 ≤ xk, yk ≤ n), separated by a space. A pair (xk, yk) means that the cell, which is located on the intersection of the xk-th row and of the yk-th column, contains one. It is guaranteed that all positions are distinct. Output Print the description of your actions. These actions should transform the matrix to the described special form. In the first line you should print a non-negative integer m (m ≤ 105) — the number of actions. In each of the next m lines print three space-separated integers t, i, j (1 ≤ t ≤ 2, 1 ≤ i, j ≤ n, i ≠ j), where t = 1 if you want to swap rows, t = 2 if you want to swap columns, and i and j denote the numbers of rows or columns respectively. Please note, that you do not need to minimize the number of operations, but their number should not exceed 105. If there are several solutions, you may print any of them. Examples Input 2 1 2 Output 2 2 1 2 1 1 2 Input 3 3 1 1 3 Output 3 2 2 3 1 1 3 1 1 2 Input 3 2 1 3 2 Output 0 Submitted Solution: ``` n = int(input()) v = [] for i in range(n-1): x,y = map(int, input().split()) if i+2 != x : v.append((1,i+2,x)) if (i+1 != y): v.append((2,i+1,y)) print(len(v)) for o in v: for x in o: print(x, end=' ') print() ```
instruction
0
85,280
15
170,560
No
output
1
85,280
15
170,561
Provide tags and a correct Python 3 solution for this coding contest problem. Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is n squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares. For example, the correct field to play looks like that: 001*2***101*. The cells that are marked with "*" contain bombs. Note that on the correct field the numbers represent the number of bombs in adjacent cells. For example, field 2* is not correct, because cell with value 2 must have two adjacent cells with bombs. Valera wants to make a correct field to play "Minesweeper 1D". He has already painted a squared field with width of n cells, put several bombs on the field and wrote numbers into some cells. Now he wonders how many ways to fill the remaining cells with bombs and numbers are there if we should get a correct field in the end. Input The first line contains sequence of characters without spaces s1s2... sn (1 ≤ n ≤ 106), containing only characters "*", "?" and digits "0", "1" or "2". If character si equals "*", then the i-th cell of the field contains a bomb. If character si equals "?", then Valera hasn't yet decided what to put in the i-th cell. Character si, that is equal to a digit, represents the digit written in the i-th square. Output Print a single integer — the number of ways Valera can fill the empty cells and get a correct field. As the answer can be rather large, print it modulo 1000000007 (109 + 7). Examples Input ?01??? Output 4 Input ? Output 2 Input **12 Output 0 Input 1 Output 0 Note In the first test sample you can get the following correct fields: 001**1, 001***, 001*2*, 001*10.
instruction
0
85,303
15
170,606
Tags: dp, implementation Correct Solution: ``` m = 1000000007 a, b, c = 1, 0, 1 for s in input(): if s == '*': a, b, c = 0, b + c, 0 elif s == '?': a, b, c = (a + b) % m, (b + c) % m, (a + b) % m elif s == '0': a, b, c = a, 0, 0 elif s == '1': a, b, c = b, 0, a else: a, b, c = 0, 0, b print((a + b) % m) ```
output
1
85,303
15
170,607
Provide tags and a correct Python 3 solution for this coding contest problem. Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is n squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares. For example, the correct field to play looks like that: 001*2***101*. The cells that are marked with "*" contain bombs. Note that on the correct field the numbers represent the number of bombs in adjacent cells. For example, field 2* is not correct, because cell with value 2 must have two adjacent cells with bombs. Valera wants to make a correct field to play "Minesweeper 1D". He has already painted a squared field with width of n cells, put several bombs on the field and wrote numbers into some cells. Now he wonders how many ways to fill the remaining cells with bombs and numbers are there if we should get a correct field in the end. Input The first line contains sequence of characters without spaces s1s2... sn (1 ≤ n ≤ 106), containing only characters "*", "?" and digits "0", "1" or "2". If character si equals "*", then the i-th cell of the field contains a bomb. If character si equals "?", then Valera hasn't yet decided what to put in the i-th cell. Character si, that is equal to a digit, represents the digit written in the i-th square. Output Print a single integer — the number of ways Valera can fill the empty cells and get a correct field. As the answer can be rather large, print it modulo 1000000007 (109 + 7). Examples Input ?01??? Output 4 Input ? Output 2 Input **12 Output 0 Input 1 Output 0 Note In the first test sample you can get the following correct fields: 001**1, 001***, 001*2*, 001*10.
instruction
0
85,304
15
170,608
Tags: dp, implementation Correct Solution: ``` Mod=1000000007 s=input() n=len(s) a,b,c,d=1,0,0,0 for i in range(0,n): if s[i]=='*': t=0,a+b+d,0,0 elif s[i]=='?': t=a+b+c,a+b+d,0,0 elif s[i]=='0': t=0,0,a+c,0 elif s[i]=='1': t=0,0,b,a+c else: t=0,0,0,b+d a,b,c,d=map(lambda a:a%Mod,t) print((a+b+c)%Mod) ```
output
1
85,304
15
170,609
Provide tags and a correct Python 3 solution for this coding contest problem. Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is n squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares. For example, the correct field to play looks like that: 001*2***101*. The cells that are marked with "*" contain bombs. Note that on the correct field the numbers represent the number of bombs in adjacent cells. For example, field 2* is not correct, because cell with value 2 must have two adjacent cells with bombs. Valera wants to make a correct field to play "Minesweeper 1D". He has already painted a squared field with width of n cells, put several bombs on the field and wrote numbers into some cells. Now he wonders how many ways to fill the remaining cells with bombs and numbers are there if we should get a correct field in the end. Input The first line contains sequence of characters without spaces s1s2... sn (1 ≤ n ≤ 106), containing only characters "*", "?" and digits "0", "1" or "2". If character si equals "*", then the i-th cell of the field contains a bomb. If character si equals "?", then Valera hasn't yet decided what to put in the i-th cell. Character si, that is equal to a digit, represents the digit written in the i-th square. Output Print a single integer — the number of ways Valera can fill the empty cells and get a correct field. As the answer can be rather large, print it modulo 1000000007 (109 + 7). Examples Input ?01??? Output 4 Input ? Output 2 Input **12 Output 0 Input 1 Output 0 Note In the first test sample you can get the following correct fields: 001**1, 001***, 001*2*, 001*10.
instruction
0
85,305
15
170,610
Tags: dp, implementation Correct Solution: ``` Mod=1000000007 s=input() n=len(s) a,b,c,d=1,0,0,0 for i in range(0,n): if s[i]=='*': a,b,c,d=0,(a+b+d)%Mod,0,0 elif s[i]=='?': a,b,c,d=(a+b+c)%Mod,(a+b+d)%Mod,0,0 elif s[i]=='0': a,b,c,d=0,0,(a+c)%Mod,0 elif s[i]=='1': a,b,c,d=0,0,b,(a+c)%Mod else: a,b,c,d=0,0,0,(b+d)%Mod print((a+b+c)%Mod) ```
output
1
85,305
15
170,611
Provide tags and a correct Python 3 solution for this coding contest problem. Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is n squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares. For example, the correct field to play looks like that: 001*2***101*. The cells that are marked with "*" contain bombs. Note that on the correct field the numbers represent the number of bombs in adjacent cells. For example, field 2* is not correct, because cell with value 2 must have two adjacent cells with bombs. Valera wants to make a correct field to play "Minesweeper 1D". He has already painted a squared field with width of n cells, put several bombs on the field and wrote numbers into some cells. Now he wonders how many ways to fill the remaining cells with bombs and numbers are there if we should get a correct field in the end. Input The first line contains sequence of characters without spaces s1s2... sn (1 ≤ n ≤ 106), containing only characters "*", "?" and digits "0", "1" or "2". If character si equals "*", then the i-th cell of the field contains a bomb. If character si equals "?", then Valera hasn't yet decided what to put in the i-th cell. Character si, that is equal to a digit, represents the digit written in the i-th square. Output Print a single integer — the number of ways Valera can fill the empty cells and get a correct field. As the answer can be rather large, print it modulo 1000000007 (109 + 7). Examples Input ?01??? Output 4 Input ? Output 2 Input **12 Output 0 Input 1 Output 0 Note In the first test sample you can get the following correct fields: 001**1, 001***, 001*2*, 001*10.
instruction
0
85,306
15
170,612
Tags: dp, implementation Correct Solution: ``` # python txdy! mod=1000000007 a,b,c=1,0,1 for s in input(): if s=='*':a,b,c=0,b+c,0 elif s=='?':a,b,c=(a+b)%mod,(b+c)%mod,(a+b)%mod elif s=='0':a,b,c=a,0,0 elif s=='1':a,b,c=b,0,a else: a,b,c=0,0,b print((a+b)%mod) ```
output
1
85,306
15
170,613
Provide tags and a correct Python 3 solution for this coding contest problem. Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is n squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares. For example, the correct field to play looks like that: 001*2***101*. The cells that are marked with "*" contain bombs. Note that on the correct field the numbers represent the number of bombs in adjacent cells. For example, field 2* is not correct, because cell with value 2 must have two adjacent cells with bombs. Valera wants to make a correct field to play "Minesweeper 1D". He has already painted a squared field with width of n cells, put several bombs on the field and wrote numbers into some cells. Now he wonders how many ways to fill the remaining cells with bombs and numbers are there if we should get a correct field in the end. Input The first line contains sequence of characters without spaces s1s2... sn (1 ≤ n ≤ 106), containing only characters "*", "?" and digits "0", "1" or "2". If character si equals "*", then the i-th cell of the field contains a bomb. If character si equals "?", then Valera hasn't yet decided what to put in the i-th cell. Character si, that is equal to a digit, represents the digit written in the i-th square. Output Print a single integer — the number of ways Valera can fill the empty cells and get a correct field. As the answer can be rather large, print it modulo 1000000007 (109 + 7). Examples Input ?01??? Output 4 Input ? Output 2 Input **12 Output 0 Input 1 Output 0 Note In the first test sample you can get the following correct fields: 001**1, 001***, 001*2*, 001*10.
instruction
0
85,307
15
170,614
Tags: dp, implementation Correct Solution: ``` s=input() n=len(s) a,b,c,d=1,0,0,0 for i in range(0,n): if s[i]=='*': a,b,c,d=0,(a+b+d)% 1000000007,0,0 elif s[i]=='?': a,b,c,d=(a+b+c)% 1000000007,(a+b+d)% 1000000007,0,0 elif s[i]=='0': a,b,c,d=0,0,(a+c)% 1000000007,0 elif s[i]=='1': a,b,c,d=0,0,b,(a+c)% 1000000007 else: a,b,c,d=0,0,0,(b+d)% 1000000007 print((a+b+c)% 1000000007) ```
output
1
85,307
15
170,615
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is n squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares. For example, the correct field to play looks like that: 001*2***101*. The cells that are marked with "*" contain bombs. Note that on the correct field the numbers represent the number of bombs in adjacent cells. For example, field 2* is not correct, because cell with value 2 must have two adjacent cells with bombs. Valera wants to make a correct field to play "Minesweeper 1D". He has already painted a squared field with width of n cells, put several bombs on the field and wrote numbers into some cells. Now he wonders how many ways to fill the remaining cells with bombs and numbers are there if we should get a correct field in the end. Input The first line contains sequence of characters without spaces s1s2... sn (1 ≤ n ≤ 106), containing only characters "*", "?" and digits "0", "1" or "2". If character si equals "*", then the i-th cell of the field contains a bomb. If character si equals "?", then Valera hasn't yet decided what to put in the i-th cell. Character si, that is equal to a digit, represents the digit written in the i-th square. Output Print a single integer — the number of ways Valera can fill the empty cells and get a correct field. As the answer can be rather large, print it modulo 1000000007 (109 + 7). Examples Input ?01??? Output 4 Input ? Output 2 Input **12 Output 0 Input 1 Output 0 Note In the first test sample you can get the following correct fields: 001**1, 001***, 001*2*, 001*10. Submitted Solution: ``` Mod=1000000007 s=input() n=len(s) a,b,c,d=1,0,0,0 for i in range(0,n): if s[i]=='?': a,b,c,d=(a+b+c)%Mod,(a+b+d)%Mod,0,0 elif s[i]=='0': a,b,c,d=0,0,(a+c)%Mod,0 elif s[i]=='1': a,b,c,d=0,0,b,(a+c)%Mod else: a,b,c,d=0,0,0,(b+d)%Mod print(a+b+c) ```
instruction
0
85,308
15
170,616
No
output
1
85,308
15
170,617
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is n squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares. For example, the correct field to play looks like that: 001*2***101*. The cells that are marked with "*" contain bombs. Note that on the correct field the numbers represent the number of bombs in adjacent cells. For example, field 2* is not correct, because cell with value 2 must have two adjacent cells with bombs. Valera wants to make a correct field to play "Minesweeper 1D". He has already painted a squared field with width of n cells, put several bombs on the field and wrote numbers into some cells. Now he wonders how many ways to fill the remaining cells with bombs and numbers are there if we should get a correct field in the end. Input The first line contains sequence of characters without spaces s1s2... sn (1 ≤ n ≤ 106), containing only characters "*", "?" and digits "0", "1" or "2". If character si equals "*", then the i-th cell of the field contains a bomb. If character si equals "?", then Valera hasn't yet decided what to put in the i-th cell. Character si, that is equal to a digit, represents the digit written in the i-th square. Output Print a single integer — the number of ways Valera can fill the empty cells and get a correct field. As the answer can be rather large, print it modulo 1000000007 (109 + 7). Examples Input ?01??? Output 4 Input ? Output 2 Input **12 Output 0 Input 1 Output 0 Note In the first test sample you can get the following correct fields: 001**1, 001***, 001*2*, 001*10. Submitted Solution: ``` # python txdy! m=1000000007 a,b,c=1,0,1 for s in input(): if s=='*':a,b,c=0,b+c,0 elif s=='?':a,b,c=(a+b)%m,(b+c)%m,(a+b)%m elif s=='0':a,b,c=a,0,0 elif s=='1':a,b,c=b,0,a else: a,b,c=0,0,b print(a+b) ```
instruction
0
85,309
15
170,618
No
output
1
85,309
15
170,619
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is n squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares. For example, the correct field to play looks like that: 001*2***101*. The cells that are marked with "*" contain bombs. Note that on the correct field the numbers represent the number of bombs in adjacent cells. For example, field 2* is not correct, because cell with value 2 must have two adjacent cells with bombs. Valera wants to make a correct field to play "Minesweeper 1D". He has already painted a squared field with width of n cells, put several bombs on the field and wrote numbers into some cells. Now he wonders how many ways to fill the remaining cells with bombs and numbers are there if we should get a correct field in the end. Input The first line contains sequence of characters without spaces s1s2... sn (1 ≤ n ≤ 106), containing only characters "*", "?" and digits "0", "1" or "2". If character si equals "*", then the i-th cell of the field contains a bomb. If character si equals "?", then Valera hasn't yet decided what to put in the i-th cell. Character si, that is equal to a digit, represents the digit written in the i-th square. Output Print a single integer — the number of ways Valera can fill the empty cells and get a correct field. As the answer can be rather large, print it modulo 1000000007 (109 + 7). Examples Input ?01??? Output 4 Input ? Output 2 Input **12 Output 0 Input 1 Output 0 Note In the first test sample you can get the following correct fields: 001**1, 001***, 001*2*, 001*10. Submitted Solution: ``` Mod=1000000007 s=input() n=len(s) a,b,c,d=1,0,0,0 for i in range(0,n): if s[i]=='*': a,b,c,d=0,(a+b+d)%Mod,0,0 elif s[i]=='?': a,b,c,d=(a+b+c)%Mod,(a+b+d)%Mod,0,0 elif s[i]=='0': a,b,c,d=0,0,(a+c)%Mod,0 elif s[i]=='1': a,b,c,d=0,0,b,(a+c)%Mod else: a,b,c,d=0,0,0,(b+d)%Mod print(a+b+c) ```
instruction
0
85,310
15
170,620
No
output
1
85,310
15
170,621
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is n squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares. For example, the correct field to play looks like that: 001*2***101*. The cells that are marked with "*" contain bombs. Note that on the correct field the numbers represent the number of bombs in adjacent cells. For example, field 2* is not correct, because cell with value 2 must have two adjacent cells with bombs. Valera wants to make a correct field to play "Minesweeper 1D". He has already painted a squared field with width of n cells, put several bombs on the field and wrote numbers into some cells. Now he wonders how many ways to fill the remaining cells with bombs and numbers are there if we should get a correct field in the end. Input The first line contains sequence of characters without spaces s1s2... sn (1 ≤ n ≤ 106), containing only characters "*", "?" and digits "0", "1" or "2". If character si equals "*", then the i-th cell of the field contains a bomb. If character si equals "?", then Valera hasn't yet decided what to put in the i-th cell. Character si, that is equal to a digit, represents the digit written in the i-th square. Output Print a single integer — the number of ways Valera can fill the empty cells and get a correct field. As the answer can be rather large, print it modulo 1000000007 (109 + 7). Examples Input ?01??? Output 4 Input ? Output 2 Input **12 Output 0 Input 1 Output 0 Note In the first test sample you can get the following correct fields: 001**1, 001***, 001*2*, 001*10. Submitted Solution: ``` m = 1000000007 a, b, c = 1, 0, 1 for s in input(): if s == '*': a, b, c = 0, b + c, 0 elif s == '?': a, b, c = (a + b) % m, (b + c) % m, b % m elif s == '0': a, b, c = a, 0, 0 elif s == '1': a, b, c = b, 0, a else: a, b, c = 0, 0, b print((a + b) % m) ```
instruction
0
85,311
15
170,622
No
output
1
85,311
15
170,623
Provide tags and a correct Python 3 solution for this coding contest problem. You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy. Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D environment. The dungeon can be represented as a rectangle matrix of n rows and m columns. Cell (x, y) is the cell in the x-th row in the y-th column. Lara can move between the neighbouring by side cells in all four directions. Moreover, she has even chosen the path for herself to avoid all the traps. She enters the dungeon in cell (1, 1), that is top left corner of the matrix. Then she goes down all the way to cell (n, 1) — the bottom left corner. Then she starts moving in the snake fashion — all the way to the right, one cell up, then to the left to the cell in 2-nd column, one cell up. She moves until she runs out of non-visited cells. n and m given are such that she always end up in cell (1, 2). Lara has already moved to a neighbouring cell k times. Can you determine her current position? Input The only line contains three integers n, m and k (2 ≤ n, m ≤ 109, n is always even, 0 ≤ k < n·m). Note that k doesn't fit into 32-bit integer type! Output Print the cell (the row and the column where the cell is situated) where Lara ends up after she moves k times. Examples Input 4 3 0 Output 1 1 Input 4 3 11 Output 1 2 Input 4 3 7 Output 3 2 Note Here is her path on matrix 4 by 3: <image>
instruction
0
85,487
15
170,974
Tags: implementation, math Correct Solution: ``` s = input().split(); n,m,k = int(s[0]),int(s[1]),int(s[2]) x,y = 0,0 if k < (n + m - 1): if k <= n - 1: x = k + 1 y = 1 elif k >= n: x = n y = k - n + 2 else: k = k - (n + m - 2) m = m - 1 if k%m == 0: x = k//m else: x = (k//m) + 1 y = k - (x - 1)*m if x%2 == 0: y = m - y + 1 else: pass x = x + 1 x = n - x + 1 y = m - y + 2 print(x,y) ```
output
1
85,487
15
170,975
Provide tags and a correct Python 3 solution for this coding contest problem. You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy. Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D environment. The dungeon can be represented as a rectangle matrix of n rows and m columns. Cell (x, y) is the cell in the x-th row in the y-th column. Lara can move between the neighbouring by side cells in all four directions. Moreover, she has even chosen the path for herself to avoid all the traps. She enters the dungeon in cell (1, 1), that is top left corner of the matrix. Then she goes down all the way to cell (n, 1) — the bottom left corner. Then she starts moving in the snake fashion — all the way to the right, one cell up, then to the left to the cell in 2-nd column, one cell up. She moves until she runs out of non-visited cells. n and m given are such that she always end up in cell (1, 2). Lara has already moved to a neighbouring cell k times. Can you determine her current position? Input The only line contains three integers n, m and k (2 ≤ n, m ≤ 109, n is always even, 0 ≤ k < n·m). Note that k doesn't fit into 32-bit integer type! Output Print the cell (the row and the column where the cell is situated) where Lara ends up after she moves k times. Examples Input 4 3 0 Output 1 1 Input 4 3 11 Output 1 2 Input 4 3 7 Output 3 2 Note Here is her path on matrix 4 by 3: <image>
instruction
0
85,488
15
170,976
Tags: implementation, math Correct Solution: ``` n,m,k=map(int,input().split()) if (k<n): print(k+1," ",1,sep="") else: k-=n if (m>=2): x=k//(m-1) if x%2==0: a=k%(m-1) +2 b=n-x else: a=(m-k%(m-1)) b=n-x print(b,a) ```
output
1
85,488
15
170,977
Provide tags and a correct Python 3 solution for this coding contest problem. You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy. Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D environment. The dungeon can be represented as a rectangle matrix of n rows and m columns. Cell (x, y) is the cell in the x-th row in the y-th column. Lara can move between the neighbouring by side cells in all four directions. Moreover, she has even chosen the path for herself to avoid all the traps. She enters the dungeon in cell (1, 1), that is top left corner of the matrix. Then she goes down all the way to cell (n, 1) — the bottom left corner. Then she starts moving in the snake fashion — all the way to the right, one cell up, then to the left to the cell in 2-nd column, one cell up. She moves until she runs out of non-visited cells. n and m given are such that she always end up in cell (1, 2). Lara has already moved to a neighbouring cell k times. Can you determine her current position? Input The only line contains three integers n, m and k (2 ≤ n, m ≤ 109, n is always even, 0 ≤ k < n·m). Note that k doesn't fit into 32-bit integer type! Output Print the cell (the row and the column where the cell is situated) where Lara ends up after she moves k times. Examples Input 4 3 0 Output 1 1 Input 4 3 11 Output 1 2 Input 4 3 7 Output 3 2 Note Here is her path on matrix 4 by 3: <image>
instruction
0
85,489
15
170,978
Tags: implementation, math Correct Solution: ``` n, m, k = [int(x) for x in input().split()] if k < n: print(k+1, 1) else: k += 1 row_num = (k-n-1) // (m-1) col_num = (k-n-1) % (m-1) if row_num % 2: print(n-row_num, m-col_num) else: print(n-row_num, col_num+2) ```
output
1
85,489
15
170,979
Provide tags and a correct Python 3 solution for this coding contest problem. You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy. Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D environment. The dungeon can be represented as a rectangle matrix of n rows and m columns. Cell (x, y) is the cell in the x-th row in the y-th column. Lara can move between the neighbouring by side cells in all four directions. Moreover, she has even chosen the path for herself to avoid all the traps. She enters the dungeon in cell (1, 1), that is top left corner of the matrix. Then she goes down all the way to cell (n, 1) — the bottom left corner. Then she starts moving in the snake fashion — all the way to the right, one cell up, then to the left to the cell in 2-nd column, one cell up. She moves until she runs out of non-visited cells. n and m given are such that she always end up in cell (1, 2). Lara has already moved to a neighbouring cell k times. Can you determine her current position? Input The only line contains three integers n, m and k (2 ≤ n, m ≤ 109, n is always even, 0 ≤ k < n·m). Note that k doesn't fit into 32-bit integer type! Output Print the cell (the row and the column where the cell is situated) where Lara ends up after she moves k times. Examples Input 4 3 0 Output 1 1 Input 4 3 11 Output 1 2 Input 4 3 7 Output 3 2 Note Here is her path on matrix 4 by 3: <image>
instruction
0
85,490
15
170,980
Tags: implementation, math Correct Solution: ``` n,m,k=map(int,input().split()) if k<n: print(k+1,1) else: k-=n floor=n-k//(m-1) if floor%2: print(floor, m-k%(m-1)) else: print(floor, (k%(m-1))+2) ```
output
1
85,490
15
170,981
Provide tags and a correct Python 3 solution for this coding contest problem. You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy. Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D environment. The dungeon can be represented as a rectangle matrix of n rows and m columns. Cell (x, y) is the cell in the x-th row in the y-th column. Lara can move between the neighbouring by side cells in all four directions. Moreover, she has even chosen the path for herself to avoid all the traps. She enters the dungeon in cell (1, 1), that is top left corner of the matrix. Then she goes down all the way to cell (n, 1) — the bottom left corner. Then she starts moving in the snake fashion — all the way to the right, one cell up, then to the left to the cell in 2-nd column, one cell up. She moves until she runs out of non-visited cells. n and m given are such that she always end up in cell (1, 2). Lara has already moved to a neighbouring cell k times. Can you determine her current position? Input The only line contains three integers n, m and k (2 ≤ n, m ≤ 109, n is always even, 0 ≤ k < n·m). Note that k doesn't fit into 32-bit integer type! Output Print the cell (the row and the column where the cell is situated) where Lara ends up after she moves k times. Examples Input 4 3 0 Output 1 1 Input 4 3 11 Output 1 2 Input 4 3 7 Output 3 2 Note Here is her path on matrix 4 by 3: <image>
instruction
0
85,491
15
170,982
Tags: implementation, math Correct Solution: ``` n, m, k = map(int, input().split()) if k < n: print(k+1, 1) else: k = k-(n-1) tmp = k//(2*(m-1)) k = k%(2*(m-1)) x, y = n-2*tmp+1, 2 if k > 0: x = x-1 k = k-1 if k <= m-2: y = y+k else: k = k-(m-1) x = x-1 y = m-k print(x, y) ```
output
1
85,491
15
170,983
Provide tags and a correct Python 3 solution for this coding contest problem. You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy. Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D environment. The dungeon can be represented as a rectangle matrix of n rows and m columns. Cell (x, y) is the cell in the x-th row in the y-th column. Lara can move between the neighbouring by side cells in all four directions. Moreover, she has even chosen the path for herself to avoid all the traps. She enters the dungeon in cell (1, 1), that is top left corner of the matrix. Then she goes down all the way to cell (n, 1) — the bottom left corner. Then she starts moving in the snake fashion — all the way to the right, one cell up, then to the left to the cell in 2-nd column, one cell up. She moves until she runs out of non-visited cells. n and m given are such that she always end up in cell (1, 2). Lara has already moved to a neighbouring cell k times. Can you determine her current position? Input The only line contains three integers n, m and k (2 ≤ n, m ≤ 109, n is always even, 0 ≤ k < n·m). Note that k doesn't fit into 32-bit integer type! Output Print the cell (the row and the column where the cell is situated) where Lara ends up after she moves k times. Examples Input 4 3 0 Output 1 1 Input 4 3 11 Output 1 2 Input 4 3 7 Output 3 2 Note Here is her path on matrix 4 by 3: <image>
instruction
0
85,492
15
170,984
Tags: implementation, math Correct Solution: ``` n,m,k = map(int, input().split()) # n=4 m=3 k=0 if k <= n-1: # k = 3 print(k+1, 1) else: k = k-n+1 level = (k-1) // (m-1) k = (k-1) % (m-1) if level % 2 == 0: print(n-level, k+2) else: print(n-level, m-k) ```
output
1
85,492
15
170,985
Provide tags and a correct Python 3 solution for this coding contest problem. You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy. Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D environment. The dungeon can be represented as a rectangle matrix of n rows and m columns. Cell (x, y) is the cell in the x-th row in the y-th column. Lara can move between the neighbouring by side cells in all four directions. Moreover, she has even chosen the path for herself to avoid all the traps. She enters the dungeon in cell (1, 1), that is top left corner of the matrix. Then she goes down all the way to cell (n, 1) — the bottom left corner. Then she starts moving in the snake fashion — all the way to the right, one cell up, then to the left to the cell in 2-nd column, one cell up. She moves until she runs out of non-visited cells. n and m given are such that she always end up in cell (1, 2). Lara has already moved to a neighbouring cell k times. Can you determine her current position? Input The only line contains three integers n, m and k (2 ≤ n, m ≤ 109, n is always even, 0 ≤ k < n·m). Note that k doesn't fit into 32-bit integer type! Output Print the cell (the row and the column where the cell is situated) where Lara ends up after she moves k times. Examples Input 4 3 0 Output 1 1 Input 4 3 11 Output 1 2 Input 4 3 7 Output 3 2 Note Here is her path on matrix 4 by 3: <image>
instruction
0
85,493
15
170,986
Tags: implementation, math Correct Solution: ``` #!/usr/bin/env python3 n, m, k = map(int, input().split(' ')) if k < n: print(k + 1, 1) else: k -= n m -= 1 row = n - k//m k %= m if row % 2 == 0: print(row, 2 + k) else: print(row, 1 + (m -k)) ```
output
1
85,493
15
170,987
Provide tags and a correct Python 3 solution for this coding contest problem. You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy. Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D environment. The dungeon can be represented as a rectangle matrix of n rows and m columns. Cell (x, y) is the cell in the x-th row in the y-th column. Lara can move between the neighbouring by side cells in all four directions. Moreover, she has even chosen the path for herself to avoid all the traps. She enters the dungeon in cell (1, 1), that is top left corner of the matrix. Then she goes down all the way to cell (n, 1) — the bottom left corner. Then she starts moving in the snake fashion — all the way to the right, one cell up, then to the left to the cell in 2-nd column, one cell up. She moves until she runs out of non-visited cells. n and m given are such that she always end up in cell (1, 2). Lara has already moved to a neighbouring cell k times. Can you determine her current position? Input The only line contains three integers n, m and k (2 ≤ n, m ≤ 109, n is always even, 0 ≤ k < n·m). Note that k doesn't fit into 32-bit integer type! Output Print the cell (the row and the column where the cell is situated) where Lara ends up after she moves k times. Examples Input 4 3 0 Output 1 1 Input 4 3 11 Output 1 2 Input 4 3 7 Output 3 2 Note Here is her path on matrix 4 by 3: <image>
instruction
0
85,494
15
170,988
Tags: implementation, math Correct Solution: ``` n, m, k = map(int, input().split()) X = 0 Y = 0 if k < n: X = k + 1 Y = 1 elif k >= n and k <= m + n - 2: X = n Y = k - n + 2 else: k -= n + m - 1 temp = k // (m - 1) X = (n - 1) - temp isEven = X % 2 == 0 remains = k % (m - 1) if not isEven: Y = m - remains else: Y = remains + 2 print(X, Y) ```
output
1
85,494
15
170,989
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy. Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D environment. The dungeon can be represented as a rectangle matrix of n rows and m columns. Cell (x, y) is the cell in the x-th row in the y-th column. Lara can move between the neighbouring by side cells in all four directions. Moreover, she has even chosen the path for herself to avoid all the traps. She enters the dungeon in cell (1, 1), that is top left corner of the matrix. Then she goes down all the way to cell (n, 1) — the bottom left corner. Then she starts moving in the snake fashion — all the way to the right, one cell up, then to the left to the cell in 2-nd column, one cell up. She moves until she runs out of non-visited cells. n and m given are such that she always end up in cell (1, 2). Lara has already moved to a neighbouring cell k times. Can you determine her current position? Input The only line contains three integers n, m and k (2 ≤ n, m ≤ 109, n is always even, 0 ≤ k < n·m). Note that k doesn't fit into 32-bit integer type! Output Print the cell (the row and the column where the cell is situated) where Lara ends up after she moves k times. Examples Input 4 3 0 Output 1 1 Input 4 3 11 Output 1 2 Input 4 3 7 Output 3 2 Note Here is her path on matrix 4 by 3: <image> Submitted Solution: ``` import sys n, m, k = map(int, input().split()) if n-1 >= k: print(k+1, 1) else: div, mod = divmod(k-n, m-1) if div % 2 == 0: print(n-div, mod+2) else: print(n-div, m-mod) ```
instruction
0
85,495
15
170,990
Yes
output
1
85,495
15
170,991