text
stringlengths
198
433k
conversation_id
int64
0
109k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Guy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon P which is defined by coordinates of its vertices. Define P(x,y) as a polygon obtained by translating P by vector \overrightarrow {(x,y)}. The picture below depicts an example of the translation: <image> Define T as a set of points which is the union of all P(x,y) such that the origin (0,0) lies in P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y) lies in T only if there are two points A,B in P such that \overrightarrow {AB} = \overrightarrow {(x,y)}. One can prove T is a polygon too. For example, if P is a regular triangle then T is a regular hexagon. At the picture below P is drawn in black and some P(x,y) which contain the origin are drawn in colored: <image> The spaceship has the best aerodynamic performance if P and T are similar. Your task is to check whether the polygons P and T are [similar](https://tinyurl.com/vp5m7vl). Input The first line of input will contain a single integer n (3 ≀ n ≀ 10^5) β€” the number of points. The i-th of the next n lines contains two integers x_i, y_i (|x_i|, |y_i| ≀ 10^9), denoting the coordinates of the i-th vertex. It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon. Output Output "YES" in a separate line, if P and T are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower). Examples Input 4 1 0 4 1 3 4 0 3 Output YES Input 3 100 86 50 0 150 0 Output nO Input 8 0 0 1 0 2 1 3 3 4 6 3 6 2 5 1 3 Output YES Note The following image shows the first sample: both P and T are squares. The second sample was shown in the statements. <image> Submitted Solution: ``` from collections import defaultdict from math import gcd n = int(input()) points = [] for i in range(n): x, y = (int(i) for i in input().split(' ')) points.append((x, y)) points.append(points[0]) if n % 2 == 1: print("NO") else: d = defaultdict(lambda: 0) for i in range(len(points) - 1): x1, y1 = points[i] x2, y2 = points[i + 1] lcm = gcd((y2 - y1), (x2 - x1)) k1 = (y2 - y1) // lcm k2 = (x2 - x1) // lcm d[(k1, k2)] += 1 flag = True for i in d: if d[i] % 2 != 0: flag = False break if flag: print("YES") else: print("NO") ``` No
12,600
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Guy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon P which is defined by coordinates of its vertices. Define P(x,y) as a polygon obtained by translating P by vector \overrightarrow {(x,y)}. The picture below depicts an example of the translation: <image> Define T as a set of points which is the union of all P(x,y) such that the origin (0,0) lies in P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y) lies in T only if there are two points A,B in P such that \overrightarrow {AB} = \overrightarrow {(x,y)}. One can prove T is a polygon too. For example, if P is a regular triangle then T is a regular hexagon. At the picture below P is drawn in black and some P(x,y) which contain the origin are drawn in colored: <image> The spaceship has the best aerodynamic performance if P and T are similar. Your task is to check whether the polygons P and T are [similar](https://tinyurl.com/vp5m7vl). Input The first line of input will contain a single integer n (3 ≀ n ≀ 10^5) β€” the number of points. The i-th of the next n lines contains two integers x_i, y_i (|x_i|, |y_i| ≀ 10^9), denoting the coordinates of the i-th vertex. It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon. Output Output "YES" in a separate line, if P and T are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower). Examples Input 4 1 0 4 1 3 4 0 3 Output YES Input 3 100 86 50 0 150 0 Output nO Input 8 0 0 1 0 2 1 3 3 4 6 3 6 2 5 1 3 Output YES Note The following image shows the first sample: both P and T are squares. The second sample was shown in the statements. <image> Submitted Solution: ``` q = int(input()) vertexP = [] z = True for x in range(q): x, y = input().split() x, y = float(x), float(y) vertexP.append([x, y]) minX = min([each[0] for each in vertexP]) maxX = max([each[0] for each in vertexP]) minY = min([each[1] for each in vertexP]) maxY = max([each[1] for each in vertexP]) cOmX = minX+(maxX-minX)/2 cOmY = minY+(maxY-minY)/2 print(cOmX) print(cOmY) for each in vertexP: each[0] -= cOmX each[1] -= cOmY #print(vertexP) for each in vertexP: #print([each[0]*-1, each[1]*-1]) if not [each[0]*-1, each[1]*-1] in vertexP: z = False break if z: print("YES") else: print("nO") ``` No
12,601
Provide tags and a correct Python 3 solution for this coding contest problem. Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced. Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7. Input Input consists of multiple test cases. The first line contains one integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. Each test case is described as follows: The first line contains two integers n and p (1 ≀ n, p ≀ 10^6). The second line contains n integers k_i (0 ≀ k_i ≀ 10^6). The sum of n over all test cases doesn't exceed 10^6. Output Output one integer β€” the reminder of division the answer by 1 000 000 007. Example Input 4 5 2 2 3 4 4 3 3 1 2 10 1000 4 5 0 1 1 100 1 8 89 Output 4 1 146981438 747093407 Note You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1. In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. Tags: greedy, implementation, math, sortings Correct Solution: ``` #!/usr/bin/env python #pyrival orz import os import sys from io import BytesIO, IOBase """ for _ in range(int(input())): n,m=map(int,input().split()) n=int(input()) a = [int(x) for x in input().split()] """ def main(): mod=10**9+7 def po(a,n): ans=1 while n: if n&1: ans=(ans*a)%mod a=(a*a)%mod n//=2 return ans for _ in range(int(input())): n,p=map(int,input().split()) a = [int(x) for x in input().split()] if p==1: print(n%2) continue a.sort(reverse=True) # print(a) from collections import defaultdict d=defaultdict(int) for x in a: # print(x,d) if len(d)==0: d[x]+=1 else: d[x]-=1 while len(d) and d[x]%p==0: if d[x]==0: del d[x] break d[x+1]+=d[x]//p del d[x] x+=1 # print(d) ans=0 for x in d.items(): ans+=x[1]*po(p,x[0])%mod print(ans%mod) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main() ```
12,602
Provide tags and a correct Python 3 solution for this coding contest problem. Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced. Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7. Input Input consists of multiple test cases. The first line contains one integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. Each test case is described as follows: The first line contains two integers n and p (1 ≀ n, p ≀ 10^6). The second line contains n integers k_i (0 ≀ k_i ≀ 10^6). The sum of n over all test cases doesn't exceed 10^6. Output Output one integer β€” the reminder of division the answer by 1 000 000 007. Example Input 4 5 2 2 3 4 4 3 3 1 2 10 1000 4 5 0 1 1 100 1 8 89 Output 4 1 146981438 747093407 Note You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1. In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. Tags: greedy, implementation, math, sortings Correct Solution: ``` import sys readline = sys.stdin.readline T = int(readline()) Ans = [None]*T MOD = 10**9+7 mod = 10**9+9 for qu in range(T): N, P = map(int, readline().split()) A = list(map(int, readline().split())) if P == 1: if N&1: Ans[qu] = 1 else: Ans[qu] = 0 continue if N == 1: Ans[qu] = pow(P, A[0], MOD) continue A.sort(reverse = True) cans = 0 carry = 0 res = 0 ra = 0 for a in A: if carry == 0: carry = pow(P, a, mod) cans = pow(P, a, MOD) continue res = (res + pow(P, a, mod))%mod ra = (ra + pow(P, a, MOD))%MOD if res == carry and ra == cans: carry = 0 cans = 0 ra = 0 res = 0 Ans[qu] = (cans-ra)%MOD print('\n'.join(map(str, Ans))) ```
12,603
Provide tags and a correct Python 3 solution for this coding contest problem. Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced. Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7. Input Input consists of multiple test cases. The first line contains one integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. Each test case is described as follows: The first line contains two integers n and p (1 ≀ n, p ≀ 10^6). The second line contains n integers k_i (0 ≀ k_i ≀ 10^6). The sum of n over all test cases doesn't exceed 10^6. Output Output one integer β€” the reminder of division the answer by 1 000 000 007. Example Input 4 5 2 2 3 4 4 3 3 1 2 10 1000 4 5 0 1 1 100 1 8 89 Output 4 1 146981438 747093407 Note You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1. In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. Tags: greedy, implementation, math, sortings Correct Solution: ``` #created by nit1n import sys input = sys.stdin.readline m = 1000000007 for T in range(int(input())) : n, p = list(map(int ,input().split())) arr = list(map(int, input().split())) if p ==1 : if n&1 : print(1) else : print(0) continue if n ==1 : print(pow(p,arr[0] ,m)) continue arr.sort(reverse = True) curr = 0 c = -1 for i in range(n ): if c == - 1 : req =1 curr = i c = arr[i] prev = arr[i] #print(c,curr) else : d = prev -arr[i] if d > 20 : break req *= p**d prev = arr[i] req -=1 #print(req) if req > n : break if req == 0 : c = -1 if c != -1 : ans = pow(p ,c , m) for i in range(curr+1 ,n ) : ans -= pow(p ,arr[i] , m ) print(ans%(m)) else : print(0) ```
12,604
Provide tags and a correct Python 3 solution for this coding contest problem. Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced. Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7. Input Input consists of multiple test cases. The first line contains one integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. Each test case is described as follows: The first line contains two integers n and p (1 ≀ n, p ≀ 10^6). The second line contains n integers k_i (0 ≀ k_i ≀ 10^6). The sum of n over all test cases doesn't exceed 10^6. Output Output one integer β€” the reminder of division the answer by 1 000 000 007. Example Input 4 5 2 2 3 4 4 3 3 1 2 10 1000 4 5 0 1 1 100 1 8 89 Output 4 1 146981438 747093407 Note You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1. In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. Tags: greedy, implementation, math, sortings Correct Solution: ``` from sys import stdin,stderr def rl(): return [int(w) for w in stdin.readline().split()] M = 1000000007 def pow(p, x): r = 1 p2k = p while x > 0: if x & 1: r = r * p2k % M x >>= 1 p2k = p2k * p2k % M return r t, = rl() for _ in range(t): n, p = rl() k = rl() if p == 1: print(n % 2) continue else: k.sort(reverse=True) multiplier = 1 i = 0 while i < n - 1: if multiplier == 0: multiplier = 1 elif multiplier > n: break else: dk = k[i] - k[i+1] if multiplier > 0 and dk >= 20: # p**20 > len(k) break multiplier = abs(multiplier * p ** dk - 1) i += 1 r = multiplier * pow(p, k[i]) % M for x in k[i+1:]: r = (r - pow(p, x)) % M print(r) ```
12,605
Provide tags and a correct Python 3 solution for this coding contest problem. Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced. Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7. Input Input consists of multiple test cases. The first line contains one integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. Each test case is described as follows: The first line contains two integers n and p (1 ≀ n, p ≀ 10^6). The second line contains n integers k_i (0 ≀ k_i ≀ 10^6). The sum of n over all test cases doesn't exceed 10^6. Output Output one integer β€” the reminder of division the answer by 1 000 000 007. Example Input 4 5 2 2 3 4 4 3 3 1 2 10 1000 4 5 0 1 1 100 1 8 89 Output 4 1 146981438 747093407 Note You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1. In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. Tags: greedy, implementation, math, sortings Correct Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------game starts now----------------------------------------------------import math 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='z', 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: 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 countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ for ik in range(int(input())): n,k=map(int,input().split()) l=list(map(int,input().split())) l.sort() #print(l) ans1=pow(k,l[-1],mod1) ans=pow(k,l[-1],1000000007) ans2=pow(k,l[-1],17) #print(ans) for i in range(n-2,-1,-1): if ans==0 and ans1==0 and ans2==0: #print(111111111111111111111111111111111111111,i) ans=pow(k,l[i],1000000007) ans1 = pow(k, l[i], mod1) ans2 = pow(k, l[i], 17) else: ans-=pow(k,l[i],1000000007) ans%=10**9+7 ans2 -= pow(k, l[i], 17) ans2 %= 17 ans1-= pow(k,l[i],mod1) ans1%=mod1 print(ans) ```
12,606
Provide tags and a correct Python 3 solution for this coding contest problem. Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced. Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7. Input Input consists of multiple test cases. The first line contains one integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. Each test case is described as follows: The first line contains two integers n and p (1 ≀ n, p ≀ 10^6). The second line contains n integers k_i (0 ≀ k_i ≀ 10^6). The sum of n over all test cases doesn't exceed 10^6. Output Output one integer β€” the reminder of division the answer by 1 000 000 007. Example Input 4 5 2 2 3 4 4 3 3 1 2 10 1000 4 5 0 1 1 100 1 8 89 Output 4 1 146981438 747093407 Note You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1. In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. Tags: greedy, implementation, math, sortings Correct Solution: ``` import sys input = sys.stdin.readline for _ in range(int(input())): n, p = map(int, input().split()) s = list(map(int, input().split())) s.sort(reverse=True) if p == 1: print(n % 2) continue c = -1 ci = 0 for i, si in enumerate(s): if c == -1: c = si ls = si f = 1 ci = i else: d = ls - si if d > 20: # 2 ** 20 > 1000000 break elif d: f *= p ** d ls = si f -= 1 if f > n: break if f == 0: c = -1 if c != -1: ans = pow(p, c, 1000000007) for si in s[ci+1:]: ans -= pow(p, si, 1000000007) ans %= 1000000007 ans += 1000000007 else: ans = 0 print(ans % 1000000007) ''' 1 6 2 0 4 4 4 4 6 ''' ```
12,607
Provide tags and a correct Python 3 solution for this coding contest problem. Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced. Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7. Input Input consists of multiple test cases. The first line contains one integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. Each test case is described as follows: The first line contains two integers n and p (1 ≀ n, p ≀ 10^6). The second line contains n integers k_i (0 ≀ k_i ≀ 10^6). The sum of n over all test cases doesn't exceed 10^6. Output Output one integer β€” the reminder of division the answer by 1 000 000 007. Example Input 4 5 2 2 3 4 4 3 3 1 2 10 1000 4 5 0 1 1 100 1 8 89 Output 4 1 146981438 747093407 Note You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1. In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. Tags: greedy, implementation, math, sortings Correct Solution: ``` from sys import stdin, gettrace, stdout from collections import defaultdict if gettrace(): inputi = input else: def input(): return next(stdin)[:-1] def inputi(): return stdin.buffer.readline() def modInt(mod): class ModInt: def __init__(self, value): self.value = value % mod def __int__(self): return self.value def __eq__(self, other): return self.value == other.value def __hash__(self): return hash(self.value) def __add__(self, other): return ModInt(self.value + int(other)) def __sub__(self, other): return ModInt(self.value - int(other)) def __mul__(self, other): return ModInt(self.value * int(other)) def __floordiv__(self, other): return ModInt(self.value // int(other)) def __truediv__(self, other): return ModInt(self.value * pow(int(other), mod - 2, mod)) def __pow__(self, exp): return pow(self.value, int(exp), mod) def __str__(self): return str(self.value) return ModInt MOD = 1000000007 def main(): ModInt = modInt(MOD) def solve(): n,p = map(int, inputi().split()) kk = [int(a) for a in inputi().split()] if p == 1: print(n%2) return kk.sort(reverse=True) res = ModInt(0) mp = ModInt(p) v = 0 lk = kk[0]+1 mxe = 0 mxp = 1 while mxp < n: mxp *= p mxe += 1 i = len(kk) for i in range(len(kk)): k = kk[i] if lk > k: v *= p**(min(lk-k, mxe)) if v > n: for k in kk[i:]: res -= mp ** k break lk = k if v == 0: res += mp**k v = 1 else: res -= mp**k if v <= n: v -= 1 print(res) q = int(inputi()) for _ in range(q): solve() if __name__ == "__main__": main() ```
12,608
Provide tags and a correct Python 3 solution for this coding contest problem. Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced. Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7. Input Input consists of multiple test cases. The first line contains one integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. Each test case is described as follows: The first line contains two integers n and p (1 ≀ n, p ≀ 10^6). The second line contains n integers k_i (0 ≀ k_i ≀ 10^6). The sum of n over all test cases doesn't exceed 10^6. Output Output one integer β€” the reminder of division the answer by 1 000 000 007. Example Input 4 5 2 2 3 4 4 3 3 1 2 10 1000 4 5 0 1 1 100 1 8 89 Output 4 1 146981438 747093407 Note You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1. In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. Tags: greedy, implementation, math, sortings Correct Solution: ``` import sys input = lambda: sys.stdin.readline().rstrip() T = int(input()) P = 10 ** 9 + 7 for _ in range(T): N, b = map(int, input().split()) A = sorted([int(a) for a in input().split()]) if b == 1: print(N % 2) continue a = A.pop() pre = a s = 1 ans = pow(b, a, P) while A: a = A.pop() s *= b ** min(pre - a, 30) if s >= len(A) + 5: ans -= pow(b, a, P) if ans < 0: ans += P while A: a = A.pop() ans -= pow(b, a, P) if ans < 0: ans += P print(ans) break if s: s -= 1 ans -= pow(b, a, P) if ans < 0: ans += P pre = a else: s = 1 ans = -ans if ans < 0: ans += P ans += pow(b, a, P) if ans >= P: ans -= P pre = a else: print(ans) ```
12,609
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced. Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7. Input Input consists of multiple test cases. The first line contains one integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. Each test case is described as follows: The first line contains two integers n and p (1 ≀ n, p ≀ 10^6). The second line contains n integers k_i (0 ≀ k_i ≀ 10^6). The sum of n over all test cases doesn't exceed 10^6. Output Output one integer β€” the reminder of division the answer by 1 000 000 007. Example Input 4 5 2 2 3 4 4 3 3 1 2 10 1000 4 5 0 1 1 100 1 8 89 Output 4 1 146981438 747093407 Note You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1. In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. Submitted Solution: ``` import sys from collections import deque, Counter input = sys.stdin.buffer.readline MOD = 1000000007 T = int(input()) for _ in range(T): n, p = map(int, input().split()) ls = list(map(int, input().split())) ls.sort(reverse=True) if p == 1: print(1 if n%2 else 0); continue cp, cc = 0, 0 ok, pos = 1, 0 for i, u in enumerate(ls): if cc == 0: cp, cc = u, 1 else: tp, tc = cp, cc while tp > u and tc <= n: tp -= 1; tc *= p if tp == u: cp, cc = tp, tc-1 else: ok, pos = 0, i; break if ok: print((pow(p, cp, MOD)*cc)%MOD) else: a = (pow(p, cp, MOD)*cc)%MOD b = 0 for u in ls[pos:]: b += pow(p, u, MOD) b %= MOD print((a-b)%MOD) ``` Yes
12,610
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced. Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7. Input Input consists of multiple test cases. The first line contains one integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. Each test case is described as follows: The first line contains two integers n and p (1 ≀ n, p ≀ 10^6). The second line contains n integers k_i (0 ≀ k_i ≀ 10^6). The sum of n over all test cases doesn't exceed 10^6. Output Output one integer β€” the reminder of division the answer by 1 000 000 007. Example Input 4 5 2 2 3 4 4 3 3 1 2 10 1000 4 5 0 1 1 100 1 8 89 Output 4 1 146981438 747093407 Note You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1. In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. Submitted Solution: ``` from sys import stdin, stdout import math from collections import defaultdict def main(): MOD7 = 1000000007 t = int(stdin.readline()) pw = [0] * 21 for w in range(20,-1,-1): pw[w] = int(math.pow(2,w)) for ks in range(t): n,p = list(map(int, stdin.readline().split())) arr = list(map(int, stdin.readline().split())) if p == 1: if n % 2 ==0: stdout.write("0\n") else: stdout.write("1\n") continue arr.sort(reverse=True) left = -1 i = 0 val = [0] * 21 tmp = p val[0] = p slot = defaultdict(int) for x in range(1,21): tmp = (tmp * tmp) % MOD7 val[x] = tmp while i < n: x = arr[i] if left == -1: left = x else: slot[x] += 1 tmp = x if x == left: left = -1 slot.pop(x) else: while slot[tmp] % p == 0: slot[tmp+1] += 1 slot.pop(tmp) tmp += 1 if tmp == left: left = -1 slot.pop(tmp) i+=1 if left == -1: stdout.write("0\n") continue res = 1 for w in range(20,-1,-1): pww = pw[w] if pww <= left: left -= pww res = (res * val[w]) % MOD7 if left == 0: break for x,c in slot.items(): tp = 1 for w in range(20,-1,-1): pww = pw[w] if pww <= x: x -= pww tp = (tp * val[w]) % MOD7 if x == 0: break res = (res - tp * c) % MOD7 stdout.write(str(res)+"\n") main() ``` Yes
12,611
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced. Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7. Input Input consists of multiple test cases. The first line contains one integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. Each test case is described as follows: The first line contains two integers n and p (1 ≀ n, p ≀ 10^6). The second line contains n integers k_i (0 ≀ k_i ≀ 10^6). The sum of n over all test cases doesn't exceed 10^6. Output Output one integer β€” the reminder of division the answer by 1 000 000 007. Example Input 4 5 2 2 3 4 4 3 3 1 2 10 1000 4 5 0 1 1 100 1 8 89 Output 4 1 146981438 747093407 Note You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1. In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. Submitted Solution: ``` from math import log2 def main(): t=int(input()) allAns=[] MOD=10**9+7 for _ in range(t): n,p=readIntArr() a=readIntArr() if p==1: #put half in each group if n%2==1: ans=1 else: ans=0 else: a.sort(reverse=True) totalMOD=0 totalExact=0 #store exact total//p**a[i] for current i. total must be a multiple of p**a[i] prevPow=a[0] i=0 while i<n: x=a[i] #if totalExact//p**x>n, then just subtract all the remaining elements since totalExact can't reach 0 if totalExact!=0 and log2(totalExact)+(prevPow-x)*log2(p)>log2(n): #using log or else number may get too big while i<n: x=a[i] totalMOD-=pow(p,x,MOD) totalMOD=(totalMOD+MOD)%MOD i+=1 else: if totalExact>0: totalExact*=(p**(prevPow-x)) prevPow=x if totalExact==0: #add totalMOD+=pow(p,x,MOD) # totalMOD+=mod_pow(p,x) totalMOD%=MOD totalExact+=1 else: totalMOD-=pow(p,x,MOD) # totalMOD-=mod_pow(p,x) totalMOD=(totalMOD+MOD)%MOD totalExact-=1 # print('x:{} total:{}'.format(x,total)) i+=1 ans=totalMOD allAns.append(ans) multiLineArrayPrint(allAns) return import sys input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) #import sys #input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] main() ``` Yes
12,612
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced. Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7. Input Input consists of multiple test cases. The first line contains one integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. Each test case is described as follows: The first line contains two integers n and p (1 ≀ n, p ≀ 10^6). The second line contains n integers k_i (0 ≀ k_i ≀ 10^6). The sum of n over all test cases doesn't exceed 10^6. Output Output one integer β€” the reminder of division the answer by 1 000 000 007. Example Input 4 5 2 2 3 4 4 3 3 1 2 10 1000 4 5 0 1 1 100 1 8 89 Output 4 1 146981438 747093407 Note You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1. In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. Submitted Solution: ``` # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase from math import log def main(): mod = 10**9+7 for _ in range(int(input())): n,p = map(int,input().split()) k = sorted(map(int,input().split()),reverse=1) a,b = 0,0 # power,num sign = [-1]*n for ind,i in enumerate(k): if not b: a,b = i,1 sign[ind] = 1 else: if a-i > log(n,p)-log(b,p): break b,a = b*pow(p,a-i)-1,i ans = 0 for a,b in zip(sign,k): ans = (ans+a*pow(p,b,mod))%mod 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() ``` Yes
12,613
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced. Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7. Input Input consists of multiple test cases. The first line contains one integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. Each test case is described as follows: The first line contains two integers n and p (1 ≀ n, p ≀ 10^6). The second line contains n integers k_i (0 ≀ k_i ≀ 10^6). The sum of n over all test cases doesn't exceed 10^6. Output Output one integer β€” the reminder of division the answer by 1 000 000 007. Example Input 4 5 2 2 3 4 4 3 3 1 2 10 1000 4 5 0 1 1 100 1 8 89 Output 4 1 146981438 747093407 Note You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1. In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. Submitted Solution: ``` from sys import stdin, stdout import math def main(): MOD7 = 1000000007 t = int(stdin.readline()) pw = [0] * 21 for w in range(20,-1,-1): pw[w] = int(math.pow(2,w)) for ks in range(t): n,p = list(map(int, stdin.readline().split())) arr = list(map(int, stdin.readline().split())) if p == 1: if n % 2 ==0: stdout.write("0\n") else: stdout.write("1\n") continue arr.sort(reverse=True) res = 0 i = 0 val = [0] * 21 tmp = p val[0] = p for x in range(1,21): tmp = (tmp * tmp) % MOD7 val[x] = tmp while i < n: if res == 0 and i + 1 < n and arr[i] == arr[i+1]: i +=2 continue tp = 1 x = arr[i] for w in range(20,-1,-1): pww = pw[w] if pww <= x: x -= pww tp = (tp * val[w]) % MOD7 if x == 0: break if res == 0: res = tp else: res = (res - tp) % MOD7 if res == 0 and t == 9999 and ks == 9998: print(i,res,tp) i+=1 if t != 9999: stdout.write(str(res)+"\n") elif ks == 9998: print(n,p) main() ``` No
12,614
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced. Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7. Input Input consists of multiple test cases. The first line contains one integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. Each test case is described as follows: The first line contains two integers n and p (1 ≀ n, p ≀ 10^6). The second line contains n integers k_i (0 ≀ k_i ≀ 10^6). The sum of n over all test cases doesn't exceed 10^6. Output Output one integer β€” the reminder of division the answer by 1 000 000 007. Example Input 4 5 2 2 3 4 4 3 3 1 2 10 1000 4 5 0 1 1 100 1 8 89 Output 4 1 146981438 747093407 Note You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1. In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. Submitted Solution: ``` import sys from collections import defaultdict as dd from collections import deque from fractions import Fraction as f def eprint(*args): print(*args, file=sys.stderr) zz=1 from math import log import copy #sys.setrecursionlimit(10**6) if zz: input=sys.stdin.readline else: sys.stdin=open('input.txt', 'r') sys.stdout=open('all.txt','w') def li(): return [int(x) for x in input().split()] def fi(): return int(input()) def si(): return list(input().rstrip()) def mi(): return map(int,input().split()) def gh(): sys.stdout.flush() def bo(i): return ord(i)-ord('a') from copy import * from bisect import * t=fi() while t>0: t-=1 n,p=mi() a=li() mod=10**9+7 a.sort() d=[0 for i in range(10**6+1)] for i in range(n): d[a[i]]+=1 if p==1: print(0 if n%2==0 else 1) continue #print(len(d)) pp=[] for i in range(len(d)): l=p #print(d[i],p) if d[i]==0: continue z=d[i] for j in range(int(log(z,p))+2,-1,-1): if d[i]>p**j: d[j+i]+=d[i]//(p**j) d[i]-=(d[i]//(p**j))*(p**j) if d[i]>0: pp.append([i,d[i]]) c=pow(p,pp[-1][0],mod)*pp[-1][1] #print(pp) for i in range(len(pp)-1): c-= pow(p,pp[i][0],mod)*pp[i][1] c=(c+mod)%mod print(c) ``` No
12,615
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced. Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7. Input Input consists of multiple test cases. The first line contains one integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. Each test case is described as follows: The first line contains two integers n and p (1 ≀ n, p ≀ 10^6). The second line contains n integers k_i (0 ≀ k_i ≀ 10^6). The sum of n over all test cases doesn't exceed 10^6. Output Output one integer β€” the reminder of division the answer by 1 000 000 007. Example Input 4 5 2 2 3 4 4 3 3 1 2 10 1000 4 5 0 1 1 100 1 8 89 Output 4 1 146981438 747093407 Note You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1. In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. Submitted Solution: ``` import sys;input=sys.stdin.readline mod = 10**9+7 T, = map(int, input().split()) for _ in range(T): N, M = map(int, input().split()) X = list(map(int, input().split())) sX = sorted(list(set(X)))[::-1] CC = dict() for x in X: if x not in CC: CC[x] = 0 CC[x] += 1 rmn = 0 flag = False bi=sX[0] for i in sX: cc = CC[i] if rmn: tmp = rmn for _ in range(bi-i): tmp*=M if tmp>N: flag = True break if flag: rmn *= pow(M, bi-i, mod) else: rmn *= pow(M, bi-i) if flag: rmn = (rmn-cc)%mod else: rmn-=cc if rmn <= cc: rmn %= 2 bi = i rmn = rmn*pow(M, bi, mod)%mod print(rmn) ``` No
12,616
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced. Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7. Input Input consists of multiple test cases. The first line contains one integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. Each test case is described as follows: The first line contains two integers n and p (1 ≀ n, p ≀ 10^6). The second line contains n integers k_i (0 ≀ k_i ≀ 10^6). The sum of n over all test cases doesn't exceed 10^6. Output Output one integer β€” the reminder of division the answer by 1 000 000 007. Example Input 4 5 2 2 3 4 4 3 3 1 2 10 1000 4 5 0 1 1 100 1 8 89 Output 4 1 146981438 747093407 Note You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1. In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. Submitted Solution: ``` import sys input = sys.stdin.buffer.readline MOD = 10 ** 9 + 7 def compress(string): string.append(-1) n = len(string) begin, end, cnt = 0, 1, 1 while end < n: if string[begin] == string[end]: end, cnt = end + 1, cnt + 1 else: yield string[begin], cnt begin, end, cnt = end, end + 1, 1 t = int(input()) LIMIT = 10 ** 6 for _ in range(t): n, p = map(int, input().split()) k = list(map(int, input().split())) k.sort(reverse=True) k = compress(k) if p == 1: print(n % 2) continue over_cnt = 0 over_ans = 1 while over_ans <= LIMIT: over_ans *= p over_cnt += 1 ans = -1 ans_cnt = -1 flag = False res = 0 for val, cnt in k: if flag: res -= cnt * pow(p, val, MOD) res %= MOD if ans == -1 and cnt % 2 == 0: continue if ans == -1: ans_cnt = 1 ans = val continue if ans - val >= over_cnt or ans_cnt >= LIMIT: flag = True res = ans_cnt * pow(p, ans, MOD) % MOD res -= cnt * pow(p, val, MOD) res %= MOD continue nokori = ans_cnt * p ** (ans - val) nokori -= cnt if nokori == 0: ans = -1 ans_cnt = -1 elif nokori < 0: ans = val ans_cnt = -nokori % 2 else: ans = val ans_cnt = nokori if res != 0: print(res) elif ans == -1: print(0) else: print(ans_cnt * pow(p, ans, MOD) % MOD) ``` No
12,617
Provide tags and a correct Python 3 solution for this coding contest problem. Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t). In one move Koa: 1. selects some subset of positions p_1, p_2, …, p_k (k β‰₯ 1; 1 ≀ p_i ≀ n; p_i β‰  p_j if i β‰  j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x). 2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x). 3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≀ i ≀ k) Koa sets A_{p_i} = y. Note that you can only modify letters in string A. Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her! Input Each test contains multiple test cases. The first line contains t (1 ≀ t ≀ 10) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains one integer n (1 ≀ n ≀ 10^5) β€” the length of strings A and B. The second line of each test case contains string A (|A|=n). The third line of each test case contains string B (|B|=n). Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal. Example Input 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda Output 2 -1 3 2 -1 Note * In the 1-st test case Koa: 1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b β†’ \color{blue}{bb}b). 2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} β†’ b\color{blue}{cc}). * In the 2-nd test case Koa has no way to make string A equal B. * In the 3-rd test case Koa: 1. selects position 1 and sets A_1 = t (\color{red}{a}bc β†’ \color{blue}{t}bc). 2. selects position 2 and sets A_2 = s (t\color{red}{b}c β†’ t\color{blue}{s}c). 3. selects position 3 and sets A_3 = r (ts\color{red}{c} β†’ ts\color{blue}{r}). Tags: dsu, graphs, greedy, sortings, strings, trees, two pointers Correct Solution: ``` """Template for Python Competitive Programmers prepared by pajengod and many others """ # ////////// SHUBHAM SHARMA \\\\\\\\\\\\\ # to use the print and division function of Python3 from __future__ import division, print_function """value of mod""" MOD = 998244353 mod = 10 ** 9 + 7 """use resource""" # import resource # resource.setrlimit(resource.RLIMIT_STACK, [0x100000000, resource.RLIM_INFINITY]) """for factorial""" def prepare_factorial(): fact = [1] for i in range(1, 100005): fact.append((fact[-1] * i) % mod) ifact = [0] * 100005 ifact[100004] = pow(fact[100004], mod - 2, mod) for i in range(100004, 0, -1): ifact[i - 1] = (i * ifact[i]) % mod return fact, ifact """uncomment next 4 lines while doing recursion based question""" # import threading # threading.stack_size(1<<27) import sys # sys.setrecursionlimit(10000) """uncomment modules according to your need""" from bisect import bisect_left, bisect_right, insort # from itertools import repeat from math import floor, ceil, sqrt, degrees, atan, pi, log, sin, radians from heapq import heappop, heapify, heappush # from random import randint as rn # from Queue import Queue as Q from collections import Counter, defaultdict, deque # from copy import deepcopy # from decimal import * # import re # import operator def modinv(n, p): return pow(n, p - 2, p) def ncr(n, r, fact, ifact): # for using this uncomment the lines calculating fact and ifact t = (fact[n] * (ifact[r] * ifact[n - r]) % mod) % mod return t def intarray(): return map(int, sys.stdin.readline().strip().split()) def array(): return list(map(int, sys.stdin.readline().strip().split())) def input(): return sys.stdin.readline().strip() """*****************************************************************************************""" def GCD(x, y): while y: x, y = y, x % y return x def lcm(x, y): return (x * y) // (GCD(x, y)) def get_xor(n): return [n, 1, n + 1, 0][n % 4] def fast_expo(a, b): res = 1 while b: if b & 1: res = (res * a) res %= MOD b -= 1 else: a = (a * a) a %= MOD b >>= 1 res %= MOD return res def get_n(P): # this function returns the maximum n for which Summation(n) <= Sum ans = (-1 + sqrt(1 + 8 * P)) // 2 return ans """ ********************************************************************************************* """ """ array() # for araay intarray() # for map array SAMPLE INPUT HERE 5 2 01 10 5 01011 11100 2 01 01 10 0110011011 1000110100 1 0 1 """ """ OM SAI RAM """ def solve(): n= int(input()) a= list(input()) b= input() ans= 0 for i in range(20): x ='z' for j in range(n): if a[j]==chr(97+i): if a[j]>b[j]: flag = 0 print(-1) return elif a[j]==b[j]: continue else: x = min(x,b[j]) if x=='z': continue for k in range(n): if a[k]==chr(97+i) and a[k]!=b[k]: a[k] = x ans+=1 print(ans) return def main(): T = int(input()) while T: solve() T -= 1 """OM SAI RAM """ """ -------- Python 2 and 3 footer by Pajenegod and c1729 ---------""" py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import IOBase, BytesIO BUFSIZE = 8192 class FastIO(BytesIO): newlines = 0 def __init__(self, file): self._file = file self._fd = file.fileno() self.writable = "x" in file.mode or "w" in file.mode self.write = super(FastIO, self).write if self.writable else None def _fill(self): s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0]) return s def read(self): while self._fill(): pass return super(FastIO, self).read() def readline(self): while self.newlines == 0: s = self._fill(); self.newlines = s.count(b"\n") + (not s) self.newlines -= 1 return super(FastIO, self).readline() def flush(self): if self.writable: os.write(self._fd, self.getvalue()) self.truncate(0), self.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable if py2: self.write = self.buffer.write self.read = self.buffer.read self.readline = self.buffer.readline else: 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') # sys.stdin = open('input.txt', 'r') # sys.stdout = open('output.txt', 'w') """ main function""" if __name__ == '__main__': main() # threading.Thread(target=main).start() ```
12,618
Provide tags and a correct Python 3 solution for this coding contest problem. Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t). In one move Koa: 1. selects some subset of positions p_1, p_2, …, p_k (k β‰₯ 1; 1 ≀ p_i ≀ n; p_i β‰  p_j if i β‰  j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x). 2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x). 3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≀ i ≀ k) Koa sets A_{p_i} = y. Note that you can only modify letters in string A. Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her! Input Each test contains multiple test cases. The first line contains t (1 ≀ t ≀ 10) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains one integer n (1 ≀ n ≀ 10^5) β€” the length of strings A and B. The second line of each test case contains string A (|A|=n). The third line of each test case contains string B (|B|=n). Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal. Example Input 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda Output 2 -1 3 2 -1 Note * In the 1-st test case Koa: 1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b β†’ \color{blue}{bb}b). 2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} β†’ b\color{blue}{cc}). * In the 2-nd test case Koa has no way to make string A equal B. * In the 3-rd test case Koa: 1. selects position 1 and sets A_1 = t (\color{red}{a}bc β†’ \color{blue}{t}bc). 2. selects position 2 and sets A_2 = s (t\color{red}{b}c β†’ t\color{blue}{s}c). 3. selects position 3 and sets A_3 = r (ts\color{red}{c} β†’ ts\color{blue}{r}). Tags: dsu, graphs, greedy, sortings, strings, trees, two pointers Correct Solution: ``` import sys input = sys.stdin.readline class UnionFind: def __init__(self, n): self.parent = [-1] * n self.cnt = n def root(self, x): if self.parent[x] < 0: return x else: self.parent[x] = self.root(self.parent[x]) return self.parent[x] def merge(self, x, y): x = self.root(x) y = self.root(y) if x == y: return if self.parent[x] > self.parent[y]: x, y = y, x self.parent[x] += self.parent[y] self.parent[y] = x self.cnt -= 1 def is_same(self, x, y): return self.root(x) == self.root(y) def get_size(self, x): return -self.parent[self.root(x)] def get_cnt(self): return self.cnt t = int(input()) alph = "abcdefghijklmnopqrstuvwxyz" to_ind = {char: i for i, char in enumerate(alph)} for _ in range(t): n = int(input()) a = list(input()) b = list(input()) flag = False for i in range(n): if a[i] > b[i]: print(-1) flag = True break if flag: continue uf = UnionFind(26) for i in range(n): u = to_ind[a[i]] v = to_ind[b[i]] uf.merge(u, v) print(26 - uf.get_cnt()) ```
12,619
Provide tags and a correct Python 3 solution for this coding contest problem. Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t). In one move Koa: 1. selects some subset of positions p_1, p_2, …, p_k (k β‰₯ 1; 1 ≀ p_i ≀ n; p_i β‰  p_j if i β‰  j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x). 2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x). 3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≀ i ≀ k) Koa sets A_{p_i} = y. Note that you can only modify letters in string A. Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her! Input Each test contains multiple test cases. The first line contains t (1 ≀ t ≀ 10) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains one integer n (1 ≀ n ≀ 10^5) β€” the length of strings A and B. The second line of each test case contains string A (|A|=n). The third line of each test case contains string B (|B|=n). Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal. Example Input 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda Output 2 -1 3 2 -1 Note * In the 1-st test case Koa: 1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b β†’ \color{blue}{bb}b). 2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} β†’ b\color{blue}{cc}). * In the 2-nd test case Koa has no way to make string A equal B. * In the 3-rd test case Koa: 1. selects position 1 and sets A_1 = t (\color{red}{a}bc β†’ \color{blue}{t}bc). 2. selects position 2 and sets A_2 = s (t\color{red}{b}c β†’ t\color{blue}{s}c). 3. selects position 3 and sets A_3 = r (ts\color{red}{c} β†’ ts\color{blue}{r}). Tags: dsu, graphs, greedy, sortings, strings, trees, two pointers Correct Solution: ``` import sys input = sys.stdin.readline I = lambda : list(map(int,input().split())) def find(x): while x!=p[x]: x=p[x] return x def union(a,b): x=find(a) y=find(b) if x!=y: p[y]=p[x]=min(x,y) r[min(x,y)]+=r[max(x,y)] t,=I() for _ in range(t): n,=I() a=input().strip() b=input().strip() p=[i for i in range(20)] r=[1]*20 pos=1 for i in range(n): if a[i]<b[i]: union(ord(a[i])-97,ord(b[i])-97) elif a[i]!=b[i]: pos=0 break if pos: an=0 for i in range(20): if p[i]==i: an+=r[i]-1 print(an) else: print(-1) ```
12,620
Provide tags and a correct Python 3 solution for this coding contest problem. Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t). In one move Koa: 1. selects some subset of positions p_1, p_2, …, p_k (k β‰₯ 1; 1 ≀ p_i ≀ n; p_i β‰  p_j if i β‰  j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x). 2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x). 3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≀ i ≀ k) Koa sets A_{p_i} = y. Note that you can only modify letters in string A. Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her! Input Each test contains multiple test cases. The first line contains t (1 ≀ t ≀ 10) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains one integer n (1 ≀ n ≀ 10^5) β€” the length of strings A and B. The second line of each test case contains string A (|A|=n). The third line of each test case contains string B (|B|=n). Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal. Example Input 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda Output 2 -1 3 2 -1 Note * In the 1-st test case Koa: 1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b β†’ \color{blue}{bb}b). 2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} β†’ b\color{blue}{cc}). * In the 2-nd test case Koa has no way to make string A equal B. * In the 3-rd test case Koa: 1. selects position 1 and sets A_1 = t (\color{red}{a}bc β†’ \color{blue}{t}bc). 2. selects position 2 and sets A_2 = s (t\color{red}{b}c β†’ t\color{blue}{s}c). 3. selects position 3 and sets A_3 = r (ts\color{red}{c} β†’ ts\color{blue}{r}). Tags: dsu, graphs, greedy, sortings, strings, trees, two pointers Correct Solution: ``` y=lambda s:ord(s)-97 z=lambda:list(map(y,input())) for _ in range(int(input())): n=int(input()) a,b=z(),z() f,c=0,0 for i in range(20): m=20 l=[] for j in range(n): if a[j]==i: if b[j]<i: f=1 break elif b[j]>i: m=min(m,b[j]) l.append(j) if f:break if m==20:continue else: c+=1 for j in l:a[j]=m if f:print(-1) else:print(c) ```
12,621
Provide tags and a correct Python 3 solution for this coding contest problem. Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t). In one move Koa: 1. selects some subset of positions p_1, p_2, …, p_k (k β‰₯ 1; 1 ≀ p_i ≀ n; p_i β‰  p_j if i β‰  j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x). 2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x). 3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≀ i ≀ k) Koa sets A_{p_i} = y. Note that you can only modify letters in string A. Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her! Input Each test contains multiple test cases. The first line contains t (1 ≀ t ≀ 10) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains one integer n (1 ≀ n ≀ 10^5) β€” the length of strings A and B. The second line of each test case contains string A (|A|=n). The third line of each test case contains string B (|B|=n). Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal. Example Input 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda Output 2 -1 3 2 -1 Note * In the 1-st test case Koa: 1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b β†’ \color{blue}{bb}b). 2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} β†’ b\color{blue}{cc}). * In the 2-nd test case Koa has no way to make string A equal B. * In the 3-rd test case Koa: 1. selects position 1 and sets A_1 = t (\color{red}{a}bc β†’ \color{blue}{t}bc). 2. selects position 2 and sets A_2 = s (t\color{red}{b}c β†’ t\color{blue}{s}c). 3. selects position 3 and sets A_3 = r (ts\color{red}{c} β†’ ts\color{blue}{r}). Tags: dsu, graphs, greedy, sortings, strings, trees, two pointers Correct Solution: ``` from collections import defaultdict import string T = int(input()) for t in range(T): n = int(input()) source = input() target = input() exit_flag = False for i in range(n): # feasibility test if target[i] < source[i]: print(-1) exit_flag = True break if exit_flag: continue d = defaultdict(set) for i in range(n): if source[i] != target[i]: d[source[i]].add(target[i]) # need to process this ans = 0 for i in string.ascii_lowercase: if i in d: if d[i]: smallest_e = min(d[i]) d[min(d[i])] |= set([j for j in d[i] if j!= smallest_e]) ans += 1 print(ans) ```
12,622
Provide tags and a correct Python 3 solution for this coding contest problem. Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t). In one move Koa: 1. selects some subset of positions p_1, p_2, …, p_k (k β‰₯ 1; 1 ≀ p_i ≀ n; p_i β‰  p_j if i β‰  j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x). 2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x). 3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≀ i ≀ k) Koa sets A_{p_i} = y. Note that you can only modify letters in string A. Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her! Input Each test contains multiple test cases. The first line contains t (1 ≀ t ≀ 10) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains one integer n (1 ≀ n ≀ 10^5) β€” the length of strings A and B. The second line of each test case contains string A (|A|=n). The third line of each test case contains string B (|B|=n). Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal. Example Input 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda Output 2 -1 3 2 -1 Note * In the 1-st test case Koa: 1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b β†’ \color{blue}{bb}b). 2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} β†’ b\color{blue}{cc}). * In the 2-nd test case Koa has no way to make string A equal B. * In the 3-rd test case Koa: 1. selects position 1 and sets A_1 = t (\color{red}{a}bc β†’ \color{blue}{t}bc). 2. selects position 2 and sets A_2 = s (t\color{red}{b}c β†’ t\color{blue}{s}c). 3. selects position 3 and sets A_3 = r (ts\color{red}{c} β†’ ts\color{blue}{r}). Tags: dsu, graphs, greedy, sortings, strings, trees, two pointers Correct Solution: ``` import sys import math def II(): return int(sys.stdin.readline()) def LI(): return list(map(int, sys.stdin.readline().split())) def MI(): return map(int, sys.stdin.readline().split()) def SI(): return sys.stdin.readline().strip() t = II() for q in range(t): n = II() a = SI() b = SI() d = [[] for i in range(20)] boo = True for i in range(n): if a[i]>b[i]: boo = False break d[ord(a[i])-97].append(ord(b[i])-97) d[ord(b[i])-97].append(ord(a[i])-97) if boo == False: print(-1) else: v = [0]*20 def dfs(ind): v[ind] = 1 for i in d[ind]: if v[i] == 0: dfs(i) ans = 20 for i in range(20): if v[i] == 0: dfs(i) ans-=1 print(ans) ```
12,623
Provide tags and a correct Python 3 solution for this coding contest problem. Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t). In one move Koa: 1. selects some subset of positions p_1, p_2, …, p_k (k β‰₯ 1; 1 ≀ p_i ≀ n; p_i β‰  p_j if i β‰  j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x). 2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x). 3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≀ i ≀ k) Koa sets A_{p_i} = y. Note that you can only modify letters in string A. Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her! Input Each test contains multiple test cases. The first line contains t (1 ≀ t ≀ 10) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains one integer n (1 ≀ n ≀ 10^5) β€” the length of strings A and B. The second line of each test case contains string A (|A|=n). The third line of each test case contains string B (|B|=n). Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal. Example Input 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda Output 2 -1 3 2 -1 Note * In the 1-st test case Koa: 1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b β†’ \color{blue}{bb}b). 2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} β†’ b\color{blue}{cc}). * In the 2-nd test case Koa has no way to make string A equal B. * In the 3-rd test case Koa: 1. selects position 1 and sets A_1 = t (\color{red}{a}bc β†’ \color{blue}{t}bc). 2. selects position 2 and sets A_2 = s (t\color{red}{b}c β†’ t\color{blue}{s}c). 3. selects position 3 and sets A_3 = r (ts\color{red}{c} β†’ ts\color{blue}{r}). Tags: dsu, graphs, greedy, sortings, strings, trees, two pointers Correct Solution: ``` t=int(input()) for _ in range(t): n=int(input()) a=list(input()) b=list(input()) count=[[0 for i in range(20)] for i in range(20)] flag=1 for i in range(n): if(ord(a[i])>ord(b[i])): flag=0 print(-1) break if(flag==0): continue ans=0 count=[[0 for i in range(20)] for i in range(20)] for i in range(n): count[ord(b[i])-97][ord(a[i])-97]+=1 #print(count) for i in range(1,20): counter=set() for j in range(i): if(count[i][j]>0): counter.add(j) ans+=1 for j in range(20): jem=0 for k in range(i): if(k in counter): jem+=count[j][k] count[j][k]=0 count[j][i]+=jem #print(counter) #print(count) print(ans) ```
12,624
Provide tags and a correct Python 3 solution for this coding contest problem. Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t). In one move Koa: 1. selects some subset of positions p_1, p_2, …, p_k (k β‰₯ 1; 1 ≀ p_i ≀ n; p_i β‰  p_j if i β‰  j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x). 2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x). 3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≀ i ≀ k) Koa sets A_{p_i} = y. Note that you can only modify letters in string A. Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her! Input Each test contains multiple test cases. The first line contains t (1 ≀ t ≀ 10) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains one integer n (1 ≀ n ≀ 10^5) β€” the length of strings A and B. The second line of each test case contains string A (|A|=n). The third line of each test case contains string B (|B|=n). Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal. Example Input 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda Output 2 -1 3 2 -1 Note * In the 1-st test case Koa: 1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b β†’ \color{blue}{bb}b). 2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} β†’ b\color{blue}{cc}). * In the 2-nd test case Koa has no way to make string A equal B. * In the 3-rd test case Koa: 1. selects position 1 and sets A_1 = t (\color{red}{a}bc β†’ \color{blue}{t}bc). 2. selects position 2 and sets A_2 = s (t\color{red}{b}c β†’ t\color{blue}{s}c). 3. selects position 3 and sets A_3 = r (ts\color{red}{c} β†’ ts\color{blue}{r}). Tags: dsu, graphs, greedy, sortings, strings, trees, two pointers Correct Solution: ``` import sys import heapq, functools, collections import math, random from collections import Counter, defaultdict # available on Google, not available on Codeforces # import numpy as np # import scipy def solve(arr,brr): # fix inputs here console("----- solving ------") console(arr) console(brr) abc = dict((ab, idx) for idx,ab in enumerate("abcdefghijklmnopqrst")) crr = [] drr = [] for a,b in zip(arr,brr): if a > b: return -1 if a != b: crr.append(abc[a]) drr.append(abc[b]) console(crr) console(drr) if len(crr) == 0: return 0 d = defaultdict(set) for a,b in zip(crr,drr): d[a].add(b) d[b].add(a) console(d) visited = [False for _ in range(len(abc))] idx = 1 for k in [x for x in d.keys()]: if visited[k]: continue idx += 1 visited[k] = idx stack = [x for x in d[k]] while stack: cur = stack.pop() visited[cur] = idx # if not cur in d: # continue for nex in d[cur]: if visited[nex]: continue visited[nex] = idx stack.append(nex) console(d) console(visited) return sum([a-1 for a in Counter([x for x in visited if x]).values()]) def console(*args): # the judge will not read these print statement # print('\033[36m', *args, '\033[0m', file=sys.stderr) return # fast read all # sys.stdin.readlines() for case_num in range(int(input())): # read line as a string # strr = input() # read line as an integer _ = int(input()) a = input() b = input() # read one line and parse each word as a string # lst = input().split() # read one line and parse each word as an integer # lst = list(map(int,input().split())) # read matrix and parse as integers (after reading read nrows) # lst = list(map(int,input().split())) # nrows = lst[0] # index containing information, please change # grid = [] # for _ in range(nrows): # grid.append(list(map(int,input().split()))) res = solve(a,b) # please change # Google - case number required # print("Case #{}: {}".format(case_num+1, res)) # Codeforces - no case number required print(res) ```
12,625
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t). In one move Koa: 1. selects some subset of positions p_1, p_2, …, p_k (k β‰₯ 1; 1 ≀ p_i ≀ n; p_i β‰  p_j if i β‰  j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x). 2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x). 3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≀ i ≀ k) Koa sets A_{p_i} = y. Note that you can only modify letters in string A. Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her! Input Each test contains multiple test cases. The first line contains t (1 ≀ t ≀ 10) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains one integer n (1 ≀ n ≀ 10^5) β€” the length of strings A and B. The second line of each test case contains string A (|A|=n). The third line of each test case contains string B (|B|=n). Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal. Example Input 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda Output 2 -1 3 2 -1 Note * In the 1-st test case Koa: 1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b β†’ \color{blue}{bb}b). 2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} β†’ b\color{blue}{cc}). * In the 2-nd test case Koa has no way to make string A equal B. * In the 3-rd test case Koa: 1. selects position 1 and sets A_1 = t (\color{red}{a}bc β†’ \color{blue}{t}bc). 2. selects position 2 and sets A_2 = s (t\color{red}{b}c β†’ t\color{blue}{s}c). 3. selects position 3 and sets A_3 = r (ts\color{red}{c} β†’ ts\color{blue}{r}). Submitted Solution: ``` # cook your dish here # code # ___________________________________ # | | # | | # | _, _ _ ,_ | # | .-'` / \'-'/ \ `'-. | # | / | | | | \ | # | ; \_ _/ \_ _/ ; | # | | `` `` | | # | | | | # | ; .-. .-. .-. .-. ; | # | \ ( '.' \ / '.' ) / | # | '-.; V ;.-' | # | ` ` | # | | # |___________________________________| # | | # | Author : Ramzz | # | Created On : 21-07-2020 | # |___________________________________| # # _ __ __ _ _ __ ___ ________ # | '__/ _` | '_ ` _ \|_ /_ / # | | | (_| | | | | | |/ / / / # |_| \__,_|_| |_| |_/___/___| # import math import collections from sys import stdin,stdout,setrecursionlimit from bisect import bisect_left as bsl from bisect import bisect_right as bsr import heapq as hq setrecursionlimit(2**20) t = 1 t = int(stdin.readline()) for _ in range(t): n = int(stdin.readline()) a = stdin.readline().strip('\n') b = stdin.readline().strip('\n') #a = list(map(int, stdin.readline().rstrip().split())) chk = False d = {} l = [] var = 'abcdefghijklmnopqrst' for i in range(n): if(a[i]>b[i]): chk = True break if(a[i]==b[i]): continue if(a[i] not in d): d[a[i]] = {} d[a[i]][b[i]] = True l.append((a[i],b[i])) if(chk): print(-1) else: ans = 0 l1 = list(d.keys()) l1.sort() for i in var: if(i in d): if(len(d[i])>0): ans += 1 mi = 'u' for j in d[i]: if(mi>j): mi=j if(mi not in d): d[mi] = {} for k in d[i]: if(k!=mi): d[mi][k] = True print(ans) ``` Yes
12,626
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t). In one move Koa: 1. selects some subset of positions p_1, p_2, …, p_k (k β‰₯ 1; 1 ≀ p_i ≀ n; p_i β‰  p_j if i β‰  j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x). 2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x). 3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≀ i ≀ k) Koa sets A_{p_i} = y. Note that you can only modify letters in string A. Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her! Input Each test contains multiple test cases. The first line contains t (1 ≀ t ≀ 10) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains one integer n (1 ≀ n ≀ 10^5) β€” the length of strings A and B. The second line of each test case contains string A (|A|=n). The third line of each test case contains string B (|B|=n). Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal. Example Input 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda Output 2 -1 3 2 -1 Note * In the 1-st test case Koa: 1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b β†’ \color{blue}{bb}b). 2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} β†’ b\color{blue}{cc}). * In the 2-nd test case Koa has no way to make string A equal B. * In the 3-rd test case Koa: 1. selects position 1 and sets A_1 = t (\color{red}{a}bc β†’ \color{blue}{t}bc). 2. selects position 2 and sets A_2 = s (t\color{red}{b}c β†’ t\color{blue}{s}c). 3. selects position 3 and sets A_3 = r (ts\color{red}{c} β†’ ts\color{blue}{r}). Submitted Solution: ``` from collections import defaultdict t=int(input()) for tc in range(t): n=int(input()) a=str(input()) arr=list(a) b=str(input()) charray=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t"] flag=0 for i in range(n): if a[i]>b[i]: print("-1") flag=1 break if flag==0: ans=0 for i in charray: f=defaultdict(int) for j in range(n): if i==b[j] and i!=a[j]: f[arr[j]]+=1 ans+=len(f) for j in range(n): if f[arr[j]]>0: arr[j]=i print(ans) ``` Yes
12,627
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t). In one move Koa: 1. selects some subset of positions p_1, p_2, …, p_k (k β‰₯ 1; 1 ≀ p_i ≀ n; p_i β‰  p_j if i β‰  j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x). 2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x). 3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≀ i ≀ k) Koa sets A_{p_i} = y. Note that you can only modify letters in string A. Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her! Input Each test contains multiple test cases. The first line contains t (1 ≀ t ≀ 10) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains one integer n (1 ≀ n ≀ 10^5) β€” the length of strings A and B. The second line of each test case contains string A (|A|=n). The third line of each test case contains string B (|B|=n). Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal. Example Input 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda Output 2 -1 3 2 -1 Note * In the 1-st test case Koa: 1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b β†’ \color{blue}{bb}b). 2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} β†’ b\color{blue}{cc}). * In the 2-nd test case Koa has no way to make string A equal B. * In the 3-rd test case Koa: 1. selects position 1 and sets A_1 = t (\color{red}{a}bc β†’ \color{blue}{t}bc). 2. selects position 2 and sets A_2 = s (t\color{red}{b}c β†’ t\color{blue}{s}c). 3. selects position 3 and sets A_3 = r (ts\color{red}{c} β†’ ts\color{blue}{r}). Submitted Solution: ``` def _find(st, u): ls = [] while st[u] != u: ls.append(u) u = st[u] for v in ls: st[v] = u return u def _union(st, u, v): su, sv = _find(st, u), _find(st, v) if su != sv: st[su] = sv return su != sv T = int(input()) for _ in range(T): n = int(input()) a, b = input(), input() st = { chr(u) : chr(u) for u in range(ord('a'), ord('t')+1) } ok, cc = 1, 0 for ca, cb in zip(a, b): if ca > cb: ok = 0; break elif cb > ca: cc += _union(st, ca, cb) print(cc if ok else -1) ``` Yes
12,628
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t). In one move Koa: 1. selects some subset of positions p_1, p_2, …, p_k (k β‰₯ 1; 1 ≀ p_i ≀ n; p_i β‰  p_j if i β‰  j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x). 2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x). 3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≀ i ≀ k) Koa sets A_{p_i} = y. Note that you can only modify letters in string A. Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her! Input Each test contains multiple test cases. The first line contains t (1 ≀ t ≀ 10) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains one integer n (1 ≀ n ≀ 10^5) β€” the length of strings A and B. The second line of each test case contains string A (|A|=n). The third line of each test case contains string B (|B|=n). Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal. Example Input 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda Output 2 -1 3 2 -1 Note * In the 1-st test case Koa: 1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b β†’ \color{blue}{bb}b). 2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} β†’ b\color{blue}{cc}). * In the 2-nd test case Koa has no way to make string A equal B. * In the 3-rd test case Koa: 1. selects position 1 and sets A_1 = t (\color{red}{a}bc β†’ \color{blue}{t}bc). 2. selects position 2 and sets A_2 = s (t\color{red}{b}c β†’ t\color{blue}{s}c). 3. selects position 3 and sets A_3 = r (ts\color{red}{c} β†’ ts\color{blue}{r}). Submitted Solution: ``` for _ in range(int(input())): n = int(input()) A = input() B = input() a=[] b=[] for i in A: a.append(i) for i in B: b.append(i) c = [] cnt=0 check=False for i in range(n): if ord(a[i])>ord(b[i]): check=True break if check: print("-1") else: for i in range(97,117): c.append(chr(i)) for i in range(len(c)): d=[] e=[] for j in range(n): if a[j]==c[i] and a[j]!=b[j]: d.append(j) e.append(b[j]) minm=116 for j in e: if ord(j)<minm: minm=ord(j) for j in d: a[j]=chr(minm) if len(d)!=0: cnt+=1 print(cnt) ``` Yes
12,629
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t). In one move Koa: 1. selects some subset of positions p_1, p_2, …, p_k (k β‰₯ 1; 1 ≀ p_i ≀ n; p_i β‰  p_j if i β‰  j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x). 2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x). 3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≀ i ≀ k) Koa sets A_{p_i} = y. Note that you can only modify letters in string A. Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her! Input Each test contains multiple test cases. The first line contains t (1 ≀ t ≀ 10) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains one integer n (1 ≀ n ≀ 10^5) β€” the length of strings A and B. The second line of each test case contains string A (|A|=n). The third line of each test case contains string B (|B|=n). Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal. Example Input 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda Output 2 -1 3 2 -1 Note * In the 1-st test case Koa: 1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b β†’ \color{blue}{bb}b). 2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} β†’ b\color{blue}{cc}). * In the 2-nd test case Koa has no way to make string A equal B. * In the 3-rd test case Koa: 1. selects position 1 and sets A_1 = t (\color{red}{a}bc β†’ \color{blue}{t}bc). 2. selects position 2 and sets A_2 = s (t\color{red}{b}c β†’ t\color{blue}{s}c). 3. selects position 3 and sets A_3 = r (ts\color{red}{c} β†’ ts\color{blue}{r}). Submitted Solution: ``` t=int(input()) for t1 in range(0,t): n=int(input()) s=input() s1=input() s=list(s) s1=list(s1) f=1 for i in range(0,n): if s[i]>s1[i]: f=0 break c=0 if f==1: for i in range(0,n): if s[i]!=s1[i]: if(s[i]<s1[i]): c=c+1 z=s[i] r=s1[i] s[i]=s1[i] for j in range(i+1,n): if s[j]==z and s[j]!=s1[j] and r<=s1[j]: s[j]=s1[i] else: f=0 break if s==s1: f=1 else: f=0 if f==0: print(-1) else: print(c) ``` No
12,630
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t). In one move Koa: 1. selects some subset of positions p_1, p_2, …, p_k (k β‰₯ 1; 1 ≀ p_i ≀ n; p_i β‰  p_j if i β‰  j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x). 2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x). 3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≀ i ≀ k) Koa sets A_{p_i} = y. Note that you can only modify letters in string A. Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her! Input Each test contains multiple test cases. The first line contains t (1 ≀ t ≀ 10) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains one integer n (1 ≀ n ≀ 10^5) β€” the length of strings A and B. The second line of each test case contains string A (|A|=n). The third line of each test case contains string B (|B|=n). Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal. Example Input 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda Output 2 -1 3 2 -1 Note * In the 1-st test case Koa: 1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b β†’ \color{blue}{bb}b). 2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} β†’ b\color{blue}{cc}). * In the 2-nd test case Koa has no way to make string A equal B. * In the 3-rd test case Koa: 1. selects position 1 and sets A_1 = t (\color{red}{a}bc β†’ \color{blue}{t}bc). 2. selects position 2 and sets A_2 = s (t\color{red}{b}c β†’ t\color{blue}{s}c). 3. selects position 3 and sets A_3 = r (ts\color{red}{c} β†’ ts\color{blue}{r}). Submitted Solution: ``` import sys inpy = [x for x in sys.stdin.read().split()] t = int(inpy[0]) index = 1 for _ in range(t): n = int(inpy[index]) a, b = inpy[index+1], inpy[index+2] index += 3 memo = set() memo2 = set() flag = True for i, j in zip(a, b): if i < j: memo.add((ord(i) - ord('a'), ord(j) - ord('a'))) elif i > j : memo2.add((ord(i) - ord('a'), ord(j) - ord('a'))) l = list(memo) # l.sort() match = [-1] * 26 def get(i): if match[i] == -1 or match[i] == i: return i return get(match[i]) res = 0 for i, j in l: if match[i] == -1: match[i] = i i, j = get(i), get(j) if i != j: res += 1 match[i] = j memo = set() l = list(memo2) for i, j in l: if match[i] == -1: match[i] = i i, j = get(i), get(j) if i == j: if j in memo: continue else: res += 1 memo.add(j) elif i != j: if i in memo and j in memo: res -= 1 memo.remove(i) res += 1 if i not in memo: match[i] = j else: match[j] = i # print(match) print(res) ``` No
12,631
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t). In one move Koa: 1. selects some subset of positions p_1, p_2, …, p_k (k β‰₯ 1; 1 ≀ p_i ≀ n; p_i β‰  p_j if i β‰  j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x). 2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x). 3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≀ i ≀ k) Koa sets A_{p_i} = y. Note that you can only modify letters in string A. Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her! Input Each test contains multiple test cases. The first line contains t (1 ≀ t ≀ 10) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains one integer n (1 ≀ n ≀ 10^5) β€” the length of strings A and B. The second line of each test case contains string A (|A|=n). The third line of each test case contains string B (|B|=n). Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal. Example Input 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda Output 2 -1 3 2 -1 Note * In the 1-st test case Koa: 1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b β†’ \color{blue}{bb}b). 2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} β†’ b\color{blue}{cc}). * In the 2-nd test case Koa has no way to make string A equal B. * In the 3-rd test case Koa: 1. selects position 1 and sets A_1 = t (\color{red}{a}bc β†’ \color{blue}{t}bc). 2. selects position 2 and sets A_2 = s (t\color{red}{b}c β†’ t\color{blue}{s}c). 3. selects position 3 and sets A_3 = r (ts\color{red}{c} β†’ ts\color{blue}{r}). Submitted Solution: ``` alp = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't'] for T in range(int(input())): ans = 0 N = int(input()) A = input() B = input() i = 0 while i < N: if A[i] != B[i]: while True: try: if A[i + 1] == A[i]: i += 1 else: break except: break if alp.index(A[i]) > alp.index(B[i]): ans = -1 break elif alp.index(A[i]) == alp.index(B[i]): i += 1 else: ans += 1 i += 1 print(ans) ``` No
12,632
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t). In one move Koa: 1. selects some subset of positions p_1, p_2, …, p_k (k β‰₯ 1; 1 ≀ p_i ≀ n; p_i β‰  p_j if i β‰  j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x). 2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x). 3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≀ i ≀ k) Koa sets A_{p_i} = y. Note that you can only modify letters in string A. Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her! Input Each test contains multiple test cases. The first line contains t (1 ≀ t ≀ 10) β€” the number of test cases. Description of the test cases follows. The first line of each test case contains one integer n (1 ≀ n ≀ 10^5) β€” the length of strings A and B. The second line of each test case contains string A (|A|=n). The third line of each test case contains string B (|B|=n). Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal. Example Input 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda Output 2 -1 3 2 -1 Note * In the 1-st test case Koa: 1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b β†’ \color{blue}{bb}b). 2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} β†’ b\color{blue}{cc}). * In the 2-nd test case Koa has no way to make string A equal B. * In the 3-rd test case Koa: 1. selects position 1 and sets A_1 = t (\color{red}{a}bc β†’ \color{blue}{t}bc). 2. selects position 2 and sets A_2 = s (t\color{red}{b}c β†’ t\color{blue}{s}c). 3. selects position 3 and sets A_3 = r (ts\color{red}{c} β†’ ts\color{blue}{r}). Submitted Solution: ``` def number(ch): return ord(ch) - ord('a') def main(): n = int(input()) a = input() b = input() count_array_a = [0] * 20 count_array_b = [0] * 20 for i in range(n): if a[i] > b[i]: return -1 elif a[i] < b[i]: count_array_a[number(a[i])] += 1 count_array_b[number(a[i])] += 1 count = 0 for i in range(n): a_num = count_array_a[i] j = 0 while a_num > 0 and j < 20: if count_array_b[j] > 0: if count_array_b[j] > a_num: count_array_b[j] -= a_num a_num = 0 else: count_array_b[j] = 0 a_num -= count_array_b[j] count += 1 j += 1 return count if __name__ == '__main__': t = int(input()) for _ in range(t): print(main()) ``` No
12,633
Provide tags and a correct Python 3 solution for this coding contest problem. A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each). You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^4). Description of the test cases follows. The first line of each test case contains two integers n and k (2 ≀ k ≀ n ≀ 3 β‹… 10^5, k is even) β€” the length of the string and the parameter for a balanced bitstring. The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?. It is guaranteed that the sum of n over all test cases does not exceed 3 β‹… 10^5. Output For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible. Example Input 9 6 4 100110 3 2 1?1 3 2 1?0 4 4 ???? 7 4 1?0??1? 10 10 11??11??11 4 2 1??1 4 4 ?0?0 6 2 ????00 Output YES YES NO YES YES NO NO YES NO Note For the first test case, the string is already a 4-balanced bitstring. For the second test case, the string can be transformed into 101. For the fourth test case, the string can be transformed into 0110. For the fifth test case, the string can be transformed into 1100110. Tags: implementation, strings Correct Solution: ``` t=int(input()) for _ in range(t): n,k=map(int,input().split()) a=list(input()) flag=1 for i in range(n): if(a[i]=="?"): if(i+k<n): a[i]=a[i+k] else: if(a[i]=="0"): if(i+k<n): if(a[i]!=a[i+k] and a[i+k]=="1"): flag=0 break a[i+k]=a[i] if(i-k>=0 ): if(a[i]!=a[i-k]and a[i-k]=="1"): flag=0 break a[i-k]=a[i] else: if(i+k<n): if(a[i]!=a[i+k]and a[i+k]=="0"): flag=0 break a[i+k]=a[i] #print(i+k) if(i-k>=0): if(a[i]!=a[i-k]and a[i-k]=="1"): flag=0 break a[i-k]=a[i] #print(a) one=0 zero=0 doubt=0 #print(a) for i in range(k): if(a[i]=="1"): one+=1 elif(a[i]=="0"): zero+=1 else: doubt=0 if(one>k/2 or zero>k/2): print("NO") continue oneneed=k/2-one zeroneed=k/2-zero #print("YES",flag) #print(a) for i in range(k,n): if(a[i-k]=='1'): one-=1 elif(a[i-k]=='0'): zero-=1 if(a[i]=='1'): one+=1 if(a[i]=="0"): zero+=1 if(one>k/2 or zero>k/2): #print(i,zero) flag=0 break if(flag==0): print("NO") else: print("YES") ```
12,634
Provide tags and a correct Python 3 solution for this coding contest problem. A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each). You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^4). Description of the test cases follows. The first line of each test case contains two integers n and k (2 ≀ k ≀ n ≀ 3 β‹… 10^5, k is even) β€” the length of the string and the parameter for a balanced bitstring. The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?. It is guaranteed that the sum of n over all test cases does not exceed 3 β‹… 10^5. Output For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible. Example Input 9 6 4 100110 3 2 1?1 3 2 1?0 4 4 ???? 7 4 1?0??1? 10 10 11??11??11 4 2 1??1 4 4 ?0?0 6 2 ????00 Output YES YES NO YES YES NO NO YES NO Note For the first test case, the string is already a 4-balanced bitstring. For the second test case, the string can be transformed into 101. For the fourth test case, the string can be transformed into 0110. For the fifth test case, the string can be transformed into 1100110. Tags: implementation, strings Correct Solution: ``` def Test(): t=int(input()) while t>0: t-=1 soln() def soln(): nk=list(map(int,input().strip().split(" "))) n=nk[0] k=nk[1] b=input() a=[] for i in range(len(b)): a.append(b[i]) if k%2!=0: print("NO") return c1=0 c0=0 cnt=0 for i in range(k): if a[i]=="0": c0+=1 elif a[i]=="1": c1+=1 else: cnt+=1 hl=k//2 if c0>hl or c1>hl: print("NO") return # while "?" in a: i=0 while(i+k<n): if a[i]!="?" and a[i+k]!="?" and a[i]!=a[i+k]: print("NO") return elif a[i]!="?" and a[i+k]=="?": a[i+k]=a[i] elif a[i]=="?" and a[i+k]!="?": a[i]=a[i+k] if a[i]=='0': c0+=1 else: c1+=1 if c0>hl or c1>hl: print("NO") return i+=1 print("YES") Test() ```
12,635
Provide tags and a correct Python 3 solution for this coding contest problem. A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each). You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^4). Description of the test cases follows. The first line of each test case contains two integers n and k (2 ≀ k ≀ n ≀ 3 β‹… 10^5, k is even) β€” the length of the string and the parameter for a balanced bitstring. The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?. It is guaranteed that the sum of n over all test cases does not exceed 3 β‹… 10^5. Output For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible. Example Input 9 6 4 100110 3 2 1?1 3 2 1?0 4 4 ???? 7 4 1?0??1? 10 10 11??11??11 4 2 1??1 4 4 ?0?0 6 2 ????00 Output YES YES NO YES YES NO NO YES NO Note For the first test case, the string is already a 4-balanced bitstring. For the second test case, the string can be transformed into 101. For the fourth test case, the string can be transformed into 0110. For the fifth test case, the string can be transformed into 1100110. Tags: implementation, strings Correct Solution: ``` def sol(): n,k = map(int,input().split()) s = list(input()) gg= False one=0 zero=0 #100110 for i in range(k): ck =0 for y in range(i,n,k): if s[y]=='1': ck|=2 if s[y]=='0': ck|=1 if ck==3: return "NO" if ck==2: one+=1 elif ck==1: zero+=1 if max(zero,one)> k/2: gg=True if gg:return "NO" else: return "YES" t = int(input()) while t: t-=1 print(sol()) ```
12,636
Provide tags and a correct Python 3 solution for this coding contest problem. A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each). You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^4). Description of the test cases follows. The first line of each test case contains two integers n and k (2 ≀ k ≀ n ≀ 3 β‹… 10^5, k is even) β€” the length of the string and the parameter for a balanced bitstring. The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?. It is guaranteed that the sum of n over all test cases does not exceed 3 β‹… 10^5. Output For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible. Example Input 9 6 4 100110 3 2 1?1 3 2 1?0 4 4 ???? 7 4 1?0??1? 10 10 11??11??11 4 2 1??1 4 4 ?0?0 6 2 ????00 Output YES YES NO YES YES NO NO YES NO Note For the first test case, the string is already a 4-balanced bitstring. For the second test case, the string can be transformed into 101. For the fourth test case, the string can be transformed into 0110. For the fifth test case, the string can be transformed into 1100110. Tags: implementation, strings Correct Solution: ``` for _ in range(int(input())): n,k=map(int,input().split()) s=input() def solve(n,k,s): l=list(s) for i in range(k): t=s[i] for j in range(i,n,k): if s[j]!='?': if t!='?' and s[j]!=t: return False t=s[j] for j in range(i,n,k): l[j]=t return max(l[:k].count('1'),l[:k].count('0')) <= k//2 if solve(n,k,s): print('YES') else: print('NO') ```
12,637
Provide tags and a correct Python 3 solution for this coding contest problem. A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each). You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^4). Description of the test cases follows. The first line of each test case contains two integers n and k (2 ≀ k ≀ n ≀ 3 β‹… 10^5, k is even) β€” the length of the string and the parameter for a balanced bitstring. The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?. It is guaranteed that the sum of n over all test cases does not exceed 3 β‹… 10^5. Output For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible. Example Input 9 6 4 100110 3 2 1?1 3 2 1?0 4 4 ???? 7 4 1?0??1? 10 10 11??11??11 4 2 1??1 4 4 ?0?0 6 2 ????00 Output YES YES NO YES YES NO NO YES NO Note For the first test case, the string is already a 4-balanced bitstring. For the second test case, the string can be transformed into 101. For the fourth test case, the string can be transformed into 0110. For the fifth test case, the string can be transformed into 1100110. Tags: implementation, strings Correct Solution: ``` import sys for _ in range(int(input())): n,k= map(int,input().split()) s=input() cnt0=0 cnt1=0 f=0 for i in range(k): S=set() for j in range(i,n,k): if s[j]=='?': continue S.add(s[j]) if len(S)>1: f=1 print("NO") break if '1' in S: cnt1+=1; elif '0' in S: cnt0+=1 if(not f): if cnt0>k//2: print("NO") elif cnt1>k//2: print("NO") else: print("YES") ```
12,638
Provide tags and a correct Python 3 solution for this coding contest problem. A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each). You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^4). Description of the test cases follows. The first line of each test case contains two integers n and k (2 ≀ k ≀ n ≀ 3 β‹… 10^5, k is even) β€” the length of the string and the parameter for a balanced bitstring. The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?. It is guaranteed that the sum of n over all test cases does not exceed 3 β‹… 10^5. Output For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible. Example Input 9 6 4 100110 3 2 1?1 3 2 1?0 4 4 ???? 7 4 1?0??1? 10 10 11??11??11 4 2 1??1 4 4 ?0?0 6 2 ????00 Output YES YES NO YES YES NO NO YES NO Note For the first test case, the string is already a 4-balanced bitstring. For the second test case, the string can be transformed into 101. For the fourth test case, the string can be transformed into 0110. For the fifth test case, the string can be transformed into 1100110. Tags: implementation, strings Correct Solution: ``` import os from io import BytesIO, IOBase import sys import math from math import ceil from collections import Counter def main(): for t in range(int(input())): n,k=map(int,input().split()) s=list(input().rstrip()) ans="YES" o=0 z=0 for i in range(k): if s[i]=="1": o+=1 if s[i]=="0": z+=1 if o>(k//2) or z>(k//2): ans="NO" if ans=="YES": for i in range(0,n-k): if s[i]=="0": if s[i+k]=="1": ans="NO" break else: if s[i+k]=="?": s[i+k]="0" elif s[i]=="1": if s[i+k]=="0": ans="NO" break else: if s[i+k]=="?": s[i+k]="1" o,z=0,0 for i in range(n-k,n): if s[i]=="1": o+=1 if s[i]=="0": z+=1 if o > (k // 2) or z > (k // 2): ans = "NO" print(ans) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": main() ```
12,639
Provide tags and a correct Python 3 solution for this coding contest problem. A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each). You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^4). Description of the test cases follows. The first line of each test case contains two integers n and k (2 ≀ k ≀ n ≀ 3 β‹… 10^5, k is even) β€” the length of the string and the parameter for a balanced bitstring. The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?. It is guaranteed that the sum of n over all test cases does not exceed 3 β‹… 10^5. Output For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible. Example Input 9 6 4 100110 3 2 1?1 3 2 1?0 4 4 ???? 7 4 1?0??1? 10 10 11??11??11 4 2 1??1 4 4 ?0?0 6 2 ????00 Output YES YES NO YES YES NO NO YES NO Note For the first test case, the string is already a 4-balanced bitstring. For the second test case, the string can be transformed into 101. For the fourth test case, the string can be transformed into 0110. For the fifth test case, the string can be transformed into 1100110. Tags: implementation, strings Correct Solution: ``` for __ in range(int(input())): n, k = list(map(int, input().split())) ar = list(input()) kek = [-1] * k ans = 'YES' for j in range(0, n, k): for i in range(j, j + k): if i < n: if ar[i] == '0': if kek[i % k] == 1: ans = 'NO' kek[i % k] = 0 elif ar[i] == '1': if kek[i % k] == 0: ans = 'NO' kek[i % k] = 1 for i in range(n): if ar[i] == '?' and kek[i % k] != -1: ar[i] = str(kek[i % k]) a, b = 0, 0 for i in range(k): if ar[i] == '0': a += 1 elif ar[i] == '1': b += 1 if a > k // 2 or b > k // 2: ans = 'NO' for i in range(k): if ar[i] == '?': if a < k // 2: a += 1 ar[i] = '0' kek[i] = 0 elif b < k // 2: b += 1 ar[i] = '1' kek[i] = 1 else: ans = 'NO' for i in range(n): if ar[i] == '?' and kek[i % k] != -1: ar[i] = str(kek[i % k]) a, b = 0, 0 for i in range(k): if ar[i] == '0': a += 1 elif ar[i] == '1': b += 1 if a != b: ans = 'NO' for i in range(k, n): if ar[i] != ar[i - k]: ans = 'NO' print(ans) ```
12,640
Provide tags and a correct Python 3 solution for this coding contest problem. A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each). You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^4). Description of the test cases follows. The first line of each test case contains two integers n and k (2 ≀ k ≀ n ≀ 3 β‹… 10^5, k is even) β€” the length of the string and the parameter for a balanced bitstring. The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?. It is guaranteed that the sum of n over all test cases does not exceed 3 β‹… 10^5. Output For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible. Example Input 9 6 4 100110 3 2 1?1 3 2 1?0 4 4 ???? 7 4 1?0??1? 10 10 11??11??11 4 2 1??1 4 4 ?0?0 6 2 ????00 Output YES YES NO YES YES NO NO YES NO Note For the first test case, the string is already a 4-balanced bitstring. For the second test case, the string can be transformed into 101. For the fourth test case, the string can be transformed into 0110. For the fifth test case, the string can be transformed into 1100110. Tags: implementation, strings Correct Solution: ``` for _ in range(int(input())): n,ws=map(int,input().split()) st=input() s=list(st) f=0 start,end=0,ws while(end<n): if(s[end]!='?' and s[start]!='?'): if(s[end]!=s[start]): f=1 break elif(s[end]=='?' and s[start]!='?'): s[end]=s[start] elif(s[end]!='?' and s[start]=='?'): s[start]=s[end] end+=1 start+=1 if(f==1): print('NO') continue #print(s) start=n-ws-1 end=n-1 while(start>=0): if(s[start]=='?' and s[end]!='?'): s[start]=s[end] elif(s[start]!='?' and s[end]=='?'): s[end]=s[start] start-=1 end-=1 #print(s) f=0 one,zero=0,0 for i in range(ws): if(s[i]=='1'): one+=1 elif(s[i]=='0'): zero+=1 if(one>ws//2 or zero>ws//2): print('NO') else: start,end=0,ws f=0 while(end<n): if(s[start]=='1'): one-=1 elif(s[start]=='0'): zero-=1 if(s[end]=='0'): zero+=1 elif(s[end]=='1'): one+=1 if(one>ws//2 or zero>ws//2): f=1 break start+=1 end+=1 if(f==0): print('YES') else: print('NO') ```
12,641
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each). You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^4). Description of the test cases follows. The first line of each test case contains two integers n and k (2 ≀ k ≀ n ≀ 3 β‹… 10^5, k is even) β€” the length of the string and the parameter for a balanced bitstring. The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?. It is guaranteed that the sum of n over all test cases does not exceed 3 β‹… 10^5. Output For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible. Example Input 9 6 4 100110 3 2 1?1 3 2 1?0 4 4 ???? 7 4 1?0??1? 10 10 11??11??11 4 2 1??1 4 4 ?0?0 6 2 ????00 Output YES YES NO YES YES NO NO YES NO Note For the first test case, the string is already a 4-balanced bitstring. For the second test case, the string can be transformed into 101. For the fourth test case, the string can be transformed into 0110. For the fifth test case, the string can be transformed into 1100110. Submitted Solution: ``` ###################################################### ############Created by Devesh Kumar################### #############devesh1102@gmail.com#################### ##########For CodeForces(Devesh1102)################# #####################2020############################# ###################################################### import sys input = sys.stdin.readline # import sys import heapq import copy import math import decimal # import sys.stdout.flush as flush # from decimal import * #heapq.heapify(li) # #heapq.heappush(li,4) # #heapq.heappop(li) # # & Bitwise AND Operator 10 & 7 = 2 # | Bitwise OR Operator 10 | 7 = 15 # ^ Bitwise XOR Operator 10 ^ 7 = 13 # << Bitwise Left Shift operator 10<<2 = 40 # >> Bitwise Right Shift Operator # '''############ ---- Input Functions ---- #######Start#####''' def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input() return(list(s[:len(s) - 1])) def insr2(): s = input() return((s[:len(s) - 1])) def invr(): return(map(int,input().split())) ############ ---- Input Functions ---- #######End # ##### ans = 0 def pr_list(a): print( *a , sep=" ") def swap(a,b): temp = a a = b b = temp return [ a,b] # return [b,a] def main(): tests = inp() # tests = 1 mod = 1000000007 limit = 10**18 ans = 0 stack = [] hashm = {} arr = [] heapq.heapify(arr) for test in range(tests): [n,k] = inlt() s = insr() hashm= {} hashm["1"] = 0 hashm["0"] = 0 hashm["?"] = 0 present = [] # for i in range(k): # hashm[s[i]] = hashm[s[i]] +1 # if s[i] == "?": # present.append(i) flag =0 h = k//2 for i in range(n-k): if s[i] != s[i+k]: if s[i] == "?": s[i] = s[i+k] elif s[i+k] == "?": s[i+k] = s[i] else: flag = 1 break if flag==1: print("NO") continue for i in range(k): hashm[s[i]] = hashm[s[i]] +1 if abs( hashm["1"] - hashm["0"]) > hashm["?"]: flag = 1 for i in range(n-k): if abs( hashm["1"] - hashm["0"]) > hashm["?"]: flag = 1 hashm[s[i]] = hashm[s[i]] - 1 hashm[s[i+k]] = hashm[s[i+k]] + 1 if flag==1: print("NO") continue else: print("YES") if __name__== "__main__": main() ``` Yes
12,642
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each). You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^4). Description of the test cases follows. The first line of each test case contains two integers n and k (2 ≀ k ≀ n ≀ 3 β‹… 10^5, k is even) β€” the length of the string and the parameter for a balanced bitstring. The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?. It is guaranteed that the sum of n over all test cases does not exceed 3 β‹… 10^5. Output For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible. Example Input 9 6 4 100110 3 2 1?1 3 2 1?0 4 4 ???? 7 4 1?0??1? 10 10 11??11??11 4 2 1??1 4 4 ?0?0 6 2 ????00 Output YES YES NO YES YES NO NO YES NO Note For the first test case, the string is already a 4-balanced bitstring. For the second test case, the string can be transformed into 101. For the fourth test case, the string can be transformed into 0110. For the fifth test case, the string can be transformed into 1100110. Submitted Solution: ``` for _ in range(int(input())): n,k = map(int,input().split()) a = list(input()) flag = False dic = [-1 for i in range(k)] for i in range(n): if a[i] == '1' and dic[i%k] != 0: dic[i%k] = 1 elif a[i] == '0' and dic[i%k] != 1: dic[i%k] = 0 elif a[i] == '?': if dic[i%k] != -1: continue else: dic[i%k] = '?' else: flag = True break if flag: print('NO') else: s = count = 0 for i in dic: if i == '?': count += 1 elif i == 1: s += 1 if s > k//2 or (s<k//2 and count == 0): print('NO') elif s == k//2 and count ==0: print('YES') elif count != 0: if s == k//2: print('YES') elif (k//2)-s <= count: print('YES') else: print('NO') ``` Yes
12,643
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each). You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^4). Description of the test cases follows. The first line of each test case contains two integers n and k (2 ≀ k ≀ n ≀ 3 β‹… 10^5, k is even) β€” the length of the string and the parameter for a balanced bitstring. The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?. It is guaranteed that the sum of n over all test cases does not exceed 3 β‹… 10^5. Output For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible. Example Input 9 6 4 100110 3 2 1?1 3 2 1?0 4 4 ???? 7 4 1?0??1? 10 10 11??11??11 4 2 1??1 4 4 ?0?0 6 2 ????00 Output YES YES NO YES YES NO NO YES NO Note For the first test case, the string is already a 4-balanced bitstring. For the second test case, the string can be transformed into 101. For the fourth test case, the string can be transformed into 0110. For the fifth test case, the string can be transformed into 1100110. Submitted Solution: ``` import sys input = sys.stdin.readline for _ in range(int(input())): N, K = map(int, input().split()) a = list(input())[: -1] cs = 0 q = 0 for i in range(K): t = 0 if a[i] == "1": t = 1 elif a[i] == "0": t = -1 else: q += 1 cs += t q -= abs(cs) if q < 0: print("NO") continue for i in range(N - K): if a[i] != "?" and (a[i + K] != "?") and (a[i] != a[i + K]): print("NO") break elif a[i] != a[i + K]: if a[i] == "0": a[i + K] = "0" elif a[i] == "1": a[i + K] = "1" elif a[i + K] == "0": a[i] = "0" elif a[i + K] == "1": a[i] = "1" else: cs = 0 q = 0 for i in range(K): t = 0 if a[i] == "1": t = 1 elif a[i] == "0": t = -1 else: q += 1 cs += t q -= abs(cs) if q < 0: print("NO") continue for i in range(N - K): if a[i] != "?" and (a[i + K] != "?") and (a[i] != a[i + K]): print("NO") break elif a[i] != a[i + K]: if a[i] == "0": a[i + K] = "0" elif a[i] == "1": a[i + K] = "1" elif a[i + K] == "0": a[i] = "0" elif a[i + K] == "1": a[i] = "1" else: cs = [0] * (N + 1) qs = [0] * (N + 1) for i in range(N): t = 0 if a[i] == "1": t = 1 elif a[i] == "0": t = -1 else: qs[i + 1] += 1 cs[i + 1] = cs[i] + t qs[i + 1] += qs[i] for i in range(N - K + 1): if (abs(cs[i + K] - cs[i]) - (qs[i + K] - qs[i])) % 2: print("NO") break elif (abs(cs[i + K] - cs[i]) - (qs[i + K] - qs[i])) > 0: print("NO") break else: print("YES") ``` Yes
12,644
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each). You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^4). Description of the test cases follows. The first line of each test case contains two integers n and k (2 ≀ k ≀ n ≀ 3 β‹… 10^5, k is even) β€” the length of the string and the parameter for a balanced bitstring. The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?. It is guaranteed that the sum of n over all test cases does not exceed 3 β‹… 10^5. Output For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible. Example Input 9 6 4 100110 3 2 1?1 3 2 1?0 4 4 ???? 7 4 1?0??1? 10 10 11??11??11 4 2 1??1 4 4 ?0?0 6 2 ????00 Output YES YES NO YES YES NO NO YES NO Note For the first test case, the string is already a 4-balanced bitstring. For the second test case, the string can be transformed into 101. For the fourth test case, the string can be transformed into 0110. For the fifth test case, the string can be transformed into 1100110. Submitted Solution: ``` from sys import stdin N = int(stdin.readline()) for case in range(N): length, k = map(int, stdin.readline().split()) string = str(stdin.readline()) count = { "1":0, "0":0, "?":0 } flag = True for i in range(k): res = string[i] for j in range(i+k, length, k): if res != "?" and string[j] != res and string[j] != "?": flag = False break if res == "?" and string[j] != "?": res = string[j] if flag: count[res] += 1 if count["1"] <= k//2 and count["0"] <= k//2 and flag: print("YES") else: print("NO") ``` Yes
12,645
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each). You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^4). Description of the test cases follows. The first line of each test case contains two integers n and k (2 ≀ k ≀ n ≀ 3 β‹… 10^5, k is even) β€” the length of the string and the parameter for a balanced bitstring. The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?. It is guaranteed that the sum of n over all test cases does not exceed 3 β‹… 10^5. Output For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible. Example Input 9 6 4 100110 3 2 1?1 3 2 1?0 4 4 ???? 7 4 1?0??1? 10 10 11??11??11 4 2 1??1 4 4 ?0?0 6 2 ????00 Output YES YES NO YES YES NO NO YES NO Note For the first test case, the string is already a 4-balanced bitstring. For the second test case, the string can be transformed into 101. For the fourth test case, the string can be transformed into 0110. For the fifth test case, the string can be transformed into 1100110. Submitted Solution: ``` # -*- coding: utf-8 -*- """ Created on Sun Sep 6 21:22:04 2020 @author: Dark Soul """ t=int(input('')) arr=[] s=[] for i in range(t): arr.append(list(map(int,input().split()))) s.append(input('')) for j in range(t): [n,k]=arr[j] tst=list(s[j]) flag=0 f1=0 f2=0 q=0 for i in range(k): if tst[i]=='1': f1+=1 elif tst[i]=='0': f2+=1 else: q+=1 if q==0: if f1!=k//2 or f2!=k//2: flag=1 if f1>k//2 or f2>k//2: flag=1 if flag: print('NO') continue if q: if f1==k//2: for i in range(k): if tst[i]=='?': tst[i]='0' if i+k<n: if tst[i+k]!=tst[i]: flag=1 break elif f2==k//2: for i in range(k): if tst[i]=='?': tst[i]='1' if i+k<n: if tst[i+k]!=tst[i]: flag=1 break else: f1=abs(f1-k//2) f2=abs(f2-k//2) for i in range(k): if tst[i]=='?': if i+k<n: if tst[i+k]!='?': tst[i]=tst[i+k] else: if f1: tst[i]='1' f1-=1 elif f2: tst[i]='0' f2-=1 else: flag=1 break else: if f1: tst[i]='1' f1-=1 elif f2: tst[i]='0' f2-=1 else: flag=1 break if flag: print('NO') continue for i in range(n-k): if tst[i]!=tst[i+k]: if tst[i+k]=='?': tst[i+k]=tst[i] else: flag=1 break if flag: print('NO') else: print('YES') ``` No
12,646
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each). You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^4). Description of the test cases follows. The first line of each test case contains two integers n and k (2 ≀ k ≀ n ≀ 3 β‹… 10^5, k is even) β€” the length of the string and the parameter for a balanced bitstring. The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?. It is guaranteed that the sum of n over all test cases does not exceed 3 β‹… 10^5. Output For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible. Example Input 9 6 4 100110 3 2 1?1 3 2 1?0 4 4 ???? 7 4 1?0??1? 10 10 11??11??11 4 2 1??1 4 4 ?0?0 6 2 ????00 Output YES YES NO YES YES NO NO YES NO Note For the first test case, the string is already a 4-balanced bitstring. For the second test case, the string can be transformed into 101. For the fourth test case, the string can be transformed into 0110. For the fifth test case, the string can be transformed into 1100110. Submitted Solution: ``` #------------------------template--------------------------# import os import sys from math import * from collections import * from fractions import * from bisect import * from heapq import* from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') 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") ALPHA='abcdefghijklmnopqrstuvwxyz' M=998244353 EPS=1e-6 def value():return tuple(map(int,input().split())) def array():return [int(i) for i in input().split()] def Int():return int(input()) def Str():return input() def arrayS():return [i for i in input().split()] #-------------------------code---------------------------# # vsInput() def check(): return True for _ in range(Int()): n,k=value() s=[i for i in input()] ok="YES" ind=[i for i in range(n) if s[i]=='?'] id=0 need=0 have=0 # INITIALS ------------------------------------/ for i in range(k): if(s[i]=='1'):need+=1 elif(s[i]=='0'):need-=1 else:have+=1 if(abs(need)>have or (have-abs(need))%2): ok="NO" elif(have==abs(need)): for i in range(have): s[ind[id]]=str(int(need<0)) id+=1 have=0 need=0 # SLIDE ---------------------------------------/ # print(ok) for i in range(1,n-k+1): if(id<len(ind) and ind[id]<i): id=bisect_left(ind,i) if(s[i-1]=='0'): need+=1 elif(s[i-1]=='1'): need-=1 else: have-=1 if(s[i+k-1]=='0'):need-=1 elif(s[i+k-1]=='1'):need+=1 else: have+=1 # print(id,have,need,ind) if(abs(need)>have or (have-abs(need))%2): ok="NO" break elif(have==abs(need)): for i in range(have): s[ind[id]]=str(int(need<0)) id+=1 have=0 need=0 # print(s) print(ok) ``` No
12,647
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each). You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^4). Description of the test cases follows. The first line of each test case contains two integers n and k (2 ≀ k ≀ n ≀ 3 β‹… 10^5, k is even) β€” the length of the string and the parameter for a balanced bitstring. The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?. It is guaranteed that the sum of n over all test cases does not exceed 3 β‹… 10^5. Output For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible. Example Input 9 6 4 100110 3 2 1?1 3 2 1?0 4 4 ???? 7 4 1?0??1? 10 10 11??11??11 4 2 1??1 4 4 ?0?0 6 2 ????00 Output YES YES NO YES YES NO NO YES NO Note For the first test case, the string is already a 4-balanced bitstring. For the second test case, the string can be transformed into 101. For the fourth test case, the string can be transformed into 0110. For the fifth test case, the string can be transformed into 1100110. Submitted Solution: ``` t=int(input()) for _ in range(t): n,k=map(int,input().split()) a=list(input()) flag=1 for i in range(n): if(a[i]=="?"): if(i+k<n): a[i]=a[i+k] else: if(a[i]=="0"): if(i+k<n): if(a[i]!=a[i+k] and a[i+k]=="1"): flag=0 break a[i+k]=a[i] if(i-k>=0 ): if(a[i]!=a[i-k]and a[i-k]=="1"): flag=0 break a[i-k]=a[i] else: if(i+k<n): if(a[i]!=a[i+k]and a[i+k]=="0"): flag=0 break a[i+k]=a[i] #print(i+k) if(i-k>=0): if(a[i]!=a[i-k]and a[i-k]=="1"): flag=0 break a[i-k]=a[i] #print(a) one=0 zero=0 doubt=0 #print(a) for i in range(k): if(a[i]=="1"): one+=1 elif(a[i]=="0"): zero+=1 else: doubt=0 if(one>k/2 or zero>k/2): print("NO") continue oneneed=k/2-one zeroneed=k/2-zero for i in range(k,n): if(a[i-k]=='1'): one-=1 if(a[i-k]=='0'): zero-=1 if(a[i]=='1'): one+=1 else: zero+=1 if(one>k/2 or zero>k/2): flag=0 break if(flag==0): print("NO") else: print("YES") ``` No
12,648
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each). You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^4). Description of the test cases follows. The first line of each test case contains two integers n and k (2 ≀ k ≀ n ≀ 3 β‹… 10^5, k is even) β€” the length of the string and the parameter for a balanced bitstring. The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?. It is guaranteed that the sum of n over all test cases does not exceed 3 β‹… 10^5. Output For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible. Example Input 9 6 4 100110 3 2 1?1 3 2 1?0 4 4 ???? 7 4 1?0??1? 10 10 11??11??11 4 2 1??1 4 4 ?0?0 6 2 ????00 Output YES YES NO YES YES NO NO YES NO Note For the first test case, the string is already a 4-balanced bitstring. For the second test case, the string can be transformed into 101. For the fourth test case, the string can be transformed into 0110. For the fifth test case, the string can be transformed into 1100110. Submitted Solution: ``` import sys, os, io def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n') import math,datetime,functools,itertools,operator,bisect,fractions from collections import deque,defaultdict,OrderedDict,Counter from fractions import Fraction from decimal import Decimal def main(): starttime=datetime.datetime.now() if(os.path.exists('input.txt')): sys.stdin = open("input.txt","r") sys.stdout = open("output.txt","w") for _ in range(ri()): n,k=ria() a=rs() a=list(a) q=deque(a[:k]) n1=0 nq=0 n0=0 for i in q: if i=='?': nq+=1 if i=='1': n1+=1 if i=='0': n0+=1 if max(n1,n0)>k//2: print("NO") else: t=0 if n1==k//2: for e in range(k): if q[e]=='?': q[e]='0' n0=nq nq=0 t=1 if n0==k//2 and t==0: for e in range(k): if q[e]=='?': q[e]='1' n1=nq nq=0 c=True for i in range(k,n): if q[0]=='?': nq-=1 if q[0]=='1': n1-=1 if q[0]=='0': n0-=1 q.popleft() q.append(a[i]) if q[-1]=='?': nq+=1 if q[-1]=='1': n1+=1 if q[-1]=='0': n0+=1 if max(n1,n0)>k//2: c=False break t=0 if n1==k//2: for e in range(k): if q[e]=='?': q[e]='0' n0=nq nq=0 t=1 if n0==k//2 and t==0: for e in range(k): if q[e]=='?': q[e]='1' n1=nq nq=0 if c: print("YES") else: print("NO") #<--Solving Area Ends endtime=datetime.datetime.now() time=(endtime-starttime).total_seconds()*1000 if(os.path.exists('input.txt')): print("Time:",time,"ms") class FastReader(io.IOBase): newlines = 0 def __init__(self, fd, chunk_size=1024 * 8): self._fd = fd self._chunk_size = chunk_size self.buffer = io.BytesIO() def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size)) 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, size=-1): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size)) 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() class FastWriter(io.IOBase): def __init__(self, fd): self._fd = fd self.buffer = io.BytesIO() self.write = self.buffer.write def flush(self): os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class FastStdin(io.IOBase): def __init__(self, fd=0): self.buffer = FastReader(fd) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") class FastStdout(io.IOBase): def __init__(self, fd=1): self.buffer = FastWriter(fd) self.write = lambda s: self.buffer.write(s.encode("ascii")) self.flush = self.buffer.flush if __name__ == '__main__': sys.stdin = FastStdin() sys.stdout = FastStdout() main() ``` No
12,649
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an interactive problem. You have to use a flush operation right after printing each line. For example, in C++ you should use the function fflush(stdout), in Java β€” System.out.flush(), in Pascal β€” flush(output) and in Python β€” sys.stdout.flush(). Mr. Chanek wants to buy a flamingo to accompany his chickens on his farm. Before going to the pet shop, Mr. Chanek stops at an animal festival to have fun. It turns out there is a carnival game with a flamingo as the prize. There are N mysterious cages, which are numbered from 1 to N. Cage i has A_i (0 ≀ A_i ≀ 10^3) flamingoes inside (1 ≀ i ≀ N). However, the game master keeps the number of flamingoes inside a secret. To win the flamingo, Mr. Chanek must guess the number of flamingoes in each cage. Coincidentally, Mr. Chanek has N coins. Each coin can be used to ask once, what is the total number of flamingoes inside cages numbered L to R inclusive? With L < R. Input Use standard input to read the responses of your questions. Initially, the judge will give an integer N (3 ≀ N ≀ 10^3), the number of cages, and the number of coins Mr. Chanek has. For each of your questions, the jury will give an integer that denotes the number of flamingoes from cage L to R inclusive. If your program does not guess the flamingoes or ask other questions, you will get "Wrong Answer". Of course, if your program asks more questions than the allowed number, your program will get "Wrong Answer". Output To ask questions, your program must use standard output. Then, you can ask at most N questions. Questions are asked in the format "? L R", (1 ≀ L < R ≀ N). To guess the flamingoes, print a line that starts with "!" followed by N integers where the i-th integer denotes the number of flamingo in cage i. After answering, your program must terminate or will receive the "idle limit exceeded" verdict. You can only guess the flamingoes once. Examples Input 6 Β  5 Β  15 Β  10 Β  Output Β  ? 1 2 Β  ? 5 6 Β  ? 3 4 Β  ! 1 4 4 6 7 8 Note In the sample input, the correct flamingoes amount is [1, 4, 4, 6, 7, 8]. Submitted Solution: ``` # DEFINING SOME GOOD STUFF import heapq import sys from math import * import threading from heapq import * from itertools import count from pprint import pprint from collections import defaultdict from heapq import heapify, heappop, heappush # threading.stack_size(10**8) # sys.setrecursionlimit(300000) ''' -> if you are increasing recursionlimit then remember submitting using python3 rather pypy3 -> sometimes increasing stack size don't work locally but it will work on CF ''' mod = 10 ** 9+7 inf = 10 ** 15 decision = ['NO', 'YES'] yes = 'YES' no = 'NO' # ------------------------------FASTIO---------------------------- import os 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") # ________________________FAST FACTORIAL______________________________# 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 def npr(self, n, k): if k < 0 or n < k: return 0 f = self.factorial return (f.calc(n) * f.invFactorial(n-k)) % self.MOD #_______________SEGMENT TREE ( logn range modifications )_____________# 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) # ____________________MY FAVOURITE FUNCTIONS_______________________# def lower_bound(li, num): answer = len(li) 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 def upper_bound(li, num): answer = len(li) start = 0 end = len(li)-1 while (start <= end): middle = (end+start) // 2 if li[middle] <= num: start = middle+1 else: answer = middle end = middle-1 return answer # max index where x is greater than num def abs(x): return x if x >= 0 else -x 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 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 pref(li): pref_sum = [0] for i in li: pref_sum.append(pref_sum[-1]+i) return pref_sum def SieveOfEratosthenes(n): prime = [{1, i} for i in range(n+1)] p = 2 while (p <= n): for i in range(p * 2, n+1, p): prime[i].add(p) p += 1 return prime def primefactors(n): factors = [] while (n % 2 == 0): factors.append(2) n //= 2 for i in range(3, int(sqrt(n))+1, 2): # only odd factors left while n % i == 0: factors.append(i) n //= i if n > 2: # incase of prime factors.append(n) return factors def prod(li): ans = 1 for i in li: ans *= i return ans def sumk(a, b): print('called for', a, b) ans = a * (a+1) // 2 ans -= b * (b+1) // 2 return ans def sumi(n): ans = 0 if len(n) > 1: for x in n: ans += int(x) return ans else: return int(n) def checkwin(x, a): if a[0][0] == a[1][1] == a[2][2] == x: return 1 if a[0][2] == a[1][1] == a[2][0] == x: return 1 if (len(set(a[0])) == 1 and a[0][0] == x) or (len(set(a[1])) == 1 and a[1][0] == x) or (len(set(a[2])) == 1 and a[2][0] == x): return 1 if (len(set(a[0][:])) == 1 and a[0][0] == x) or (len(set(a[1][:])) == 1 and a[0][1] == x) or (len(set(a[2][:])) == 1 and a[0][0] == x): return 1 return 0 # _______________________________________________________________# inf = 10**9 + 7 def main(): # karmanya = int(input()) karmanya = 1 # divisors = SieveOfEratosthenes(200010) # print(divisors) while karmanya != 0: karmanya -= 1 n = int(input()) # a,b,c,d = map(int, input().split()) # s = [int(x) for x in list(input())] # s = list(input()) # a = list(map(int, input().split())) # b = list(map(int, input().split())) # c = list(map(int, input().split())) # d = defaultdict(list) ans = [0]*n # print(ans) l,r = 1, n print('?',l,r) sys.stdout.flush() s = int(input()) for i in range(n-2): r -= 1 print('?',l,r) sys.stdout.flush() x = int(input()) ans[n-1-i] = s - x s = x ans[1] = s-1 ans[0] = 1 print('!', *ans) sys.stdout.flush() main() # t = threading.Thread(target=main) # t.start() # t.join() ``` No
12,650
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an interactive problem. You have to use a flush operation right after printing each line. For example, in C++ you should use the function fflush(stdout), in Java β€” System.out.flush(), in Pascal β€” flush(output) and in Python β€” sys.stdout.flush(). Mr. Chanek wants to buy a flamingo to accompany his chickens on his farm. Before going to the pet shop, Mr. Chanek stops at an animal festival to have fun. It turns out there is a carnival game with a flamingo as the prize. There are N mysterious cages, which are numbered from 1 to N. Cage i has A_i (0 ≀ A_i ≀ 10^3) flamingoes inside (1 ≀ i ≀ N). However, the game master keeps the number of flamingoes inside a secret. To win the flamingo, Mr. Chanek must guess the number of flamingoes in each cage. Coincidentally, Mr. Chanek has N coins. Each coin can be used to ask once, what is the total number of flamingoes inside cages numbered L to R inclusive? With L < R. Input Use standard input to read the responses of your questions. Initially, the judge will give an integer N (3 ≀ N ≀ 10^3), the number of cages, and the number of coins Mr. Chanek has. For each of your questions, the jury will give an integer that denotes the number of flamingoes from cage L to R inclusive. If your program does not guess the flamingoes or ask other questions, you will get "Wrong Answer". Of course, if your program asks more questions than the allowed number, your program will get "Wrong Answer". Output To ask questions, your program must use standard output. Then, you can ask at most N questions. Questions are asked in the format "? L R", (1 ≀ L < R ≀ N). To guess the flamingoes, print a line that starts with "!" followed by N integers where the i-th integer denotes the number of flamingo in cage i. After answering, your program must terminate or will receive the "idle limit exceeded" verdict. You can only guess the flamingoes once. Examples Input 6 Β  5 Β  15 Β  10 Β  Output Β  ? 1 2 Β  ? 5 6 Β  ? 3 4 Β  ! 1 4 4 6 7 8 Note In the sample input, the correct flamingoes amount is [1, 4, 4, 6, 7, 8]. Submitted Solution: ``` import sys import time t=int(input()) print("? 1 2",flush=True) a=int(input()) print("? 1 3",flush=True) b=int(input()) print("? 2 3",flush=True) c=int(input()) l=[(a+b-c)//2,(a+c-b)//2,(b+c-a)//2] d=(b+c-a)//2 for i in range(2,t-1): print(f"? {i+1} {i+2} ",flush=True) e=int(input()) l.append(e-d) d=e-d print("!",end= " ") for i in range(t): print(l[i],end=" ") print() ``` No
12,651
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an interactive problem. You have to use a flush operation right after printing each line. For example, in C++ you should use the function fflush(stdout), in Java β€” System.out.flush(), in Pascal β€” flush(output) and in Python β€” sys.stdout.flush(). Mr. Chanek wants to buy a flamingo to accompany his chickens on his farm. Before going to the pet shop, Mr. Chanek stops at an animal festival to have fun. It turns out there is a carnival game with a flamingo as the prize. There are N mysterious cages, which are numbered from 1 to N. Cage i has A_i (0 ≀ A_i ≀ 10^3) flamingoes inside (1 ≀ i ≀ N). However, the game master keeps the number of flamingoes inside a secret. To win the flamingo, Mr. Chanek must guess the number of flamingoes in each cage. Coincidentally, Mr. Chanek has N coins. Each coin can be used to ask once, what is the total number of flamingoes inside cages numbered L to R inclusive? With L < R. Input Use standard input to read the responses of your questions. Initially, the judge will give an integer N (3 ≀ N ≀ 10^3), the number of cages, and the number of coins Mr. Chanek has. For each of your questions, the jury will give an integer that denotes the number of flamingoes from cage L to R inclusive. If your program does not guess the flamingoes or ask other questions, you will get "Wrong Answer". Of course, if your program asks more questions than the allowed number, your program will get "Wrong Answer". Output To ask questions, your program must use standard output. Then, you can ask at most N questions. Questions are asked in the format "? L R", (1 ≀ L < R ≀ N). To guess the flamingoes, print a line that starts with "!" followed by N integers where the i-th integer denotes the number of flamingo in cage i. After answering, your program must terminate or will receive the "idle limit exceeded" verdict. You can only guess the flamingoes once. Examples Input 6 Β  5 Β  15 Β  10 Β  Output Β  ? 1 2 Β  ? 5 6 Β  ? 3 4 Β  ! 1 4 4 6 7 8 Note In the sample input, the correct flamingoes amount is [1, 4, 4, 6, 7, 8]. Submitted Solution: ``` ''' =============================== -- @uthor : Kaleab Asfaw -- Handle : kaleabasfaw2010 -- Bio : High-School Student ===============================''' import sys def inOut(x): print("?", x) sys.stdout.flush() val = int(input()) return val n = int(input()) if n%2: lst = [] for i in range(1, n-2, 2): val = inOut(str(i) + " " + str(i+1)) lst.append(1) lst.append(val-1) val = inOut(str(i+2) + " " + str(i+3)) val1 = inOut(str(i+3) + " " + str(i+4)) val2 = inOut(str(i+2) + " " + str(i+4)) y = val+val1-val2 x = val-y z = val1-y lst += [x, y, z] else: lst = [] for i in range(1, n+1, 2): val = inOut(str(i) + " " + str(i+1)) lst.append(1) lst.append(val-1) ans = "! " + " ".join(list(map(str, lst))) print(ans) sys.stdout.flush() # 1 4 4 6 7 8 ``` No
12,652
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an interactive problem. You have to use a flush operation right after printing each line. For example, in C++ you should use the function fflush(stdout), in Java β€” System.out.flush(), in Pascal β€” flush(output) and in Python β€” sys.stdout.flush(). Mr. Chanek wants to buy a flamingo to accompany his chickens on his farm. Before going to the pet shop, Mr. Chanek stops at an animal festival to have fun. It turns out there is a carnival game with a flamingo as the prize. There are N mysterious cages, which are numbered from 1 to N. Cage i has A_i (0 ≀ A_i ≀ 10^3) flamingoes inside (1 ≀ i ≀ N). However, the game master keeps the number of flamingoes inside a secret. To win the flamingo, Mr. Chanek must guess the number of flamingoes in each cage. Coincidentally, Mr. Chanek has N coins. Each coin can be used to ask once, what is the total number of flamingoes inside cages numbered L to R inclusive? With L < R. Input Use standard input to read the responses of your questions. Initially, the judge will give an integer N (3 ≀ N ≀ 10^3), the number of cages, and the number of coins Mr. Chanek has. For each of your questions, the jury will give an integer that denotes the number of flamingoes from cage L to R inclusive. If your program does not guess the flamingoes or ask other questions, you will get "Wrong Answer". Of course, if your program asks more questions than the allowed number, your program will get "Wrong Answer". Output To ask questions, your program must use standard output. Then, you can ask at most N questions. Questions are asked in the format "? L R", (1 ≀ L < R ≀ N). To guess the flamingoes, print a line that starts with "!" followed by N integers where the i-th integer denotes the number of flamingo in cage i. After answering, your program must terminate or will receive the "idle limit exceeded" verdict. You can only guess the flamingoes once. Examples Input 6 Β  5 Β  15 Β  10 Β  Output Β  ? 1 2 Β  ? 5 6 Β  ? 3 4 Β  ! 1 4 4 6 7 8 Note In the sample input, the correct flamingoes amount is [1, 4, 4, 6, 7, 8]. Submitted Solution: ``` import sys n=int(input()) a=[0]*n print("1",n) sys.stdout.flush() x=int(input()) c=x for j in range(1,n-1): print("1",n-j) sys.stdout.flush() y=int(input()) a[n-j]=x-y x=y print("2",n) sys.stdout.flush() x=int(input()) a[0]=c-x a[1]=y-a[0] print("!",' '.join(map(str,a))) ``` No
12,653
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4β‹… LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the essays could have been copied, therefore you're interested in their substrings. Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. If X is a string, |X| denotes its length. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters. Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement. You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem). Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 5000) β€” lengths of the two strings A and B. The second line contains a string consisting of n lowercase Latin letters β€” string A. The third line contains a string consisting of m lowercase Latin letters β€” string B. Output Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. Examples Input 4 5 abba babab Output 5 Input 8 10 bbbbabab bbbabaaaaa Output 12 Input 7 7 uiibwws qhtkxcn Output 0 Note For the first case: abb from the first string and abab from the second string have LCS equal to abb. The result is S(abb, abab) = (4 β‹… |abb|) - |abb| - |abab| = 4 β‹… 3 - 3 - 4 = 5. Tags: dp, strings Correct Solution: ``` def make_array(n, m): new_arr = [] for _ in range(n): new_arr += [[0] * m] return new_arr def catching_cheaters(): n, m = [int(x) for x in input().split(' ')] str_a = input() str_b = input() dp = make_array(n + 1, m + 1) ans = 0 for i in range(1, n + 1): for j in range(1, m + 1): if str_a[i - 1] == str_b[j - 1]: dp[i][j] = dp[i - 1][j - 1] + 2 else: dp[i][j] = max(0, max(dp[i - 1][j], dp[i][j - 1]) - 1) ans = max(ans, dp[i][j]) print(ans) if __name__ == "__main__": catching_cheaters() ```
12,654
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4β‹… LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the essays could have been copied, therefore you're interested in their substrings. Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. If X is a string, |X| denotes its length. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters. Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement. You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem). Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 5000) β€” lengths of the two strings A and B. The second line contains a string consisting of n lowercase Latin letters β€” string A. The third line contains a string consisting of m lowercase Latin letters β€” string B. Output Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. Examples Input 4 5 abba babab Output 5 Input 8 10 bbbbabab bbbabaaaaa Output 12 Input 7 7 uiibwws qhtkxcn Output 0 Note For the first case: abb from the first string and abab from the second string have LCS equal to abb. The result is S(abb, abab) = (4 β‹… |abb|) - |abb| - |abab| = 4 β‹… 3 - 3 - 4 = 5. Tags: dp, strings Correct Solution: ``` import sys import os from io import BytesIO, IOBase #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") n, m = map(int, input().split()) a, b = input(), input() dp = [[0] * (m+2) for _ in range(n+2)] ans = 0 for i in range(n-1, -1, -1): for j in range(m-1, -1, -1): if a[i] == b[j]: dp[i][j] = dp[i+1][j+1] + 2 else: dp[i][j] = max(0, max(dp[i][j+1], dp[i+1][j]) -1) ans = max(ans, dp[i][j]) print(ans) ```
12,655
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4β‹… LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the essays could have been copied, therefore you're interested in their substrings. Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. If X is a string, |X| denotes its length. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters. Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement. You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem). Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 5000) β€” lengths of the two strings A and B. The second line contains a string consisting of n lowercase Latin letters β€” string A. The third line contains a string consisting of m lowercase Latin letters β€” string B. Output Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. Examples Input 4 5 abba babab Output 5 Input 8 10 bbbbabab bbbabaaaaa Output 12 Input 7 7 uiibwws qhtkxcn Output 0 Note For the first case: abb from the first string and abab from the second string have LCS equal to abb. The result is S(abb, abab) = (4 β‹… |abb|) - |abb| - |abab| = 4 β‹… 3 - 3 - 4 = 5. Tags: dp, strings Correct Solution: ``` from collections import deque n,m = list(map(int,input().split())) a = input() b = input() l1 = len(a) l2 = len(b) dp = [[0 for j in range(l2+1)] for i in range(l1+1)] mv = 0 for i in range(1,l1+1): for j in range(1,l2+1): if a[i-1]==b[j-1]: dp[i][j] = dp[i-1][j-1]+2 else: dp[i][j] = max(max(dp[i-1][j],dp[i][j-1])-1,0) mv = max(mv,dp[i][j]) print(mv) ```
12,656
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4β‹… LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the essays could have been copied, therefore you're interested in their substrings. Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. If X is a string, |X| denotes its length. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters. Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement. You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem). Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 5000) β€” lengths of the two strings A and B. The second line contains a string consisting of n lowercase Latin letters β€” string A. The third line contains a string consisting of m lowercase Latin letters β€” string B. Output Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. Examples Input 4 5 abba babab Output 5 Input 8 10 bbbbabab bbbabaaaaa Output 12 Input 7 7 uiibwws qhtkxcn Output 0 Note For the first case: abb from the first string and abab from the second string have LCS equal to abb. The result is S(abb, abab) = (4 β‹… |abb|) - |abb| - |abab| = 4 β‹… 3 - 3 - 4 = 5. Tags: dp, strings Correct Solution: ``` # coding: utf-8 n, m = map(int, input().split()) a = input() b = input() dp = [[0 for j in range(m + 1)] for i in range(n + 1)] maximal = 0 for i in range(1, n + 1): for j in range(1, m + 1): dp[i][j] = max(dp[i - 1][j] - 1, dp[i][j - 1] - 1, dp[i - 1][j - 1] + 2 if a[i - 1] == b[j - 1] else 0) maximal = max(maximal, dp[i][j]) print(maximal) ```
12,657
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4β‹… LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the essays could have been copied, therefore you're interested in their substrings. Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. If X is a string, |X| denotes its length. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters. Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement. You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem). Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 5000) β€” lengths of the two strings A and B. The second line contains a string consisting of n lowercase Latin letters β€” string A. The third line contains a string consisting of m lowercase Latin letters β€” string B. Output Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. Examples Input 4 5 abba babab Output 5 Input 8 10 bbbbabab bbbabaaaaa Output 12 Input 7 7 uiibwws qhtkxcn Output 0 Note For the first case: abb from the first string and abab from the second string have LCS equal to abb. The result is S(abb, abab) = (4 β‹… |abb|) - |abb| - |abab| = 4 β‹… 3 - 3 - 4 = 5. Tags: dp, strings Correct Solution: ``` n,m=map(int,input().split()) a=input() b=input() dp=[[0 for i in range(m+1)] for j in range(n+1)] ans=0 for i in range(1,n+1): for j in range(1,m+1): if a[i-1]==b[j-1]: dp[i][j]=max(dp[i][j],dp[i-1][j-1]+2) ans=max(ans,dp[i][j]) else: dp[i][j]=max(dp[i-1][j], dp[i][j-1],1)-1 print(ans) ```
12,658
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4β‹… LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the essays could have been copied, therefore you're interested in their substrings. Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. If X is a string, |X| denotes its length. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters. Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement. You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem). Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 5000) β€” lengths of the two strings A and B. The second line contains a string consisting of n lowercase Latin letters β€” string A. The third line contains a string consisting of m lowercase Latin letters β€” string B. Output Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. Examples Input 4 5 abba babab Output 5 Input 8 10 bbbbabab bbbabaaaaa Output 12 Input 7 7 uiibwws qhtkxcn Output 0 Note For the first case: abb from the first string and abab from the second string have LCS equal to abb. The result is S(abb, abab) = (4 β‹… |abb|) - |abb| - |abab| = 4 β‹… 3 - 3 - 4 = 5. Tags: dp, strings Correct Solution: ``` ''' =============================== -- @uthor : Kaleab Asfaw -- Handle : kaleabasfaw2010 -- Bio : High-School Student ===============================''' # Fast IO import sys import os 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 solve(n, m, a, b): dp = dp = [[0] * (m + 1) for _ in range(n + 1)] maxx = 0 for i in range(1, n+1): for j in range(1, m+1): if a[i-1] == b[j-1]: dp[i][j] = max(dp[i][j], dp[i-1][j-1] + 2) else: dp[i][j] = max(dp[i][j], dp[i-1][j] - 1, dp[i][j-1] - 1) maxx = max(maxx, dp[i][j]) return maxx n, m = list(map(int, input().split())) a = input() b = input() print(solve(n, m, a, b)) ```
12,659
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4β‹… LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the essays could have been copied, therefore you're interested in their substrings. Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. If X is a string, |X| denotes its length. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters. Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement. You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem). Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 5000) β€” lengths of the two strings A and B. The second line contains a string consisting of n lowercase Latin letters β€” string A. The third line contains a string consisting of m lowercase Latin letters β€” string B. Output Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. Examples Input 4 5 abba babab Output 5 Input 8 10 bbbbabab bbbabaaaaa Output 12 Input 7 7 uiibwws qhtkxcn Output 0 Note For the first case: abb from the first string and abab from the second string have LCS equal to abb. The result is S(abb, abab) = (4 β‹… |abb|) - |abb| - |abab| = 4 β‹… 3 - 3 - 4 = 5. Tags: dp, strings Correct Solution: ``` #!/usr/bin/env python import os import sys from io import BytesIO, IOBase import threading from bisect import bisect_right from math import gcd,log from collections import Counter,defaultdict from pprint import pprint def lcs(a,b): ans=0 dp=[[0]*(len(b)+1) for i in range(len(a)+1)] for i in range(1,1+len(a)): for j in range(1,1+len(b)): if a[i-1]==b[j-1]: dp[i][j]=dp[i-1][j-1]+2 dp[i][j]=max(0,dp[i][j],dp[i][j-1]-1,dp[i-1][j]-1) ans=max(ans,dp[i][j]) # pprint(dp) return ans def main(case_no): n,m=map(int,input().split()) a=input() b=input() ans=lcs(a,b) print(ans) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": for _ in range(1): main(_+1) ```
12,660
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4β‹… LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the essays could have been copied, therefore you're interested in their substrings. Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. If X is a string, |X| denotes its length. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters. Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement. You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem). Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 5000) β€” lengths of the two strings A and B. The second line contains a string consisting of n lowercase Latin letters β€” string A. The third line contains a string consisting of m lowercase Latin letters β€” string B. Output Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. Examples Input 4 5 abba babab Output 5 Input 8 10 bbbbabab bbbabaaaaa Output 12 Input 7 7 uiibwws qhtkxcn Output 0 Note For the first case: abb from the first string and abab from the second string have LCS equal to abb. The result is S(abb, abab) = (4 β‹… |abb|) - |abb| - |abab| = 4 β‹… 3 - 3 - 4 = 5. Tags: dp, strings Correct Solution: ``` #include <CodeforcesSolutions.h> #include <ONLINE_JUDGE <solution.cf(contestID = "1447",questionID = "A",method = "GET")>.h> """ Author : thekushalghosh Team : CodeDiggers I prefer Python language over the C++ language :p :D Visit my website : thekushalghosh.github.io """ import sys,math,cmath,time start_time = time.time() ########################################################################## ################# ---- THE ACTUAL CODE STARTS BELOW ---- ################# def solve(): n,m = invr() a = insr() b = insr() dp = [[0] * (m + 1) for i in range(n + 1)] q = 0 for i in range(n): for j in range(m): if a[i] == b[j]: dp[i + 1][j + 1] = max(dp[i + 1][j] - 1,dp[i][j] + 2,dp[i][j + 1] - 1) q = max(q,dp[i + 1][j + 1]) else: dp[i + 1][j + 1] = max(dp[i][j + 1] - 1,dp[i + 1][j] - 1,0) print(q) ################## ---- THE ACTUAL CODE ENDS ABOVE ---- ################## ########################################################################## def main(): global tt if not ONLINE_JUDGE: sys.stdin = open("input.txt","r") sys.stdout = open("output.txt","w") 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 - OUTPUT FUNCTIONS -----------------# def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): return(input().strip()) def invr(): return(map(int,input().split())) def prints(a,qw = " "): sys.stdout.write(qw.join(map(str,a)) + "\n") #------------------ USER DEFINED PROGRAMMING FUNCTIONS ------------------# 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 ncr(n,r): return(math.factorial(n) // (math.factorial(n - r) * math.factorial(r))) def npr(n,r): return(math.factorial(n) // math.factorial(n - r)) #-----------------------------------------------------------------------# ONLINE_JUDGE = __debug__ if ONLINE_JUDGE: #import io,os #input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline input = sys.stdin.readline main() ```
12,661
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4β‹… LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the essays could have been copied, therefore you're interested in their substrings. Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. If X is a string, |X| denotes its length. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters. Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement. You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem). Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 5000) β€” lengths of the two strings A and B. The second line contains a string consisting of n lowercase Latin letters β€” string A. The third line contains a string consisting of m lowercase Latin letters β€” string B. Output Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. Examples Input 4 5 abba babab Output 5 Input 8 10 bbbbabab bbbabaaaaa Output 12 Input 7 7 uiibwws qhtkxcn Output 0 Note For the first case: abb from the first string and abab from the second string have LCS equal to abb. The result is S(abb, abab) = (4 β‹… |abb|) - |abb| - |abab| = 4 β‹… 3 - 3 - 4 = 5. Submitted Solution: ``` n, m = map(int, input().split());a = input();b = input();LR = [0 for _ in range(n+1)];best = 0 for c in b: NR = [0 for _ in range(n+1)] for i in range(1,n+1): back = NR[i-1] - 1;up = LR[i] - 1;diag = LR[i-1] - 2 if c == a[i-1]: diag += 4 NR[i] = max(back, up, diag, 0);best = max(best, NR[i]) LR = NR print(best) ``` Yes
12,662
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4β‹… LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the essays could have been copied, therefore you're interested in their substrings. Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. If X is a string, |X| denotes its length. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters. Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement. You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem). Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 5000) β€” lengths of the two strings A and B. The second line contains a string consisting of n lowercase Latin letters β€” string A. The third line contains a string consisting of m lowercase Latin letters β€” string B. Output Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. Examples Input 4 5 abba babab Output 5 Input 8 10 bbbbabab bbbabaaaaa Output 12 Input 7 7 uiibwws qhtkxcn Output 0 Note For the first case: abb from the first string and abab from the second string have LCS equal to abb. The result is S(abb, abab) = (4 β‹… |abb|) - |abb| - |abab| = 4 β‹… 3 - 3 - 4 = 5. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase import math import itertools as iter from collections import defaultdict as ddic from collections import Counter as Co from collections import deque import threading def increase_stack(): sys.setrecursionlimit(2**32//2-1) threading.stack_size(1 << 27) #sys.setrecursionlimit(10**6) #threading.stack_size(10**8) t = threading.Thread(target=main) t.start() t.join() #? Region Funtions def binary(n): return (bin(n).replace("0b", "")) def decimal(s): return (int(s, 2)) def pow2(n): p = 0 while (n > 1): n //= 2 p += 1 return (p) def primeFactors(n): l=[] while n % 2 == 0: l.append(2) n = n / 2 for i in range(3, int(math.sqrt(n)) + 1, 2): while n % i == 0: l.append(i) n = n / i if n > 2: l.append(int(n)) return (l) def isPrime(n): if (n == 1): return (False) else: root = int(n ** 0.5) root += 1 for i in range(2, root): if (n % i == 0): return (False) return (True) def maxPrimeFactors(n): maxPrime = -1 while n % 2 == 0: maxPrime = 2 n >>= 1 for i in range(3, int(math.sqrt(n)) + 1, 2): while n % i == 0: maxPrime = i n = n / i if n > 2: maxPrime = n return int(maxPrime) def countchar(s,i): c=0 ch=s[i] for i in range(i,len(s)): if(s[i]==ch): c+=1 else: break return(c) def lis(arr): n = len(arr) lis = [1] * n maximum=0 for i in range(1, n): for j in range(0, i): if arr[i] > arr[j] and lis[i] < lis[j] + 1: lis[i] = lis[j] + 1 maximum=max(maximum,lis[i]) return maximum def lcm(arr): a=arr[0]; val=arr[0] for i in range(1,len(arr)): gcd=gcd(a,arr[i]) a=arr[i]; val*=arr[i] return val//gcd #? Region Taking Input def inint(): return int(input()) def inarr(): return list(map(int,input().split())) def invar(): return map(int,input().split()) def instr(): s=input() return list(s) #? Region Fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #!==================================== Write The Useful Code Here ============================ def solver(): pass #! This is the Main Function def main(): n,m=invar() s1=input() s2=input() ans=0 dp=[[0]*(m+1) for i in range(0,n+1)] #print(dp) for i in range(0,n): for j in range(0,m): if(s1[i]==s2[j]): dp[i+1][j+1]=max(0,dp[i][j]+2) else: dp[i+1][j+1]=max(0,dp[i+1][j]-1,dp[i][j+1]-1) ans=max(ans,dp[i+1][j+1]) print(ans) #? End Region if __name__ == "__main__": #? Incresing Stack Limit #increase_stack() #! Calling Main Function main() ``` Yes
12,663
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4β‹… LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the essays could have been copied, therefore you're interested in their substrings. Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. If X is a string, |X| denotes its length. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters. Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement. You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem). Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 5000) β€” lengths of the two strings A and B. The second line contains a string consisting of n lowercase Latin letters β€” string A. The third line contains a string consisting of m lowercase Latin letters β€” string B. Output Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. Examples Input 4 5 abba babab Output 5 Input 8 10 bbbbabab bbbabaaaaa Output 12 Input 7 7 uiibwws qhtkxcn Output 0 Note For the first case: abb from the first string and abab from the second string have LCS equal to abb. The result is S(abb, abab) = (4 β‹… |abb|) - |abb| - |abab| = 4 β‹… 3 - 3 - 4 = 5. Submitted Solution: ``` n, m = map(int, input().split()) A = input() B = input() dp = [] for i, a in enumerate(A): dp.append([]) for j, b in enumerate(B): if i == 0 and j == 0: if a == b: dp[i].append(2) else: dp[i].append(0) elif i == 0: if a == b: dp[i].append(2) else: dp[i].append(max(0, dp[i][j-1] - 1)) elif j == 0: if a == b: dp[i].append(2) else: dp[i].append(max(0, dp[i-1][j] - 1)) else: if a != b: dp[i].append(max(0, dp[i-1][j]-1, dp[i][j-1]-1)) else: dp[i].append(max(0, dp[i-1][j-1]+2, dp[i-1][j]-1, dp[i][j-1]-1)) maxi = max([max(val) for val in dp]) print(maxi) ``` Yes
12,664
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4β‹… LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the essays could have been copied, therefore you're interested in their substrings. Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. If X is a string, |X| denotes its length. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters. Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement. You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem). Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 5000) β€” lengths of the two strings A and B. The second line contains a string consisting of n lowercase Latin letters β€” string A. The third line contains a string consisting of m lowercase Latin letters β€” string B. Output Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. Examples Input 4 5 abba babab Output 5 Input 8 10 bbbbabab bbbabaaaaa Output 12 Input 7 7 uiibwws qhtkxcn Output 0 Note For the first case: abb from the first string and abab from the second string have LCS equal to abb. The result is S(abb, abab) = (4 β‹… |abb|) - |abb| - |abab| = 4 β‹… 3 - 3 - 4 = 5. Submitted Solution: ``` import pprint n, m = map(int, input().split()) s = input() t = input() ans = 0 X = s Y = t m = len(X) n = len(Y) L = [[0]*(n + 1) for i in range(m + 1)] i = 1 j = 1 while i < m + 1: j = 1 while j < n + 1: v = 0 if X[i-1] == Y[j-1]: v = max(L[i - 1][j - 1] + 2, 2) if L[i][j - 1] > v: v = L[i][j - 1] - 1 if L[i - 1][j] > v: v = L[i - 1][j] - 1 L[i][j] = v if v > ans: ans = v j += 1 i += 1 print(ans) ``` Yes
12,665
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4β‹… LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the essays could have been copied, therefore you're interested in their substrings. Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. If X is a string, |X| denotes its length. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters. Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement. You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem). Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 5000) β€” lengths of the two strings A and B. The second line contains a string consisting of n lowercase Latin letters β€” string A. The third line contains a string consisting of m lowercase Latin letters β€” string B. Output Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. Examples Input 4 5 abba babab Output 5 Input 8 10 bbbbabab bbbabaaaaa Output 12 Input 7 7 uiibwws qhtkxcn Output 0 Note For the first case: abb from the first string and abab from the second string have LCS equal to abb. The result is S(abb, abab) = (4 β‹… |abb|) - |abb| - |abab| = 4 β‹… 3 - 3 - 4 = 5. Submitted Solution: ``` import sys from math import gcd,sqrt,ceil,log2 from collections import defaultdict,Counter,deque from bisect import bisect_left,bisect_right import math sys.setrecursionlimit(2*10**5+10) import heapq from itertools import permutations # input=sys.stdin.readline # def print(x): # sys.stdout.write(str(x)+"\n") # sys.stdin = open('input.txt', 'r') # sys.stdout = open('output.txt', 'w') import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 aa='abcdefghijklmnopqrstuvwxyz' 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") # import sys # import io, os # input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def get_sum(bit,i): s = 0 i+=1 while i>0: s+=bit[i] i-=i&(-i) return s def update(bit,n,i,v): i+=1 while i<=n: bit[i]+=v i+=i&(-i) def modInverse(b,m): g = math.gcd(b, m) if (g != 1): return -1 else: return pow(b, m - 2, m) def primeFactors(n): sa = [] # sa.add(n) while n % 2 == 0: sa.append(2) n = n // 2 for i in range(3,int(math.sqrt(n))+1,2): while n % i== 0: sa.append(i) n = n // i # sa.add(n) if n > 2: sa.append(n) return sa def seive(n): pri = [True]*(n+1) p = 2 while p*p<=n: if pri[p] == True: for i in range(p*p,n+1,p): pri[i] = False p+=1 return pri def check_prim(n): if n<0: return False for i in range(2,int(sqrt(n))+1): if n%i == 0: return False return True def getZarr(string, z): n = len(string) # [L,R] make a window which matches # with prefix of s l, r, k = 0, 0, 0 for i in range(1, n): # if i>R nothing matches so we will calculate. # Z[i] using naive way. if i > r: l, r = i, i # R-L = 0 in starting, so it will start # checking from 0'th index. For example, # for "ababab" and i = 1, the value of R # remains 0 and Z[i] becomes 0. For string # "aaaaaa" and i = 1, Z[i] and R become 5 while r < n and string[r - l] == string[r]: r += 1 z[i] = r - l r -= 1 else: # k = i-L so k corresponds to number which # matches in [L,R] interval. k = i - l # if Z[k] is less than remaining interval # then Z[i] will be equal to Z[k]. # For example, str = "ababab", i = 3, R = 5 # and L = 2 if z[k] < r - i + 1: z[i] = z[k] # For example str = "aaaaaa" and i = 2, # R is 5, L is 0 else: # else start from R and check manually l = i while r < n and string[r - l] == string[r]: r += 1 z[i] = r - l r -= 1 def search(text, pattern): # Create concatenated string "P$T" concat = pattern + "$" + text l = len(concat) z = [0] * l getZarr(concat, z) ha = [] for i in range(l): if z[i] == len(pattern): ha.append(i - len(pattern) - 1) return ha # n,k = map(int,input().split()) # l = list(map(int,input().split())) # # n = int(input()) # l = list(map(int,input().split())) # # hash = defaultdict(list) # la = [] # # for i in range(n): # la.append([l[i],i+1]) # # la.sort(key = lambda x: (x[0],-x[1])) # ans = [] # r = n # flag = 0 # lo = [] # ha = [i for i in range(n,0,-1)] # yo = [] # for a,b in la: # # if a == 1: # ans.append([r,b]) # # hash[(1,1)].append([b,r]) # lo.append((r,b)) # ha.pop(0) # yo.append([r,b]) # r-=1 # # elif a == 2: # # print(yo,lo) # # print(hash[1,1]) # if lo == []: # flag = 1 # break # c,d = lo.pop(0) # yo.pop(0) # if b>=d: # flag = 1 # break # ans.append([c,b]) # yo.append([c,b]) # # # # elif a == 3: # # if yo == []: # flag = 1 # break # c,d = yo.pop(0) # if b>=d: # flag = 1 # break # if ha == []: # flag = 1 # break # # ka = ha.pop(0) # # ans.append([ka,b]) # ans.append([ka,d]) # yo.append([ka,b]) # # if flag: # print(-1) # else: # print(len(ans)) # for a,b in ans: # print(a,b) def mergeIntervals(arr): # Sorting based on the increasing order # of the start intervals arr.sort(key = lambda x: x[0]) # array to hold the merged intervals m = [] s = -10000 max = -100000 for i in range(len(arr)): a = arr[i] if a[0] > max: if i != 0: m.append([s,max]) max = a[1] s = a[0] else: if a[1] >= max: max = a[1] #'max' value gives the last point of # that particular interval # 's' gives the starting point of that interval # 'm' array contains the list of all merged intervals if max != -100000 and [s, max] not in m: m.append([s, max]) return m class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) def ncr(n, r, p): num = den = 1 for i in range(r): num = (num * (n - i)) % p den = (den * (i + 1)) % p return (num * pow(den, p - 2, p)) % p def sol(n): seti = set() for i in range(1,int(sqrt(n))+1): if n%i == 0: seti.add(n//i) seti.add(i) return seti def lcm(a,b): return (a*b)//gcd(a,b) # # n,p = map(int,input().split()) # # s = input() # # if n <=2: # if n == 1: # pass # if n == 2: # pass # i = n-1 # idx = -1 # while i>=0: # z = ord(s[i])-96 # k = chr(z+1+96) # flag = 1 # if i-1>=0: # if s[i-1]!=k: # flag+=1 # else: # flag+=1 # if i-2>=0: # if s[i-2]!=k: # flag+=1 # else: # flag+=1 # if flag == 2: # idx = i # s[i] = k # break # if idx == -1: # print('NO') # exit() # for i in range(idx+1,n): # if # def moore_voting(l): count1 = 0 count2 = 0 first = 10**18 second = 10**18 n = len(l) for i in range(n): if l[i] == first: count1+=1 elif l[i] == second: count2+=1 elif count1 == 0: count1+=1 first = l[i] elif count2 == 0: count2+=1 second = l[i] else: count1-=1 count2-=1 for i in range(n): if l[i] == first: count1+=1 elif l[i] == second: count2+=1 if count1>n//3: return first if count2>n//3: return second return -1 def find_parent(u,parent): if u!=parent[u]: parent[u] = find_parent(parent[u],parent) return parent[u] def dis_union(n): par = [i for i in range(n+1)] rank = [1]*(n+1) k = int(input()) for i in range(k): a,b = map(int,input().split()) z1,z2 = find_parent(a,par),find_parent(b,par) if z1!=z2: par[z1] = z2 rank[z2]+=rank[z1] def dijkstra(n,tot,hash): hea = [[0,n]] dis = [10**18]*(tot+1) dis[n] = 0 boo = defaultdict(bool) check = defaultdict(int) while hea: a,b = heapq.heappop(hea) if boo[b]: continue boo[b] = True for i,w in hash[b]: if b == 1: c = 0 if (1,i,w) in nodes: c = nodes[(1,i,w)] del nodes[(1,i,w)] if dis[b]+w<dis[i]: dis[i] = dis[b]+w check[i] = c elif dis[b]+w == dis[i] and c == 0: dis[i] = dis[b]+w check[i] = c else: if dis[b]+w<=dis[i]: dis[i] = dis[b]+w check[i] = check[b] heapq.heappush(hea,[dis[i],i]) return check def power(x,y,p): res = 1 x = x%p if x == 0: return 0 while y>0: if (y&1) == 1: res*=x x = x*x y = y>>1 return res n,m = map(int,input().split()) s1 = input() s2 = input() dp = defaultdict(int) maxi = 0 for i in range(n+1): for j in range(m+1): if i == 0 or j == 0: continue if s1[i-1] == s2[j-1]: dp[(i,j)] = max(dp[(i,j)],dp[(i-1,j-1)]+2) else: dp[(i,j)] = max(dp[(i-1,j)],dp[(i,j-1)]) - 1 maxi = max(dp[(i,j)],maxi) print(maxi) ``` No
12,666
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4β‹… LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the essays could have been copied, therefore you're interested in their substrings. Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. If X is a string, |X| denotes its length. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters. Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement. You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem). Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 5000) β€” lengths of the two strings A and B. The second line contains a string consisting of n lowercase Latin letters β€” string A. The third line contains a string consisting of m lowercase Latin letters β€” string B. Output Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. Examples Input 4 5 abba babab Output 5 Input 8 10 bbbbabab bbbabaaaaa Output 12 Input 7 7 uiibwws qhtkxcn Output 0 Note For the first case: abb from the first string and abab from the second string have LCS equal to abb. The result is S(abb, abab) = (4 β‹… |abb|) - |abb| - |abab| = 4 β‹… 3 - 3 - 4 = 5. Submitted Solution: ``` n,m = list(map(int,input().split())) a = input() b = input() l1 = len(a) l2 = len(b) lcs = [[0 for j in range(l2+1)] for i in range(l1+1)] for i in range(1,l1+1): for j in range(1,l2+1): if a[i-1]==b[j-1]: lcs[i][j] = lcs[i-1][j-1]+1 else: lcs[i][j] = max(lcs[i-1][j],lcs[i][j-1]) i,j = l1,l2 ilist = [] jlist = [] while i>0 and j>0: if a[i-1]==b[j-1]: ilist.append(i) jlist.append(j) i-=1 j-=1 else: if lcs[i][j]==lcs[i][j-1]: j-=1 else: i-=1 out = lcs[-1][-1] la,lb = 0,0 if ilist and jlist: la = ilist[0]-ilist[-1]+1 lb = jlist[0]-jlist[-1]+1 print(4*out-la-lb) ``` No
12,667
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4β‹… LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the essays could have been copied, therefore you're interested in their substrings. Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. If X is a string, |X| denotes its length. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters. Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement. You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem). Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 5000) β€” lengths of the two strings A and B. The second line contains a string consisting of n lowercase Latin letters β€” string A. The third line contains a string consisting of m lowercase Latin letters β€” string B. Output Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. Examples Input 4 5 abba babab Output 5 Input 8 10 bbbbabab bbbabaaaaa Output 12 Input 7 7 uiibwws qhtkxcn Output 0 Note For the first case: abb from the first string and abab from the second string have LCS equal to abb. The result is S(abb, abab) = (4 β‹… |abb|) - |abb| - |abab| = 4 β‹… 3 - 3 - 4 = 5. Submitted Solution: ``` """ #If FastIO not needed, use this and don't forget to strip #import sys, math #input = sys.stdin.readline """ import os import sys from io import BytesIO, IOBase import heapq as h from bisect import bisect_left, bisect_right import time from types import GeneratorType BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os 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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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: self.os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") from collections import defaultdict as dd, deque as dq, Counter as dc import math, string #start_time = time.time() def getInts(): return [int(s) for s in input().split()] def getInt(): return int(input()) def getStrs(): return [s for s in input().split()] def getStr(): return input() def listStr(): return list(input()) def getMat(n): return [getInts() for _ in range(n)] MOD = 10**9+7 """ 4*L(C,D) - |C| - |D| 5 7 8 5 3 4 6 2 4 6 7 3 abba babab Substrings can have length 0 to len(S) in each dp = [[0 for j in range(M+1)] for i in range(N+1)] dp[1][0] = dp[0][1] = 0 dp[1][1] = 0 if S[0] != T[0] else 2 """ def solve(): N, M = getInts() S = [0]+listStr() T = [0]+listStr() ans = 0 dp = [[0 for m in range(M+1)] for n in range(N+1)] for i in range(1,N+1): for j in range(1,M+1): dp[i][j] = max(dp[i-1][j]-1,dp[i][j-1]-1) if S[i] == T[j]: dp[i][j] = max(dp[i][j],dp[i-1][j-1]+2) ans = max(ans,dp[i][j]) return ans #for _ in range(getInt()): print(solve()) #print(time.time()-start_time) ``` No
12,668
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4β‹… LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the essays could have been copied, therefore you're interested in their substrings. Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. If X is a string, |X| denotes its length. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters. Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement. You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem). Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 5000) β€” lengths of the two strings A and B. The second line contains a string consisting of n lowercase Latin letters β€” string A. The third line contains a string consisting of m lowercase Latin letters β€” string B. Output Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. Examples Input 4 5 abba babab Output 5 Input 8 10 bbbbabab bbbabaaaaa Output 12 Input 7 7 uiibwws qhtkxcn Output 0 Note For the first case: abb from the first string and abab from the second string have LCS equal to abb. The result is S(abb, abab) = (4 β‹… |abb|) - |abb| - |abab| = 4 β‹… 3 - 3 - 4 = 5. Submitted Solution: ``` import sys import math def II(): return int(sys.stdin.readline()) def LI(): return list(map(int, sys.stdin.readline().split())) def MI(): return map(int, sys.stdin.readline().split()) def SI(): return sys.stdin.readline().strip() def FACT(n, mod): s = 1 facts = [1] for i in range(1,n+1): s*=i s%=mod facts.append(s) return facts[n] def C(n, k, mod): return (FACT(n,mod) * pow((FACT(k,mod)*FACT(n-k,mod))%mod,mod-2, mod))%mod n,m = MI() a = list(SI()) b = list(SI()) n1 = len(a) n2 = len(b) ans = 0 dp = [[0 for i in range(n2 + 1)] for i in range(n1 + 1)] dp1 = [[[1,1] for i in range(n2 + 1)] for i in range(n1 + 1)] for i in range(1,n+1): for j in range(1,m+1): if a[i-1] == b[j-1]: dp[i][j] = dp[i-1][j-1]+1 dp1[i][j] = dp1[i-1][j-1] if dp[i][j] == 1: dp1[i][j] = [i,j] x,y = dp1[i][j] ans = max(ans,4*dp[i][j]-(i-x+1)-(j-y+1)) else: if dp[i-1][j]>dp[i][j-1]: dp[i][j] = dp[i-1][j] dp1[i][j] = dp1[i-1][j] elif dp[i][j-1]>dp[i-1][j]: dp[i][j] = dp[i][j-1] dp1[i][j] = dp1[i][j-1] else: x,y = dp1[i][j-1] x2,y2 = dp1[i-1][j] if x2-x+y2-y > 0: dp1[i][j] = dp1[i-1][j] else: dp1[i][j] = dp1[i][j-1] print(ans) ``` No
12,669
Provide tags and a correct Python 3 solution for this coding contest problem. During their New Year holidays, Alice and Bob play the following game using an array a of n integers: * Players take turns, Alice moves first. * Each turn a player chooses any element and removes it from the array. * If Alice chooses even value, then she adds it to her score. If the chosen value is odd, Alice's score does not change. * Similarly, if Bob chooses odd value, then he adds it to his score. If the chosen value is even, then Bob's score does not change. If there are no numbers left in the array, then the game ends. The player with the highest score wins. If the scores of the players are equal, then a draw is declared. For example, if n = 4 and a = [5, 2, 7, 3], then the game could go as follows (there are other options): * On the first move, Alice chooses 2 and get two points. Her score is now 2. The array a is now [5, 7, 3]. * On the second move, Bob chooses 5 and get five points. His score is now 5. The array a is now [7, 3]. * On the third move, Alice chooses 7 and get no points. Her score is now 2. The array a is now [3]. * On the last move, Bob chooses 3 and get three points. His score is now 8. The array a is empty now. * Since Bob has more points at the end of the game, he is the winner. You want to find out who will win if both players play optimally. Note that there may be duplicate numbers in the array. Input The first line contains an integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of elements in the array a. The next line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9) β€” the array a used to play the game. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case, output on a separate line: * "Alice" if Alice wins with the optimal play; * "Bob" if Bob wins with the optimal play; * "Tie", if a tie is declared during the optimal play. Example Input 4 4 5 2 7 3 3 3 2 1 4 2 2 2 2 2 7 8 Output Bob Tie Alice Alice Tags: dp, games, greedy, sortings Correct Solution: ``` from heapq import heappush, heappop def solve_slow(l): n = len(l) o = [] e = [] for ele in l: if ele % 2 == 0: heappush(e, -ele) else: heappush(o, -ele) a, b = 0, 0 for i in range(n): # print(e, o, a, b) if i % 2 == 0: if e and o: if -e[0] > -o[0]: a -= heappop(e) else: heappop(o) elif e: a -= heappop(e) else: heappop(o) else: if e and o: if -o[0] > -e[0]: b -= heappop(o) else: heappop(e) elif o: b -= heappop(o) else: heappop(e) if a > b: return "Alice" elif b > a: return "Bob" return "Tie" def solve(l): n = len(l) s = sorted(l) s = s[::-1] a, b = 0, 0 for i in range(n): if i % 2 == 0: a = a + s[i] if s[i] % 2 == 0 else a else: b = b + s[i] if s[i] % 2 == 1 else b if a > b: return "Alice" elif b > a: return "Bob" return "Tie" def main(): p = int(input()) for i in range(p): _ = input() l = [int(_) for _ in input().split()] print(solve(l)) if __name__ == "__main__": main() ```
12,670
Provide tags and a correct Python 3 solution for this coding contest problem. During their New Year holidays, Alice and Bob play the following game using an array a of n integers: * Players take turns, Alice moves first. * Each turn a player chooses any element and removes it from the array. * If Alice chooses even value, then she adds it to her score. If the chosen value is odd, Alice's score does not change. * Similarly, if Bob chooses odd value, then he adds it to his score. If the chosen value is even, then Bob's score does not change. If there are no numbers left in the array, then the game ends. The player with the highest score wins. If the scores of the players are equal, then a draw is declared. For example, if n = 4 and a = [5, 2, 7, 3], then the game could go as follows (there are other options): * On the first move, Alice chooses 2 and get two points. Her score is now 2. The array a is now [5, 7, 3]. * On the second move, Bob chooses 5 and get five points. His score is now 5. The array a is now [7, 3]. * On the third move, Alice chooses 7 and get no points. Her score is now 2. The array a is now [3]. * On the last move, Bob chooses 3 and get three points. His score is now 8. The array a is empty now. * Since Bob has more points at the end of the game, he is the winner. You want to find out who will win if both players play optimally. Note that there may be duplicate numbers in the array. Input The first line contains an integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of elements in the array a. The next line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9) β€” the array a used to play the game. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case, output on a separate line: * "Alice" if Alice wins with the optimal play; * "Bob" if Bob wins with the optimal play; * "Tie", if a tie is declared during the optimal play. Example Input 4 4 5 2 7 3 3 3 2 1 4 2 2 2 2 2 7 8 Output Bob Tie Alice Alice Tags: dp, games, greedy, sortings Correct Solution: ``` for _ in range(int(input())): n = int(input()) values = [int(i) for i in input().split()] odd, even = [], [] for v in values: if v % 2 == 0: even.append(v) else: odd.append(v) even.sort() odd.sort() alice = 0 bob = 0 turn = 0 # print(values) while even or odd: # print(even, odd) if not turn: # alice playing if even and odd and even[-1] > odd[-1]: alice += even.pop() elif odd: odd.pop() elif even: alice += even.pop() turn = 1 else: if even and odd and odd[-1] > even[-1]: bob += odd.pop() elif even: even.pop() elif odd: bob += odd.pop() turn = 0 if alice > bob: print("Alice") elif bob > alice: print("Bob") else: print("Tie") ```
12,671
Provide tags and a correct Python 3 solution for this coding contest problem. During their New Year holidays, Alice and Bob play the following game using an array a of n integers: * Players take turns, Alice moves first. * Each turn a player chooses any element and removes it from the array. * If Alice chooses even value, then she adds it to her score. If the chosen value is odd, Alice's score does not change. * Similarly, if Bob chooses odd value, then he adds it to his score. If the chosen value is even, then Bob's score does not change. If there are no numbers left in the array, then the game ends. The player with the highest score wins. If the scores of the players are equal, then a draw is declared. For example, if n = 4 and a = [5, 2, 7, 3], then the game could go as follows (there are other options): * On the first move, Alice chooses 2 and get two points. Her score is now 2. The array a is now [5, 7, 3]. * On the second move, Bob chooses 5 and get five points. His score is now 5. The array a is now [7, 3]. * On the third move, Alice chooses 7 and get no points. Her score is now 2. The array a is now [3]. * On the last move, Bob chooses 3 and get three points. His score is now 8. The array a is empty now. * Since Bob has more points at the end of the game, he is the winner. You want to find out who will win if both players play optimally. Note that there may be duplicate numbers in the array. Input The first line contains an integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of elements in the array a. The next line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9) β€” the array a used to play the game. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case, output on a separate line: * "Alice" if Alice wins with the optimal play; * "Bob" if Bob wins with the optimal play; * "Tie", if a tie is declared during the optimal play. Example Input 4 4 5 2 7 3 3 3 2 1 4 2 2 2 2 2 7 8 Output Bob Tie Alice Alice Tags: dp, games, greedy, sortings Correct Solution: ``` for _ in range(int(input())): n = int(input()) l = list(map(int,input().split())) l.sort() dif = 0 l1, l2 = [i for i in l if i%2!=0], [i for i in l if i%2==0] alev, bood, c = 0, 0, 0 while len(l1)>0 or len(l2)>0: if c%2==0: if (len(l1)>0 and len(l2)>0) and l1[-1]>l2[-1]: l1.pop() elif len(l2)==0: l1.pop() else: alev+=l2.pop() else: if (len(l1)>0 and len(l2)>0) and l1[-1]<l2[-1]: l2.pop() elif len(l1)==0: l2.pop() else: bood+=l1.pop() c+=1 # print(alev, bood) if alev>bood: print('Alice') elif alev<bood: print('Bob') else: print('Tie') ```
12,672
Provide tags and a correct Python 3 solution for this coding contest problem. During their New Year holidays, Alice and Bob play the following game using an array a of n integers: * Players take turns, Alice moves first. * Each turn a player chooses any element and removes it from the array. * If Alice chooses even value, then she adds it to her score. If the chosen value is odd, Alice's score does not change. * Similarly, if Bob chooses odd value, then he adds it to his score. If the chosen value is even, then Bob's score does not change. If there are no numbers left in the array, then the game ends. The player with the highest score wins. If the scores of the players are equal, then a draw is declared. For example, if n = 4 and a = [5, 2, 7, 3], then the game could go as follows (there are other options): * On the first move, Alice chooses 2 and get two points. Her score is now 2. The array a is now [5, 7, 3]. * On the second move, Bob chooses 5 and get five points. His score is now 5. The array a is now [7, 3]. * On the third move, Alice chooses 7 and get no points. Her score is now 2. The array a is now [3]. * On the last move, Bob chooses 3 and get three points. His score is now 8. The array a is empty now. * Since Bob has more points at the end of the game, he is the winner. You want to find out who will win if both players play optimally. Note that there may be duplicate numbers in the array. Input The first line contains an integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of elements in the array a. The next line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9) β€” the array a used to play the game. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case, output on a separate line: * "Alice" if Alice wins with the optimal play; * "Bob" if Bob wins with the optimal play; * "Tie", if a tie is declared during the optimal play. Example Input 4 4 5 2 7 3 3 3 2 1 4 2 2 2 2 2 7 8 Output Bob Tie Alice Alice Tags: dp, games, greedy, sortings Correct Solution: ``` t=int(input()) for _ in range(t): n=int(input()) arr=list(map(int,input().split())) arr.sort(reverse=True) dif=0 for i in range(n): if( i%2==0 and arr[i]%2==0): dif+=arr[i] elif(i%2==1 and arr[i]%2==1): dif-=arr[i] print("Tie" if dif==0 else("Alice"if dif>0 else "Bob")) ```
12,673
Provide tags and a correct Python 3 solution for this coding contest problem. During their New Year holidays, Alice and Bob play the following game using an array a of n integers: * Players take turns, Alice moves first. * Each turn a player chooses any element and removes it from the array. * If Alice chooses even value, then she adds it to her score. If the chosen value is odd, Alice's score does not change. * Similarly, if Bob chooses odd value, then he adds it to his score. If the chosen value is even, then Bob's score does not change. If there are no numbers left in the array, then the game ends. The player with the highest score wins. If the scores of the players are equal, then a draw is declared. For example, if n = 4 and a = [5, 2, 7, 3], then the game could go as follows (there are other options): * On the first move, Alice chooses 2 and get two points. Her score is now 2. The array a is now [5, 7, 3]. * On the second move, Bob chooses 5 and get five points. His score is now 5. The array a is now [7, 3]. * On the third move, Alice chooses 7 and get no points. Her score is now 2. The array a is now [3]. * On the last move, Bob chooses 3 and get three points. His score is now 8. The array a is empty now. * Since Bob has more points at the end of the game, he is the winner. You want to find out who will win if both players play optimally. Note that there may be duplicate numbers in the array. Input The first line contains an integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of elements in the array a. The next line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9) β€” the array a used to play the game. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case, output on a separate line: * "Alice" if Alice wins with the optimal play; * "Bob" if Bob wins with the optimal play; * "Tie", if a tie is declared during the optimal play. Example Input 4 4 5 2 7 3 3 3 2 1 4 2 2 2 2 2 7 8 Output Bob Tie Alice Alice Tags: dp, games, greedy, sortings Correct Solution: ``` for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) a.sort(reverse=True) res = 0 for i in range(n): if i % 2 == 0: if a[i] % 2 == 0: res += a[i] else: if a[i] % 2 == 1: res -= a[i] if res > 0: print("Alice") elif res == 0: print("Tie") else: print("Bob") ```
12,674
Provide tags and a correct Python 3 solution for this coding contest problem. During their New Year holidays, Alice and Bob play the following game using an array a of n integers: * Players take turns, Alice moves first. * Each turn a player chooses any element and removes it from the array. * If Alice chooses even value, then she adds it to her score. If the chosen value is odd, Alice's score does not change. * Similarly, if Bob chooses odd value, then he adds it to his score. If the chosen value is even, then Bob's score does not change. If there are no numbers left in the array, then the game ends. The player with the highest score wins. If the scores of the players are equal, then a draw is declared. For example, if n = 4 and a = [5, 2, 7, 3], then the game could go as follows (there are other options): * On the first move, Alice chooses 2 and get two points. Her score is now 2. The array a is now [5, 7, 3]. * On the second move, Bob chooses 5 and get five points. His score is now 5. The array a is now [7, 3]. * On the third move, Alice chooses 7 and get no points. Her score is now 2. The array a is now [3]. * On the last move, Bob chooses 3 and get three points. His score is now 8. The array a is empty now. * Since Bob has more points at the end of the game, he is the winner. You want to find out who will win if both players play optimally. Note that there may be duplicate numbers in the array. Input The first line contains an integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of elements in the array a. The next line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9) β€” the array a used to play the game. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case, output on a separate line: * "Alice" if Alice wins with the optimal play; * "Bob" if Bob wins with the optimal play; * "Tie", if a tie is declared during the optimal play. Example Input 4 4 5 2 7 3 3 3 2 1 4 2 2 2 2 2 7 8 Output Bob Tie Alice Alice Tags: dp, games, greedy, sortings Correct Solution: ``` test_cases = int(input()) for x in range(test_cases): a = 0 b = 0 i = int(input()) l = list(map(int, input().split())) l = sorted(l) for move in range(1,len(l)+1): n = l.pop() # check first for turn Alice or Bob if move%2 == 0 and n%2 != 0: # Bobs turn and n is odd b += n elif move%2 != 0 and n%2 == 0: # Alice turn and n is even a += n if a>b: print('Alice') elif a == b: print('Tie') else: print('Bob') ```
12,675
Provide tags and a correct Python 3 solution for this coding contest problem. During their New Year holidays, Alice and Bob play the following game using an array a of n integers: * Players take turns, Alice moves first. * Each turn a player chooses any element and removes it from the array. * If Alice chooses even value, then she adds it to her score. If the chosen value is odd, Alice's score does not change. * Similarly, if Bob chooses odd value, then he adds it to his score. If the chosen value is even, then Bob's score does not change. If there are no numbers left in the array, then the game ends. The player with the highest score wins. If the scores of the players are equal, then a draw is declared. For example, if n = 4 and a = [5, 2, 7, 3], then the game could go as follows (there are other options): * On the first move, Alice chooses 2 and get two points. Her score is now 2. The array a is now [5, 7, 3]. * On the second move, Bob chooses 5 and get five points. His score is now 5. The array a is now [7, 3]. * On the third move, Alice chooses 7 and get no points. Her score is now 2. The array a is now [3]. * On the last move, Bob chooses 3 and get three points. His score is now 8. The array a is empty now. * Since Bob has more points at the end of the game, he is the winner. You want to find out who will win if both players play optimally. Note that there may be duplicate numbers in the array. Input The first line contains an integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of elements in the array a. The next line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9) β€” the array a used to play the game. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case, output on a separate line: * "Alice" if Alice wins with the optimal play; * "Bob" if Bob wins with the optimal play; * "Tie", if a tie is declared during the optimal play. Example Input 4 4 5 2 7 3 3 3 2 1 4 2 2 2 2 2 7 8 Output Bob Tie Alice Alice Tags: dp, games, greedy, sortings Correct Solution: ``` # fn = "input.txt" # dat = open(fn).read().strip().split('\n') import sys n_tests = int(sys.stdin.readline().strip()) for _ in range(n_tests): alice = 0 bob = 0 max_index = int(sys.stdin.readline().strip()) l1 = [int(v) for v in sys.stdin.readline().strip().split(" ")] l1.sort() i = 1 while l1: v = l1.pop() if i % 2 == 0: if v % 2 != 0: bob += v else: if v % 2 == 0: alice += v i += 1 if alice > bob: print("Alice") elif bob > alice: print("Bob") else: print("Tie") ```
12,676
Provide tags and a correct Python 3 solution for this coding contest problem. During their New Year holidays, Alice and Bob play the following game using an array a of n integers: * Players take turns, Alice moves first. * Each turn a player chooses any element and removes it from the array. * If Alice chooses even value, then she adds it to her score. If the chosen value is odd, Alice's score does not change. * Similarly, if Bob chooses odd value, then he adds it to his score. If the chosen value is even, then Bob's score does not change. If there are no numbers left in the array, then the game ends. The player with the highest score wins. If the scores of the players are equal, then a draw is declared. For example, if n = 4 and a = [5, 2, 7, 3], then the game could go as follows (there are other options): * On the first move, Alice chooses 2 and get two points. Her score is now 2. The array a is now [5, 7, 3]. * On the second move, Bob chooses 5 and get five points. His score is now 5. The array a is now [7, 3]. * On the third move, Alice chooses 7 and get no points. Her score is now 2. The array a is now [3]. * On the last move, Bob chooses 3 and get three points. His score is now 8. The array a is empty now. * Since Bob has more points at the end of the game, he is the winner. You want to find out who will win if both players play optimally. Note that there may be duplicate numbers in the array. Input The first line contains an integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of elements in the array a. The next line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9) β€” the array a used to play the game. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case, output on a separate line: * "Alice" if Alice wins with the optimal play; * "Bob" if Bob wins with the optimal play; * "Tie", if a tie is declared during the optimal play. Example Input 4 4 5 2 7 3 3 3 2 1 4 2 2 2 2 2 7 8 Output Bob Tie Alice Alice Tags: dp, games, greedy, sortings Correct Solution: ``` for _ in range(int(input())): n = int(input()) A = sorted([int(x) for x in input().split()]) A.reverse() a = sum([i for i in A[::2] if not i%2]) b = sum([i for i in A[1::2] if i%2]) if(a>b): print("Alice") elif(a<b): print("Bob") else: print("Tie") ```
12,677
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. During their New Year holidays, Alice and Bob play the following game using an array a of n integers: * Players take turns, Alice moves first. * Each turn a player chooses any element and removes it from the array. * If Alice chooses even value, then she adds it to her score. If the chosen value is odd, Alice's score does not change. * Similarly, if Bob chooses odd value, then he adds it to his score. If the chosen value is even, then Bob's score does not change. If there are no numbers left in the array, then the game ends. The player with the highest score wins. If the scores of the players are equal, then a draw is declared. For example, if n = 4 and a = [5, 2, 7, 3], then the game could go as follows (there are other options): * On the first move, Alice chooses 2 and get two points. Her score is now 2. The array a is now [5, 7, 3]. * On the second move, Bob chooses 5 and get five points. His score is now 5. The array a is now [7, 3]. * On the third move, Alice chooses 7 and get no points. Her score is now 2. The array a is now [3]. * On the last move, Bob chooses 3 and get three points. His score is now 8. The array a is empty now. * Since Bob has more points at the end of the game, he is the winner. You want to find out who will win if both players play optimally. Note that there may be duplicate numbers in the array. Input The first line contains an integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of elements in the array a. The next line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9) β€” the array a used to play the game. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case, output on a separate line: * "Alice" if Alice wins with the optimal play; * "Bob" if Bob wins with the optimal play; * "Tie", if a tie is declared during the optimal play. Example Input 4 4 5 2 7 3 3 3 2 1 4 2 2 2 2 2 7 8 Output Bob Tie Alice Alice Submitted Solution: ``` import sys input=sys.stdin.readline t=int(input()) for k in range(t): n=int(input()) a=list(map(int,input().split())) p,q=[],[] x,y=0,0 for i in range(n): if a[i]%2==0: p.append(a[i]) x+=1 else: q.append(a[i]) y+=1 p=sorted(p,reverse=True) q=sorted(q,reverse=True) i,j=0,0 r,s=0,0 c=0 while(i<x or j<y): if i<x and j<y: z=max(p[i],q[j]) elif i<x: z=p[i] elif j<y: z=q[j] if c%2==1: if z%2==1: s+=z j+=1 else: i+=1 elif c%2==0: if z%2==0: r+=z i+=1 else: j+=1 c+=1 if s>r: print("Bob") elif r==s: print("Tie") else: print("Alice") ``` Yes
12,678
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. During their New Year holidays, Alice and Bob play the following game using an array a of n integers: * Players take turns, Alice moves first. * Each turn a player chooses any element and removes it from the array. * If Alice chooses even value, then she adds it to her score. If the chosen value is odd, Alice's score does not change. * Similarly, if Bob chooses odd value, then he adds it to his score. If the chosen value is even, then Bob's score does not change. If there are no numbers left in the array, then the game ends. The player with the highest score wins. If the scores of the players are equal, then a draw is declared. For example, if n = 4 and a = [5, 2, 7, 3], then the game could go as follows (there are other options): * On the first move, Alice chooses 2 and get two points. Her score is now 2. The array a is now [5, 7, 3]. * On the second move, Bob chooses 5 and get five points. His score is now 5. The array a is now [7, 3]. * On the third move, Alice chooses 7 and get no points. Her score is now 2. The array a is now [3]. * On the last move, Bob chooses 3 and get three points. His score is now 8. The array a is empty now. * Since Bob has more points at the end of the game, he is the winner. You want to find out who will win if both players play optimally. Note that there may be duplicate numbers in the array. Input The first line contains an integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of elements in the array a. The next line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9) β€” the array a used to play the game. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case, output on a separate line: * "Alice" if Alice wins with the optimal play; * "Bob" if Bob wins with the optimal play; * "Tie", if a tie is declared during the optimal play. Example Input 4 4 5 2 7 3 3 3 2 1 4 2 2 2 2 2 7 8 Output Bob Tie Alice Alice Submitted Solution: ``` t = int(input()) for _ in range(t): n = int(input()) *a, = map(int, input().split()) a.sort(reverse=1) r = 0 for i in range(n): if i % 2 == 0 and a[i] % 2 == 0: r += a[i] elif i % 2 == 1 and a[i] % 2 == 1: r -= a[i] if r == 0: print('Tie') elif r > 0: print('Alice') elif r < 0: print('Bob') ``` Yes
12,679
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. During their New Year holidays, Alice and Bob play the following game using an array a of n integers: * Players take turns, Alice moves first. * Each turn a player chooses any element and removes it from the array. * If Alice chooses even value, then she adds it to her score. If the chosen value is odd, Alice's score does not change. * Similarly, if Bob chooses odd value, then he adds it to his score. If the chosen value is even, then Bob's score does not change. If there are no numbers left in the array, then the game ends. The player with the highest score wins. If the scores of the players are equal, then a draw is declared. For example, if n = 4 and a = [5, 2, 7, 3], then the game could go as follows (there are other options): * On the first move, Alice chooses 2 and get two points. Her score is now 2. The array a is now [5, 7, 3]. * On the second move, Bob chooses 5 and get five points. His score is now 5. The array a is now [7, 3]. * On the third move, Alice chooses 7 and get no points. Her score is now 2. The array a is now [3]. * On the last move, Bob chooses 3 and get three points. His score is now 8. The array a is empty now. * Since Bob has more points at the end of the game, he is the winner. You want to find out who will win if both players play optimally. Note that there may be duplicate numbers in the array. Input The first line contains an integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of elements in the array a. The next line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9) β€” the array a used to play the game. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case, output on a separate line: * "Alice" if Alice wins with the optimal play; * "Bob" if Bob wins with the optimal play; * "Tie", if a tie is declared during the optimal play. Example Input 4 4 5 2 7 3 3 3 2 1 4 2 2 2 2 2 7 8 Output Bob Tie Alice Alice Submitted Solution: ``` for _ in range(int(input())): n=int(input()) arr=list(map(int,input().split())) arr=sorted(arr)[::-1];Alice=0;Bob=0 for i in range(n): if i%2==0:#ALice turn if arr[i]%2==0:Alice+=arr[i] else: if arr[i]%2==1:Bob+=arr[i] if Alice==Bob:print("Tie") elif Alice>Bob:print("Alice") else:print("Bob") ``` Yes
12,680
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. During their New Year holidays, Alice and Bob play the following game using an array a of n integers: * Players take turns, Alice moves first. * Each turn a player chooses any element and removes it from the array. * If Alice chooses even value, then she adds it to her score. If the chosen value is odd, Alice's score does not change. * Similarly, if Bob chooses odd value, then he adds it to his score. If the chosen value is even, then Bob's score does not change. If there are no numbers left in the array, then the game ends. The player with the highest score wins. If the scores of the players are equal, then a draw is declared. For example, if n = 4 and a = [5, 2, 7, 3], then the game could go as follows (there are other options): * On the first move, Alice chooses 2 and get two points. Her score is now 2. The array a is now [5, 7, 3]. * On the second move, Bob chooses 5 and get five points. His score is now 5. The array a is now [7, 3]. * On the third move, Alice chooses 7 and get no points. Her score is now 2. The array a is now [3]. * On the last move, Bob chooses 3 and get three points. His score is now 8. The array a is empty now. * Since Bob has more points at the end of the game, he is the winner. You want to find out who will win if both players play optimally. Note that there may be duplicate numbers in the array. Input The first line contains an integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of elements in the array a. The next line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9) β€” the array a used to play the game. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case, output on a separate line: * "Alice" if Alice wins with the optimal play; * "Bob" if Bob wins with the optimal play; * "Tie", if a tie is declared during the optimal play. Example Input 4 4 5 2 7 3 3 3 2 1 4 2 2 2 2 2 7 8 Output Bob Tie Alice Alice Submitted Solution: ``` import math from time import time from collections import Counter, deque def main(): # Main code in every file n = int(input()) K = list(map(int, input().split())) A = deque(sorted(K, reverse=True)) s1 = 0 s2 = 0 t = 1 while len(A) != 0: if t == 1: if A[0] % 2 == 0: s1 += A[0] else: if A[0] % 2 == 1: s2 += A[0] A.popleft() if t == 1: t = 2 else: t = 1 if s1 == s2: print('Tie') elif s1 > s2: print('Alice') else: print('Bob') for i in range(int(input())): # When many inputs main() # main() ``` Yes
12,681
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. During their New Year holidays, Alice and Bob play the following game using an array a of n integers: * Players take turns, Alice moves first. * Each turn a player chooses any element and removes it from the array. * If Alice chooses even value, then she adds it to her score. If the chosen value is odd, Alice's score does not change. * Similarly, if Bob chooses odd value, then he adds it to his score. If the chosen value is even, then Bob's score does not change. If there are no numbers left in the array, then the game ends. The player with the highest score wins. If the scores of the players are equal, then a draw is declared. For example, if n = 4 and a = [5, 2, 7, 3], then the game could go as follows (there are other options): * On the first move, Alice chooses 2 and get two points. Her score is now 2. The array a is now [5, 7, 3]. * On the second move, Bob chooses 5 and get five points. His score is now 5. The array a is now [7, 3]. * On the third move, Alice chooses 7 and get no points. Her score is now 2. The array a is now [3]. * On the last move, Bob chooses 3 and get three points. His score is now 8. The array a is empty now. * Since Bob has more points at the end of the game, he is the winner. You want to find out who will win if both players play optimally. Note that there may be duplicate numbers in the array. Input The first line contains an integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of elements in the array a. The next line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9) β€” the array a used to play the game. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case, output on a separate line: * "Alice" if Alice wins with the optimal play; * "Bob" if Bob wins with the optimal play; * "Tie", if a tie is declared during the optimal play. Example Input 4 4 5 2 7 3 3 3 2 1 4 2 2 2 2 2 7 8 Output Bob Tie Alice Alice Submitted Solution: ``` t=int(input()) for _ in range(t): n=int(input()) l=list(map(int,input().split())) l.sort(reverse=True) a=[] b=[] for i in l: if i%2==0: a.append(i) else: b.append(i) if len(a)==len(b): n1=sum(a) n2=sum(b) elif len(a)<len(b): n1=sum(a) n2=sum(b[0:len(a)]) l=b[len(a):] for i in range(len(b)-len(a)): if i%2==0: if l[i]%2==0: n1+=l[i] else: if l[i]%2!=0: n2+=l[i] elif len(a)>len(b): n2=sum(b) n1=sum(a[0:len(b)]) l=a[len(b):] for i in range(len(a)-len(b)): if i%2==0: if l[i]%2!=0: n2+=l[i] else: if l[i]%2==0: n1+=l[i] if n1<n2: print("Bob") elif n1>n2: print("Alice") else: print("Tie") ``` No
12,682
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. During their New Year holidays, Alice and Bob play the following game using an array a of n integers: * Players take turns, Alice moves first. * Each turn a player chooses any element and removes it from the array. * If Alice chooses even value, then she adds it to her score. If the chosen value is odd, Alice's score does not change. * Similarly, if Bob chooses odd value, then he adds it to his score. If the chosen value is even, then Bob's score does not change. If there are no numbers left in the array, then the game ends. The player with the highest score wins. If the scores of the players are equal, then a draw is declared. For example, if n = 4 and a = [5, 2, 7, 3], then the game could go as follows (there are other options): * On the first move, Alice chooses 2 and get two points. Her score is now 2. The array a is now [5, 7, 3]. * On the second move, Bob chooses 5 and get five points. His score is now 5. The array a is now [7, 3]. * On the third move, Alice chooses 7 and get no points. Her score is now 2. The array a is now [3]. * On the last move, Bob chooses 3 and get three points. His score is now 8. The array a is empty now. * Since Bob has more points at the end of the game, he is the winner. You want to find out who will win if both players play optimally. Note that there may be duplicate numbers in the array. Input The first line contains an integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of elements in the array a. The next line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9) β€” the array a used to play the game. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case, output on a separate line: * "Alice" if Alice wins with the optimal play; * "Bob" if Bob wins with the optimal play; * "Tie", if a tie is declared during the optimal play. Example Input 4 4 5 2 7 3 3 3 2 1 4 2 2 2 2 2 7 8 Output Bob Tie Alice Alice Submitted Solution: ``` def EvenOddGame(n, arr): visited = {} for i in range(0, n): visited[arr[i]] = False bob = 0 alice = 0 bobS = False aliceS = True for i in range(0, n): j = 0 while ((j < n) and ((arr[j] & 1) != 1) and (not visited[arr[j]]) and (aliceS)): print("Alice" + str(arr[j])) visited[arr[j]] = True aliceS = False bobS = True alice += arr[j] break while j < n and ((arr[j] & 1) == 1) and not visited[arr[j]] and bobS: print("Bob" + str(arr[j])) visited[arr[j]] = True bobS = False aliceS = True bob += arr[j] break # print(bob, alice) if bob == alice: return "Trie" elif bob > alice: return "Bob" else: return "Alice" tc = int(input()) for _ in range(0,tc): n = int(input()) arr = [int(i) for i in input().split()][:n] print(EvenOddGame(n, arr)) ``` No
12,683
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. During their New Year holidays, Alice and Bob play the following game using an array a of n integers: * Players take turns, Alice moves first. * Each turn a player chooses any element and removes it from the array. * If Alice chooses even value, then she adds it to her score. If the chosen value is odd, Alice's score does not change. * Similarly, if Bob chooses odd value, then he adds it to his score. If the chosen value is even, then Bob's score does not change. If there are no numbers left in the array, then the game ends. The player with the highest score wins. If the scores of the players are equal, then a draw is declared. For example, if n = 4 and a = [5, 2, 7, 3], then the game could go as follows (there are other options): * On the first move, Alice chooses 2 and get two points. Her score is now 2. The array a is now [5, 7, 3]. * On the second move, Bob chooses 5 and get five points. His score is now 5. The array a is now [7, 3]. * On the third move, Alice chooses 7 and get no points. Her score is now 2. The array a is now [3]. * On the last move, Bob chooses 3 and get three points. His score is now 8. The array a is empty now. * Since Bob has more points at the end of the game, he is the winner. You want to find out who will win if both players play optimally. Note that there may be duplicate numbers in the array. Input The first line contains an integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of elements in the array a. The next line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9) β€” the array a used to play the game. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case, output on a separate line: * "Alice" if Alice wins with the optimal play; * "Bob" if Bob wins with the optimal play; * "Tie", if a tie is declared during the optimal play. Example Input 4 4 5 2 7 3 3 3 2 1 4 2 2 2 2 2 7 8 Output Bob Tie Alice Alice Submitted Solution: ``` t = int(input("")) for _ in range(t): n = int(input("")) data = list(map(int,input("").split(" "))) odd = list() even = list() for x in data: if x % 2 == 1: odd.append(x) else: even.append(x) sorted(odd) sorted(even) i = len(odd) - 1 j = len(even) - 1 bob = 0 alice = 0 cnt = 0 while(i >= 0 and j >= 0): if (cnt % 2 == 0): if(even[j] > odd[i]): alice += even[j] j -= 1 else: i -= 1 else: if(odd[i] > even[j]): bob += odd[i] i -= 1 else: j -= 1 cnt += 1 while(i >= 0): if(cnt % 2 == 1): bob += odd[i] i -= 1 cnt += 1 while(j >= 0): if(cnt % 2 == 0): alice += even[j] j -= 1 cnt += 1 if bob > alice: print("Bob") elif alice > bob: print("Alice") else: print("Tie") ``` No
12,684
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. During their New Year holidays, Alice and Bob play the following game using an array a of n integers: * Players take turns, Alice moves first. * Each turn a player chooses any element and removes it from the array. * If Alice chooses even value, then she adds it to her score. If the chosen value is odd, Alice's score does not change. * Similarly, if Bob chooses odd value, then he adds it to his score. If the chosen value is even, then Bob's score does not change. If there are no numbers left in the array, then the game ends. The player with the highest score wins. If the scores of the players are equal, then a draw is declared. For example, if n = 4 and a = [5, 2, 7, 3], then the game could go as follows (there are other options): * On the first move, Alice chooses 2 and get two points. Her score is now 2. The array a is now [5, 7, 3]. * On the second move, Bob chooses 5 and get five points. His score is now 5. The array a is now [7, 3]. * On the third move, Alice chooses 7 and get no points. Her score is now 2. The array a is now [3]. * On the last move, Bob chooses 3 and get three points. His score is now 8. The array a is empty now. * Since Bob has more points at the end of the game, he is the winner. You want to find out who will win if both players play optimally. Note that there may be duplicate numbers in the array. Input The first line contains an integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains an integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of elements in the array a. The next line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9) β€” the array a used to play the game. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case, output on a separate line: * "Alice" if Alice wins with the optimal play; * "Bob" if Bob wins with the optimal play; * "Tie", if a tie is declared during the optimal play. Example Input 4 4 5 2 7 3 3 3 2 1 4 2 2 2 2 2 7 8 Output Bob Tie Alice Alice Submitted Solution: ``` T=int(input()) for _ in range(T): n=int(input()) a=[int(x) for x in input().split()] a.sort(reverse=True) a1=0 b1=0 for i in range(n): if i%2==0: if a[i]%2==0: a1+=a[i] else: if a[i]%2!=0: b1=+a[i] if a1>b1: print("Alice") elif b1>a1: print("Bob") else: print("Tie") ``` No
12,685
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: <https://codeforces.com/blog/entry/45307>. There is a city in which Dixit lives. In the city, there are n houses. There is exactly one directed road between every pair of houses. For example, consider two houses A and B, then there is a directed road either from A to B or from B to A but not both. The number of roads leading to the i-th house is k_i. Two houses A and B are bi-reachable if A is reachable from B and B is reachable from A. We say that house B is reachable from house A when there is a path from house A to house B. Dixit wants to buy two houses in the city, that is, one for living and one for studying. Of course, he would like to travel from one house to another. So, he wants to find a pair of bi-reachable houses A and B. Among all such pairs, he wants to choose one with the maximum value of |k_A - k_B|, where k_i is the number of roads leading to the house i. If more than one optimal pair exists, any of them is suitable. Since Dixit is busy preparing CodeCraft, can you help him find the desired pair of houses, or tell him that no such houses exist? In the problem input, you are not given the direction of each road. You are given β€” for each house β€” only the number of incoming roads to that house (k_i). You are allowed to ask only one type of query from the judge: give two houses A and B, and the judge answers whether B is reachable from A. There is no upper limit on the number of queries. But, you cannot ask more queries after the judge answers "Yes" to any of your queries. Also, you cannot ask the same query twice. Once you have exhausted all your queries (or the judge responds "Yes" to any of your queries), your program must output its guess for the two houses and quit. See the Interaction section below for more details. Input The first line contains a single integer n (3 ≀ n ≀ 500) denoting the number of houses in the city. The next line contains n space-separated integers k_1, k_2, ..., k_n (0 ≀ k_i ≀ n - 1), the i-th of them represents the number of incoming roads to the i-th house. Interaction To ask a query, print "? A B" (1 ≀ A,B ≀ N, Aβ‰  B). The judge will respond "Yes" if house B is reachable from house A, or "No" otherwise. To output the final answer, print "! A B", where A and B are bi-reachable with the maximum possible value of |k_A - k_B|. If there does not exist such pair of houses A and B, output "! 0 0". After outputting the final answer, your program must terminate immediately, otherwise you will receive Wrong Answer verdict. You cannot ask the same query twice. There is no upper limit to the number of queries you ask, but, you cannot ask more queries after the judge answers "Yes" to any of your queries. Your program must now output the final answer ("! A B" or "! 0 0") and terminate. If you ask a query in incorrect format or repeat a previous query, you will get Wrong Answer verdict. After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get the Idleness limit exceeded error. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. Examples Input 3 1 1 1 Yes Output ? 1 2 ! 1 2 Input 4 1 2 0 3 No No No No No No Output ? 2 1 ? 1 3 ? 4 1 ? 2 3 ? 4 2 ? 4 3 ! 0 0 Note In the first sample input, we are given a city of three houses with one incoming road each. The user program asks one query: "? 1 2": asking whether we can reach from house 1 to house 2. The judge responds with "Yes". The user program now concludes that this is sufficient information to determine the correct answer. So, it outputs "! 1 2" and quits. In the second sample input, the user program queries for six different pairs of houses, and finally answers "! 0 0" as it is convinced that no two houses as desired in the question exist in this city. Tags: brute force, graphs, greedy, interactive, sortings Correct Solution: ``` import sys def guess(i, j): print(f"? {i} {j}") sys.stdout.flush() return input() def answer(i, j): print(f"! {i} {j}") sys.stdout.flush() def solve(n, k): pairs = [] for i in range(len(k)): for j in range(i+1, len(k)): pairs.append((abs(k[i] - k[j]), i, j)) for d, i, j in reversed(sorted(pairs)): a, b = i, j if k[i] < k[j]: a, b = b, a r = guess(a+1, b+1) if r == "Yes": answer(a+1, b+1) return answer(0, 0) n = int(input()) k = [int(v) for v in input().split()] solve(n, k) ```
12,686
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: <https://codeforces.com/blog/entry/45307>. There is a city in which Dixit lives. In the city, there are n houses. There is exactly one directed road between every pair of houses. For example, consider two houses A and B, then there is a directed road either from A to B or from B to A but not both. The number of roads leading to the i-th house is k_i. Two houses A and B are bi-reachable if A is reachable from B and B is reachable from A. We say that house B is reachable from house A when there is a path from house A to house B. Dixit wants to buy two houses in the city, that is, one for living and one for studying. Of course, he would like to travel from one house to another. So, he wants to find a pair of bi-reachable houses A and B. Among all such pairs, he wants to choose one with the maximum value of |k_A - k_B|, where k_i is the number of roads leading to the house i. If more than one optimal pair exists, any of them is suitable. Since Dixit is busy preparing CodeCraft, can you help him find the desired pair of houses, or tell him that no such houses exist? In the problem input, you are not given the direction of each road. You are given β€” for each house β€” only the number of incoming roads to that house (k_i). You are allowed to ask only one type of query from the judge: give two houses A and B, and the judge answers whether B is reachable from A. There is no upper limit on the number of queries. But, you cannot ask more queries after the judge answers "Yes" to any of your queries. Also, you cannot ask the same query twice. Once you have exhausted all your queries (or the judge responds "Yes" to any of your queries), your program must output its guess for the two houses and quit. See the Interaction section below for more details. Input The first line contains a single integer n (3 ≀ n ≀ 500) denoting the number of houses in the city. The next line contains n space-separated integers k_1, k_2, ..., k_n (0 ≀ k_i ≀ n - 1), the i-th of them represents the number of incoming roads to the i-th house. Interaction To ask a query, print "? A B" (1 ≀ A,B ≀ N, Aβ‰  B). The judge will respond "Yes" if house B is reachable from house A, or "No" otherwise. To output the final answer, print "! A B", where A and B are bi-reachable with the maximum possible value of |k_A - k_B|. If there does not exist such pair of houses A and B, output "! 0 0". After outputting the final answer, your program must terminate immediately, otherwise you will receive Wrong Answer verdict. You cannot ask the same query twice. There is no upper limit to the number of queries you ask, but, you cannot ask more queries after the judge answers "Yes" to any of your queries. Your program must now output the final answer ("! A B" or "! 0 0") and terminate. If you ask a query in incorrect format or repeat a previous query, you will get Wrong Answer verdict. After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get the Idleness limit exceeded error. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. Examples Input 3 1 1 1 Yes Output ? 1 2 ! 1 2 Input 4 1 2 0 3 No No No No No No Output ? 2 1 ? 1 3 ? 4 1 ? 2 3 ? 4 2 ? 4 3 ! 0 0 Note In the first sample input, we are given a city of three houses with one incoming road each. The user program asks one query: "? 1 2": asking whether we can reach from house 1 to house 2. The judge responds with "Yes". The user program now concludes that this is sufficient information to determine the correct answer. So, it outputs "! 1 2" and quits. In the second sample input, the user program queries for six different pairs of houses, and finally answers "! 0 0" as it is convinced that no two houses as desired in the question exist in this city. Tags: brute force, graphs, greedy, interactive, sortings Correct Solution: ``` from sys import stdin, stdout input = stdin.readline def MyIter(n): for k in range(n-1, 0, -1): i = 0 while i + k < n: yield i, i + k i += 1 def solve(n, a): dct = [[] for i in range(n)] for i, el in enumerate(a): dct[el].append(i + 1) for i, j in MyIter(n): for a in dct[i]: for b in dct[j]: stdout.write('? %d %d\n' % (b, a)) stdout.flush() if input()[0] == 'Y': return [a, b] for j in range(n): if len(dct[j]) >= 2: return dct[j][:2] return [0, 0] n = int(input()) a = list(map(int, input().split())) ''' _qq = 0 def input(): global _qq _qq += 1 print(_qq, end='\r') return 'No' ''' res = solve(n, a) print('!', *res) ```
12,687
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: <https://codeforces.com/blog/entry/45307>. There is a city in which Dixit lives. In the city, there are n houses. There is exactly one directed road between every pair of houses. For example, consider two houses A and B, then there is a directed road either from A to B or from B to A but not both. The number of roads leading to the i-th house is k_i. Two houses A and B are bi-reachable if A is reachable from B and B is reachable from A. We say that house B is reachable from house A when there is a path from house A to house B. Dixit wants to buy two houses in the city, that is, one for living and one for studying. Of course, he would like to travel from one house to another. So, he wants to find a pair of bi-reachable houses A and B. Among all such pairs, he wants to choose one with the maximum value of |k_A - k_B|, where k_i is the number of roads leading to the house i. If more than one optimal pair exists, any of them is suitable. Since Dixit is busy preparing CodeCraft, can you help him find the desired pair of houses, or tell him that no such houses exist? In the problem input, you are not given the direction of each road. You are given β€” for each house β€” only the number of incoming roads to that house (k_i). You are allowed to ask only one type of query from the judge: give two houses A and B, and the judge answers whether B is reachable from A. There is no upper limit on the number of queries. But, you cannot ask more queries after the judge answers "Yes" to any of your queries. Also, you cannot ask the same query twice. Once you have exhausted all your queries (or the judge responds "Yes" to any of your queries), your program must output its guess for the two houses and quit. See the Interaction section below for more details. Input The first line contains a single integer n (3 ≀ n ≀ 500) denoting the number of houses in the city. The next line contains n space-separated integers k_1, k_2, ..., k_n (0 ≀ k_i ≀ n - 1), the i-th of them represents the number of incoming roads to the i-th house. Interaction To ask a query, print "? A B" (1 ≀ A,B ≀ N, Aβ‰  B). The judge will respond "Yes" if house B is reachable from house A, or "No" otherwise. To output the final answer, print "! A B", where A and B are bi-reachable with the maximum possible value of |k_A - k_B|. If there does not exist such pair of houses A and B, output "! 0 0". After outputting the final answer, your program must terminate immediately, otherwise you will receive Wrong Answer verdict. You cannot ask the same query twice. There is no upper limit to the number of queries you ask, but, you cannot ask more queries after the judge answers "Yes" to any of your queries. Your program must now output the final answer ("! A B" or "! 0 0") and terminate. If you ask a query in incorrect format or repeat a previous query, you will get Wrong Answer verdict. After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get the Idleness limit exceeded error. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. Examples Input 3 1 1 1 Yes Output ? 1 2 ! 1 2 Input 4 1 2 0 3 No No No No No No Output ? 2 1 ? 1 3 ? 4 1 ? 2 3 ? 4 2 ? 4 3 ! 0 0 Note In the first sample input, we are given a city of three houses with one incoming road each. The user program asks one query: "? 1 2": asking whether we can reach from house 1 to house 2. The judge responds with "Yes". The user program now concludes that this is sufficient information to determine the correct answer. So, it outputs "! 1 2" and quits. In the second sample input, the user program queries for six different pairs of houses, and finally answers "! 0 0" as it is convinced that no two houses as desired in the question exist in this city. Tags: brute force, graphs, greedy, interactive, sortings Correct Solution: ``` n = int(input()) nums = list(map(int, input().split())) pairs = [] for i in range(len(nums)): for j in range(i+1, len(nums)): pairs.append((abs(nums[i]-nums[j]), (i+1, j+1))) pairs.sort(reverse=True) for _, (i, j) in pairs: if nums[i-1] > nums[j-1]: print(f"? {i} {j}", flush=True) else: print(f"? {j} {i}", flush=True) if input() == 'Yes': print(f"! {j} {i}", flush=True) exit(0) print("! 0 0", flush=True) ```
12,688
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: <https://codeforces.com/blog/entry/45307>. There is a city in which Dixit lives. In the city, there are n houses. There is exactly one directed road between every pair of houses. For example, consider two houses A and B, then there is a directed road either from A to B or from B to A but not both. The number of roads leading to the i-th house is k_i. Two houses A and B are bi-reachable if A is reachable from B and B is reachable from A. We say that house B is reachable from house A when there is a path from house A to house B. Dixit wants to buy two houses in the city, that is, one for living and one for studying. Of course, he would like to travel from one house to another. So, he wants to find a pair of bi-reachable houses A and B. Among all such pairs, he wants to choose one with the maximum value of |k_A - k_B|, where k_i is the number of roads leading to the house i. If more than one optimal pair exists, any of them is suitable. Since Dixit is busy preparing CodeCraft, can you help him find the desired pair of houses, or tell him that no such houses exist? In the problem input, you are not given the direction of each road. You are given β€” for each house β€” only the number of incoming roads to that house (k_i). You are allowed to ask only one type of query from the judge: give two houses A and B, and the judge answers whether B is reachable from A. There is no upper limit on the number of queries. But, you cannot ask more queries after the judge answers "Yes" to any of your queries. Also, you cannot ask the same query twice. Once you have exhausted all your queries (or the judge responds "Yes" to any of your queries), your program must output its guess for the two houses and quit. See the Interaction section below for more details. Input The first line contains a single integer n (3 ≀ n ≀ 500) denoting the number of houses in the city. The next line contains n space-separated integers k_1, k_2, ..., k_n (0 ≀ k_i ≀ n - 1), the i-th of them represents the number of incoming roads to the i-th house. Interaction To ask a query, print "? A B" (1 ≀ A,B ≀ N, Aβ‰  B). The judge will respond "Yes" if house B is reachable from house A, or "No" otherwise. To output the final answer, print "! A B", where A and B are bi-reachable with the maximum possible value of |k_A - k_B|. If there does not exist such pair of houses A and B, output "! 0 0". After outputting the final answer, your program must terminate immediately, otherwise you will receive Wrong Answer verdict. You cannot ask the same query twice. There is no upper limit to the number of queries you ask, but, you cannot ask more queries after the judge answers "Yes" to any of your queries. Your program must now output the final answer ("! A B" or "! 0 0") and terminate. If you ask a query in incorrect format or repeat a previous query, you will get Wrong Answer verdict. After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get the Idleness limit exceeded error. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. Examples Input 3 1 1 1 Yes Output ? 1 2 ! 1 2 Input 4 1 2 0 3 No No No No No No Output ? 2 1 ? 1 3 ? 4 1 ? 2 3 ? 4 2 ? 4 3 ! 0 0 Note In the first sample input, we are given a city of three houses with one incoming road each. The user program asks one query: "? 1 2": asking whether we can reach from house 1 to house 2. The judge responds with "Yes". The user program now concludes that this is sufficient information to determine the correct answer. So, it outputs "! 1 2" and quits. In the second sample input, the user program queries for six different pairs of houses, and finally answers "! 0 0" as it is convinced that no two houses as desired in the question exist in this city. Tags: brute force, graphs, greedy, interactive, sortings Correct Solution: ``` import time #start_time = time.time() #def TIME_(): print(time.time()-start_time) import os, sys from io import BytesIO, IOBase from types import GeneratorType from bisect import bisect_left, bisect_right from collections import defaultdict as dd, deque as dq, Counter as dc import math, string, heapq as h BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os 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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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: self.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 getInt(): return int(input()) def getStrs(): return input().split() def getInts(): return list(map(int,input().split())) def getStr(): return input() def listStr(): return list(input()) def getMat(n): return [getInts() for _ in range(n)] def getBin(): return list(map(int,list(input()))) def isInt(s): return '0' <= s[0] <= '9' def ceil_(a,b): return a//b + (a%b > 0) MOD = 10**9 + 7 """ """ def solve(): N = getInt() A = getInts() A = [[a,i] for i,a in enumerate(A)] A.sort(reverse=True) while A and A[-1][0] == 0: A.pop() for i in range(len(A)): A[i][0] -= 1 if len(A) <= 2: print("!",0,0,flush=True) return for j in range(len(A)): for k in range(len(A)-1,j,-1): print("?",A[j][1]+1,A[k][1]+1,flush=True) if input() == "Yes": print("!",A[j][1]+1,A[k][1]+1,flush=True) return print("!",0,0,flush=True) return #for _ in range(getInt()): #print(solve()) solve() exit(0) #TIME_() ```
12,689
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: <https://codeforces.com/blog/entry/45307>. There is a city in which Dixit lives. In the city, there are n houses. There is exactly one directed road between every pair of houses. For example, consider two houses A and B, then there is a directed road either from A to B or from B to A but not both. The number of roads leading to the i-th house is k_i. Two houses A and B are bi-reachable if A is reachable from B and B is reachable from A. We say that house B is reachable from house A when there is a path from house A to house B. Dixit wants to buy two houses in the city, that is, one for living and one for studying. Of course, he would like to travel from one house to another. So, he wants to find a pair of bi-reachable houses A and B. Among all such pairs, he wants to choose one with the maximum value of |k_A - k_B|, where k_i is the number of roads leading to the house i. If more than one optimal pair exists, any of them is suitable. Since Dixit is busy preparing CodeCraft, can you help him find the desired pair of houses, or tell him that no such houses exist? In the problem input, you are not given the direction of each road. You are given β€” for each house β€” only the number of incoming roads to that house (k_i). You are allowed to ask only one type of query from the judge: give two houses A and B, and the judge answers whether B is reachable from A. There is no upper limit on the number of queries. But, you cannot ask more queries after the judge answers "Yes" to any of your queries. Also, you cannot ask the same query twice. Once you have exhausted all your queries (or the judge responds "Yes" to any of your queries), your program must output its guess for the two houses and quit. See the Interaction section below for more details. Input The first line contains a single integer n (3 ≀ n ≀ 500) denoting the number of houses in the city. The next line contains n space-separated integers k_1, k_2, ..., k_n (0 ≀ k_i ≀ n - 1), the i-th of them represents the number of incoming roads to the i-th house. Interaction To ask a query, print "? A B" (1 ≀ A,B ≀ N, Aβ‰  B). The judge will respond "Yes" if house B is reachable from house A, or "No" otherwise. To output the final answer, print "! A B", where A and B are bi-reachable with the maximum possible value of |k_A - k_B|. If there does not exist such pair of houses A and B, output "! 0 0". After outputting the final answer, your program must terminate immediately, otherwise you will receive Wrong Answer verdict. You cannot ask the same query twice. There is no upper limit to the number of queries you ask, but, you cannot ask more queries after the judge answers "Yes" to any of your queries. Your program must now output the final answer ("! A B" or "! 0 0") and terminate. If you ask a query in incorrect format or repeat a previous query, you will get Wrong Answer verdict. After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get the Idleness limit exceeded error. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. Examples Input 3 1 1 1 Yes Output ? 1 2 ! 1 2 Input 4 1 2 0 3 No No No No No No Output ? 2 1 ? 1 3 ? 4 1 ? 2 3 ? 4 2 ? 4 3 ! 0 0 Note In the first sample input, we are given a city of three houses with one incoming road each. The user program asks one query: "? 1 2": asking whether we can reach from house 1 to house 2. The judge responds with "Yes". The user program now concludes that this is sufficient information to determine the correct answer. So, it outputs "! 1 2" and quits. In the second sample input, the user program queries for six different pairs of houses, and finally answers "! 0 0" as it is convinced that no two houses as desired in the question exist in this city. Tags: brute force, graphs, greedy, interactive, sortings Correct Solution: ``` import time #start_time = time.time() #def TIME_(): print(time.time()-start_time) import os, sys from io import BytesIO, IOBase from types import GeneratorType from bisect import bisect_left, bisect_right from collections import defaultdict as dd, deque as dq, Counter as dc import math, string, heapq as h BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os 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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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: self.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 getInt(): return int(input()) def getStrs(): return input().split() def getInts(): return list(map(int,input().split())) def getStr(): return input() def listStr(): return list(input()) def getMat(n): return [getInts() for _ in range(n)] def getBin(): return list(map(int,list(input()))) def isInt(s): return '0' <= s[0] <= '9' def ceil_(a,b): return a//b + (a%b > 0) MOD = 10**9 + 7 """ """ def solve(): N = getInt() A = getInts() A = [[a,i] for i,a in enumerate(A)] A.sort(reverse=True) while A and A[-1][0] == 0: A.pop() for i in range(len(A)): A[i][0] -= 1 if len(A) <= 2: print("!",0,0,flush=True) return B = [] for i in range(len(A)): for j in range(i+1,len(A)): x = A[i][1] y = A[j][1] B.append((A[i][0]-A[j][0],x+1,y+1)) B.sort(reverse=True) for a,b,c in B: print("?",b,c,flush=True) if input() == "Yes": print("!",b,c,flush=True) return print("!",0,0,flush=True) return #for _ in range(getInt()): #print(solve()) solve() exit(0) #TIME_() ```
12,690
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: <https://codeforces.com/blog/entry/45307>. There is a city in which Dixit lives. In the city, there are n houses. There is exactly one directed road between every pair of houses. For example, consider two houses A and B, then there is a directed road either from A to B or from B to A but not both. The number of roads leading to the i-th house is k_i. Two houses A and B are bi-reachable if A is reachable from B and B is reachable from A. We say that house B is reachable from house A when there is a path from house A to house B. Dixit wants to buy two houses in the city, that is, one for living and one for studying. Of course, he would like to travel from one house to another. So, he wants to find a pair of bi-reachable houses A and B. Among all such pairs, he wants to choose one with the maximum value of |k_A - k_B|, where k_i is the number of roads leading to the house i. If more than one optimal pair exists, any of them is suitable. Since Dixit is busy preparing CodeCraft, can you help him find the desired pair of houses, or tell him that no such houses exist? In the problem input, you are not given the direction of each road. You are given β€” for each house β€” only the number of incoming roads to that house (k_i). You are allowed to ask only one type of query from the judge: give two houses A and B, and the judge answers whether B is reachable from A. There is no upper limit on the number of queries. But, you cannot ask more queries after the judge answers "Yes" to any of your queries. Also, you cannot ask the same query twice. Once you have exhausted all your queries (or the judge responds "Yes" to any of your queries), your program must output its guess for the two houses and quit. See the Interaction section below for more details. Input The first line contains a single integer n (3 ≀ n ≀ 500) denoting the number of houses in the city. The next line contains n space-separated integers k_1, k_2, ..., k_n (0 ≀ k_i ≀ n - 1), the i-th of them represents the number of incoming roads to the i-th house. Interaction To ask a query, print "? A B" (1 ≀ A,B ≀ N, Aβ‰  B). The judge will respond "Yes" if house B is reachable from house A, or "No" otherwise. To output the final answer, print "! A B", where A and B are bi-reachable with the maximum possible value of |k_A - k_B|. If there does not exist such pair of houses A and B, output "! 0 0". After outputting the final answer, your program must terminate immediately, otherwise you will receive Wrong Answer verdict. You cannot ask the same query twice. There is no upper limit to the number of queries you ask, but, you cannot ask more queries after the judge answers "Yes" to any of your queries. Your program must now output the final answer ("! A B" or "! 0 0") and terminate. If you ask a query in incorrect format or repeat a previous query, you will get Wrong Answer verdict. After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get the Idleness limit exceeded error. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. Examples Input 3 1 1 1 Yes Output ? 1 2 ! 1 2 Input 4 1 2 0 3 No No No No No No Output ? 2 1 ? 1 3 ? 4 1 ? 2 3 ? 4 2 ? 4 3 ! 0 0 Note In the first sample input, we are given a city of three houses with one incoming road each. The user program asks one query: "? 1 2": asking whether we can reach from house 1 to house 2. The judge responds with "Yes". The user program now concludes that this is sufficient information to determine the correct answer. So, it outputs "! 1 2" and quits. In the second sample input, the user program queries for six different pairs of houses, and finally answers "! 0 0" as it is convinced that no two houses as desired in the question exist in this city. Tags: brute force, graphs, greedy, interactive, sortings Correct Solution: ``` import os import sys from io import BytesIO, IOBase def main(): n=int(input()) k=list(map(int,input().split())) lens=[] for i in range(n+1): lens.append([]) for i in range(len(k)): lens[k[i]].append(i+1) for diff in range(n-2,-1,-1): for lower in range(1,n-diff): higher=lower+diff for a in lens[lower]: for b in lens[higher]: if a==b: continue print('?',b,a,flush=True) s=input() if s=='Yes': print('!',b,a,flush=True) exit() print('!',0,0,flush=True) exit() # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main() ```
12,691
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: <https://codeforces.com/blog/entry/45307>. There is a city in which Dixit lives. In the city, there are n houses. There is exactly one directed road between every pair of houses. For example, consider two houses A and B, then there is a directed road either from A to B or from B to A but not both. The number of roads leading to the i-th house is k_i. Two houses A and B are bi-reachable if A is reachable from B and B is reachable from A. We say that house B is reachable from house A when there is a path from house A to house B. Dixit wants to buy two houses in the city, that is, one for living and one for studying. Of course, he would like to travel from one house to another. So, he wants to find a pair of bi-reachable houses A and B. Among all such pairs, he wants to choose one with the maximum value of |k_A - k_B|, where k_i is the number of roads leading to the house i. If more than one optimal pair exists, any of them is suitable. Since Dixit is busy preparing CodeCraft, can you help him find the desired pair of houses, or tell him that no such houses exist? In the problem input, you are not given the direction of each road. You are given β€” for each house β€” only the number of incoming roads to that house (k_i). You are allowed to ask only one type of query from the judge: give two houses A and B, and the judge answers whether B is reachable from A. There is no upper limit on the number of queries. But, you cannot ask more queries after the judge answers "Yes" to any of your queries. Also, you cannot ask the same query twice. Once you have exhausted all your queries (or the judge responds "Yes" to any of your queries), your program must output its guess for the two houses and quit. See the Interaction section below for more details. Input The first line contains a single integer n (3 ≀ n ≀ 500) denoting the number of houses in the city. The next line contains n space-separated integers k_1, k_2, ..., k_n (0 ≀ k_i ≀ n - 1), the i-th of them represents the number of incoming roads to the i-th house. Interaction To ask a query, print "? A B" (1 ≀ A,B ≀ N, Aβ‰  B). The judge will respond "Yes" if house B is reachable from house A, or "No" otherwise. To output the final answer, print "! A B", where A and B are bi-reachable with the maximum possible value of |k_A - k_B|. If there does not exist such pair of houses A and B, output "! 0 0". After outputting the final answer, your program must terminate immediately, otherwise you will receive Wrong Answer verdict. You cannot ask the same query twice. There is no upper limit to the number of queries you ask, but, you cannot ask more queries after the judge answers "Yes" to any of your queries. Your program must now output the final answer ("! A B" or "! 0 0") and terminate. If you ask a query in incorrect format or repeat a previous query, you will get Wrong Answer verdict. After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get the Idleness limit exceeded error. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. Examples Input 3 1 1 1 Yes Output ? 1 2 ! 1 2 Input 4 1 2 0 3 No No No No No No Output ? 2 1 ? 1 3 ? 4 1 ? 2 3 ? 4 2 ? 4 3 ! 0 0 Note In the first sample input, we are given a city of three houses with one incoming road each. The user program asks one query: "? 1 2": asking whether we can reach from house 1 to house 2. The judge responds with "Yes". The user program now concludes that this is sufficient information to determine the correct answer. So, it outputs "! 1 2" and quits. In the second sample input, the user program queries for six different pairs of houses, and finally answers "! 0 0" as it is convinced that no two houses as desired in the question exist in this city. Tags: brute force, graphs, greedy, interactive, sortings Correct Solution: ``` from itertools import permutations, product n = int(input()) nums = list(map(int, input().split())) indexed = sorted(zip(nums, range(1, len(nums)+1))) groups = [] prev_value = -1 for value, index in indexed: if prev_value != value: groups.append([]) groups[-1].append((value, index)) prev_value = value max_groups = [] for i in range(len(groups)): for j in range(i, len(groups)): if i != j or len(groups[i]) >= 3: max_groups.append((abs(groups[i][0][0] - groups[j][0][0]), (i, j))) max_groups.sort(reverse=True) for _, (start, end) in max_groups: for v1, i1 in groups[start]: for v2, i2 in groups[end]: if i1 != i2: print(f"? {i2} {i1}", flush=True) ans = input() # if (i2, i1) in roads: if ans.lower().strip() == 'yes': print(f"! {i1} {i2}", flush=True) exit(0) print("! 0 0") ```
12,692
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: <https://codeforces.com/blog/entry/45307>. There is a city in which Dixit lives. In the city, there are n houses. There is exactly one directed road between every pair of houses. For example, consider two houses A and B, then there is a directed road either from A to B or from B to A but not both. The number of roads leading to the i-th house is k_i. Two houses A and B are bi-reachable if A is reachable from B and B is reachable from A. We say that house B is reachable from house A when there is a path from house A to house B. Dixit wants to buy two houses in the city, that is, one for living and one for studying. Of course, he would like to travel from one house to another. So, he wants to find a pair of bi-reachable houses A and B. Among all such pairs, he wants to choose one with the maximum value of |k_A - k_B|, where k_i is the number of roads leading to the house i. If more than one optimal pair exists, any of them is suitable. Since Dixit is busy preparing CodeCraft, can you help him find the desired pair of houses, or tell him that no such houses exist? In the problem input, you are not given the direction of each road. You are given β€” for each house β€” only the number of incoming roads to that house (k_i). You are allowed to ask only one type of query from the judge: give two houses A and B, and the judge answers whether B is reachable from A. There is no upper limit on the number of queries. But, you cannot ask more queries after the judge answers "Yes" to any of your queries. Also, you cannot ask the same query twice. Once you have exhausted all your queries (or the judge responds "Yes" to any of your queries), your program must output its guess for the two houses and quit. See the Interaction section below for more details. Input The first line contains a single integer n (3 ≀ n ≀ 500) denoting the number of houses in the city. The next line contains n space-separated integers k_1, k_2, ..., k_n (0 ≀ k_i ≀ n - 1), the i-th of them represents the number of incoming roads to the i-th house. Interaction To ask a query, print "? A B" (1 ≀ A,B ≀ N, Aβ‰  B). The judge will respond "Yes" if house B is reachable from house A, or "No" otherwise. To output the final answer, print "! A B", where A and B are bi-reachable with the maximum possible value of |k_A - k_B|. If there does not exist such pair of houses A and B, output "! 0 0". After outputting the final answer, your program must terminate immediately, otherwise you will receive Wrong Answer verdict. You cannot ask the same query twice. There is no upper limit to the number of queries you ask, but, you cannot ask more queries after the judge answers "Yes" to any of your queries. Your program must now output the final answer ("! A B" or "! 0 0") and terminate. If you ask a query in incorrect format or repeat a previous query, you will get Wrong Answer verdict. After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get the Idleness limit exceeded error. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. Examples Input 3 1 1 1 Yes Output ? 1 2 ! 1 2 Input 4 1 2 0 3 No No No No No No Output ? 2 1 ? 1 3 ? 4 1 ? 2 3 ? 4 2 ? 4 3 ! 0 0 Note In the first sample input, we are given a city of three houses with one incoming road each. The user program asks one query: "? 1 2": asking whether we can reach from house 1 to house 2. The judge responds with "Yes". The user program now concludes that this is sufficient information to determine the correct answer. So, it outputs "! 1 2" and quits. In the second sample input, the user program queries for six different pairs of houses, and finally answers "! 0 0" as it is convinced that no two houses as desired in the question exist in this city. Tags: brute force, graphs, greedy, interactive, sortings Correct Solution: ``` from itertools import permutations, product n = int(input()) nums = list(map(int, input().split())) # print(nums) indexed = sorted(zip(nums, range(1, len(nums)+1))) removed = 0 while len(indexed) > 0 and indexed[0][0] <= removed: indexed = indexed[1:] removed += 1 # while len(indexed) > 0 and indexed[-1][0] >= len(indexed): # indexed = indexed[:len(indexed)-2] # if len(indexed) <= 2: print("! 0 0", flush=True) exit(0) groups = [] # roads = { # (1, 5), (5, 6), (6, 1), (4, 2), # (2, 3), (3, 4), (1, 2), (1, 3), # (1, 4), (5, 4), (5, 3), (5, 2), # (6, 4), (6, 3), (6, 2), # } prev_value = -1 for value, index in indexed: if prev_value != value: groups.append([]) groups[-1].append((value, index)) prev_value = value # print(indexed) # print(groups) max_groups = [] for i in range(len(groups)): for j in range(i, len(groups)): if i != j or len(groups[i]) >= 3: max_groups.append((abs(groups[i][0][0] - groups[j][0][0]), (i, j))) max_groups.sort(reverse=True) # print(max_groups) for _, (start, end) in max_groups: for v1, i1 in groups[start]: for v2, i2 in groups[end]: if i1 != i2: print(f"? {i2} {i1}", flush=True) ans = input() # if (i2, i1) in roads: if ans.lower().strip() == 'yes': print(f"! {i1} {i2}", flush=True) exit(0) # exit(1) print("! 0 0") # print(f"! {groups[0][0][1]} {groups[-1][-1][1]}", flush=True) # filtered = [i for i in nums if i != n-1 and i != 0] # # # print(filtered) # print("? 1 2", flush=True) # ans = input() # else: # low = nums.index(min(filtered))+1 # # print(f"{low=}") # # print(nums[0:low-1]) # # print(nums[low:]) # try: # high = nums.index(max(filtered), 0, low-1)+1 # except ValueError: # high = nums.index(max(filtered), low)+1 # print(f"! {low} {high}", flush=True) ```
12,693
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: <https://codeforces.com/blog/entry/45307>. There is a city in which Dixit lives. In the city, there are n houses. There is exactly one directed road between every pair of houses. For example, consider two houses A and B, then there is a directed road either from A to B or from B to A but not both. The number of roads leading to the i-th house is k_i. Two houses A and B are bi-reachable if A is reachable from B and B is reachable from A. We say that house B is reachable from house A when there is a path from house A to house B. Dixit wants to buy two houses in the city, that is, one for living and one for studying. Of course, he would like to travel from one house to another. So, he wants to find a pair of bi-reachable houses A and B. Among all such pairs, he wants to choose one with the maximum value of |k_A - k_B|, where k_i is the number of roads leading to the house i. If more than one optimal pair exists, any of them is suitable. Since Dixit is busy preparing CodeCraft, can you help him find the desired pair of houses, or tell him that no such houses exist? In the problem input, you are not given the direction of each road. You are given β€” for each house β€” only the number of incoming roads to that house (k_i). You are allowed to ask only one type of query from the judge: give two houses A and B, and the judge answers whether B is reachable from A. There is no upper limit on the number of queries. But, you cannot ask more queries after the judge answers "Yes" to any of your queries. Also, you cannot ask the same query twice. Once you have exhausted all your queries (or the judge responds "Yes" to any of your queries), your program must output its guess for the two houses and quit. See the Interaction section below for more details. Input The first line contains a single integer n (3 ≀ n ≀ 500) denoting the number of houses in the city. The next line contains n space-separated integers k_1, k_2, ..., k_n (0 ≀ k_i ≀ n - 1), the i-th of them represents the number of incoming roads to the i-th house. Interaction To ask a query, print "? A B" (1 ≀ A,B ≀ N, Aβ‰  B). The judge will respond "Yes" if house B is reachable from house A, or "No" otherwise. To output the final answer, print "! A B", where A and B are bi-reachable with the maximum possible value of |k_A - k_B|. If there does not exist such pair of houses A and B, output "! 0 0". After outputting the final answer, your program must terminate immediately, otherwise you will receive Wrong Answer verdict. You cannot ask the same query twice. There is no upper limit to the number of queries you ask, but, you cannot ask more queries after the judge answers "Yes" to any of your queries. Your program must now output the final answer ("! A B" or "! 0 0") and terminate. If you ask a query in incorrect format or repeat a previous query, you will get Wrong Answer verdict. After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get the Idleness limit exceeded error. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. Examples Input 3 1 1 1 Yes Output ? 1 2 ! 1 2 Input 4 1 2 0 3 No No No No No No Output ? 2 1 ? 1 3 ? 4 1 ? 2 3 ? 4 2 ? 4 3 ! 0 0 Note In the first sample input, we are given a city of three houses with one incoming road each. The user program asks one query: "? 1 2": asking whether we can reach from house 1 to house 2. The judge responds with "Yes". The user program now concludes that this is sufficient information to determine the correct answer. So, it outputs "! 1 2" and quits. In the second sample input, the user program queries for six different pairs of houses, and finally answers "! 0 0" as it is convinced that no two houses as desired in the question exist in this city. Submitted Solution: ``` import sys N = int(input()) A = list(map(int,input().split())) adj=[set() for _ in range(N)] INF=float("inf") dist=[[INF]*N for _ in range(N)] for i in range(N): for j in range(i+1,N): print("? {} {}".format(i,j)) sys.stdout.flush() ret = input() if ret=="Yes": dist[i][j]=1 else: dist[j][i]=1 for k in range(N): for i in range(N): for j in range(N): dist[i][j] = min(dist[i][j],dist[i][k]+dist[k][j]) ans=0 ans_idx=None for i in range(N): for j in range(N): if i==j: continue if dist[i][j]<INF and dist[j][i]<INF: if ans<abs(A[i]-A[j]): ans=max(ans,abs(A[i]-A[j])) ans_idx=(i,j) print(ans_idx) ``` No
12,694
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: <https://codeforces.com/blog/entry/45307>. There is a city in which Dixit lives. In the city, there are n houses. There is exactly one directed road between every pair of houses. For example, consider two houses A and B, then there is a directed road either from A to B or from B to A but not both. The number of roads leading to the i-th house is k_i. Two houses A and B are bi-reachable if A is reachable from B and B is reachable from A. We say that house B is reachable from house A when there is a path from house A to house B. Dixit wants to buy two houses in the city, that is, one for living and one for studying. Of course, he would like to travel from one house to another. So, he wants to find a pair of bi-reachable houses A and B. Among all such pairs, he wants to choose one with the maximum value of |k_A - k_B|, where k_i is the number of roads leading to the house i. If more than one optimal pair exists, any of them is suitable. Since Dixit is busy preparing CodeCraft, can you help him find the desired pair of houses, or tell him that no such houses exist? In the problem input, you are not given the direction of each road. You are given β€” for each house β€” only the number of incoming roads to that house (k_i). You are allowed to ask only one type of query from the judge: give two houses A and B, and the judge answers whether B is reachable from A. There is no upper limit on the number of queries. But, you cannot ask more queries after the judge answers "Yes" to any of your queries. Also, you cannot ask the same query twice. Once you have exhausted all your queries (or the judge responds "Yes" to any of your queries), your program must output its guess for the two houses and quit. See the Interaction section below for more details. Input The first line contains a single integer n (3 ≀ n ≀ 500) denoting the number of houses in the city. The next line contains n space-separated integers k_1, k_2, ..., k_n (0 ≀ k_i ≀ n - 1), the i-th of them represents the number of incoming roads to the i-th house. Interaction To ask a query, print "? A B" (1 ≀ A,B ≀ N, Aβ‰  B). The judge will respond "Yes" if house B is reachable from house A, or "No" otherwise. To output the final answer, print "! A B", where A and B are bi-reachable with the maximum possible value of |k_A - k_B|. If there does not exist such pair of houses A and B, output "! 0 0". After outputting the final answer, your program must terminate immediately, otherwise you will receive Wrong Answer verdict. You cannot ask the same query twice. There is no upper limit to the number of queries you ask, but, you cannot ask more queries after the judge answers "Yes" to any of your queries. Your program must now output the final answer ("! A B" or "! 0 0") and terminate. If you ask a query in incorrect format or repeat a previous query, you will get Wrong Answer verdict. After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get the Idleness limit exceeded error. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. Examples Input 3 1 1 1 Yes Output ? 1 2 ! 1 2 Input 4 1 2 0 3 No No No No No No Output ? 2 1 ? 1 3 ? 4 1 ? 2 3 ? 4 2 ? 4 3 ! 0 0 Note In the first sample input, we are given a city of three houses with one incoming road each. The user program asks one query: "? 1 2": asking whether we can reach from house 1 to house 2. The judge responds with "Yes". The user program now concludes that this is sufficient information to determine the correct answer. So, it outputs "! 1 2" and quits. In the second sample input, the user program queries for six different pairs of houses, and finally answers "! 0 0" as it is convinced that no two houses as desired in the question exist in this city. Submitted Solution: ``` import time #start_time = time.time() #def TIME_(): print(time.time()-start_time) import os, sys from io import BytesIO, IOBase from types import GeneratorType from bisect import bisect_left, bisect_right from collections import defaultdict as dd, deque as dq, Counter as dc import math, string, heapq as h BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os 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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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: self.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 getInt(): return int(input()) def getStrs(): return input().split() def getInts(): return list(map(int,input().split())) def getStr(): return input() def listStr(): return list(input()) def getMat(n): return [getInts() for _ in range(n)] def getBin(): return list(map(int,list(input()))) def isInt(s): return '0' <= s[0] <= '9' def ceil_(a,b): return a//b + (a%b > 0) MOD = 10**9 + 7 """ """ def solve(): N = getInt() A = getInts() A = [[a,i] for i,a in enumerate(A)] A.sort(reverse=True) while A and A[-1][0] == 0: A.pop() for i in range(len(A)): A[i][0] -= 1 if len(A) <= 2: print("!",0,0,flush=True) return for j in range(len(A)): for k in range(len(A)-1,j,-1): print("?",A[j][1]+1,A[k][1]+1,flush=True) if input() == "Yes": print("!",A[j][1]+1,A[k][1]+1,flush=True) return print("!",0,0,flush=True) return #for _ in range(getInt()): #print(solve()) solve() exit(0) #TIME_() ``` No
12,695
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: <https://codeforces.com/blog/entry/45307>. There is a city in which Dixit lives. In the city, there are n houses. There is exactly one directed road between every pair of houses. For example, consider two houses A and B, then there is a directed road either from A to B or from B to A but not both. The number of roads leading to the i-th house is k_i. Two houses A and B are bi-reachable if A is reachable from B and B is reachable from A. We say that house B is reachable from house A when there is a path from house A to house B. Dixit wants to buy two houses in the city, that is, one for living and one for studying. Of course, he would like to travel from one house to another. So, he wants to find a pair of bi-reachable houses A and B. Among all such pairs, he wants to choose one with the maximum value of |k_A - k_B|, where k_i is the number of roads leading to the house i. If more than one optimal pair exists, any of them is suitable. Since Dixit is busy preparing CodeCraft, can you help him find the desired pair of houses, or tell him that no such houses exist? In the problem input, you are not given the direction of each road. You are given β€” for each house β€” only the number of incoming roads to that house (k_i). You are allowed to ask only one type of query from the judge: give two houses A and B, and the judge answers whether B is reachable from A. There is no upper limit on the number of queries. But, you cannot ask more queries after the judge answers "Yes" to any of your queries. Also, you cannot ask the same query twice. Once you have exhausted all your queries (or the judge responds "Yes" to any of your queries), your program must output its guess for the two houses and quit. See the Interaction section below for more details. Input The first line contains a single integer n (3 ≀ n ≀ 500) denoting the number of houses in the city. The next line contains n space-separated integers k_1, k_2, ..., k_n (0 ≀ k_i ≀ n - 1), the i-th of them represents the number of incoming roads to the i-th house. Interaction To ask a query, print "? A B" (1 ≀ A,B ≀ N, Aβ‰  B). The judge will respond "Yes" if house B is reachable from house A, or "No" otherwise. To output the final answer, print "! A B", where A and B are bi-reachable with the maximum possible value of |k_A - k_B|. If there does not exist such pair of houses A and B, output "! 0 0". After outputting the final answer, your program must terminate immediately, otherwise you will receive Wrong Answer verdict. You cannot ask the same query twice. There is no upper limit to the number of queries you ask, but, you cannot ask more queries after the judge answers "Yes" to any of your queries. Your program must now output the final answer ("! A B" or "! 0 0") and terminate. If you ask a query in incorrect format or repeat a previous query, you will get Wrong Answer verdict. After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get the Idleness limit exceeded error. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. Examples Input 3 1 1 1 Yes Output ? 1 2 ! 1 2 Input 4 1 2 0 3 No No No No No No Output ? 2 1 ? 1 3 ? 4 1 ? 2 3 ? 4 2 ? 4 3 ! 0 0 Note In the first sample input, we are given a city of three houses with one incoming road each. The user program asks one query: "? 1 2": asking whether we can reach from house 1 to house 2. The judge responds with "Yes". The user program now concludes that this is sufficient information to determine the correct answer. So, it outputs "! 1 2" and quits. In the second sample input, the user program queries for six different pairs of houses, and finally answers "! 0 0" as it is convinced that no two houses as desired in the question exist in this city. Submitted Solution: ``` import sys n = int(input()) lst = list(map(int,input().split())) dct = {} for i in range(1,n+1): dct[i] = lst[i-1] sortdct = {k: v for k, v in sorted(dct.items(), key=lambda item: item[1],reverse= True)} keys = list(sortdct.keys()) for i in range(0,n-1): c = 0 for j in range(i+1,n): print("? {0} {1}".format(keys[i],keys[j])) if input() == "Yes": print("! {0} {1}".format(keys[i],keys[j])) c=1 sys.stdout.flush() sys.exit() ``` No
12,696
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: <https://codeforces.com/blog/entry/45307>. There is a city in which Dixit lives. In the city, there are n houses. There is exactly one directed road between every pair of houses. For example, consider two houses A and B, then there is a directed road either from A to B or from B to A but not both. The number of roads leading to the i-th house is k_i. Two houses A and B are bi-reachable if A is reachable from B and B is reachable from A. We say that house B is reachable from house A when there is a path from house A to house B. Dixit wants to buy two houses in the city, that is, one for living and one for studying. Of course, he would like to travel from one house to another. So, he wants to find a pair of bi-reachable houses A and B. Among all such pairs, he wants to choose one with the maximum value of |k_A - k_B|, where k_i is the number of roads leading to the house i. If more than one optimal pair exists, any of them is suitable. Since Dixit is busy preparing CodeCraft, can you help him find the desired pair of houses, or tell him that no such houses exist? In the problem input, you are not given the direction of each road. You are given β€” for each house β€” only the number of incoming roads to that house (k_i). You are allowed to ask only one type of query from the judge: give two houses A and B, and the judge answers whether B is reachable from A. There is no upper limit on the number of queries. But, you cannot ask more queries after the judge answers "Yes" to any of your queries. Also, you cannot ask the same query twice. Once you have exhausted all your queries (or the judge responds "Yes" to any of your queries), your program must output its guess for the two houses and quit. See the Interaction section below for more details. Input The first line contains a single integer n (3 ≀ n ≀ 500) denoting the number of houses in the city. The next line contains n space-separated integers k_1, k_2, ..., k_n (0 ≀ k_i ≀ n - 1), the i-th of them represents the number of incoming roads to the i-th house. Interaction To ask a query, print "? A B" (1 ≀ A,B ≀ N, Aβ‰  B). The judge will respond "Yes" if house B is reachable from house A, or "No" otherwise. To output the final answer, print "! A B", where A and B are bi-reachable with the maximum possible value of |k_A - k_B|. If there does not exist such pair of houses A and B, output "! 0 0". After outputting the final answer, your program must terminate immediately, otherwise you will receive Wrong Answer verdict. You cannot ask the same query twice. There is no upper limit to the number of queries you ask, but, you cannot ask more queries after the judge answers "Yes" to any of your queries. Your program must now output the final answer ("! A B" or "! 0 0") and terminate. If you ask a query in incorrect format or repeat a previous query, you will get Wrong Answer verdict. After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get the Idleness limit exceeded error. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. Examples Input 3 1 1 1 Yes Output ? 1 2 ! 1 2 Input 4 1 2 0 3 No No No No No No Output ? 2 1 ? 1 3 ? 4 1 ? 2 3 ? 4 2 ? 4 3 ! 0 0 Note In the first sample input, we are given a city of three houses with one incoming road each. The user program asks one query: "? 1 2": asking whether we can reach from house 1 to house 2. The judge responds with "Yes". The user program now concludes that this is sufficient information to determine the correct answer. So, it outputs "! 1 2" and quits. In the second sample input, the user program queries for six different pairs of houses, and finally answers "! 0 0" as it is convinced that no two houses as desired in the question exist in this city. Submitted Solution: ``` from sys import stdin, stdout def write(s): stdout.write(s) stdout.flush() def question(a, b): write(f'? {a} {b}\n') def finish(a, b): write(f'! {a} {b}') def read_numbers(): return map(int, stdin.readline().split()) def read_answer(): return stdin.readline().startswith('Yes') def main(): n = int(stdin.readline()) a = [(v, i) for i, v in enumerate(read_numbers())] a.sort() pairs = [] for i in range(n): for j in range(i+1, n): pairs.append((i, j, a[j][0]-a[i][1])) pairs.sort(key=lambda x: x[2], reverse=True) for i, j, _ in pairs: question(a[j][1], a[i][1]) if read_answer(): finish(a[i][1], a[j][1]) break else: finish(0, 0) if __name__ == '__main__': main() ``` No
12,697
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a of n integers. Count the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Input The first line contains one integer t (1 ≀ t ≀ 10^4). Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5). The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” array a. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case output the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Example Input 4 6 3 5 1 4 6 6 3 1 2 3 4 1 3 3 4 6 1 6 3 4 5 6 Output 1 3 3 10 Tags: data structures, hashing, math Correct Solution: ``` for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) d = {} for i in range(n): x = a[i]-i if x in d: d[x] += 1 else: d[x] = 1 count = 0 for i in d: count += ((d[i]*(d[i]-1))//2) print(count) ```
12,698
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a of n integers. Count the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Input The first line contains one integer t (1 ≀ t ≀ 10^4). Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5). The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” array a. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case output the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Example Input 4 6 3 5 1 4 6 6 3 1 2 3 4 1 3 3 4 6 1 6 3 4 5 6 Output 1 3 3 10 Tags: data structures, hashing, math Correct Solution: ``` cases = int(input()) for _ in range(cases): n = int(input()) ints = [int(n) for n in input().split(" ")] counts = {} for i in range(n): if ints[i]-i not in counts.keys(): counts[ints[i]-i] = 0 counts[ints[i]-i] += 1 count = 0 for c in counts.values(): count += (c*(c-1))//2 print(count) ```
12,699