text
stringlengths
198
433k
conversation_id
int64
0
109k
Provide tags and a correct Python 3 solution for this coding contest problem. Suppose you have two points p = (x_p, y_p) and q = (x_q, y_q). Let's denote the Manhattan distance between them as d(p, q) = |x_p - x_q| + |y_p - y_q|. Let's say that three points p, q, r form a bad triple if d(p, r) = d(p, q) + d(q, r). Let's say that an array b_1, b_2, ..., b_m is good if it is impossible to choose three distinct indices i, j, k such that the points (b_i, i), (b_j, j) and (b_k, k) form a bad triple. You are given an array a_1, a_2, ..., a_n. Calculate the number of good subarrays of a. A subarray of the array a is the array a_l, a_{l + 1}, ..., a_r for some 1 ≀ l ≀ r ≀ n. Note that, according to the definition, subarrays of length 1 and 2 are good. Input The first line contains one integer t (1 ≀ t ≀ 5000) β€” the number of test cases. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of array a. The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). It's guaranteed that the sum of n doesn't exceed 2 β‹… 10^5. Output For each test case, print the number of good subarrays of array a. Example Input 3 4 2 4 1 3 5 6 9 1 9 6 2 13 37 Output 10 12 3 Note In the first test case, it can be proven that any subarray of a is good. For example, subarray [a_2, a_3, a_4] is good since it contains only three elements and: * d((a_2, 2), (a_4, 4)) = |4 - 3| + |2 - 4| = 3 < d((a_2, 2), (a_3, 3)) + d((a_3, 3), (a_4, 4)) = 3 + 1 + 2 + 1 = 7; * d((a_2, 2), (a_3, 3)) < d((a_2, 2), (a_4, 4)) + d((a_4, 4), (a_3, 3)); * d((a_3, 3), (a_4, 4)) < d((a_3, 3), (a_2, 2)) + d((a_2, 2), (a_4, 4)); In the second test case, for example, subarray [a_1, a_2, a_3, a_4] is not good, since it contains a bad triple (a_1, 1), (a_2, 2), (a_4, 4): * d((a_1, 1), (a_4, 4)) = |6 - 9| + |1 - 4| = 6; * d((a_1, 1), (a_2, 2)) = |6 - 9| + |1 - 2| = 4; * d((a_2, 2), (a_4, 4)) = |9 - 9| + |2 - 4| = 2; So, d((a_1, 1), (a_4, 4)) = d((a_1, 1), (a_2, 2)) + d((a_2, 2), (a_4, 4)). Tags: brute force, geometry, greedy, implementation Correct Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq,bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase sys.setrecursionlimit(300000) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=2*10**9, func=lambda a, b: min(a,b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: max(a,b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] < key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) class TrieNode: def __init__(self): self.children = [None] * 26 self.isEndOfWord = False class Trie: def __init__(self): self.root = self.getNode() def getNode(self): return TrieNode() def _charToIndex(self, ch): return ord(ch) - ord('a') def insert(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: pCrawl.children[index] = self.getNode() pCrawl = pCrawl.children[index] pCrawl.isEndOfWord = True def search(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: return False pCrawl = pCrawl.children[index] return pCrawl != None and pCrawl.isEndOfWord #-----------------------------------------trie--------------------------------- class Node: def __init__(self, data): self.data = data self.count=0 self.left = None # left node for 0 self.right = None # right node for 1 class BinaryTrie: def __init__(self): self.root = Node(0) def insert(self, pre_xor): self.temp = self.root for i in range(31, -1, -1): val = pre_xor & (1 << i) if val: if not self.temp.right: self.temp.right = Node(0) self.temp = self.temp.right self.temp.count+=1 if not val: if not self.temp.left: self.temp.left = Node(0) self.temp = self.temp.left self.temp.count += 1 self.temp.data = pre_xor def query(self, xor): self.temp = self.root for i in range(31, -1, -1): val = xor & (1 << i) if not val: if self.temp.left and self.temp.left.count>0: self.temp = self.temp.left elif self.temp.right: self.temp = self.temp.right else: if self.temp.right and self.temp.right.count>0: self.temp = self.temp.right elif self.temp.left: self.temp = self.temp.left self.temp.count-=1 return xor ^ self.temp.data # --------------------------------------------------binary----------------------------------- for ik in range(int(input())): n=int(input()) l=list(map(int,input().split())) s=sorted(set(l+[])) ind=defaultdict(int) for i in range(len(s)): ind[s[i]]=i ma=0 for i in range(n): l[i]=ind[l[i]] ma=max(i,ma) e=[n]*(ma+1) e1=[n] * (ma + 1) e2=[n]*(ma+1) s = SegmentTree1(e) s1=SegmentTree1(e1) s2 = SegmentTree1(e2) nextg=[n]*(n+1) nexts=[n]*(n+1) ind = [n] * (n + 1) ind1 = [n] * (n + 1) for i in range(n-1,-1,-1): nextg[i]=s.query(l[i],ma) nexts[i]=s.query(0,l[i]) s.__setitem__(l[i],i) ind[i]=s1.query(0,l[i]) ind1[i]=s2.query(l[i],ma) s1.__setitem__(l[i],nexts[i]) s2.__setitem__(l[i],nextg[i]) e[l[i]]=i end=[0]*n for i in range(n): end[i]=min(ind[i],ind1[i])-1 ans=1 for i in range(n-2,-1,-1): end[i]=min(end[i],end[i+1]) ans+=end[i]-i+1 print(ans) ```
108,100
Provide tags and a correct Python 3 solution for this coding contest problem. Suppose you have two points p = (x_p, y_p) and q = (x_q, y_q). Let's denote the Manhattan distance between them as d(p, q) = |x_p - x_q| + |y_p - y_q|. Let's say that three points p, q, r form a bad triple if d(p, r) = d(p, q) + d(q, r). Let's say that an array b_1, b_2, ..., b_m is good if it is impossible to choose three distinct indices i, j, k such that the points (b_i, i), (b_j, j) and (b_k, k) form a bad triple. You are given an array a_1, a_2, ..., a_n. Calculate the number of good subarrays of a. A subarray of the array a is the array a_l, a_{l + 1}, ..., a_r for some 1 ≀ l ≀ r ≀ n. Note that, according to the definition, subarrays of length 1 and 2 are good. Input The first line contains one integer t (1 ≀ t ≀ 5000) β€” the number of test cases. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of array a. The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). It's guaranteed that the sum of n doesn't exceed 2 β‹… 10^5. Output For each test case, print the number of good subarrays of array a. Example Input 3 4 2 4 1 3 5 6 9 1 9 6 2 13 37 Output 10 12 3 Note In the first test case, it can be proven that any subarray of a is good. For example, subarray [a_2, a_3, a_4] is good since it contains only three elements and: * d((a_2, 2), (a_4, 4)) = |4 - 3| + |2 - 4| = 3 < d((a_2, 2), (a_3, 3)) + d((a_3, 3), (a_4, 4)) = 3 + 1 + 2 + 1 = 7; * d((a_2, 2), (a_3, 3)) < d((a_2, 2), (a_4, 4)) + d((a_4, 4), (a_3, 3)); * d((a_3, 3), (a_4, 4)) < d((a_3, 3), (a_2, 2)) + d((a_2, 2), (a_4, 4)); In the second test case, for example, subarray [a_1, a_2, a_3, a_4] is not good, since it contains a bad triple (a_1, 1), (a_2, 2), (a_4, 4): * d((a_1, 1), (a_4, 4)) = |6 - 9| + |1 - 4| = 6; * d((a_1, 1), (a_2, 2)) = |6 - 9| + |1 - 2| = 4; * d((a_2, 2), (a_4, 4)) = |9 - 9| + |2 - 4| = 2; So, d((a_1, 1), (a_4, 4)) = d((a_1, 1), (a_2, 2)) + d((a_2, 2), (a_4, 4)). Tags: brute force, geometry, greedy, implementation Correct Solution: ``` def is_bad(l): for i in range(2): for j in range(i+1,3): for k in range(j+1,4): if l[i] >= l[j] >= l[k] or l[i] <= l[j] <= l[k]: return True return False def solve(): n = int(input()) inp = list(map(int,input().split())) ans = n + n - 1 for i in range(n-2): if all(inp[i+x] <= inp[i+x+1] for x in range(2)) or all(inp[i+x] >= inp[i+x+1] for x in range(2)): pass else: ans += 1 for i in range(n-3): if is_bad(inp[i:i + 4]): pass else: ans += 1 print(ans) tests = int(input()) for _ in range(tests): solve() ```
108,101
Provide tags and a correct Python 3 solution for this coding contest problem. Suppose you have two points p = (x_p, y_p) and q = (x_q, y_q). Let's denote the Manhattan distance between them as d(p, q) = |x_p - x_q| + |y_p - y_q|. Let's say that three points p, q, r form a bad triple if d(p, r) = d(p, q) + d(q, r). Let's say that an array b_1, b_2, ..., b_m is good if it is impossible to choose three distinct indices i, j, k such that the points (b_i, i), (b_j, j) and (b_k, k) form a bad triple. You are given an array a_1, a_2, ..., a_n. Calculate the number of good subarrays of a. A subarray of the array a is the array a_l, a_{l + 1}, ..., a_r for some 1 ≀ l ≀ r ≀ n. Note that, according to the definition, subarrays of length 1 and 2 are good. Input The first line contains one integer t (1 ≀ t ≀ 5000) β€” the number of test cases. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of array a. The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). It's guaranteed that the sum of n doesn't exceed 2 β‹… 10^5. Output For each test case, print the number of good subarrays of array a. Example Input 3 4 2 4 1 3 5 6 9 1 9 6 2 13 37 Output 10 12 3 Note In the first test case, it can be proven that any subarray of a is good. For example, subarray [a_2, a_3, a_4] is good since it contains only three elements and: * d((a_2, 2), (a_4, 4)) = |4 - 3| + |2 - 4| = 3 < d((a_2, 2), (a_3, 3)) + d((a_3, 3), (a_4, 4)) = 3 + 1 + 2 + 1 = 7; * d((a_2, 2), (a_3, 3)) < d((a_2, 2), (a_4, 4)) + d((a_4, 4), (a_3, 3)); * d((a_3, 3), (a_4, 4)) < d((a_3, 3), (a_2, 2)) + d((a_2, 2), (a_4, 4)); In the second test case, for example, subarray [a_1, a_2, a_3, a_4] is not good, since it contains a bad triple (a_1, 1), (a_2, 2), (a_4, 4): * d((a_1, 1), (a_4, 4)) = |6 - 9| + |1 - 4| = 6; * d((a_1, 1), (a_2, 2)) = |6 - 9| + |1 - 2| = 4; * d((a_2, 2), (a_4, 4)) = |9 - 9| + |2 - 4| = 2; So, d((a_1, 1), (a_4, 4)) = d((a_1, 1), (a_2, 2)) + d((a_2, 2), (a_4, 4)). Tags: brute force, geometry, greedy, implementation Correct Solution: ``` def is_bad(l): if l[0]<=l[1]<=l[2] or l[0]>=l[1]>=l[2]:return True if l[0]<=l[1]<=l[3] or l[0]>=l[1]>=l[3]:return True if l[0]<=l[2]<=l[3] or l[0]>=l[2]>=l[3]:return True if l[1]<=l[2]<=l[3] or l[1]>=l[2]>=l[3]:return True return False def solve(): n = int(input()) inp = list(map(int,input().split())) ans = n + n - 1 for i in range(n-2): #print(10000000000+i) if all(inp[i+x] <= inp[i+x+1] for x in range(2)) or all(inp[i+x] >= inp[i+x+1] for x in range(2)): pass else: ans += 1 for i in range(n-3): #print("asd") if is_bad(inp[i:i + 4]): pass else: ans += 1 print(ans) tests = int(input()) for _ in range(tests): solve() ```
108,102
Provide tags and a correct Python 3 solution for this coding contest problem. Suppose you have two points p = (x_p, y_p) and q = (x_q, y_q). Let's denote the Manhattan distance between them as d(p, q) = |x_p - x_q| + |y_p - y_q|. Let's say that three points p, q, r form a bad triple if d(p, r) = d(p, q) + d(q, r). Let's say that an array b_1, b_2, ..., b_m is good if it is impossible to choose three distinct indices i, j, k such that the points (b_i, i), (b_j, j) and (b_k, k) form a bad triple. You are given an array a_1, a_2, ..., a_n. Calculate the number of good subarrays of a. A subarray of the array a is the array a_l, a_{l + 1}, ..., a_r for some 1 ≀ l ≀ r ≀ n. Note that, according to the definition, subarrays of length 1 and 2 are good. Input The first line contains one integer t (1 ≀ t ≀ 5000) β€” the number of test cases. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of array a. The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). It's guaranteed that the sum of n doesn't exceed 2 β‹… 10^5. Output For each test case, print the number of good subarrays of array a. Example Input 3 4 2 4 1 3 5 6 9 1 9 6 2 13 37 Output 10 12 3 Note In the first test case, it can be proven that any subarray of a is good. For example, subarray [a_2, a_3, a_4] is good since it contains only three elements and: * d((a_2, 2), (a_4, 4)) = |4 - 3| + |2 - 4| = 3 < d((a_2, 2), (a_3, 3)) + d((a_3, 3), (a_4, 4)) = 3 + 1 + 2 + 1 = 7; * d((a_2, 2), (a_3, 3)) < d((a_2, 2), (a_4, 4)) + d((a_4, 4), (a_3, 3)); * d((a_3, 3), (a_4, 4)) < d((a_3, 3), (a_2, 2)) + d((a_2, 2), (a_4, 4)); In the second test case, for example, subarray [a_1, a_2, a_3, a_4] is not good, since it contains a bad triple (a_1, 1), (a_2, 2), (a_4, 4): * d((a_1, 1), (a_4, 4)) = |6 - 9| + |1 - 4| = 6; * d((a_1, 1), (a_2, 2)) = |6 - 9| + |1 - 2| = 4; * d((a_2, 2), (a_4, 4)) = |9 - 9| + |2 - 4| = 2; So, d((a_1, 1), (a_4, 4)) = d((a_1, 1), (a_2, 2)) + d((a_2, 2), (a_4, 4)). Tags: brute force, geometry, greedy, implementation Correct Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ####################################### def f(p1,p2,p3): l2=[p1,p2,p3] l2.sort() if len(set([p1[0],p2[0],p3[0]]))>1: if l2[1][0]==l2[2][0]: if l2[1][1]<l2[0][1]<l2[2][1]: return True else: return False if l2[0][0]==l2[1][0]: if l2[0][1]<l2[2][1]<l2[1][1]: return True else: return False a=min(l2[0][1],l2[2][1]) b=max(l2[0][1],l2[2][1]) if not (a<=l2[1][1]<=b): return True return False for t in range(int(input())): n=int(input()) l=list(map(int,input().split())) ans=2*n-1 for i in range(n-2): if f([l[i],i],[l[i+1],i+1],[l[i+2],i+2]): ans+=1 for i in range(n-3): p1=[l[i],i] p2=[l[i+1],i+1] p3=[l[i+2],i+2] p4=[l[i+3],i+3] if f(p1,p2,p3) and f(p1,p3,p4) and f(p1,p2,p4) and f(p2,p3,p4): ans+=1 print(ans) ```
108,103
Provide tags and a correct Python 3 solution for this coding contest problem. Suppose you have two points p = (x_p, y_p) and q = (x_q, y_q). Let's denote the Manhattan distance between them as d(p, q) = |x_p - x_q| + |y_p - y_q|. Let's say that three points p, q, r form a bad triple if d(p, r) = d(p, q) + d(q, r). Let's say that an array b_1, b_2, ..., b_m is good if it is impossible to choose three distinct indices i, j, k such that the points (b_i, i), (b_j, j) and (b_k, k) form a bad triple. You are given an array a_1, a_2, ..., a_n. Calculate the number of good subarrays of a. A subarray of the array a is the array a_l, a_{l + 1}, ..., a_r for some 1 ≀ l ≀ r ≀ n. Note that, according to the definition, subarrays of length 1 and 2 are good. Input The first line contains one integer t (1 ≀ t ≀ 5000) β€” the number of test cases. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of array a. The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). It's guaranteed that the sum of n doesn't exceed 2 β‹… 10^5. Output For each test case, print the number of good subarrays of array a. Example Input 3 4 2 4 1 3 5 6 9 1 9 6 2 13 37 Output 10 12 3 Note In the first test case, it can be proven that any subarray of a is good. For example, subarray [a_2, a_3, a_4] is good since it contains only three elements and: * d((a_2, 2), (a_4, 4)) = |4 - 3| + |2 - 4| = 3 < d((a_2, 2), (a_3, 3)) + d((a_3, 3), (a_4, 4)) = 3 + 1 + 2 + 1 = 7; * d((a_2, 2), (a_3, 3)) < d((a_2, 2), (a_4, 4)) + d((a_4, 4), (a_3, 3)); * d((a_3, 3), (a_4, 4)) < d((a_3, 3), (a_2, 2)) + d((a_2, 2), (a_4, 4)); In the second test case, for example, subarray [a_1, a_2, a_3, a_4] is not good, since it contains a bad triple (a_1, 1), (a_2, 2), (a_4, 4): * d((a_1, 1), (a_4, 4)) = |6 - 9| + |1 - 4| = 6; * d((a_1, 1), (a_2, 2)) = |6 - 9| + |1 - 2| = 4; * d((a_2, 2), (a_4, 4)) = |9 - 9| + |2 - 4| = 2; So, d((a_1, 1), (a_4, 4)) = d((a_1, 1), (a_2, 2)) + d((a_2, 2), (a_4, 4)). Tags: brute force, geometry, greedy, implementation Correct Solution: ``` import sys t = int(sys.stdin.readline()) while(t>0): n = int(sys.stdin.readline()) a = list(map(int, input().split())) c = 2*n-1 if n<=2: print(c) else: for i in range(n-2): j = i+1 k = j+1 if a[i]>=a[j]>=a[k] or a[i]<=a[j]<=a[k]: c+=0 else: c+=1 for i in range(n-3): j = i+1 k = j+1 l = k+1 if a[i]>=a[j]>=a[k] or a[i]<=a[j]<=a[k]: c+=0 elif a[j]>=a[k]>=a[l] or a[j]<=a[k]<=a[l]: c+=0 elif a[i]>=a[j]>=a[l] or a[i]<=a[j]<=a[l]: c+=0 elif a[i]>=a[k]>=a[l] or a[i]<=a[k]<=a[l]: c+=0 else: c+=1 print(c) t-=1 ```
108,104
Provide tags and a correct Python 3 solution for this coding contest problem. Suppose you have two points p = (x_p, y_p) and q = (x_q, y_q). Let's denote the Manhattan distance between them as d(p, q) = |x_p - x_q| + |y_p - y_q|. Let's say that three points p, q, r form a bad triple if d(p, r) = d(p, q) + d(q, r). Let's say that an array b_1, b_2, ..., b_m is good if it is impossible to choose three distinct indices i, j, k such that the points (b_i, i), (b_j, j) and (b_k, k) form a bad triple. You are given an array a_1, a_2, ..., a_n. Calculate the number of good subarrays of a. A subarray of the array a is the array a_l, a_{l + 1}, ..., a_r for some 1 ≀ l ≀ r ≀ n. Note that, according to the definition, subarrays of length 1 and 2 are good. Input The first line contains one integer t (1 ≀ t ≀ 5000) β€” the number of test cases. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of array a. The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). It's guaranteed that the sum of n doesn't exceed 2 β‹… 10^5. Output For each test case, print the number of good subarrays of array a. Example Input 3 4 2 4 1 3 5 6 9 1 9 6 2 13 37 Output 10 12 3 Note In the first test case, it can be proven that any subarray of a is good. For example, subarray [a_2, a_3, a_4] is good since it contains only three elements and: * d((a_2, 2), (a_4, 4)) = |4 - 3| + |2 - 4| = 3 < d((a_2, 2), (a_3, 3)) + d((a_3, 3), (a_4, 4)) = 3 + 1 + 2 + 1 = 7; * d((a_2, 2), (a_3, 3)) < d((a_2, 2), (a_4, 4)) + d((a_4, 4), (a_3, 3)); * d((a_3, 3), (a_4, 4)) < d((a_3, 3), (a_2, 2)) + d((a_2, 2), (a_4, 4)); In the second test case, for example, subarray [a_1, a_2, a_3, a_4] is not good, since it contains a bad triple (a_1, 1), (a_2, 2), (a_4, 4): * d((a_1, 1), (a_4, 4)) = |6 - 9| + |1 - 4| = 6; * d((a_1, 1), (a_2, 2)) = |6 - 9| + |1 - 2| = 4; * d((a_2, 2), (a_4, 4)) = |9 - 9| + |2 - 4| = 2; So, d((a_1, 1), (a_4, 4)) = d((a_1, 1), (a_2, 2)) + d((a_2, 2), (a_4, 4)). Tags: brute force, geometry, greedy, implementation Correct Solution: ``` from collections import * import os, sys from io import BytesIO, IOBase from itertools import combinations class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, 8192)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, 8192)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") inp = lambda dtype: dtype(input().strip()) inp_d = lambda dtype: [dtype(x) for x in input().split()] inp_2d = lambda dtype, n: [inp(dtype) for _ in range(n)] inp_2ds = lambda dtype, n: [inp_d(dtype) for _ in range(n)] inp_enu = lambda dtype: [(i, x) for i, x in enumerate(inp_d(dtype))] inp_enus = lambda dtype, n: [[i, inp_d(dtype)] for i in range(n)] ceil1 = lambda a, b: (a + b - 1) // b for _ in range(inp(int)): n, a = inp(int), inp_d(int) good = 2 * n - 1 for i in range(2, n): good += not (min(a[i - 2], a[i]) <= a[i - 1] <= max(a[i], a[i - 2])) for i in range(4, n + 1): bad = False for com in combinations(a[i - 4:i], 3): bad |= min(com[0], com[2]) <= com[1] <= max(com[2], com[0]) good += 1 - bad print(good) ```
108,105
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Suppose you have two points p = (x_p, y_p) and q = (x_q, y_q). Let's denote the Manhattan distance between them as d(p, q) = |x_p - x_q| + |y_p - y_q|. Let's say that three points p, q, r form a bad triple if d(p, r) = d(p, q) + d(q, r). Let's say that an array b_1, b_2, ..., b_m is good if it is impossible to choose three distinct indices i, j, k such that the points (b_i, i), (b_j, j) and (b_k, k) form a bad triple. You are given an array a_1, a_2, ..., a_n. Calculate the number of good subarrays of a. A subarray of the array a is the array a_l, a_{l + 1}, ..., a_r for some 1 ≀ l ≀ r ≀ n. Note that, according to the definition, subarrays of length 1 and 2 are good. Input The first line contains one integer t (1 ≀ t ≀ 5000) β€” the number of test cases. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of array a. The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). It's guaranteed that the sum of n doesn't exceed 2 β‹… 10^5. Output For each test case, print the number of good subarrays of array a. Example Input 3 4 2 4 1 3 5 6 9 1 9 6 2 13 37 Output 10 12 3 Note In the first test case, it can be proven that any subarray of a is good. For example, subarray [a_2, a_3, a_4] is good since it contains only three elements and: * d((a_2, 2), (a_4, 4)) = |4 - 3| + |2 - 4| = 3 < d((a_2, 2), (a_3, 3)) + d((a_3, 3), (a_4, 4)) = 3 + 1 + 2 + 1 = 7; * d((a_2, 2), (a_3, 3)) < d((a_2, 2), (a_4, 4)) + d((a_4, 4), (a_3, 3)); * d((a_3, 3), (a_4, 4)) < d((a_3, 3), (a_2, 2)) + d((a_2, 2), (a_4, 4)); In the second test case, for example, subarray [a_1, a_2, a_3, a_4] is not good, since it contains a bad triple (a_1, 1), (a_2, 2), (a_4, 4): * d((a_1, 1), (a_4, 4)) = |6 - 9| + |1 - 4| = 6; * d((a_1, 1), (a_2, 2)) = |6 - 9| + |1 - 2| = 4; * d((a_2, 2), (a_4, 4)) = |9 - 9| + |2 - 4| = 2; So, d((a_1, 1), (a_4, 4)) = d((a_1, 1), (a_2, 2)) + d((a_2, 2), (a_4, 4)). Submitted Solution: ``` from collections import * import os, sys from io import BytesIO, IOBase from itertools import combinations class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, 8192)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, 8192)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") inp = lambda dtype: dtype(input().strip()) inp_d = lambda dtype: [dtype(x) for x in input().split()] inp_2d = lambda dtype, n: [inp(dtype) for _ in range(n)] inp_2ds = lambda dtype, n: [inp_d(dtype) for _ in range(n)] inp_enu = lambda dtype: [(i, x) for i, x in enumerate(inp_d(dtype))] inp_enus = lambda dtype, n: [[i, inp_d(dtype)] for i in range(n)] ceil1 = lambda a, b: (a + b - 1) // b for _ in range(inp(int)): n, a = inp(int), inp_d(int) good = 2 * n - 1 for i in range(2, n): good += not (a[i - 2] >= a[i - 1] >= a[i] or a[i - 2] <= a[i - 1] <= a[i]) for i in range(4, n + 1): bad = False for com in combinations(a[i - 4:i], 3): bad |= com[0] >= com[1] >= com[2] or com[0] <= com[1] <= com[2] good += 1 - bad print(good) ``` Yes
108,106
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Suppose you have two points p = (x_p, y_p) and q = (x_q, y_q). Let's denote the Manhattan distance between them as d(p, q) = |x_p - x_q| + |y_p - y_q|. Let's say that three points p, q, r form a bad triple if d(p, r) = d(p, q) + d(q, r). Let's say that an array b_1, b_2, ..., b_m is good if it is impossible to choose three distinct indices i, j, k such that the points (b_i, i), (b_j, j) and (b_k, k) form a bad triple. You are given an array a_1, a_2, ..., a_n. Calculate the number of good subarrays of a. A subarray of the array a is the array a_l, a_{l + 1}, ..., a_r for some 1 ≀ l ≀ r ≀ n. Note that, according to the definition, subarrays of length 1 and 2 are good. Input The first line contains one integer t (1 ≀ t ≀ 5000) β€” the number of test cases. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of array a. The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). It's guaranteed that the sum of n doesn't exceed 2 β‹… 10^5. Output For each test case, print the number of good subarrays of array a. Example Input 3 4 2 4 1 3 5 6 9 1 9 6 2 13 37 Output 10 12 3 Note In the first test case, it can be proven that any subarray of a is good. For example, subarray [a_2, a_3, a_4] is good since it contains only three elements and: * d((a_2, 2), (a_4, 4)) = |4 - 3| + |2 - 4| = 3 < d((a_2, 2), (a_3, 3)) + d((a_3, 3), (a_4, 4)) = 3 + 1 + 2 + 1 = 7; * d((a_2, 2), (a_3, 3)) < d((a_2, 2), (a_4, 4)) + d((a_4, 4), (a_3, 3)); * d((a_3, 3), (a_4, 4)) < d((a_3, 3), (a_2, 2)) + d((a_2, 2), (a_4, 4)); In the second test case, for example, subarray [a_1, a_2, a_3, a_4] is not good, since it contains a bad triple (a_1, 1), (a_2, 2), (a_4, 4): * d((a_1, 1), (a_4, 4)) = |6 - 9| + |1 - 4| = 6; * d((a_1, 1), (a_2, 2)) = |6 - 9| + |1 - 2| = 4; * d((a_2, 2), (a_4, 4)) = |9 - 9| + |2 - 4| = 2; So, d((a_1, 1), (a_4, 4)) = d((a_1, 1), (a_2, 2)) + d((a_2, 2), (a_4, 4)). Submitted Solution: ``` from copy import * import sys def init(N,node,A,unit,func): n=1 while n<N: n<<=1 for i in range(n*2-1): if len(node)<=i: node.append(deepcopy(unit)) else: node[i]=deepcopy(unit) for i in range(len(A)): node[n-1+i]=deepcopy(A[i]) for i in range(n-2,-1,-1): node[i]=func(node[(i<<1)+1],node[(i<<1)+2]) node.append(func) node.append(unit) node.append(n) def upd(node,x,a): y=node[-1]+x node[y-1]=a while y>1: y=y>>1 node[y-1]=node[-3](node[(y<<1)-1],node[y<<1]) def query(node,l,r): x,y=l,r z=node[-1]-1 rr=deepcopy(node[-2]) rl=deepcopy(node[-2]) while True: if x==y: return node[-3](rl,rr) if x&1: rl=node[-3](rl,node[x+z]) x+=1 if y&1: rr=node[-3](node[y+z-1],rr) if z==0: return node[-3](rl,rr) x>>=1 y>>=1 z>>=1 def bis_min_k(node,k,cond): x=k+1 while True: if node[-1]<=x: return x-node[-1] if cond(node[(x<<1)-1]): x=x<<1 else: x=(x<<1)+1 def bis_min(node,l,r,cond): x,y=l,r z=node[-1]-1 for i in range(30): if x+(1<<i)>y: break if x&(1<<i): if cond(node[z+(x>>i)]): return bis_min_k(node,z+(x>>i),cond) x+=(1<<i) if z==0: break z>>=1 for i in range(29,-1,-1): if i and ((node[-1]-1)>>(i-1))==0: continue if x+(1<<i)>y: continue if (y-x)&(1<<i): if cond(node[((node[-1]-1)>>i)+(x>>i)]): return bis_min_k(node,((node[-1]-1)>>i)+(x>>i),cond) x+=(1<<i) return node[-1] input=sys.stdin.buffer.readline INF=(10**9)+7 for t in range(int(input())): sega=[] segb=[] segarev=[] segbrev=[] N=int(input()) A=list(map(int,input().split())) init(N,sega,A[:],0,lambda x,y:max(x,y)) init(N,segb,A[:],INF,lambda x,y:min(x,y)) init(N,segarev,A[::-1],0,lambda x,y:max(x,y)) init(N,segbrev,A[::-1],INF,lambda x,y:min(x,y)) X=[INF]*N for i in range(N): ra=bis_min(sega,i+1,N,lambda x:x>=A[i]) rb=bis_min(segb,i+1,N,lambda x:x<=A[i]) la=N-1-bis_min(segarev,N-i,N,lambda x:x>=A[i]) lb=N-1-bis_min(segbrev,N-i,N,lambda x:x<=A[i]) if 0<=la<N and 0<=rb<N: X[la]=min(X[la],rb) if 0<=lb<N and 0<=ra<N: X[lb]=min(X[lb],ra) seg=[] init(N,seg,[],INF,lambda x,y:min(x,y)) l=0 ANS=0 for r in range(N): upd(seg,r,X[r]) while seg[0]<=r: upd(seg,l,INF) l+=1 ANS+=r-l+1 print(ANS) ``` Yes
108,107
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Suppose you have two points p = (x_p, y_p) and q = (x_q, y_q). Let's denote the Manhattan distance between them as d(p, q) = |x_p - x_q| + |y_p - y_q|. Let's say that three points p, q, r form a bad triple if d(p, r) = d(p, q) + d(q, r). Let's say that an array b_1, b_2, ..., b_m is good if it is impossible to choose three distinct indices i, j, k such that the points (b_i, i), (b_j, j) and (b_k, k) form a bad triple. You are given an array a_1, a_2, ..., a_n. Calculate the number of good subarrays of a. A subarray of the array a is the array a_l, a_{l + 1}, ..., a_r for some 1 ≀ l ≀ r ≀ n. Note that, according to the definition, subarrays of length 1 and 2 are good. Input The first line contains one integer t (1 ≀ t ≀ 5000) β€” the number of test cases. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of array a. The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). It's guaranteed that the sum of n doesn't exceed 2 β‹… 10^5. Output For each test case, print the number of good subarrays of array a. Example Input 3 4 2 4 1 3 5 6 9 1 9 6 2 13 37 Output 10 12 3 Note In the first test case, it can be proven that any subarray of a is good. For example, subarray [a_2, a_3, a_4] is good since it contains only three elements and: * d((a_2, 2), (a_4, 4)) = |4 - 3| + |2 - 4| = 3 < d((a_2, 2), (a_3, 3)) + d((a_3, 3), (a_4, 4)) = 3 + 1 + 2 + 1 = 7; * d((a_2, 2), (a_3, 3)) < d((a_2, 2), (a_4, 4)) + d((a_4, 4), (a_3, 3)); * d((a_3, 3), (a_4, 4)) < d((a_3, 3), (a_2, 2)) + d((a_2, 2), (a_4, 4)); In the second test case, for example, subarray [a_1, a_2, a_3, a_4] is not good, since it contains a bad triple (a_1, 1), (a_2, 2), (a_4, 4): * d((a_1, 1), (a_4, 4)) = |6 - 9| + |1 - 4| = 6; * d((a_1, 1), (a_2, 2)) = |6 - 9| + |1 - 2| = 4; * d((a_2, 2), (a_4, 4)) = |9 - 9| + |2 - 4| = 2; So, d((a_1, 1), (a_4, 4)) = d((a_1, 1), (a_2, 2)) + d((a_2, 2), (a_4, 4)). Submitted Solution: ``` #DaRk DeveLopeR import sys #taking input as string input = lambda: sys.stdin.readline().rstrip("\r\n") inp = lambda: list(map(int,sys.stdin.readline().rstrip("\r\n").split())) mod = 10**9+7; Mod = 998244353; INF = float('inf') #______________________________________________________________________________________________________ import math from bisect import * from heapq import * from collections import defaultdict as dd from collections import OrderedDict as odict from collections import Counter as cc from collections import deque from itertools import groupby sys.setrecursionlimit(20*20*20*20+10) #this is must for dfs def good(arr): n=len(arr) for i in range(n): for j in range(i+1,n): for k in range(j+1,n): if max(arr[i],arr[k])>=arr[j] and min(arr[i],arr[k])<=arr[j]: return False return True def solve(): n=takein() arr=takeiar() if n==1: print(1) return if n==2: print(3) return ans=n+n-1 for j in range(0,n-2): if good(arr[j:j+3]): ans+=1 if n==3: print(ans) return for j in range(0,n-3): if good(arr[j:j+4]): ans+=1 print(ans) return def main(): global tt if not ONLINE_JUDGE: sys.stdin = open("input.txt","r") sys.stdout = open("output.txt","w") t = 1 t = takein() #t = 1 for tt in range(1,t + 1): solve() if not ONLINE_JUDGE: print("Time Elapsed :",time.time() - start_time,"seconds") sys.stdout.close() #---------------------- USER DEFINED INPUT FUNCTIONS ----------------------# def takein(): return (int(sys.stdin.readline().rstrip("\r\n"))) # input the string def takesr(): return (sys.stdin.readline().rstrip("\r\n")) # input int array def takeiar(): return (list(map(int, sys.stdin.readline().rstrip("\r\n").split()))) # input string array def takesar(): return (list(map(str, sys.stdin.readline().rstrip("\r\n").split()))) # innut values for the diffrent variables def takeivr(): return (map(int, sys.stdin.readline().rstrip("\r\n").split())) def takesvr(): return (map(str, sys.stdin.readline().rstrip("\r\n").split())) #------------------ USER DEFINED PROGRAMMING FUNCTIONS ------------------# def ispalindrome(s): return s==s[::-1] def invert(bit_s): # convert binary string # into integer temp = int(bit_s, 2) # applying Ex-or operator # b/w 10 and 31 inverse_s = temp ^ (2 ** (len(bit_s) + 1) - 1) # convert the integer result # into binary result and then # slicing of the '0b1' # binary indicator rslt = bin(inverse_s)[3 : ] return str(rslt) def counter(a): q = [0] * max(a) for i in range(len(a)): q[a[i] - 1] = q[a[i] - 1] + 1 return(q) def counter_elements(a): q = dict() for i in range(len(a)): if a[i] not in q: q[a[i]] = 0 q[a[i]] = q[a[i]] + 1 return(q) def string_counter(a): q = [0] * 26 for i in range(len(a)): q[ord(a[i]) - 97] = q[ord(a[i]) - 97] + 1 return(q) def factorial(n,m = 1000000007): q = 1 for i in range(n): q = (q * (i + 1)) % m return(q) def factors(n): q = [] for i in range(1,int(n ** 0.5) + 1): if n % i == 0: q.append(i); q.append(n // i) return(list(sorted(list(set(q))))) def prime_factors(n): q = [] while n % 2 == 0: q.append(2); n = n // 2 for i in range(3,int(n ** 0.5) + 1,2): while n % i == 0: q.append(i); n = n // i if n > 2: q.append(n) return(list(sorted(q))) def transpose(a): n,m = len(a),len(a[0]) b = [[0] * n for i in range(m)] for i in range(m): for j in range(n): b[i][j] = a[j][i] return(b) def power_two(x): return (x and (not(x & (x - 1)))) def ceil(a, b): return -(-a // b) def seive(n): a = [1] prime = [True for i in range(n+1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p ** 2,n + 1, p): prime[i] = False p = p + 1 for p in range(2,n + 1): if prime[p]: a.append(p) return(a) def pref(li): pref_sum = [0] for i in li: pref_sum.append(pref_sum[-1]+i) return pref_sum def kadane(x): # maximum sum contiguous subarray sum_so_far = 0 current_sum = 0 for i in x: current_sum += i if current_sum < 0: current_sum = 0 else: sum_so_far = max(sum_so_far, current_sum) return sum_so_far def binary_search(li, val): # print(lb, ub, li) ans = -1 lb = 0 ub = len(li)-1 while (lb <= ub): mid = (lb+ub) // 2 # print('mid is',mid, li[mid]) if li[mid] > val: ub = mid-1 elif val > li[mid]: lb = mid+1 else: ans = mid # return index break return ans def upper_bound(li, num): answer = -1 start = 0 end = len(li)-1 while (start <= end): middle = (end+start) // 2 if li[middle] <= num: answer = middle start = middle+1 else: end = middle-1 return answer # max index where x is not greater than num def lower_bound(li, num): answer = -1 start = 0 end = len(li)-1 while (start <= end): middle = (end+start) // 2 if li[middle] >= num: answer = middle end = middle-1 else: start = middle+1 return answer # min index where x is not less than num #-----------------------------------------------------------------------# ONLINE_JUDGE = __debug__ if ONLINE_JUDGE: input = sys.stdin.readline main() ``` Yes
108,108
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Suppose you have two points p = (x_p, y_p) and q = (x_q, y_q). Let's denote the Manhattan distance between them as d(p, q) = |x_p - x_q| + |y_p - y_q|. Let's say that three points p, q, r form a bad triple if d(p, r) = d(p, q) + d(q, r). Let's say that an array b_1, b_2, ..., b_m is good if it is impossible to choose three distinct indices i, j, k such that the points (b_i, i), (b_j, j) and (b_k, k) form a bad triple. You are given an array a_1, a_2, ..., a_n. Calculate the number of good subarrays of a. A subarray of the array a is the array a_l, a_{l + 1}, ..., a_r for some 1 ≀ l ≀ r ≀ n. Note that, according to the definition, subarrays of length 1 and 2 are good. Input The first line contains one integer t (1 ≀ t ≀ 5000) β€” the number of test cases. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of array a. The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). It's guaranteed that the sum of n doesn't exceed 2 β‹… 10^5. Output For each test case, print the number of good subarrays of array a. Example Input 3 4 2 4 1 3 5 6 9 1 9 6 2 13 37 Output 10 12 3 Note In the first test case, it can be proven that any subarray of a is good. For example, subarray [a_2, a_3, a_4] is good since it contains only three elements and: * d((a_2, 2), (a_4, 4)) = |4 - 3| + |2 - 4| = 3 < d((a_2, 2), (a_3, 3)) + d((a_3, 3), (a_4, 4)) = 3 + 1 + 2 + 1 = 7; * d((a_2, 2), (a_3, 3)) < d((a_2, 2), (a_4, 4)) + d((a_4, 4), (a_3, 3)); * d((a_3, 3), (a_4, 4)) < d((a_3, 3), (a_2, 2)) + d((a_2, 2), (a_4, 4)); In the second test case, for example, subarray [a_1, a_2, a_3, a_4] is not good, since it contains a bad triple (a_1, 1), (a_2, 2), (a_4, 4): * d((a_1, 1), (a_4, 4)) = |6 - 9| + |1 - 4| = 6; * d((a_1, 1), (a_2, 2)) = |6 - 9| + |1 - 2| = 4; * d((a_2, 2), (a_4, 4)) = |9 - 9| + |2 - 4| = 2; So, d((a_1, 1), (a_4, 4)) = d((a_1, 1), (a_2, 2)) + d((a_2, 2), (a_4, 4)). Submitted Solution: ``` for _ in range(int(input())): n = int(input() ) a = list(map(int, input().split())) #n, a, b = map(int, input().split()) #s = input() h = [] # max 4 points? i, j = 0, 1 ans = 1 while j < n: d = [] if i+3 < j: i += 1 notgood = True while i+1 < j and notgood: # if i+1 == j - stop notgood = False bad = i for x in range(i, j+1): for y in range(x+1, j+1): for z in range(y+1, j+1): d = sorted([abs(x-y)+abs(a[x]-a[y]), abs(y-z)+abs(a[y]-a[z]), abs(z-x)+abs(a[z]-a[x])]) if d[0] + d[1] == d[2]: notgood = True bad = x if notgood: i = bad + 1 ans += j-i+1 j += 1 print(ans) ``` Yes
108,109
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Suppose you have two points p = (x_p, y_p) and q = (x_q, y_q). Let's denote the Manhattan distance between them as d(p, q) = |x_p - x_q| + |y_p - y_q|. Let's say that three points p, q, r form a bad triple if d(p, r) = d(p, q) + d(q, r). Let's say that an array b_1, b_2, ..., b_m is good if it is impossible to choose three distinct indices i, j, k such that the points (b_i, i), (b_j, j) and (b_k, k) form a bad triple. You are given an array a_1, a_2, ..., a_n. Calculate the number of good subarrays of a. A subarray of the array a is the array a_l, a_{l + 1}, ..., a_r for some 1 ≀ l ≀ r ≀ n. Note that, according to the definition, subarrays of length 1 and 2 are good. Input The first line contains one integer t (1 ≀ t ≀ 5000) β€” the number of test cases. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of array a. The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). It's guaranteed that the sum of n doesn't exceed 2 β‹… 10^5. Output For each test case, print the number of good subarrays of array a. Example Input 3 4 2 4 1 3 5 6 9 1 9 6 2 13 37 Output 10 12 3 Note In the first test case, it can be proven that any subarray of a is good. For example, subarray [a_2, a_3, a_4] is good since it contains only three elements and: * d((a_2, 2), (a_4, 4)) = |4 - 3| + |2 - 4| = 3 < d((a_2, 2), (a_3, 3)) + d((a_3, 3), (a_4, 4)) = 3 + 1 + 2 + 1 = 7; * d((a_2, 2), (a_3, 3)) < d((a_2, 2), (a_4, 4)) + d((a_4, 4), (a_3, 3)); * d((a_3, 3), (a_4, 4)) < d((a_3, 3), (a_2, 2)) + d((a_2, 2), (a_4, 4)); In the second test case, for example, subarray [a_1, a_2, a_3, a_4] is not good, since it contains a bad triple (a_1, 1), (a_2, 2), (a_4, 4): * d((a_1, 1), (a_4, 4)) = |6 - 9| + |1 - 4| = 6; * d((a_1, 1), (a_2, 2)) = |6 - 9| + |1 - 2| = 4; * d((a_2, 2), (a_4, 4)) = |9 - 9| + |2 - 4| = 2; So, d((a_1, 1), (a_4, 4)) = d((a_1, 1), (a_2, 2)) + d((a_2, 2), (a_4, 4)). Submitted Solution: ``` import os import sys from io import BytesIO, IOBase import math from decimal import Decimal from decimal import * from collections import defaultdict, deque import heapq from decimal import Decimal getcontext().prec = 25 abcd='abcdefghijklmnopqrstuvwxyz' MOD = 1000000007 BUFSIZE = 8192 from bisect import bisect_left, bisect_right class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # for _ in range(int(input())): # n, k = map(int, input().split(" ")) # list(map(int, input().split(" "))) for _ in range(int(input())): n = int(input()) l = list(map(int, input().split(" "))) ans = 2*n -1 for i in range(n-2): if l[i+1] not in range(min(l[i], l[i+2]),max(l[i], l[i+2])+1): ans+=1 for i in range(n-3): if l[i+1] not in range(min(l[i], l[i+3]),max(l[i], l[i+3])+1) and l[i+2] not in range(min(l[i], l[i+3]),max(l[i], l[i+3])+1): ans+=1 print(ans) ``` No
108,110
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Suppose you have two points p = (x_p, y_p) and q = (x_q, y_q). Let's denote the Manhattan distance between them as d(p, q) = |x_p - x_q| + |y_p - y_q|. Let's say that three points p, q, r form a bad triple if d(p, r) = d(p, q) + d(q, r). Let's say that an array b_1, b_2, ..., b_m is good if it is impossible to choose three distinct indices i, j, k such that the points (b_i, i), (b_j, j) and (b_k, k) form a bad triple. You are given an array a_1, a_2, ..., a_n. Calculate the number of good subarrays of a. A subarray of the array a is the array a_l, a_{l + 1}, ..., a_r for some 1 ≀ l ≀ r ≀ n. Note that, according to the definition, subarrays of length 1 and 2 are good. Input The first line contains one integer t (1 ≀ t ≀ 5000) β€” the number of test cases. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of array a. The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). It's guaranteed that the sum of n doesn't exceed 2 β‹… 10^5. Output For each test case, print the number of good subarrays of array a. Example Input 3 4 2 4 1 3 5 6 9 1 9 6 2 13 37 Output 10 12 3 Note In the first test case, it can be proven that any subarray of a is good. For example, subarray [a_2, a_3, a_4] is good since it contains only three elements and: * d((a_2, 2), (a_4, 4)) = |4 - 3| + |2 - 4| = 3 < d((a_2, 2), (a_3, 3)) + d((a_3, 3), (a_4, 4)) = 3 + 1 + 2 + 1 = 7; * d((a_2, 2), (a_3, 3)) < d((a_2, 2), (a_4, 4)) + d((a_4, 4), (a_3, 3)); * d((a_3, 3), (a_4, 4)) < d((a_3, 3), (a_2, 2)) + d((a_2, 2), (a_4, 4)); In the second test case, for example, subarray [a_1, a_2, a_3, a_4] is not good, since it contains a bad triple (a_1, 1), (a_2, 2), (a_4, 4): * d((a_1, 1), (a_4, 4)) = |6 - 9| + |1 - 4| = 6; * d((a_1, 1), (a_2, 2)) = |6 - 9| + |1 - 2| = 4; * d((a_2, 2), (a_4, 4)) = |9 - 9| + |2 - 4| = 2; So, d((a_1, 1), (a_4, 4)) = d((a_1, 1), (a_2, 2)) + d((a_2, 2), (a_4, 4)). Submitted Solution: ``` def d(p1,p2): return abs(p1[0]-p2[0])+abs(p1[1]-p2[1]) for _ in range(int(input())): n = int(input()) a = [int(x) for x in input().split()] sol = 0 for i in range(n-2): done = False p1 = [a[i+0],1] p2 = [a[i+1],2] p3 = [a[i+2],3] ds = [d(p1,p2),d(p2,p3),d(p1,p3)] ds = sorted(ds) if ds[2] != ds[1] + ds[0]: sol += 1 if i < n-3: al = a[i:i+4] if len(set(al)) == 4: if (a[i+1] == min(al) and a[i+2] == max(al)) or (a[i+1] == max(al) and a[i+2] == min(al)): sol += 1 print(sol+n-1+n) ``` No
108,111
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Suppose you have two points p = (x_p, y_p) and q = (x_q, y_q). Let's denote the Manhattan distance between them as d(p, q) = |x_p - x_q| + |y_p - y_q|. Let's say that three points p, q, r form a bad triple if d(p, r) = d(p, q) + d(q, r). Let's say that an array b_1, b_2, ..., b_m is good if it is impossible to choose three distinct indices i, j, k such that the points (b_i, i), (b_j, j) and (b_k, k) form a bad triple. You are given an array a_1, a_2, ..., a_n. Calculate the number of good subarrays of a. A subarray of the array a is the array a_l, a_{l + 1}, ..., a_r for some 1 ≀ l ≀ r ≀ n. Note that, according to the definition, subarrays of length 1 and 2 are good. Input The first line contains one integer t (1 ≀ t ≀ 5000) β€” the number of test cases. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of array a. The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). It's guaranteed that the sum of n doesn't exceed 2 β‹… 10^5. Output For each test case, print the number of good subarrays of array a. Example Input 3 4 2 4 1 3 5 6 9 1 9 6 2 13 37 Output 10 12 3 Note In the first test case, it can be proven that any subarray of a is good. For example, subarray [a_2, a_3, a_4] is good since it contains only three elements and: * d((a_2, 2), (a_4, 4)) = |4 - 3| + |2 - 4| = 3 < d((a_2, 2), (a_3, 3)) + d((a_3, 3), (a_4, 4)) = 3 + 1 + 2 + 1 = 7; * d((a_2, 2), (a_3, 3)) < d((a_2, 2), (a_4, 4)) + d((a_4, 4), (a_3, 3)); * d((a_3, 3), (a_4, 4)) < d((a_3, 3), (a_2, 2)) + d((a_2, 2), (a_4, 4)); In the second test case, for example, subarray [a_1, a_2, a_3, a_4] is not good, since it contains a bad triple (a_1, 1), (a_2, 2), (a_4, 4): * d((a_1, 1), (a_4, 4)) = |6 - 9| + |1 - 4| = 6; * d((a_1, 1), (a_2, 2)) = |6 - 9| + |1 - 2| = 4; * d((a_2, 2), (a_4, 4)) = |9 - 9| + |2 - 4| = 2; So, d((a_1, 1), (a_4, 4)) = d((a_1, 1), (a_2, 2)) + d((a_2, 2), (a_4, 4)). Submitted Solution: ``` from sys import stdin , stdout from collections import defaultdict import math def get_list(): return list(map(int, stdin.readline().strip().split())) def get_int(): return int(stdin.readline()) def get_ints(): return map(int, stdin.readline().strip().split()) def get_string(): return stdin.readline() def printn(n) : stdout.write(str(n) + "\n") def increasingSubseq(a, k, dp): n = len(a) for i in range(n) : dp[0][i] = i for l in range(1,k): for i in range(l,n): for j in range(l-1,i): if a[j] <= a[i]: dp[l][i] = min(dp[l][i],dp[l-1][j]) return def decreasingSubseq(a, k, dp): n = len(a) for i in range(n) : dp[0][i] = i for l in range(1,k): for i in range(l,n): for j in range(l-1,i): if a[j] >= a[i]: dp[l][i] = min(dp[l][i],dp[l-1][j]) return def solve() : n = get_int() a = get_list() ans = 0 mx = 200002 dp1 = [[mx for i in range(n)] for i in range(3)] dp2 = [[mx for i in range(n)] for i in range(3)] increasingSubseq(a,3,dp1) decreasingSubseq(a,3,dp2) check = [] for i in range(n): if dp1[2][i] != dp2[2][i] : if dp1[2][i] == mx: check.append((dp2[2][i], -1)) elif dp2[2][i] == mx: check.append((dp1[2][i], -1)) else : check.append((dp1[2][i], dp2[2][i])) else : check.append((dp1[2][i], dp2[2][i])) for i in range(n): for j in range(i,n): if i not in check[j]: ans += 1 else : break printn(ans) if __name__ == "__main__" : t = get_int() # t = 1 while t: t-=1 solve() ``` No
108,112
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Suppose you have two points p = (x_p, y_p) and q = (x_q, y_q). Let's denote the Manhattan distance between them as d(p, q) = |x_p - x_q| + |y_p - y_q|. Let's say that three points p, q, r form a bad triple if d(p, r) = d(p, q) + d(q, r). Let's say that an array b_1, b_2, ..., b_m is good if it is impossible to choose three distinct indices i, j, k such that the points (b_i, i), (b_j, j) and (b_k, k) form a bad triple. You are given an array a_1, a_2, ..., a_n. Calculate the number of good subarrays of a. A subarray of the array a is the array a_l, a_{l + 1}, ..., a_r for some 1 ≀ l ≀ r ≀ n. Note that, according to the definition, subarrays of length 1 and 2 are good. Input The first line contains one integer t (1 ≀ t ≀ 5000) β€” the number of test cases. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of array a. The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^9). It's guaranteed that the sum of n doesn't exceed 2 β‹… 10^5. Output For each test case, print the number of good subarrays of array a. Example Input 3 4 2 4 1 3 5 6 9 1 9 6 2 13 37 Output 10 12 3 Note In the first test case, it can be proven that any subarray of a is good. For example, subarray [a_2, a_3, a_4] is good since it contains only three elements and: * d((a_2, 2), (a_4, 4)) = |4 - 3| + |2 - 4| = 3 < d((a_2, 2), (a_3, 3)) + d((a_3, 3), (a_4, 4)) = 3 + 1 + 2 + 1 = 7; * d((a_2, 2), (a_3, 3)) < d((a_2, 2), (a_4, 4)) + d((a_4, 4), (a_3, 3)); * d((a_3, 3), (a_4, 4)) < d((a_3, 3), (a_2, 2)) + d((a_2, 2), (a_4, 4)); In the second test case, for example, subarray [a_1, a_2, a_3, a_4] is not good, since it contains a bad triple (a_1, 1), (a_2, 2), (a_4, 4): * d((a_1, 1), (a_4, 4)) = |6 - 9| + |1 - 4| = 6; * d((a_1, 1), (a_2, 2)) = |6 - 9| + |1 - 2| = 4; * d((a_2, 2), (a_4, 4)) = |9 - 9| + |2 - 4| = 2; So, d((a_1, 1), (a_4, 4)) = d((a_1, 1), (a_2, 2)) + d((a_2, 2), (a_4, 4)). Submitted Solution: ``` import sys input = sys.stdin.readline def main(): t = int(input()); INF = 1001001001 for _ in range(t): n = int(input()) A = list(map(int,input().split())) ans = 0 for i in range(n): S = set([]) mn1 = INF mn2 = INF for j in range(i,n): if A[j] >= mn2: break if j - i == 2 and A[j] == A[j-1]: break if A[j] > mn1: mn2 = min(mn2,A[j]) if A[j] < mn1: mn1 = A[j] if A[j] in S: mn2 = 0 S.add(A[j]) #print(i,j) ans += 1 print(ans) if __name__ == "__main__": main() ``` No
108,113
Provide tags and a correct Python 3 solution for this coding contest problem. The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n Γ— n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: * Elements of the main diagonal. * Elements of the secondary diagonal. * Elements of the "middle" row β€” the row which has exactly <image> rows above it and the same number of rows below it. * Elements of the "middle" column β€” the column that has exactly <image> columns to the left of it and the same number of columns to the right of it. <image> The figure shows a 5 Γ— 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix. Input The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: * 1 ≀ n ≀ 5 The input limitations for getting 100 points are: * 1 ≀ n ≀ 101 Output Print a single integer β€” the sum of good matrix elements. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 45 Input 5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Output 17 Note In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure. Tags: implementation Correct Solution: ``` n = int(input()) matrix = [[0] * n] * n for i in range(n): a = list(map(int, input().split(' '))) matrix[i] = a ans = 0 for i in range(n): for j in range(n): if i == n // 2 or j == n // 2 or i == j or i + j == n - 1: ans += matrix[i][j] print(ans) ```
108,114
Provide tags and a correct Python 3 solution for this coding contest problem. The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n Γ— n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: * Elements of the main diagonal. * Elements of the secondary diagonal. * Elements of the "middle" row β€” the row which has exactly <image> rows above it and the same number of rows below it. * Elements of the "middle" column β€” the column that has exactly <image> columns to the left of it and the same number of columns to the right of it. <image> The figure shows a 5 Γ— 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix. Input The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: * 1 ≀ n ≀ 5 The input limitations for getting 100 points are: * 1 ≀ n ≀ 101 Output Print a single integer β€” the sum of good matrix elements. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 45 Input 5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Output 17 Note In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure. Tags: implementation Correct Solution: ``` n=int(input()) if n==1: print(int(input())) else: g=[] for i in range(n): g.append(list(map(int,input().split()))) x=n//2 count=sum(g[x]) for i in range(n): count+=g[i][x] count+=g[i][i]+g[i][n-1-i] count-=g[x][x]*3 print(count) ```
108,115
Provide tags and a correct Python 3 solution for this coding contest problem. The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n Γ— n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: * Elements of the main diagonal. * Elements of the secondary diagonal. * Elements of the "middle" row β€” the row which has exactly <image> rows above it and the same number of rows below it. * Elements of the "middle" column β€” the column that has exactly <image> columns to the left of it and the same number of columns to the right of it. <image> The figure shows a 5 Γ— 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix. Input The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: * 1 ≀ n ≀ 5 The input limitations for getting 100 points are: * 1 ≀ n ≀ 101 Output Print a single integer β€” the sum of good matrix elements. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 45 Input 5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Output 17 Note In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure. Tags: implementation Correct Solution: ``` n = int(input()) a = [list(map(int, input().split())) for _ in range(n)] s1 = sum(a[i][i] for i in range(n)) s2 = sum(a[i][n - 1 - i] for i in range(n)) s3 = sum(a[i][n // 2] for i in range(n)) s4 = sum(a[n // 2][i] for i in range(n)) print(s1 + s2 + s3 + s4 - 3 * a[n //2][n // 2]) ```
108,116
Provide tags and a correct Python 3 solution for this coding contest problem. The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n Γ— n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: * Elements of the main diagonal. * Elements of the secondary diagonal. * Elements of the "middle" row β€” the row which has exactly <image> rows above it and the same number of rows below it. * Elements of the "middle" column β€” the column that has exactly <image> columns to the left of it and the same number of columns to the right of it. <image> The figure shows a 5 Γ— 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix. Input The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: * 1 ≀ n ≀ 5 The input limitations for getting 100 points are: * 1 ≀ n ≀ 101 Output Print a single integer β€” the sum of good matrix elements. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 45 Input 5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Output 17 Note In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure. Tags: implementation Correct Solution: ``` n = int(input()) lst = [] for i in range(n): a = list(map(int, input().split())) lst.append(a) middle = n // 2 first = 0 second = 0 for i in range(0, n): for j in range(0, n): if (i == j): first += lst[i][j] if (i == n - j - 1): second += lst[i][j] midrow = sum(lst[middle]) midcol = 0 for i in range(n): midcol = midcol + lst[i][middle] print(midcol + midrow + first + second -3*(lst[n//2][n//2])) ```
108,117
Provide tags and a correct Python 3 solution for this coding contest problem. The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n Γ— n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: * Elements of the main diagonal. * Elements of the secondary diagonal. * Elements of the "middle" row β€” the row which has exactly <image> rows above it and the same number of rows below it. * Elements of the "middle" column β€” the column that has exactly <image> columns to the left of it and the same number of columns to the right of it. <image> The figure shows a 5 Γ— 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix. Input The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: * 1 ≀ n ≀ 5 The input limitations for getting 100 points are: * 1 ≀ n ≀ 101 Output Print a single integer β€” the sum of good matrix elements. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 45 Input 5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Output 17 Note In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure. Tags: implementation Correct Solution: ``` n = int(input()) a = [list(map(int, input().split())) for i in range(n)] print(sum(a[i][i] + a[i][n - i - 1] + a[n // 2][i] + a[i][n // 2] for i in range(n)) - 3 * a[n // 2][n // 2]) ```
108,118
Provide tags and a correct Python 3 solution for this coding contest problem. The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n Γ— n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: * Elements of the main diagonal. * Elements of the secondary diagonal. * Elements of the "middle" row β€” the row which has exactly <image> rows above it and the same number of rows below it. * Elements of the "middle" column β€” the column that has exactly <image> columns to the left of it and the same number of columns to the right of it. <image> The figure shows a 5 Γ— 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix. Input The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: * 1 ≀ n ≀ 5 The input limitations for getting 100 points are: * 1 ≀ n ≀ 101 Output Print a single integer β€” the sum of good matrix elements. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 45 Input 5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Output 17 Note In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure. Tags: implementation Correct Solution: ``` n=int(input()) are=[] suma=0 for k in range (n): a=input() a=a.split() are.append(a) espaciovacio=n-3 for k in range ( n): for r in range (n): if k==((n)//2): suma=suma+int(are[k][r]) are[k][r]="0" elif r==((n)//2): suma=suma+int(are[k][r]) are[k][r]="0" elif k==r: suma=suma+int(are[k][r]) are[k][r]="0" elif (k+r==n-1): suma=suma+int(are[k][r]) are[k][r]="0" print(suma) ```
108,119
Provide tags and a correct Python 3 solution for this coding contest problem. The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n Γ— n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: * Elements of the main diagonal. * Elements of the secondary diagonal. * Elements of the "middle" row β€” the row which has exactly <image> rows above it and the same number of rows below it. * Elements of the "middle" column β€” the column that has exactly <image> columns to the left of it and the same number of columns to the right of it. <image> The figure shows a 5 Γ— 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix. Input The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: * 1 ≀ n ≀ 5 The input limitations for getting 100 points are: * 1 ≀ n ≀ 101 Output Print a single integer β€” the sum of good matrix elements. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 45 Input 5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Output 17 Note In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure. Tags: implementation Correct Solution: ``` """ instagram : essipoortahmasb2018 telegram channel : essi_python """ Sum = 0 i = input n = int(i()) l = [] for i in range(n): l.append([*map(int,input().split())]) for i in range(n): Sum+= l[i][i] l[i][i] = 0 Sum+=l[i][n//2] l[i][n//2] = 0 a = 0 b = n - 1 for i in range(n): Sum+=l[a][b] l[a][b]=0 Sum+=l[n//2][b] l[n//2][b] = 0 a+=1 b-=1 print(Sum) ```
108,120
Provide tags and a correct Python 3 solution for this coding contest problem. The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n Γ— n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: * Elements of the main diagonal. * Elements of the secondary diagonal. * Elements of the "middle" row β€” the row which has exactly <image> rows above it and the same number of rows below it. * Elements of the "middle" column β€” the column that has exactly <image> columns to the left of it and the same number of columns to the right of it. <image> The figure shows a 5 Γ— 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix. Input The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: * 1 ≀ n ≀ 5 The input limitations for getting 100 points are: * 1 ≀ n ≀ 101 Output Print a single integer β€” the sum of good matrix elements. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 45 Input 5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Output 17 Note In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure. Tags: implementation Correct Solution: ``` n = int(input()) ans = 0 for i in range(n): a = [int(i) for i in input().split()] if i != n // 2: ans += a[i] + a[n//2] +a[n-1-i] else: for j in range(n): ans += a[j] print(ans) ```
108,121
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n Γ— n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: * Elements of the main diagonal. * Elements of the secondary diagonal. * Elements of the "middle" row β€” the row which has exactly <image> rows above it and the same number of rows below it. * Elements of the "middle" column β€” the column that has exactly <image> columns to the left of it and the same number of columns to the right of it. <image> The figure shows a 5 Γ— 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix. Input The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: * 1 ≀ n ≀ 5 The input limitations for getting 100 points are: * 1 ≀ n ≀ 101 Output Print a single integer β€” the sum of good matrix elements. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 45 Input 5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Output 17 Note In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure. Submitted Solution: ``` n = int(input()) gh = [0 for _ in range(n)] arr = [gh[:] for _ in range(n) ] visited = [gh[:] for _ in range(n)] for i in range(n): a = input() a1 = a.split() for j in range(n): arr[i][j] = int(a1[j]) if n == 1: print( a) else: middleR = (n - 1) // 2 middleC = (n - 1 ) // 2 total = 0 for i in range(n): if visited[middleR][i] == 0: visited[middleR][i] = 1 total += arr[middleR][i] #print(visited) for i in range(n): if visited[i][middleC] == 0: visited[i][middleC] = 1 total += arr[i][middleC] #print(visited) for i in range(n): if visited[i][i] == 0: visited[i][i] = 1 total += arr[i][i] #print(visited) ku = 0 for i in range(n): kkt = n - 1 - i if visited[ku][kkt] == 0: visited[ku][kkt] = 1 total += arr[ku][kkt] ku += 1 #print(visited) print(total) ``` Yes
108,122
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n Γ— n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: * Elements of the main diagonal. * Elements of the secondary diagonal. * Elements of the "middle" row β€” the row which has exactly <image> rows above it and the same number of rows below it. * Elements of the "middle" column β€” the column that has exactly <image> columns to the left of it and the same number of columns to the right of it. <image> The figure shows a 5 Γ— 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix. Input The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: * 1 ≀ n ≀ 5 The input limitations for getting 100 points are: * 1 ≀ n ≀ 101 Output Print a single integer β€” the sum of good matrix elements. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 45 Input 5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Output 17 Note In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure. Submitted Solution: ``` x = int(input()) a = [] b = [] for i in range(x): b.append(list(map(int, input().split(" ")))) c = b[x//2][x//2] b[x//2][x//2] = 0 a = a + b[x//2] for i in b: a.append(i[x//2]) for i in range(x): for j in range(x): if i == j: a.append(b[i][j]) else: pass for i in reversed(range(x)): for j in range(x): if i + j == x - 1: a.append(b[i][j]) else: pass print(sum(a) + c) ``` Yes
108,123
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n Γ— n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: * Elements of the main diagonal. * Elements of the secondary diagonal. * Elements of the "middle" row β€” the row which has exactly <image> rows above it and the same number of rows below it. * Elements of the "middle" column β€” the column that has exactly <image> columns to the left of it and the same number of columns to the right of it. <image> The figure shows a 5 Γ— 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix. Input The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: * 1 ≀ n ≀ 5 The input limitations for getting 100 points are: * 1 ≀ n ≀ 101 Output Print a single integer β€” the sum of good matrix elements. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 45 Input 5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Output 17 Note In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure. Submitted Solution: ``` n = int(input()) res = 0 for i in range(n): row = map(int, input().split()) for j, v in enumerate(row): if i == j or i + j == n - 1 or i == n // 2 or j == n // 2: res += v print(res) ``` Yes
108,124
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n Γ— n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: * Elements of the main diagonal. * Elements of the secondary diagonal. * Elements of the "middle" row β€” the row which has exactly <image> rows above it and the same number of rows below it. * Elements of the "middle" column β€” the column that has exactly <image> columns to the left of it and the same number of columns to the right of it. <image> The figure shows a 5 Γ— 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix. Input The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: * 1 ≀ n ≀ 5 The input limitations for getting 100 points are: * 1 ≀ n ≀ 101 Output Print a single integer β€” the sum of good matrix elements. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 45 Input 5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Output 17 Note In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure. Submitted Solution: ``` n = int(input()) a = [list(map(int,input().split())) for i in range(n)] ans = 0 for i in range(n): ans += a[i][i] + a[i][n - i - 1] + a[n // 2][i] + a[i][n // 2] print(ans-3*a[n//2][n//2]) ``` Yes
108,125
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n Γ— n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: * Elements of the main diagonal. * Elements of the secondary diagonal. * Elements of the "middle" row β€” the row which has exactly <image> rows above it and the same number of rows below it. * Elements of the "middle" column β€” the column that has exactly <image> columns to the left of it and the same number of columns to the right of it. <image> The figure shows a 5 Γ— 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix. Input The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: * 1 ≀ n ≀ 5 The input limitations for getting 100 points are: * 1 ≀ n ≀ 101 Output Print a single integer β€” the sum of good matrix elements. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 45 Input 5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Output 17 Note In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure. Submitted Solution: ``` # matrix dimensions n = int(input()) matrix = [] for mr in range(0, n): matrix.append(list(map(int, input().split()))) # get middle row (no need for + 1 since index starts with 0) # good matrix points gmp = sum(matrix[(n//2)]) matrix[n//2] = [0] * n # get middle column gmp += sum([x[n//2] for x in matrix]) for x in range(0, n): matrix[x][n//2] = 0 # get main and secondary diagonal # since all elements already counted for middle row # and middle column are already 0 # there's no need to worry about [n/2][n/2] now for x in range(0, n): gmp += matrix[x][x] + matrix[-1 - x][-1 - x] print(gmp) ``` No
108,126
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n Γ— n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: * Elements of the main diagonal. * Elements of the secondary diagonal. * Elements of the "middle" row β€” the row which has exactly <image> rows above it and the same number of rows below it. * Elements of the "middle" column β€” the column that has exactly <image> columns to the left of it and the same number of columns to the right of it. <image> The figure shows a 5 Γ— 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix. Input The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: * 1 ≀ n ≀ 5 The input limitations for getting 100 points are: * 1 ≀ n ≀ 101 Output Print a single integer β€” the sum of good matrix elements. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 45 Input 5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Output 17 Note In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure. Submitted Solution: ``` """ Author : Indian Coder Date : 29th May ,2021 """ #Imports import math import time import random start=time.time() n=int(input()) sample=0 sample1=[] for i in range(0,n): a1=list(map(int ,input().split())) sample+=(sum(a1)) sample1.append(a1) if(n<=3): print(sample) else: back_val=n back_value_list=[] for i in range(0,len(sample1)): back_value_list.append(sample1[i][back_val-1]) back_val-=1 #print(sample1) #print(back_value_list) front_valu=0 front_value_list=[] for j in range(0,len(sample1)): front_value_list.append(sample1[j][front_valu]) front_valu+=1 #print(front_value_list) middle_col_value=0 pos_add=n//2+1 for k in range(0,len(sample1)): middle_col_value+=sample1[k][pos_add-1] #print(middle_col_value) middle_row_sum=sum(sample1[pos_add-1]) print(sum(front_value_list)+sum(back_value_list)+middle_col_value+middle_row_sum-3*sample1[n//2+1][n//2]) end=time.time() #print("Time Of Execution Is",end-start) ``` No
108,127
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n Γ— n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: * Elements of the main diagonal. * Elements of the secondary diagonal. * Elements of the "middle" row β€” the row which has exactly <image> rows above it and the same number of rows below it. * Elements of the "middle" column β€” the column that has exactly <image> columns to the left of it and the same number of columns to the right of it. <image> The figure shows a 5 Γ— 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix. Input The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: * 1 ≀ n ≀ 5 The input limitations for getting 100 points are: * 1 ≀ n ≀ 101 Output Print a single integer β€” the sum of good matrix elements. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 45 Input 5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Output 17 Note In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure. Submitted Solution: ``` n=int(input()) y=[] s=0 j=0 for i in range(n): x=list(map(int,input().split())) y.append(x) for i in range(n): s+=y[i][i] for i in range(n): s+=y[i][-i] for i in range(i): s+=y[n//2][i] s+=y[i][n//2] print(s-1) ``` No
108,128
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n Γ— n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: * Elements of the main diagonal. * Elements of the secondary diagonal. * Elements of the "middle" row β€” the row which has exactly <image> rows above it and the same number of rows below it. * Elements of the "middle" column β€” the column that has exactly <image> columns to the left of it and the same number of columns to the right of it. <image> The figure shows a 5 Γ— 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix. Input The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix. The input limitations for getting 30 points are: * 1 ≀ n ≀ 5 The input limitations for getting 100 points are: * 1 ≀ n ≀ 101 Output Print a single integer β€” the sum of good matrix elements. Examples Input 3 1 2 3 4 5 6 7 8 9 Output 45 Input 5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Output 17 Note In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure. Submitted Solution: ``` n = int(input()) a = [] b = [1] for i in range(0,n): a.append(1) for i in range(1,n): b = [1] for j in range(1,n): k = a[j] + b[j-1] b.append(k) a = b print(b[n-1]) ``` No
108,129
Provide tags and a correct Python 3 solution for this coding contest problem. You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence. We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 < p2 < ... < pk ≀ |s|) a subsequence of string s = s1s2... s|s|. String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes. Input The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105. Output Print the lexicographically maximum subsequence of string s. Examples Input ababba Output bbba Input abbcbccacbbcbaaba Output cccccbba Note Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters). The first sample: aBaBBA The second sample: abbCbCCaCbbCBaaBA Tags: greedy, strings Correct Solution: ``` def lms(s): t="" if len(s)==1: return s else: while(len(s)>1): l=0 j=0 for i in range(len(s)): if ord(s[i])>l: l=ord(s[i]) j=i t+= (s.count(s[j]))*s[j] y = len(s) - 1 - s[::-1].index(s[j]) s=s[y+1:] if len(set(map(str,s)))==1: t+=s break return t print(lms(input())) ```
108,130
Provide tags and a correct Python 3 solution for this coding contest problem. You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence. We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 < p2 < ... < pk ≀ |s|) a subsequence of string s = s1s2... s|s|. String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes. Input The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105. Output Print the lexicographically maximum subsequence of string s. Examples Input ababba Output bbba Input abbcbccacbbcbaaba Output cccccbba Note Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters). The first sample: aBaBBA The second sample: abbCbCCaCbbCBaaBA Tags: greedy, strings Correct Solution: ``` a=m='' for x in input()[::-1]: if x>=m: a+=x m=max(m,x) print(a[::-1]) ```
108,131
Provide tags and a correct Python 3 solution for this coding contest problem. You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence. We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 < p2 < ... < pk ≀ |s|) a subsequence of string s = s1s2... s|s|. String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes. Input The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105. Output Print the lexicographically maximum subsequence of string s. Examples Input ababba Output bbba Input abbcbccacbbcbaaba Output cccccbba Note Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters). The first sample: aBaBBA The second sample: abbCbCCaCbbCBaaBA Tags: greedy, strings Correct Solution: ``` from sys import stdin, stdout s = stdin.readline().strip() maximum = [] mx = 'a' for f in s[::-1]: mx = max(f, mx) maximum.append(mx) maximum = maximum[::-1] ans = '' for i in range(len(s)): if s[i] == maximum[i]: ans += s[i] stdout.write(str(ans)) ```
108,132
Provide tags and a correct Python 3 solution for this coding contest problem. You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence. We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 < p2 < ... < pk ≀ |s|) a subsequence of string s = s1s2... s|s|. String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes. Input The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105. Output Print the lexicographically maximum subsequence of string s. Examples Input ababba Output bbba Input abbcbccacbbcbaaba Output cccccbba Note Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters). The first sample: aBaBBA The second sample: abbCbCCaCbbCBaaBA Tags: greedy, strings Correct Solution: ``` A = input() letter_to_index = {} for i, letter in enumerate(A): if letter in letter_to_index: letter_to_index[letter] += [i] else: letter_to_index[letter] = [i] pos = 0 letter = 'z' result = "" while True: if letter in letter_to_index: letter_pos = letter_to_index[letter] for index in letter_pos: if index >= pos: result += letter pos = index if letter == 'a': break letter = chr(ord(letter) - 1) print(result) ```
108,133
Provide tags and a correct Python 3 solution for this coding contest problem. You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence. We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 < p2 < ... < pk ≀ |s|) a subsequence of string s = s1s2... s|s|. String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes. Input The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105. Output Print the lexicographically maximum subsequence of string s. Examples Input ababba Output bbba Input abbcbccacbbcbaaba Output cccccbba Note Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters). The first sample: aBaBBA The second sample: abbCbCCaCbbCBaaBA Tags: greedy, strings Correct Solution: ``` s = input() l = len(s) m = 'a' ans = "" for i in range(l): if s[l-i-1] >= m: ans = s[l-i-1] + ans m = s[l-i-1] print(ans) # Made By Mostafa_Khaled ```
108,134
Provide tags and a correct Python 3 solution for this coding contest problem. You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence. We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 < p2 < ... < pk ≀ |s|) a subsequence of string s = s1s2... s|s|. String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes. Input The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105. Output Print the lexicographically maximum subsequence of string s. Examples Input ababba Output bbba Input abbcbccacbbcbaaba Output cccccbba Note Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters). The first sample: aBaBBA The second sample: abbCbCCaCbbCBaaBA Tags: greedy, strings Correct Solution: ``` s,l=input(),[''] for i in reversed(s): if l[-1]<=i: l.append(i) print(*reversed(l),sep='') ```
108,135
Provide tags and a correct Python 3 solution for this coding contest problem. You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence. We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 < p2 < ... < pk ≀ |s|) a subsequence of string s = s1s2... s|s|. String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes. Input The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105. Output Print the lexicographically maximum subsequence of string s. Examples Input ababba Output bbba Input abbcbccacbbcbaaba Output cccccbba Note Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters). The first sample: aBaBBA The second sample: abbCbCCaCbbCBaaBA Tags: greedy, strings Correct Solution: ``` string = str(input()) listx = [x for x in string] listx.reverse() join = [''.join(listx)] letts = list(set(listx)) letts.sort() letts.reverse() stringx = '' for i in letts: if i in string: for k in range(len(string)): if string[k] == i: indx = k for j in range(indx): if string[j] == i: stringx += i stringx += i string = string[indx+1:] print(stringx) ```
108,136
Provide tags and a correct Python 3 solution for this coding contest problem. You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence. We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 < p2 < ... < pk ≀ |s|) a subsequence of string s = s1s2... s|s|. String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes. Input The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105. Output Print the lexicographically maximum subsequence of string s. Examples Input ababba Output bbba Input abbcbccacbbcbaaba Output cccccbba Note Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters). The first sample: aBaBBA The second sample: abbCbCCaCbbCBaaBA Tags: greedy, strings Correct Solution: ``` from collections import Counter s = input() c = Counter(s) cur_char = 'z' for ch in s: while c[cur_char] == 0: cur_char = chr(ord(cur_char) - 1) if ch == cur_char: print(cur_char, end='') c[ch] -= 1 ```
108,137
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence. We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 < p2 < ... < pk ≀ |s|) a subsequence of string s = s1s2... s|s|. String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes. Input The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105. Output Print the lexicographically maximum subsequence of string s. Examples Input ababba Output bbba Input abbcbccacbbcbaaba Output cccccbba Note Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters). The first sample: aBaBBA The second sample: abbCbCCaCbbCBaaBA Submitted Solution: ``` string = str(input()) listx = [x for x in string] listx.reverse() join = [''.join(listx)] letts = list(set(listx)) letts.sort() letts.reverse() stringx = '' for i in letts: leng = len(string) indx = listx.index(i) for j in range(leng - indx): if string[j] == i: stringx += i string = string[-indx:] print(stringx) ``` No
108,138
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence. We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 < p2 < ... < pk ≀ |s|) a subsequence of string s = s1s2... s|s|. String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes. Input The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105. Output Print the lexicographically maximum subsequence of string s. Examples Input ababba Output bbba Input abbcbccacbbcbaaba Output cccccbba Note Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters). The first sample: aBaBBA The second sample: abbCbCCaCbbCBaaBA Submitted Solution: ``` string = str(input()) listx = [x for x in string] listx.reverse() join = [''.join(listx)] letts = list(set(listx)) letts.sort() letts.reverse() stringx = '' for i in letts: if i in string: indx = string.index(i) for j in range(indx): if string[j] == i: stringx += i stringx += i string = string[indx+1:] print(stringx) ``` No
108,139
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence. We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 < p2 < ... < pk ≀ |s|) a subsequence of string s = s1s2... s|s|. String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes. Input The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105. Output Print the lexicographically maximum subsequence of string s. Examples Input ababba Output bbba Input abbcbccacbbcbaaba Output cccccbba Note Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters). The first sample: aBaBBA The second sample: abbCbCCaCbbCBaaBA Submitted Solution: ``` def lms(s): t="" while(len(s)>1): l=0 j=0 for i in range(len(s)): if ord(s[i])>l: l=ord(s[i]) j=i t+= (s.count(s[j]))*s[j] y = len(s) - 1 - s[::-1].index(s[j]) s=s[y+1:] if len(set(map(str,s)))==1: t+=s break return t print(lms(input())) ``` No
108,140
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence. We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 < p2 < ... < pk ≀ |s|) a subsequence of string s = s1s2... s|s|. String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes. Input The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105. Output Print the lexicographically maximum subsequence of string s. Examples Input ababba Output bbba Input abbcbccacbbcbaaba Output cccccbba Note Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters). The first sample: aBaBBA The second sample: abbCbCCaCbbCBaaBA Submitted Solution: ``` string = str(input()) listx = [x for x in string] listx.reverse() join = [''.join(listx)] letts = list(set(listx)) letts.sort() letts.reverse() stringx = '' for i in letts: if i in string: leng = len(string) indx = string.index(i) for j in range(leng - indx): if string[j] == i: stringx += i string = string[-indx:] print(stringx) ``` No
108,141
Provide tags and a correct Python 3 solution for this coding contest problem. Once Bob decided to lay a parquet floor in his living room. The living room is of size n Γ— m metres. Bob had planks of three types: a planks 1 Γ— 2 meters, b planks 2 Γ— 1 meters, and c planks 2 Γ— 2 meters. Help Bob find out, if it is possible to parquet the living room with such a set of planks, and if it is possible, find one of the possible ways to do so. Bob doesn't have to use all the planks. Input The first input line contains 5 space-separated integer numbers n, m, a, b, c (1 ≀ n, m ≀ 100, 0 ≀ a, b, c ≀ 104), n and m β€” the living room dimensions, a, b and c β€” amount of planks 1 Γ— 2, 2 Γ— 1 ΠΈ 2 Γ— 2 respectively. It's not allowed to turn the planks. Output If it is not possible to parquet the room with such a set of planks, output IMPOSSIBLE. Otherwise output one of the possible ways to parquet the room β€” output n lines with m lower-case Latin letters each. Two squares with common sides should contain the same letters, if they belong to one and the same plank, and different letters otherwise. Different planks can be marked with one and the same letter (see examples). If the answer is not unique, output any. Examples Input 2 6 2 2 1 Output aabcca aabdda Input 1 1 100 100 100 Output IMPOSSIBLE Input 4 4 10 10 10 Output aabb aabb bbaa bbaa Tags: combinatorics, constructive algorithms, greedy, implementation Correct Solution: ``` n, m, a, b, c = map(int, input().split()) mat = [0]*n for i in range(n): mat[i] = [0] * m n1 = [min(n*m//4, c), min(m//2 * n, a), min(n//2 * m, b)] p = ['c', 'a', 'b'] z = ['d', 'e', 'f', 'g'] z1 = ['m', 'n', 'u', 'o'] z2 = ['p', 'q', 'r', 'w'] #print(n1) def fill(h, w): if h <= 0 or w <= 0: return True i = 0; j = 0 for k in range(3): while n1[k] > 0: #print(i, j, h, w) if k == 0: if i%4 and j%4: o = 3 elif i%4 and not j%4: o = 2 elif not i%4 and j%4: o = 1 else: o = 0 mat[i][j] = mat[i+1][j] = mat[i][j+1] = mat[i+1][j+1] = z[o]; if p[k] == 'a': if j%4: o = 2 else: o = 0 mat[i][j] = mat[i][j+1] = z1[o] mat[i+1][j] = mat[i+1][j+1] = z1[o+1]; elif p[k] == 'b': if i%4: o = 0 else: o = 2 mat[i][j] = mat[i+1][j] = z2[o] mat[i][j+1] = mat[i+1][j+1] = z2[o+1]; if k == 0: n1[k] -= 1 else: n1[k] -= 2 j += 2 if j >= w: i += 2 j = 0 if i >= h: return True return False def pmat(): for i in range(n): for j in range(m): print(mat[i][j], end='') print('\n', end='') def even(h, w): k1 = 0; k2 = 0 if n1[1] %2 == 1: n1[1] -= 1; k1 = 1 if n1[2] %2 == 1: n1[2] -= 1; k2 = 1 if fill(h, w): n1[1] += k1 n1[2] += k2 return True else: n1[1] += k1 n1[2] += k2 return False if n*m % 2 == 0: if n%2 == 0 and m%2 == 0: if even(n, m): pmat() else: print('IMPOSSIBLE') elif n%2 == 0 and m%2 != 0: n1 = [min(n*m//4, c), min(m//2 * n, a), min(n//2 * m, b)] p = ['c', 'a', 'b'] f = 'b' if even(n, m-1): for i in range(0, n, 2): mat[i][m-1] = f; mat[i+1][m-1] = f if f == 'a': f = 'b' else: f = 'a' n1[2] -= 1 else: if n1[2] >= 0: pmat() else: print('IMPOSSIBLE') else: print('IMPOSSIBLE') else: n1 = [min(n*m//4, c), min(n//2 * m, b), min(m//2 * n, a)] p = ['c', 'b', 'a'] f = 'a' if even(n-1, m): for i in range(0, m, 2): mat[n-1][i] = f; mat[n-1][i+1] = f if f == 'a': f = 'b' else: f = 'a' n1[2] -= 1 else: if n1[2] >= 0: pmat() else: print('IMPOSSIBLE') else: print('IMPOSSIBLE') elif n*m % 2 != 0: print('IMPOSSIBLE') ```
108,142
Provide tags and a correct Python 3 solution for this coding contest problem. Once Bob decided to lay a parquet floor in his living room. The living room is of size n Γ— m metres. Bob had planks of three types: a planks 1 Γ— 2 meters, b planks 2 Γ— 1 meters, and c planks 2 Γ— 2 meters. Help Bob find out, if it is possible to parquet the living room with such a set of planks, and if it is possible, find one of the possible ways to do so. Bob doesn't have to use all the planks. Input The first input line contains 5 space-separated integer numbers n, m, a, b, c (1 ≀ n, m ≀ 100, 0 ≀ a, b, c ≀ 104), n and m β€” the living room dimensions, a, b and c β€” amount of planks 1 Γ— 2, 2 Γ— 1 ΠΈ 2 Γ— 2 respectively. It's not allowed to turn the planks. Output If it is not possible to parquet the room with such a set of planks, output IMPOSSIBLE. Otherwise output one of the possible ways to parquet the room β€” output n lines with m lower-case Latin letters each. Two squares with common sides should contain the same letters, if they belong to one and the same plank, and different letters otherwise. Different planks can be marked with one and the same letter (see examples). If the answer is not unique, output any. Examples Input 2 6 2 2 1 Output aabcca aabdda Input 1 1 100 100 100 Output IMPOSSIBLE Input 4 4 10 10 10 Output aabb aabb bbaa bbaa Tags: combinatorics, constructive algorithms, greedy, implementation Correct Solution: ``` n,m,a,b,c = map(int,input().split()) swapped = False if(n%2 == 1 and m%2 == 1): print('IMPOSSIBLE') exit() if(m%2 == 1): n,m,a,b,swapped = m,n,b,a,True ans = [['.' for i in range(m)] for i in range(n)] for i in range(0,n-1,2): for j in range(0,m-1,2): l1,l2 = chr(i%4+4*(j%4)+ord('a')),chr(i%4+4*((j+1)%4)+ord('a')) if(c >= 1): ans[i][j] = l1 ans[i+1][j] = l1 ans[i][j+1] = l1 ans[i+1][j+1] = l1 c -= 1 elif(b >= 2): ans[i][j] = l1 ans[i+1][j] = l1 ans[i][j+1] = l2 ans[i+1][j+1] = l2 b -= 2 elif(a >= 2): ans[i][j] = l1 ans[i+1][j] = l2 ans[i][j+1] = l1 ans[i+1][j+1] = l2 a -= 2 else: print('IMPOSSIBLE') exit() #print(a,b,ans) if(n%2 == 1): for j in range(0,m,2): i = n-1 l1,l2 = chr(i%4+4*(j%4)+ord('a')),chr(i%4+4*((j+1)%4)+ord('a')) if(a >= 1): ans[i][j] = l1 ans[i][j+1] = l1 a -= 1 else: print('IMPOSSIBLE') exit() if(swapped): ans = [[ans[i][j] for i in range(n)] for j in range(m)] print('\n'.join([''.join(x) for x in ans])) ```
108,143
Provide tags and a correct Python 3 solution for this coding contest problem. Once Bob decided to lay a parquet floor in his living room. The living room is of size n Γ— m metres. Bob had planks of three types: a planks 1 Γ— 2 meters, b planks 2 Γ— 1 meters, and c planks 2 Γ— 2 meters. Help Bob find out, if it is possible to parquet the living room with such a set of planks, and if it is possible, find one of the possible ways to do so. Bob doesn't have to use all the planks. Input The first input line contains 5 space-separated integer numbers n, m, a, b, c (1 ≀ n, m ≀ 100, 0 ≀ a, b, c ≀ 104), n and m β€” the living room dimensions, a, b and c β€” amount of planks 1 Γ— 2, 2 Γ— 1 ΠΈ 2 Γ— 2 respectively. It's not allowed to turn the planks. Output If it is not possible to parquet the room with such a set of planks, output IMPOSSIBLE. Otherwise output one of the possible ways to parquet the room β€” output n lines with m lower-case Latin letters each. Two squares with common sides should contain the same letters, if they belong to one and the same plank, and different letters otherwise. Different planks can be marked with one and the same letter (see examples). If the answer is not unique, output any. Examples Input 2 6 2 2 1 Output aabcca aabdda Input 1 1 100 100 100 Output IMPOSSIBLE Input 4 4 10 10 10 Output aabb aabb bbaa bbaa Tags: combinatorics, constructive algorithms, greedy, implementation Correct Solution: ``` n,m,a,b,c = map( int,input().split() ) ok = False if ( n%2==1 and m%2==1 ): print ( 'IMPOSSIBLE' ) exit() if( m%2==1 ): n,m,a,b,ok = m,n,b,a,True res = [ [ '.' for i in range(m) ] for i in range(n) ] for i in range( 0,n-1,2 ): for j in range( 0,m-1,2 ): x1 = chr( i%4+4*(j%4)+ord('a') ) x2 = chr( i%4+4*((j+1)%4)+ord('a') ) if( c>=1 ): res[i][j] = x1 res[i+1][j] = x1 res[i][j+1] = x1 res[i+1][j+1] = x1 c -= 1 elif( b>=2 ): res[i][j] = x1 res[i+1][j] = x1 res[i][j+1] = x2 res[i+1][j+1] = x2 b -= 2 elif( a>=2 ): res[i][j] = x1 res[i+1][j] = x2 res[i][j+1] = x1 res[i+1][j+1] = x2 a -= 2 else : print( 'IMPOSSIBLE' ) exit() if( n%2==1 ): for j in range( 0,m,2 ): i = n-1 x1 = chr( i%4+4*(j%4)+ord('a') ) x2 = chr( i%4+4*((j+1)%4)+ord('a') ) if( a >= 1 ): res[i][j] = x1 res[i][j+1]= x1 a -= 1 else : print( 'IMPOSSIBLE' ) exit() if( ok ): res = [ [ res[i][j] for i in range(n) ]for j in range(m) ] print( '\n'.join( [ ''.join(it) for it in res ] ) ) ```
108,144
Provide tags and a correct Python 3 solution for this coding contest problem. Once Bob decided to lay a parquet floor in his living room. The living room is of size n Γ— m metres. Bob had planks of three types: a planks 1 Γ— 2 meters, b planks 2 Γ— 1 meters, and c planks 2 Γ— 2 meters. Help Bob find out, if it is possible to parquet the living room with such a set of planks, and if it is possible, find one of the possible ways to do so. Bob doesn't have to use all the planks. Input The first input line contains 5 space-separated integer numbers n, m, a, b, c (1 ≀ n, m ≀ 100, 0 ≀ a, b, c ≀ 104), n and m β€” the living room dimensions, a, b and c β€” amount of planks 1 Γ— 2, 2 Γ— 1 ΠΈ 2 Γ— 2 respectively. It's not allowed to turn the planks. Output If it is not possible to parquet the room with such a set of planks, output IMPOSSIBLE. Otherwise output one of the possible ways to parquet the room β€” output n lines with m lower-case Latin letters each. Two squares with common sides should contain the same letters, if they belong to one and the same plank, and different letters otherwise. Different planks can be marked with one and the same letter (see examples). If the answer is not unique, output any. Examples Input 2 6 2 2 1 Output aabcca aabdda Input 1 1 100 100 100 Output IMPOSSIBLE Input 4 4 10 10 10 Output aabb aabb bbaa bbaa Tags: combinatorics, constructive algorithms, greedy, implementation Correct Solution: ``` import sys def fail(): print('IMPOSSIBLE') sys.exit() n, m, a, b, c = map(int, input().split()) if (n * m) % 2 == 1: # odd area fail() if n * m > 2 * (a + b + 2 * c): # too large fail() g = [ [ ' ' for c in range(m) ] for r in range(n) ] if n % 2 == 1: if m > 2 * a: # not enough horizontal planks fail() letter = 'y' for i in range(0, m, 2): g[n - 1][i] = g[n - 1][i + 1] = letter letter = 'z' if letter == 'y' else 'y' a -= m // 2 if m % 2 == 1: if n > 2 * b: # not enough vertical planks fail() letter = 'y' for r in range(0, n, 2): g[r][m - 1] = g[r + 1][m - 1] = letter letter = 'z' if letter == 'y' else 'y' b -= n // 2 a -= a % 2 # get rid of odd pieces b -= b % 2 if (n - n % 2) * (m - m % 2) > 2 * (a + b + 2 * c): # remainder too large fail() letter_pairs = ( ('a', 'i'), ('x', 'q') ) for r in range(0, n - n % 2, 2): for c in range(0, m - m % 2, 2): letters = letter_pairs[(r // 2 + c // 2) % 2] if a > 0: g[r][c] = g[r][c + 1] = letters[0] g[r + 1][c] = g[r + 1][c + 1] = letters[1] a -= 2 elif b > 0: g[r][c] = g[r + 1][c] = letters[0] g[r][c + 1] = g[r + 1][c + 1] = letters[1] b -= 2 else: g[r][c] = g[r + 1][c] = g[r][c + 1] = g[r + 1][c + 1] = letters[0] c -= 1 print('\n'.join([ ''.join(g[r]) for r in range(n) ])) ```
108,145
Provide tags and a correct Python 3 solution for this coding contest problem. Once Bob decided to lay a parquet floor in his living room. The living room is of size n Γ— m metres. Bob had planks of three types: a planks 1 Γ— 2 meters, b planks 2 Γ— 1 meters, and c planks 2 Γ— 2 meters. Help Bob find out, if it is possible to parquet the living room with such a set of planks, and if it is possible, find one of the possible ways to do so. Bob doesn't have to use all the planks. Input The first input line contains 5 space-separated integer numbers n, m, a, b, c (1 ≀ n, m ≀ 100, 0 ≀ a, b, c ≀ 104), n and m β€” the living room dimensions, a, b and c β€” amount of planks 1 Γ— 2, 2 Γ— 1 ΠΈ 2 Γ— 2 respectively. It's not allowed to turn the planks. Output If it is not possible to parquet the room with such a set of planks, output IMPOSSIBLE. Otherwise output one of the possible ways to parquet the room β€” output n lines with m lower-case Latin letters each. Two squares with common sides should contain the same letters, if they belong to one and the same plank, and different letters otherwise. Different planks can be marked with one and the same letter (see examples). If the answer is not unique, output any. Examples Input 2 6 2 2 1 Output aabcca aabdda Input 1 1 100 100 100 Output IMPOSSIBLE Input 4 4 10 10 10 Output aabb aabb bbaa bbaa Tags: combinatorics, constructive algorithms, greedy, implementation Correct Solution: ``` import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n, m, b, a, c = map(int, input().split()) def ng(): print('IMPOSSIBLE') exit() if (n * m) & 1: ng() ans = [['*'] * m for _ in range(n)] if n % 2: s = ['y', 'z'] for i, j in enumerate(range(0, m, 2)): ans[-1][j] = ans[-1][j + 1] = s[i & 1] b -= 1 if m % 2: s = ['y', 'z'] for i, j in enumerate(range(0, n, 2)): ans[j][-1] = ans[j + 1][-1] = s[i & 1] a -= 1 s1 = [['a', 'b'], ['c', 'd']] s2 = [['e', 'f'], ['g', 'h']] for i in range(0, n - (n & 1), 2): for j in range(0, m - (m & 1), 2): if c: ans[i][j] = ans[i + 1][j] = ans[i][j + 1] = ans[i + 1][j + 1] = s1[0][0] c -= 1 elif a >= 2: ans[i][j] = ans[i + 1][j] = s1[0][0] ans[i][j + 1] = ans[i + 1][j + 1] = s1[0][1] a -= 2 else: ans[i][j] = ans[i][j + 1] = s1[0][0] ans[i + 1][j] = ans[i + 1][j + 1] = s1[0][1] b -= 2 s1[0], s1[1] = s1[1], s1[0] s1, s2 = s2, s1 if a < 0 or b < 0: ng() else: for row in ans: print(*row, sep='') ```
108,146
Provide tags and a correct Python 3 solution for this coding contest problem. Once Bob decided to lay a parquet floor in his living room. The living room is of size n Γ— m metres. Bob had planks of three types: a planks 1 Γ— 2 meters, b planks 2 Γ— 1 meters, and c planks 2 Γ— 2 meters. Help Bob find out, if it is possible to parquet the living room with such a set of planks, and if it is possible, find one of the possible ways to do so. Bob doesn't have to use all the planks. Input The first input line contains 5 space-separated integer numbers n, m, a, b, c (1 ≀ n, m ≀ 100, 0 ≀ a, b, c ≀ 104), n and m β€” the living room dimensions, a, b and c β€” amount of planks 1 Γ— 2, 2 Γ— 1 ΠΈ 2 Γ— 2 respectively. It's not allowed to turn the planks. Output If it is not possible to parquet the room with such a set of planks, output IMPOSSIBLE. Otherwise output one of the possible ways to parquet the room β€” output n lines with m lower-case Latin letters each. Two squares with common sides should contain the same letters, if they belong to one and the same plank, and different letters otherwise. Different planks can be marked with one and the same letter (see examples). If the answer is not unique, output any. Examples Input 2 6 2 2 1 Output aabcca aabdda Input 1 1 100 100 100 Output IMPOSSIBLE Input 4 4 10 10 10 Output aabb aabb bbaa bbaa Tags: combinatorics, constructive algorithms, greedy, implementation Correct Solution: ``` from fractions import Fraction import sys sys.setrecursionlimit(1000*100) #c=int(input()) #a,b=tuple(map(int,input().split())) #edges=dict((i,[]) for i in range(1,c+1)) #children=filter(lambda x: x != p, edges[r]) #cs.sort(key=lambda x:Fraction(x[0],x[1]),reverse=True) #if dp[r] is not None: #chr(ord('a')+1) #''.join(['a','b','c']) #sys.exit() n,m,a,b,c=tuple(map(int,input().split())) err='IMPOSSIBLE' if n%2==1 and m%2==1: print(err) sys.exit() ret=[['.' for _ in range(m)] for _ in range(n)] def col(i,j): return chr(ord('a')+4*(i%4)+j%4) if n%2==1: for i in range(0,m,2): if a==0: print(err) sys.exit() ret[n-1][i]=ret[n-1][i+1]=col(n-1,i) a-=1 n-=1 if m%2==1: for i in range(0,n,2): if b==0: print(err) sys.exit() ret[i][m-1]=ret[i+1][m-1]=col(i,m-1) b-=1 m-=1 for i in range(0,n,2): for j in range(0,m,2): if a>=2: a-=2 ret[i][j]=ret[i][j+1]=col(i,j) ret[i+1][j]=ret[i+1][j+1]=col(i+1,j) elif b>=2: b-=2 ret[i][j]=ret[i+1][j]=col(i,j) ret[i][j+1]=ret[i+1][j+1]=col(i,j+1) elif c>=1: c-=1 ret[i][j]=ret[i+1][j]=ret[i][j+1]=ret[i+1][j+1]=col(i,j) else: print(err) sys.exit() for l in ret: print(''.join(l)) ```
108,147
Provide tags and a correct Python 3 solution for this coding contest problem. Once Bob decided to lay a parquet floor in his living room. The living room is of size n Γ— m metres. Bob had planks of three types: a planks 1 Γ— 2 meters, b planks 2 Γ— 1 meters, and c planks 2 Γ— 2 meters. Help Bob find out, if it is possible to parquet the living room with such a set of planks, and if it is possible, find one of the possible ways to do so. Bob doesn't have to use all the planks. Input The first input line contains 5 space-separated integer numbers n, m, a, b, c (1 ≀ n, m ≀ 100, 0 ≀ a, b, c ≀ 104), n and m β€” the living room dimensions, a, b and c β€” amount of planks 1 Γ— 2, 2 Γ— 1 ΠΈ 2 Γ— 2 respectively. It's not allowed to turn the planks. Output If it is not possible to parquet the room with such a set of planks, output IMPOSSIBLE. Otherwise output one of the possible ways to parquet the room β€” output n lines with m lower-case Latin letters each. Two squares with common sides should contain the same letters, if they belong to one and the same plank, and different letters otherwise. Different planks can be marked with one and the same letter (see examples). If the answer is not unique, output any. Examples Input 2 6 2 2 1 Output aabcca aabdda Input 1 1 100 100 100 Output IMPOSSIBLE Input 4 4 10 10 10 Output aabb aabb bbaa bbaa Tags: combinatorics, constructive algorithms, greedy, implementation Correct Solution: ``` n,m,a,b,c = map( int,input().split() ) ok = False if ( n%2==1 and m%2==1 ): print ( 'IMPOSSIBLE' ) exit() if( m%2==1 ): n,m,a,b,ok = m,n,b,a,True res = [ [ '.' for i in range(m) ] for i in range(n) ] for i in range( 0,n-1,2 ): for j in range( 0,m-1,2 ): x1 = chr( i%4+4*(j%4)+ord('a') ) x2 = chr( i%4+4*((j+1)%4)+ord('a') ) if( c>=1 ): res[i][j] = x1 res[i+1][j] = x1 res[i][j+1] = x1 res[i+1][j+1] = x1 c -= 1 elif( b>=2 ): res[i][j] = x1 res[i+1][j] = x1 res[i][j+1] = x2 res[i+1][j+1] = x2 b -= 2 elif( a>=2 ): res[i][j] = x1 res[i+1][j] = x2 res[i][j+1] = x1 res[i+1][j+1] = x2 a -= 2 else : print( 'IMPOSSIBLE' ) exit() if( n%2==1 ): for j in range( 0,m,2 ): i = n-1 x1 = chr( i%4+4*(j%4)+ord('a') ) x2 = chr( i%4+4*((j+1)%4)+ord('a') ) if( a >= 1 ): res[i][j] = x1 res[i][j+1]= x1 a -= 1 else : print( 'IMPOSSIBLE' ) exit() if( ok ): res = [ [ res[i][j] for i in range(n) ]for j in range(m) ] print( '\n'.join( [ ''.join(it) for it in res ] ) ) # Made By Mostafa_Khaled ```
108,148
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Once Bob decided to lay a parquet floor in his living room. The living room is of size n Γ— m metres. Bob had planks of three types: a planks 1 Γ— 2 meters, b planks 2 Γ— 1 meters, and c planks 2 Γ— 2 meters. Help Bob find out, if it is possible to parquet the living room with such a set of planks, and if it is possible, find one of the possible ways to do so. Bob doesn't have to use all the planks. Input The first input line contains 5 space-separated integer numbers n, m, a, b, c (1 ≀ n, m ≀ 100, 0 ≀ a, b, c ≀ 104), n and m β€” the living room dimensions, a, b and c β€” amount of planks 1 Γ— 2, 2 Γ— 1 ΠΈ 2 Γ— 2 respectively. It's not allowed to turn the planks. Output If it is not possible to parquet the room with such a set of planks, output IMPOSSIBLE. Otherwise output one of the possible ways to parquet the room β€” output n lines with m lower-case Latin letters each. Two squares with common sides should contain the same letters, if they belong to one and the same plank, and different letters otherwise. Different planks can be marked with one and the same letter (see examples). If the answer is not unique, output any. Examples Input 2 6 2 2 1 Output aabcca aabdda Input 1 1 100 100 100 Output IMPOSSIBLE Input 4 4 10 10 10 Output aabb aabb bbaa bbaa Submitted Solution: ``` n, m, a, b, c = map(int, input().split()) mat = [0]*n for i in range(n): mat[i] = [0] * m n1 = [min(n*m//4, c), min(m//2 * n, a), min(n//2 * m, b)] p = ['c', 'a', 'b'] z = ['d', 'e', 'f', 'g'] z1 = ['m', 'n'] #print(n1) def fill(h, w): i = 0; j = 0 for k in range(3): while n1[k] > 0: #print(i, j, h, w) if k == 0: if i%4 and j%4: o = 3 elif i%4 and not j%4: o = 2 elif not i%4 and j%4: o = 1 else: o = 0 mat[i][j] = mat[i+1][j] = mat[i][j+1] = mat[i+1][j+1] = z[o]; if p[k] == 'a': mat[i][j] = mat[i][j+1] = 'm' mat[i+1][j] = mat[i+1][j+1] = 'n'; elif p[k] == 'b': mat[i][j] = mat[i+1][j] = 'p' mat[i][j+1] = mat[i+1][j+1] = 'q'; if k == 0: n1[k] -= 1 else: n1[k] -= 2 j += 2 if j >= w: i += 2 j = 0 if i >= h: return True return False def pmat(): for i in range(n): for j in range(m): print(mat[i][j], end='') print('\n', end='') def even(h, w): k1 = 0; k2 = 0 if n1[1] %2 == 1: n1[1] -= 1; k1 = 1 if n1[2] %2 == 1: n1[2] -= 1; k2 = 1 if fill(h, w): return True else: return False n1[1] += k1 n1[2] += k2 if n*m % 2 == 0: if n%2 == 0 and m%2 == 0: if even(n, m): pmat() else: print('IMPOSSIBLE') elif n%2 == 0 and m%2 != 0: n1 = [min(n*m//4, c), min(m//2 * n, a), min(n//2 * m, b)] p = ['c', 'a', 'b'] f = 'b' if even(n, m-1): for i in range(0, n, 2): mat[i][m-1] = 'b'; mat[i+1][m-1] = 'b' if f == 'a': f = 'b' else: f = 'a' n1[2] -= 1 if n1[2] == 0 and i != n-2: print('IMPOSSIBLE') break else: pmat() else: print('IMPOSSIBLE') else: n1 = [min(n*m//4, c), min(n//2 * m, b), min(m//2 * n, a)] p = ['c', 'b', 'a'] f = 'a' if even(n-1, m): for i in range(0, m, 2): mat[n-1][i] = f; mat[n-1][i+1] = f if f == 'a': f = 'b' else: f = 'a' n1[2] -= 1 if n1[2] == 0 and i != m-2: print('IMPOSSIBLE') break else: pmat() else: print('IMPOSSIBLE') elif n*m % 2 != 0: print('IMPOSSIBLE') ``` No
108,149
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Once Bob decided to lay a parquet floor in his living room. The living room is of size n Γ— m metres. Bob had planks of three types: a planks 1 Γ— 2 meters, b planks 2 Γ— 1 meters, and c planks 2 Γ— 2 meters. Help Bob find out, if it is possible to parquet the living room with such a set of planks, and if it is possible, find one of the possible ways to do so. Bob doesn't have to use all the planks. Input The first input line contains 5 space-separated integer numbers n, m, a, b, c (1 ≀ n, m ≀ 100, 0 ≀ a, b, c ≀ 104), n and m β€” the living room dimensions, a, b and c β€” amount of planks 1 Γ— 2, 2 Γ— 1 ΠΈ 2 Γ— 2 respectively. It's not allowed to turn the planks. Output If it is not possible to parquet the room with such a set of planks, output IMPOSSIBLE. Otherwise output one of the possible ways to parquet the room β€” output n lines with m lower-case Latin letters each. Two squares with common sides should contain the same letters, if they belong to one and the same plank, and different letters otherwise. Different planks can be marked with one and the same letter (see examples). If the answer is not unique, output any. Examples Input 2 6 2 2 1 Output aabcca aabdda Input 1 1 100 100 100 Output IMPOSSIBLE Input 4 4 10 10 10 Output aabb aabb bbaa bbaa Submitted Solution: ``` import sys def fail(): print('IMPOSSIBLE') sys.exit() n, m, a, b, c = map(int, input().split()) if (n * m) % 2 == 1: # odd area fail() if n * m > 2 * (a + b + c + c): # too large fail() g = [ [ ' ' for c in range(m) ] for r in range(n) ] if n % 2 == 1: if m > 2 * a: # not enough horizontal planks fail() letter = 'y' for c in range(0, m, 2): g[n - 1][c] = g[n - 1][c + 1] = letter letter = 'z' if letter == 'y' else 'y' a -= m // 2 if m % 2 == 1: if n > 2 * b: # not enough vertical planks fail() letter = 'y' for r in range(0, n, 2): g[r][m - 1] = g[r + 1][m - 1] = letter letter = 'z' if letter == 'y' else 'y' b -= n // 2 a -= a % 2 # get rid of odd pieces b -= b % 2 if (n - n % 2) * (m - m % 2) > 2 * (a + b + c + c): # remainder too large fail() letter_pairs = ( ('a', 'b'), ('c', 'd') ) for r in range(0, n - n % 2, 2): for c in range(0, m - m % 2, 2): letters = letter_pairs[(r // 2 + c // 2) % 2] if a > 0: g[r][c] = g[r][c + 1] = letters[0] g[r + 1][c] = g[r + 1][c + 1] = letters[1] a -= 2 elif b > 0: g[r][c] = g[r + 1][c] = letters[0] g[r][c + 1] = g[r + 1][c + 1] = letters[1] b -= 2 else: g[r][c] = g[r + 1][c] = g[r][c + 1] = g[r + 1][c + 1] = letters[0] c -= 1 print('\n'.join([ ''.join(g[r]) for r in range(n) ])) ``` No
108,150
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Once Bob decided to lay a parquet floor in his living room. The living room is of size n Γ— m metres. Bob had planks of three types: a planks 1 Γ— 2 meters, b planks 2 Γ— 1 meters, and c planks 2 Γ— 2 meters. Help Bob find out, if it is possible to parquet the living room with such a set of planks, and if it is possible, find one of the possible ways to do so. Bob doesn't have to use all the planks. Input The first input line contains 5 space-separated integer numbers n, m, a, b, c (1 ≀ n, m ≀ 100, 0 ≀ a, b, c ≀ 104), n and m β€” the living room dimensions, a, b and c β€” amount of planks 1 Γ— 2, 2 Γ— 1 ΠΈ 2 Γ— 2 respectively. It's not allowed to turn the planks. Output If it is not possible to parquet the room with such a set of planks, output IMPOSSIBLE. Otherwise output one of the possible ways to parquet the room β€” output n lines with m lower-case Latin letters each. Two squares with common sides should contain the same letters, if they belong to one and the same plank, and different letters otherwise. Different planks can be marked with one and the same letter (see examples). If the answer is not unique, output any. Examples Input 2 6 2 2 1 Output aabcca aabdda Input 1 1 100 100 100 Output IMPOSSIBLE Input 4 4 10 10 10 Output aabb aabb bbaa bbaa Submitted Solution: ``` n, m, a, b, c = map(int, input().split()) mat = [0]*n for i in range(n): mat[i] = [0] * m n1 = [min(n*m//4, c), min(m//2 * n, a), min(n//2 * m, b)] p = ['c', 'a', 'b'] z = ['d', 'e', 'f', 'g'] z1 = ['m', 'n'] #print(n1) def fill(h, w): i = 0; j = 0 for k in range(3): while n1[k] > 0: #print(i, j, h, w) if k == 0: if i%4 and j%4: o = 3 elif i%4 and not j%4: o = 2 elif not i%4 and j%4: o = 1 else: o = 0 mat[i][j] = mat[i+1][j] = mat[i][j+1] = mat[i+1][j+1] = z[o]; if p[k] == 'a': mat[i][j] = mat[i][j+1] = 'm' mat[i+1][j] = mat[i+1][j+1] = 'n'; elif p[k] == 'b': mat[i][j] = mat[i+1][j] = 'p' mat[i][j+1] = mat[i+1][j+1] = 'q'; if k == 0: n1[k] -= 1 else: n1[k] -= 2 j += 2 if j >= w: i += 2 j = 0 if i >= h: return True return False def pmat(): for i in range(n): for j in range(m): print(mat[i][j], end='') print('\n', end='') def even(h, w): k1 = 0; k2 = 0 if n1[1] %2 == 1: n1[1] -= 1; k1 = 1 if n1[2] %2 == 1: n1[2] -= 1; k2 = 1 if fill(h, w): n1[1] += k1 n1[2] += k2 return True else: n1[1] += k1 n1[2] += k2 return False if n*m % 2 == 0: if n%2 == 0 and m%2 == 0: if even(n, m): pmat() else: print('IMPOSSIBLE') elif n%2 == 0 and m%2 != 0: n1 = [min(n*m//4, c), min(m//2 * n, a), min(n//2 * m, b)] p = ['c', 'a', 'b'] f = 'b' if even(n, m-1): for i in range(0, n, 2): mat[i][m-1] = 'b'; mat[i+1][m-1] = 'b' if f == 'a': f = 'b' else: f = 'a' n1[2] -= 1 if n1[2] == 0 and i != n-2: print('IMPOSSIBLE') break else: pmat() else: print('IMPOSSIBLE') else: n1 = [min(n*m//4, c), min(n//2 * m, b), min(m//2 * n, a)] p = ['c', 'b', 'a'] f = 'a' if even(n-1, m): for i in range(0, m, 2): mat[n-1][i] = f; mat[n-1][i+1] = f if f == 'a': f = 'b' else: f = 'a' n1[2] -= 1 if n1[2] == 0 and i != m-2: print('IMPOSSIBLE') break else: pmat() else: print('IMPOSSIBLE') elif n*m % 2 != 0: print('IMPOSSIBLE') ``` No
108,151
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Once Bob decided to lay a parquet floor in his living room. The living room is of size n Γ— m metres. Bob had planks of three types: a planks 1 Γ— 2 meters, b planks 2 Γ— 1 meters, and c planks 2 Γ— 2 meters. Help Bob find out, if it is possible to parquet the living room with such a set of planks, and if it is possible, find one of the possible ways to do so. Bob doesn't have to use all the planks. Input The first input line contains 5 space-separated integer numbers n, m, a, b, c (1 ≀ n, m ≀ 100, 0 ≀ a, b, c ≀ 104), n and m β€” the living room dimensions, a, b and c β€” amount of planks 1 Γ— 2, 2 Γ— 1 ΠΈ 2 Γ— 2 respectively. It's not allowed to turn the planks. Output If it is not possible to parquet the room with such a set of planks, output IMPOSSIBLE. Otherwise output one of the possible ways to parquet the room β€” output n lines with m lower-case Latin letters each. Two squares with common sides should contain the same letters, if they belong to one and the same plank, and different letters otherwise. Different planks can be marked with one and the same letter (see examples). If the answer is not unique, output any. Examples Input 2 6 2 2 1 Output aabcca aabdda Input 1 1 100 100 100 Output IMPOSSIBLE Input 4 4 10 10 10 Output aabb aabb bbaa bbaa Submitted Solution: ``` n, m, a, b, c = map(int, input().split()) mat = [0]*n for i in range(n): mat[i] = [0] * m n1 = [min(n*m//4, c), min(m//2 * n, a), min(n//2 * m, b)] p = ['c', 'a', 'b'] z = ['d', 'e', 'f', 'g'] z1 = ['m', 'n', 'u', 'o'] z2 = ['p', 'q', 'r', 'w'] #print(n1) def fill(h, w): if h <= 0 or w <= 0: return True i = 0; j = 0 for k in range(3): while n1[k] > 0: #print(i, j, h, w) if k == 0: if i%4 and j%4: o = 3 elif i%4 and not j%4: o = 2 elif not i%4 and j%4: o = 1 else: o = 0 mat[i][j] = mat[i+1][j] = mat[i][j+1] = mat[i+1][j+1] = z[o]; if p[k] == 'a': if j%4: o = 2 else: o = 0 mat[i][j] = mat[i][j+1] = z1[o] mat[i+1][j] = mat[i+1][j+1] = z1[o+1]; elif p[k] == 'b': if i%4: o = 0 else: o = 2 mat[i][j] = mat[i+1][j] = z2[o] mat[i][j+1] = mat[i+1][j+1] = z2[o+1]; if k == 0: n1[k] -= 1 else: n1[k] -= 2 j += 2 if j >= w: i += 2 j = 0 if i >= h: return True return False def pmat(): for i in range(n): for j in range(m): print(mat[i][j], end='') print('\n', end='') def even(h, w): k1 = 0; k2 = 0 if n1[1] %2 == 1: n1[1] -= 1; k1 = 1 if n1[2] %2 == 1: n1[2] -= 1; k2 = 1 if fill(h, w): n1[1] += k1 n1[2] += k2 return True else: n1[1] += k1 n1[2] += k2 return False if n*m % 2 == 0: if n%2 == 0 and m%2 == 0: if even(n, m): pmat() else: print('IMPOSSIBLE') elif n%2 == 0 and m%2 != 0: n1 = [min(n*m//4, c), min(m//2 * n, a), min(n//2 * m, b)] p = ['c', 'a', 'b'] f = 'b' if even(n, m-1): for i in range(0, n, 2): mat[i][m-1] = f; mat[i+1][m-1] = f if f == 'a': f = 'b' else: f = 'a' n1[2] -= 1 if n1[2] <= 0 and i != n-2: print('IMPOSSIBLE') break else: pmat() else: print('IMPOSSIBLE') else: n1 = [min(n*m//4, c), min(n//2 * m, b), min(m//2 * n, a)] p = ['c', 'b', 'a'] f = 'a' if even(n-1, m): for i in range(0, m, 2): mat[n-1][i] = f; mat[n-1][i+1] = f if f == 'a': f = 'b' else: f = 'a' n1[2] -= 1 if n1[2] <= 0 and i != m-2: print('IMPOSSIBLE') break else: pmat() else: print('IMPOSSIBLE') elif n*m % 2 != 0: print('IMPOSSIBLE') ``` No
108,152
Provide tags and a correct Python 3 solution for this coding contest problem. We often have to copy large volumes of information. Such operation can take up many computer resources. Therefore, in this problem you are advised to come up with a way to copy some part of a number array into another one, quickly. More formally, you've got two arrays of integers a1, a2, ..., an and b1, b2, ..., bn of length n. Also, you've got m queries of two types: 1. Copy the subsegment of array a of length k, starting from position x, into array b, starting from position y, that is, execute by + q = ax + q for all integer q (0 ≀ q < k). The given operation is correct β€” both subsegments do not touch unexistent elements. 2. Determine the value in position x of array b, that is, find value bx. For each query of the second type print the result β€” the value of the corresponding element of array b. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of elements in the arrays and the number of queries, correspondingly. The second line contains an array of integers a1, a2, ..., an (|ai| ≀ 109). The third line contains an array of integers b1, b2, ..., bn (|bi| ≀ 109). Next m lines contain the descriptions of the queries. The i-th line first contains integer ti β€” the type of the i-th query (1 ≀ ti ≀ 2). If ti = 1, then the i-th query means the copying operation. If ti = 2, then the i-th query means taking the value in array b. If ti = 1, then the query type is followed by three integers xi, yi, ki (1 ≀ xi, yi, ki ≀ n) β€” the parameters of the copying query. If ti = 2, then the query type is followed by integer xi (1 ≀ xi ≀ n) β€” the position in array b. All numbers in the lines are separated with single spaces. It is guaranteed that all the queries are correct, that is, the copying borders fit into the borders of arrays a and b. Output For each second type query print the result on a single line. Examples Input 5 10 1 2 0 -1 3 3 1 5 -2 0 2 5 1 3 3 3 2 5 2 4 2 1 1 2 1 4 2 1 2 4 1 4 2 1 2 2 Output 0 3 -1 3 2 3 -1 Tags: data structures Correct Solution: ``` import sys ''' SEGMENT TREE Assign ''' class SegmTree(): ''' - modify elements on interval - get single element ''' def __init__(self, size): N = 1 while N < size: N <<= 1 self.N = N self.tree = [0] * (2*N) def modify_range(self, l, r, value): l += self.N r += self.N while l < r: if l & 1: self.tree[l] = value l += 1 if r & 1: r -= 1 self.tree[r] = value l >>= 1 r >>= 1 def query(self, i): i += self.N latest_change = self.tree[i] p = i while p > 1: p >>= 1 latest_change = max(latest_change, self.tree[p]) return latest_change # inf = open('input.txt', 'r') # reader = (map(int, line.split()) for line in inf) reader = (map(int, line.split()) for line in sys.stdin) input = reader.__next__ n, m = input() a = list(input()) b = list(input()) st = SegmTree(n) request = [None] * (m + 1) for i in range(1, m+1): t, *arg = input() if t == 1: x, y, k = request[i] = arg st.modify_range(y-1, y-1+k, i) else: pos = arg[0] - 1 req_id = st.query(pos) if req_id > 0: x, y, k = request[req_id] ans = a[x+(pos-y)] else: ans = b[pos] sys.stdout.write(f'{ans}\n') # inf.close() ```
108,153
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We often have to copy large volumes of information. Such operation can take up many computer resources. Therefore, in this problem you are advised to come up with a way to copy some part of a number array into another one, quickly. More formally, you've got two arrays of integers a1, a2, ..., an and b1, b2, ..., bn of length n. Also, you've got m queries of two types: 1. Copy the subsegment of array a of length k, starting from position x, into array b, starting from position y, that is, execute by + q = ax + q for all integer q (0 ≀ q < k). The given operation is correct β€” both subsegments do not touch unexistent elements. 2. Determine the value in position x of array b, that is, find value bx. For each query of the second type print the result β€” the value of the corresponding element of array b. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of elements in the arrays and the number of queries, correspondingly. The second line contains an array of integers a1, a2, ..., an (|ai| ≀ 109). The third line contains an array of integers b1, b2, ..., bn (|bi| ≀ 109). Next m lines contain the descriptions of the queries. The i-th line first contains integer ti β€” the type of the i-th query (1 ≀ ti ≀ 2). If ti = 1, then the i-th query means the copying operation. If ti = 2, then the i-th query means taking the value in array b. If ti = 1, then the query type is followed by three integers xi, yi, ki (1 ≀ xi, yi, ki ≀ n) β€” the parameters of the copying query. If ti = 2, then the query type is followed by integer xi (1 ≀ xi ≀ n) β€” the position in array b. All numbers in the lines are separated with single spaces. It is guaranteed that all the queries are correct, that is, the copying borders fit into the borders of arrays a and b. Output For each second type query print the result on a single line. Examples Input 5 10 1 2 0 -1 3 3 1 5 -2 0 2 5 1 3 3 3 2 5 2 4 2 1 1 2 1 4 2 1 2 4 1 4 2 1 2 2 Output 0 3 -1 3 2 3 -1 Submitted Solution: ``` n,m=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) for _ in range(m): temp=list(map(int,input().split())) if len(temp)==4: x,y,k=temp[1],temp[2],temp[3] #b=b[:y-1]+a[x-1:x+k]+b[y-1:] b=b[:y-1]+a[x-1:x+k]+b[x+k:] else: x=temp[1] print(b[x-1]) ``` No
108,154
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We often have to copy large volumes of information. Such operation can take up many computer resources. Therefore, in this problem you are advised to come up with a way to copy some part of a number array into another one, quickly. More formally, you've got two arrays of integers a1, a2, ..., an and b1, b2, ..., bn of length n. Also, you've got m queries of two types: 1. Copy the subsegment of array a of length k, starting from position x, into array b, starting from position y, that is, execute by + q = ax + q for all integer q (0 ≀ q < k). The given operation is correct β€” both subsegments do not touch unexistent elements. 2. Determine the value in position x of array b, that is, find value bx. For each query of the second type print the result β€” the value of the corresponding element of array b. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of elements in the arrays and the number of queries, correspondingly. The second line contains an array of integers a1, a2, ..., an (|ai| ≀ 109). The third line contains an array of integers b1, b2, ..., bn (|bi| ≀ 109). Next m lines contain the descriptions of the queries. The i-th line first contains integer ti β€” the type of the i-th query (1 ≀ ti ≀ 2). If ti = 1, then the i-th query means the copying operation. If ti = 2, then the i-th query means taking the value in array b. If ti = 1, then the query type is followed by three integers xi, yi, ki (1 ≀ xi, yi, ki ≀ n) β€” the parameters of the copying query. If ti = 2, then the query type is followed by integer xi (1 ≀ xi ≀ n) β€” the position in array b. All numbers in the lines are separated with single spaces. It is guaranteed that all the queries are correct, that is, the copying borders fit into the borders of arrays a and b. Output For each second type query print the result on a single line. Examples Input 5 10 1 2 0 -1 3 3 1 5 -2 0 2 5 1 3 3 3 2 5 2 4 2 1 1 2 1 4 2 1 2 4 1 4 2 1 2 2 Output 0 3 -1 3 2 3 -1 Submitted Solution: ``` read_line = lambda: [int(x) for x in input().split(' ')] n, m = read_line() a = read_line() b = read_line() class Node(object): def __init__(_, l=0, r=n): _.l, _.r = l, r _.delta = None if l + 1 < r: _.m = (l + r) // 2 _.lc, _.rc = Node(l, _.m), Node(_.m, r) def set(_, l, r, delta): if _.r <= l or r <= _.l: return if l <= _.l and _.r <= r: _.delta = delta return _.lc.delta, _.rc.delta = _.delta, _.delta _.delta = None _.lc.set(l, r, delta) _.rc.set(l, r, delta) def get(_, i): if _.delta is not None: return a[i + _.delta] if _.l + 1 == _.r: return b[i] return _.lc.get(i) if i < _.m else _.rc.get(i) tree = Node() while m: c = read_line() if c[0] == 1: tree.set(c[2] - 1, c[2] - 1 + c[3], c[1] - c[2]) else: print(tree.get(c[1] - 1)) m -= 1 ``` No
108,155
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We often have to copy large volumes of information. Such operation can take up many computer resources. Therefore, in this problem you are advised to come up with a way to copy some part of a number array into another one, quickly. More formally, you've got two arrays of integers a1, a2, ..., an and b1, b2, ..., bn of length n. Also, you've got m queries of two types: 1. Copy the subsegment of array a of length k, starting from position x, into array b, starting from position y, that is, execute by + q = ax + q for all integer q (0 ≀ q < k). The given operation is correct β€” both subsegments do not touch unexistent elements. 2. Determine the value in position x of array b, that is, find value bx. For each query of the second type print the result β€” the value of the corresponding element of array b. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of elements in the arrays and the number of queries, correspondingly. The second line contains an array of integers a1, a2, ..., an (|ai| ≀ 109). The third line contains an array of integers b1, b2, ..., bn (|bi| ≀ 109). Next m lines contain the descriptions of the queries. The i-th line first contains integer ti β€” the type of the i-th query (1 ≀ ti ≀ 2). If ti = 1, then the i-th query means the copying operation. If ti = 2, then the i-th query means taking the value in array b. If ti = 1, then the query type is followed by three integers xi, yi, ki (1 ≀ xi, yi, ki ≀ n) β€” the parameters of the copying query. If ti = 2, then the query type is followed by integer xi (1 ≀ xi ≀ n) β€” the position in array b. All numbers in the lines are separated with single spaces. It is guaranteed that all the queries are correct, that is, the copying borders fit into the borders of arrays a and b. Output For each second type query print the result on a single line. Examples Input 5 10 1 2 0 -1 3 3 1 5 -2 0 2 5 1 3 3 3 2 5 2 4 2 1 1 2 1 4 2 1 2 4 1 4 2 1 2 2 Output 0 3 -1 3 2 3 -1 Submitted Solution: ``` n,m=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) for _ in range(m): temp=list(map(int,input().split())) if len(temp)==4: x,y,k=temp[1],temp[2],temp[3] b=b[:y-1]+a[x-1:x+k]+b[y-1:] else: x=temp[1] print(b[x-1]) ``` No
108,156
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We often have to copy large volumes of information. Such operation can take up many computer resources. Therefore, in this problem you are advised to come up with a way to copy some part of a number array into another one, quickly. More formally, you've got two arrays of integers a1, a2, ..., an and b1, b2, ..., bn of length n. Also, you've got m queries of two types: 1. Copy the subsegment of array a of length k, starting from position x, into array b, starting from position y, that is, execute by + q = ax + q for all integer q (0 ≀ q < k). The given operation is correct β€” both subsegments do not touch unexistent elements. 2. Determine the value in position x of array b, that is, find value bx. For each query of the second type print the result β€” the value of the corresponding element of array b. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of elements in the arrays and the number of queries, correspondingly. The second line contains an array of integers a1, a2, ..., an (|ai| ≀ 109). The third line contains an array of integers b1, b2, ..., bn (|bi| ≀ 109). Next m lines contain the descriptions of the queries. The i-th line first contains integer ti β€” the type of the i-th query (1 ≀ ti ≀ 2). If ti = 1, then the i-th query means the copying operation. If ti = 2, then the i-th query means taking the value in array b. If ti = 1, then the query type is followed by three integers xi, yi, ki (1 ≀ xi, yi, ki ≀ n) β€” the parameters of the copying query. If ti = 2, then the query type is followed by integer xi (1 ≀ xi ≀ n) β€” the position in array b. All numbers in the lines are separated with single spaces. It is guaranteed that all the queries are correct, that is, the copying borders fit into the borders of arrays a and b. Output For each second type query print the result on a single line. Examples Input 5 10 1 2 0 -1 3 3 1 5 -2 0 2 5 1 3 3 3 2 5 2 4 2 1 1 2 1 4 2 1 2 4 1 4 2 1 2 2 Output 0 3 -1 3 2 3 -1 Submitted Solution: ``` from bisect import bisect_left, bisect_right n, m = map(int, input().split()) a, b = [''] + input().split(), [''] + input().split() c, q = [(0, 0, 0)], [] for i in range(m): t = input() if t[0] == '1': x, y, d = map(int, t[2: ].split()) p = (y, y + d, x - y) u = v = bisect_right(c, p) x, y, d = c[u - 1] if y > p[0]: if y > p[1]: c = c[: u - 1] + [(x, p[0], d), p, (p[1], y, d)] + c[u: ] continue c[u - 1] = (x, p[0], d) while v < len(c) and c[v][1] <= p[1]: v += 1 if v == len(c): c = c[: u] + [p] elif c[v][0] < p[1]: c = c[: u] + [p, (p[1], c[v][1], c[v][2])] + c[v + 1: ] else: c = c[: u] + [p] + c[v: ] else: p = (int(t[2: ]), n, n) u = bisect_right(c, p) - 1 x, y, d = c[u] if p[0] < y: q.append(a[p[0] + d]) else: q.append(b[p[0]]) print('\n'.join(q)) ``` No
108,157
Provide tags and a correct Python 3 solution for this coding contest problem. Smart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (l ≀ r) are integers. We’ll say that string t complies with rule (p, l, r), if the number of occurrences of string t in string p lies between l and r, inclusive. For example, string "ab", complies with rules ("ab", 1, 2) and ("aab", 0, 1), but does not comply with rules ("cd", 1, 2) and ("abab", 0, 1). A substring s[l... r] (1 ≀ l ≀ r ≀ |s|) of string s = s1s2... s|s| (|s| is a length of s) is string slsl + 1... sr. Consider a number of occurrences of string t in string p as a number of pairs of integers l, r (1 ≀ l ≀ r ≀ |p|) such that p[l... r] = t. We’ll say that string t is good if it complies with all n rules. Smart Beaver asks you to help him to write a program that can calculate the number of distinct good substrings of string s. Two substrings s[x... y] and s[z... w] are cosidered to be distinct iff s[x... y] β‰  s[z... w]. Input The first line contains string s. The second line contains integer n. Next n lines contain the rules, one per line. Each of these lines contains a string and two integers pi, li, ri, separated by single spaces (0 ≀ li ≀ ri ≀ |pi|). It is guaranteed that all the given strings are non-empty and only contain lowercase English letters. The input limits for scoring 30 points are (subproblem G1): * 0 ≀ n ≀ 10. * The length of string s and the maximum length of string p is ≀ 200. The input limits for scoring 70 points are (subproblems G1+G2): * 0 ≀ n ≀ 10. * The length of string s and the maximum length of string p is ≀ 2000. The input limits for scoring 100 points are (subproblems G1+G2+G3): * 0 ≀ n ≀ 10. * The length of string s and the maximum length of string p is ≀ 50000. Output Print a single integer β€” the number of good substrings of string s. Examples Input aaab 2 aa 0 0 aab 1 1 Output 3 Input ltntlnen 3 n 0 0 ttlneenl 1 4 lelllt 1 1 Output 2 Input a 0 Output 1 Note There are three good substrings in the first sample test: Β«aabΒ», Β«abΒ» and Β«bΒ». In the second test only substrings Β«eΒ» and Β«tΒ» are good. Tags: hashing, strings Correct Solution: ``` from sys import stdin import re def substrings(s): for i in range(0, len(s)): for l in range(i, len(s)): yield s[i:l+1] test = stdin.readline().rstrip('\n') ruleCount = int(stdin.readline()) rules = [] for i in range(0, ruleCount): ruleStr = stdin.readline() sp = ruleStr.split(' ') m = {} for s in substrings(sp[0]): m[s] = m.get(s, 0) + 1 rules.append((sp[0], int(sp[1]), int(sp[2]), m)) def works(x): for rule in rules: if not rule[1] <= rule[3].get(x, 0) <= rule[2]: return False return True print(len([x for x in set(substrings(test)) if works(x)])) ```
108,158
Provide tags and a correct Python 3 solution for this coding contest problem. Smart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (l ≀ r) are integers. We’ll say that string t complies with rule (p, l, r), if the number of occurrences of string t in string p lies between l and r, inclusive. For example, string "ab", complies with rules ("ab", 1, 2) and ("aab", 0, 1), but does not comply with rules ("cd", 1, 2) and ("abab", 0, 1). A substring s[l... r] (1 ≀ l ≀ r ≀ |s|) of string s = s1s2... s|s| (|s| is a length of s) is string slsl + 1... sr. Consider a number of occurrences of string t in string p as a number of pairs of integers l, r (1 ≀ l ≀ r ≀ |p|) such that p[l... r] = t. We’ll say that string t is good if it complies with all n rules. Smart Beaver asks you to help him to write a program that can calculate the number of distinct good substrings of string s. Two substrings s[x... y] and s[z... w] are cosidered to be distinct iff s[x... y] β‰  s[z... w]. Input The first line contains string s. The second line contains integer n. Next n lines contain the rules, one per line. Each of these lines contains a string and two integers pi, li, ri, separated by single spaces (0 ≀ li ≀ ri ≀ |pi|). It is guaranteed that all the given strings are non-empty and only contain lowercase English letters. The input limits for scoring 30 points are (subproblem G1): * 0 ≀ n ≀ 10. * The length of string s and the maximum length of string p is ≀ 200. The input limits for scoring 70 points are (subproblems G1+G2): * 0 ≀ n ≀ 10. * The length of string s and the maximum length of string p is ≀ 2000. The input limits for scoring 100 points are (subproblems G1+G2+G3): * 0 ≀ n ≀ 10. * The length of string s and the maximum length of string p is ≀ 50000. Output Print a single integer β€” the number of good substrings of string s. Examples Input aaab 2 aa 0 0 aab 1 1 Output 3 Input ltntlnen 3 n 0 0 ttlneenl 1 4 lelllt 1 1 Output 2 Input a 0 Output 1 Note There are three good substrings in the first sample test: Β«aabΒ», Β«abΒ» and Β«bΒ». In the second test only substrings Β«eΒ» and Β«tΒ» are good. Tags: hashing, strings Correct Solution: ``` def count(p, s): start = 0 c = 0 while True: try: pos = s.index(p, start) c += 1 start = pos + 1 except ValueError: return c s = input() n = int(input()) pravs = [] for i in range(n): p, l, r = input().split() l = int(l); r = int(r) pravs.append((p, l, r)) var = set() for l in range(len(s)): for r in range(l+1, len(s)+1): pods = s[l:r] for prav in pravs: if not prav[1] <= count(pods, prav[0]) <= prav[2]: break else: var.add(pods) print(len(var)) ```
108,159
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Smart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (l ≀ r) are integers. We’ll say that string t complies with rule (p, l, r), if the number of occurrences of string t in string p lies between l and r, inclusive. For example, string "ab", complies with rules ("ab", 1, 2) and ("aab", 0, 1), but does not comply with rules ("cd", 1, 2) and ("abab", 0, 1). A substring s[l... r] (1 ≀ l ≀ r ≀ |s|) of string s = s1s2... s|s| (|s| is a length of s) is string slsl + 1... sr. Consider a number of occurrences of string t in string p as a number of pairs of integers l, r (1 ≀ l ≀ r ≀ |p|) such that p[l... r] = t. We’ll say that string t is good if it complies with all n rules. Smart Beaver asks you to help him to write a program that can calculate the number of distinct good substrings of string s. Two substrings s[x... y] and s[z... w] are cosidered to be distinct iff s[x... y] β‰  s[z... w]. Input The first line contains string s. The second line contains integer n. Next n lines contain the rules, one per line. Each of these lines contains a string and two integers pi, li, ri, separated by single spaces (0 ≀ li ≀ ri ≀ |pi|). It is guaranteed that all the given strings are non-empty and only contain lowercase English letters. The input limits for scoring 30 points are (subproblem G1): * 0 ≀ n ≀ 10. * The length of string s and the maximum length of string p is ≀ 200. The input limits for scoring 70 points are (subproblems G1+G2): * 0 ≀ n ≀ 10. * The length of string s and the maximum length of string p is ≀ 2000. The input limits for scoring 100 points are (subproblems G1+G2+G3): * 0 ≀ n ≀ 10. * The length of string s and the maximum length of string p is ≀ 50000. Output Print a single integer β€” the number of good substrings of string s. Examples Input aaab 2 aa 0 0 aab 1 1 Output 3 Input ltntlnen 3 n 0 0 ttlneenl 1 4 lelllt 1 1 Output 2 Input a 0 Output 1 Note There are three good substrings in the first sample test: Β«aabΒ», Β«abΒ» and Β«bΒ». In the second test only substrings Β«eΒ» and Β«tΒ» are good. Submitted Solution: ``` s = input() n = int(input()) rules = [] for i in range(n): rules.append(input().split()) rules[-1][1]=int(rules[-1][1]) rules[-1][2]=int(rules[-1][2]) used = set() ans=0 def check(rules,s): for ru in rules: if ru[1]<=ru[0].count(s)<=ru[2]:continue else: return False return True for i in range(len(s)): for j in range(len(s)): sk=s[i:j+1] if(sk not in used): if check(rules,sk): ans+=1 used.add(sk) print(ans) ``` No
108,160
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Smart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (l ≀ r) are integers. We’ll say that string t complies with rule (p, l, r), if the number of occurrences of string t in string p lies between l and r, inclusive. For example, string "ab", complies with rules ("ab", 1, 2) and ("aab", 0, 1), but does not comply with rules ("cd", 1, 2) and ("abab", 0, 1). A substring s[l... r] (1 ≀ l ≀ r ≀ |s|) of string s = s1s2... s|s| (|s| is a length of s) is string slsl + 1... sr. Consider a number of occurrences of string t in string p as a number of pairs of integers l, r (1 ≀ l ≀ r ≀ |p|) such that p[l... r] = t. We’ll say that string t is good if it complies with all n rules. Smart Beaver asks you to help him to write a program that can calculate the number of distinct good substrings of string s. Two substrings s[x... y] and s[z... w] are cosidered to be distinct iff s[x... y] β‰  s[z... w]. Input The first line contains string s. The second line contains integer n. Next n lines contain the rules, one per line. Each of these lines contains a string and two integers pi, li, ri, separated by single spaces (0 ≀ li ≀ ri ≀ |pi|). It is guaranteed that all the given strings are non-empty and only contain lowercase English letters. The input limits for scoring 30 points are (subproblem G1): * 0 ≀ n ≀ 10. * The length of string s and the maximum length of string p is ≀ 200. The input limits for scoring 70 points are (subproblems G1+G2): * 0 ≀ n ≀ 10. * The length of string s and the maximum length of string p is ≀ 2000. The input limits for scoring 100 points are (subproblems G1+G2+G3): * 0 ≀ n ≀ 10. * The length of string s and the maximum length of string p is ≀ 50000. Output Print a single integer β€” the number of good substrings of string s. Examples Input aaab 2 aa 0 0 aab 1 1 Output 3 Input ltntlnen 3 n 0 0 ttlneenl 1 4 lelllt 1 1 Output 2 Input a 0 Output 1 Note There are three good substrings in the first sample test: Β«aabΒ», Β«abΒ» and Β«bΒ». In the second test only substrings Β«eΒ» and Β«tΒ» are good. Submitted Solution: ``` s = input() n = int(input()) rules = [] for i in range(n): rules.append(input().split()) rules[i][1]=int(rules[i][1]) rules[i][2]=int(rules[i][2]) used = set() ans=0 def check(rules,s): for ru in rules: if ru[1]<=ru[0].count(s)<=ru[2]:continue else: return False return True for i in range(len(s)): sk = '' for j in range(i,len(s)): sk+=s[j] if(sk not in used): if check(rules,sk): ans+=1 used.add(sk) print(ans) ``` No
108,161
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Smart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (l ≀ r) are integers. We’ll say that string t complies with rule (p, l, r), if the number of occurrences of string t in string p lies between l and r, inclusive. For example, string "ab", complies with rules ("ab", 1, 2) and ("aab", 0, 1), but does not comply with rules ("cd", 1, 2) and ("abab", 0, 1). A substring s[l... r] (1 ≀ l ≀ r ≀ |s|) of string s = s1s2... s|s| (|s| is a length of s) is string slsl + 1... sr. Consider a number of occurrences of string t in string p as a number of pairs of integers l, r (1 ≀ l ≀ r ≀ |p|) such that p[l... r] = t. We’ll say that string t is good if it complies with all n rules. Smart Beaver asks you to help him to write a program that can calculate the number of distinct good substrings of string s. Two substrings s[x... y] and s[z... w] are cosidered to be distinct iff s[x... y] β‰  s[z... w]. Input The first line contains string s. The second line contains integer n. Next n lines contain the rules, one per line. Each of these lines contains a string and two integers pi, li, ri, separated by single spaces (0 ≀ li ≀ ri ≀ |pi|). It is guaranteed that all the given strings are non-empty and only contain lowercase English letters. The input limits for scoring 30 points are (subproblem G1): * 0 ≀ n ≀ 10. * The length of string s and the maximum length of string p is ≀ 200. The input limits for scoring 70 points are (subproblems G1+G2): * 0 ≀ n ≀ 10. * The length of string s and the maximum length of string p is ≀ 2000. The input limits for scoring 100 points are (subproblems G1+G2+G3): * 0 ≀ n ≀ 10. * The length of string s and the maximum length of string p is ≀ 50000. Output Print a single integer β€” the number of good substrings of string s. Examples Input aaab 2 aa 0 0 aab 1 1 Output 3 Input ltntlnen 3 n 0 0 ttlneenl 1 4 lelllt 1 1 Output 2 Input a 0 Output 1 Note There are three good substrings in the first sample test: Β«aabΒ», Β«abΒ» and Β«bΒ». In the second test only substrings Β«eΒ» and Β«tΒ» are good. Submitted Solution: ``` s = input() n = int(input()) rules = [] def count(a,b): ans = 0 for i in range(len(a)-len(b)): if a[i:i+len(b)]==b: ans+=1 return ans for i in range(n): rules.append(input().split()) rules[-1][1]=int(rules[-1][1]) rules[-1][2]=int(rules[-1][2]) used = set() ans=0 def check(rules,s): for ru in rules: if ru[1]<=count(ru[0],s)<=ru[2]:continue else: return False return True for i in range(len(s)): for j in range(i,len(s)): sk=s[i:j+1] if(sk not in used): if check(rules,sk): ans+=1 used.add(sk) print(ans) ``` No
108,162
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Smart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (l ≀ r) are integers. We’ll say that string t complies with rule (p, l, r), if the number of occurrences of string t in string p lies between l and r, inclusive. For example, string "ab", complies with rules ("ab", 1, 2) and ("aab", 0, 1), but does not comply with rules ("cd", 1, 2) and ("abab", 0, 1). A substring s[l... r] (1 ≀ l ≀ r ≀ |s|) of string s = s1s2... s|s| (|s| is a length of s) is string slsl + 1... sr. Consider a number of occurrences of string t in string p as a number of pairs of integers l, r (1 ≀ l ≀ r ≀ |p|) such that p[l... r] = t. We’ll say that string t is good if it complies with all n rules. Smart Beaver asks you to help him to write a program that can calculate the number of distinct good substrings of string s. Two substrings s[x... y] and s[z... w] are cosidered to be distinct iff s[x... y] β‰  s[z... w]. Input The first line contains string s. The second line contains integer n. Next n lines contain the rules, one per line. Each of these lines contains a string and two integers pi, li, ri, separated by single spaces (0 ≀ li ≀ ri ≀ |pi|). It is guaranteed that all the given strings are non-empty and only contain lowercase English letters. The input limits for scoring 30 points are (subproblem G1): * 0 ≀ n ≀ 10. * The length of string s and the maximum length of string p is ≀ 200. The input limits for scoring 70 points are (subproblems G1+G2): * 0 ≀ n ≀ 10. * The length of string s and the maximum length of string p is ≀ 2000. The input limits for scoring 100 points are (subproblems G1+G2+G3): * 0 ≀ n ≀ 10. * The length of string s and the maximum length of string p is ≀ 50000. Output Print a single integer β€” the number of good substrings of string s. Examples Input aaab 2 aa 0 0 aab 1 1 Output 3 Input ltntlnen 3 n 0 0 ttlneenl 1 4 lelllt 1 1 Output 2 Input a 0 Output 1 Note There are three good substrings in the first sample test: Β«aabΒ», Β«abΒ» and Β«bΒ». In the second test only substrings Β«eΒ» and Β«tΒ» are good. Submitted Solution: ``` s = input() n = int(input()) sp = [] l = [] r = [] for i in range(n): tmp = input() tsp, tl, tr = tmp.split() sp += [tsp] l += [int(tl)] r += [int(tr)] was = {} for i in range(len(s)): for j in range(len(s)): if (i <= j): c = s[i:j + 1] #print(c) good = True for q in range(n): if (sp[q].count(c) < l[q]) or (sp[q].count(c) > r[q]): #print(c) #print(q + 1) good = False break if (good) and not (c in was): was[c] = 1 #print(c) print(len(was.keys())) ``` No
108,163
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents that the kth destination is at distance ak kilometers from the starting point. No two destinations are located in the same place. Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination. The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once. Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him. Input The first line contains integer n (2 ≀ n ≀ 105). Next line contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ 107). Output Output two integers β€” the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible. Examples Input 3 2 3 5 Output 22 3 Note Consider 6 possible routes: * [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5; * [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7; * [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7; * [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8; * [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9; * [5, 3, 2]: |5 – 0| + |3 – 5| + |2 – 3| = 8. The average travel distance is <image> = <image> = <image>. Tags: combinatorics, implementation, math Correct Solution: ``` import fractions x = int(input()) a = sorted(map(int, input().split())) z = 2 * x + 1 ans = sum(((4 * i - z) * a[i - 1]) for i in range(1, x + 1, 1)) s = fractions._gcd(ans, x) ans //= s; x //= s ss = [] ss.append(ans); ss.append(x) print(*ss) ```
108,164
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents that the kth destination is at distance ak kilometers from the starting point. No two destinations are located in the same place. Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination. The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once. Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him. Input The first line contains integer n (2 ≀ n ≀ 105). Next line contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ 107). Output Output two integers β€” the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible. Examples Input 3 2 3 5 Output 22 3 Note Consider 6 possible routes: * [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5; * [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7; * [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7; * [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8; * [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9; * [5, 3, 2]: |5 – 0| + |3 – 5| + |2 – 3| = 8. The average travel distance is <image> = <image> = <image>. Tags: combinatorics, implementation, math Correct Solution: ``` from fractions import * n = int(input()) a = [int(x) for x in input().split()] a.sort() a1 = a[0] lef_sum = 0 for i in range(1,n): lef_sum+= a[i]*i - a1 a1+=a[i] lef_sum*=2 total = lef_sum+a1 s = Fraction(total,n) print(s.numerator,s.denominator) ```
108,165
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents that the kth destination is at distance ak kilometers from the starting point. No two destinations are located in the same place. Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination. The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once. Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him. Input The first line contains integer n (2 ≀ n ≀ 105). Next line contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ 107). Output Output two integers β€” the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible. Examples Input 3 2 3 5 Output 22 3 Note Consider 6 possible routes: * [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5; * [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7; * [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7; * [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8; * [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9; * [5, 3, 2]: |5 – 0| + |3 – 5| + |2 – 3| = 8. The average travel distance is <image> = <image> = <image>. Tags: combinatorics, implementation, math Correct Solution: ``` import math t=int(input()) l=list(map(int,input().split())) l.sort() s=sum(l) a=s j=1 m=0 for i in l: s-=i m+=s-(t-j)*i j+=1 x=2*m+a y=math.gcd(x,t) x//=y t//=y print(x,t) ```
108,166
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents that the kth destination is at distance ak kilometers from the starting point. No two destinations are located in the same place. Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination. The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once. Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him. Input The first line contains integer n (2 ≀ n ≀ 105). Next line contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ 107). Output Output two integers β€” the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible. Examples Input 3 2 3 5 Output 22 3 Note Consider 6 possible routes: * [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5; * [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7; * [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7; * [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8; * [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9; * [5, 3, 2]: |5 – 0| + |3 – 5| + |2 – 3| = 8. The average travel distance is <image> = <image> = <image>. Tags: combinatorics, implementation, math Correct Solution: ``` import math n=int(input()) arr=[] arr = [int(item) for item in input().split()] length=len(arr) sum2=0 sum=0 for i in range(length): val=arr[i] sum2+=val #print(sum) arr.sort() pre=[] bef=0 for i in range(length): sum+=(i*arr[i]-bef) bef+=arr[i] sum*=2 sum+=sum2 div1=math.gcd(sum,n) sum//=div1 n//=div1 print(sum," ",n) ```
108,167
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents that the kth destination is at distance ak kilometers from the starting point. No two destinations are located in the same place. Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination. The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once. Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him. Input The first line contains integer n (2 ≀ n ≀ 105). Next line contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ 107). Output Output two integers β€” the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible. Examples Input 3 2 3 5 Output 22 3 Note Consider 6 possible routes: * [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5; * [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7; * [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7; * [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8; * [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9; * [5, 3, 2]: |5 – 0| + |3 – 5| + |2 – 3| = 8. The average travel distance is <image> = <image> = <image>. Tags: combinatorics, implementation, math Correct Solution: ``` def gcd(a,b) : return a if b==0 else gcd(b,a%b) n = int(input()) l = input().split() l = [int(i) for i in l] l.sort() t = sum((i+i-n+1)*l[i] for i in range(n)) t = t+t+sum(l) d = gcd(t,n) print(t//d,n//d) # Made By Mostafa_Khaled ```
108,168
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents that the kth destination is at distance ak kilometers from the starting point. No two destinations are located in the same place. Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination. The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once. Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him. Input The first line contains integer n (2 ≀ n ≀ 105). Next line contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ 107). Output Output two integers β€” the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible. Examples Input 3 2 3 5 Output 22 3 Note Consider 6 possible routes: * [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5; * [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7; * [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7; * [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8; * [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9; * [5, 3, 2]: |5 – 0| + |3 – 5| + |2 – 3| = 8. The average travel distance is <image> = <image> = <image>. Tags: combinatorics, implementation, math Correct Solution: ``` def gcd(a, b): return gcd(b % a, a) if a else b n = int(input()) a = sorted(map(int, input().split())) p, q = 0, n for i in range(1, n): p += i * (n - i) * (a[i] - a[i - 1]) p = 2 * p + sum(a) r = gcd(p, q) print(p // r, q // r) ```
108,169
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents that the kth destination is at distance ak kilometers from the starting point. No two destinations are located in the same place. Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination. The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once. Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him. Input The first line contains integer n (2 ≀ n ≀ 105). Next line contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ 107). Output Output two integers β€” the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible. Examples Input 3 2 3 5 Output 22 3 Note Consider 6 possible routes: * [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5; * [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7; * [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7; * [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8; * [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9; * [5, 3, 2]: |5 – 0| + |3 – 5| + |2 – 3| = 8. The average travel distance is <image> = <image> = <image>. Tags: combinatorics, implementation, math Correct Solution: ``` import math n = int(input()) l = [int(x) for x in input().split()] a1 = sum(l) a2 = n a3 = 0 temp = 0 l.sort() for i in range(n): temp += l[n-i-1] a3-=(a1-temp) a3+=(n-i-1)*(l[n-i-1]) a1 = a1+a3+a3 a4 = math.gcd(a1, a2) print(a1//a4, a2//a4) ```
108,170
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents that the kth destination is at distance ak kilometers from the starting point. No two destinations are located in the same place. Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination. The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once. Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him. Input The first line contains integer n (2 ≀ n ≀ 105). Next line contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ 107). Output Output two integers β€” the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible. Examples Input 3 2 3 5 Output 22 3 Note Consider 6 possible routes: * [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5; * [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7; * [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7; * [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8; * [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9; * [5, 3, 2]: |5 – 0| + |3 – 5| + |2 – 3| = 8. The average travel distance is <image> = <image> = <image>. Tags: combinatorics, implementation, math Correct Solution: ``` from math import gcd n = int(input()) a = list(map(int, input().split())) a.sort() s = sum(a) current_sum = 0 s2 = 0 for i in range(n): s2 += a[i] * i - current_sum current_sum += a[i] g = gcd(s + 2*s2, n) print((s +2*s2) // g, n // g) ```
108,171
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents that the kth destination is at distance ak kilometers from the starting point. No two destinations are located in the same place. Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination. The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once. Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him. Input The first line contains integer n (2 ≀ n ≀ 105). Next line contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ 107). Output Output two integers β€” the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible. Examples Input 3 2 3 5 Output 22 3 Note Consider 6 possible routes: * [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5; * [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7; * [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7; * [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8; * [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9; * [5, 3, 2]: |5 – 0| + |3 – 5| + |2 – 3| = 8. The average travel distance is <image> = <image> = <image>. Submitted Solution: ``` from fractions import Fraction n = int(input()) l = [int(x) for x in input().split()] l.sort() f = Fraction(sum([(3-2*n+4*i)*l[i] for i in range(n)]),n) print(f.numerator,f.denominator) ##import itertools ##tot2 = 0 ##for i in itertools.permutations(l): ## loc = 0 ## tot = 0 ## for e in i: ## tot += abs(loc-e) ## loc = e ## #print(i,tot) ## tot2 += tot ##import math ##f2 = Fraction(tot2,math.factorial(n)) ##print(f2.numerator,f2.denominator) ## ``` Yes
108,172
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents that the kth destination is at distance ak kilometers from the starting point. No two destinations are located in the same place. Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination. The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once. Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him. Input The first line contains integer n (2 ≀ n ≀ 105). Next line contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ 107). Output Output two integers β€” the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible. Examples Input 3 2 3 5 Output 22 3 Note Consider 6 possible routes: * [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5; * [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7; * [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7; * [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8; * [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9; * [5, 3, 2]: |5 – 0| + |3 – 5| + |2 – 3| = 8. The average travel distance is <image> = <image> = <image>. Submitted Solution: ``` import math def main(arr): arr.sort() n=len(arr) prefix=[arr[0]] for i in range(1,len(arr)): prefix.append(prefix[-1]+arr[i]) ans=sum(arr) for i in range(len(arr)): s=0 if (i>0): s=prefix[i-1] val=(arr[i]*i-s+(prefix[-1]-prefix[i])-(n-1-i)*arr[i]) ans+=val d=n g=math.gcd(d,ans) print(ans//g,d//g) return n=int(input()) arr=list(map(int,input().split())) main(arr) ``` Yes
108,173
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents that the kth destination is at distance ak kilometers from the starting point. No two destinations are located in the same place. Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination. The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once. Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him. Input The first line contains integer n (2 ≀ n ≀ 105). Next line contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ 107). Output Output two integers β€” the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible. Examples Input 3 2 3 5 Output 22 3 Note Consider 6 possible routes: * [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5; * [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7; * [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7; * [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8; * [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9; * [5, 3, 2]: |5 – 0| + |3 – 5| + |2 – 3| = 8. The average travel distance is <image> = <image> = <image>. Submitted Solution: ``` def gcd(a,b): if b == 0: return a return gcd(b,a%b) n = int(input()) a = [int(x) for x in input().split()] sum1 = sum(a) sum2 = 0 sumbefore = 0 a.sort() for i in range(n): sum2 += a[i]*(i) - sumbefore sumbefore += a[i] sumtot = sum1 + 2*sum2 k = gcd(sumtot,n) print(sumtot//k,n//k) ``` Yes
108,174
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents that the kth destination is at distance ak kilometers from the starting point. No two destinations are located in the same place. Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination. The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once. Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him. Input The first line contains integer n (2 ≀ n ≀ 105). Next line contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ 107). Output Output two integers β€” the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible. Examples Input 3 2 3 5 Output 22 3 Note Consider 6 possible routes: * [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5; * [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7; * [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7; * [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8; * [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9; * [5, 3, 2]: |5 – 0| + |3 – 5| + |2 – 3| = 8. The average travel distance is <image> = <image> = <image>. Submitted Solution: ``` from math import * n=int(input()) arr=list(map(int,input().split())) arr.sort() S1=sum(arr) sums=0 sumsi=arr[0] for i in range(1,n): sums+=(i)*(arr[i])-sumsi sumsi+=arr[i] S2=sums num=S1+2*S2 den=n #print(num,den) while(int(gcd(num,den))!=1): x=gcd(num,den) num=num//x den=den//x print(int(num),int(den)) ``` Yes
108,175
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents that the kth destination is at distance ak kilometers from the starting point. No two destinations are located in the same place. Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination. The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once. Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him. Input The first line contains integer n (2 ≀ n ≀ 105). Next line contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ 107). Output Output two integers β€” the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible. Examples Input 3 2 3 5 Output 22 3 Note Consider 6 possible routes: * [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5; * [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7; * [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7; * [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8; * [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9; * [5, 3, 2]: |5 – 0| + |3 – 5| + |2 – 3| = 8. The average travel distance is <image> = <image> = <image>. Submitted Solution: ``` '''input 3 2 3 5 ''' from sys import stdin import collections import math # main starts n = int(stdin.readline().strip()) arr = list(map(int, stdin.readline().split())) arr.sort() numerator = (n - 1) * sum(arr) temp = 0 for i in range(n): temp += i * arr[i] for i in range(n - 1, -1, -1): temp -= arr[n - 1 - i] * i numerator += 4 * temp denominator = 1 for i in range(2, n + 1): denominator *= i g = math.gcd(numerator, denominator) numerator //= g denominator //= g print(numerator, denominator) ``` No
108,176
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents that the kth destination is at distance ak kilometers from the starting point. No two destinations are located in the same place. Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination. The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once. Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him. Input The first line contains integer n (2 ≀ n ≀ 105). Next line contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ 107). Output Output two integers β€” the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible. Examples Input 3 2 3 5 Output 22 3 Note Consider 6 possible routes: * [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5; * [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7; * [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7; * [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8; * [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9; * [5, 3, 2]: |5 – 0| + |3 – 5| + |2 – 3| = 8. The average travel distance is <image> = <image> = <image>. Submitted Solution: ``` import math t=int(input()) l=list(map(int,input().split())) s=sum(l) a=s j=1 m=0 for i in l: s-=i m+=s-(t-j)*i j+=1 x=2*m+a y=math.gcd(x,t) x//=y t//=y print(x,t) ``` No
108,177
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents that the kth destination is at distance ak kilometers from the starting point. No two destinations are located in the same place. Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination. The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once. Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him. Input The first line contains integer n (2 ≀ n ≀ 105). Next line contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ 107). Output Output two integers β€” the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible. Examples Input 3 2 3 5 Output 22 3 Note Consider 6 possible routes: * [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5; * [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7; * [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7; * [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8; * [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9; * [5, 3, 2]: |5 – 0| + |3 – 5| + |2 – 3| = 8. The average travel distance is <image> = <image> = <image>. Submitted Solution: ``` def gcd(a, b): return gcd(b % a, a) if a else b n = int(input()) a = list(map(int, input().split())) p, q = 0, n for i in range(1, n): p += i * (n - i) * (a[i] - a[i - 1]) p = 2 * p + sum(a) r = gcd(p, q) print(p // r, q // r) ``` No
108,178
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents that the kth destination is at distance ak kilometers from the starting point. No two destinations are located in the same place. Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination. The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once. Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him. Input The first line contains integer n (2 ≀ n ≀ 105). Next line contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ 107). Output Output two integers β€” the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible. Examples Input 3 2 3 5 Output 22 3 Note Consider 6 possible routes: * [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5; * [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7; * [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7; * [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8; * [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9; * [5, 3, 2]: |5 – 0| + |3 – 5| + |2 – 3| = 8. The average travel distance is <image> = <image> = <image>. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase import math from collections import Counter BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) def gcd(a, b): if a == 0: return b return gcd(b % a, a) def lcm(a, b): return (a * b) / gcd(a, b) def main(): n=int(input()) a=list(map(int, input().split())) t=0 a.sort() su=sum(a) for i in range(n): t+=(su-(n-i)*a[i]) su-=a[i] t*=(n-1) t+=sum(a) #print(t) k=gcd(t, n) t//=k n//=k print(t, n) return if __name__ == "__main__": main() ``` No
108,179
Provide tags and a correct Python 3 solution for this coding contest problem. George loves graphs. Most of all, he loves interesting graphs. We will assume that a directed graph is interesting, if it meets the following criteria: * The graph doesn't contain any multiple arcs; * There is vertex v (we'll call her the center), such that for any vertex of graph u, the graph contains arcs (u, v) and (v, u). Please note that the graph also contains loop (v, v). * The outdegree of all vertexes except for the center equals two and the indegree of all vertexes except for the center equals two. The outdegree of vertex u is the number of arcs that go out of u, the indegree of vertex u is the number of arcs that go in u. Please note that the graph can contain loops. However, not everything's that simple. George got a directed graph of n vertices and m arcs as a present. The graph didn't have any multiple arcs. As George loves interesting graphs, he wants to slightly alter the presented graph and transform it into an interesting one. In one alteration he can either remove an arbitrary existing arc from the graph or add an arbitrary arc to the graph. George wonders: what is the minimum number of changes that he needs to obtain an interesting graph from the graph he's got as a present? Help George and find the answer to the question. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 500, 1 ≀ m ≀ 1000) β€” the number of vertices and arcs in the presented graph. Each of the next m lines contains two space-separated integers ai, bi (1 ≀ ai, bi ≀ n) β€” the descriptions of the graph's arcs. Pair (ai, bi) means that the graph contains an arc from vertex number ai to vertex number bi. It is guaranteed that the presented graph doesn't contain multiple arcs. Assume that the grah vertices are numbered 1 through n. Output Print a single integer β€” the answer to George's question. Examples Input 3 7 1 1 2 2 3 1 1 3 3 2 2 3 3 3 Output 0 Input 3 6 1 1 2 2 3 1 3 2 2 3 3 3 Output 1 Input 3 1 2 2 Output 6 Note For more information about directed graphs, please visit: http://en.wikipedia.org/wiki/Directed_graph In the first sample the graph already is interesting, its center is vertex 3. Tags: graph matchings Correct Solution: ``` # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase def matching(n,m,path): # Hopkrocft Karp O(EV^0.5) match1 = [-1]*n match2 = [-1]*m for node in range(n): for nei in path[node]: if match2[nei] == -1: match1[node] = nei match2[nei] = node break while 1: bfs = [node for node in range(n) if match1[node] == -1] depth = [-1]*n for node in bfs: depth[node] = 0 for node in bfs: for nei in path[node]: next_node = match2[nei] if next_node == -1: break if depth[next_node] == -1: depth[next_node] = depth[node]+1 bfs.append(next_node) else: continue break else: break pointer = [len(c) for c in path] dfs = [node for node in range(n) if depth[node] == 0] while dfs: node = dfs[-1] while pointer[node]: pointer[node] -= 1 nei = path[node][pointer[node]] next_node = match2[nei] if next_node == -1: while nei != -1: node = dfs.pop() match2[nei],match1[node],nei = node,nei,match1[node] break elif depth[node]+1 == depth[next_node]: dfs.append(next_node) break else: dfs.pop() return n-match1.count(-1) def main(): n,m = map(int,input().split()) edg = [tuple(map(lambda xx:int(xx)-1,input().split())) for _ in range(m)] ans = float("inf") for centre in range(n): path = [[] for _ in range(n)] cost = 2*n-1 extra = m for u,v in edg: if u == centre or v == centre: cost -= 1 extra -= 1 else: path[u].append(v) maxMatch = matching(n,n,path) extra -= maxMatch cost += n-1-maxMatch+extra ans = min(ans,cost) print(ans) # Fast IO Region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": main() ```
108,180
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. George loves graphs. Most of all, he loves interesting graphs. We will assume that a directed graph is interesting, if it meets the following criteria: * The graph doesn't contain any multiple arcs; * There is vertex v (we'll call her the center), such that for any vertex of graph u, the graph contains arcs (u, v) and (v, u). Please note that the graph also contains loop (v, v). * The outdegree of all vertexes except for the center equals two and the indegree of all vertexes except for the center equals two. The outdegree of vertex u is the number of arcs that go out of u, the indegree of vertex u is the number of arcs that go in u. Please note that the graph can contain loops. However, not everything's that simple. George got a directed graph of n vertices and m arcs as a present. The graph didn't have any multiple arcs. As George loves interesting graphs, he wants to slightly alter the presented graph and transform it into an interesting one. In one alteration he can either remove an arbitrary existing arc from the graph or add an arbitrary arc to the graph. George wonders: what is the minimum number of changes that he needs to obtain an interesting graph from the graph he's got as a present? Help George and find the answer to the question. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 500, 1 ≀ m ≀ 1000) β€” the number of vertices and arcs in the presented graph. Each of the next m lines contains two space-separated integers ai, bi (1 ≀ ai, bi ≀ n) β€” the descriptions of the graph's arcs. Pair (ai, bi) means that the graph contains an arc from vertex number ai to vertex number bi. It is guaranteed that the presented graph doesn't contain multiple arcs. Assume that the grah vertices are numbered 1 through n. Output Print a single integer β€” the answer to George's question. Examples Input 3 7 1 1 2 2 3 1 1 3 3 2 2 3 3 3 Output 0 Input 3 6 1 1 2 2 3 1 3 2 2 3 3 3 Output 1 Input 3 1 2 2 Output 6 Note For more information about directed graphs, please visit: http://en.wikipedia.org/wiki/Directed_graph In the first sample the graph already is interesting, its center is vertex 3. Submitted Solution: ``` import sys def invariant(edges, incomingEdges): edgesCount = sum(map(len, edges)) incomingCount = sum(map(len, incomingEdges)) assert edgesCount == incomingCount, "%i %i - %s %s" % (edgesCount, incomingCount, edges, incomingEdges) for (i, edge) in enumerate(edges): for e in edge: assert i in incomingEdges[e], "%i %s" % (i, incomingEdges[e]) def findCenter(edges, incomingEdges): center = 0 max = 0 for (i, edge) in enumerate(edges): outLength = len(edge) inLength = len(incomingEdges[i]) if i in incomingEdges: inLength -= 1 if outLength + inLength > max: max = outLength + inLength center = i return center def centerise(edges, incomingEdges, center): count = 0 for (i, edge) in enumerate(edges): if i == center: if not i in edges[i]: edges[i].append(i) incomingEdges[i].append(i) count += 1 else: if not center in edge: # Π² Ρ†Π΅Π½Ρ‚Ρ€ edge.append(center) incomingEdges[center].append(i) count += 1 if not i in edges[center]: # ΠΈΠ· Ρ†Π΅Π½Ρ‚Ρ€Π° Π² мСня edges[center].append(i) incomingEdges[i].append(center) count += 1 return count def deleteExtra(edges, incomingEdges, center): count = 0 #outgoing overhead for (i, edge) in enumerate(edges): if i == center: continue while len(edge) > 2: for outgoingEdge in edge: if outgoingEdge == center or i == outgoingEdge: continue if len(incomingEdges[outgoingEdge]) > 2: edge.remove(outgoingEdge) incomingEdges[outgoingEdge].remove(i) count += 1 break else: # passed all element break if len(edge) > 2 and i in edge: edge.remove(i) incomingEdges[i].remove(i) count += 1 while len(edge) > 2: for (j, toRemove) in enumerate(edge): if j == center: continue edge.remove(toRemove) incomingEdges[toRemove].remove(i) count += 1 break return count def addRequired(edges, incomingEdges, center): count = 0 for (i, edge) in enumerate(edges): if i == center: continue if len(edge) < 2: #we should add edge #look for candidate for (j, incomingEdge) in enumerate(incomingEdges): #print("%s %s" % (incomingEdges, incomingEdge)) if len(edge) >= 2: break if i in incomingEdge: continue if len(incomingEdge) < 2: edge.append(j) incomingEdge.append(i) count += 1 #if len(edge) < 2 and i not in edge: # edge.append(i) # incomingEdges[i].append(i) # count += 1 #assert len(edge) == 2, "len(%i) != %i" % (i, len(edge)) return count def addLoops(edges, incomingEdges, center): count = 0 for (i, edge) in enumerate(edges): if i == center: continue if len(edge) < 2 and i not in edge: edge.append(i) incomingEdges[i].append(i) count += 1 assert len(edge) == 2, "len(%i) != %i" % (i, len(edge)) return count def read(): pairs = [] firstRow = sys.stdin.readline() pairs.append(firstRow) v = int(firstRow.split(' ')[1]) for i in range(v): eString = sys.stdin.readline() pairs.append(eString) return pairs def parse(pairs): firstrow = pairs[0].split(' ') (E, V) = (int(firstrow[0]), int(firstrow[1])) es = [] ies = [] for i in range(E): es.append([]) ies.append([]) for row in pairs[1:]: eString = row.split(' ') eFrom = int(eString[0]) - 1 eTo = int(eString[1]) - 1 es[eFrom].append(eTo) ies[eTo].append(eFrom) return es, ies def main(edges, incomingEdges): invariant(edges, incomingEdges) center = findCenter(edges, incomingEdges) result = 0 centerLen = len(edges[center]) + len(incomingEdges[center]) if centerLen != len(edges) * 2: result += centerise(edges, incomingEdges, center) invariant(edges, incomingEdges) invariant(edges, incomingEdges) result += addRequired(edges, incomingEdges, center) result += deleteExtra(edges, incomingEdges, center) invariant(edges, incomingEdges) result += deleteExtra(incomingEdges, edges, center) result += addLoops(edges, incomingEdges, center) invariant(edges, incomingEdges) return result rows = read() edges, incomingEdges = parse(rows) result = main(edges, incomingEdges) print(result) ``` No
108,181
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. George loves graphs. Most of all, he loves interesting graphs. We will assume that a directed graph is interesting, if it meets the following criteria: * The graph doesn't contain any multiple arcs; * There is vertex v (we'll call her the center), such that for any vertex of graph u, the graph contains arcs (u, v) and (v, u). Please note that the graph also contains loop (v, v). * The outdegree of all vertexes except for the center equals two and the indegree of all vertexes except for the center equals two. The outdegree of vertex u is the number of arcs that go out of u, the indegree of vertex u is the number of arcs that go in u. Please note that the graph can contain loops. However, not everything's that simple. George got a directed graph of n vertices and m arcs as a present. The graph didn't have any multiple arcs. As George loves interesting graphs, he wants to slightly alter the presented graph and transform it into an interesting one. In one alteration he can either remove an arbitrary existing arc from the graph or add an arbitrary arc to the graph. George wonders: what is the minimum number of changes that he needs to obtain an interesting graph from the graph he's got as a present? Help George and find the answer to the question. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 500, 1 ≀ m ≀ 1000) β€” the number of vertices and arcs in the presented graph. Each of the next m lines contains two space-separated integers ai, bi (1 ≀ ai, bi ≀ n) β€” the descriptions of the graph's arcs. Pair (ai, bi) means that the graph contains an arc from vertex number ai to vertex number bi. It is guaranteed that the presented graph doesn't contain multiple arcs. Assume that the grah vertices are numbered 1 through n. Output Print a single integer β€” the answer to George's question. Examples Input 3 7 1 1 2 2 3 1 1 3 3 2 2 3 3 3 Output 0 Input 3 6 1 1 2 2 3 1 3 2 2 3 3 3 Output 1 Input 3 1 2 2 Output 6 Note For more information about directed graphs, please visit: http://en.wikipedia.org/wiki/Directed_graph In the first sample the graph already is interesting, its center is vertex 3. Submitted Solution: ``` import sys def invariant(edges, incomingEdges): edgesCount = sum(map(len, edges)) incomingCount = sum(map(len, incomingEdges)) assert edgesCount == incomingCount, "%i %i - %s %s" % (edgesCount, incomingCount, edges, incomingEdges) for (i, edge) in enumerate(edges): for e in edge: assert i in incomingEdges[e], "%i %s" % (i, incomingEdges[e]) def findCenter(edges, incomingEdges): center = 0 max = 0 for (i, edge) in enumerate(edges): outLength = len(edge) inLength = len(incomingEdges[i]) if outLength + inLength > max: max = outLength + inLength center = i return center def centerise(edges, incomingEdges, center): count = 0 for (i, edge) in enumerate(edges): if i == center: if not i in edges[i]: edges[i].append(i) incomingEdges[i].append(i) count += 1 else: if not center in edge: # Π² Ρ†Π΅Π½Ρ‚Ρ€ edge.append(center) incomingEdges[center].append(i) count += 1 if not i in edges[center]: # ΠΈΠ· Ρ†Π΅Π½Ρ‚Ρ€Π° Π² мСня edges[center].append(i) incomingEdges[i].append(center) count += 1 return count def deleteExtra(edges, incomingEdges, center): count = 0 #outgoing overhead for (i, edge) in enumerate(edges): if i == center: continue while len(edge) > 2: for outgoingEdge in edge: if outgoingEdge == center or i == outgoingEdge: continue if len(incomingEdges[outgoingEdge]) > 2: edge.remove(outgoingEdge) incomingEdges[outgoingEdge].remove(i) count += 1 break else: # passed all element break if len(edge) > 2 and i in edge: edge.remove(i) incomingEdges[i].remove(i) count += 1 while len(edge) > 2: for (j, toRemove) in enumerate(edge): if j == center: continue edge.remove(toRemove) incomingEdges[toRemove].remove(i) count += 1 break return count def addRequired(edges, incomingEdges, center): count = 0 for (i, edge) in enumerate(edges): if i == center: continue if len(edge) < 2: #we should add edge #look for candidate for (j, incomingEdge) in enumerate(incomingEdges): #print("%s %s" % (incomingEdges, incomingEdge)) if len(edge) >= 2: break if i in incomingEdge: continue if len(incomingEdge) < 2: edge.append(j) incomingEdge.append(i) count += 1 if len(edge) < 2 and i not in edge: edge.append(i) incomingEdges[i].append(i) count += 1 #assert len(edge) == 2, "len(%i) != %i" % (i, len(edge)) return count def read(): pairs = [] firstRow = sys.stdin.readline() pairs.append(firstRow) v = int(firstRow.split(' ')[1]) for i in range(v): eString = sys.stdin.readline() pairs.append(eString) return pairs def parse(pairs): firstrow = pairs[0].split(' ') (E, V) = (int(firstrow[0]), int(firstrow[1])) es = [] ies = [] for i in range(E): es.append([]) ies.append([]) for row in pairs[1:]: eString = row.split(' ') eFrom = int(eString[0]) - 1 eTo = int(eString[1]) - 1 es[eFrom].append(eTo) ies[eTo].append(eFrom) return es, ies def main(edges, incomingEdges): invariant(edges, incomingEdges) center = findCenter(edges, incomingEdges) result = 0 centerLen = len(edges[center]) + len(incomingEdges[center]) if centerLen != len(edges) * 2: result += centerise(edges, incomingEdges, center) invariant(edges, incomingEdges) invariant(edges, incomingEdges) result += addRequired(edges, incomingEdges, center) result += deleteExtra(edges, incomingEdges, center) invariant(edges, incomingEdges) result += deleteExtra(incomingEdges, edges, center) invariant(edges, incomingEdges) return result rows = read() edges, incomingEdges = parse(rows) result = main(edges, incomingEdges) print(result) ``` No
108,182
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. George loves graphs. Most of all, he loves interesting graphs. We will assume that a directed graph is interesting, if it meets the following criteria: * The graph doesn't contain any multiple arcs; * There is vertex v (we'll call her the center), such that for any vertex of graph u, the graph contains arcs (u, v) and (v, u). Please note that the graph also contains loop (v, v). * The outdegree of all vertexes except for the center equals two and the indegree of all vertexes except for the center equals two. The outdegree of vertex u is the number of arcs that go out of u, the indegree of vertex u is the number of arcs that go in u. Please note that the graph can contain loops. However, not everything's that simple. George got a directed graph of n vertices and m arcs as a present. The graph didn't have any multiple arcs. As George loves interesting graphs, he wants to slightly alter the presented graph and transform it into an interesting one. In one alteration he can either remove an arbitrary existing arc from the graph or add an arbitrary arc to the graph. George wonders: what is the minimum number of changes that he needs to obtain an interesting graph from the graph he's got as a present? Help George and find the answer to the question. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 500, 1 ≀ m ≀ 1000) β€” the number of vertices and arcs in the presented graph. Each of the next m lines contains two space-separated integers ai, bi (1 ≀ ai, bi ≀ n) β€” the descriptions of the graph's arcs. Pair (ai, bi) means that the graph contains an arc from vertex number ai to vertex number bi. It is guaranteed that the presented graph doesn't contain multiple arcs. Assume that the grah vertices are numbered 1 through n. Output Print a single integer β€” the answer to George's question. Examples Input 3 7 1 1 2 2 3 1 1 3 3 2 2 3 3 3 Output 0 Input 3 6 1 1 2 2 3 1 3 2 2 3 3 3 Output 1 Input 3 1 2 2 Output 6 Note For more information about directed graphs, please visit: http://en.wikipedia.org/wiki/Directed_graph In the first sample the graph already is interesting, its center is vertex 3. Submitted Solution: ``` import sys def invariant(edges, incomingEdges): edgesCount = sum(map(len, edges)) incomingCount = sum(map(len, incomingEdges)) assert edgesCount == incomingCount, "%i %i - %s %s" % (edgesCount, incomingCount, edges, incomingEdges) for (i, edge) in enumerate(edges): for e in edge: assert i in incomingEdges[e], "%i %s" % (i, incomingEdges[e]) def findCenter(edges, incomingEdges): center = 0 max = 0 for (i, edge) in enumerate(edges): outLength = len(edge) inLength = len(incomingEdges[i]) if outLength + inLength > max: max = outLength + inLength center = i return center def centerise(edges, incomingEdges, center): count = 0 for (i, edge) in enumerate(edges): if i == center: if not i in edges[i]: edges[i].append(i) incomingEdges[i].append(i) count += 1 else: if not center in edge: # Π² Ρ†Π΅Π½Ρ‚Ρ€ edge.append(center) incomingEdges[center].append(i) count += 1 if not i in edges[center]: # ΠΈΠ· Ρ†Π΅Π½Ρ‚Ρ€Π° Π² мСня edges[center].append(i) incomingEdges[i].append(center) count += 1 return count def deleteExtra(edges, incomingEdges, center): count = 0 #outgoing overhead for (i, edge) in enumerate(edges): if i == center: continue while len(edge) > 2: for outgoingEdge in edge: if outgoingEdge == center or i == outgoingEdge: continue if len(incomingEdges[outgoingEdge]) > 2: edge.remove(outgoingEdge) incomingEdges[outgoingEdge].remove(i) count += 1 break else: # passed all element break if len(edge) > 2 and i in edge: edge.remove(i) incomingEdges[i].remove(i) count += 1 while len(edge) > 2: for (j, toRemove) in enumerate(edge): if j == center: continue edge.remove(toRemove) incomingEdges[toRemove].remove(i) count += 1 break return count def addRequired(edges, incomingEdges, center): count = 0 for (i, edge) in enumerate(edges): if i == center: continue if len(edge) < 2: #we should add edge #look for candidate for (j, incomingEdge) in enumerate(incomingEdges): #print("%s %s" % (incomingEdges, incomingEdge)) if len(edge) >= 2: break if i in incomingEdge: continue if len(incomingEdge) < 2: edge.append(j) incomingEdge.append(i) count += 1 #if len(edge) < 2 and i not in edge: # edge.append(i) # incomingEdges[i].append(i) # count += 1 #assert len(edge) == 2, "len(%i) != %i" % (i, len(edge)) return count def addLoops(edges, incomingEdges, center): count = 0 for (i, edge) in enumerate(edges): if i == center: continue if len(edge) < 2 and i not in edge: edge.append(i) incomingEdges[i].append(i) count += 1 assert len(edge) == 2, "len(%i) != %i" % (i, len(edge)) return count def read(): pairs = [] firstRow = sys.stdin.readline() pairs.append(firstRow) v = int(firstRow.split(' ')[1]) for i in range(v): eString = sys.stdin.readline() pairs.append(eString) return pairs def parse(pairs): firstrow = pairs[0].split(' ') (E, V) = (int(firstrow[0]), int(firstrow[1])) es = [] ies = [] for i in range(E): es.append([]) ies.append([]) for row in pairs[1:]: eString = row.split(' ') eFrom = int(eString[0]) - 1 eTo = int(eString[1]) - 1 es[eFrom].append(eTo) ies[eTo].append(eFrom) return es, ies def main(edges, incomingEdges): invariant(edges, incomingEdges) center = findCenter(edges, incomingEdges) result = 0 centerLen = len(edges[center]) + len(incomingEdges[center]) if centerLen != len(edges) * 2: result += centerise(edges, incomingEdges, center) invariant(edges, incomingEdges) invariant(edges, incomingEdges) result += addRequired(edges, incomingEdges, center) result += deleteExtra(edges, incomingEdges, center) invariant(edges, incomingEdges) result += deleteExtra(incomingEdges, edges, center) result += addLoops(edges, incomingEdges, center) invariant(edges, incomingEdges) return result rows = read() edges, incomingEdges = parse(rows) result = main(edges, incomingEdges) print(result) ``` No
108,183
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. George loves graphs. Most of all, he loves interesting graphs. We will assume that a directed graph is interesting, if it meets the following criteria: * The graph doesn't contain any multiple arcs; * There is vertex v (we'll call her the center), such that for any vertex of graph u, the graph contains arcs (u, v) and (v, u). Please note that the graph also contains loop (v, v). * The outdegree of all vertexes except for the center equals two and the indegree of all vertexes except for the center equals two. The outdegree of vertex u is the number of arcs that go out of u, the indegree of vertex u is the number of arcs that go in u. Please note that the graph can contain loops. However, not everything's that simple. George got a directed graph of n vertices and m arcs as a present. The graph didn't have any multiple arcs. As George loves interesting graphs, he wants to slightly alter the presented graph and transform it into an interesting one. In one alteration he can either remove an arbitrary existing arc from the graph or add an arbitrary arc to the graph. George wonders: what is the minimum number of changes that he needs to obtain an interesting graph from the graph he's got as a present? Help George and find the answer to the question. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 500, 1 ≀ m ≀ 1000) β€” the number of vertices and arcs in the presented graph. Each of the next m lines contains two space-separated integers ai, bi (1 ≀ ai, bi ≀ n) β€” the descriptions of the graph's arcs. Pair (ai, bi) means that the graph contains an arc from vertex number ai to vertex number bi. It is guaranteed that the presented graph doesn't contain multiple arcs. Assume that the grah vertices are numbered 1 through n. Output Print a single integer β€” the answer to George's question. Examples Input 3 7 1 1 2 2 3 1 1 3 3 2 2 3 3 3 Output 0 Input 3 6 1 1 2 2 3 1 3 2 2 3 3 3 Output 1 Input 3 1 2 2 Output 6 Note For more information about directed graphs, please visit: http://en.wikipedia.org/wiki/Directed_graph In the first sample the graph already is interesting, its center is vertex 3. Submitted Solution: ``` import sys def findCenter(edges, incomingEdges): center = 0 max = 0 for (i, edge) in enumerate(edges): outLength = len(edge) inLength = len(incomingEdges[i]) if i in incomingEdges: inLength -= 1 if outLength + inLength > max: max = outLength + inLength center = i return center def centerise(edges, incomingEdges, center): count = 0 for (i, edge) in enumerate(edges): if i == center: if not i in edges[i]: edges[i].append(i) incomingEdges[i].append(i) count += 1 else: if not center in edge: # Π² Ρ†Π΅Π½Ρ‚Ρ€ edge.append(center) incomingEdges[center].append(i) count += 1 if not i in edges[center]: # ΠΈΠ· Ρ†Π΅Π½Ρ‚Ρ€Π° Π² мСня edges[center].append(i) incomingEdges[i].append(center) count += 1 return count def deleteExtra(edges, incomingEdges, center): count = 0 #outgoing overhead for (i, edge) in enumerate(edges): if i == center: continue while len(edge) > 2: for outgoingEdge in edge: if outgoingEdge == center or i == outgoingEdge: continue if len(incomingEdges[outgoingEdge]) > 2: edge.remove(outgoingEdge) incomingEdges[outgoingEdge].remove(i) count += 1 break else: # passed all element break if len(edge) > 2 and i in edge: edge.remove(i) incomingEdges[i].remove(i) count += 1 while len(edge) > 2: for toRemove in edge: if toRemove == center: continue edge.remove(toRemove) incomingEdges[toRemove].remove(i) count += 1 break return count def addRequired(edges, incomingEdges, center): count = 0 for (i, edge) in enumerate(edges): if i == center: continue while len(edge) < 2: if len(incomingEdges[i]) < 2: edge.append(i) incomingEdges[i].append(i) count += 1 else: for (j, incomingEdge) in enumerate(incomingEdges): if len(incomingEdge) < 2: incomingEdge.append(i) edge.append(j) count += 1 break return count def read(): pairs = [] firstRow = sys.stdin.readline() pairs.append(firstRow) v = int(firstRow.split(' ')[1]) for i in range(v): eString = sys.stdin.readline() pairs.append(eString) return pairs def parse(pairs): firstrow = pairs[0].split(' ') (E, V) = (int(firstrow[0]), int(firstrow[1])) es = [] ies = [] for i in range(E): es.append([]) ies.append([]) for row in pairs[1:]: eString = row.split(' ') eFrom = int(eString[0]) - 1 eTo = int(eString[1]) - 1 es[eFrom].append(eTo) ies[eTo].append(eFrom) return es, ies def check(edges, center): for (i, edge) in enumerate(edges): if i == center: assert len(edge) == len(edges), "len = %i, %s" % (len(edge), edge) continue assert len(edge) == 2, "len() == %i %s i=%i" % (len(edge), edge, i) def main(edges, incomingEdges): center = findCenter(edges, incomingEdges) result = 0 centerLen = len(edges[center]) + len(incomingEdges[center]) if centerLen != len(edges) * 2: result += centerise(edges, incomingEdges, center) result += deleteExtra(edges, incomingEdges, center) result += deleteExtra(incomingEdges, edges, center) result += addRequired(edges, incomingEdges, center) check(edges, center) check(incomingEdges, center) return result rows = read() edges, incomingEdges = parse(rows) result = main(edges, incomingEdges) print(result) ``` No
108,184
Provide tags and a correct Python 3 solution for this coding contest problem. Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter. The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland. Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of ​​m pieces of paper in the garland. Calculate what the maximum total area of ​​the pieces of paper in the garland Vasya can get. Input The first line contains a non-empty sequence of n (1 ≀ n ≀ 1000) small English letters ("a"..."z"). Each letter means that Vasya has a sheet of paper of the corresponding color. The second line contains a non-empty sequence of m (1 ≀ m ≀ 1000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make. Output Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer. Examples Input aaabbac aabbccac Output 6 Input a z Output -1 Note In the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6. In the second test sample Vasya cannot make a garland at all β€” he doesn't have a sheet of color z. Tags: implementation Correct Solution: ``` have = input() required = input() have_dict = {} required_dict = {} for char in have: if char not in have_dict: have_dict[char] = 0 have_dict[char] += 1 for char in required: if char not in required_dict: required_dict[char] = 0 required_dict[char] += 1 # print(have_dict) # print(required_dict) ans = 0 for c in required_dict: if c not in have_dict: print(-1) exit() else: if required_dict[c] == have_dict[c]: ans += have_dict[c] elif required_dict[c] < have_dict[c]: ans += required_dict[c] elif required_dict[c] > have_dict[c]: ans += have_dict[c] print(ans) ```
108,185
Provide tags and a correct Python 3 solution for this coding contest problem. Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter. The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland. Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of ​​m pieces of paper in the garland. Calculate what the maximum total area of ​​the pieces of paper in the garland Vasya can get. Input The first line contains a non-empty sequence of n (1 ≀ n ≀ 1000) small English letters ("a"..."z"). Each letter means that Vasya has a sheet of paper of the corresponding color. The second line contains a non-empty sequence of m (1 ≀ m ≀ 1000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make. Output Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer. Examples Input aaabbac aabbccac Output 6 Input a z Output -1 Note In the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6. In the second test sample Vasya cannot make a garland at all β€” he doesn't have a sheet of color z. Tags: implementation Correct Solution: ``` import collections def m(): # n= "aaabbac" # m= "aabbccac" n = input() m = input() nhash = collections.defaultdict(int) mhash = collections.defaultdict(int) for i in n: nhash[i] +=1 for i in m: mhash[i] +=1 sum = 0 for i,k in mhash.items(): if(nhash[i] ==0): return 0 sum += min(k,nhash[i]) return sum res = m() if res == 0: print(-1) else: print(res) ```
108,186
Provide tags and a correct Python 3 solution for this coding contest problem. Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter. The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland. Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of ​​m pieces of paper in the garland. Calculate what the maximum total area of ​​the pieces of paper in the garland Vasya can get. Input The first line contains a non-empty sequence of n (1 ≀ n ≀ 1000) small English letters ("a"..."z"). Each letter means that Vasya has a sheet of paper of the corresponding color. The second line contains a non-empty sequence of m (1 ≀ m ≀ 1000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make. Output Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer. Examples Input aaabbac aabbccac Output 6 Input a z Output -1 Note In the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6. In the second test sample Vasya cannot make a garland at all β€” he doesn't have a sheet of color z. Tags: implementation Correct Solution: ``` n = [] m = [] n[0:] = input() m[0:] = input() m_unique = list(set(m)) area = 0 for i in m_unique: if i not in n: area = -1 break area += m.count(i) if m.count(i) <= n.count(i) else n.count(i) print(area) ```
108,187
Provide tags and a correct Python 3 solution for this coding contest problem. Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter. The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland. Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of ​​m pieces of paper in the garland. Calculate what the maximum total area of ​​the pieces of paper in the garland Vasya can get. Input The first line contains a non-empty sequence of n (1 ≀ n ≀ 1000) small English letters ("a"..."z"). Each letter means that Vasya has a sheet of paper of the corresponding color. The second line contains a non-empty sequence of m (1 ≀ m ≀ 1000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make. Output Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer. Examples Input aaabbac aabbccac Output 6 Input a z Output -1 Note In the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6. In the second test sample Vasya cannot make a garland at all β€” he doesn't have a sheet of color z. Tags: implementation Correct Solution: ``` from collections import Counter C = lambda: Counter(input()) s, t = C(), C() x = sum(min(s[ch],t[ch]) for ch in s) print(x if x and set(s)>=set(t) else -1) ```
108,188
Provide tags and a correct Python 3 solution for this coding contest problem. Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter. The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland. Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of ​​m pieces of paper in the garland. Calculate what the maximum total area of ​​the pieces of paper in the garland Vasya can get. Input The first line contains a non-empty sequence of n (1 ≀ n ≀ 1000) small English letters ("a"..."z"). Each letter means that Vasya has a sheet of paper of the corresponding color. The second line contains a non-empty sequence of m (1 ≀ m ≀ 1000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make. Output Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer. Examples Input aaabbac aabbccac Output 6 Input a z Output -1 Note In the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6. In the second test sample Vasya cannot make a garland at all β€” he doesn't have a sheet of color z. Tags: implementation Correct Solution: ``` l1=list(input()) l2=list(input()) d1={} d2={} for i in l1: try: d1[i]+=1 except: d1[i]=1 for i in l2: try: d2[i]+=1 except: d2[i]=1 ans=0 for i in d2: try: ans+=min(d1[i],d2[i]) except: print(-1) exit() print(ans) ```
108,189
Provide tags and a correct Python 3 solution for this coding contest problem. Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter. The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland. Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of ​​m pieces of paper in the garland. Calculate what the maximum total area of ​​the pieces of paper in the garland Vasya can get. Input The first line contains a non-empty sequence of n (1 ≀ n ≀ 1000) small English letters ("a"..."z"). Each letter means that Vasya has a sheet of paper of the corresponding color. The second line contains a non-empty sequence of m (1 ≀ m ≀ 1000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make. Output Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer. Examples Input aaabbac aabbccac Output 6 Input a z Output -1 Note In the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6. In the second test sample Vasya cannot make a garland at all β€” he doesn't have a sheet of color z. Tags: implementation Correct Solution: ``` from collections import Counter s=list(input()) t=list(input()) d1=Counter(s) d2=Counter(t) f=1 for i in d2: if(d1[i]==0): f=0 if(f): ans=0 for i in d2: if(d2[i]<=d1[i]): ans+=d2[i] else: ans+=d1[i] print(ans) else: print(-1) ```
108,190
Provide tags and a correct Python 3 solution for this coding contest problem. Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter. The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland. Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of ​​m pieces of paper in the garland. Calculate what the maximum total area of ​​the pieces of paper in the garland Vasya can get. Input The first line contains a non-empty sequence of n (1 ≀ n ≀ 1000) small English letters ("a"..."z"). Each letter means that Vasya has a sheet of paper of the corresponding color. The second line contains a non-empty sequence of m (1 ≀ m ≀ 1000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make. Output Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer. Examples Input aaabbac aabbccac Output 6 Input a z Output -1 Note In the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6. In the second test sample Vasya cannot make a garland at all β€” he doesn't have a sheet of color z. Tags: implementation Correct Solution: ``` have=input() want=input() c=True area=0 for i in want: if have.count(i)==0: c=False if c: done=[] for i in want: if i not in done: if have.count(i)<=want.count(i) : area+=have.count(i) done.append(i) else: area+=want.count(i) done.append(i) print(area) else: print(-1) ```
108,191
Provide tags and a correct Python 3 solution for this coding contest problem. Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter. The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland. Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of ​​m pieces of paper in the garland. Calculate what the maximum total area of ​​the pieces of paper in the garland Vasya can get. Input The first line contains a non-empty sequence of n (1 ≀ n ≀ 1000) small English letters ("a"..."z"). Each letter means that Vasya has a sheet of paper of the corresponding color. The second line contains a non-empty sequence of m (1 ≀ m ≀ 1000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make. Output Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer. Examples Input aaabbac aabbccac Output 6 Input a z Output -1 Note In the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6. In the second test sample Vasya cannot make a garland at all β€” he doesn't have a sheet of color z. Tags: implementation Correct Solution: ``` n = input() m = input() def f(n,m): an=[0]*26 am=[0]*26 for i in (n): an[ord(i)-97]+=1 for j in (m): am[ord(j)-97]+=1 c = 0 for x in range(26): if am[x]!=0 and an[x]==0: return (-1) elif am[x]>an[x]: c+=an[x] else: c+=am[x] return c print(f(n,m)) ```
108,192
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter. The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland. Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of ​​m pieces of paper in the garland. Calculate what the maximum total area of ​​the pieces of paper in the garland Vasya can get. Input The first line contains a non-empty sequence of n (1 ≀ n ≀ 1000) small English letters ("a"..."z"). Each letter means that Vasya has a sheet of paper of the corresponding color. The second line contains a non-empty sequence of m (1 ≀ m ≀ 1000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make. Output Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer. Examples Input aaabbac aabbccac Output 6 Input a z Output -1 Note In the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6. In the second test sample Vasya cannot make a garland at all β€” he doesn't have a sheet of color z. Submitted Solution: ``` n = list(input()) m = list(input()) ns = {} ms = {} for i in n: if not ns.get(i): ns[i] = 0 ns[i] += 1 for i in m: if not ms.get(i): ms[i] = 0 ms[i] += 1 count = 0 bad = False for c in ms: if not ns.get(c): count = -1 break count += min(ns[c], ms[c]) print(count) ``` Yes
108,193
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter. The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland. Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of ​​m pieces of paper in the garland. Calculate what the maximum total area of ​​the pieces of paper in the garland Vasya can get. Input The first line contains a non-empty sequence of n (1 ≀ n ≀ 1000) small English letters ("a"..."z"). Each letter means that Vasya has a sheet of paper of the corresponding color. The second line contains a non-empty sequence of m (1 ≀ m ≀ 1000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make. Output Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer. Examples Input aaabbac aabbccac Output 6 Input a z Output -1 Note In the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6. In the second test sample Vasya cannot make a garland at all β€” he doesn't have a sheet of color z. Submitted Solution: ``` from collections import Counter a = Counter(input()) b = Counter(input()) c = 0 for k,v in b.items(): if k not in a: print(-1) exit(0) c += min(v,a.get(k,0)) print(c) ``` Yes
108,194
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter. The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland. Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of ​​m pieces of paper in the garland. Calculate what the maximum total area of ​​the pieces of paper in the garland Vasya can get. Input The first line contains a non-empty sequence of n (1 ≀ n ≀ 1000) small English letters ("a"..."z"). Each letter means that Vasya has a sheet of paper of the corresponding color. The second line contains a non-empty sequence of m (1 ≀ m ≀ 1000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make. Output Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer. Examples Input aaabbac aabbccac Output 6 Input a z Output -1 Note In the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6. In the second test sample Vasya cannot make a garland at all β€” he doesn't have a sheet of color z. Submitted Solution: ``` n = input() m = input() dn = dict() dm = dict() for i in n: if i not in dn: dn[i] = 1 else: dn[i]+=1 #print ("dn : ",dn) for i in m: if i not in dm: dm[i] = 1 else: dm[i]+=1 #print ("dm : ",dm) area = 0 for c in dm: if c not in dn: area = -1 break else: if dn[c] > dm[c]: area += dm[c] else: area += dn[c] print(area) ``` Yes
108,195
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter. The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland. Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of ​​m pieces of paper in the garland. Calculate what the maximum total area of ​​the pieces of paper in the garland Vasya can get. Input The first line contains a non-empty sequence of n (1 ≀ n ≀ 1000) small English letters ("a"..."z"). Each letter means that Vasya has a sheet of paper of the corresponding color. The second line contains a non-empty sequence of m (1 ≀ m ≀ 1000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make. Output Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer. Examples Input aaabbac aabbccac Output 6 Input a z Output -1 Note In the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6. In the second test sample Vasya cannot make a garland at all β€” he doesn't have a sheet of color z. Submitted Solution: ``` def start(): x = input() y = input() u = {} for i in x: try: u[i] += 1 except: u[i] = 1 v = {} for i in y: try: v[i] += 1 except: v[i] = 1 ans = 0 for i,j in v.items(): try: ans += min(0,u[i]-v[i])+v[i] except: print(-1) exit() print(ans) tc=1 # tc=int(input()) while tc: start() tc=tc-1 ``` Yes
108,196
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter. The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland. Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of ​​m pieces of paper in the garland. Calculate what the maximum total area of ​​the pieces of paper in the garland Vasya can get. Input The first line contains a non-empty sequence of n (1 ≀ n ≀ 1000) small English letters ("a"..."z"). Each letter means that Vasya has a sheet of paper of the corresponding color. The second line contains a non-empty sequence of m (1 ≀ m ≀ 1000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make. Output Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer. Examples Input aaabbac aabbccac Output 6 Input a z Output -1 Note In the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6. In the second test sample Vasya cannot make a garland at all β€” he doesn't have a sheet of color z. Submitted Solution: ``` a=list(input()) b=list(input()) cont=0 for z in range(len(b)): for g in range(len(a)): if b[z]==a[g]: cont=cont+1 a[g]='0' break print(cont if cont>0 else '-1') ``` No
108,197
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter. The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland. Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of ​​m pieces of paper in the garland. Calculate what the maximum total area of ​​the pieces of paper in the garland Vasya can get. Input The first line contains a non-empty sequence of n (1 ≀ n ≀ 1000) small English letters ("a"..."z"). Each letter means that Vasya has a sheet of paper of the corresponding color. The second line contains a non-empty sequence of m (1 ≀ m ≀ 1000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make. Output Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer. Examples Input aaabbac aabbccac Output 6 Input a z Output -1 Note In the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6. In the second test sample Vasya cannot make a garland at all β€” he doesn't have a sheet of color z. Submitted Solution: ``` from sys import stdin,stdout from collections import Counter nmbr=lambda:int(stdin.readline()) lst = lambda: list(map(int, input().split())) for i in range(1):#nmbr(): d=Counter(input()) d1=Counter(input()) ans=0 for k,v in d1.items(): ans+=min(v,d.get(k,0)) print(ans) ``` No
108,198
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter. The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland. Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of ​​m pieces of paper in the garland. Calculate what the maximum total area of ​​the pieces of paper in the garland Vasya can get. Input The first line contains a non-empty sequence of n (1 ≀ n ≀ 1000) small English letters ("a"..."z"). Each letter means that Vasya has a sheet of paper of the corresponding color. The second line contains a non-empty sequence of m (1 ≀ m ≀ 1000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make. Output Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer. Examples Input aaabbac aabbccac Output 6 Input a z Output -1 Note In the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6. In the second test sample Vasya cannot make a garland at all β€” he doesn't have a sheet of color z. Submitted Solution: ``` def start(): x = input() y = input() u = {} for i in x: try: u[i] += 1 except: u[i] = 1 v = {} for i in y: try: v[i] += 1 except: v[i] = 1 ans = 0 for i,j in v.items(): try: ans += min(0,u[i]-v[i])+v[i] except: ans += 0 if ans == 0: ans = -1 print(ans) tc=1 # tc=int(input()) while tc: start() tc=tc-1 ``` No
108,199