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. You are asked to watch your nephew who likes to play with toy blocks in a strange way. He has n boxes and the i-th box has a_i blocks. His game consists of two steps: 1. he chooses an arbitrary box i; 2. he tries to move all blocks from the i-th box to other boxes. If he can make the same number of blocks in each of n - 1 other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes. You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box i he chooses he won't be sad. What is the minimum number of extra blocks you need to put? Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains the integer n (2 ≀ n ≀ 10^5) β€” the number of boxes. The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≀ a_i ≀ 10^9) β€” the number of blocks in each box. It's guaranteed that the sum of n over test cases doesn't exceed 10^5. Output For each test case, print a single integer β€” the minimum number of blocks you need to put. It can be proved that the answer always exists, i. e. the number of blocks is finite. Example Input 3 3 3 2 2 4 2 2 3 2 3 0 3 0 Output 1 0 3 Note In the first test case, you can, for example, put one extra block into the first box and make a = [4, 2, 2]. If your nephew chooses the box with 4 blocks, then we will move two blocks to the second box and two blocks to the third box. If he chooses the box with 2 blocks then he will move these two blocks to the other box with 2 blocks. In the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal. In the third test case, you should put 3 extra blocks. For example, you can put 2 blocks in the first box and 1 block in the third box. You'll get array a = [2, 3, 1]. Submitted Solution: ``` for _ in range(int(input())): n= int(input()) li = input().split() li=[int(i) for i in li] li.sort() s=0 if li[0]==li[-1]: print(0) else: for i in range(0,len(li)-1): s+=li[i] if s-li[-1]==li[-1]: print(0) else: print(abs(s-li[-1])) ``` No
103,900
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are asked to watch your nephew who likes to play with toy blocks in a strange way. He has n boxes and the i-th box has a_i blocks. His game consists of two steps: 1. he chooses an arbitrary box i; 2. he tries to move all blocks from the i-th box to other boxes. If he can make the same number of blocks in each of n - 1 other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes. You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box i he chooses he won't be sad. What is the minimum number of extra blocks you need to put? Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains the integer n (2 ≀ n ≀ 10^5) β€” the number of boxes. The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≀ a_i ≀ 10^9) β€” the number of blocks in each box. It's guaranteed that the sum of n over test cases doesn't exceed 10^5. Output For each test case, print a single integer β€” the minimum number of blocks you need to put. It can be proved that the answer always exists, i. e. the number of blocks is finite. Example Input 3 3 3 2 2 4 2 2 3 2 3 0 3 0 Output 1 0 3 Note In the first test case, you can, for example, put one extra block into the first box and make a = [4, 2, 2]. If your nephew chooses the box with 4 blocks, then we will move two blocks to the second box and two blocks to the third box. If he chooses the box with 2 blocks then he will move these two blocks to the other box with 2 blocks. In the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal. In the third test case, you should put 3 extra blocks. For example, you can put 2 blocks in the first box and 1 block in the third box. You'll get array a = [2, 3, 1]. Submitted Solution: ``` T= int(input()) for _ in range(T): n = int(input()) a = list(map(int, input().split())) if sum(a) % (n - 1) == 0: print(0) else: print(max(max(a) * (n - 1) - sum(a), (n - 1 - sum(a) % (n - 1)))) ``` No
103,901
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are asked to watch your nephew who likes to play with toy blocks in a strange way. He has n boxes and the i-th box has a_i blocks. His game consists of two steps: 1. he chooses an arbitrary box i; 2. he tries to move all blocks from the i-th box to other boxes. If he can make the same number of blocks in each of n - 1 other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes. You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box i he chooses he won't be sad. What is the minimum number of extra blocks you need to put? Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains the integer n (2 ≀ n ≀ 10^5) β€” the number of boxes. The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≀ a_i ≀ 10^9) β€” the number of blocks in each box. It's guaranteed that the sum of n over test cases doesn't exceed 10^5. Output For each test case, print a single integer β€” the minimum number of blocks you need to put. It can be proved that the answer always exists, i. e. the number of blocks is finite. Example Input 3 3 3 2 2 4 2 2 3 2 3 0 3 0 Output 1 0 3 Note In the first test case, you can, for example, put one extra block into the first box and make a = [4, 2, 2]. If your nephew chooses the box with 4 blocks, then we will move two blocks to the second box and two blocks to the third box. If he chooses the box with 2 blocks then he will move these two blocks to the other box with 2 blocks. In the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal. In the third test case, you should put 3 extra blocks. For example, you can put 2 blocks in the first box and 1 block in the third box. You'll get array a = [2, 3, 1]. Submitted Solution: ``` t = int(input()) l = [] for i in range(t): a = int(input()) b = list(map(int, input().split())) min1_ = min(b) index = b.index(min1_) del b[index] min2_ = min(b) max_ = max(b) ost = (sum(b) + min1_) % (a - 1) if min2_ + ost + min1_ < max_: min2_ += ost + min1_ rasn = max_ - min2_ pl = (rasn + (a - 1) - 1) // (a - 1) l.append(ost + pl * (a - 1)) else: l.append(ost) for i in l: print(i) ``` No
103,902
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Tags: dp, math, number theory, sortings Correct Solution: ``` for _ in range(int(input())): length=int(input()) array=list(map(int,input().split())) array.sort() cnt=[0]*(max(array)+1) dp=[0]*(max(array)+1) for x in array: cnt[x]+=1 """ [3, 7, 9, 14, 63] """ for i in range(1,len(dp)): dp[i]+=cnt[i] for j in range(i,len(dp),i): dp[j]=max(dp[j],dp[i]) print(length-max(dp)) ```
103,903
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Tags: dp, math, number theory, sortings Correct Solution: ``` # Legends Always Come Up with Solution # Author: Manvir Singh import os from io import BytesIO, IOBase import sys from collections import defaultdict, deque, Counter from math import sqrt, pi, ceil, log, inf, gcd, floor from itertools import combinations, permutations from bisect import * from fractions import Fraction from heapq import * from random import randint def main(): for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) ma=max(a) b=Counter(a) c=sorted(set(a)) d=[0]*(ma+1) d[c[-1]] =b[c[-1]] ans = b[c[-1]] c.pop() c.reverse() for i in range(len(c)): j=2*c[i] zz=0 while j<=ma: zz=max(zz,d[j]) j+=c[i] d[c[i]]=b[c[i]]+zz ans=max(ans,d[c[i]]) print(n-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() ```
103,904
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Tags: dp, math, number theory, sortings Correct Solution: ``` import os,io input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from collections import deque for i in range(int(input())): n=int(input()) alist=list(map(int,input().split())) maxN=int(2e5+1) anslist=[0]*maxN blist=[0]*maxN for i,val in enumerate(alist):blist[val]+=1 for i in range(1,maxN): if blist[i]==0: continue anslist[i]+=blist[i] for j in range(2*i,maxN,i): anslist[j]=max(anslist[i],anslist[j]) print(n-max(anslist)) ```
103,905
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Tags: dp, math, number theory, sortings 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() 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 t = II() for q in range(t): n = II() a = LI() inf = max(a)+1 cnt = [0 for i in range(inf)] for i in a: cnt[i]+=1 dp = [0 for i in range(inf)] for i in range(1,inf): dp[i]+=cnt[i] for j in range(i*2,inf, i): dp[j] = max(dp[j], dp[i]) print(n-max(dp)) ```
103,906
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Tags: dp, math, number theory, sortings Correct Solution: ``` import sys import copy input=sys.stdin.readline for z in range(int(input())): n=int(input()) a=list(map(int,input().split())) cnt=[0]*(2*10**5+10) cnt2=[0]*(2*10**5+10) a.sort() num10=-1 cnt10=0 a2=[] for i in range(n): if num10!=a[i]: if cnt10!=0: a2.append(num10) cnt[num10]=cnt10 cnt10=1 num10=a[i] else: cnt10+=1 if cnt10!=0: a2.append(num10) cnt[num10]=cnt10 cnt2=copy.copy(cnt) a2.sort() for i in range(len(a2)): b=a2[i] num11=cnt2[b] for j in range(b*2,2*10**5+10,b): cnt2[j]=max(cnt2[j],num11+cnt[j]) ans=n+10 for i in range(len(a2)): ans=min(ans,n-cnt2[a2[i]]) print(ans) ```
103,907
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Tags: dp, math, number theory, sortings Correct Solution: ``` from sys import stdin from collections import Counter input = stdin.readline for test in range(int(input())): n = int(input()) lst = list(map(int, input().strip().split())) N = max(lst) + 1 po = [0] * N cnt = Counter(lst) for k in range(1, N): po[k] += cnt.get(k, 0) for i in range(2 * k, N, k): po[i] = max(po[i], po[k]) print(n - max(po)) ```
103,908
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Tags: dp, math, number theory, sortings Correct Solution: ``` from bisect import bisect_left for _ in range(int(input())): n = int(input()) l = list(map(int, input().split())) l.sort() m = max(l) z = [0] * (m+1) f = [0] * (m+1) for i in range(n): z[l[i]] += 1 for i in sorted(set(l)): b = i+i f[i] += z[i] while b <= m: f[b] = max(f[b], f[i]) b += i print(n-max(f)) ```
103,909
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Tags: dp, math, number theory, sortings Correct Solution: ``` from collections import Counter #fk this shit def f(arr): cnt=Counter(arr) mxn=max(arr)+100 factor=[0]*(mxn) for i in range(1,len(factor)): factor[i]+=cnt.get(i,0) for j in range(2*i,mxn,i): factor[j]=max(factor[i],factor[j]) return len(arr)-max(factor) for i in range(int(input())): s=input() lst=list(map(int,input().strip().split())) print(f(lst)) ```
103,910
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Submitted Solution: ``` from collections import Counter MX = 200001 def solve(arr): total = len(arr) cnt = [0] * MX for a in arr: cnt[a] += 1 u = sorted(set(arr)) loc = [-1] * MX for i,a in enumerate(u): loc[a] = i N = len(u) dp = [0] * N for i,a in enumerate(u): dp[i] = max(dp[i], cnt[a]) for b in range(2*a,MX,a): j = loc[b] if j >= 0: dp[j] = max(dp[j], dp[i] + cnt[b]) return total - max(dp) for _ in range(int(input())): input() arr = list(map(int,input().split())) print(solve(arr)) ``` Yes
103,911
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): def __init__(self, file): self.newlines = 0 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() # -------------------------------------------------------------------- def RL(): return map(int, sys.stdin.readline().split()) def RLL(): return list(map(int, sys.stdin.readline().split())) def N(): return int(input()) def S(): return input().strip() def print_list(l): print(' '.join(map(str, l))) # sys.setrecursionlimit(200000) # import random # from functools import reduce # from functools import lru_cache # from heapq import * # from collections import deque as dq # import math # import bisect as bs from collections import Counter # from collections import defaultdict as dc for t in range(N()): n = N() a = RLL() count = Counter(a) dp = [0] * 200001 for i in range(1, 200001): if count[i] == 0: continue dp[i] += count[i] for j in range(2 * i, 200001, i): dp[j] = max(dp[i], dp[j]) print(n - max(dp)) ``` Yes
103,912
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Submitted Solution: ``` import sys,math def main(): for _ in range(int(sys.stdin.readline().strip())): n=int(sys.stdin.readline().strip()) arr=list(map(int,sys.stdin.readline().strip().split())) table=[0]*(200001) dp=[0]*(200001) for i in range(n): table[arr[i]]+=1 for i in range(1,200001): dp[i]+=table[i] if dp[i]>0: for j in range(2*i,200001,i): dp[j]=max(dp[j],dp[i]) ans=n-max(dp) sys.stdout.write(str(ans)+'\n') main() ``` Yes
103,913
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Submitted Solution: ``` factorsMemo=[-1 for _ in range(200001)] def getAllFactors(x): #returns a sorted list of all the factors or divisors of x (including 1 and x) if factorsMemo[x]==-1: factors=[] for i in range(1,int(x**0.5)+1): if x%i==0: factors.append(i) if x//i!=i: factors.append(x//i) factorsMemo[x]=factors return factorsMemo[x] def main(): t=int(input()) allAns=[] for _ in range(t): n=int(input()) a=readIntArr() a.sort() dp=[-inf for _ in range(200001)] #dp[previous number]max number of elements before and including it to be beautiful} maxSizeOfBeautifulArray=0 for x in a: maxPrevCnts=0 for f in getAllFactors(x): maxPrevCnts=max(maxPrevCnts,dp[f]) dp[x]=1+maxPrevCnts maxSizeOfBeautifulArray=max(maxSizeOfBeautifulArray,dp[x]) allAns.append(n-maxSizeOfBeautifulArray) 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()] inf=float('inf') MOD=10**9+7 main() ``` Yes
103,914
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Submitted Solution: ``` import sys,math # FASTEST IO from io import BytesIO, IOBase 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) # End of FASTEST IO def main(): for _ in range(int(sys.stdin.readline().strip())): n=int(sys.stdin.readline().strip()) arr=list(map(int,sys.stdin.readline().strip().split())) table=[0]*(200001) dp=[0]*(200001) for i in range(n): table[arr[i]]+=1 for i in range(1,200001): for j in range(2*i,200001,i): dp[j]=max(dp[j],table[i]+dp[i]) ans=n-max(dp) sys.stdout.write(str(ans)+'\n') main() ``` No
103,915
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Submitted Solution: ``` import heapq __all__ = ['MappedQueue'] class MappedQueue(object): """The MappedQueue class implements an efficient minimum heap. The smallest element can be popped in O(1) time, new elements can be pushed in O(log n) time, and any element can be removed or updated in O(log n) time. The queue cannot contain duplicate elements and an attempt to push an element already in the queue will have no effect. MappedQueue complements the heapq package from the python standard library. While MappedQueue is designed for maximum compatibility with heapq, it has slightly different functionality. Examples -------- A `MappedQueue` can be created empty or optionally given an array of initial elements. Calling `push()` will add an element and calling `pop()` will remove and return the smallest element. >>> q = MappedQueue([916, 50, 4609, 493, 237]) >>> q.push(1310) True >>> x = [q.pop() for i in range(len(q.h))] >>> x [50, 237, 493, 916, 1310, 4609] Elements can also be updated or removed from anywhere in the queue. >>> q = MappedQueue([916, 50, 4609, 493, 237]) >>> q.remove(493) >>> q.update(237, 1117) >>> x = [q.pop() for i in range(len(q.h))] >>> x [50, 916, 1117, 4609] References ---------- .. [1] Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C. (2001). Introduction to algorithms second edition. .. [2] Knuth, D. E. (1997). The art of computer programming (Vol. 3). Pearson Education. """ def __init__(self, data=[]): """Priority queue class with updatable priorities. """ self.h = list(data) self.d = dict() self._heapify() def __len__(self): return len(self.h) def _heapify(self): """Restore heap invariant and recalculate map.""" heapq.heapify(self.h) self.d = dict([(elt, pos) for pos, elt in enumerate(self.h)]) if len(self.h) != len(self.d): raise AssertionError("Heap contains duplicate elements") def push(self, elt): """Add an element to the queue.""" # If element is already in queue, do nothing if elt in self.d: return False # Add element to heap and dict pos = len(self.h) self.h.append(elt) self.d[elt] = pos # Restore invariant by sifting down self._siftdown(pos) return True def pop(self): """Remove and return the smallest element in the queue.""" # Remove smallest element elt = self.h[0] del self.d[elt] # If elt is last item, remove and return if len(self.h) == 1: self.h.pop() return elt # Replace root with last element last = self.h.pop() self.h[0] = last self.d[last] = 0 # Restore invariant by sifting up, then down pos = self._siftup(0) self._siftdown(pos) # Return smallest element return elt def update(self, elt, new): """Replace an element in the queue with a new one.""" # Replace pos = self.d[elt] self.h[pos] = new del self.d[elt] self.d[new] = pos # Restore invariant by sifting up, then down pos = self._siftup(pos) self._siftdown(pos) def remove(self, elt): """Remove an element from the queue.""" # Find and remove element try: pos = self.d[elt] del self.d[elt] except KeyError: # Not in queue raise # If elt is last item, remove and return if pos == len(self.h) - 1: self.h.pop() return # Replace elt with last element last = self.h.pop() self.h[pos] = last self.d[last] = pos # Restore invariant by sifting up, then down pos = self._siftup(pos) self._siftdown(pos) def _siftup(self, pos): """Move element at pos down to a leaf by repeatedly moving the smaller child up.""" h, d = self.h, self.d elt = h[pos] # Continue until element is in a leaf end_pos = len(h) left_pos = (pos << 1) + 1 while left_pos < end_pos: # Left child is guaranteed to exist by loop predicate left = h[left_pos] try: right_pos = left_pos + 1 right = h[right_pos] # Out-of-place, swap with left unless right is smaller if right < left: h[pos], h[right_pos] = right, elt pos, right_pos = right_pos, pos d[elt], d[right] = pos, right_pos else: h[pos], h[left_pos] = left, elt pos, left_pos = left_pos, pos d[elt], d[left] = pos, left_pos except IndexError: # Left leaf is the end of the heap, swap h[pos], h[left_pos] = left, elt pos, left_pos = left_pos, pos d[elt], d[left] = pos, left_pos # Update left_pos left_pos = (pos << 1) + 1 return pos def _siftdown(self, pos): """Restore invariant by repeatedly replacing out-of-place element with its parent.""" h, d = self.h, self.d elt = h[pos] # Continue until element is at root while pos > 0: parent_pos = (pos - 1) >> 1 parent = h[parent_pos] if parent > elt: # Swap out-of-place element with parent h[parent_pos], h[pos] = elt, parent parent_pos, pos = pos, parent_pos d[elt] = pos d[parent] = parent_pos else: # Invariant is satisfied break return pos ########################################################## ########################################################## ########################################################## from collections import Counter # from sortedcontainers import SortedList t = int(input()) DEBUG = False for asdasd in range(t): # with open('temp.txt', 'w') as file: # for i in range(1, 200001): # file.write(str(i) + ' ') # break n = int(input()) arr = [int(i) for i in input().split(" ")] # if n==200000: # DEBUG = True # if DEBUG and asdasd == 3: # arr.insert(0,n) # line = str(arr) # n = 400 # x = [line[i:i+n] for i in range(0, len(line), n)] # for asd in x: # print(asd) arr.sort(reverse = True) # print(arr) count = dict(Counter(arr)) edges = {} ########################################## # DOESNT REALLY WORK ########################################## # heads = set() # for x in count: # edges[x] = set() # heads_to_remove = set() # for head in heads: # if head % x == 0: # edges[x].update(edges[head]) # edges[x].add(head) # heads_to_remove.add(head) # heads -= heads_to_remove # heads.add(x) # # print(edges) # edges_copy = edges.copy() # for x, edge_set in edges.items(): # for e in edge_set: # edges_copy[e].add(x) # edges = edges_copy ############################################ print('x1') ########################################## # TRYING N^2 EDGEs ########################################## for x in count: edges[x] = set() count_list = list(count.items()) for i in range(len(count_list)): if i % 10 == 0: print(i/len(count_list)) for j in range(i+1, len(count_list)): if count_list[i][0] % count_list[j][0] == 0 or count_list[j][0] % count_list[i][0] == 0: edges[count_list[i][0]].add(count_list[j][0]) edges[count_list[j][0]].add(count_list[i][0]) ############################################ print('x2') edge_count = {} total_edges = 0 for x, edge_set in edges.items(): edge_count[x] = count[x]-1 for e in edge_set: edge_count[x] += count[e] total_edges += count[x] * edge_count[x] total_edges //= 2 NODE_VALUE = 1 N_EDGES = 0 # queue = SortedList(list(edge_count.items()), key=lambda x: -x[N_EDGES]) # for key, value in edge_count.items(): # edge_count[key] = value * count[key] queue = MappedQueue([(n_edges, node_value) for node_value, n_edges in edge_count.items()]) # print('edges:', edges) # print('edge_count:', edge_count) # print('total_edges', total_edges) # print() # print('queue:', queue) # print() remaining_nodes = n # print('total_edges:', total_edges, 'remaining_nodes:', remaining_nodes) # print() # print(count) while total_edges != remaining_nodes*(remaining_nodes-1)//2: small = queue.pop() # remaining_nodes -= count[small[NODE_VALUE]] remaining_nodes -= 1 # print('popping node:', small[NODE_VALUE], 'edges:', small[N_EDGES]) # print(queue) for e in edges[small[NODE_VALUE]]: # print('updating edge', e) # queue.remove((e, edge_count[e])) queue.remove((edge_count[e], e)) # print('rem2', count[e] * count[small[NODE_VALUE]]) # edge_count[e] -= count[e] * count[small[NODE_VALUE]] # total_edges -= count[e] * count[small[NODE_VALUE]] # print('decreasing edge', e, ' edges by', 1) edge_count[e] -= 1 # print('decreasing total edges by', count[e]) total_edges -= count[e] if count[small[NODE_VALUE]] == 1: edges[e].remove(small[NODE_VALUE]) # queue.add((e, edge_count[e])) queue.push((edge_count[e], e)) # Edges between nodes of same value t = count[small[NODE_VALUE]] # print('rem1', t*(t-1)//2) t2 = t-1 total_edges -= t2 # print(t, '(*) decreasing total edges by', t2) count[small[NODE_VALUE]] -= 1 if count[small[NODE_VALUE]] != 0: queue.push((small[N_EDGES]-1, small[NODE_VALUE])) # print(queue) # print('total_edges:', total_edges, 'remaining_nodes:', remaining_nodes) # print() print(n - remaining_nodes) ``` No
103,916
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase def main(): pass # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") from collections import defaultdict,Counter m=2*10**5+5 t=int(input()) for _ in range(t): n=int(input()) a=list(map(int,input().split())) c=Counter(a) greater_count=defaultdict(lambda: 0) #Stores number of numbers a given number(not necessarily in a) is greater than or equal to the numbers in a. greater_count[0]=c[0] for i in range(1,m+1): greater_count[i]=greater_count[i-1]+c[i] dp=[float('inf') for i in range(m+1)] for i in range(m,0,-1): dp[i]=n-greater_count[i-1] #number of numbers in a, strictly greater than i (this is worst case answer for the sublist consisting of all numbers in a >=i) for j in range(2*i,m,i): dp[i]=min(dp[i],dp[j]+greater_count[j-1]-greater_count[i]) #number of numbers in a, between (i,j) print(dp[1]) ``` No
103,917
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Submitted Solution: ``` # Legends Always Come Up with Solution # Author: Manvir Singh import os from io import BytesIO, IOBase import sys from collections import defaultdict, deque, Counter from math import sqrt, pi, ceil, log, inf, gcd, floor from itertools import combinations, permutations from bisect import * from fractions import Fraction from heapq import * from random import randint def main(): for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) ma=max(a) b=[0]*(ma+1) for i in a: b[i]+=1 c=[] for i in range(1,ma+1): if b[i]: c.append(i) d = [0] * (ma + 1) d[c[-1]] =b[c[-1]] c.pop() c.reverse() ans=1 for i in range(len(c)): j=2*c[i] zz=0 while j<=ma: zz=max(zz,d[j]) j+=c[i] d[c[i]]=b[c[i]]+zz ans=max(ans,d[c[i]]) print(n-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() ``` No
103,918
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vanya invented an interesting trick with a set of integers. Let an illusionist have a set of positive integers S. He names a positive integer x. Then an audience volunteer must choose some subset (possibly, empty) of S without disclosing it to the illusionist. The volunteer tells the illusionist the size of the chosen subset. And here comes the trick: the illusionist guesses whether the sum of the subset elements does not exceed x. The sum of elements of an empty subset is considered to be 0. Vanya wants to prepare the trick for a public performance. He prepared some set of distinct positive integers S. Vasya wants the trick to be successful. He calls a positive number x unsuitable, if he can't be sure that the trick would be successful for every subset a viewer can choose. Vanya wants to count the number of unsuitable integers for the chosen set S. Vanya plans to try different sets S. He wants you to write a program that finds the number of unsuitable integers for the initial set S, and after each change to the set S. Vanya will make q changes to the set, and each change is one of the following two types: * add a new integer a to the set S, or * remove some integer a from the set S. Input The first line contains two integers n, q (1 ≀ n, q ≀ 200 000) β€” the size of the initial set S and the number of changes. The next line contains n distinct integers s_1, s_2, …, s_n (1 ≀ s_i ≀ 10^{13}) β€” the initial elements of S. Each of the following q lines contain two integers t_i, a_i (1 ≀ t_i ≀ 2, 1 ≀ a_i ≀ 10^{13}), describing a change: * If t_i = 1, then an integer a_i is added to the set S. It is guaranteed that this integer is not present in S before this operation. * If t_i = 2, then an integer a_i is removed from the set S. In is guaranteed that this integer is present in S before this operation. Output Print q + 1 lines. In the first line print the number of unsuitable integers for the initial set S. In the next q lines print the number of unsuitable integers for S after each change. Example Input 3 11 1 2 3 2 1 1 5 1 6 1 7 2 6 2 2 2 3 1 10 2 5 2 7 2 10 Output 4 1 6 12 19 13 8 2 10 3 0 0 Note In the first example the initial set is S = \{1, 2, 3\}. For this set the trick can be unsuccessful for x ∈ \{1, 2, 3, 4\}. For example, if x = 4, the volunteer can choose the subset \{1, 2\} with sum 3 ≀ x, and can choose the subset \{2, 3\} with sum 5 > x. However, in both cases the illusionist only know the same size of the subset (2), so he can't be sure answering making a guess. Since there is only one subset of size 3, and the sum of each subset of smaller size does not exceed 5, all x β‰₯ 5 are suitable. Submitted Solution: ``` def CountError(arr): set1 = set() for i in range(1,len(arr)+1): min=0 max=0 for j in range(i): min=min+arr[j] max=max+arr[len(arr)-j-1] for j in range(min+1, max+1): set1.add(j) count = len(set1) del set1 return count def change(arr,t, x): if t==1: arr.append(x) else: arr.remove(x) return arr n,q=map(int,input().split()) del n arr = list(map(int,input().split())) print(len(arr)) arr = sorted(arr) print(CountError(arr)) for i in range(q): t,x = map(int,input().split()) arr=change(arr,t,x) print(CountError(arr)) ``` No
103,919
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vanya invented an interesting trick with a set of integers. Let an illusionist have a set of positive integers S. He names a positive integer x. Then an audience volunteer must choose some subset (possibly, empty) of S without disclosing it to the illusionist. The volunteer tells the illusionist the size of the chosen subset. And here comes the trick: the illusionist guesses whether the sum of the subset elements does not exceed x. The sum of elements of an empty subset is considered to be 0. Vanya wants to prepare the trick for a public performance. He prepared some set of distinct positive integers S. Vasya wants the trick to be successful. He calls a positive number x unsuitable, if he can't be sure that the trick would be successful for every subset a viewer can choose. Vanya wants to count the number of unsuitable integers for the chosen set S. Vanya plans to try different sets S. He wants you to write a program that finds the number of unsuitable integers for the initial set S, and after each change to the set S. Vanya will make q changes to the set, and each change is one of the following two types: * add a new integer a to the set S, or * remove some integer a from the set S. Input The first line contains two integers n, q (1 ≀ n, q ≀ 200 000) β€” the size of the initial set S and the number of changes. The next line contains n distinct integers s_1, s_2, …, s_n (1 ≀ s_i ≀ 10^{13}) β€” the initial elements of S. Each of the following q lines contain two integers t_i, a_i (1 ≀ t_i ≀ 2, 1 ≀ a_i ≀ 10^{13}), describing a change: * If t_i = 1, then an integer a_i is added to the set S. It is guaranteed that this integer is not present in S before this operation. * If t_i = 2, then an integer a_i is removed from the set S. In is guaranteed that this integer is present in S before this operation. Output Print q + 1 lines. In the first line print the number of unsuitable integers for the initial set S. In the next q lines print the number of unsuitable integers for S after each change. Example Input 3 11 1 2 3 2 1 1 5 1 6 1 7 2 6 2 2 2 3 1 10 2 5 2 7 2 10 Output 4 1 6 12 19 13 8 2 10 3 0 0 Note In the first example the initial set is S = \{1, 2, 3\}. For this set the trick can be unsuccessful for x ∈ \{1, 2, 3, 4\}. For example, if x = 4, the volunteer can choose the subset \{1, 2\} with sum 3 ≀ x, and can choose the subset \{2, 3\} with sum 5 > x. However, in both cases the illusionist only know the same size of the subset (2), so he can't be sure answering making a guess. Since there is only one subset of size 3, and the sum of each subset of smaller size does not exceed 5, all x β‰₯ 5 are suitable. Submitted Solution: ``` import bisect def solve(s): if s==[]: return 0 i=0 j=len(s)-1 left=right=0 x=s[0] y=0 while j>0: left+=s[i] right+=s[j] #print(left,right) if left<=x: if right>x: x=right else: y=left-x x=right i+=1 j-=1 return x-s[0]-y inp=input() inp=inp.split(' ') inp=[int(i) for i in inp] n=inp[0] q=inp[1] inp=input() inp=inp.split(' ') s=[int(i) for i in inp] s=sorted(s) print(solve(s)) for k in range(q): inp=input() inp=inp.split(' ') inp=[int(i) for i in inp] a=inp[0] b=inp[1] if a==1: bisect.insort(s,b) else: s.remove(b) print(solve(s)) ``` No
103,920
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vanya invented an interesting trick with a set of integers. Let an illusionist have a set of positive integers S. He names a positive integer x. Then an audience volunteer must choose some subset (possibly, empty) of S without disclosing it to the illusionist. The volunteer tells the illusionist the size of the chosen subset. And here comes the trick: the illusionist guesses whether the sum of the subset elements does not exceed x. The sum of elements of an empty subset is considered to be 0. Vanya wants to prepare the trick for a public performance. He prepared some set of distinct positive integers S. Vasya wants the trick to be successful. He calls a positive number x unsuitable, if he can't be sure that the trick would be successful for every subset a viewer can choose. Vanya wants to count the number of unsuitable integers for the chosen set S. Vanya plans to try different sets S. He wants you to write a program that finds the number of unsuitable integers for the initial set S, and after each change to the set S. Vanya will make q changes to the set, and each change is one of the following two types: * add a new integer a to the set S, or * remove some integer a from the set S. Input The first line contains two integers n, q (1 ≀ n, q ≀ 200 000) β€” the size of the initial set S and the number of changes. The next line contains n distinct integers s_1, s_2, …, s_n (1 ≀ s_i ≀ 10^{13}) β€” the initial elements of S. Each of the following q lines contain two integers t_i, a_i (1 ≀ t_i ≀ 2, 1 ≀ a_i ≀ 10^{13}), describing a change: * If t_i = 1, then an integer a_i is added to the set S. It is guaranteed that this integer is not present in S before this operation. * If t_i = 2, then an integer a_i is removed from the set S. In is guaranteed that this integer is present in S before this operation. Output Print q + 1 lines. In the first line print the number of unsuitable integers for the initial set S. In the next q lines print the number of unsuitable integers for S after each change. Example Input 3 11 1 2 3 2 1 1 5 1 6 1 7 2 6 2 2 2 3 1 10 2 5 2 7 2 10 Output 4 1 6 12 19 13 8 2 10 3 0 0 Note In the first example the initial set is S = \{1, 2, 3\}. For this set the trick can be unsuccessful for x ∈ \{1, 2, 3, 4\}. For example, if x = 4, the volunteer can choose the subset \{1, 2\} with sum 3 ≀ x, and can choose the subset \{2, 3\} with sum 5 > x. However, in both cases the illusionist only know the same size of the subset (2), so he can't be sure answering making a guess. Since there is only one subset of size 3, and the sum of each subset of smaller size does not exceed 5, all x β‰₯ 5 are suitable. Submitted Solution: ``` s=input().split(" ") n=int(s[0]) q=int(s[1]) l=input().split(" ") for i in range(n): l[i]=int(l[i]) l=sorted(l) ma=0 mi=0 s=0 j=0 while j<len(l): mi1=mi+l[j] ma1=ma+l[len(l)-j-1] if mi1<ma: s+=ma1-ma-1 else: s+=ma1-mi1 ma=ma1 mi=mi1 j+=1 print(s) for i in range(q): s=input().split(" ") a=int(s[1]) if s[0]=="2": l.remove(a) else: l.append(a) j=len(l)-1 while j>0 and l[j]<l[j-1]: l[j],l[j-1]=l[j-1],l[j] j-=1 ma=0 mi=0 s=0 j=0 while j<len(l): mi1=mi+l[j] ma1=ma+l[len(l)-j-1] if mi1<ma: s+=ma1-ma else: s+=ma1-mi1 ma=ma1 mi=mi1 j+=1 print(s) ``` No
103,921
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vanya invented an interesting trick with a set of integers. Let an illusionist have a set of positive integers S. He names a positive integer x. Then an audience volunteer must choose some subset (possibly, empty) of S without disclosing it to the illusionist. The volunteer tells the illusionist the size of the chosen subset. And here comes the trick: the illusionist guesses whether the sum of the subset elements does not exceed x. The sum of elements of an empty subset is considered to be 0. Vanya wants to prepare the trick for a public performance. He prepared some set of distinct positive integers S. Vasya wants the trick to be successful. He calls a positive number x unsuitable, if he can't be sure that the trick would be successful for every subset a viewer can choose. Vanya wants to count the number of unsuitable integers for the chosen set S. Vanya plans to try different sets S. He wants you to write a program that finds the number of unsuitable integers for the initial set S, and after each change to the set S. Vanya will make q changes to the set, and each change is one of the following two types: * add a new integer a to the set S, or * remove some integer a from the set S. Input The first line contains two integers n, q (1 ≀ n, q ≀ 200 000) β€” the size of the initial set S and the number of changes. The next line contains n distinct integers s_1, s_2, …, s_n (1 ≀ s_i ≀ 10^{13}) β€” the initial elements of S. Each of the following q lines contain two integers t_i, a_i (1 ≀ t_i ≀ 2, 1 ≀ a_i ≀ 10^{13}), describing a change: * If t_i = 1, then an integer a_i is added to the set S. It is guaranteed that this integer is not present in S before this operation. * If t_i = 2, then an integer a_i is removed from the set S. In is guaranteed that this integer is present in S before this operation. Output Print q + 1 lines. In the first line print the number of unsuitable integers for the initial set S. In the next q lines print the number of unsuitable integers for S after each change. Example Input 3 11 1 2 3 2 1 1 5 1 6 1 7 2 6 2 2 2 3 1 10 2 5 2 7 2 10 Output 4 1 6 12 19 13 8 2 10 3 0 0 Note In the first example the initial set is S = \{1, 2, 3\}. For this set the trick can be unsuccessful for x ∈ \{1, 2, 3, 4\}. For example, if x = 4, the volunteer can choose the subset \{1, 2\} with sum 3 ≀ x, and can choose the subset \{2, 3\} with sum 5 > x. However, in both cases the illusionist only know the same size of the subset (2), so he can't be sure answering making a guess. Since there is only one subset of size 3, and the sum of each subset of smaller size does not exceed 5, all x β‰₯ 5 are suitable. Submitted Solution: ``` def CountError(arr): set1 = set() min = 0 max = 0 for i in range(1,len(arr)+1): for j in range(i): min=min+arr[j] max=max+arr[len(arr)-j-1] for j in range(min+1, max+1): set1.add(j) count = len(set1) del set1 return count def change(arr,t, x): if t==1: arr.append(x) else: arr.remove(x) return arr n,q=map(int,input().split()) del n arr = list(map(int,input().split())) arr = sorted(arr) print(CountError(arr)) for i in range(q): t,x = map(int,input().split()) arr=change(arr,t,x) print(CountError(arr)) ``` No
103,922
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a of 2n distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its 2 neighbours. More formally, find an array b, such that: * b is a permutation of a. * For every i from 1 to 2n, b_i β‰  \frac{b_{i-1}+b_{i+1}}{2}, where b_0 = b_{2n} and b_{2n+1} = b_1. It can be proved that under the constraints of this problem, such array b always exists. Input The first line of input contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. The description of testcases follows. The first line of each testcase contains a single integer n (1 ≀ n ≀ 25). The second line of each testcase contains 2n integers a_1, a_2, …, a_{2n} (1 ≀ a_i ≀ 10^9) β€” elements of the array. Note that there is no limit to the sum of n over all testcases. Output For each testcase, you should output 2n integers, b_1, b_2, … b_{2n}, for which the conditions from the statement are satisfied. Example Input 3 3 1 2 3 4 5 6 2 123 456 789 10 1 6 9 Output 3 1 4 2 5 6 123 10 456 789 9 6 Note In the first testcase, array [3, 1, 4, 2, 5, 6] works, as it's a permutation of [1, 2, 3, 4, 5, 6], and (3+4)/(2)β‰  1, (1+2)/(2)β‰  4, (4+5)/(2)β‰  2, (2+6)/(2)β‰  5, (5+3)/(2)β‰  6, (6+1)/(2)β‰  3. Tags: constructive algorithms, sortings Correct Solution: ``` for _ in range(int(input())): n = int(input()) l = sorted(list(map(int, input().split())), reverse=True) ans = [0]*(2*n) for i, j in enumerate(l): if i < n: ans[2*i+1] = j else: x = n - i ans[2*x] = j print(*ans) ```
103,923
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a of 2n distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its 2 neighbours. More formally, find an array b, such that: * b is a permutation of a. * For every i from 1 to 2n, b_i β‰  \frac{b_{i-1}+b_{i+1}}{2}, where b_0 = b_{2n} and b_{2n+1} = b_1. It can be proved that under the constraints of this problem, such array b always exists. Input The first line of input contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. The description of testcases follows. The first line of each testcase contains a single integer n (1 ≀ n ≀ 25). The second line of each testcase contains 2n integers a_1, a_2, …, a_{2n} (1 ≀ a_i ≀ 10^9) β€” elements of the array. Note that there is no limit to the sum of n over all testcases. Output For each testcase, you should output 2n integers, b_1, b_2, … b_{2n}, for which the conditions from the statement are satisfied. Example Input 3 3 1 2 3 4 5 6 2 123 456 789 10 1 6 9 Output 3 1 4 2 5 6 123 10 456 789 9 6 Note In the first testcase, array [3, 1, 4, 2, 5, 6] works, as it's a permutation of [1, 2, 3, 4, 5, 6], and (3+4)/(2)β‰  1, (1+2)/(2)β‰  4, (4+5)/(2)β‰  2, (2+6)/(2)β‰  5, (5+3)/(2)β‰  6, (6+1)/(2)β‰  3. Tags: constructive algorithms, sortings Correct Solution: ``` t=int(input()) for _ in range(t): n=int(input()) arr=list(map(int,input().split(' '))) arr.sort() l=[] i=0 j=2*n-1 while(i<j): l.append(arr[i]) l.append(arr[j]) i=i+1 j=j-1 for k in l: print(k,end=' ') ```
103,924
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a of 2n distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its 2 neighbours. More formally, find an array b, such that: * b is a permutation of a. * For every i from 1 to 2n, b_i β‰  \frac{b_{i-1}+b_{i+1}}{2}, where b_0 = b_{2n} and b_{2n+1} = b_1. It can be proved that under the constraints of this problem, such array b always exists. Input The first line of input contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. The description of testcases follows. The first line of each testcase contains a single integer n (1 ≀ n ≀ 25). The second line of each testcase contains 2n integers a_1, a_2, …, a_{2n} (1 ≀ a_i ≀ 10^9) β€” elements of the array. Note that there is no limit to the sum of n over all testcases. Output For each testcase, you should output 2n integers, b_1, b_2, … b_{2n}, for which the conditions from the statement are satisfied. Example Input 3 3 1 2 3 4 5 6 2 123 456 789 10 1 6 9 Output 3 1 4 2 5 6 123 10 456 789 9 6 Note In the first testcase, array [3, 1, 4, 2, 5, 6] works, as it's a permutation of [1, 2, 3, 4, 5, 6], and (3+4)/(2)β‰  1, (1+2)/(2)β‰  4, (4+5)/(2)β‰  2, (2+6)/(2)β‰  5, (5+3)/(2)β‰  6, (6+1)/(2)β‰  3. Tags: constructive algorithms, sortings Correct Solution: ``` # cook your dish here # from math import factorial, ceil, pow, sqrt, floor, gcd from sys import stdin, stdout #from collections import defaultdict, Counter, deque #from bisect import bisect_left, bisect_right # import sympy # from itertools import permutations # import numpy as np # n = int(stdin.readline()) # stdout.write(str()) # s = stdin.readline().strip('\n') # map(int, stdin.readline().split()) # l = list(map(int, stdin.readline().split())) #for _ in range(1): for _ in range(int(stdin.readline())): n = int(stdin.readline()) l = list(map(int, stdin.readline().split())) l.sort() shan = [] i = 0 j = 2*n-1 while i<j: shan.append(l[i]) shan.append(l[j]) i += 1 j -= 1 print(*shan) ```
103,925
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a of 2n distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its 2 neighbours. More formally, find an array b, such that: * b is a permutation of a. * For every i from 1 to 2n, b_i β‰  \frac{b_{i-1}+b_{i+1}}{2}, where b_0 = b_{2n} and b_{2n+1} = b_1. It can be proved that under the constraints of this problem, such array b always exists. Input The first line of input contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. The description of testcases follows. The first line of each testcase contains a single integer n (1 ≀ n ≀ 25). The second line of each testcase contains 2n integers a_1, a_2, …, a_{2n} (1 ≀ a_i ≀ 10^9) β€” elements of the array. Note that there is no limit to the sum of n over all testcases. Output For each testcase, you should output 2n integers, b_1, b_2, … b_{2n}, for which the conditions from the statement are satisfied. Example Input 3 3 1 2 3 4 5 6 2 123 456 789 10 1 6 9 Output 3 1 4 2 5 6 123 10 456 789 9 6 Note In the first testcase, array [3, 1, 4, 2, 5, 6] works, as it's a permutation of [1, 2, 3, 4, 5, 6], and (3+4)/(2)β‰  1, (1+2)/(2)β‰  4, (4+5)/(2)β‰  2, (2+6)/(2)β‰  5, (5+3)/(2)β‰  6, (6+1)/(2)β‰  3. Tags: constructive algorithms, sortings Correct Solution: ``` #Fast I/O import sys,os import math # To enable the file I/O i the below 2 lines are uncommented. # read from in.txt if uncommented if os.path.exists('in.txt'): sys.stdin=open('in.txt','r') # will print on Console if file I/O is not activated #if os.path.exists('out.txt'): sys.stdout=open('out.txt', 'w') # inputs template from io import BytesIO, IOBase def main(): for _ in range(int(input())): n=int(input()) arr=list(MI()) arr.sort() out=[arr[0]] for i in range(1,n): out.append(arr[2*i]) out.append(arr[2*i-1]) out.append(arr[-1]) print(*out) # Sample Inputs/Output # 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") #for array of integers def MI():return (map(int,input().split())) # endregion #for fast output, always take string def outP(var): sys.stdout.write(str(var)+'\n') # end of any user-defined functions MOD=10**9+7 mod=998244353 # main functions for execution of the program. if __name__ == '__main__': #This doesn't works here but works wonders when submitted on CodeChef or CodeForces main() ```
103,926
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a of 2n distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its 2 neighbours. More formally, find an array b, such that: * b is a permutation of a. * For every i from 1 to 2n, b_i β‰  \frac{b_{i-1}+b_{i+1}}{2}, where b_0 = b_{2n} and b_{2n+1} = b_1. It can be proved that under the constraints of this problem, such array b always exists. Input The first line of input contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. The description of testcases follows. The first line of each testcase contains a single integer n (1 ≀ n ≀ 25). The second line of each testcase contains 2n integers a_1, a_2, …, a_{2n} (1 ≀ a_i ≀ 10^9) β€” elements of the array. Note that there is no limit to the sum of n over all testcases. Output For each testcase, you should output 2n integers, b_1, b_2, … b_{2n}, for which the conditions from the statement are satisfied. Example Input 3 3 1 2 3 4 5 6 2 123 456 789 10 1 6 9 Output 3 1 4 2 5 6 123 10 456 789 9 6 Note In the first testcase, array [3, 1, 4, 2, 5, 6] works, as it's a permutation of [1, 2, 3, 4, 5, 6], and (3+4)/(2)β‰  1, (1+2)/(2)β‰  4, (4+5)/(2)β‰  2, (2+6)/(2)β‰  5, (5+3)/(2)β‰  6, (6+1)/(2)β‰  3. Tags: constructive algorithms, sortings Correct Solution: ``` from random import random def good(a,n): for i in range(1,2*n-1): if a[i-1] + a[i+1] == a[i]*2: return False if a[0]*2 == a[1] + a[-1]: return False if a[-1]*2 == a[-2] + a[0]: return False return True for nt in range(int(input())): n = int(input()) a = list(map(int,input().split())) while not good(a,n): a = sorted(a,key=lambda x:random()) print(*a) ```
103,927
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a of 2n distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its 2 neighbours. More formally, find an array b, such that: * b is a permutation of a. * For every i from 1 to 2n, b_i β‰  \frac{b_{i-1}+b_{i+1}}{2}, where b_0 = b_{2n} and b_{2n+1} = b_1. It can be proved that under the constraints of this problem, such array b always exists. Input The first line of input contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. The description of testcases follows. The first line of each testcase contains a single integer n (1 ≀ n ≀ 25). The second line of each testcase contains 2n integers a_1, a_2, …, a_{2n} (1 ≀ a_i ≀ 10^9) β€” elements of the array. Note that there is no limit to the sum of n over all testcases. Output For each testcase, you should output 2n integers, b_1, b_2, … b_{2n}, for which the conditions from the statement are satisfied. Example Input 3 3 1 2 3 4 5 6 2 123 456 789 10 1 6 9 Output 3 1 4 2 5 6 123 10 456 789 9 6 Note In the first testcase, array [3, 1, 4, 2, 5, 6] works, as it's a permutation of [1, 2, 3, 4, 5, 6], and (3+4)/(2)β‰  1, (1+2)/(2)β‰  4, (4+5)/(2)β‰  2, (2+6)/(2)β‰  5, (5+3)/(2)β‰  6, (6+1)/(2)β‰  3. Tags: constructive algorithms, sortings Correct Solution: ``` import sys input = sys.stdin.buffer.readline for _ in range(int(input())): n = int(input()) a = list(map(int,input().split())) a.sort() b = [0]*(2*n) for i in range(n): b[2*i] = a[i] for i in range(n): b[2*i+1] = a[2*n-1-i] print(*b) ```
103,928
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a of 2n distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its 2 neighbours. More formally, find an array b, such that: * b is a permutation of a. * For every i from 1 to 2n, b_i β‰  \frac{b_{i-1}+b_{i+1}}{2}, where b_0 = b_{2n} and b_{2n+1} = b_1. It can be proved that under the constraints of this problem, such array b always exists. Input The first line of input contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. The description of testcases follows. The first line of each testcase contains a single integer n (1 ≀ n ≀ 25). The second line of each testcase contains 2n integers a_1, a_2, …, a_{2n} (1 ≀ a_i ≀ 10^9) β€” elements of the array. Note that there is no limit to the sum of n over all testcases. Output For each testcase, you should output 2n integers, b_1, b_2, … b_{2n}, for which the conditions from the statement are satisfied. Example Input 3 3 1 2 3 4 5 6 2 123 456 789 10 1 6 9 Output 3 1 4 2 5 6 123 10 456 789 9 6 Note In the first testcase, array [3, 1, 4, 2, 5, 6] works, as it's a permutation of [1, 2, 3, 4, 5, 6], and (3+4)/(2)β‰  1, (1+2)/(2)β‰  4, (4+5)/(2)β‰  2, (2+6)/(2)β‰  5, (5+3)/(2)β‰  6, (6+1)/(2)β‰  3. Tags: constructive algorithms, sortings Correct Solution: ``` from itertools import combinations, permutations, combinations_with_replacement, product import itertools from timeit import timeit import timeit import time from time import time from random import * import random import collections import bisect import os import math from collections import defaultdict, OrderedDict, Counter from sys import stdin, stdout from bisect import bisect_left, bisect_right # import numpy as np from queue import Queue, PriorityQueue from heapq import * from statistics import * from math import sqrt, log10, log2, log, gcd, ceil, floor import fractions import copy from copy import deepcopy import sys import io import string from string import ascii_lowercase,ascii_uppercase,ascii_letters,digits sys.setrecursionlimit(10000) mod = int(pow(10, 9)) + 7 def ncr(n, r, p=mod): 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 normalncr(n, r): r = min(r, n - r) count = 1 for i in range(n - r, n + 1): count *= i for i in range(1, r + 1): count //= i return count inf = float("inf") adj = defaultdict(set) visited = defaultdict(int) def addedge(a, b): adj[a].add(b) adj[b].add(a) def bfs(v): q = Queue() q.put(v) visited[v] = 1 while q.qsize() > 0: s = q.get_nowait() print(s) for i in adj[s]: if visited[i] == 0: q.put(i) visited[i] = 1 def dfs(v, visited): if visited[v] == 1: return visited[v] = 1 print(v) for i in adj[v]: dfs(i, visited) # a9=pow(10,5)+100 # prime = [True for i in range(a9 + 1)] # def SieveOfEratosthenes(n): # p = 2 # while (p * p <= n): # if (prime[p] == True): # for i in range(p * p, n + 1, p): # prime[i] = False # p += 1 # SieveOfEratosthenes(a9) # prime_number=[] # for i in range(2,a9): # if prime[i]: # prime_number.append(i) def reverse_bisect_right(a, x, lo=0, hi=None): if lo < 0: raise ValueError('lo must be non-negative') if hi is None: hi = len(a) while lo < hi: mid = (lo + hi) // 2 if x > a[mid]: hi = mid else: lo = mid + 1 return lo def reverse_bisect_left(a, x, lo=0, hi=None): if lo < 0: raise ValueError('lo must be non-negative') if hi is None: hi = len(a) while lo < hi: mid = (lo + hi) // 2 if x >= a[mid]: hi = mid else: lo = mid + 1 return lo def get_list(): return list(map(int, input().split())) def make_list(m): m += list(map(int, input().split())) def get_str_list_in_int(): return [int(i) for i in list(input())] def get_str_list(): return list(input()) def get_map(): return map(int, input().split()) def input_int(): return int(input()) def matrix(a, b): return [[0 for i in range(b)] for j in range(a)] def swap(a, b): return b, a def find_gcd(l): a = l[0] for i in range(len(l)): a = gcd(a, l[i]) return a def is_prime(n): sqrta = int(sqrt(n)) for i in range(2, sqrta + 1): if n % i == 0: return 0 return 1 def prime_factors(n): l = [] while n % 2 == 0: l.append(2) n //= 2 sqrta = int(sqrt(n)) for i in range(3, sqrta + 1, 2): while n % i == 0: n //= i l.append(i) if n > 2: l.append(n) return l def p(a): if type(a) == str: print(a + "\n") else: print(str(a) + "\n") def ps(a): if type(a) == str: print(a) else: print(str(a)) def kth_no_not_div_by_n(n, k): return k + (k - 1) // (n - 1) def forward_array(l): """ returns the forward index where the elemetn is just greater than that element [100,200] gives [1,2] because element at index 1 is greater than 100 and nearest similarly if it is largest then it outputs n :param l: :return: """ n = len(l) stack = [] forward = [0] * n for i in range(len(l) - 1, -1, -1): while len(stack) and l[stack[-1]] < l[i]: stack.pop() if len(stack) == 0: forward[i] = len(l) else: forward[i] = stack[-1] stack.append(i) return forward def forward_array_notequal(l): n = len(l) stack = [] forward = [n]*n for i in range(len(l) - 1, -1, -1): while len(stack) and l[stack[-1]] <= l[i]: stack.pop() if len(stack) == 0: forward[i] = len(l) else: forward[i] = stack[-1] stack.append(i) return forward def backward_array(l): n = len(l) stack = [] backward = [0] * n for i in range(len(l)): while len(stack) and l[stack[-1]] < l[i]: stack.pop() if len(stack) == 0: backward[i] = -1 else: backward[i] = stack[-1] stack.append(i) return backward def char(a): return chr(a + 97) def get_length(a): return a.bit_length() def issq(n): sqrta = int(n ** 0.5) return sqrta ** 2 == n def ceil(a, b): return int((a+b-1)/b) def equal_sum_partition(arr, n): sum = 0 for i in range(n): sum += arr[i] if sum % 2 != 0: return False part = [[True for i in range(n + 1)] for j in range(sum // 2 + 1)] for i in range(0, n + 1): part[0][i] = True for i in range(1, sum // 2 + 1): part[i][0] = False for i in range(1, sum // 2 + 1): for j in range(1, n + 1): part[i][j] = part[i][j - 1] if i >= arr[j - 1]: part[i][j] = (part[i][j] or part[i - arr[j - 1]][j - 1]) return part[sum // 2][n] def bin_sum_array(arr, n): for i in range(n): if arr[i] % 2 == 1: return i+1 binarray = [list(reversed(bin(i)[2:])) for i in arr] new_array = [0 for i in range(32)] for i in binarray: for j in range(len(i)): if i[j] == '1': new_array[j] += 1 return new_array def ispalindrome(s): return s == s[::-1] def get_prefix(l): if l == []: return [] prefix = [l[0]] for i in range(1, len(l)): prefix.append(prefix[-1]+l[i]) return prefix def get_suffix(l): if l == []: return [] suffix = [l[-1]]*len(l) for i in range(len(l)-2, -1, -1): suffix[i] = suffix[i+1]+l[i] return suffix nc = "NO" yc = "YES" ns = "No" ys = "Yes" def yesno(a): print(yc if a else nc) def reduce(dict, a): dict[a] -= 1 if dict[a] == 0: dict.pop(a) # import math as mt # MAXN=10**7 # spf = [0 for i in range(MAXN)] # def sieve(): # spf[1] = 1 # for i in range(2, MAXN): # # marking smallest prime factor # # for every number to be itself. # spf[i] = i # # # separately marking spf for # # every even number as 2 # for i in range(4, MAXN, 2): # spf[i] = 2 # # for i in range(3, mt.ceil(mt.sqrt(MAXN))): # # # checking if i is prime # if (spf[i] == i): # # # marking SPF for all numbers # # divisible by i # for j in range(i * i, MAXN, i): # # # marking spf[j] if it is # # not previously marked # if (spf[j] == j): # spf[j] = i # def getFactorization(x): # ret = list() # while (x != 1): # ret.append(spf[x]) # x = x // spf[x] # # return ret # sieve() # if(os.path.exists('input.txt')): # sys.stdin = open("input.txt","r") ; sys.stdout = open("output.txt","w") import sys import io from sys import stdin, stdout # input=sys.stdin.readline input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline # print=sys.stdout.write t = 1 t=int(input()) for i in range(t): n=int(input()) l=get_list() l.sort() arr=[0]*2*n; counter=0; for i in range(0,2*n,2): arr[i]=l[counter] counter+=1 for i in range(1,2*n,2): arr[i] = l[counter] counter += 1 # print(*arr) print(" ".join(map(str,arr))+"\n") ```
103,929
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a of 2n distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its 2 neighbours. More formally, find an array b, such that: * b is a permutation of a. * For every i from 1 to 2n, b_i β‰  \frac{b_{i-1}+b_{i+1}}{2}, where b_0 = b_{2n} and b_{2n+1} = b_1. It can be proved that under the constraints of this problem, such array b always exists. Input The first line of input contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. The description of testcases follows. The first line of each testcase contains a single integer n (1 ≀ n ≀ 25). The second line of each testcase contains 2n integers a_1, a_2, …, a_{2n} (1 ≀ a_i ≀ 10^9) β€” elements of the array. Note that there is no limit to the sum of n over all testcases. Output For each testcase, you should output 2n integers, b_1, b_2, … b_{2n}, for which the conditions from the statement are satisfied. Example Input 3 3 1 2 3 4 5 6 2 123 456 789 10 1 6 9 Output 3 1 4 2 5 6 123 10 456 789 9 6 Note In the first testcase, array [3, 1, 4, 2, 5, 6] works, as it's a permutation of [1, 2, 3, 4, 5, 6], and (3+4)/(2)β‰  1, (1+2)/(2)β‰  4, (4+5)/(2)β‰  2, (2+6)/(2)β‰  5, (5+3)/(2)β‰  6, (6+1)/(2)β‰  3. Tags: constructive algorithms, sortings Correct Solution: ``` def solve(a, n): i = 0 while i < n: a[i], a[2*n - i - 1] = a[2*n - i - 1], a[i] i += 2 return a for _ in range(int(input())): n = int(input()) a = sorted(list(map(int, input().split()))) print(*solve(a, n)) ```
103,930
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of 2n distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its 2 neighbours. More formally, find an array b, such that: * b is a permutation of a. * For every i from 1 to 2n, b_i β‰  \frac{b_{i-1}+b_{i+1}}{2}, where b_0 = b_{2n} and b_{2n+1} = b_1. It can be proved that under the constraints of this problem, such array b always exists. Input The first line of input contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. The description of testcases follows. The first line of each testcase contains a single integer n (1 ≀ n ≀ 25). The second line of each testcase contains 2n integers a_1, a_2, …, a_{2n} (1 ≀ a_i ≀ 10^9) β€” elements of the array. Note that there is no limit to the sum of n over all testcases. Output For each testcase, you should output 2n integers, b_1, b_2, … b_{2n}, for which the conditions from the statement are satisfied. Example Input 3 3 1 2 3 4 5 6 2 123 456 789 10 1 6 9 Output 3 1 4 2 5 6 123 10 456 789 9 6 Note In the first testcase, array [3, 1, 4, 2, 5, 6] works, as it's a permutation of [1, 2, 3, 4, 5, 6], and (3+4)/(2)β‰  1, (1+2)/(2)β‰  4, (4+5)/(2)β‰  2, (2+6)/(2)β‰  5, (5+3)/(2)β‰  6, (6+1)/(2)β‰  3. Submitted Solution: ``` for _ in range(int(input())): N=int(input()) A=[int(i) for i in input().split()] A.sort() for i in range(N): print(A[i],A[N+i],end=" ") print() ``` Yes
103,931
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of 2n distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its 2 neighbours. More formally, find an array b, such that: * b is a permutation of a. * For every i from 1 to 2n, b_i β‰  \frac{b_{i-1}+b_{i+1}}{2}, where b_0 = b_{2n} and b_{2n+1} = b_1. It can be proved that under the constraints of this problem, such array b always exists. Input The first line of input contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. The description of testcases follows. The first line of each testcase contains a single integer n (1 ≀ n ≀ 25). The second line of each testcase contains 2n integers a_1, a_2, …, a_{2n} (1 ≀ a_i ≀ 10^9) β€” elements of the array. Note that there is no limit to the sum of n over all testcases. Output For each testcase, you should output 2n integers, b_1, b_2, … b_{2n}, for which the conditions from the statement are satisfied. Example Input 3 3 1 2 3 4 5 6 2 123 456 789 10 1 6 9 Output 3 1 4 2 5 6 123 10 456 789 9 6 Note In the first testcase, array [3, 1, 4, 2, 5, 6] works, as it's a permutation of [1, 2, 3, 4, 5, 6], and (3+4)/(2)β‰  1, (1+2)/(2)β‰  4, (4+5)/(2)β‰  2, (2+6)/(2)β‰  5, (5+3)/(2)β‰  6, (6+1)/(2)β‰  3. Submitted Solution: ``` for _ in range(int(input())): n=int(input()) arr=list(map(int, input().split())) arr.sort() if n==1: print(" ".join(map(str, arr))) continue arr_a = arr[n:] final=[] for x in range(n): final.extend([arr[x],arr_a[x]]) print(" ".join(map(str, final))) ``` Yes
103,932
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of 2n distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its 2 neighbours. More formally, find an array b, such that: * b is a permutation of a. * For every i from 1 to 2n, b_i β‰  \frac{b_{i-1}+b_{i+1}}{2}, where b_0 = b_{2n} and b_{2n+1} = b_1. It can be proved that under the constraints of this problem, such array b always exists. Input The first line of input contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. The description of testcases follows. The first line of each testcase contains a single integer n (1 ≀ n ≀ 25). The second line of each testcase contains 2n integers a_1, a_2, …, a_{2n} (1 ≀ a_i ≀ 10^9) β€” elements of the array. Note that there is no limit to the sum of n over all testcases. Output For each testcase, you should output 2n integers, b_1, b_2, … b_{2n}, for which the conditions from the statement are satisfied. Example Input 3 3 1 2 3 4 5 6 2 123 456 789 10 1 6 9 Output 3 1 4 2 5 6 123 10 456 789 9 6 Note In the first testcase, array [3, 1, 4, 2, 5, 6] works, as it's a permutation of [1, 2, 3, 4, 5, 6], and (3+4)/(2)β‰  1, (1+2)/(2)β‰  4, (4+5)/(2)β‰  2, (2+6)/(2)β‰  5, (5+3)/(2)β‰  6, (6+1)/(2)β‰  3. Submitted Solution: ``` for _ in range(int(input())): n = int(input()) arr = list(map(int, input().split())) arr.sort() while(arr): print(arr[0], end=' ') print(arr[-1], end=' ') arr.pop() arr.pop(0) print() ``` Yes
103,933
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of 2n distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its 2 neighbours. More formally, find an array b, such that: * b is a permutation of a. * For every i from 1 to 2n, b_i β‰  \frac{b_{i-1}+b_{i+1}}{2}, where b_0 = b_{2n} and b_{2n+1} = b_1. It can be proved that under the constraints of this problem, such array b always exists. Input The first line of input contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. The description of testcases follows. The first line of each testcase contains a single integer n (1 ≀ n ≀ 25). The second line of each testcase contains 2n integers a_1, a_2, …, a_{2n} (1 ≀ a_i ≀ 10^9) β€” elements of the array. Note that there is no limit to the sum of n over all testcases. Output For each testcase, you should output 2n integers, b_1, b_2, … b_{2n}, for which the conditions from the statement are satisfied. Example Input 3 3 1 2 3 4 5 6 2 123 456 789 10 1 6 9 Output 3 1 4 2 5 6 123 10 456 789 9 6 Note In the first testcase, array [3, 1, 4, 2, 5, 6] works, as it's a permutation of [1, 2, 3, 4, 5, 6], and (3+4)/(2)β‰  1, (1+2)/(2)β‰  4, (4+5)/(2)β‰  2, (2+6)/(2)β‰  5, (5+3)/(2)β‰  6, (6+1)/(2)β‰  3. Submitted Solution: ``` for _ in range(int(input())): n=int(input()) arr=list(map(int,input().split())) arr.sort() pt2=n pt1=0 for i in range(n): print(arr[pt1],arr[pt2],end=' ') pt1+=1 pt2+=1 print() ``` Yes
103,934
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of 2n distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its 2 neighbours. More formally, find an array b, such that: * b is a permutation of a. * For every i from 1 to 2n, b_i β‰  \frac{b_{i-1}+b_{i+1}}{2}, where b_0 = b_{2n} and b_{2n+1} = b_1. It can be proved that under the constraints of this problem, such array b always exists. Input The first line of input contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. The description of testcases follows. The first line of each testcase contains a single integer n (1 ≀ n ≀ 25). The second line of each testcase contains 2n integers a_1, a_2, …, a_{2n} (1 ≀ a_i ≀ 10^9) β€” elements of the array. Note that there is no limit to the sum of n over all testcases. Output For each testcase, you should output 2n integers, b_1, b_2, … b_{2n}, for which the conditions from the statement are satisfied. Example Input 3 3 1 2 3 4 5 6 2 123 456 789 10 1 6 9 Output 3 1 4 2 5 6 123 10 456 789 9 6 Note In the first testcase, array [3, 1, 4, 2, 5, 6] works, as it's a permutation of [1, 2, 3, 4, 5, 6], and (3+4)/(2)β‰  1, (1+2)/(2)β‰  4, (4+5)/(2)β‰  2, (2+6)/(2)β‰  5, (5+3)/(2)β‰  6, (6+1)/(2)β‰  3. Submitted Solution: ``` t=int(input()) while t: n=int(input()) l=list(sorted(map(int,input().split()))) if n==1: print(l) else: for i in range(n-1): l[2*i+1],l[2*i+2]=l[2*i+2],l[2*i+1] print(l) t-=1 ``` No
103,935
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of 2n distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its 2 neighbours. More formally, find an array b, such that: * b is a permutation of a. * For every i from 1 to 2n, b_i β‰  \frac{b_{i-1}+b_{i+1}}{2}, where b_0 = b_{2n} and b_{2n+1} = b_1. It can be proved that under the constraints of this problem, such array b always exists. Input The first line of input contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. The description of testcases follows. The first line of each testcase contains a single integer n (1 ≀ n ≀ 25). The second line of each testcase contains 2n integers a_1, a_2, …, a_{2n} (1 ≀ a_i ≀ 10^9) β€” elements of the array. Note that there is no limit to the sum of n over all testcases. Output For each testcase, you should output 2n integers, b_1, b_2, … b_{2n}, for which the conditions from the statement are satisfied. Example Input 3 3 1 2 3 4 5 6 2 123 456 789 10 1 6 9 Output 3 1 4 2 5 6 123 10 456 789 9 6 Note In the first testcase, array [3, 1, 4, 2, 5, 6] works, as it's a permutation of [1, 2, 3, 4, 5, 6], and (3+4)/(2)β‰  1, (1+2)/(2)β‰  4, (4+5)/(2)β‰  2, (2+6)/(2)β‰  5, (5+3)/(2)β‰  6, (6+1)/(2)β‰  3. Submitted Solution: ``` from sys import stdin input=stdin.readline from math import * # map(int,input().split()) for _ in range(int(input())): n=int(input()) n*=2 a=list(map(int,input().split())) a.sort() for i in range(2,n//2+1,2): a[i],a[n+1-i]=a[n+1-i],a[i] print(*a) ``` No
103,936
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of 2n distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its 2 neighbours. More formally, find an array b, such that: * b is a permutation of a. * For every i from 1 to 2n, b_i β‰  \frac{b_{i-1}+b_{i+1}}{2}, where b_0 = b_{2n} and b_{2n+1} = b_1. It can be proved that under the constraints of this problem, such array b always exists. Input The first line of input contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. The description of testcases follows. The first line of each testcase contains a single integer n (1 ≀ n ≀ 25). The second line of each testcase contains 2n integers a_1, a_2, …, a_{2n} (1 ≀ a_i ≀ 10^9) β€” elements of the array. Note that there is no limit to the sum of n over all testcases. Output For each testcase, you should output 2n integers, b_1, b_2, … b_{2n}, for which the conditions from the statement are satisfied. Example Input 3 3 1 2 3 4 5 6 2 123 456 789 10 1 6 9 Output 3 1 4 2 5 6 123 10 456 789 9 6 Note In the first testcase, array [3, 1, 4, 2, 5, 6] works, as it's a permutation of [1, 2, 3, 4, 5, 6], and (3+4)/(2)β‰  1, (1+2)/(2)β‰  4, (4+5)/(2)β‰  2, (2+6)/(2)β‰  5, (5+3)/(2)β‰  6, (6+1)/(2)β‰  3. Submitted Solution: ``` s = [] for i in range(int(input())): n = int(input()) a = list(map(int, input().split()[:2*n])) a.sort() if len(a) == 1 or len(a) == 2: s.append(a) elif len(a) == 4: a[2], a[1] = a[1], a[2] s.append(a) else: k = 0 while k+2 < n: a[k+2], a[2*n-1-k] = a[2*n-1-k], a[k+2] k += 2 s.append(a) for i in range(len(s)): if i > 0: print('\n', end = '') for j in range(len(s[i])): print(s[i][j], ' ', end = '', sep = '') ``` No
103,937
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of 2n distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its 2 neighbours. More formally, find an array b, such that: * b is a permutation of a. * For every i from 1 to 2n, b_i β‰  \frac{b_{i-1}+b_{i+1}}{2}, where b_0 = b_{2n} and b_{2n+1} = b_1. It can be proved that under the constraints of this problem, such array b always exists. Input The first line of input contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. The description of testcases follows. The first line of each testcase contains a single integer n (1 ≀ n ≀ 25). The second line of each testcase contains 2n integers a_1, a_2, …, a_{2n} (1 ≀ a_i ≀ 10^9) β€” elements of the array. Note that there is no limit to the sum of n over all testcases. Output For each testcase, you should output 2n integers, b_1, b_2, … b_{2n}, for which the conditions from the statement are satisfied. Example Input 3 3 1 2 3 4 5 6 2 123 456 789 10 1 6 9 Output 3 1 4 2 5 6 123 10 456 789 9 6 Note In the first testcase, array [3, 1, 4, 2, 5, 6] works, as it's a permutation of [1, 2, 3, 4, 5, 6], and (3+4)/(2)β‰  1, (1+2)/(2)β‰  4, (4+5)/(2)β‰  2, (2+6)/(2)β‰  5, (5+3)/(2)β‰  6, (6+1)/(2)β‰  3. Submitted Solution: ``` t = int(input()) for _ in range(t): n = int(input()) a = list(map(int,input().split())) if 2*n<3: a.reverse() else: for i in range(2*n+1): if i==2*n: if (a[i-1]+a[1])//2 == a[0]: a[i-1],a[1] = a[1],a[i-1] elif i==2*n-1: if (a[i-1]+a[0])//2 == a[i]: a[i-1],a[i] = a[i],a[i-1] else: if (a[i-1]+a[i+1])//2 == a[i]: a[i-1],a[i] = a[i],a[i-1] print(*a) ``` No
103,938
Provide tags and a correct Python 3 solution for this coding contest problem. As Sherlock Holmes was investigating a crime, he identified n suspects. He knows for sure that exactly one of them committed the crime. To find out which one did it, the detective lines up the suspects and numbered them from 1 to n. After that, he asked each one: "Which one committed the crime?". Suspect number i answered either "The crime was committed by suspect number ai", or "Suspect number ai didn't commit the crime". Also, the suspect could say so about himself (ai = i). Sherlock Holmes understood for sure that exactly m answers were the truth and all other answers were a lie. Now help him understand this: which suspect lied and which one told the truth? Input The first line contains two integers n and m (1 ≀ n ≀ 105, 0 ≀ m ≀ n) β€” the total number of suspects and the number of suspects who told the truth. Next n lines contain the suspects' answers. The i-th line contains either "+ai" (without the quotes), if the suspect number i says that the crime was committed by suspect number ai, or "-ai" (without the quotes), if the suspect number i says that the suspect number ai didn't commit the crime (ai is an integer, 1 ≀ ai ≀ n). It is guaranteed that at least one suspect exists, such that if he committed the crime, then exactly m people told the truth. Output Print n lines. Line number i should contain "Truth" if suspect number i has told the truth for sure. Print "Lie" if the suspect number i lied for sure and print "Not defined" if he could lie and could tell the truth, too, depending on who committed the crime. Examples Input 1 1 +1 Output Truth Input 3 2 -1 -2 -3 Output Not defined Not defined Not defined Input 4 1 +2 -3 +4 -1 Output Lie Not defined Lie Not defined Note The first sample has the single person and he confesses to the crime, and Sherlock Holmes knows that one person is telling the truth. That means that this person is telling the truth. In the second sample there are three suspects and each one denies his guilt. Sherlock Holmes knows that only two of them are telling the truth. Any one of them can be the criminal, so we don't know for any of them, whether this person is telling the truth or not. In the third sample the second and the fourth suspect defend the first and the third one. But only one is telling the truth, thus, the first or the third one is the criminal. Both of them can be criminals, so the second and the fourth one can either be lying or telling the truth. The first and the third one are lying for sure as they are blaming the second and the fourth one. Tags: constructive algorithms, data structures, implementation Correct Solution: ``` from sys import stdin, stdout n, m = map(int, stdin.readline().split()) cntf = [0 for i in range(n + 1)] cnts = [0 for i in range(n + 1)] challengers = [] for i in range(n): s = stdin.readline().strip() challengers.append(s) if s[0] == '+': cntf[int(s[1:])] += 1 else: cnts[int(s[1:])] += 1 first = sum(cntf) second = sum(cnts) ans = set() for i in range(1, n + 1): if cntf[i] + second - cnts[i] == m: ans.add(i) for i in range(n): s = challengers[i] if s[0] == '+': if int(s[1:]) in ans: if len(ans) > 1: stdout.write('Not defined\n') else: stdout.write('Truth\n') else: stdout.write('Lie\n') else: if int(s[1:]) in ans: if len(ans) > 1: stdout.write('Not defined\n') else: stdout.write('Lie\n') else: stdout.write('Truth\n') ```
103,939
Provide tags and a correct Python 3 solution for this coding contest problem. As Sherlock Holmes was investigating a crime, he identified n suspects. He knows for sure that exactly one of them committed the crime. To find out which one did it, the detective lines up the suspects and numbered them from 1 to n. After that, he asked each one: "Which one committed the crime?". Suspect number i answered either "The crime was committed by suspect number ai", or "Suspect number ai didn't commit the crime". Also, the suspect could say so about himself (ai = i). Sherlock Holmes understood for sure that exactly m answers were the truth and all other answers were a lie. Now help him understand this: which suspect lied and which one told the truth? Input The first line contains two integers n and m (1 ≀ n ≀ 105, 0 ≀ m ≀ n) β€” the total number of suspects and the number of suspects who told the truth. Next n lines contain the suspects' answers. The i-th line contains either "+ai" (without the quotes), if the suspect number i says that the crime was committed by suspect number ai, or "-ai" (without the quotes), if the suspect number i says that the suspect number ai didn't commit the crime (ai is an integer, 1 ≀ ai ≀ n). It is guaranteed that at least one suspect exists, such that if he committed the crime, then exactly m people told the truth. Output Print n lines. Line number i should contain "Truth" if suspect number i has told the truth for sure. Print "Lie" if the suspect number i lied for sure and print "Not defined" if he could lie and could tell the truth, too, depending on who committed the crime. Examples Input 1 1 +1 Output Truth Input 3 2 -1 -2 -3 Output Not defined Not defined Not defined Input 4 1 +2 -3 +4 -1 Output Lie Not defined Lie Not defined Note The first sample has the single person and he confesses to the crime, and Sherlock Holmes knows that one person is telling the truth. That means that this person is telling the truth. In the second sample there are three suspects and each one denies his guilt. Sherlock Holmes knows that only two of them are telling the truth. Any one of them can be the criminal, so we don't know for any of them, whether this person is telling the truth or not. In the third sample the second and the fourth suspect defend the first and the third one. But only one is telling the truth, thus, the first or the third one is the criminal. Both of them can be criminals, so the second and the fourth one can either be lying or telling the truth. The first and the third one are lying for sure as they are blaming the second and the fourth one. Tags: constructive algorithms, data structures, implementation Correct Solution: ``` """ Brandt Smith, Lemuel Gorion and Peter Haddad codeforces.com Problem 156B """ import sys n, m = map(int, input().split(' ')) inp = [] guess = [0] * (n + 1) for i in range(n): temp = int(input()) inp.append(temp) if temp < 0: m -= 1 guess[-temp] -= 1 else: guess[temp] += 1 dic = {temp for temp in range(1, n + 1) if guess[temp] == m} if len(dic) == 0: for i in range(n): print('Not defined') elif len(dic) == 1: temp = dic.pop() for i in inp: if i == temp or (i < 0 and i + temp): print('Truth') else: print('Lie') else: temp = dic.update({-i for i in dic}) for i in inp: if i in dic: print('Not defined') else: if i < 0: print('Truth') else: print('Lie') # Made By Mostafa_Khaled ```
103,940
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In ABBYY a wonderful Smart Beaver lives. This time, he began to study history. When he read about the Roman Empire, he became interested in the life of merchants. The Roman Empire consisted of n cities numbered from 1 to n. It also had m bidirectional roads numbered from 1 to m. Each road connected two different cities. Any two cities were connected by no more than one road. We say that there is a path between cities c1 and c2 if there exists a finite sequence of cities t1, t2, ..., tp (p β‰₯ 1) such that: * t1 = c1 * tp = c2 * for any i (1 ≀ i < p), cities ti and ti + 1 are connected by a road We know that there existed a path between any two cities in the Roman Empire. In the Empire k merchants lived numbered from 1 to k. For each merchant we know a pair of numbers si and li, where si is the number of the city where this merchant's warehouse is, and li is the number of the city where his shop is. The shop and the warehouse could be located in different cities, so the merchants had to deliver goods from the warehouse to the shop. Let's call a road important for the merchant if its destruction threatens to ruin the merchant, that is, without this road there is no path from the merchant's warehouse to his shop. Merchants in the Roman Empire are very greedy, so each merchant pays a tax (1 dinar) only for those roads which are important for him. In other words, each merchant pays di dinars of tax, where di (di β‰₯ 0) is the number of roads important for the i-th merchant. The tax collection day came in the Empire. The Smart Beaver from ABBYY is very curious by nature, so he decided to count how many dinars each merchant had paid that day. And now he needs your help. Input The first input line contains two integers n and m, separated by a space, n is the number of cities, and m is the number of roads in the empire. The following m lines contain pairs of integers ai, bi (1 ≀ ai, bi ≀ n, ai β‰  bi), separated by a space β€” the numbers of cities connected by the i-th road. It is guaranteed that any two cities are connected by no more than one road and that there exists a path between any two cities in the Roman Empire. The next line contains a single integer k β€” the number of merchants in the empire. The following k lines contain pairs of integers si, li (1 ≀ si, li ≀ n), separated by a space, β€” si is the number of the city in which the warehouse of the i-th merchant is located, and li is the number of the city in which the shop of the i-th merchant is located. The input limitations for getting 20 points are: * 1 ≀ n ≀ 200 * 1 ≀ m ≀ 200 * 1 ≀ k ≀ 200 The input limitations for getting 50 points are: * 1 ≀ n ≀ 2000 * 1 ≀ m ≀ 2000 * 1 ≀ k ≀ 2000 The input limitations for getting 100 points are: * 1 ≀ n ≀ 105 * 1 ≀ m ≀ 105 * 1 ≀ k ≀ 105 Output Print exactly k lines, the i-th line should contain a single integer di β€” the number of dinars that the i-th merchant paid. Examples Input 7 8 1 2 2 3 3 4 4 5 5 6 5 7 3 5 4 7 4 1 5 2 4 2 6 4 7 Output 2 1 2 0 Note The given sample is illustrated in the figure below. <image> Let's describe the result for the first merchant. The merchant's warehouse is located in city 1 and his shop is in city 5. Let us note that if either road, (1, 2) or (2, 3) is destroyed, there won't be any path between cities 1 and 5 anymore. If any other road is destroyed, the path will be preserved. That's why for the given merchant the answer is 2. Submitted Solution: ``` from math import * from collections import deque from sys import * #//bisect #//input()=stdin.readline() #//print()=stdout.write() #///\\\# #Disjoint_Set_Union def make_set(a): size[a] = 1 parent[a] = a def find_set(a): if a == parent[a]: return a else: parent[a] = find_set(parent[a]) return parent[a] def union_sets(a,b): a = find_set(a) b = find_set(b) if a != b: if size[b] > size[a]: a,b=b,a parent[b] = a size[a] += size[b] #size = dict() #parent=dict() #///\\\# #Segment_Tree def build(): for j in range(n1-1,n1+n-1): tree[j] = [j-n1+2,j-n1+2,A[j-n1+1],0] for j in range(n1+n-1,2*n1-1): tree[j] = [j-n1+2,j-n1+2,-float('infinity'),0] for j in range(n1-2,-1,-1): l = tree[j* 2 + 1] r = tree[j*2+2] tree[j] = [l[0], r[1],max(l[2],r[2]),0] def push(node): tree[2 * node + 1][3] += tree[node][3] tree[2*node+2][3] += tree[node][3] tree[node][3] = 0 def update(node, a,b,val): l = tree[node][0] r = tree[node][1] if l == a and r == b: tree[node][3] += val return if r < a or b < l: return push(node) update(2*node+1,a,min(b,(l+r)//2),val) update(2*node+2,max(a,(l+r)//2 + 1),b,val) tree[node][2] = max(tree[node*2+1][2] + tree[node*2+1][3], tree[node*2+2][2] + tree[node*2+2][3]) def query(node,a,b): l = tree[node][0] r = tree[node][1] if r < a or b < l: return -float('infinity') if l == a and r == b: return tree[node][2] + tree[node][3] push(node) ans = max(query(node*2+1,a,min(b,(l+r)//2)),query(node*2+2,max(a,(l+r)//2 + 1),b)) tree[node][2] = max(tree[2*node+1][2] + tree[2*node+1][3], tree[2*node+2][2] + tree[2*node+2][3]) return ans #n=int(stdin.readline()) #n1 = int(2**ceil(log2(n))) #tree = [0] * (2*n1-1) #A = list(map(int,stdin.readline().split())) #build() #///\\\# #Decart_Tree def merge(A,B): s=0 num = 'l' ans = 0 if A[1] >= B[1]: ans =(A) else: ans = (B) while True: if A[1] >= B[1]: s2= A if num == 'l': childl[s] = s2 else: childr[s] = s2 if s2 not in childr: childr[s2] = B break else: A = childr[s2] num = 'r' else: s2 = B if num == 'l': childl[s] = s2 else: childr[s] = s2 if s2 not in childl: childl[s2] = A break else: B = childl[s2] num = 'l' s = s2 if 0 in childl: childl.pop(0) if 0 in childr: childr.pop(0) return ans def split(T, x): L = -1 R = -1 s=0 s2=1 last = -1 while True: if T[0] >= x: if R == -1: R = T childl[s2] = T s2 = T last = 2 if T not in childl: break else: T = childl[T] else: if L == -1: L = T childr[s] = T s = T last = 1 if T not in childr: break else: T = childr[T] if last == 2: if s in childr: childr.pop(s) elif last == 1: if s2 in childl: childl.pop(s2) return L,R #childl = dict() #childr = dict() #n = int(stdin.readline()) #A=[0] * n #for j in range(n): # per1,per2=map(int,stdin.readline().split()) # A[j] = (per1,per2) #root = A[0] #for j in range(1,n): # L,R = split(root,A[j][0]) # if L == -1: # root=merge(A[j],R) # elif R == -1: # root=merge(L,A[j]) # else: # L1 = merge(L,A[j]) # root=merge(L1,R) #///\\\# #||||||# ``` No
103,941
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Once upon a time there lived a good fairy A. One day a fine young man B came to her and asked to predict his future. The fairy looked into her magic ball and said that soon the fine young man will meet the most beautiful princess ever and will marry her. Then she drew on a sheet of paper n points and joined some of them with segments, each of the segments starts in some point and ends in some other point. Having drawn that picture, she asked the young man to erase one of the segments from the sheet. Then she tries to colour each point red or blue so, that there is no segment having points of the same colour as its ends. If she manages to do so, the prediction will come true. B wants to meet the most beautiful princess, that's why he asks you to help him. Find all the segments that will help him to meet the princess. Input The first input line contains two integer numbers: n β€” amount of the drawn points and m β€” amount of the drawn segments (1 ≀ n ≀ 104, 0 ≀ m ≀ 104). The following m lines contain the descriptions of the segments. Each description contains two different space-separated integer numbers v, u (1 ≀ v ≀ n, 1 ≀ u ≀ n) β€” indexes of the points, joined by this segment. No segment is met in the description twice. Output In the first line output number k β€” amount of the segments in the answer. In the second line output k space-separated numbers β€” indexes of these segments in ascending order. Each index should be output only once. Segments are numbered from 1 in the input order. Examples Input 4 4 1 2 1 3 2 4 3 4 Output 4 1 2 3 4 Input 4 5 1 2 2 3 3 4 4 1 1 3 Output 1 5 Submitted Solution: ``` import sys sys.setrecursionlimit(1000000) n, m = [int(x) for x in input().split()] adj = [[] for _ in range(n)] edges = [] for i in range(m): u,v = [int(x) for x in input().split()] adj[u-1].append([v-1, i]) adj[v-1].append([u-1, i]) edges.append([u-1,v-1]) color = [-1]*n parent = [-1]*m cycles = [0]*m count = 0 def dfs(i,p,c,s): global count if(color[i]!=-1): #Found Cycle if(c == color[i]): return 0 #Found Odd Cycle count += 1 while True: cycles[s]+=1 if i in edges[s]: break s = parent[s] return 0 color[i] = c for ch,r in adj[i]: if(ch == p): continue parent[r] = s dfs(ch,i,1-c,r) for i in range(n): if(color[i]==-1): dfs(i,-1,1,-1) ans = [] for i in range(m): if(cycles[i]==count): ans.append(i+1) print(len(ans)) print(*ans,sep = " ") print() ``` No
103,942
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Once upon a time there lived a good fairy A. One day a fine young man B came to her and asked to predict his future. The fairy looked into her magic ball and said that soon the fine young man will meet the most beautiful princess ever and will marry her. Then she drew on a sheet of paper n points and joined some of them with segments, each of the segments starts in some point and ends in some other point. Having drawn that picture, she asked the young man to erase one of the segments from the sheet. Then she tries to colour each point red or blue so, that there is no segment having points of the same colour as its ends. If she manages to do so, the prediction will come true. B wants to meet the most beautiful princess, that's why he asks you to help him. Find all the segments that will help him to meet the princess. Input The first input line contains two integer numbers: n β€” amount of the drawn points and m β€” amount of the drawn segments (1 ≀ n ≀ 104, 0 ≀ m ≀ 104). The following m lines contain the descriptions of the segments. Each description contains two different space-separated integer numbers v, u (1 ≀ v ≀ n, 1 ≀ u ≀ n) β€” indexes of the points, joined by this segment. No segment is met in the description twice. Output In the first line output number k β€” amount of the segments in the answer. In the second line output k space-separated numbers β€” indexes of these segments in ascending order. Each index should be output only once. Segments are numbered from 1 in the input order. Examples Input 4 4 1 2 1 3 2 4 3 4 Output 4 1 2 3 4 Input 4 5 1 2 2 3 3 4 4 1 1 3 Output 1 5 Submitted Solution: ``` print("big pp") ``` No
103,943
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Once upon a time there lived a good fairy A. One day a fine young man B came to her and asked to predict his future. The fairy looked into her magic ball and said that soon the fine young man will meet the most beautiful princess ever and will marry her. Then she drew on a sheet of paper n points and joined some of them with segments, each of the segments starts in some point and ends in some other point. Having drawn that picture, she asked the young man to erase one of the segments from the sheet. Then she tries to colour each point red or blue so, that there is no segment having points of the same colour as its ends. If she manages to do so, the prediction will come true. B wants to meet the most beautiful princess, that's why he asks you to help him. Find all the segments that will help him to meet the princess. Input The first input line contains two integer numbers: n β€” amount of the drawn points and m β€” amount of the drawn segments (1 ≀ n ≀ 104, 0 ≀ m ≀ 104). The following m lines contain the descriptions of the segments. Each description contains two different space-separated integer numbers v, u (1 ≀ v ≀ n, 1 ≀ u ≀ n) β€” indexes of the points, joined by this segment. No segment is met in the description twice. Output In the first line output number k β€” amount of the segments in the answer. In the second line output k space-separated numbers β€” indexes of these segments in ascending order. Each index should be output only once. Segments are numbered from 1 in the input order. Examples Input 4 4 1 2 1 3 2 4 3 4 Output 4 1 2 3 4 Input 4 5 1 2 2 3 3 4 4 1 1 3 Output 1 5 Submitted Solution: ``` import sys sys.setrecursionlimit(1000000) n, m = [int(x) for x in input().split()] adj = [[] for _ in range(n)] edges = [] for i in range(m): u,v = [int(x) for x in input().split()] adj[u-1].append([v-1, i]) adj[v-1].append([u-1, i]) edges.append([u-1,v-1]) color = [-1]*n parent = [-1]*m cycles = [0]*m count = 0 def dfs(i,p,c,s): global count if(color[i]!=-1): #Found Cycle if(c == color[i]): return 0 #Found Odd Cycle count += 1 while True: cycles[s]+=1 if i in edges[s]: break s = parent[s] return 0 color[i] = c for ch,r in adj[i]: if(ch == p): continue parent[r] = s dfs(ch,i,1-c,r) dfs(0,-1,1,-1) ans = [] for i in range(m): if(cycles[i]==count): ans.append(i+1) print(len(ans)) print(*ans,sep = " ") print() ``` No
103,944
Provide tags and a correct Python 3 solution for this coding contest problem. You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. Input The first and the single line contains three space-separated integers β€” the areas of the parallelepiped's faces. The area's values are positive ( > 0) and do not exceed 104. It is guaranteed that there exists at least one parallelepiped that satisfies the problem statement. Output Print a single number β€” the sum of all edges of the parallelepiped. Examples Input 1 1 1 Output 12 Input 4 6 6 Output 28 Note In the first sample the parallelepiped has sizes 1 Γ— 1 Γ— 1, in the second one β€” 2 Γ— 2 Γ— 3. Tags: brute force, geometry, math Correct Solution: ``` import math ar = [] for i in input().split(' '): ar.append(int(i)) b = math.sqrt((ar[0]*ar[1])/ar[2]) a = ar[0]/b c = ar[2]/a print(int(4*(a+b+c))) ```
103,945
Provide tags and a correct Python 3 solution for this coding contest problem. You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. Input The first and the single line contains three space-separated integers β€” the areas of the parallelepiped's faces. The area's values are positive ( > 0) and do not exceed 104. It is guaranteed that there exists at least one parallelepiped that satisfies the problem statement. Output Print a single number β€” the sum of all edges of the parallelepiped. Examples Input 1 1 1 Output 12 Input 4 6 6 Output 28 Note In the first sample the parallelepiped has sizes 1 Γ— 1 Γ— 1, in the second one β€” 2 Γ— 2 Γ— 3. Tags: brute force, geometry, math Correct Solution: ``` s1,s2,s3=map(int,input().split()) a=int((s1*s3//s2)**0.5) b=int((s1*s2//s3)**0.5) c=int((s2*s3//s1)**0.5) print(4*(a+b+c)) ```
103,946
Provide tags and a correct Python 3 solution for this coding contest problem. You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. Input The first and the single line contains three space-separated integers β€” the areas of the parallelepiped's faces. The area's values are positive ( > 0) and do not exceed 104. It is guaranteed that there exists at least one parallelepiped that satisfies the problem statement. Output Print a single number β€” the sum of all edges of the parallelepiped. Examples Input 1 1 1 Output 12 Input 4 6 6 Output 28 Note In the first sample the parallelepiped has sizes 1 Γ— 1 Γ— 1, in the second one β€” 2 Γ— 2 Γ— 3. Tags: brute force, geometry, math Correct Solution: ``` a,b,c = list(map(int,input().split())) import math c = math.sqrt((c*b)/a) b = b/c a = a/b print(int(sum([4*a,4*b,4*c]))) ```
103,947
Provide tags and a correct Python 3 solution for this coding contest problem. You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. Input The first and the single line contains three space-separated integers β€” the areas of the parallelepiped's faces. The area's values are positive ( > 0) and do not exceed 104. It is guaranteed that there exists at least one parallelepiped that satisfies the problem statement. Output Print a single number β€” the sum of all edges of the parallelepiped. Examples Input 1 1 1 Output 12 Input 4 6 6 Output 28 Note In the first sample the parallelepiped has sizes 1 Γ— 1 Γ— 1, in the second one β€” 2 Γ— 2 Γ— 3. Tags: brute force, geometry, math Correct Solution: ``` a,b,c=map(int,input().split()) v=(a*b*c)**0.5 #l*b*h print(int(4*(v/a+v/b+v/c))) ```
103,948
Provide tags and a correct Python 3 solution for this coding contest problem. You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. Input The first and the single line contains three space-separated integers β€” the areas of the parallelepiped's faces. The area's values are positive ( > 0) and do not exceed 104. It is guaranteed that there exists at least one parallelepiped that satisfies the problem statement. Output Print a single number β€” the sum of all edges of the parallelepiped. Examples Input 1 1 1 Output 12 Input 4 6 6 Output 28 Note In the first sample the parallelepiped has sizes 1 Γ— 1 Γ— 1, in the second one β€” 2 Γ— 2 Γ— 3. Tags: brute force, geometry, math Correct Solution: ``` import math a,b,c=map(int,input().split()) x=math.sqrt(a*b/c) y=math.sqrt(b*c/a) z=math.sqrt(a*c/b) print(int((x+y+z)*4)) ```
103,949
Provide tags and a correct Python 3 solution for this coding contest problem. You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. Input The first and the single line contains three space-separated integers β€” the areas of the parallelepiped's faces. The area's values are positive ( > 0) and do not exceed 104. It is guaranteed that there exists at least one parallelepiped that satisfies the problem statement. Output Print a single number β€” the sum of all edges of the parallelepiped. Examples Input 1 1 1 Output 12 Input 4 6 6 Output 28 Note In the first sample the parallelepiped has sizes 1 Γ— 1 Γ— 1, in the second one β€” 2 Γ— 2 Γ— 3. Tags: brute force, geometry, math Correct Solution: ``` import math s1, s2, s3 = map(int, input().split()) v2 = s1*s2*s3 print(int(4 * (math.sqrt(v2 / (s1 * s1)) + math.sqrt(v2 / (s2 * s2)) + math.sqrt(v2 / (s3 * s3))))) ```
103,950
Provide tags and a correct Python 3 solution for this coding contest problem. You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. Input The first and the single line contains three space-separated integers β€” the areas of the parallelepiped's faces. The area's values are positive ( > 0) and do not exceed 104. It is guaranteed that there exists at least one parallelepiped that satisfies the problem statement. Output Print a single number β€” the sum of all edges of the parallelepiped. Examples Input 1 1 1 Output 12 Input 4 6 6 Output 28 Note In the first sample the parallelepiped has sizes 1 Γ— 1 Γ— 1, in the second one β€” 2 Γ— 2 Γ— 3. Tags: brute force, geometry, math Correct Solution: ``` import math arr = [int(x) for x in input().split()] print(int(4*(math.sqrt((arr[0]*arr[1])/arr[2])+math.sqrt((arr[0]*arr[2])/arr[1])+math.sqrt((arr[2]*arr[1])/arr[0])))) ```
103,951
Provide tags and a correct Python 3 solution for this coding contest problem. You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. Input The first and the single line contains three space-separated integers β€” the areas of the parallelepiped's faces. The area's values are positive ( > 0) and do not exceed 104. It is guaranteed that there exists at least one parallelepiped that satisfies the problem statement. Output Print a single number β€” the sum of all edges of the parallelepiped. Examples Input 1 1 1 Output 12 Input 4 6 6 Output 28 Note In the first sample the parallelepiped has sizes 1 Γ— 1 Γ— 1, in the second one β€” 2 Γ— 2 Γ— 3. Tags: brute force, geometry, math Correct Solution: ``` arr = input().split() ab , bc , ca = int(arr[0]), int(arr[1]), int(arr[2]) b = (ab*bc//ca)**(1/2) a = (ab*ca//bc)**(1/2) c = (bc*ca//ab)**(1/2) print(int((a+b+c)*4)) ```
103,952
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. Input The first and the single line contains three space-separated integers β€” the areas of the parallelepiped's faces. The area's values are positive ( > 0) and do not exceed 104. It is guaranteed that there exists at least one parallelepiped that satisfies the problem statement. Output Print a single number β€” the sum of all edges of the parallelepiped. Examples Input 1 1 1 Output 12 Input 4 6 6 Output 28 Note In the first sample the parallelepiped has sizes 1 Γ— 1 Γ— 1, in the second one β€” 2 Γ— 2 Γ— 3. Submitted Solution: ``` import math def solve(areas): a = math.sqrt((areas[2] * areas[0]) / areas[1]) b = areas[0] / a c = areas[2] / a result = a * 4 + b * 4 + c * 4 return result areas = [int(num) for num in input().split()] result = solve(areas) print(int(result)) ``` Yes
103,953
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. Input The first and the single line contains three space-separated integers β€” the areas of the parallelepiped's faces. The area's values are positive ( > 0) and do not exceed 104. It is guaranteed that there exists at least one parallelepiped that satisfies the problem statement. Output Print a single number β€” the sum of all edges of the parallelepiped. Examples Input 1 1 1 Output 12 Input 4 6 6 Output 28 Note In the first sample the parallelepiped has sizes 1 Γ— 1 Γ— 1, in the second one β€” 2 Γ— 2 Γ— 3. Submitted Solution: ``` x,y,z=map(int,input().split()) xx=(x*y/z)**0.5 yy=(y*z/x)**0.5 zz=(z*x/y)**0.5 print(int(xx+yy+zz)*4) ``` Yes
103,954
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. Input The first and the single line contains three space-separated integers β€” the areas of the parallelepiped's faces. The area's values are positive ( > 0) and do not exceed 104. It is guaranteed that there exists at least one parallelepiped that satisfies the problem statement. Output Print a single number β€” the sum of all edges of the parallelepiped. Examples Input 1 1 1 Output 12 Input 4 6 6 Output 28 Note In the first sample the parallelepiped has sizes 1 Γ— 1 Γ— 1, in the second one β€” 2 Γ— 2 Γ— 3. Submitted Solution: ``` import math import sys import collections # imgur.com/Pkt7iIf.png def getdict(n): d = {} if type(n) is list: for i in n: if i in d: d[i] += 1 else: d[i] = 1 else: for i in range(n): t = ii() if t in d: d[t] += 1 else: d[t] = 1 return d def cdiv(n, k): return n // k + (n % k != 0) def ii(): return int(input()) def mi(): return map(int, input().split()) def li(): return list(map(int, input().split())) def lcm(a, b): return abs(a*b) // math.gcd(a, b) a, b, c = mi() q = math.sqrt(a*b/c) w = math.sqrt(b*c/a) e = math.sqrt(a*c/b) print(int(4*(q+w+e))) ``` Yes
103,955
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. Input The first and the single line contains three space-separated integers β€” the areas of the parallelepiped's faces. The area's values are positive ( > 0) and do not exceed 104. It is guaranteed that there exists at least one parallelepiped that satisfies the problem statement. Output Print a single number β€” the sum of all edges of the parallelepiped. Examples Input 1 1 1 Output 12 Input 4 6 6 Output 28 Note In the first sample the parallelepiped has sizes 1 Γ— 1 Γ— 1, in the second one β€” 2 Γ— 2 Γ— 3. Submitted Solution: ``` import math a, b, c = input().split() a, b, c = int(a), int(b), int(c) a1 = math.sqrt(a * b / c) b1 = math.sqrt(c * a / b) c1 = math.sqrt(c * b / a) print(int(a1*4 + b1*4 + c1*4)) ``` Yes
103,956
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. Input The first and the single line contains three space-separated integers β€” the areas of the parallelepiped's faces. The area's values are positive ( > 0) and do not exceed 104. It is guaranteed that there exists at least one parallelepiped that satisfies the problem statement. Output Print a single number β€” the sum of all edges of the parallelepiped. Examples Input 1 1 1 Output 12 Input 4 6 6 Output 28 Note In the first sample the parallelepiped has sizes 1 Γ— 1 Γ— 1, in the second one β€” 2 Γ— 2 Γ— 3. Submitted Solution: ``` import math a, b, c = map(int, input().split()) volume_sqr = math.sqrt(a * b * c) print(4 * (volume_sqr / a + volume_sqr / b + volume_sqr / c)) ``` No
103,957
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. Input The first and the single line contains three space-separated integers β€” the areas of the parallelepiped's faces. The area's values are positive ( > 0) and do not exceed 104. It is guaranteed that there exists at least one parallelepiped that satisfies the problem statement. Output Print a single number β€” the sum of all edges of the parallelepiped. Examples Input 1 1 1 Output 12 Input 4 6 6 Output 28 Note In the first sample the parallelepiped has sizes 1 Γ— 1 Γ— 1, in the second one β€” 2 Γ— 2 Γ— 3. Submitted Solution: ``` '''input 152 108 4104 ''' def gcd(x, y): while y != 0: x, y = y, x % y return x a, b, c = map(int, input().split()) l = a * b // gcd(a, b) l = l * c // gcd(l, c) print((l // a + l // b + l // c) * 4 if l != max([a,b,c]) else (l // a + l // b + l // c) * 8) ``` No
103,958
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. Input The first and the single line contains three space-separated integers β€” the areas of the parallelepiped's faces. The area's values are positive ( > 0) and do not exceed 104. It is guaranteed that there exists at least one parallelepiped that satisfies the problem statement. Output Print a single number β€” the sum of all edges of the parallelepiped. Examples Input 1 1 1 Output 12 Input 4 6 6 Output 28 Note In the first sample the parallelepiped has sizes 1 Γ— 1 Γ— 1, in the second one β€” 2 Γ— 2 Γ— 3. Submitted Solution: ``` a=[int(x) for x in input().split()] #d*b=a[0] #b*c=a[1] #d*c=a[2] #b=a[0]/d #c=a[2]/d #a[0]*a[2]/d**2=a[1] d=(a[0]*a[2]/a[1])**0.5 b=a[0]/d c=a[2]/d print(4*d + 4*b + 4*c) ``` No
103,959
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. Input The first and the single line contains three space-separated integers β€” the areas of the parallelepiped's faces. The area's values are positive ( > 0) and do not exceed 104. It is guaranteed that there exists at least one parallelepiped that satisfies the problem statement. Output Print a single number β€” the sum of all edges of the parallelepiped. Examples Input 1 1 1 Output 12 Input 4 6 6 Output 28 Note In the first sample the parallelepiped has sizes 1 Γ— 1 Γ— 1, in the second one β€” 2 Γ— 2 Γ— 3. Submitted Solution: ``` def gcd(a, b): if b == 0: return a return gcd(b, a % b) x, y, z = map(int, input().split()) if x == y == z: print(int(x ** 0.5) * 12) else: if x == y: y, z = z, y a = gcd(x, y) if a == min(x, y): a = int(min(x, y) ** 0.5) b = x // a c = y // a if b * c != z: a = gcd(x, z) b = x // a c = z // a print(4 * (a + b + c)) ``` No
103,960
Provide tags and a correct Python 3 solution for this coding contest problem. For he knew every Who down in Whoville beneath, Was busy now, hanging a mistletoe wreath. "And they're hanging their stockings!" he snarled with a sneer, "Tomorrow is Christmas! It's practically here!" Dr. Suess, How The Grinch Stole Christmas Christmas celebrations are coming to Whoville. Cindy Lou Who and her parents Lou Lou Who and Betty Lou Who decided to give sweets to all people in their street. They decided to give the residents of each house on the street, one kilogram of sweets. So they need as many kilos of sweets as there are homes on their street. The street, where the Lou Who family lives can be represented as n consecutive sections of equal length. You can go from any section to a neighbouring one in one unit of time. Each of the sections is one of three types: an empty piece of land, a house or a shop. Cindy Lou and her family can buy sweets in a shop, but no more than one kilogram of sweets in one shop (the vendors care about the residents of Whoville not to overeat on sweets). After the Lou Who family leave their home, they will be on the first section of the road. To get to this section of the road, they also require one unit of time. We can assume that Cindy and her mom and dad can carry an unlimited number of kilograms of sweets. Every time they are on a house section, they can give a kilogram of sweets to the inhabitants of the house, or they can simply move to another section. If the family have already given sweets to the residents of a house, they can't do it again. Similarly, if they are on the shop section, they can either buy a kilo of sweets in it or skip this shop. If they've bought a kilo of sweets in a shop, the seller of the shop remembered them and the won't sell them a single candy if they come again. The time to buy and give sweets can be neglected. The Lou Whos do not want the people of any house to remain without food. The Lou Whos want to spend no more than t time units of time to give out sweets, as they really want to have enough time to prepare for the Christmas celebration. In order to have time to give all the sweets, they may have to initially bring additional k kilos of sweets. Cindy Lou wants to know the minimum number of k kilos of sweets they need to take with them, to have time to give sweets to the residents of each house in their street. Your task is to write a program that will determine the minimum possible value of k. Input The first line of the input contains two space-separated integers n and t (2 ≀ n ≀ 5Β·105, 1 ≀ t ≀ 109). The second line of the input contains n characters, the i-th of them equals "H" (if the i-th segment contains a house), "S" (if the i-th segment contains a shop) or "." (if the i-th segment doesn't contain a house or a shop). It is guaranteed that there is at least one segment with a house. Output If there isn't a single value of k that makes it possible to give sweets to everybody in at most t units of time, print in a single line "-1" (without the quotes). Otherwise, print on a single line the minimum possible value of k. Examples Input 6 6 HSHSHS Output 1 Input 14 100 ...HHHSSS...SH Output 0 Input 23 50 HHSS.......SSHHHHHHHHHH Output 8 Note In the first example, there are as many stores, as houses. If the family do not take a single kilo of sweets from home, in order to treat the inhabitants of the first house, they will need to make at least one step back, and they have absolutely no time for it. If they take one kilogram of sweets, they won't need to go back. In the second example, the number of shops is equal to the number of houses and plenty of time. Available at all stores passing out candy in one direction and give them when passing in the opposite direction. In the third example, the shops on the street are fewer than houses. The Lou Whos have to take the missing number of kilograms of sweets with them from home. Tags: binary search, greedy, implementation Correct Solution: ``` def check(n, casas): #print('n:',n) global T,N,street current = n time = T need = 0 last_house = 0 for ind, i in enumerate(street): time -= 1 if i == 'S': current += 1 elif i == 'H': need += 1 if need == 1: last_house = ind if need > 0 and current >= need: #print('p',time, ind-last_house) current -= need casas -= need need = 0 if casas > 0: if (ind-last_house)*2 >= N-last_house-1: time -= N-last_house-1 + N-ind-1 return time >= 0 time -= (ind-last_house)*2 else: time -= ind-last_house #print('lugar:',i,ind,current, time, need, last_house) if casas == 0: break #print(time) return time >= 0 and casas == 0 N,T = [int(i) for i in input().split()] street = input().rstrip('.') N = len(street) C = street.count('H') S = street.count('S') l = max(C-S, 0) r = 500005 #print(N, C) while l < r: mid = (l+r)//2 if check(mid, C): r = mid else: l = mid + 1 print(l if l < 500005 else -1) ```
103,961
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For he knew every Who down in Whoville beneath, Was busy now, hanging a mistletoe wreath. "And they're hanging their stockings!" he snarled with a sneer, "Tomorrow is Christmas! It's practically here!" Dr. Suess, How The Grinch Stole Christmas Christmas celebrations are coming to Whoville. Cindy Lou Who and her parents Lou Lou Who and Betty Lou Who decided to give sweets to all people in their street. They decided to give the residents of each house on the street, one kilogram of sweets. So they need as many kilos of sweets as there are homes on their street. The street, where the Lou Who family lives can be represented as n consecutive sections of equal length. You can go from any section to a neighbouring one in one unit of time. Each of the sections is one of three types: an empty piece of land, a house or a shop. Cindy Lou and her family can buy sweets in a shop, but no more than one kilogram of sweets in one shop (the vendors care about the residents of Whoville not to overeat on sweets). After the Lou Who family leave their home, they will be on the first section of the road. To get to this section of the road, they also require one unit of time. We can assume that Cindy and her mom and dad can carry an unlimited number of kilograms of sweets. Every time they are on a house section, they can give a kilogram of sweets to the inhabitants of the house, or they can simply move to another section. If the family have already given sweets to the residents of a house, they can't do it again. Similarly, if they are on the shop section, they can either buy a kilo of sweets in it or skip this shop. If they've bought a kilo of sweets in a shop, the seller of the shop remembered them and the won't sell them a single candy if they come again. The time to buy and give sweets can be neglected. The Lou Whos do not want the people of any house to remain without food. The Lou Whos want to spend no more than t time units of time to give out sweets, as they really want to have enough time to prepare for the Christmas celebration. In order to have time to give all the sweets, they may have to initially bring additional k kilos of sweets. Cindy Lou wants to know the minimum number of k kilos of sweets they need to take with them, to have time to give sweets to the residents of each house in their street. Your task is to write a program that will determine the minimum possible value of k. Input The first line of the input contains two space-separated integers n and t (2 ≀ n ≀ 5Β·105, 1 ≀ t ≀ 109). The second line of the input contains n characters, the i-th of them equals "H" (if the i-th segment contains a house), "S" (if the i-th segment contains a shop) or "." (if the i-th segment doesn't contain a house or a shop). It is guaranteed that there is at least one segment with a house. Output If there isn't a single value of k that makes it possible to give sweets to everybody in at most t units of time, print in a single line "-1" (without the quotes). Otherwise, print on a single line the minimum possible value of k. Examples Input 6 6 HSHSHS Output 1 Input 14 100 ...HHHSSS...SH Output 0 Input 23 50 HHSS.......SSHHHHHHHHHH Output 8 Note In the first example, there are as many stores, as houses. If the family do not take a single kilo of sweets from home, in order to treat the inhabitants of the first house, they will need to make at least one step back, and they have absolutely no time for it. If they take one kilogram of sweets, they won't need to go back. In the second example, the number of shops is equal to the number of houses and plenty of time. Available at all stores passing out candy in one direction and give them when passing in the opposite direction. In the third example, the shops on the street are fewer than houses. The Lou Whos have to take the missing number of kilograms of sweets with them from home. Submitted Solution: ``` def check(n, casas): #print('n:',n) global T,N,street current = n time = T need = 0 last_house = 0 for ind, i in enumerate(street): time -= 1 if i == 'S': current += 1 elif i == 'H': need += 1 if need == 1: last_house = ind if need > 0 and current >= need: #print('p',time, ind-last_house) current -= need casas -= need need = 0 if casas > 0: if (ind-last_house)*2 >= N-last_house-1: time -= N-last_house-1 + N-ind-1 return time >= 0 time -= (ind-last_house)*2 else: time -= ind-last_house #print('lugar:',i,ind,current, time, need, last_house) if casas == 0: break #print(time) return time >= 0 and casas == 0 N,T = [int(i) for i in input().split()] street = input().rstrip('.') N = len(street) C = street.count('H') S = street.count('S') l = C-S r = C #print(N, C) while l < r: mid = (l+r)//2 if check(mid, C): r = mid else: l = mid + 1 print(l if l < 500005 else -1) ``` No
103,962
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For he knew every Who down in Whoville beneath, Was busy now, hanging a mistletoe wreath. "And they're hanging their stockings!" he snarled with a sneer, "Tomorrow is Christmas! It's practically here!" Dr. Suess, How The Grinch Stole Christmas Christmas celebrations are coming to Whoville. Cindy Lou Who and her parents Lou Lou Who and Betty Lou Who decided to give sweets to all people in their street. They decided to give the residents of each house on the street, one kilogram of sweets. So they need as many kilos of sweets as there are homes on their street. The street, where the Lou Who family lives can be represented as n consecutive sections of equal length. You can go from any section to a neighbouring one in one unit of time. Each of the sections is one of three types: an empty piece of land, a house or a shop. Cindy Lou and her family can buy sweets in a shop, but no more than one kilogram of sweets in one shop (the vendors care about the residents of Whoville not to overeat on sweets). After the Lou Who family leave their home, they will be on the first section of the road. To get to this section of the road, they also require one unit of time. We can assume that Cindy and her mom and dad can carry an unlimited number of kilograms of sweets. Every time they are on a house section, they can give a kilogram of sweets to the inhabitants of the house, or they can simply move to another section. If the family have already given sweets to the residents of a house, they can't do it again. Similarly, if they are on the shop section, they can either buy a kilo of sweets in it or skip this shop. If they've bought a kilo of sweets in a shop, the seller of the shop remembered them and the won't sell them a single candy if they come again. The time to buy and give sweets can be neglected. The Lou Whos do not want the people of any house to remain without food. The Lou Whos want to spend no more than t time units of time to give out sweets, as they really want to have enough time to prepare for the Christmas celebration. In order to have time to give all the sweets, they may have to initially bring additional k kilos of sweets. Cindy Lou wants to know the minimum number of k kilos of sweets they need to take with them, to have time to give sweets to the residents of each house in their street. Your task is to write a program that will determine the minimum possible value of k. Input The first line of the input contains two space-separated integers n and t (2 ≀ n ≀ 5Β·105, 1 ≀ t ≀ 109). The second line of the input contains n characters, the i-th of them equals "H" (if the i-th segment contains a house), "S" (if the i-th segment contains a shop) or "." (if the i-th segment doesn't contain a house or a shop). It is guaranteed that there is at least one segment with a house. Output If there isn't a single value of k that makes it possible to give sweets to everybody in at most t units of time, print in a single line "-1" (without the quotes). Otherwise, print on a single line the minimum possible value of k. Examples Input 6 6 HSHSHS Output 1 Input 14 100 ...HHHSSS...SH Output 0 Input 23 50 HHSS.......SSHHHHHHHHHH Output 8 Note In the first example, there are as many stores, as houses. If the family do not take a single kilo of sweets from home, in order to treat the inhabitants of the first house, they will need to make at least one step back, and they have absolutely no time for it. If they take one kilogram of sweets, they won't need to go back. In the second example, the number of shops is equal to the number of houses and plenty of time. Available at all stores passing out candy in one direction and give them when passing in the opposite direction. In the third example, the shops on the street are fewer than houses. The Lou Whos have to take the missing number of kilograms of sweets with them from home. Submitted Solution: ``` def check(n, casas): global T current = n time = T + 1 need = 0 walk = 0 last_house = 0 for ind, i in enumerate(street): time -= 1 if i == 'S': current += 1 elif i == 'H': need += 1 if need == 1: last_house = ind if need > 0 and current >= need: #print(time, ind-last_house) current -= need casas -= need walk = 0 need = 0 if ind > last_house: time -= (ind-last_house) * 2 if casas == 0: time += 1 #print('lugar:',i,current, time, need, walk) if casas == 0: break #print(T-time) return time > 0 and casas == 0 N,T = [int(i) for i in input().split()] street = input() C = street.count('H') l = 0 r = 500005 while l < r: mid = (l+r)//2 if check(mid, C): r = mid else: l = mid + 1 print(l if l < 500005 else -1) ``` No
103,963
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For he knew every Who down in Whoville beneath, Was busy now, hanging a mistletoe wreath. "And they're hanging their stockings!" he snarled with a sneer, "Tomorrow is Christmas! It's practically here!" Dr. Suess, How The Grinch Stole Christmas Christmas celebrations are coming to Whoville. Cindy Lou Who and her parents Lou Lou Who and Betty Lou Who decided to give sweets to all people in their street. They decided to give the residents of each house on the street, one kilogram of sweets. So they need as many kilos of sweets as there are homes on their street. The street, where the Lou Who family lives can be represented as n consecutive sections of equal length. You can go from any section to a neighbouring one in one unit of time. Each of the sections is one of three types: an empty piece of land, a house or a shop. Cindy Lou and her family can buy sweets in a shop, but no more than one kilogram of sweets in one shop (the vendors care about the residents of Whoville not to overeat on sweets). After the Lou Who family leave their home, they will be on the first section of the road. To get to this section of the road, they also require one unit of time. We can assume that Cindy and her mom and dad can carry an unlimited number of kilograms of sweets. Every time they are on a house section, they can give a kilogram of sweets to the inhabitants of the house, or they can simply move to another section. If the family have already given sweets to the residents of a house, they can't do it again. Similarly, if they are on the shop section, they can either buy a kilo of sweets in it or skip this shop. If they've bought a kilo of sweets in a shop, the seller of the shop remembered them and the won't sell them a single candy if they come again. The time to buy and give sweets can be neglected. The Lou Whos do not want the people of any house to remain without food. The Lou Whos want to spend no more than t time units of time to give out sweets, as they really want to have enough time to prepare for the Christmas celebration. In order to have time to give all the sweets, they may have to initially bring additional k kilos of sweets. Cindy Lou wants to know the minimum number of k kilos of sweets they need to take with them, to have time to give sweets to the residents of each house in their street. Your task is to write a program that will determine the minimum possible value of k. Input The first line of the input contains two space-separated integers n and t (2 ≀ n ≀ 5Β·105, 1 ≀ t ≀ 109). The second line of the input contains n characters, the i-th of them equals "H" (if the i-th segment contains a house), "S" (if the i-th segment contains a shop) or "." (if the i-th segment doesn't contain a house or a shop). It is guaranteed that there is at least one segment with a house. Output If there isn't a single value of k that makes it possible to give sweets to everybody in at most t units of time, print in a single line "-1" (without the quotes). Otherwise, print on a single line the minimum possible value of k. Examples Input 6 6 HSHSHS Output 1 Input 14 100 ...HHHSSS...SH Output 0 Input 23 50 HHSS.......SSHHHHHHHHHH Output 8 Note In the first example, there are as many stores, as houses. If the family do not take a single kilo of sweets from home, in order to treat the inhabitants of the first house, they will need to make at least one step back, and they have absolutely no time for it. If they take one kilogram of sweets, they won't need to go back. In the second example, the number of shops is equal to the number of houses and plenty of time. Available at all stores passing out candy in one direction and give them when passing in the opposite direction. In the third example, the shops on the street are fewer than houses. The Lou Whos have to take the missing number of kilograms of sweets with them from home. Submitted Solution: ``` def check(n, casas): #print('n:',n) global T,N,street current = n time = T need = 0 last_house = 0 for ind, i in enumerate(street): time -= 1 if i == 'S': current += 1 elif i == 'H': need += 1 if need == 1: last_house = ind if need > 0 and current >= need: #print('p',time, ind-last_house) current -= need casas -= need need = 0 if casas > 0: if (ind-last_house)*2 >= N-last_house-1: time -= N-last_house-1 + N-ind-1 return time >= 0 time -= (ind-last_house)*2 else: time -= ind-last_house #print('lugar:',i,ind,current, time, need, last_house) if casas == 0: break #print(time) return time >= 0 and casas == 0 N,T = [int(i) for i in input().split()] street = input().rstrip('.') N = len(street) C = street.count('H') S = street.count('S') l = C-S r = 500005 #print(N, C) while l < r: mid = (l+r)//2 if check(mid, C): r = mid else: l = mid + 1 print(l if l < 500005 else -1) ``` No
103,964
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For he knew every Who down in Whoville beneath, Was busy now, hanging a mistletoe wreath. "And they're hanging their stockings!" he snarled with a sneer, "Tomorrow is Christmas! It's practically here!" Dr. Suess, How The Grinch Stole Christmas Christmas celebrations are coming to Whoville. Cindy Lou Who and her parents Lou Lou Who and Betty Lou Who decided to give sweets to all people in their street. They decided to give the residents of each house on the street, one kilogram of sweets. So they need as many kilos of sweets as there are homes on their street. The street, where the Lou Who family lives can be represented as n consecutive sections of equal length. You can go from any section to a neighbouring one in one unit of time. Each of the sections is one of three types: an empty piece of land, a house or a shop. Cindy Lou and her family can buy sweets in a shop, but no more than one kilogram of sweets in one shop (the vendors care about the residents of Whoville not to overeat on sweets). After the Lou Who family leave their home, they will be on the first section of the road. To get to this section of the road, they also require one unit of time. We can assume that Cindy and her mom and dad can carry an unlimited number of kilograms of sweets. Every time they are on a house section, they can give a kilogram of sweets to the inhabitants of the house, or they can simply move to another section. If the family have already given sweets to the residents of a house, they can't do it again. Similarly, if they are on the shop section, they can either buy a kilo of sweets in it or skip this shop. If they've bought a kilo of sweets in a shop, the seller of the shop remembered them and the won't sell them a single candy if they come again. The time to buy and give sweets can be neglected. The Lou Whos do not want the people of any house to remain without food. The Lou Whos want to spend no more than t time units of time to give out sweets, as they really want to have enough time to prepare for the Christmas celebration. In order to have time to give all the sweets, they may have to initially bring additional k kilos of sweets. Cindy Lou wants to know the minimum number of k kilos of sweets they need to take with them, to have time to give sweets to the residents of each house in their street. Your task is to write a program that will determine the minimum possible value of k. Input The first line of the input contains two space-separated integers n and t (2 ≀ n ≀ 5Β·105, 1 ≀ t ≀ 109). The second line of the input contains n characters, the i-th of them equals "H" (if the i-th segment contains a house), "S" (if the i-th segment contains a shop) or "." (if the i-th segment doesn't contain a house or a shop). It is guaranteed that there is at least one segment with a house. Output If there isn't a single value of k that makes it possible to give sweets to everybody in at most t units of time, print in a single line "-1" (without the quotes). Otherwise, print on a single line the minimum possible value of k. Examples Input 6 6 HSHSHS Output 1 Input 14 100 ...HHHSSS...SH Output 0 Input 23 50 HHSS.......SSHHHHHHHHHH Output 8 Note In the first example, there are as many stores, as houses. If the family do not take a single kilo of sweets from home, in order to treat the inhabitants of the first house, they will need to make at least one step back, and they have absolutely no time for it. If they take one kilogram of sweets, they won't need to go back. In the second example, the number of shops is equal to the number of houses and plenty of time. Available at all stores passing out candy in one direction and give them when passing in the opposite direction. In the third example, the shops on the street are fewer than houses. The Lou Whos have to take the missing number of kilograms of sweets with them from home. Submitted Solution: ``` def check(n, casas): #print('n:',n) global T,N current = n time = T need = 0 last_house = 0 for ind, i in enumerate(street): time -= 1 if i == 'S': current += 1 elif i == 'H': need += 1 if need == 1: last_house = ind if need > 0 and current >= need: #print('p',time, ind-last_house) current -= need casas -= need need = 0 if casas > 0: if (ind-last_house)*2 >= N-last_house-1: time -= N-last_house-1 + N-ind-1 casas = 0 break time -= (ind-last_house)*2 else: time -= ind-last_house #print('lugar:',i,ind,current, time, need, last_house) if casas == 0: break #print(time) return time >= 0 and casas == 0 N,T = [int(i) for i in input().split()] street = input().rstrip('.') N = len(street) C = street.count('H') l = 0 r = 500005 #print(N, C) while l < r: mid = (l+r)//2 if check(mid, C): r = mid else: l = mid + 1 print(l if l < 500005 else -1) ``` No
103,965
Provide tags and a correct Python 3 solution for this coding contest problem. Yaroslav thinks that two strings s and w, consisting of digits and having length n are non-comparable if there are two numbers, i and j (1 ≀ i, j ≀ n), such that si > wi and sj < wj. Here sign si represents the i-th digit of string s, similarly, wj represents the j-th digit of string w. A string's template is a string that consists of digits and question marks ("?"). Yaroslav has two string templates, each of them has length n. Yaroslav wants to count the number of ways to replace all question marks by some integers in both templates, so as to make the resulting strings incomparable. Note that the obtained strings can contain leading zeroes and that distinct question marks can be replaced by distinct or the same integers. Help Yaroslav, calculate the remainder after dividing the described number of ways by 1000000007 (109 + 7). Input The first line contains integer n (1 ≀ n ≀ 105) β€” the length of both templates. The second line contains the first template β€” a string that consists of digits and characters "?". The string's length equals n. The third line contains the second template in the same format. Output In a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7). Examples Input 2 90 09 Output 1 Input 2 11 55 Output 0 Input 5 ????? ????? Output 993531194 Note The first test contains no question marks and both strings are incomparable, so the answer is 1. The second test has no question marks, but the given strings are comparable, so the answer is 0. Tags: combinatorics, dp Correct Solution: ``` from functools import reduce n = int(input()) s1, s2 = str(input()), str(input()) print((10 ** sum([(s1[i] == '?') + (s2[i] == '?') for i in range(n)]) - (not reduce(lambda x, y: x or y, [s1[i] != '?' and s2[i] != '?' and ord(s1[i]) > ord(s2[i]) for i in range(n)], False)) * reduce(lambda x, y: (x * y) % 1000000007, [55 if s1[i] == '?' and s2[i] == '?' else (ord(s2[i]) - ord('0') + 1) if s1[i] == '?' else (10 - ord(s1[i]) + ord('0')) if s2[i] == '?' else 1 for i in range(n)], 1) - (not reduce(lambda x, y: x or y, [s1[i] != '?' and s2[i] != '?' and ord(s1[i]) < ord(s2[i]) for i in range(n)], False)) * reduce(lambda x, y: (x * y) % 1000000007, [55 if s1[i] == '?' and s2[i] == '?' else (10 - ord(s2[i]) + ord('0')) if s1[i] == '?' else (ord(s1[i]) - ord('0')) + 1 if s2[i] == '?' else 1 for i in range(n)], 1) + (not reduce(lambda x, y: x or y, [s1[i] != '?' and s2[i] != '?' and ord(s1[i]) < ord(s2[i]) for i in range(n)], False) and not reduce(lambda x, y: x or y, [s1[i] != '?' and s2[i] != '?' and ord(s1[i]) > ord(s2[i]) for i in range(n)], False)) * reduce(lambda x, y: (x * y) % 1000000007, [10 if s1[i] == '?' and s2[i] == '?' else 1 for i in range(n)], 1)) % 1000000007) ```
103,966
Provide tags and a correct Python 3 solution for this coding contest problem. Yaroslav thinks that two strings s and w, consisting of digits and having length n are non-comparable if there are two numbers, i and j (1 ≀ i, j ≀ n), such that si > wi and sj < wj. Here sign si represents the i-th digit of string s, similarly, wj represents the j-th digit of string w. A string's template is a string that consists of digits and question marks ("?"). Yaroslav has two string templates, each of them has length n. Yaroslav wants to count the number of ways to replace all question marks by some integers in both templates, so as to make the resulting strings incomparable. Note that the obtained strings can contain leading zeroes and that distinct question marks can be replaced by distinct or the same integers. Help Yaroslav, calculate the remainder after dividing the described number of ways by 1000000007 (109 + 7). Input The first line contains integer n (1 ≀ n ≀ 105) β€” the length of both templates. The second line contains the first template β€” a string that consists of digits and characters "?". The string's length equals n. The third line contains the second template in the same format. Output In a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7). Examples Input 2 90 09 Output 1 Input 2 11 55 Output 0 Input 5 ????? ????? Output 993531194 Note The first test contains no question marks and both strings are incomparable, so the answer is 1. The second test has no question marks, but the given strings are comparable, so the answer is 0. Tags: combinatorics, dp Correct Solution: ``` n = int(input()) C = 10**9+7 a = input() s = input() d = [[0, 0, 0, 1]] for q in range(n): d.append(d[-1][::]) if a[q] != '?' and s[q] != '?': if int(a[q]) < int(s[q]): d[-1][1] = d[-1][3] = 0 d[-1][0] += d[-2][3] d[-1][2] += d[-2][1] elif int(a[q]) > int(s[q]): d[-1][0] = d[-1][3] = 0 d[-1][1] += d[-2][3] d[-1][2] += d[-2][0] elif s[q] != '?': d[-1][2] *= 10 d[-1][0] += d[-2][3] d[-1][1] += d[-2][3] d[-1][0] *= int(s[q])+1 d[-1][1] *= 10-int(s[q]) d[-1][0] -= d[-2][3] d[-1][1] -= d[-2][3] d[-1][2] += d[-2][0]*(9-int(s[q]))+d[-2][1]*int(s[q]) elif a[q] != '?': d[-1][2] *= 10 d[-1][0] += d[-2][3] d[-1][1] += d[-2][3] d[-1][1] *= int(a[q]) + 1 d[-1][0] *= 10 - int(a[q]) d[-1][0] -= d[-2][3] d[-1][1] -= d[-2][3] d[-1][2] += d[-2][1] * (9 - int(a[q])) + d[-2][0] * int(a[q]) else: d[-1][3] *= 10 d[-1][2] *= 100 d[-1][0] *= 55 d[-1][1] *= 55 d[-1][0] += d[-2][3]*45 d[-1][1] += d[-2][3]*45 d[-1][2] += d[-2][0]*45+d[-2][1]*45 d[-1][0] %= C d[-1][1] %= C d[-1][2] %= C d[-1][3] %= C print(d[-1][2]) ```
103,967
Provide tags and a correct Python 3 solution for this coding contest problem. Yaroslav thinks that two strings s and w, consisting of digits and having length n are non-comparable if there are two numbers, i and j (1 ≀ i, j ≀ n), such that si > wi and sj < wj. Here sign si represents the i-th digit of string s, similarly, wj represents the j-th digit of string w. A string's template is a string that consists of digits and question marks ("?"). Yaroslav has two string templates, each of them has length n. Yaroslav wants to count the number of ways to replace all question marks by some integers in both templates, so as to make the resulting strings incomparable. Note that the obtained strings can contain leading zeroes and that distinct question marks can be replaced by distinct or the same integers. Help Yaroslav, calculate the remainder after dividing the described number of ways by 1000000007 (109 + 7). Input The first line contains integer n (1 ≀ n ≀ 105) β€” the length of both templates. The second line contains the first template β€” a string that consists of digits and characters "?". The string's length equals n. The third line contains the second template in the same format. Output In a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7). Examples Input 2 90 09 Output 1 Input 2 11 55 Output 0 Input 5 ????? ????? Output 993531194 Note The first test contains no question marks and both strings are incomparable, so the answer is 1. The second test has no question marks, but the given strings are comparable, so the answer is 0. Tags: combinatorics, dp Correct Solution: ``` from functools import reduce n = int(input()) s1, s2 = str(input()), str(input()) b1 = reduce(lambda x, y: x or y, [s1[i] != '?' and s2[i] != '?' and ord(s1[i]) < ord(s2[i]) for i in range(n)], False) b2 = reduce(lambda x, y: x or y, [s1[i] != '?' and s2[i] != '?' and ord(s1[i]) > ord(s2[i]) for i in range(n)], False) s = sum([(s1[i] == '?') + (s2[i] == '?') for i in range(n)]) ans1 = reduce(lambda x, y: (x * y) % 1000000007, [55 if s1[i] == '?' and s2[i] == '?' else (ord(s2[i]) - ord('0') + 1) if s1[i] == '?' else (10 - ord(s1[i]) + ord('0')) if s2[i] == '?' else 1 for i in range(n)], 1) ans2 = reduce(lambda x, y: (x * y) % 1000000007, [55 if s1[i] == '?' and s2[i] == '?' else (10 - ord(s2[i]) + ord('0')) if s1[i] == '?' else (ord(s1[i]) - ord('0')) + 1 if s2[i] == '?' else 1 for i in range(n)], 1) ans3 = reduce(lambda x, y: (x * y) % 1000000007, [10 if s1[i] == '?' and s2[i] == '?' else 1 for i in range(n)], 1) print((10 ** s - (not b2) * ans1 - (not b1) * ans2 + (not b1 and not b2) * ans3) % 1000000007) # Made By Mostafa_Khaled ```
103,968
Provide tags and a correct Python 3 solution for this coding contest problem. Yaroslav thinks that two strings s and w, consisting of digits and having length n are non-comparable if there are two numbers, i and j (1 ≀ i, j ≀ n), such that si > wi and sj < wj. Here sign si represents the i-th digit of string s, similarly, wj represents the j-th digit of string w. A string's template is a string that consists of digits and question marks ("?"). Yaroslav has two string templates, each of them has length n. Yaroslav wants to count the number of ways to replace all question marks by some integers in both templates, so as to make the resulting strings incomparable. Note that the obtained strings can contain leading zeroes and that distinct question marks can be replaced by distinct or the same integers. Help Yaroslav, calculate the remainder after dividing the described number of ways by 1000000007 (109 + 7). Input The first line contains integer n (1 ≀ n ≀ 105) β€” the length of both templates. The second line contains the first template β€” a string that consists of digits and characters "?". The string's length equals n. The third line contains the second template in the same format. Output In a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7). Examples Input 2 90 09 Output 1 Input 2 11 55 Output 0 Input 5 ????? ????? Output 993531194 Note The first test contains no question marks and both strings are incomparable, so the answer is 1. The second test has no question marks, but the given strings are comparable, so the answer is 0. Tags: combinatorics, dp Correct Solution: ``` #!/usr/bin/python3 def build(n, s, t): ans = 1 for i in range(n): if s[i] == '?' and t[i] == '?': ans = (55 * ans) % (10 ** 9 + 7) elif s[i] == '?': ans = ((ord(t[i]) - ord('0') + 1) * ans) % (10 ** 9 + 7) elif t[i] == '?': ans = ((ord('9') - ord(s[i]) + 1) * ans) % (10 ** 9 + 7) return ans n = int(input()) s = input() t = input() sltt = True tlts = True qm = 0 cqm = 0 for i in range(n): if t[i] == '?': qm += 1 if s[i] == '?': qm += 1 if t[i] == '?' and s[i] == '?': cqm += 1 if t[i] == '?' or s[i] == '?': continue if ord(s[i]) < ord(t[i]): tlts = False if ord(t[i]) < ord(s[i]): sltt = False if not sltt and not tlts: print(pow(10, qm, 10 ** 9 + 7)) elif sltt and tlts: print((pow(10, qm, 10 ** 9 + 7) - build(n, s, t) - build(n, t, s) + pow(10, cqm, 10 ** 9 + 7)) % (10 ** 9 + 7)) elif sltt: print((pow(10, qm, 10 ** 9 + 7) - build(n, s, t)) % (10 ** 9 + 7)) else: print((pow(10, qm, 10 ** 9 + 7) - build(n, t, s)) % (10 ** 9 + 7)) ```
103,969
Provide tags and a correct Python 3 solution for this coding contest problem. Yaroslav thinks that two strings s and w, consisting of digits and having length n are non-comparable if there are two numbers, i and j (1 ≀ i, j ≀ n), such that si > wi and sj < wj. Here sign si represents the i-th digit of string s, similarly, wj represents the j-th digit of string w. A string's template is a string that consists of digits and question marks ("?"). Yaroslav has two string templates, each of them has length n. Yaroslav wants to count the number of ways to replace all question marks by some integers in both templates, so as to make the resulting strings incomparable. Note that the obtained strings can contain leading zeroes and that distinct question marks can be replaced by distinct or the same integers. Help Yaroslav, calculate the remainder after dividing the described number of ways by 1000000007 (109 + 7). Input The first line contains integer n (1 ≀ n ≀ 105) β€” the length of both templates. The second line contains the first template β€” a string that consists of digits and characters "?". The string's length equals n. The third line contains the second template in the same format. Output In a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7). Examples Input 2 90 09 Output 1 Input 2 11 55 Output 0 Input 5 ????? ????? Output 993531194 Note The first test contains no question marks and both strings are incomparable, so the answer is 1. The second test has no question marks, but the given strings are comparable, so the answer is 0. Tags: combinatorics, dp Correct Solution: ``` import sys mod = 1000000007 n = int(input()) s1 = input() s2 = input() flag1 = 0 flag2 = 0 for i in range(n): if s1[i] != "?" and s2[i] != "?" and s1[i] > s2[i]: flag1 = 1 if s1[i] != "?" and s2[i] != "?" and s1[i] < s2[i]: flag2 = 1 if flag1 and flag2: ans = 1 for i in range(n): if s1[i] == "?": ans *= 10 ans %= mod for i in range(n): if s2[i] == "?": ans *= 10 ans %= mod print (ans % mod) sys.exit(0) if not(flag1) and not(flag2): ans1 = 1 ans2 = 1 x = 0 al = 1 for i in range(n): if s1[i] == "?" and s2[i] == "?": x += 1 for i in range(n): if s1[i] == "?": al *= 10 al %= mod for i in range(n): if s2[i] == "?": al *= 10 al %= mod for i in range(n): if s1[i] == "?" and s2[i] == "?": ans1 *= 55 ans1 %= mod elif s1[i] == "?": ans1 *= 10 - int(s2[i]) ans1 %= mod elif s2[i] == "?": ans1 *= int(s1[i]) + 1 ans1 %= mod s1, s2 = s2, s1 for i in range(n): if s1[i] == "?" and s2[i] == "?": ans2 *= 55 ans2 %= mod elif s1[i] == "?": ans2 *= 10 - int(s2[i]) ans2 %= mod elif s2[i] == "?": ans2 *= int(s1[i]) + 1 ans2 %= mod y = 1 for i in range(x): y *= 10 y %= mod print ((al - (ans1 + ans2 - y)) % mod) sys.exit(0) if flag2: s1, s2 = s2, s1 ans = 1 al = 1 for i in range(n): if s1[i] == "?": al *= 10 al %= mod for i in range(n): if s2[i] == "?": al *= 10 al %= mod for i in range(n): if s1[i] == "?" and s2[i] == "?": ans *= 55 ans %= mod elif s1[i] == "?": ans *= 10 - int(s2[i]) ans %= mod elif s2[i] == "?": ans *= int(s1[i]) + 1 ans %= mod print ((al - ans) % mod) ```
103,970
Provide tags and a correct Python 3 solution for this coding contest problem. Yaroslav thinks that two strings s and w, consisting of digits and having length n are non-comparable if there are two numbers, i and j (1 ≀ i, j ≀ n), such that si > wi and sj < wj. Here sign si represents the i-th digit of string s, similarly, wj represents the j-th digit of string w. A string's template is a string that consists of digits and question marks ("?"). Yaroslav has two string templates, each of them has length n. Yaroslav wants to count the number of ways to replace all question marks by some integers in both templates, so as to make the resulting strings incomparable. Note that the obtained strings can contain leading zeroes and that distinct question marks can be replaced by distinct or the same integers. Help Yaroslav, calculate the remainder after dividing the described number of ways by 1000000007 (109 + 7). Input The first line contains integer n (1 ≀ n ≀ 105) β€” the length of both templates. The second line contains the first template β€” a string that consists of digits and characters "?". The string's length equals n. The third line contains the second template in the same format. Output In a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7). Examples Input 2 90 09 Output 1 Input 2 11 55 Output 0 Input 5 ????? ????? Output 993531194 Note The first test contains no question marks and both strings are incomparable, so the answer is 1. The second test has no question marks, but the given strings are comparable, so the answer is 0. Tags: combinatorics, dp Correct Solution: ``` from functools import reduce n = int(input()) s1, s2 = str(input()), str(input()) b1 = reduce(lambda x, y: x or y, [s1[i] != '?' and s2[i] != '?' and ord(s1[i]) < ord(s2[i]) for i in range(n)], False) b2 = reduce(lambda x, y: x or y, [s1[i] != '?' and s2[i] != '?' and ord(s1[i]) > ord(s2[i]) for i in range(n)], False) s = sum([(s1[i] == '?') + (s2[i] == '?') for i in range(n)]) ans1 = reduce(lambda x, y: (x * y) % 1000000007, [55 if s1[i] == '?' and s2[i] == '?' else (ord(s2[i]) - ord('0') + 1) if s1[i] == '?' else (10 - ord(s1[i]) + ord('0')) if s2[i] == '?' else 1 for i in range(n)], 1) ans2 = reduce(lambda x, y: (x * y) % 1000000007, [55 if s1[i] == '?' and s2[i] == '?' else (10 - ord(s2[i]) + ord('0')) if s1[i] == '?' else (ord(s1[i]) - ord('0')) + 1 if s2[i] == '?' else 1 for i in range(n)], 1) ans3 = reduce(lambda x, y: (x * y) % 1000000007, [10 if s1[i] == '?' and s2[i] == '?' else 1 for i in range(n)], 1) print((10 ** s - (not b2) * ans1 - (not b1) * ans2 + (not b1 and not b2) * ans3) % 1000000007) ```
103,971
Provide tags and a correct Python 3 solution for this coding contest problem. Yaroslav thinks that two strings s and w, consisting of digits and having length n are non-comparable if there are two numbers, i and j (1 ≀ i, j ≀ n), such that si > wi and sj < wj. Here sign si represents the i-th digit of string s, similarly, wj represents the j-th digit of string w. A string's template is a string that consists of digits and question marks ("?"). Yaroslav has two string templates, each of them has length n. Yaroslav wants to count the number of ways to replace all question marks by some integers in both templates, so as to make the resulting strings incomparable. Note that the obtained strings can contain leading zeroes and that distinct question marks can be replaced by distinct or the same integers. Help Yaroslav, calculate the remainder after dividing the described number of ways by 1000000007 (109 + 7). Input The first line contains integer n (1 ≀ n ≀ 105) β€” the length of both templates. The second line contains the first template β€” a string that consists of digits and characters "?". The string's length equals n. The third line contains the second template in the same format. Output In a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7). Examples Input 2 90 09 Output 1 Input 2 11 55 Output 0 Input 5 ????? ????? Output 993531194 Note The first test contains no question marks and both strings are incomparable, so the answer is 1. The second test has no question marks, but the given strings are comparable, so the answer is 0. Tags: combinatorics, dp Correct Solution: ``` from functools import reduce n, s1, s2, f1, f2 = int(input()), str(input()), str(input()), lambda x: reduce((lambda a, b: (a * b) % 1000000007), x, 1), lambda x: reduce((lambda a, b: a or b), x, False) print((10 ** sum([(s1[i] == '?') + (s2[i] == '?') for i in range(n)]) - (not f2([s1[i] != '?' and s2[i] != '?' and ord(s1[i]) > ord(s2[i]) for i in range(n)])) * f1([55 if s1[i] == '?' and s2[i] == '?' else (ord(s2[i]) - ord('0') + 1) if s1[i] == '?' else (10 - ord(s1[i]) + ord('0')) if s2[i] == '?' else 1 for i in range(n)]) - (not f2([s1[i] != '?' and s2[i] != '?' and ord(s1[i]) < ord(s2[i]) for i in range(n)])) * f1([55 if s1[i] == '?' and s2[i] == '?' else (10 - ord(s2[i]) + ord('0')) if s1[i] == '?' else (ord(s1[i]) - ord('0')) + 1 if s2[i] == '?' else 1 for i in range(n)]) + (not f2([s1[i] != '?' and s2[i] != '?' and ord(s1[i]) < ord(s2[i]) for i in range(n)]) and not f2([s1[i] != '?' and s2[i] != '?' and ord(s1[i]) > ord(s2[i]) for i in range(n)])) * f1([10 if s1[i] == '?' and s2[i] == '?' else 1 for i in range(n)])) % 1000000007) ```
103,972
Provide tags and a correct Python 3 solution for this coding contest problem. Yaroslav thinks that two strings s and w, consisting of digits and having length n are non-comparable if there are two numbers, i and j (1 ≀ i, j ≀ n), such that si > wi and sj < wj. Here sign si represents the i-th digit of string s, similarly, wj represents the j-th digit of string w. A string's template is a string that consists of digits and question marks ("?"). Yaroslav has two string templates, each of them has length n. Yaroslav wants to count the number of ways to replace all question marks by some integers in both templates, so as to make the resulting strings incomparable. Note that the obtained strings can contain leading zeroes and that distinct question marks can be replaced by distinct or the same integers. Help Yaroslav, calculate the remainder after dividing the described number of ways by 1000000007 (109 + 7). Input The first line contains integer n (1 ≀ n ≀ 105) β€” the length of both templates. The second line contains the first template β€” a string that consists of digits and characters "?". The string's length equals n. The third line contains the second template in the same format. Output In a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7). Examples Input 2 90 09 Output 1 Input 2 11 55 Output 0 Input 5 ????? ????? Output 993531194 Note The first test contains no question marks and both strings are incomparable, so the answer is 1. The second test has no question marks, but the given strings are comparable, so the answer is 0. Tags: combinatorics, dp Correct Solution: ``` n = int(input()) a = input() b = input() mod = int(1e9+7) x, y, z = 1, 1, 1 for i in range(n): if a[i] == '?' and b[i] == '?': x = (x * 55) % mod y = (y * 55) % mod z = (z * 10) % mod elif a[i] == '?': x = (x * (10 - int(b[i]))) % mod y = (y * (int(b[i]) + 1)) % mod elif b[i] == '?': x = (x * (int(a[i]) + 1)) % mod y = (y * (10 - int(a[i]))) % mod else: if int(a[i]) < int(b[i]): x = 0 if int(a[i]) > int(b[i]): y = 0 if a[i] != b[i]: z = 0 res = pow(10, a.count('?') + b.count('?'), mod) print((res - x - y + z) % mod) ```
103,973
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Yaroslav thinks that two strings s and w, consisting of digits and having length n are non-comparable if there are two numbers, i and j (1 ≀ i, j ≀ n), such that si > wi and sj < wj. Here sign si represents the i-th digit of string s, similarly, wj represents the j-th digit of string w. A string's template is a string that consists of digits and question marks ("?"). Yaroslav has two string templates, each of them has length n. Yaroslav wants to count the number of ways to replace all question marks by some integers in both templates, so as to make the resulting strings incomparable. Note that the obtained strings can contain leading zeroes and that distinct question marks can be replaced by distinct or the same integers. Help Yaroslav, calculate the remainder after dividing the described number of ways by 1000000007 (109 + 7). Input The first line contains integer n (1 ≀ n ≀ 105) β€” the length of both templates. The second line contains the first template β€” a string that consists of digits and characters "?". The string's length equals n. The third line contains the second template in the same format. Output In a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7). Examples Input 2 90 09 Output 1 Input 2 11 55 Output 0 Input 5 ????? ????? Output 993531194 Note The first test contains no question marks and both strings are incomparable, so the answer is 1. The second test has no question marks, but the given strings are comparable, so the answer is 0. Submitted Solution: ``` n, s = int(input()), 0 s1, s2 = str(input()), str(input()) b1, b2 = False, False for i in range(n): if s1[i] != '?' and s2[i] != '?': if ord(s1[i]) < ord(s2[i]): b1 = True if ord(s1[i]) > ord(s2[i]): b2 = True s += (s1[i] == '?') + (s2[i] == '?') if b1 and b2: print((10 ** s) % (1000000007)) elif b1: ans = 1 for i in range(n): if s1[i] == '?' and s2[i] == '?': ans = (ans * 55) % 1000000007 elif s1[i] == '?': ans = (ans * (ord(s2[i]) - ord('0') + 1)) % 1000000007 elif s2[i] == '?': ans = (ans * (10 - ord(s1[i]) + ord('0'))) % 1000000007 print((10 ** s - ans) % 1000000007) elif b2: ans = 1 for i in range(n): if s1[i] == '?' and s2[i] == '?': ans = (ans * 55) % 1000000007 elif s1[i] == '?': ans = (ans * (10 - ord(s2[i]) + ord('0'))) % 1000000007 elif s2[i] == '?': ans = (ans * (ord(s1[i]) - ord('0') + 1)) % 1000000007 print((10 ** s - ans) % 1000000007) else: ans1 = 1 for i in range(n): if s1[i] == '?' and s2[i] == '?': ans1 = (ans1 * 55) % 1000000007 elif s1[i] == '?': ans1 = (ans1 * (ord(s2[i]) - ord('0') + 1)) % 1000000007 elif s2[i] == '?': ans1 = (ans1 * (10 - ord(s1[i]) + ord('0'))) % 1000000007 ans2 = 1 for i in range(n): if s1[i] == '?' and s2[i] == '?': ans2 = (ans2 * 55) % 1000000007 elif s1[i] == '?': ans2 = (ans2 * (10 - ord(s2[i]) + ord('0'))) % 1000000007 elif s2[i] == '?': ans2 = (ans2 * (ord(s1[i]) - ord('0') + 1)) % 1000000007 ans3 = 1 for i in range(n): if s1[i] == '?' and s2[i] == '?': ans3 = (ans3 * 10) % 1000000007 print((10 ** s - ans1 - ans2 + ans3) % 1000000007) ``` Yes
103,974
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Yaroslav thinks that two strings s and w, consisting of digits and having length n are non-comparable if there are two numbers, i and j (1 ≀ i, j ≀ n), such that si > wi and sj < wj. Here sign si represents the i-th digit of string s, similarly, wj represents the j-th digit of string w. A string's template is a string that consists of digits and question marks ("?"). Yaroslav has two string templates, each of them has length n. Yaroslav wants to count the number of ways to replace all question marks by some integers in both templates, so as to make the resulting strings incomparable. Note that the obtained strings can contain leading zeroes and that distinct question marks can be replaced by distinct or the same integers. Help Yaroslav, calculate the remainder after dividing the described number of ways by 1000000007 (109 + 7). Input The first line contains integer n (1 ≀ n ≀ 105) β€” the length of both templates. The second line contains the first template β€” a string that consists of digits and characters "?". The string's length equals n. The third line contains the second template in the same format. Output In a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7). Examples Input 2 90 09 Output 1 Input 2 11 55 Output 0 Input 5 ????? ????? Output 993531194 Note The first test contains no question marks and both strings are incomparable, so the answer is 1. The second test has no question marks, but the given strings are comparable, so the answer is 0. Submitted Solution: ``` from functools import reduce n, s1, s2 = int(input()), str(input()), str(input()) print((10 ** sum([(s1[i] == '?') + (s2[i] == '?') for i in range(n)]) - (not reduce(lambda x, y: x or y, [s1[i] != '?' and s2[i] != '?' and ord(s1[i]) > ord(s2[i]) for i in range(n)], False)) * reduce(lambda x, y: (x * y) % 1000000007, [55 if s1[i] == '?' and s2[i] == '?' else (ord(s2[i]) - ord('0') + 1) if s1[i] == '?' else (10 - ord(s1[i]) + ord('0')) if s2[i] == '?' else 1 for i in range(n)], 1) - (not reduce(lambda x, y: x or y, [s1[i] != '?' and s2[i] != '?' and ord(s1[i]) < ord(s2[i]) for i in range(n)], False)) * reduce(lambda x, y: (x * y) % 1000000007, [55 if s1[i] == '?' and s2[i] == '?' else (10 - ord(s2[i]) + ord('0')) if s1[i] == '?' else (ord(s1[i]) - ord('0')) + 1 if s2[i] == '?' else 1 for i in range(n)], 1) + (not reduce(lambda x, y: x or y, [s1[i] != '?' and s2[i] != '?' and ord(s1[i]) < ord(s2[i]) for i in range(n)], False) and not reduce(lambda x, y: x or y, [s1[i] != '?' and s2[i] != '?' and ord(s1[i]) > ord(s2[i]) for i in range(n)], False)) * reduce(lambda x, y: (x * y) % 1000000007, [10 if s1[i] == '?' and s2[i] == '?' else 1 for i in range(n)], 1)) % 1000000007) ``` Yes
103,975
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Yaroslav thinks that two strings s and w, consisting of digits and having length n are non-comparable if there are two numbers, i and j (1 ≀ i, j ≀ n), such that si > wi and sj < wj. Here sign si represents the i-th digit of string s, similarly, wj represents the j-th digit of string w. A string's template is a string that consists of digits and question marks ("?"). Yaroslav has two string templates, each of them has length n. Yaroslav wants to count the number of ways to replace all question marks by some integers in both templates, so as to make the resulting strings incomparable. Note that the obtained strings can contain leading zeroes and that distinct question marks can be replaced by distinct or the same integers. Help Yaroslav, calculate the remainder after dividing the described number of ways by 1000000007 (109 + 7). Input The first line contains integer n (1 ≀ n ≀ 105) β€” the length of both templates. The second line contains the first template β€” a string that consists of digits and characters "?". The string's length equals n. The third line contains the second template in the same format. Output In a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7). Examples Input 2 90 09 Output 1 Input 2 11 55 Output 0 Input 5 ????? ????? Output 993531194 Note The first test contains no question marks and both strings are incomparable, so the answer is 1. The second test has no question marks, but the given strings are comparable, so the answer is 0. Submitted Solution: ``` mod = 1000000007 n = int(input()) s1 = input() s2 = input() ans = 1 tc = 1 for i in range(n): if s1[i] == '?': ans *= 10 ans %= mod if s2[i] == '?': ans *= 10 ans %= mod for i in range(n): if s1[i] != '?' and s2[i] != '?' and s1[i] > s2[i]: break if s1[i] == '?' and s2[i] == '?': tc *= 55 tc %= mod if s1[i] == '?' and s2[i] != '?': tc = tc * (int(s2[i]) + 1) tc %= mod if s1[i] != '?' and s2[i] == '?': tc = tc * (10 - int(s1[i])) tc %= mod if i == n - 1: ans -= tc ans = (ans + mod) % mod tc = 1 for i in range(n): if s1[i] != '?' and s2[i] != '?' and s2[i] > s1[i]: break; if s1[i] == '?' and s2[i] == '?': tc *= 55 tc %= mod if s1[i] != '?' and s2[i] == '?': tc = tc * (int(s1[i]) + 1) tc %= mod if s1[i] == '?' and s2[i] != '?': tc = tc * (10 - int(s2[i])) tc %= mod if i == n - 1: ans -= tc ans = (ans + mod) % mod tc = 1 for i in range(n): if s1[i] != '?' and s2[i] != '?' and s1[i] != s2[i]: break if s1[i] == '?' and s2[i] == '?': tc *= 10 tc %= mod if i == n - 1: ans += tc ans = (ans + mod) % mod print(ans) ``` Yes
103,976
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Yaroslav thinks that two strings s and w, consisting of digits and having length n are non-comparable if there are two numbers, i and j (1 ≀ i, j ≀ n), such that si > wi and sj < wj. Here sign si represents the i-th digit of string s, similarly, wj represents the j-th digit of string w. A string's template is a string that consists of digits and question marks ("?"). Yaroslav has two string templates, each of them has length n. Yaroslav wants to count the number of ways to replace all question marks by some integers in both templates, so as to make the resulting strings incomparable. Note that the obtained strings can contain leading zeroes and that distinct question marks can be replaced by distinct or the same integers. Help Yaroslav, calculate the remainder after dividing the described number of ways by 1000000007 (109 + 7). Input The first line contains integer n (1 ≀ n ≀ 105) β€” the length of both templates. The second line contains the first template β€” a string that consists of digits and characters "?". The string's length equals n. The third line contains the second template in the same format. Output In a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7). Examples Input 2 90 09 Output 1 Input 2 11 55 Output 0 Input 5 ????? ????? Output 993531194 Note The first test contains no question marks and both strings are incomparable, so the answer is 1. The second test has no question marks, but the given strings are comparable, so the answer is 0. Submitted Solution: ``` n, s = int(input()), 0 s1, s2 = str(input()), str(input()) b1, b2 = False, False for i in range(n): if s1[i] != '?' and s2[i] != '?': if ord(s1[i]) < ord(s2[i]): b1 = True if ord(s1[i]) > ord(s2[i]): b2 = True s += (s1[i] == '?') + (s2[i] == '?') ans1, ans2, ans3 = 1, 1, 1 for i in range(n): if s1[i] == '?' and s2[i] == '?': ans1 = (ans1 * 55) % 1000000007 ans2 = (ans2 * 55) % 1000000007 ans3 = (ans3 * 10) % 1000000007 elif s1[i] == '?': ans1 = (ans1 * (ord(s2[i]) - ord('0') + 1)) % 1000000007 ans2 = (ans2 * (10 - ord(s2[i]) + ord('0'))) % 1000000007 elif s2[i] == '?': ans1 = (ans1 * (10 - ord(s1[i]) + ord('0'))) % 1000000007 ans2 = (ans2 * (ord(s1[i]) - ord('0') + 1)) % 1000000007 print((10 ** s - (not b2) * ans1 - (not b1) * ans2 + (not b1 and not b2) * ans3) % 1000000007) ``` Yes
103,977
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Yaroslav thinks that two strings s and w, consisting of digits and having length n are non-comparable if there are two numbers, i and j (1 ≀ i, j ≀ n), such that si > wi and sj < wj. Here sign si represents the i-th digit of string s, similarly, wj represents the j-th digit of string w. A string's template is a string that consists of digits and question marks ("?"). Yaroslav has two string templates, each of them has length n. Yaroslav wants to count the number of ways to replace all question marks by some integers in both templates, so as to make the resulting strings incomparable. Note that the obtained strings can contain leading zeroes and that distinct question marks can be replaced by distinct or the same integers. Help Yaroslav, calculate the remainder after dividing the described number of ways by 1000000007 (109 + 7). Input The first line contains integer n (1 ≀ n ≀ 105) β€” the length of both templates. The second line contains the first template β€” a string that consists of digits and characters "?". The string's length equals n. The third line contains the second template in the same format. Output In a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7). Examples Input 2 90 09 Output 1 Input 2 11 55 Output 0 Input 5 ????? ????? Output 993531194 Note The first test contains no question marks and both strings are incomparable, so the answer is 1. The second test has no question marks, but the given strings are comparable, so the answer is 0. Submitted Solution: ``` #!/usr/bin/python3 def build(n, s, t): ans = 1 for i in range(n): if s[i] == '?' and t[i] == '?': ans = (55 * ans) % (10 ** 9 + 7) elif s[i] == '?': ans = ((ord(t[i]) - ord('0') + 1) * ans) % (10 ** 9 + 7) elif t[i] == '?': ans = ((ord('9') - ord(s[i]) + 1) * ans) % (10 ** 9 + 7) return ans n = int(input()) s = input() t = input() sltt = True tlts = True qm = 0 cqm = 0 for i in range(n): if t[i] == '?': qm += 1 if s[i] == '?': qm += 1 if t[i] == '?' or s[i] == '?': cqm += 1 continue if ord(s[i]) < ord(t[i]): tlts = False if ord(t[i]) < ord(s[i]): sltt = False if not sltt and not tlts: print(pow(10, qm, 10 ** 9 + 7)) elif sltt and tlts: print((pow(10, qm, 10 ** 9 + 7) - build(n, s, t) - build(n, t, s) + pow(10, cqm, 10 ** 9 + 7)) % (10 ** 9 + 7)) elif sltt: print((pow(10, qm, 10 ** 9 + 7) - build(n, s, t)) % (10 ** 9 + 7)) else: print((pow(10, qm, 10 ** 9 + 7) - build(n, t, s)) % (10 ** 9 + 7)) ``` No
103,978
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Yaroslav thinks that two strings s and w, consisting of digits and having length n are non-comparable if there are two numbers, i and j (1 ≀ i, j ≀ n), such that si > wi and sj < wj. Here sign si represents the i-th digit of string s, similarly, wj represents the j-th digit of string w. A string's template is a string that consists of digits and question marks ("?"). Yaroslav has two string templates, each of them has length n. Yaroslav wants to count the number of ways to replace all question marks by some integers in both templates, so as to make the resulting strings incomparable. Note that the obtained strings can contain leading zeroes and that distinct question marks can be replaced by distinct or the same integers. Help Yaroslav, calculate the remainder after dividing the described number of ways by 1000000007 (109 + 7). Input The first line contains integer n (1 ≀ n ≀ 105) β€” the length of both templates. The second line contains the first template β€” a string that consists of digits and characters "?". The string's length equals n. The third line contains the second template in the same format. Output In a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7). Examples Input 2 90 09 Output 1 Input 2 11 55 Output 0 Input 5 ????? ????? Output 993531194 Note The first test contains no question marks and both strings are incomparable, so the answer is 1. The second test has no question marks, but the given strings are comparable, so the answer is 0. Submitted Solution: ``` # not E i, j((si > wi) and (sj < wj)) # forall i, j not(si > wi) or not (sj < wj) # forall i,j (si <= wi or sj >= wj) n = int(input()) s = list(input()) w = list(input()) contS = s.count("?") contW = w.count("?") total = 10 ** (contS + contW) maiorIgual = 1 menorIgual = 1 igual = 1 for i in range(0, n): if (s[i] == '?'): if (w[i] == '?'): maiorIgual *= 55 menorIgual *= 55 igual *= 10 else: maiorIgual *= 10 - int(w[i]) menorIgual *= int(w[i]) + 1 igual *= 1 else: if (w[i] == '?'): maiorIgual *= 10 - int(s[i]) menorIgual *= int(s[i]) + 1 igual *= 1 else: if (s[i] > w[i]): maiorIgual *= 1 menorIgual *= 0 igual *= 0 if (s[i] == w[i]): igual *= 1 maiorIgual *= 1 menorIgual *= 1 if (s[i] < w[i]): maiorIgual *= 0 menorIgual *= 1 igual *= 0 print("Maior ou igual: ", maiorIgual) print("Menor ou igual: ", menorIgual) print("Igual: ", igual) print((total - menorIgual - maiorIgual + igual) % 1000000007) ``` No
103,979
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Yaroslav thinks that two strings s and w, consisting of digits and having length n are non-comparable if there are two numbers, i and j (1 ≀ i, j ≀ n), such that si > wi and sj < wj. Here sign si represents the i-th digit of string s, similarly, wj represents the j-th digit of string w. A string's template is a string that consists of digits and question marks ("?"). Yaroslav has two string templates, each of them has length n. Yaroslav wants to count the number of ways to replace all question marks by some integers in both templates, so as to make the resulting strings incomparable. Note that the obtained strings can contain leading zeroes and that distinct question marks can be replaced by distinct or the same integers. Help Yaroslav, calculate the remainder after dividing the described number of ways by 1000000007 (109 + 7). Input The first line contains integer n (1 ≀ n ≀ 105) β€” the length of both templates. The second line contains the first template β€” a string that consists of digits and characters "?". The string's length equals n. The third line contains the second template in the same format. Output In a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7). Examples Input 2 90 09 Output 1 Input 2 11 55 Output 0 Input 5 ????? ????? Output 993531194 Note The first test contains no question marks and both strings are incomparable, so the answer is 1. The second test has no question marks, but the given strings are comparable, so the answer is 0. Submitted Solution: ``` # not E i, j((si > wi) and (sj < wj)) # forall i, j not(si > wi) or not (sj < wj) # forall i,j (si <= wi or sj >= wj) n = int(input()) s = list(input()) w = list(input()) contS = s.count("?") contW = w.count("?") total = 10 ** (contS + contW) maiorIgual = 1 menorIgual = 1 igual = 1 for i in range(0, n): if (s[i] == '?'): if (w[i] == '?'): maiorIgual *= 55 menorIgual *= 55 igual *= 10 else: maiorIgual *= 10 - int(w[i]) menorIgual *= int(w[i]) + 1 igual *= 1 else: if (w[i] == '?'): maiorIgual = 10 - int(s[i]) menorIgual = int(s[i]) + 1 igual *= 1 else: if (s[i] > w[i]): maiorIgual *= 1 menorIgual *= 0 igual *= 0 if (s[i] == w[i]): igual *= 1 maiorIgual *= 1 menorIgual *= 1 if (s[i] < w[i]): maiorIgual *= 0 menorIgual *= 1 igual *= 0 print((total - menorIgual - maiorIgual + igual) % 1000000007) ``` No
103,980
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Yaroslav thinks that two strings s and w, consisting of digits and having length n are non-comparable if there are two numbers, i and j (1 ≀ i, j ≀ n), such that si > wi and sj < wj. Here sign si represents the i-th digit of string s, similarly, wj represents the j-th digit of string w. A string's template is a string that consists of digits and question marks ("?"). Yaroslav has two string templates, each of them has length n. Yaroslav wants to count the number of ways to replace all question marks by some integers in both templates, so as to make the resulting strings incomparable. Note that the obtained strings can contain leading zeroes and that distinct question marks can be replaced by distinct or the same integers. Help Yaroslav, calculate the remainder after dividing the described number of ways by 1000000007 (109 + 7). Input The first line contains integer n (1 ≀ n ≀ 105) β€” the length of both templates. The second line contains the first template β€” a string that consists of digits and characters "?". The string's length equals n. The third line contains the second template in the same format. Output In a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7). Examples Input 2 90 09 Output 1 Input 2 11 55 Output 0 Input 5 ????? ????? Output 993531194 Note The first test contains no question marks and both strings are incomparable, so the answer is 1. The second test has no question marks, but the given strings are comparable, so the answer is 0. Submitted Solution: ``` mod = 1000000007 n = int(input()) s1 = input() s2 = input() ans = 1 tc = 1 for i in range(n): if s1[i] == '?': ans *= 10 ans %= mod if s2[i] == '?': ans *= 10 ans %= mod for i in range(n): if s1[i] != '?' and s2[i] != '?' and s1[i] > s2[i]: break if s1[i] == '?' and s2[i] == '?': tc *= 55 tc %= mod if s1[i] == '?' and s2[i] != '?': tc = tc * (int(s2[i]) + 1) tc %= mod if i == n - 1: ans -= tc ans = (ans + mod) % mod tc = 1 for i in range(n): if s1[i] != '?' and s2[i] != '?' and s2[i] > s1[i]: break; if s1[i] == '?' and s2[i] == '?': tc *= 55 tc %= mod if s1[i] != '?' and s2[i] == '?': tc = tc * (int(s1[i]) + 1) tc %= mod if s1[i] == '?' and s2[i] != '?': tc = tc * (10 - s2[i]) tc %= mod if i == n - 1: ans -= tc ans = (ans + mod) % mod tc = 1 for i in range(n): if s1[i] != '?' and s2[i] != '?' and s1[i] != s2[i]: break if s1[i] == '?' and s2[i] == '?': tc *= 10 tc %= mod if i == n - 1: ans += tc ans = (ans + mod) % mod print(ans) ``` No
103,981
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2. Your program should handle the queries of the following two types: 1. "1 x y" (x < y) β€” add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. 2. "2 a b" (a β‰  b) β€” answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. Input The first line of the input contains integer n denoting the number of queries, (1 ≀ n ≀ 105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. Output For each query of the second type print "YES" or "NO" on a separate line depending on the answer. Examples Input 5 1 1 5 1 5 11 2 1 2 1 2 9 2 1 2 Output NO YES Tags: data structures Correct Solution: ``` def dfs(G, start, target, path_exists): s = [start] visited = set([]) # if not start in path_exists: # path_exists[start] = set([]) while(s): node = s.pop() if not node in visited: visited.add(node) # path_exists[start].add(node) a, b = G[node] for i, (c, d) in enumerate(G): if i != node: if (c < a < d) or (c < b < d): s.append(i) if i == target: return True if __name__ == "__main__": n = int(input()) G = [] path_exists = {} for _ in range(n): q, a, b = map(int, input().split()) if q == 1: G.append((a, b)) else: a -= 1 b -= 1 if dfs(G, a, b, path_exists): print("YES") else: print("NO") ```
103,982
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2. Your program should handle the queries of the following two types: 1. "1 x y" (x < y) β€” add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. 2. "2 a b" (a β‰  b) β€” answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. Input The first line of the input contains integer n denoting the number of queries, (1 ≀ n ≀ 105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. Output For each query of the second type print "YES" or "NO" on a separate line depending on the answer. Examples Input 5 1 1 5 1 5 11 2 1 2 1 2 9 2 1 2 Output NO YES Tags: data structures Correct Solution: ``` interval = [] nodes = {} n = int(input()) def func(x, y): a, b = x c, d = y return(c < a < d or c < b < d) for i in range(0, n): t, x, y = map(int, input().split()) if(t == 1): #aΓ±adir intervalo xy = (x, y) interval.append(xy) nodes[xy] = [] for i in interval: if func(i, xy): nodes[i].append(xy) if func(xy, i): nodes[xy].append(i) if(t == 2): #revisar si hay path de x a y x -= 1 y -= 1 a = interval[x] b = interval[y] visited = {a} lst = [a] while len(lst) > 0: i = lst[0] lst = lst[1:] for j in nodes[i]: if not j in visited: lst.append(j) visited = visited | {j} if b in visited: print("YES") else: print("NO") ```
103,983
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2. Your program should handle the queries of the following two types: 1. "1 x y" (x < y) β€” add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. 2. "2 a b" (a β‰  b) β€” answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. Input The first line of the input contains integer n denoting the number of queries, (1 ≀ n ≀ 105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. Output For each query of the second type print "YES" or "NO" on a separate line depending on the answer. Examples Input 5 1 1 5 1 5 11 2 1 2 1 2 9 2 1 2 Output NO YES Tags: data structures Correct Solution: ``` from sys import stdin,stdout from collections import defaultdict nmbr=lambda:int(stdin.readline()) lst = lambda: list(map(int, input().split())) def dfs(src,des): global f vis[src]=1 if src==des: f=1 return for neigh in g[src]: if not vis[neigh]: dfs(neigh,des) for _ in range(1):#nmbr(): g=defaultdict(list) l=[] for q in range(nmbr()): qt,u,v=lst() if qt==1: ln=len(l) for i in range(ln): s,e=l[i] if u<e<v or u<s<v: # print(s,e,'->',u,v,'first') g[i] += [ln] # g[ln] += [i] if s<v<e or s<u<e: # print(u,v,'->',s,e,'second') # g[i]+=[ln] g[ln]+=[i] l+=[[u,v]] else: # print(g) # print(l) f=0 vis=[0]*101 dfs(u-1,v-1) if f :print('YES') else:print('NO') # 10 # 1 -311 -186 # 1 -1070 -341 # 1 -1506 -634 # 1 688 1698 # 2 2 4 # 1 70 1908 # 2 1 2 # 2 2 4 # 1 -1053 1327 # 2 5 4 # 20 # 1 1208 1583 # 1 -258 729 # 1 -409 1201 # 1 194 1938 # 1 -958 1575 # 1 -1466 1752 # 2 1 2 # 2 1 2 # 2 6 5 # 1 -1870 1881 # 1 -2002 2749 # 1 -2002 2984 # 1 -2002 3293 # 2 2 4 # 2 8 10 # 2 9 6 # 1 -2002 3572 # 1 -2002 4175 # 1 -2002 4452 # 1 -2002 4605 ```
103,984
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2. Your program should handle the queries of the following two types: 1. "1 x y" (x < y) β€” add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. 2. "2 a b" (a β‰  b) β€” answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. Input The first line of the input contains integer n denoting the number of queries, (1 ≀ n ≀ 105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. Output For each query of the second type print "YES" or "NO" on a separate line depending on the answer. Examples Input 5 1 1 5 1 5 11 2 1 2 1 2 9 2 1 2 Output NO YES Tags: data structures Correct Solution: ``` def to_list(s): return list(map(int, s.split(" "))) def query(q, ranges): start_idx = q[1] - 1 end_idx = q[2] - 1 queue = [start_idx] visited = {} while len(queue) > 0: r = queue.pop(0) visited[r] = True for i in range(0, len(ranges)): if not visited.get(i, False): r_lb = ranges[r][1] r_ub = ranges[r][2] c_lb = ranges[i][1] c_ub = ranges[i][2] if (r_lb < c_ub and r_lb > c_lb) or (r_ub > c_lb and r_ub < c_ub): #print(r_lb, r_ub, c_lb, c_ub) if i == end_idx: print("YES") return else: queue.append(i) print("NO") n = int(input()) ranges = [] queries = [] for _ in range(0, n): request = to_list(input()) if request[0] == 1: ranges.append(request) elif request[0] == 2: query(request, ranges) ```
103,985
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2. Your program should handle the queries of the following two types: 1. "1 x y" (x < y) β€” add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. 2. "2 a b" (a β‰  b) β€” answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. Input The first line of the input contains integer n denoting the number of queries, (1 ≀ n ≀ 105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. Output For each query of the second type print "YES" or "NO" on a separate line depending on the answer. Examples Input 5 1 1 5 1 5 11 2 1 2 1 2 9 2 1 2 Output NO YES Tags: data structures Correct Solution: ``` #------------------------template--------------------------# import os import sys from math import * from collections import * from bisect 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") 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 bfs(adj,s,k): vis={i:False for i in adj} vis[s]=True qu=[s] while(len(qu)!=0): e=qu.pop(0) if(e==k): return True for i in adj[e]: if(vis[i]!=True): qu.append(i) vis[i]=True return False adj={} inter=[] for _ in range(Int()): q,a,b=value() if(q==1): adj[(a,b)]=[] for i in inter: x=i[0] y=i[1] if(a>x and a<y) or (b>x and b<y): adj[(a,b)].append(i) if(x>a and x<b) or (y>a and y<b): adj[i].append((a,b)) inter.append((a,b)) elif(bfs(adj,inter[a-1],inter[b-1])):print("YES") else:print("NO") ```
103,986
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2. Your program should handle the queries of the following two types: 1. "1 x y" (x < y) β€” add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. 2. "2 a b" (a β‰  b) β€” answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. Input The first line of the input contains integer n denoting the number of queries, (1 ≀ n ≀ 105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. Output For each query of the second type print "YES" or "NO" on a separate line depending on the answer. Examples Input 5 1 1 5 1 5 11 2 1 2 1 2 9 2 1 2 Output NO YES Tags: data structures Correct Solution: ``` """ Template written to be used by Python Programmers. Use at your own risk!!!! Owned by enraged(rating - 5 star at CodeChef and Specialist at Codeforces). """ import sys from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf, log from collections import defaultdict as dd, deque, Counter as c from itertools import combinations as comb, permutations as perm from bisect import bisect_left as bl, bisect_right as br, bisect # sys.setrecursionlimit(2*pow(10, 6)) # sys.stdin = open("input.txt", "r") # sys.stdout = open("output.txt", "w") mod = pow(10, 9) + 7 mod2 = 998244353 def data(): return sys.stdin.readline().strip() def out(var): sys.stdout.write(str(var)) def outln(var): sys.stdout.write(str(var)+"\n") def l(): return list(sp()) def sl(): return list(ssp()) def sp(): return map(int, data().split()) def ssp(): return map(str, data().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)] n = int(data()) intervals = dd(list) graph = dd(set) i = 1 for _ in range(n): a, b, c = sp() intervals[i] = [b, c] if a == 1: for j in intervals.keys(): u, v = intervals[j] if u < b < v and u < c < v: graph[i].add(j) elif b < u < c and b < v < c: graph[j].add(i) elif u < b < v or u < c < v or b < u < c or b < v < c: graph[i].add(j) graph[j].add(i) i += 1 else: d = deque() d.append(b) vis = [0] * 101 vis[b] = 1 while d: temp = d.popleft() if temp == c: outln("YES") break for child in graph[temp]: if not vis[child]: d.append(child) vis[child] = 1 else: outln("NO") ```
103,987
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2. Your program should handle the queries of the following two types: 1. "1 x y" (x < y) β€” add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. 2. "2 a b" (a β‰  b) β€” answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. Input The first line of the input contains integer n denoting the number of queries, (1 ≀ n ≀ 105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. Output For each query of the second type print "YES" or "NO" on a separate line depending on the answer. Examples Input 5 1 1 5 1 5 11 2 1 2 1 2 9 2 1 2 Output NO YES Tags: data structures Correct Solution: ``` def dfs(node, destination): if node == destination: return True visited[node] = True for adj in graph[node]: if not visited[adj] and dfs(adj, destination): return True return False n = int(input()) graph = [[] for _ in range(n+1)] intervals = [] for _ in range(n): t, first, second = map(int, input().split()) if t == 1: no = len(intervals) for interval in intervals: if interval[0] < first < interval[1] or interval[0] < second < interval[1]: graph[no].append(interval[2]) if first < interval[0] < second or first < interval[1] < second: graph[interval[2]].append(no) intervals.append((first, second, no)) else: visited = [False] * (n + 1) print("YES" if dfs(first-1, second-1) else "NO") ```
103,988
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2. Your program should handle the queries of the following two types: 1. "1 x y" (x < y) β€” add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. 2. "2 a b" (a β‰  b) β€” answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. Input The first line of the input contains integer n denoting the number of queries, (1 ≀ n ≀ 105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. Output For each query of the second type print "YES" or "NO" on a separate line depending on the answer. Examples Input 5 1 1 5 1 5 11 2 1 2 1 2 9 2 1 2 Output NO YES Tags: data structures Correct Solution: ``` _set, h = [], [] def dfs(a, b, Len, h): if a == b: return True Len[a] = True for x in h[a]: if not Len[x] and dfs(x, b, Len, h): return True return False for i in range(int(input())): q, x, y = map(int, input().split()) if q == 1: _set.append((x, y)) h.append([]) for i, part_set in enumerate(_set): if x in range(part_set[0] + 1, part_set[1]) or y in range(part_set[0] + 1, part_set[1]): h[-1].append(i) if part_set[0] in range(x + 1, y) or part_set[1] in range(x + 1, y): h[i].append(len(_set) - 1) else: print('YES' if dfs(x - 1, y - 1, [False] * len(_set), h) else 'NO') ```
103,989
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2. Your program should handle the queries of the following two types: 1. "1 x y" (x < y) β€” add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. 2. "2 a b" (a β‰  b) β€” answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. Input The first line of the input contains integer n denoting the number of queries, (1 ≀ n ≀ 105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. Output For each query of the second type print "YES" or "NO" on a separate line depending on the answer. Examples Input 5 1 1 5 1 5 11 2 1 2 1 2 9 2 1 2 Output NO YES Submitted Solution: ``` read_line = lambda : map(int,input().split()) n, = read_line() intervals = [] def dfs(start, end): visited = [] stack = [intervals[start]] while stack: v = stack.pop() if v not in visited: visited.append(v) for i in intervals: if i[0] < v[0] < i[1] or i[0] < v[1] < i[1]: stack.extend([i]) if intervals.index(v) == end: return True return False for i in range(n): option, x, y = read_line() if option == 1: intervals.append([x,y]) else: print ("YES" if dfs(x-1, y-1) else "NO") ``` Yes
103,990
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2. Your program should handle the queries of the following two types: 1. "1 x y" (x < y) β€” add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. 2. "2 a b" (a β‰  b) β€” answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. Input The first line of the input contains integer n denoting the number of queries, (1 ≀ n ≀ 105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. Output For each query of the second type print "YES" or "NO" on a separate line depending on the answer. Examples Input 5 1 1 5 1 5 11 2 1 2 1 2 9 2 1 2 Output NO YES Submitted Solution: ``` import collections def update_edges(intervals, edges, new_interval): new_interval_id = len(intervals) for idx, interval in enumerate(intervals): # connect from new -> old if interval[0] < new_interval[0] < interval[1] or interval[0] < new_interval[1] < interval[1]: edges[new_interval_id].append(idx) # connect from old -> new if new_interval[0] < interval[0] < new_interval[1] or new_interval[0] < interval[1] < new_interval[1]: edges[idx].append(new_interval_id) def bfs(edges, start, target): seen = set() q = collections.deque([start]) while len(q) != 0: v = q.popleft() if v in seen: continue if v == target: return "YES" seen.add(v) for nb in edges[v]: q.append(nb) return "NO" def main(): queries = int(input()) edges = collections.defaultdict(list) intervals = [] for _ in range(queries): query, a, b = map(int, input().split(' ')) if query == 1: new_interval = (a, b) update_edges(intervals, edges, new_interval) intervals.append(new_interval) if query == 2: print(bfs(edges, a-1, b-1)) if __name__ == "__main__": main() ``` Yes
103,991
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2. Your program should handle the queries of the following two types: 1. "1 x y" (x < y) β€” add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. 2. "2 a b" (a β‰  b) β€” answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. Input The first line of the input contains integer n denoting the number of queries, (1 ≀ n ≀ 105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. Output For each query of the second type print "YES" or "NO" on a separate line depending on the answer. Examples Input 5 1 1 5 1 5 11 2 1 2 1 2 9 2 1 2 Output NO YES Submitted Solution: ``` class Interval: def __init__(self, a, b): self.interval_a = a self.interval_b = b def can_go(self, interval): return (interval.interval_a < self.interval_a < interval.interval_b) or ( interval.interval_a < self.interval_b < interval.interval_b) intervals = [] matrix = [] def dfs(a, b, visited, matrix): if a == b: return True ans = False visited[a] = True for i in range(len(matrix)): if matrix[a][i] and not visited[i]: ans = ans or dfs(i, b, visited, matrix) return ans for i in range(int(input())): t, a, b = list(map(int, input().split())) if t == 1: newInterval = Interval(a, b) intervals.append(newInterval) for row in range(len(matrix)): matrix[row].append(intervals[row].can_go(newInterval)) matrix.append([]) for col in range(len(matrix)): matrix[len(matrix) - 1].append(newInterval.can_go(intervals[col])) if t == 2: visited = [] for i in range(len(intervals)): visited.append(False) if dfs(a - 1, b - 1, visited, matrix): print("YES") else: print("NO") ``` Yes
103,992
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2. Your program should handle the queries of the following two types: 1. "1 x y" (x < y) β€” add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. 2. "2 a b" (a β‰  b) β€” answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. Input The first line of the input contains integer n denoting the number of queries, (1 ≀ n ≀ 105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. Output For each query of the second type print "YES" or "NO" on a separate line depending on the answer. Examples Input 5 1 1 5 1 5 11 2 1 2 1 2 9 2 1 2 Output NO YES Submitted Solution: ``` s, t, i = {}, [], 1 for n in range(int(input())): c, a, b = map(int, input().split()) if c > 1: print('YES' if b in s[a] else 'NO') else: s[i] = [i] for j, (x, y) in enumerate(t, 1): if x < a < y or x < b < y: s[i].extend(s[j]) s[i] = set(s[i]) r = [j for j, (x, y) in enumerate(t, 1) if a < x < b or a < y < b] for j in range(1, len(t) + 1): if any(k in s[j] for k in r): s[j].update(s[i]) t.append((a, b)) i += 1 ``` Yes
103,993
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2. Your program should handle the queries of the following two types: 1. "1 x y" (x < y) β€” add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. 2. "2 a b" (a β‰  b) β€” answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. Input The first line of the input contains integer n denoting the number of queries, (1 ≀ n ≀ 105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. Output For each query of the second type print "YES" or "NO" on a separate line depending on the answer. Examples Input 5 1 1 5 1 5 11 2 1 2 1 2 9 2 1 2 Output NO YES Submitted Solution: ``` set_of_intervals = [] def in_interval(w, x, y, z): #print("fdsa{}".format(9 < 11)) if (w > y and w < z) or (x > y and x < z): return True else: return False def step_through(a, b, c, d, temp): for interval in temp: e = int(interval[0]) f = int(interval[1]) if in_interval(a,b,c,d): return True if in_interval(a,b,e,f): #print(interval) temp.remove(interval) return step_through(e,f,c,d,temp) return False n = int(input()) c = 0 for i in range (n): line = input().split() if line[0] == "1": set_of_intervals.append([line[1], line[2]]) else: c += 1 a = int(set_of_intervals[int(line[1]) - 1][0]) b = int(set_of_intervals[int(line[1]) - 1][1]) c = int(set_of_intervals[int(line[2]) - 1][0]) d = int(set_of_intervals[int(line[2]) - 1][1]) temp = set_of_intervals[:] temp.remove([str(a),str(b)]) if( c > 30 ): print(temp) #print(temp) if(step_through(a,b,c,d, temp)): print ("YES") else: print("NO") #print(set_of_intervals) ``` No
103,994
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2. Your program should handle the queries of the following two types: 1. "1 x y" (x < y) β€” add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. 2. "2 a b" (a β‰  b) β€” answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. Input The first line of the input contains integer n denoting the number of queries, (1 ≀ n ≀ 105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. Output For each query of the second type print "YES" or "NO" on a separate line depending on the answer. Examples Input 5 1 1 5 1 5 11 2 1 2 1 2 9 2 1 2 Output NO YES Submitted Solution: ``` n = int(input()) Set = [] for i in range(0, n): q, x, y = map(int, input().split()) if(q == 1): Set.insert(0,[x,y]) elif(q == 2): a = Set[x-1][0] b = Set[x-1][1] c = Set[y-1][0] d = Set[y-1][1] if( (c > (a) > d) and ( c > (b) > d)): print("YES") else: print("NO") ``` No
103,995
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2. Your program should handle the queries of the following two types: 1. "1 x y" (x < y) β€” add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. 2. "2 a b" (a β‰  b) β€” answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. Input The first line of the input contains integer n denoting the number of queries, (1 ≀ n ≀ 105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. Output For each query of the second type print "YES" or "NO" on a separate line depending on the answer. Examples Input 5 1 1 5 1 5 11 2 1 2 1 2 9 2 1 2 Output NO YES Submitted Solution: ``` import sys def ping_pong(): data = [line.rstrip().split() for line in sys.stdin.readlines()] data = [[int(x) for x in row] for row in data] input_1 = data[0] num_queries = input_1[0] v = [] for ir in data[1:]: t = ir[0] a = ir[1] b = ir[2] if (t == 1): if (len(v) == 0): v.append((a,b)) else: spot = True i = 0 while (spot): vertex = v[i] c = vertex[0] d = vertex[1] if ((c < a and a < d) or (c < b and b < d)): spot = False if (i == len(v) -1): v.append((a, b)) else: v.insert(i + 1, (a, b)) i += 1 if (i == len(v)): v.append((a,b)) spot = False else: a = a - 1 b = b - 1 index = a vertex1 = v[a - 1][0] vertex2 = v[a - 1][1] a += 1 while (a != b): vertex = v[a] c = vertex[0] d = vertex[1] if (not((c < vertex1 and vertex1 < d) or (c < vertex2 and vertex2 < d))): print('NO') break vertex1 = c vertex2 = d a += 1 print('YES') ping_pong() ``` No
103,996
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2. Your program should handle the queries of the following two types: 1. "1 x y" (x < y) β€” add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. 2. "2 a b" (a β‰  b) β€” answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. Input The first line of the input contains integer n denoting the number of queries, (1 ≀ n ≀ 105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. Output For each query of the second type print "YES" or "NO" on a separate line depending on the answer. Examples Input 5 1 1 5 1 5 11 2 1 2 1 2 9 2 1 2 Output NO YES Submitted Solution: ``` n = int(input()) g = [] for i in range(0, n): t, x, y = map(int,input().split()) if(x > y): x, y = y, x if(t == 1): g.insert(0,[x,y]) elif(t == 2): a = g[x-1][0] b = g[x-1][1] c = g[y-1][0] d = g[y-1][1] if(c < a < d or c < b < d): print("YES") else: print("NO") ``` No
103,997
Provide tags and a correct Python 3 solution for this coding contest problem. Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)Β·p ≀ n; q β‰₯ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements. Sereja needs to rush to the gym, so he asked to find all the described positions of q. Input The first line contains three integers n, m and p (1 ≀ n, m ≀ 2Β·105, 1 ≀ p ≀ 2Β·105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). The next line contains m integers b1, b2, ..., bm (1 ≀ bi ≀ 109). Output In the first line print the number of valid qs. In the second line, print the valid values in the increasing order. Examples Input 5 3 1 1 2 3 2 1 1 2 3 Output 2 1 3 Input 6 3 2 1 3 2 2 3 1 1 2 3 Output 2 1 2 Tags: binary search, data structures Correct Solution: ``` from collections import Counter n, m, p = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) def try_from(start, a, b): result = [] seq = a[start::p] i = 0 if len(seq) < len(b): return [] counts_a = Counter(seq[:len(b)]) counts_b = Counter(b) if counts_a == counts_b: result.append(start) for i in range(1, len(seq) - len(b) + 1): counts_a[seq[i-1]] -= 1 counts_a[seq[i+len(b) - 1]] += 1 if not counts_a[seq[i-1]]: del counts_a[seq[i-1]] ok = counts_a == counts_b #ok = sorted(seq[i:i+len(b)]) == sorted(b) if ok: result.append(start + p * i) return [x + 1 for x in result] result = [] for start in range(p): result += try_from(start, a, b) print(len(result)) print(' '.join(map(str, sorted(result)))) ```
103,998
Provide tags and a correct Python 3 solution for this coding contest problem. Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)Β·p ≀ n; q β‰₯ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements. Sereja needs to rush to the gym, so he asked to find all the described positions of q. Input The first line contains three integers n, m and p (1 ≀ n, m ≀ 2Β·105, 1 ≀ p ≀ 2Β·105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). The next line contains m integers b1, b2, ..., bm (1 ≀ bi ≀ 109). Output In the first line print the number of valid qs. In the second line, print the valid values in the increasing order. Examples Input 5 3 1 1 2 3 2 1 1 2 3 Output 2 1 3 Input 6 3 2 1 3 2 2 3 1 1 2 3 Output 2 1 2 Tags: binary search, data structures Correct Solution: ``` from collections import Counter n, m, p = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) def try_from(start, a, b): result = [] seq = a[start::p] i = 0 if len(seq) < len(b): return [] counts_a = Counter(seq[:len(b)]) counts_b = Counter(b) if counts_a == counts_b: result.append(start) for i in range(1, len(seq) - len(b) + 1): counts_a[seq[i-1]] -= 1 counts_a[seq[i+len(b) - 1]] += 1 if not counts_a[seq[i-1]]: del counts_a[seq[i-1]] ok = counts_a == counts_b #ok = sorted(seq[i:i+len(b)]) == sorted(b) if ok: result.append(start + p * i) return [x + 1 for x in result] result = [] for start in range(p): result += try_from(start, a, b) print(len(result)) print(' '.join(map(str, sorted(result)))) # Made By Mostafa_Khaled ```
103,999