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. Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated. For example, Zookeeper can use two such operations: AABABBA β†’ AABBA β†’ AAA. Zookeeper wonders what the shortest string he can make is. Can you help him find the length of the shortest string? Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 20000) β€” the number of test cases. The description of the test cases follows. Each of the next t lines contains a single test case each, consisting of a non-empty string s: the string that Zookeeper needs to bomb. It is guaranteed that all symbols of s are either 'A' or 'B'. It is guaranteed that the sum of |s| (length of s) among all test cases does not exceed 2 β‹… 10^5. Output For each test case, print a single integer: the length of the shortest string that Zookeeper can make. Example Input 3 AAA BABA AABBBABBBB Output 3 2 0 Note For the first test case, you can't make any moves, so the answer is 3. For the second test case, one optimal sequence of moves is BABA β†’ BA. So, the answer is 2. For the third test case, one optimal sequence of moves is AABBBABBBB β†’ AABBBABB β†’ AABBBB β†’ ABBB β†’ AB β†’ (empty string). So, the answer is 0. Submitted Solution: ``` import sys input = sys.stdin.readline for _ in range(int(input())): S = list(input())[: -1] b = 0 res = len(S) for i in range(len(S) - 1, -1, -1): b += S[i] == "B" if S[i] == "A" and b > 0: res -= 2 b -= 1 res -= (b // 2) * 2 print(res) ``` Yes
88,600
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated. For example, Zookeeper can use two such operations: AABABBA β†’ AABBA β†’ AAA. Zookeeper wonders what the shortest string he can make is. Can you help him find the length of the shortest string? Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 20000) β€” the number of test cases. The description of the test cases follows. Each of the next t lines contains a single test case each, consisting of a non-empty string s: the string that Zookeeper needs to bomb. It is guaranteed that all symbols of s are either 'A' or 'B'. It is guaranteed that the sum of |s| (length of s) among all test cases does not exceed 2 β‹… 10^5. Output For each test case, print a single integer: the length of the shortest string that Zookeeper can make. Example Input 3 AAA BABA AABBBABBBB Output 3 2 0 Note For the first test case, you can't make any moves, so the answer is 3. For the second test case, one optimal sequence of moves is BABA β†’ BA. So, the answer is 2. For the third test case, one optimal sequence of moves is AABBBABBBB β†’ AABBBABB β†’ AABBBB β†’ ABBB β†’ AB β†’ (empty string). So, the answer is 0. Submitted Solution: ``` import os import math import statistics true = True; false = False; # from collections import defaultdict, deque from functools import reduce is_dev = 'vscode' in os.environ if is_dev: inF = open('in.txt', 'r') outF = open('out.txt', 'w') def ins(): return list(map(int, input_().split(' '))) def inss(): return list(input_().split(' ')) def input_(): if is_dev: return inF.readline()[:-1] else: return input() def ranin(): return range(int(input_())) def print_(data): if is_dev: outF.write(str(data)+'\n') else: print(data) epsilon = 1e-7 def prev_i(ii): return (ii - 1) % n def next_i(ii): return (ii + 1) % n for _ in ranin(): a = input_() if len(a) <= 1: print_(len(a)) continue; cntA = 0 cntB = 0 for i in a: if i == 'A': cntA += 1 else: if cntA > 0: cntA -= 1 else: if cntB > 0: cntB -= 1 else: cntB += 1 print_(cntA+cntB) # aa = [a[0]] # idx = 1 # while idx < len(a): # if a[idx] == 'B': # if aa: # aa.pop() # else: # aa.append(a[idx]) # else: # aa.append(a[idx]) # idx += 1 # print_(len(aa)) if is_dev: outF.close() def compare_file(): print(open('out.txt', 'r').read() == open('outactual.txt', 'r').read()) compare_file() ``` Yes
88,601
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated. For example, Zookeeper can use two such operations: AABABBA β†’ AABBA β†’ AAA. Zookeeper wonders what the shortest string he can make is. Can you help him find the length of the shortest string? Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 20000) β€” the number of test cases. The description of the test cases follows. Each of the next t lines contains a single test case each, consisting of a non-empty string s: the string that Zookeeper needs to bomb. It is guaranteed that all symbols of s are either 'A' or 'B'. It is guaranteed that the sum of |s| (length of s) among all test cases does not exceed 2 β‹… 10^5. Output For each test case, print a single integer: the length of the shortest string that Zookeeper can make. Example Input 3 AAA BABA AABBBABBBB Output 3 2 0 Note For the first test case, you can't make any moves, so the answer is 3. For the second test case, one optimal sequence of moves is BABA β†’ BA. So, the answer is 2. For the third test case, one optimal sequence of moves is AABBBABBBB β†’ AABBBABB β†’ AABBBB β†’ ABBB β†’ AB β†’ (empty string). So, the answer is 0. Submitted Solution: ``` from math import * t=int(input()) while t: t=t-1 #x1,y1,x2,y2=map(int,input().split()) #n=int(input()) #a=list(map(int,input().split())) s=input() aa=0 bb=0 for i in s: if i=='A': aa+=1 elif i=='B' and aa!=0: aa-=1 else: bb+=1 print(bb%2+aa) ``` Yes
88,602
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated. For example, Zookeeper can use two such operations: AABABBA β†’ AABBA β†’ AAA. Zookeeper wonders what the shortest string he can make is. Can you help him find the length of the shortest string? Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 20000) β€” the number of test cases. The description of the test cases follows. Each of the next t lines contains a single test case each, consisting of a non-empty string s: the string that Zookeeper needs to bomb. It is guaranteed that all symbols of s are either 'A' or 'B'. It is guaranteed that the sum of |s| (length of s) among all test cases does not exceed 2 β‹… 10^5. Output For each test case, print a single integer: the length of the shortest string that Zookeeper can make. Example Input 3 AAA BABA AABBBABBBB Output 3 2 0 Note For the first test case, you can't make any moves, so the answer is 3. For the second test case, one optimal sequence of moves is BABA β†’ BA. So, the answer is 2. For the third test case, one optimal sequence of moves is AABBBABBBB β†’ AABBBABB β†’ AABBBB β†’ ABBB β†’ AB β†’ (empty string). So, the answer is 0. Submitted Solution: ``` for _ in range(int(input())) : arr=input() x=arr z='' while arr != z : z=arr arr=arr.replace('AB','') arr=arr.replace('AB','') arr=arr.replace('BB','') arr=arr.replace('BB','') print(len(arr)) ``` No
88,603
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated. For example, Zookeeper can use two such operations: AABABBA β†’ AABBA β†’ AAA. Zookeeper wonders what the shortest string he can make is. Can you help him find the length of the shortest string? Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 20000) β€” the number of test cases. The description of the test cases follows. Each of the next t lines contains a single test case each, consisting of a non-empty string s: the string that Zookeeper needs to bomb. It is guaranteed that all symbols of s are either 'A' or 'B'. It is guaranteed that the sum of |s| (length of s) among all test cases does not exceed 2 β‹… 10^5. Output For each test case, print a single integer: the length of the shortest string that Zookeeper can make. Example Input 3 AAA BABA AABBBABBBB Output 3 2 0 Note For the first test case, you can't make any moves, so the answer is 3. For the second test case, one optimal sequence of moves is BABA β†’ BA. So, the answer is 2. For the third test case, one optimal sequence of moves is AABBBABBBB β†’ AABBBABB β†’ AABBBB β†’ ABBB β†’ AB β†’ (empty string). So, the answer is 0. Submitted Solution: ``` ab = int(input()) for s in range(ab): temp = input() rem = 0 for i in temp: if s == 'B' and rem != 0: rem = rem - 1 else: rem = rem + 1 print(rem) ``` No
88,604
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated. For example, Zookeeper can use two such operations: AABABBA β†’ AABBA β†’ AAA. Zookeeper wonders what the shortest string he can make is. Can you help him find the length of the shortest string? Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 20000) β€” the number of test cases. The description of the test cases follows. Each of the next t lines contains a single test case each, consisting of a non-empty string s: the string that Zookeeper needs to bomb. It is guaranteed that all symbols of s are either 'A' or 'B'. It is guaranteed that the sum of |s| (length of s) among all test cases does not exceed 2 β‹… 10^5. Output For each test case, print a single integer: the length of the shortest string that Zookeeper can make. Example Input 3 AAA BABA AABBBABBBB Output 3 2 0 Note For the first test case, you can't make any moves, so the answer is 3. For the second test case, one optimal sequence of moves is BABA β†’ BA. So, the answer is 2. For the third test case, one optimal sequence of moves is AABBBABBBB β†’ AABBBABB β†’ AABBBB β†’ ABBB β†’ AB β†’ (empty string). So, the answer is 0. Submitted Solution: ``` for t in range(int(input())): i = str(input()) h = 0 while h == 0: if len(i) == 1 or len(i) == 0: break k2 = any([k,v] == ["A","B"] or [k,v] == ["B","B"] for k, v in zip(i, i[1:])) if k2 == True: for k, v in zip(i, i[1:]): if [k,v] == ["A","B"] or [k,v] == ["B","B"]: i = i.replace("{}{}".format(k,v),"") else: h = 1 print(i) ``` No
88,605
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated. For example, Zookeeper can use two such operations: AABABBA β†’ AABBA β†’ AAA. Zookeeper wonders what the shortest string he can make is. Can you help him find the length of the shortest string? Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 20000) β€” the number of test cases. The description of the test cases follows. Each of the next t lines contains a single test case each, consisting of a non-empty string s: the string that Zookeeper needs to bomb. It is guaranteed that all symbols of s are either 'A' or 'B'. It is guaranteed that the sum of |s| (length of s) among all test cases does not exceed 2 β‹… 10^5. Output For each test case, print a single integer: the length of the shortest string that Zookeeper can make. Example Input 3 AAA BABA AABBBABBBB Output 3 2 0 Note For the first test case, you can't make any moves, so the answer is 3. For the second test case, one optimal sequence of moves is BABA β†’ BA. So, the answer is 2. For the third test case, one optimal sequence of moves is AABBBABBBB β†’ AABBBABB β†’ AABBBB β†’ ABBB β†’ AB β†’ (empty string). So, the answer is 0. Submitted Solution: ``` for t in range(int(input())): s = input() if len(set(s)) == 1: print(len(s)) continue while s.find('AB') != -1: s = s.replace('AB', '') while s.find('BB') != -1: s = s.replace('BB', '') print(len(s)) ``` No
88,606
Provide tags and a correct Python 3 solution for this coding contest problem. Ashish has two strings a and b, each of length n, and an integer k. The strings only contain lowercase English letters. He wants to convert string a into string b by performing some (possibly zero) operations on a. In one move, he can either * choose an index i (1 ≀ i≀ n-1) and swap a_i and a_{i+1}, or * choose an index i (1 ≀ i ≀ n-k+1) and if a_i, a_{i+1}, …, a_{i+k-1} are all equal to some character c (c β‰  'z'), replace each one with the next character (c+1), that is, 'a' is replaced by 'b', 'b' is replaced by 'c' and so on. Note that he can perform any number of operations, and the operations can only be performed on string a. Help Ashish determine if it is possible to convert string a into b after performing some (possibly zero) operations on it. Input The first line contains a single integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n (2 ≀ n ≀ 10^6) and k (1 ≀ k ≀ n). The second line of each test case contains the string a of length n consisting of lowercase English letters. The third line of each test case contains the string b of length n consisting of lowercase English letters. It is guaranteed that the sum of values n among all test cases does not exceed 10^6. Output For each test case, print "Yes" if Ashish can convert a into b after some moves, else print "No". You may print the letters of the answer in any case (upper or lower). Example Input 4 3 3 abc bcd 4 2 abba azza 2 1 zz aa 6 2 aaabba ddddcc Output No Yes No Yes Note In the first test case it can be shown that it is impossible to convert a into b. In the second test case, "abba" \xrightarrow{inc} "acca" \xrightarrow{inc} … \xrightarrow{inc} "azza". Here "swap" denotes an operation of the first type, and "inc" denotes an operation of the second type. In the fourth test case, "aaabba" \xrightarrow{swap} "aaabab" \xrightarrow{swap} "aaaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddddbb" \xrightarrow{inc} … \xrightarrow{inc} "ddddcc". Tags: dp, greedy, hashing, implementation, strings Correct Solution: ``` ##############--->>>>> Deepcoder Amit Kumar Bhuyan <<<<<---############## """ Perfection is achieved not when there is nothing more to add, but rather when there is nothing more to take away. """ from __future__ import division, print_function import os,sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip def ii(): return int(input()) def si(): return input() def mi(): return map(int,input().strip().split(" ")) def msi(): return map(str,input().strip().split(" ")) def li(): return list(mi()) def dmain(): sys.setrecursionlimit(1000000) threading.stack_size(1024000) thread = threading.Thread(target=main) thread.start() #from collections import deque, Counter, OrderedDict,defaultdict #from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace #from math import log,sqrt,factorial,cos,tan,sin,radians #from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right #from decimal import * #import threading #from itertools import permutations #Copy 2D list m = [x[:] for x in mark] .. Avoid Using Deepcopy import sys input = sys.stdin.readline scanner = lambda: int(input()) string = lambda: input().rstrip() get_list = lambda: list(read()) read = lambda: map(int, input().split()) get_float = lambda: map(float, input().split()) # from bisect import bisect_left as lower_bound; # from bisect import bisect_right as upper_bound; # from math import ceil, factorial; def ceil(x): if x != int(x): x = int(x) + 1 return x def factorial(x, m): val = 1 while x>0: val = (val * x) % m x -= 1 return val def fact(x): val = 1 while x > 0: val *= x x -= 1 return val # swap_array function def swaparr(arr, a,b): temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; ## gcd function def gcd(a,b): if b == 0: return a; return gcd(b, a % b); ## lcm function def lcm(a, b): return (a * b) // math.gcd(a, b) def is_integer(n): return math.ceil(n) == math.floor(n) ## nCr function efficient using Binomial Cofficient def nCr(n, k): if k > n: return 0 if(k > n - k): k = n - k res = 1 for i in range(k): res = res * (n - i) res = res / (i + 1) return int(res) ## upper bound function code -- such that e in a[:i] e < x; ## prime factorization def primefs(n): ## if n == 1 ## calculating primes primes = {} while(n%2 == 0 and n > 0): primes[2] = primes.get(2, 0) + 1 n = n//2 for i in range(3, int(n**0.5)+2, 2): while(n%i == 0 and n > 0): primes[i] = primes.get(i, 0) + 1 n = n//i if n > 2: primes[n] = primes.get(n, 0) + 1 ## prime factoriazation of n is stored in dictionary ## primes and can be accesed. O(sqrt n) return primes ## MODULAR EXPONENTIATION FUNCTION def power(x, y, p): if y == 0: return 1 res = 1 x = x % p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : res = (res * x) % p y = y >> 1 x = (x * x) % p return res ## DISJOINT SET UNINON FUNCTIONS def swap(a,b): temp = a a = b b = temp return a,b; # find function with path compression included (recursive) # def find(x, link): # if link[x] == x: # return x # link[x] = find(link[x], link); # return link[x]; # find function with path compression (ITERATIVE) def find(x, link): p = x; while( p != link[p]): p = link[p]; while( x != p): nex = link[x]; link[x] = p; x = nex; return p; # the union function which makes union(x,y) # of two nodes x and y def union(x, y, link, size): x = find(x, link) y = find(y, link) if size[x] < size[y]: x,y = swap(x,y) if x != y: size[x] += size[y] link[y] = x ## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES def sieve(n): prime = [True for i in range(n+1)] prime[0], prime[1] = False, False p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n+1, p): prime[i] = False p += 1 return prime # Euler's Toitent Function phi def phi(n) : result = n p = 2 while(p * p<= n) : if (n % p == 0) : while (n % p == 0) : n = n // p result = result * (1.0 - (1.0 / (float) (p))) p = p + 1 if (n > 1) : result = result * (1.0 - (1.0 / (float)(n))) return (int)(result) def is_prime(n): if n == 0: return False if n == 1: return True for i in range(2, int(n ** (1 / 2)) + 1): if not n % i: return False return True def next_prime(n, primes): while primes[n] != True: n += 1 return n #### PRIME FACTORIZATION IN O(log n) using Sieve #### MAXN = int(1e5 + 5) def spf_sieve(): spf[1] = 1; for i in range(2, MAXN): spf[i] = i; for i in range(4, MAXN, 2): spf[i] = 2; for i in range(3, ceil(MAXN ** 0.5), 2): if spf[i] == i: for j in range(i*i, MAXN, i): if spf[j] == j: spf[j] = i; ## function for storing smallest prime factors (spf) in the array ################## un-comment below 2 lines when using factorization ################# spf = [0 for i in range(MAXN)] # spf_sieve(); def factoriazation(x): res = [] for i in range(2, int(x ** 0.5) + 1): while x % i == 0: res.append(i) x //= i if x != 1: res.append(x) return res ## this function is useful for multiple queries only, o/w use ## primefs function above. complexity O(log n) def factors(n): res = [] for i in range(1, int(n ** 0.5) + 1): if n % i == 0: res.append(i) res.append(n // i) return list(set(res)) ## taking integer array input def int_array(): return list(map(int, input().strip().split())); def float_array(): return list(map(float, input().strip().split())); ## taking string array input def str_array(): return input().strip().split(); def binary_search(low, high, w, h, n): while low < high: mid = low + (high - low) // 2 # print(low, mid, high) if check(mid, w, h, n): low = mid + 1 else: high = mid return low ## for checking any conditions def check(val, pair): summ = 0 for x in pair: if x[1] > val: summ += x[0] return summ > val ## for sorting according to second position def sortSecond(val): return val[1] #defining a couple constants MOD = int(1e9)+7; CMOD = 998244353; INF = float('inf'); NINF = -float('inf'); alphs = "abcdefghijklmnopqrstuvwxyz" ################### ---------------- TEMPLATE ENDS HERE ---------------- ################### from itertools import permutations import math import bisect as bis import random import sys import collections as collect import functools as fnt from decimal import Decimal # from sys import stdout # import numpy as np """ _______________ rough work here _______________ n piranhas with sizes a1, a2, .... an scientist of berland state univ want to find if there is dominant piranha the piranha is dominant if it can eat all the other piranhas in the aquarium piranha can eat only one of the adjacent piranhas during one move piranha can do as many moves as it needs piranha i can eat i - 1 """ def solve(): n, k = read() a = list(string()) b = list(string()) freqa = [0] * 26 freqb = [0] * 26 for c in a: freqa[ord(c) - 97] += 1 for c in b: freqb[ord(c) - 97] += 1 rem = 0 for x, y in zip(freqa, freqb): d = x - y if d == 0: continue if abs(d) % k: print("NO") break rem += d // k if rem < 0: print("NO") break else: print("YES") # region fastio # template taken from https://github.com/cheran-senthil/PyRival/blob/master/templates/template.py 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") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": #read() # sys.stdin = open("input.txt", "r") # sys.stdout = open("output.txt", "w") t = scanner() for i in range(t): solve() #dmain() # Comment Read() # fin_time = datetime.now() # print("Execution time (for loop): ", (fin_time-init_time)) ```
88,607
Provide tags and a correct Python 3 solution for this coding contest problem. Ashish has two strings a and b, each of length n, and an integer k. The strings only contain lowercase English letters. He wants to convert string a into string b by performing some (possibly zero) operations on a. In one move, he can either * choose an index i (1 ≀ i≀ n-1) and swap a_i and a_{i+1}, or * choose an index i (1 ≀ i ≀ n-k+1) and if a_i, a_{i+1}, …, a_{i+k-1} are all equal to some character c (c β‰  'z'), replace each one with the next character (c+1), that is, 'a' is replaced by 'b', 'b' is replaced by 'c' and so on. Note that he can perform any number of operations, and the operations can only be performed on string a. Help Ashish determine if it is possible to convert string a into b after performing some (possibly zero) operations on it. Input The first line contains a single integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n (2 ≀ n ≀ 10^6) and k (1 ≀ k ≀ n). The second line of each test case contains the string a of length n consisting of lowercase English letters. The third line of each test case contains the string b of length n consisting of lowercase English letters. It is guaranteed that the sum of values n among all test cases does not exceed 10^6. Output For each test case, print "Yes" if Ashish can convert a into b after some moves, else print "No". You may print the letters of the answer in any case (upper or lower). Example Input 4 3 3 abc bcd 4 2 abba azza 2 1 zz aa 6 2 aaabba ddddcc Output No Yes No Yes Note In the first test case it can be shown that it is impossible to convert a into b. In the second test case, "abba" \xrightarrow{inc} "acca" \xrightarrow{inc} … \xrightarrow{inc} "azza". Here "swap" denotes an operation of the first type, and "inc" denotes an operation of the second type. In the fourth test case, "aaabba" \xrightarrow{swap} "aaabab" \xrightarrow{swap} "aaaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddddbb" \xrightarrow{inc} … \xrightarrow{inc} "ddddcc". Tags: dp, greedy, hashing, implementation, strings Correct Solution: ``` # region fastio import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion t=int(input()) for _ in range(t): n,k=map(int,input().split()) a=input() b=input() alist=[0]*26 blist=[0]*26 for i in range(n): alist[ord(a[i])-97]+=1 blist[ord(b[i])-97]+=1 flag=0 tmp=0 for i in range(26): if (blist[i]-alist[i])%k!=0: flag=1 break tmp+=alist[i]-blist[i] if tmp<0: flag=1 break if flag==0: print('YES') else: print('NO') ```
88,608
Provide tags and a correct Python 3 solution for this coding contest problem. Ashish has two strings a and b, each of length n, and an integer k. The strings only contain lowercase English letters. He wants to convert string a into string b by performing some (possibly zero) operations on a. In one move, he can either * choose an index i (1 ≀ i≀ n-1) and swap a_i and a_{i+1}, or * choose an index i (1 ≀ i ≀ n-k+1) and if a_i, a_{i+1}, …, a_{i+k-1} are all equal to some character c (c β‰  'z'), replace each one with the next character (c+1), that is, 'a' is replaced by 'b', 'b' is replaced by 'c' and so on. Note that he can perform any number of operations, and the operations can only be performed on string a. Help Ashish determine if it is possible to convert string a into b after performing some (possibly zero) operations on it. Input The first line contains a single integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n (2 ≀ n ≀ 10^6) and k (1 ≀ k ≀ n). The second line of each test case contains the string a of length n consisting of lowercase English letters. The third line of each test case contains the string b of length n consisting of lowercase English letters. It is guaranteed that the sum of values n among all test cases does not exceed 10^6. Output For each test case, print "Yes" if Ashish can convert a into b after some moves, else print "No". You may print the letters of the answer in any case (upper or lower). Example Input 4 3 3 abc bcd 4 2 abba azza 2 1 zz aa 6 2 aaabba ddddcc Output No Yes No Yes Note In the first test case it can be shown that it is impossible to convert a into b. In the second test case, "abba" \xrightarrow{inc} "acca" \xrightarrow{inc} … \xrightarrow{inc} "azza". Here "swap" denotes an operation of the first type, and "inc" denotes an operation of the second type. In the fourth test case, "aaabba" \xrightarrow{swap} "aaabab" \xrightarrow{swap} "aaaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddddbb" \xrightarrow{inc} … \xrightarrow{inc} "ddddcc". Tags: dp, greedy, hashing, implementation, strings Correct Solution: ``` input = __import__('sys').stdin.readline def solve(a, b, k, n): deca = {} decb = {} for i in a: if i in deca: deca[i] += 1 else: deca[i] = 1 for i in b: if i in decb: decb[i] += 1 else: decb[i] = 1 for j in decb: if j in deca: if deca[j] < decb[j]: decb[j] -= deca[j] deca[j] = 0 else: deca[j] -= decb[j] decb[j] = 0 for j in decb: if decb[j] % k != 0: return 'NO' for j in deca: if deca[j] % k != 0: return 'NO' q = "" p = "" for i in decb: if decb[i] != 0: q += i for i in deca: if deca[i] != 0: p += i p = sorted(p) q = sorted(q) i = 0 j = 0 while i < len(p) and j < len(q): if p[i] < q[j]: if deca[p[i]] < decb[q[j]]: decb[q[j]] -= deca[p[i]] i += 1 elif deca[p[i]] == decb[q[j]]: i += 1 j += 1 else: deca[p[i]] -= decb[q[j]] j += 1 else: return 'NO' return 'YES' for _ in range(int(input())): n, k = map(int, input().split()) a = list(input()) b = list(input()) print(solve(a, b, k, n)) ```
88,609
Provide tags and a correct Python 3 solution for this coding contest problem. Ashish has two strings a and b, each of length n, and an integer k. The strings only contain lowercase English letters. He wants to convert string a into string b by performing some (possibly zero) operations on a. In one move, he can either * choose an index i (1 ≀ i≀ n-1) and swap a_i and a_{i+1}, or * choose an index i (1 ≀ i ≀ n-k+1) and if a_i, a_{i+1}, …, a_{i+k-1} are all equal to some character c (c β‰  'z'), replace each one with the next character (c+1), that is, 'a' is replaced by 'b', 'b' is replaced by 'c' and so on. Note that he can perform any number of operations, and the operations can only be performed on string a. Help Ashish determine if it is possible to convert string a into b after performing some (possibly zero) operations on it. Input The first line contains a single integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n (2 ≀ n ≀ 10^6) and k (1 ≀ k ≀ n). The second line of each test case contains the string a of length n consisting of lowercase English letters. The third line of each test case contains the string b of length n consisting of lowercase English letters. It is guaranteed that the sum of values n among all test cases does not exceed 10^6. Output For each test case, print "Yes" if Ashish can convert a into b after some moves, else print "No". You may print the letters of the answer in any case (upper or lower). Example Input 4 3 3 abc bcd 4 2 abba azza 2 1 zz aa 6 2 aaabba ddddcc Output No Yes No Yes Note In the first test case it can be shown that it is impossible to convert a into b. In the second test case, "abba" \xrightarrow{inc} "acca" \xrightarrow{inc} … \xrightarrow{inc} "azza". Here "swap" denotes an operation of the first type, and "inc" denotes an operation of the second type. In the fourth test case, "aaabba" \xrightarrow{swap} "aaabab" \xrightarrow{swap} "aaaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddddbb" \xrightarrow{inc} … \xrightarrow{inc} "ddddcc". Tags: dp, greedy, hashing, implementation, strings Correct Solution: ``` import sys input = lambda: sys.stdin.readline().rstrip("\r\n") for _ in range(int(input())): n,k = map(int,input().split()) a = input() b=input() d1=[0]*26 d2=[0]*26 for i1,i2 in zip(a,b): d1[ord(i1)-97]+=1 d2[ord(i2)-97]+=1 ans='YES' for i,v in enumerate(d1): if d1[i]!=d2[i]: if v<d2[i] or (v-d2[i])%k or i==25 : ans='NO' break else: d1[i]=d2[i] d1[i+1]+=v-d2[i] print(ans) ```
88,610
Provide tags and a correct Python 3 solution for this coding contest problem. Ashish has two strings a and b, each of length n, and an integer k. The strings only contain lowercase English letters. He wants to convert string a into string b by performing some (possibly zero) operations on a. In one move, he can either * choose an index i (1 ≀ i≀ n-1) and swap a_i and a_{i+1}, or * choose an index i (1 ≀ i ≀ n-k+1) and if a_i, a_{i+1}, …, a_{i+k-1} are all equal to some character c (c β‰  'z'), replace each one with the next character (c+1), that is, 'a' is replaced by 'b', 'b' is replaced by 'c' and so on. Note that he can perform any number of operations, and the operations can only be performed on string a. Help Ashish determine if it is possible to convert string a into b after performing some (possibly zero) operations on it. Input The first line contains a single integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n (2 ≀ n ≀ 10^6) and k (1 ≀ k ≀ n). The second line of each test case contains the string a of length n consisting of lowercase English letters. The third line of each test case contains the string b of length n consisting of lowercase English letters. It is guaranteed that the sum of values n among all test cases does not exceed 10^6. Output For each test case, print "Yes" if Ashish can convert a into b after some moves, else print "No". You may print the letters of the answer in any case (upper or lower). Example Input 4 3 3 abc bcd 4 2 abba azza 2 1 zz aa 6 2 aaabba ddddcc Output No Yes No Yes Note In the first test case it can be shown that it is impossible to convert a into b. In the second test case, "abba" \xrightarrow{inc} "acca" \xrightarrow{inc} … \xrightarrow{inc} "azza". Here "swap" denotes an operation of the first type, and "inc" denotes an operation of the second type. In the fourth test case, "aaabba" \xrightarrow{swap} "aaabab" \xrightarrow{swap} "aaaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddddbb" \xrightarrow{inc} … \xrightarrow{inc} "ddddcc". Tags: dp, greedy, hashing, implementation, strings Correct Solution: ``` import sys def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for k in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for k in range(c)] for k in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)] def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') INF = 10**19 MOD = 10**9 + 7 EPS = 10**-10 for _ in range(INT()): N, K = MAP() S = [ord(s)-97 for s in input()] T = [ord(s)-97 for s in input()] C1 = [0] * 26 C2 = [0] * 26 for i in range(N): C1[S[i]] += 1 C2[T[i]] += 1 ok = 1 for c in range(26): if C1[c] < C2[c]: ok = 0 break while C1[c] > C2[c]: C1[c] -= K C1[c+1] += K if C1[c] != C2[c]: ok = 0 break if ok: Yes() else: No() ```
88,611
Provide tags and a correct Python 3 solution for this coding contest problem. Ashish has two strings a and b, each of length n, and an integer k. The strings only contain lowercase English letters. He wants to convert string a into string b by performing some (possibly zero) operations on a. In one move, he can either * choose an index i (1 ≀ i≀ n-1) and swap a_i and a_{i+1}, or * choose an index i (1 ≀ i ≀ n-k+1) and if a_i, a_{i+1}, …, a_{i+k-1} are all equal to some character c (c β‰  'z'), replace each one with the next character (c+1), that is, 'a' is replaced by 'b', 'b' is replaced by 'c' and so on. Note that he can perform any number of operations, and the operations can only be performed on string a. Help Ashish determine if it is possible to convert string a into b after performing some (possibly zero) operations on it. Input The first line contains a single integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n (2 ≀ n ≀ 10^6) and k (1 ≀ k ≀ n). The second line of each test case contains the string a of length n consisting of lowercase English letters. The third line of each test case contains the string b of length n consisting of lowercase English letters. It is guaranteed that the sum of values n among all test cases does not exceed 10^6. Output For each test case, print "Yes" if Ashish can convert a into b after some moves, else print "No". You may print the letters of the answer in any case (upper or lower). Example Input 4 3 3 abc bcd 4 2 abba azza 2 1 zz aa 6 2 aaabba ddddcc Output No Yes No Yes Note In the first test case it can be shown that it is impossible to convert a into b. In the second test case, "abba" \xrightarrow{inc} "acca" \xrightarrow{inc} … \xrightarrow{inc} "azza". Here "swap" denotes an operation of the first type, and "inc" denotes an operation of the second type. In the fourth test case, "aaabba" \xrightarrow{swap} "aaabab" \xrightarrow{swap} "aaaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddddbb" \xrightarrow{inc} … \xrightarrow{inc} "ddddcc". Tags: dp, greedy, hashing, implementation, strings Correct Solution: ``` import math from collections import deque from sys import stdin, stdout, setrecursionlimit from string import ascii_letters letters = ascii_letters[:26] from collections import defaultdict #from functools import reduce input = stdin.readline print = stdout.write for _ in range(int(input())): n, k = map(int, input().split()) first = input().strip() second = input().strip() have = defaultdict(int) need = defaultdict(int) for i in first: have[letters.index(i)] += 1 for i in second: need[letters.index(i)] += 1 ost = 0 can = True for i in range(26): if (have[i] + ost) - need[i] < 0 or ((have[i] + ost) - need[i]) % k: can = False break ost = (have[i] + ost) - need[i] if ost > 0: can = False print('Yes\n' if can else 'No\n') ```
88,612
Provide tags and a correct Python 3 solution for this coding contest problem. Ashish has two strings a and b, each of length n, and an integer k. The strings only contain lowercase English letters. He wants to convert string a into string b by performing some (possibly zero) operations on a. In one move, he can either * choose an index i (1 ≀ i≀ n-1) and swap a_i and a_{i+1}, or * choose an index i (1 ≀ i ≀ n-k+1) and if a_i, a_{i+1}, …, a_{i+k-1} are all equal to some character c (c β‰  'z'), replace each one with the next character (c+1), that is, 'a' is replaced by 'b', 'b' is replaced by 'c' and so on. Note that he can perform any number of operations, and the operations can only be performed on string a. Help Ashish determine if it is possible to convert string a into b after performing some (possibly zero) operations on it. Input The first line contains a single integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n (2 ≀ n ≀ 10^6) and k (1 ≀ k ≀ n). The second line of each test case contains the string a of length n consisting of lowercase English letters. The third line of each test case contains the string b of length n consisting of lowercase English letters. It is guaranteed that the sum of values n among all test cases does not exceed 10^6. Output For each test case, print "Yes" if Ashish can convert a into b after some moves, else print "No". You may print the letters of the answer in any case (upper or lower). Example Input 4 3 3 abc bcd 4 2 abba azza 2 1 zz aa 6 2 aaabba ddddcc Output No Yes No Yes Note In the first test case it can be shown that it is impossible to convert a into b. In the second test case, "abba" \xrightarrow{inc} "acca" \xrightarrow{inc} … \xrightarrow{inc} "azza". Here "swap" denotes an operation of the first type, and "inc" denotes an operation of the second type. In the fourth test case, "aaabba" \xrightarrow{swap} "aaabab" \xrightarrow{swap} "aaaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddddbb" \xrightarrow{inc} … \xrightarrow{inc} "ddddcc". Tags: dp, greedy, hashing, implementation, strings Correct Solution: ``` import sys input=sys.stdin.readline t = int(input()) for _ in range(t): n, k = map(int, input().split()) a = input() b = input() c1=[0]*26 c2=[0]*26 for i in range(0,n): c1[ord(a[i])-97]+=1 c2[ord(b[i])-97]+=1 ans="YES" for j in range(0,26): if c1[j]==c2[j]: continue elif c2[j]>c1[j]: ans='NO' break elif (c1[j]-c2[j])%k!=0: ans="NO" break else: c1[j+1]+=c1[j]-c2[j] print(ans) ```
88,613
Provide tags and a correct Python 3 solution for this coding contest problem. Ashish has two strings a and b, each of length n, and an integer k. The strings only contain lowercase English letters. He wants to convert string a into string b by performing some (possibly zero) operations on a. In one move, he can either * choose an index i (1 ≀ i≀ n-1) and swap a_i and a_{i+1}, or * choose an index i (1 ≀ i ≀ n-k+1) and if a_i, a_{i+1}, …, a_{i+k-1} are all equal to some character c (c β‰  'z'), replace each one with the next character (c+1), that is, 'a' is replaced by 'b', 'b' is replaced by 'c' and so on. Note that he can perform any number of operations, and the operations can only be performed on string a. Help Ashish determine if it is possible to convert string a into b after performing some (possibly zero) operations on it. Input The first line contains a single integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n (2 ≀ n ≀ 10^6) and k (1 ≀ k ≀ n). The second line of each test case contains the string a of length n consisting of lowercase English letters. The third line of each test case contains the string b of length n consisting of lowercase English letters. It is guaranteed that the sum of values n among all test cases does not exceed 10^6. Output For each test case, print "Yes" if Ashish can convert a into b after some moves, else print "No". You may print the letters of the answer in any case (upper or lower). Example Input 4 3 3 abc bcd 4 2 abba azza 2 1 zz aa 6 2 aaabba ddddcc Output No Yes No Yes Note In the first test case it can be shown that it is impossible to convert a into b. In the second test case, "abba" \xrightarrow{inc} "acca" \xrightarrow{inc} … \xrightarrow{inc} "azza". Here "swap" denotes an operation of the first type, and "inc" denotes an operation of the second type. In the fourth test case, "aaabba" \xrightarrow{swap} "aaabab" \xrightarrow{swap} "aaaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddddbb" \xrightarrow{inc} … \xrightarrow{inc} "ddddcc". Tags: dp, greedy, hashing, implementation, strings Correct Solution: ``` ''' Auther: ghoshashis545 Ashis Ghosh College: jalpaiguri Govt Enggineering College ''' from os import path from io import BytesIO, IOBase import sys from heapq import heappush,heappop from functools import cmp_to_key as ctk from collections import deque,Counter,defaultdict as dd from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right from itertools import permutations from datetime import datetime from math import ceil,sqrt,log,gcd def ii():return int(input()) def si():return input().rstrip() def mi():return map(int,input().split()) def li():return list(mi()) abc='abcdefghijklmnopqrstuvwxyz' # mod=1000000007 mod=998244353 inf = float("inf") vow=['a','e','i','o','u'] dx,dy=[-1,1,0,0],[0,0,1,-1] def bo(i): return ord(i)-ord('a') file = 1 def ceil(a,b): return (a+b-1)//b # write fastio for getting fastio template. def solve(): for _ in range(ii()): n,k = mi() f1 = [0]*27 f2 = f1[::] a = si() b = si() for i in a: f1[bo(i)]+=1 for i in b: f2[bo(i)]+=1 f = 0 for i in range(26): mnx = min(f1[i],f2[i]) f1[i] -= mnx f2[i] -= mnx if f1[i]%k or f2[i]%k: f = 1 break if f: print('NO') continue for i in range(26): if f1[i] >= f2[i]: f1[i] -= f2[i] f2[i] = 0 f1[i+1] += f1[i] f1[i] = 0 # print(f1,f2) for i in range(26): if f2[i]: f = 1 break print('NO' if f else 'YES') if __name__ =="__main__": if(file): if path.exists('input.txt'): sys.stdin=open('input.txt', 'r') sys.stdout=open('output.txt','w') else: input=sys.stdin.readline solve() ```
88,614
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ashish has two strings a and b, each of length n, and an integer k. The strings only contain lowercase English letters. He wants to convert string a into string b by performing some (possibly zero) operations on a. In one move, he can either * choose an index i (1 ≀ i≀ n-1) and swap a_i and a_{i+1}, or * choose an index i (1 ≀ i ≀ n-k+1) and if a_i, a_{i+1}, …, a_{i+k-1} are all equal to some character c (c β‰  'z'), replace each one with the next character (c+1), that is, 'a' is replaced by 'b', 'b' is replaced by 'c' and so on. Note that he can perform any number of operations, and the operations can only be performed on string a. Help Ashish determine if it is possible to convert string a into b after performing some (possibly zero) operations on it. Input The first line contains a single integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n (2 ≀ n ≀ 10^6) and k (1 ≀ k ≀ n). The second line of each test case contains the string a of length n consisting of lowercase English letters. The third line of each test case contains the string b of length n consisting of lowercase English letters. It is guaranteed that the sum of values n among all test cases does not exceed 10^6. Output For each test case, print "Yes" if Ashish can convert a into b after some moves, else print "No". You may print the letters of the answer in any case (upper or lower). Example Input 4 3 3 abc bcd 4 2 abba azza 2 1 zz aa 6 2 aaabba ddddcc Output No Yes No Yes Note In the first test case it can be shown that it is impossible to convert a into b. In the second test case, "abba" \xrightarrow{inc} "acca" \xrightarrow{inc} … \xrightarrow{inc} "azza". Here "swap" denotes an operation of the first type, and "inc" denotes an operation of the second type. In the fourth test case, "aaabba" \xrightarrow{swap} "aaabab" \xrightarrow{swap} "aaaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddddbb" \xrightarrow{inc} … \xrightarrow{inc} "ddddcc". Submitted Solution: ``` import sys sys.setrecursionlimit(10**5) int1 = lambda x: int(x)-1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.buffer.readline()) def MI(): return map(int, sys.stdin.buffer.readline().split()) def LI(): return list(map(int, sys.stdin.buffer.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def BI(): return sys.stdin.buffer.readline().rstrip() def SI(): return sys.stdin.buffer.readline().rstrip().decode() def cal(s): res=[0]*26 for c in s: res[c-97]+=1 return res def ok(): cnt=0 for c1,c2 in zip(cc1,cc2): d=c1-c2 if d==0:continue if abs(d)%k:return False cnt+=d//k if cnt<0:return False return True for _ in range(II()): n,k=MI() s=BI() t=BI() cc1=cal(s) cc2=cal(t) if ok():print("Yes") else:print("No") ``` Yes
88,615
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ashish has two strings a and b, each of length n, and an integer k. The strings only contain lowercase English letters. He wants to convert string a into string b by performing some (possibly zero) operations on a. In one move, he can either * choose an index i (1 ≀ i≀ n-1) and swap a_i and a_{i+1}, or * choose an index i (1 ≀ i ≀ n-k+1) and if a_i, a_{i+1}, …, a_{i+k-1} are all equal to some character c (c β‰  'z'), replace each one with the next character (c+1), that is, 'a' is replaced by 'b', 'b' is replaced by 'c' and so on. Note that he can perform any number of operations, and the operations can only be performed on string a. Help Ashish determine if it is possible to convert string a into b after performing some (possibly zero) operations on it. Input The first line contains a single integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n (2 ≀ n ≀ 10^6) and k (1 ≀ k ≀ n). The second line of each test case contains the string a of length n consisting of lowercase English letters. The third line of each test case contains the string b of length n consisting of lowercase English letters. It is guaranteed that the sum of values n among all test cases does not exceed 10^6. Output For each test case, print "Yes" if Ashish can convert a into b after some moves, else print "No". You may print the letters of the answer in any case (upper or lower). Example Input 4 3 3 abc bcd 4 2 abba azza 2 1 zz aa 6 2 aaabba ddddcc Output No Yes No Yes Note In the first test case it can be shown that it is impossible to convert a into b. In the second test case, "abba" \xrightarrow{inc} "acca" \xrightarrow{inc} … \xrightarrow{inc} "azza". Here "swap" denotes an operation of the first type, and "inc" denotes an operation of the second type. In the fourth test case, "aaabba" \xrightarrow{swap} "aaabab" \xrightarrow{swap} "aaaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddddbb" \xrightarrow{inc} … \xrightarrow{inc} "ddddcc". Submitted Solution: ``` import sys, math import io, os #data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from bisect import bisect_left as bl, bisect_right as br, insort from heapq import heapify, heappush, heappop from collections import defaultdict as dd, deque, Counter from itertools import permutations,combinations def data(): return sys.stdin.readline().strip() def mdata(): return list(map(int, data().split())) def outl(var) : sys.stdout.write('\n'.join(map(str, var))+'\n') def out(var) : sys.stdout.write(str(var)+'\n') #from decimal import Decimal #from fractions import Fraction sys.setrecursionlimit(100000) INF = float('inf') mod = 998244353 def solve(): n, k = mdata() a = data() b = data() d1 = dd(int) d2 = dd(int) for i in a: d1[i] += 1 for i in b: d2[i] += 1 for i in range(26): c = chr(97 + i) if d1[c] < d2[c] or (d1[c] - d2[c]) % k != 0: return 'No' d1[c] -= d2[c] d1[chr(97+i+1)] += d1[c] return "Yes" for t in range(int(data())): out(solve()) ``` Yes
88,616
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ashish has two strings a and b, each of length n, and an integer k. The strings only contain lowercase English letters. He wants to convert string a into string b by performing some (possibly zero) operations on a. In one move, he can either * choose an index i (1 ≀ i≀ n-1) and swap a_i and a_{i+1}, or * choose an index i (1 ≀ i ≀ n-k+1) and if a_i, a_{i+1}, …, a_{i+k-1} are all equal to some character c (c β‰  'z'), replace each one with the next character (c+1), that is, 'a' is replaced by 'b', 'b' is replaced by 'c' and so on. Note that he can perform any number of operations, and the operations can only be performed on string a. Help Ashish determine if it is possible to convert string a into b after performing some (possibly zero) operations on it. Input The first line contains a single integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n (2 ≀ n ≀ 10^6) and k (1 ≀ k ≀ n). The second line of each test case contains the string a of length n consisting of lowercase English letters. The third line of each test case contains the string b of length n consisting of lowercase English letters. It is guaranteed that the sum of values n among all test cases does not exceed 10^6. Output For each test case, print "Yes" if Ashish can convert a into b after some moves, else print "No". You may print the letters of the answer in any case (upper or lower). Example Input 4 3 3 abc bcd 4 2 abba azza 2 1 zz aa 6 2 aaabba ddddcc Output No Yes No Yes Note In the first test case it can be shown that it is impossible to convert a into b. In the second test case, "abba" \xrightarrow{inc} "acca" \xrightarrow{inc} … \xrightarrow{inc} "azza". Here "swap" denotes an operation of the first type, and "inc" denotes an operation of the second type. In the fourth test case, "aaabba" \xrightarrow{swap} "aaabab" \xrightarrow{swap} "aaaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddddbb" \xrightarrow{inc} … \xrightarrow{inc} "ddddcc". Submitted Solution: ``` from sys import stdin, stdout import sys def get_ints(): return map(int, sys.stdin.readline().strip().split()) def get_string(): return sys.stdin.readline().strip() for _ in range(int(input())): n, k = get_ints() a = get_string() b = get_string() acount = [0] * 26 bcount = [0] * 26 for i in a: acount[ord(i) - ord('a')] += 1 for i in b: bcount[ord(i) - ord('a')] += 1 flag = True for i in range(25): extra = acount[i] - bcount[i] if extra < 0 or extra % k: flag = False break acount[i + 1] += extra if flag: print("Yes") else: print("No") ``` Yes
88,617
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ashish has two strings a and b, each of length n, and an integer k. The strings only contain lowercase English letters. He wants to convert string a into string b by performing some (possibly zero) operations on a. In one move, he can either * choose an index i (1 ≀ i≀ n-1) and swap a_i and a_{i+1}, or * choose an index i (1 ≀ i ≀ n-k+1) and if a_i, a_{i+1}, …, a_{i+k-1} are all equal to some character c (c β‰  'z'), replace each one with the next character (c+1), that is, 'a' is replaced by 'b', 'b' is replaced by 'c' and so on. Note that he can perform any number of operations, and the operations can only be performed on string a. Help Ashish determine if it is possible to convert string a into b after performing some (possibly zero) operations on it. Input The first line contains a single integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n (2 ≀ n ≀ 10^6) and k (1 ≀ k ≀ n). The second line of each test case contains the string a of length n consisting of lowercase English letters. The third line of each test case contains the string b of length n consisting of lowercase English letters. It is guaranteed that the sum of values n among all test cases does not exceed 10^6. Output For each test case, print "Yes" if Ashish can convert a into b after some moves, else print "No". You may print the letters of the answer in any case (upper or lower). Example Input 4 3 3 abc bcd 4 2 abba azza 2 1 zz aa 6 2 aaabba ddddcc Output No Yes No Yes Note In the first test case it can be shown that it is impossible to convert a into b. In the second test case, "abba" \xrightarrow{inc} "acca" \xrightarrow{inc} … \xrightarrow{inc} "azza". Here "swap" denotes an operation of the first type, and "inc" denotes an operation of the second type. In the fourth test case, "aaabba" \xrightarrow{swap} "aaabab" \xrightarrow{swap} "aaaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddddbb" \xrightarrow{inc} … \xrightarrow{inc} "ddddcc". Submitted Solution: ``` #!/usr/bin/env python3 import sys input = sys.stdin.readline from collections import Counter def convert(diff, k): # if min(+diff) < min(-diff): # # print(f'{min(+diff)} < {min(-diff)}') # return 'NO' # +diff: letters in b not in a # -diff: letters in a not in b lena, lenb = 0, 0 # print(diff.keys()) for letter in sorted(diff.keys()): n_letters = diff[letter] # print(f'{letter}: {n_letters}') if n_letters > 0: lenb += n_letters else: lena += abs(n_letters) # lena >= lenb means sorted(a) < sorted(b) if lena < lenb: return 'NO' for key, val in diff.items(): if abs(val) % k != 0: return 'NO' return 'YES' for _ in range(int(input())): n, k = map(int, input().split()) a = Counter(input()[:-1]) b = Counter(input()[:-1]) if a == b: print('YES') continue b.subtract(a) print(convert(b, k)) ``` Yes
88,618
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ashish has two strings a and b, each of length n, and an integer k. The strings only contain lowercase English letters. He wants to convert string a into string b by performing some (possibly zero) operations on a. In one move, he can either * choose an index i (1 ≀ i≀ n-1) and swap a_i and a_{i+1}, or * choose an index i (1 ≀ i ≀ n-k+1) and if a_i, a_{i+1}, …, a_{i+k-1} are all equal to some character c (c β‰  'z'), replace each one with the next character (c+1), that is, 'a' is replaced by 'b', 'b' is replaced by 'c' and so on. Note that he can perform any number of operations, and the operations can only be performed on string a. Help Ashish determine if it is possible to convert string a into b after performing some (possibly zero) operations on it. Input The first line contains a single integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n (2 ≀ n ≀ 10^6) and k (1 ≀ k ≀ n). The second line of each test case contains the string a of length n consisting of lowercase English letters. The third line of each test case contains the string b of length n consisting of lowercase English letters. It is guaranteed that the sum of values n among all test cases does not exceed 10^6. Output For each test case, print "Yes" if Ashish can convert a into b after some moves, else print "No". You may print the letters of the answer in any case (upper or lower). Example Input 4 3 3 abc bcd 4 2 abba azza 2 1 zz aa 6 2 aaabba ddddcc Output No Yes No Yes Note In the first test case it can be shown that it is impossible to convert a into b. In the second test case, "abba" \xrightarrow{inc} "acca" \xrightarrow{inc} … \xrightarrow{inc} "azza". Here "swap" denotes an operation of the first type, and "inc" denotes an operation of the second type. In the fourth test case, "aaabba" \xrightarrow{swap} "aaabab" \xrightarrow{swap} "aaaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddddbb" \xrightarrow{inc} … \xrightarrow{inc} "ddddcc". Submitted Solution: ``` for _ in range(int(input())): n,k=map(int,input().split()) a=list(input()) b=list(input()) d1=dict() mx=0 f=1 for i in range(n): d1[a[i]]=d1.get(a[i],0)+1 d1[b[i]]=d1.get(b[i],0)-1 if(f): s=0 mx=0 for j in d1.values(): s+=j mx=max(mx,j) if(s==0 and mx<k): print("No") else: print("Yes") else: print("No") ``` No
88,619
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ashish has two strings a and b, each of length n, and an integer k. The strings only contain lowercase English letters. He wants to convert string a into string b by performing some (possibly zero) operations on a. In one move, he can either * choose an index i (1 ≀ i≀ n-1) and swap a_i and a_{i+1}, or * choose an index i (1 ≀ i ≀ n-k+1) and if a_i, a_{i+1}, …, a_{i+k-1} are all equal to some character c (c β‰  'z'), replace each one with the next character (c+1), that is, 'a' is replaced by 'b', 'b' is replaced by 'c' and so on. Note that he can perform any number of operations, and the operations can only be performed on string a. Help Ashish determine if it is possible to convert string a into b after performing some (possibly zero) operations on it. Input The first line contains a single integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n (2 ≀ n ≀ 10^6) and k (1 ≀ k ≀ n). The second line of each test case contains the string a of length n consisting of lowercase English letters. The third line of each test case contains the string b of length n consisting of lowercase English letters. It is guaranteed that the sum of values n among all test cases does not exceed 10^6. Output For each test case, print "Yes" if Ashish can convert a into b after some moves, else print "No". You may print the letters of the answer in any case (upper or lower). Example Input 4 3 3 abc bcd 4 2 abba azza 2 1 zz aa 6 2 aaabba ddddcc Output No Yes No Yes Note In the first test case it can be shown that it is impossible to convert a into b. In the second test case, "abba" \xrightarrow{inc} "acca" \xrightarrow{inc} … \xrightarrow{inc} "azza". Here "swap" denotes an operation of the first type, and "inc" denotes an operation of the second type. In the fourth test case, "aaabba" \xrightarrow{swap} "aaabab" \xrightarrow{swap} "aaaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddddbb" \xrightarrow{inc} … \xrightarrow{inc} "ddddcc". Submitted Solution: ``` def countFreq(s): d = {} for x in s: if x not in d: d[x] = 1 else: d[x] += 1 return d T = int(input()) for t in range(T): n, k = map(int, input().split()) a = input() b = input() d1 = countFreq(a) d2 = countFreq(b) l1 = sorted(d1.values()) l2 = sorted(d2.values()) k1 = sorted(d1.keys()) k2 = sorted(d2.keys()) flag = 0 if(l1 != l2): print('No') else: if k not in l1: if (k1 == k2): print('Yes') else: print('No') else: for i in range(len(k1)): if(k1[i] > k2[i]): print('No') flag = 1 break if(flag == 0): print('Yes') ``` No
88,620
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ashish has two strings a and b, each of length n, and an integer k. The strings only contain lowercase English letters. He wants to convert string a into string b by performing some (possibly zero) operations on a. In one move, he can either * choose an index i (1 ≀ i≀ n-1) and swap a_i and a_{i+1}, or * choose an index i (1 ≀ i ≀ n-k+1) and if a_i, a_{i+1}, …, a_{i+k-1} are all equal to some character c (c β‰  'z'), replace each one with the next character (c+1), that is, 'a' is replaced by 'b', 'b' is replaced by 'c' and so on. Note that he can perform any number of operations, and the operations can only be performed on string a. Help Ashish determine if it is possible to convert string a into b after performing some (possibly zero) operations on it. Input The first line contains a single integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n (2 ≀ n ≀ 10^6) and k (1 ≀ k ≀ n). The second line of each test case contains the string a of length n consisting of lowercase English letters. The third line of each test case contains the string b of length n consisting of lowercase English letters. It is guaranteed that the sum of values n among all test cases does not exceed 10^6. Output For each test case, print "Yes" if Ashish can convert a into b after some moves, else print "No". You may print the letters of the answer in any case (upper or lower). Example Input 4 3 3 abc bcd 4 2 abba azza 2 1 zz aa 6 2 aaabba ddddcc Output No Yes No Yes Note In the first test case it can be shown that it is impossible to convert a into b. In the second test case, "abba" \xrightarrow{inc} "acca" \xrightarrow{inc} … \xrightarrow{inc} "azza". Here "swap" denotes an operation of the first type, and "inc" denotes an operation of the second type. In the fourth test case, "aaabba" \xrightarrow{swap} "aaabab" \xrightarrow{swap} "aaaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddddbb" \xrightarrow{inc} … \xrightarrow{inc} "ddddcc". Submitted Solution: ``` from collections import Counter import string import math import sys # sys.setrecursionlimit(10**6) from fractions import Fraction from itertools import product def array_int(): return [int(i) for i in sys.stdin.readline().split()] def vary(arrber_of_variables): if arrber_of_variables==1: return int(sys.stdin.readline()) if arrber_of_variables>=2: return map(int,sys.stdin.readline().split()) def makedict(var): return dict(Counter(var)) # i am noob wanted to be better and trying hard for that def printDivisors(n): divisors=[] # Note that this loop runs till square root i = 1 while i <= math.sqrt(n): if (n % i == 0) : # If divisors are equal, print only one if (n//i == i) : divisors.append(i) else : # Otherwise print both divisors.extend((i,n//i)) i = i + 1 return divisors def countTotalBits(num): binary = bin(num)[2:] return(len(binary)) def isPrime(n): # Corner cases if (n <= 1) : return False if (n <= 3) : return True # This is checked so that we can skip # middle five numbers in below loop if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True mod=10**9+7 # def ncr(n,r): # if n<r: # return 0 # if n==r: # return 1 # numer=fact[n] # # print(numer) # denm=(fact[n-r]*fact[r]) # # print(denm) # return numer*pow(denm,mod-2,mod) # def dfs(node): # global graph,m,cats,count,visited,val # # print(val) # visited[node]=1 # if cats[node]==1: # val+=1 # # print(val) # for i in graph[node]: # if visited[i]==0: # z=dfs(i) # # print(z,i) # count+=z # val-=1 # return 0 # else: # return 1 # fact=[1]*(1001) # c=1 # mod=10**9+7 # for i in range(1,1001): # print(fact) def comp(x): # fact[i]=(fact[i-1]*i)%mod return x[1] def SieveOfEratosthenes(n): # Create a boolean array "prime[0..n]" and initialize # all entries it as true. A value in prime[i] will # finally be false if i is Not a prime, else true. prime = [True for i in range(n+1)] p = 2 while (p * p <= n): # If prime[p] is not changed, then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * p, n+1, p): prime[i] = False p += 1 # Print all prime numbers for p in range(2, n+1): if prime[p]: primes.append(p*p) primes=[] # primes=[] # SieveOfEratosthenes(2*(10**6)) def binary_search(arr, x): low = 0 high = len(arr) - 1 mid = 0 while low <= high: mid = (high + low) // 2 # Check if x is present at mid if arr[mid] < x: low = mid + 1 # If x is greater, ignore left half elif arr[mid] > x: high = mid - 1 # If x is smaller, ignore right half # if val>m: else: return mid # If we reach here, then the element was not present return -1 def lcm(a,b): return (a*b)//math.gcd(a,b) mod=10**9+7 testCases=1 testCases=vary(1) for _ in range(testCases): n,k=vary(2) a=list(input()) b=list(input()) i=0 cog=1 cogu=[] value=-9999 while i<n: if a[i]==b[i]: i+=1 cog=1 value=9999 continue elif i<n-1 and a[i]!=b[i] and a[i+1]==b[i] and b[i+1]==a[i]: a[i+1]=a[i] cog=1 value=9999 i+=2 continue elif a[i]!=b[i]: if value==ord(a[i])-ord(b[i]): cog+=1 if i==n-1: cogu.append(cog) else: if cog==1: value=ord(a[i])-ord(b[i]) i+=1 continue cogu.append(cog) cog=1 i+=1 if a.count('z')>b.count('z'): print('No') else: if k==1: print('Yes') continue for i in cogu: if i%k==0: continue else: print('No') break else: print('Yes') ``` No
88,621
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ashish has two strings a and b, each of length n, and an integer k. The strings only contain lowercase English letters. He wants to convert string a into string b by performing some (possibly zero) operations on a. In one move, he can either * choose an index i (1 ≀ i≀ n-1) and swap a_i and a_{i+1}, or * choose an index i (1 ≀ i ≀ n-k+1) and if a_i, a_{i+1}, …, a_{i+k-1} are all equal to some character c (c β‰  'z'), replace each one with the next character (c+1), that is, 'a' is replaced by 'b', 'b' is replaced by 'c' and so on. Note that he can perform any number of operations, and the operations can only be performed on string a. Help Ashish determine if it is possible to convert string a into b after performing some (possibly zero) operations on it. Input The first line contains a single integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n (2 ≀ n ≀ 10^6) and k (1 ≀ k ≀ n). The second line of each test case contains the string a of length n consisting of lowercase English letters. The third line of each test case contains the string b of length n consisting of lowercase English letters. It is guaranteed that the sum of values n among all test cases does not exceed 10^6. Output For each test case, print "Yes" if Ashish can convert a into b after some moves, else print "No". You may print the letters of the answer in any case (upper or lower). Example Input 4 3 3 abc bcd 4 2 abba azza 2 1 zz aa 6 2 aaabba ddddcc Output No Yes No Yes Note In the first test case it can be shown that it is impossible to convert a into b. In the second test case, "abba" \xrightarrow{inc} "acca" \xrightarrow{inc} … \xrightarrow{inc} "azza". Here "swap" denotes an operation of the first type, and "inc" denotes an operation of the second type. In the fourth test case, "aaabba" \xrightarrow{swap} "aaabab" \xrightarrow{swap} "aaaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddddbb" \xrightarrow{inc} … \xrightarrow{inc} "ddddcc". Submitted Solution: ``` #!/usr/bin/env python from __future__ import division, print_function from collections import Counter from string import ascii_lowercase import os import sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip def main(): t = int(input()) for _ in range(t): n, k = map(int, input().split()) a = input() b = input() aCount, bCount = Counter(a), Counter(b) for i, letter in enumerate(ascii_lowercase): diff = aCount[letter] - bCount[letter] if diff < 0: print("No") break elif diff >= k and letter != "z": aCount[letter] = 0 aCount[ascii_lowercase[i + 1]] += diff else: print("Yes") # 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") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main() ``` No
88,622
Provide tags and a correct Python 3 solution for this coding contest problem. At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls. Each class must present two couples to the ball. In Vasya's class, a boys and b girls wish to participate. But not all boys and not all girls are ready to dance in pairs. Formally, you know k possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair. For example, if a=3, b=4, k=4 and the couples (1, 2), (1, 3), (2, 2), (3, 4) are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below): * (1, 3) and (2, 2); * (3, 4) and (1, 3); But the following combinations are not possible: * (1, 3) and (1, 2) β€” the first boy enters two pairs; * (1, 2) and (2, 2) β€” the second girl enters two pairs; Find the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains three integers a, b and k (1 ≀ a, b, k ≀ 2 β‹… 10^5) β€” the number of boys and girls in the class and the number of couples ready to dance together. The second line of each test case contains k integers a_1, a_2, … a_k. (1 ≀ a_i ≀ a), where a_i is the number of the boy in the pair with the number i. The third line of each test case contains k integers b_1, b_2, … b_k. (1 ≀ b_i ≀ b), where b_i is the number of the girl in the pair with the number i. It is guaranteed that the sums of a, b, and k over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that each pair is specified at most once in one test case. Output For each test case, on a separate line print one integer β€” the number of ways to choose two pairs that match the condition above. Example Input 3 3 4 4 1 1 2 3 2 3 2 4 1 1 1 1 1 2 2 4 1 1 2 2 1 2 1 2 Output 4 0 2 Note In the first test case, the following combinations of pairs fit: * (1, 2) and (3, 4); * (1, 3) and (2, 2); * (1, 3) and (3, 4); * (2, 2) and (3, 4). There is only one pair in the second test case. In the third test case, the following combinations of pairs fit: * (1, 1) and (2, 2); * (1, 2) and (2, 1). Tags: combinatorics, graphs, math Correct Solution: ``` #pyrival orz import os import sys import math from io import BytesIO, IOBase input = sys.stdin.readline ############ ---- Input Functions ---- ############ def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input() return(list(s[:len(s) - 1])) def invr(): return(map(int,input().split())) ############ ---- Dijkstra with path ---- ############ def dijkstra(start, distance, path, n): # requires n == number of vertices in graph, # adj == adjacency list with weight of graph visited = [False for _ in range(n)] # To keep track of vertices that are visited distance[start] = 0 # distance of start node from itself is 0 for i in range(n): v = -1 # Initialize v == vertex from which its neighboring vertices' distance will be calculated for j in range(n): # If it has not been visited and has the lowest distance from start if not visited[v] and (v == -1 or distance[j] < distance[v]): v = j if distance[v] == math.inf: break visited[v] = True # Mark as visited for edge in adj[v]: destination = edge[0] # Neighbor of the vertex weight = edge[1] # Its corresponding weight if distance[v] + weight < distance[destination]: # If its distance is less than the stored distance distance[destination] = distance[v] + weight # Update the distance path[destination] = v # Update the path def gcd(a, b): if b == 0: return a else: return gcd(b, a%b) def lcm(a, b): return (a*b)//gcd(a, b) def ncr(n, r): return math.factorial(n)//(math.factorial(n-r)*math.factorial(r)) def npr(n, r): return math.factorial(n)//math.factorial(n-r) def seive(n): primes = [True]*(n+1) ans = [] for i in range(2, n): if not primes[i]: continue j = 2*i while j <= n: primes[j] = False j += i for p in range(2, n+1): if primes[p]: ans += [p] return ans def factors(n): factors = [] x = 1 while x*x <= n: if n % x == 0: if n // x == x: factors.append(x) else: factors.append(x) factors.append(n//x) x += 1 return factors # Functions: list of factors, seive of primes, gcd of two numbers, # lcm of two numbers, npr, ncr def main(): try: for _ in range(inp()): la, lb, k = invr() a = inlt() b = inlt() da = {} db = {} for i in range(k): if a[i] not in da: da[a[i]] = 0 if b[i] not in db: db[b[i]] = 0 da[a[i]] += 1 db[b[i]] += 1 ans = 0 for i in range(k): ans += k - da[a[i]] - db[b[i]] + 1 - i da[a[i]] -= 1 db[b[i]] -= 1 print(ans) except Exception as e: print(e) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main() ```
88,623
Provide tags and a correct Python 3 solution for this coding contest problem. At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls. Each class must present two couples to the ball. In Vasya's class, a boys and b girls wish to participate. But not all boys and not all girls are ready to dance in pairs. Formally, you know k possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair. For example, if a=3, b=4, k=4 and the couples (1, 2), (1, 3), (2, 2), (3, 4) are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below): * (1, 3) and (2, 2); * (3, 4) and (1, 3); But the following combinations are not possible: * (1, 3) and (1, 2) β€” the first boy enters two pairs; * (1, 2) and (2, 2) β€” the second girl enters two pairs; Find the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains three integers a, b and k (1 ≀ a, b, k ≀ 2 β‹… 10^5) β€” the number of boys and girls in the class and the number of couples ready to dance together. The second line of each test case contains k integers a_1, a_2, … a_k. (1 ≀ a_i ≀ a), where a_i is the number of the boy in the pair with the number i. The third line of each test case contains k integers b_1, b_2, … b_k. (1 ≀ b_i ≀ b), where b_i is the number of the girl in the pair with the number i. It is guaranteed that the sums of a, b, and k over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that each pair is specified at most once in one test case. Output For each test case, on a separate line print one integer β€” the number of ways to choose two pairs that match the condition above. Example Input 3 3 4 4 1 1 2 3 2 3 2 4 1 1 1 1 1 2 2 4 1 1 2 2 1 2 1 2 Output 4 0 2 Note In the first test case, the following combinations of pairs fit: * (1, 2) and (3, 4); * (1, 3) and (2, 2); * (1, 3) and (3, 4); * (2, 2) and (3, 4). There is only one pair in the second test case. In the third test case, the following combinations of pairs fit: * (1, 1) and (2, 2); * (1, 2) and (2, 1). Tags: combinatorics, graphs, math Correct Solution: ``` import sys import math import bisect from sys import stdin, stdout from math import gcd, floor, sqrt, log2, ceil from collections import defaultdict as dd from bisect import bisect_left as bl, bisect_right as br from bisect import insort from collections import Counter from collections import deque from heapq import heappush,heappop,heapify from itertools import permutations,combinations from itertools import accumulate as ac mod = int(1e9)+7 #mod = 998244353 ip = lambda : int(stdin.readline()) inp = lambda: map(int,stdin.readline().split()) ips = lambda: stdin.readline().rstrip() out = lambda x : stdout.write(str(x)+"\n") t = ip() for _ in range(t): a,b,k = inp() x = list(inp()) y = list(inp()) dica = Counter() dicb = Counter() ch = dd(int) ans = (k*(k-1))//2 for i in range(k): if i == 0: dica[x[i]] += 1 dicb[y[i]] += 1 ch[(x[i],y[i])] += 1 else: xx = x[i] yy = y[i] cal = dica[xx] cal += dicb[yy] cal -= ch[(xx,yy)] ans -= cal dica[xx] += 1 dicb[yy] += 1 ch[(xx,yy)] += 1 print(ans) ```
88,624
Provide tags and a correct Python 3 solution for this coding contest problem. At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls. Each class must present two couples to the ball. In Vasya's class, a boys and b girls wish to participate. But not all boys and not all girls are ready to dance in pairs. Formally, you know k possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair. For example, if a=3, b=4, k=4 and the couples (1, 2), (1, 3), (2, 2), (3, 4) are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below): * (1, 3) and (2, 2); * (3, 4) and (1, 3); But the following combinations are not possible: * (1, 3) and (1, 2) β€” the first boy enters two pairs; * (1, 2) and (2, 2) β€” the second girl enters two pairs; Find the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains three integers a, b and k (1 ≀ a, b, k ≀ 2 β‹… 10^5) β€” the number of boys and girls in the class and the number of couples ready to dance together. The second line of each test case contains k integers a_1, a_2, … a_k. (1 ≀ a_i ≀ a), where a_i is the number of the boy in the pair with the number i. The third line of each test case contains k integers b_1, b_2, … b_k. (1 ≀ b_i ≀ b), where b_i is the number of the girl in the pair with the number i. It is guaranteed that the sums of a, b, and k over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that each pair is specified at most once in one test case. Output For each test case, on a separate line print one integer β€” the number of ways to choose two pairs that match the condition above. Example Input 3 3 4 4 1 1 2 3 2 3 2 4 1 1 1 1 1 2 2 4 1 1 2 2 1 2 1 2 Output 4 0 2 Note In the first test case, the following combinations of pairs fit: * (1, 2) and (3, 4); * (1, 3) and (2, 2); * (1, 3) and (3, 4); * (2, 2) and (3, 4). There is only one pair in the second test case. In the third test case, the following combinations of pairs fit: * (1, 1) and (2, 2); * (1, 2) and (2, 1). Tags: combinatorics, graphs, math Correct Solution: ``` #Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction import collections from itertools import permutations from collections import defaultdict from collections import deque import threading #sys.setrecursionlimit(300000) #threading.stack_size(10**8) 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") #------------------------------------------------------------------------- #mod = 9223372036854775807 class SegmentTree: def __init__(self, data, default=-10**6, func=lambda a, b: max(a,b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) class SegmentTree1: def __init__(self, data, default=10**6, func=lambda a, b: min(a,b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) MOD=10**9+7 class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD mod=10**9+7 omod=998244353 #------------------------------------------------------------------------- prime = [True for i in range(50001)] pp=[] def SieveOfEratosthenes(n=50000): # Create a boolean array "prime[0..n]" and initialize # all entries it as true. A value in prime[i] will # finally be false if i is Not a prime, else true. p = 2 while (p * p <= n): # If prime[p] is not changed, then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * p, n+1, p): prime[i] = False p += 1 for i in range(50001): if prime[i]: pp.append(i) #---------------------------------running code------------------------------------------ for _ in range (int(input())): x,y,k=map(int,input().split()) d1=defaultdict(int) d2=defaultdict(int) s=[] a=list(map(int,input().split())) b=list(map(int,input().split())) for i in range (k): s.append((a[i],b[i])) d1[a[i]]+=1 d2[b[i]]+=1 res=0 for i in s: res+=k-d1[i[0]]-d2[i[1]]+1 res//=2 print(res) ```
88,625
Provide tags and a correct Python 3 solution for this coding contest problem. At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls. Each class must present two couples to the ball. In Vasya's class, a boys and b girls wish to participate. But not all boys and not all girls are ready to dance in pairs. Formally, you know k possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair. For example, if a=3, b=4, k=4 and the couples (1, 2), (1, 3), (2, 2), (3, 4) are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below): * (1, 3) and (2, 2); * (3, 4) and (1, 3); But the following combinations are not possible: * (1, 3) and (1, 2) β€” the first boy enters two pairs; * (1, 2) and (2, 2) β€” the second girl enters two pairs; Find the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains three integers a, b and k (1 ≀ a, b, k ≀ 2 β‹… 10^5) β€” the number of boys and girls in the class and the number of couples ready to dance together. The second line of each test case contains k integers a_1, a_2, … a_k. (1 ≀ a_i ≀ a), where a_i is the number of the boy in the pair with the number i. The third line of each test case contains k integers b_1, b_2, … b_k. (1 ≀ b_i ≀ b), where b_i is the number of the girl in the pair with the number i. It is guaranteed that the sums of a, b, and k over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that each pair is specified at most once in one test case. Output For each test case, on a separate line print one integer β€” the number of ways to choose two pairs that match the condition above. Example Input 3 3 4 4 1 1 2 3 2 3 2 4 1 1 1 1 1 2 2 4 1 1 2 2 1 2 1 2 Output 4 0 2 Note In the first test case, the following combinations of pairs fit: * (1, 2) and (3, 4); * (1, 3) and (2, 2); * (1, 3) and (3, 4); * (2, 2) and (3, 4). There is only one pair in the second test case. In the third test case, the following combinations of pairs fit: * (1, 1) and (2, 2); * (1, 2) and (2, 1). Tags: combinatorics, graphs, math Correct Solution: ``` for tests in range(int(input())): a,b,k=map(int,input().split()) la=list(map(int,input().split())) lb=list(map(int,input().split())) d={} g={} for i in range(k): if d.get(la[i])==None: d[la[i]]=1 else: d[la[i]]+=1 if g.get(lb[i])==None: g[lb[i]]=1 else: g[lb[i]]+=1 sum=0 for i in range(k): x=la[i] y=lb[i] sum+=k-i-d[x]-g[y]+1 d[x]-=1 g[y]-=1 print(sum) ```
88,626
Provide tags and a correct Python 3 solution for this coding contest problem. At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls. Each class must present two couples to the ball. In Vasya's class, a boys and b girls wish to participate. But not all boys and not all girls are ready to dance in pairs. Formally, you know k possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair. For example, if a=3, b=4, k=4 and the couples (1, 2), (1, 3), (2, 2), (3, 4) are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below): * (1, 3) and (2, 2); * (3, 4) and (1, 3); But the following combinations are not possible: * (1, 3) and (1, 2) β€” the first boy enters two pairs; * (1, 2) and (2, 2) β€” the second girl enters two pairs; Find the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains three integers a, b and k (1 ≀ a, b, k ≀ 2 β‹… 10^5) β€” the number of boys and girls in the class and the number of couples ready to dance together. The second line of each test case contains k integers a_1, a_2, … a_k. (1 ≀ a_i ≀ a), where a_i is the number of the boy in the pair with the number i. The third line of each test case contains k integers b_1, b_2, … b_k. (1 ≀ b_i ≀ b), where b_i is the number of the girl in the pair with the number i. It is guaranteed that the sums of a, b, and k over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that each pair is specified at most once in one test case. Output For each test case, on a separate line print one integer β€” the number of ways to choose two pairs that match the condition above. Example Input 3 3 4 4 1 1 2 3 2 3 2 4 1 1 1 1 1 2 2 4 1 1 2 2 1 2 1 2 Output 4 0 2 Note In the first test case, the following combinations of pairs fit: * (1, 2) and (3, 4); * (1, 3) and (2, 2); * (1, 3) and (3, 4); * (2, 2) and (3, 4). There is only one pair in the second test case. In the third test case, the following combinations of pairs fit: * (1, 1) and (2, 2); * (1, 2) and (2, 1). Tags: combinatorics, graphs, math Correct Solution: ``` from math import sqrt import operator import sys # inf = open('input.txt', 'r') inf = sys.stdin input = inf.readline def read_one_int(): return int(input().rstrip('\n')) def read_list_of_ints(): res = [int(val) for val in (input().rstrip('\n')).split(' ')] return res def read_str(): return input().rstrip() def check_seq(k, a_lst, b_lst): res = 0 a_to_b = {} b_to_a = {} for i in range(k): if a_lst[i] not in a_to_b: a_to_b[a_lst[i]] = [] a_to_b[a_lst[i]].append(b_lst[i]) if b_lst[i] not in b_to_a: b_to_a[b_lst[i]] = [] b_to_a[b_lst[i]].append(a_lst[i]) for a_cur, a_mp in a_to_b.items(): for b_cur in a_mp: res += k - len(a_mp) - len(b_to_a[b_cur]) + 1 return res // 2 def main(): samples = read_one_int() for _ in range(samples): a, b, k = read_list_of_ints() a_lst = read_list_of_ints() b_lst = read_list_of_ints() cur_res = check_seq(k, a_lst, b_lst) print(cur_res) if __name__== '__main__': main() ```
88,627
Provide tags and a correct Python 3 solution for this coding contest problem. At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls. Each class must present two couples to the ball. In Vasya's class, a boys and b girls wish to participate. But not all boys and not all girls are ready to dance in pairs. Formally, you know k possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair. For example, if a=3, b=4, k=4 and the couples (1, 2), (1, 3), (2, 2), (3, 4) are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below): * (1, 3) and (2, 2); * (3, 4) and (1, 3); But the following combinations are not possible: * (1, 3) and (1, 2) β€” the first boy enters two pairs; * (1, 2) and (2, 2) β€” the second girl enters two pairs; Find the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains three integers a, b and k (1 ≀ a, b, k ≀ 2 β‹… 10^5) β€” the number of boys and girls in the class and the number of couples ready to dance together. The second line of each test case contains k integers a_1, a_2, … a_k. (1 ≀ a_i ≀ a), where a_i is the number of the boy in the pair with the number i. The third line of each test case contains k integers b_1, b_2, … b_k. (1 ≀ b_i ≀ b), where b_i is the number of the girl in the pair with the number i. It is guaranteed that the sums of a, b, and k over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that each pair is specified at most once in one test case. Output For each test case, on a separate line print one integer β€” the number of ways to choose two pairs that match the condition above. Example Input 3 3 4 4 1 1 2 3 2 3 2 4 1 1 1 1 1 2 2 4 1 1 2 2 1 2 1 2 Output 4 0 2 Note In the first test case, the following combinations of pairs fit: * (1, 2) and (3, 4); * (1, 3) and (2, 2); * (1, 3) and (3, 4); * (2, 2) and (3, 4). There is only one pair in the second test case. In the third test case, the following combinations of pairs fit: * (1, 1) and (2, 2); * (1, 2) and (2, 1). Tags: combinatorics, graphs, math Correct Solution: ``` from math import * from collections import * def read(): return list(map(int, input().split(' '))) n, = read() for _ in range(n): a, b, k = read() boy = read() girl = read() pair = [(boy[i], girl[i]) for i in range(k)] if(k==1): print(0) continue # # print(pair) # ans = 0 # for i in range(k): # for j in range(i+1,k): # if pair[i][0]!=pair[j][0] and pair[i][1]!=pair[j][1]: # ans += 1 # print(ans) dic1, dic2 = defaultdict(int), defaultdict(int) for (i, j) in pair: dic1[i] += 1 dic2[j] += 1 # print(pair) ans = 0 for (i, j) in pair: # print(i,j,(dic1[i] + dic2[j] - 1)) ans += k - (dic1[i] + dic2[j] - 1) print(ans//2) ```
88,628
Provide tags and a correct Python 3 solution for this coding contest problem. At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls. Each class must present two couples to the ball. In Vasya's class, a boys and b girls wish to participate. But not all boys and not all girls are ready to dance in pairs. Formally, you know k possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair. For example, if a=3, b=4, k=4 and the couples (1, 2), (1, 3), (2, 2), (3, 4) are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below): * (1, 3) and (2, 2); * (3, 4) and (1, 3); But the following combinations are not possible: * (1, 3) and (1, 2) β€” the first boy enters two pairs; * (1, 2) and (2, 2) β€” the second girl enters two pairs; Find the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains three integers a, b and k (1 ≀ a, b, k ≀ 2 β‹… 10^5) β€” the number of boys and girls in the class and the number of couples ready to dance together. The second line of each test case contains k integers a_1, a_2, … a_k. (1 ≀ a_i ≀ a), where a_i is the number of the boy in the pair with the number i. The third line of each test case contains k integers b_1, b_2, … b_k. (1 ≀ b_i ≀ b), where b_i is the number of the girl in the pair with the number i. It is guaranteed that the sums of a, b, and k over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that each pair is specified at most once in one test case. Output For each test case, on a separate line print one integer β€” the number of ways to choose two pairs that match the condition above. Example Input 3 3 4 4 1 1 2 3 2 3 2 4 1 1 1 1 1 2 2 4 1 1 2 2 1 2 1 2 Output 4 0 2 Note In the first test case, the following combinations of pairs fit: * (1, 2) and (3, 4); * (1, 3) and (2, 2); * (1, 3) and (3, 4); * (2, 2) and (3, 4). There is only one pair in the second test case. In the third test case, the following combinations of pairs fit: * (1, 1) and (2, 2); * (1, 2) and (2, 1). Tags: combinatorics, graphs, math Correct Solution: ``` import math, sys from collections import defaultdict, Counter, deque from bisect import bisect_left, bisect_right INF = float('inf') MOD = int(1e9) + 7 MAX = int(1e6) + 1 def solve(): a, b, k = vars() boys = array() girls = array() pair = [] for i in range(k): pair.append([boys[i], girls[i]]) pair = sorted(pair) index = defaultdict(list) for i in range(k): index[pair[i][1]].append(i) # print(pair) ans = 0 i = 0 while i < k: d = 0 tmp = i while i < k - 1 and pair[i + 1][0] == pair[i][0]: i += 1 d += 1 db = i i = tmp # print('#', db, pair[i]) while i <= db: girl = pair[i][1] discard = len(index[girl]) - bisect_right(index[girl], db) # print(i, discard, db + 1) ans += k - db - discard - 1 i += 1 print(ans) def main(): t = 1 t = int(input()) for _ in range(t): solve() def gcd(a, b): while b: a, b = b, a%b return a def input(): return sys.stdin.readline().rstrip('\n').strip() def print(*args, sep=' ', end='\n'): first = True for arg in args: if not first: sys.stdout.write(sep) sys.stdout.write(str(arg)) first = False sys.stdout.write(end) primes = [ 1 for i in range(MAX) ] def sieve(): global primes primes[0] = primes[1] = 0 i = 2 while i <= MAX ** 0.5: j = i * i while primes[i] and j < MAX: if j % i == 0: primes[j] = 0 j += i i += 1 def vars(): return map(int, input().split()) def array(): return list(map(int, input().split())) if __name__ == "__main__": main() ```
88,629
Provide tags and a correct Python 3 solution for this coding contest problem. At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls. Each class must present two couples to the ball. In Vasya's class, a boys and b girls wish to participate. But not all boys and not all girls are ready to dance in pairs. Formally, you know k possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair. For example, if a=3, b=4, k=4 and the couples (1, 2), (1, 3), (2, 2), (3, 4) are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below): * (1, 3) and (2, 2); * (3, 4) and (1, 3); But the following combinations are not possible: * (1, 3) and (1, 2) β€” the first boy enters two pairs; * (1, 2) and (2, 2) β€” the second girl enters two pairs; Find the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains three integers a, b and k (1 ≀ a, b, k ≀ 2 β‹… 10^5) β€” the number of boys and girls in the class and the number of couples ready to dance together. The second line of each test case contains k integers a_1, a_2, … a_k. (1 ≀ a_i ≀ a), where a_i is the number of the boy in the pair with the number i. The third line of each test case contains k integers b_1, b_2, … b_k. (1 ≀ b_i ≀ b), where b_i is the number of the girl in the pair with the number i. It is guaranteed that the sums of a, b, and k over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that each pair is specified at most once in one test case. Output For each test case, on a separate line print one integer β€” the number of ways to choose two pairs that match the condition above. Example Input 3 3 4 4 1 1 2 3 2 3 2 4 1 1 1 1 1 2 2 4 1 1 2 2 1 2 1 2 Output 4 0 2 Note In the first test case, the following combinations of pairs fit: * (1, 2) and (3, 4); * (1, 3) and (2, 2); * (1, 3) and (3, 4); * (2, 2) and (3, 4). There is only one pair in the second test case. In the third test case, the following combinations of pairs fit: * (1, 1) and (2, 2); * (1, 2) and (2, 1). Tags: combinatorics, graphs, math Correct Solution: ``` for _ in range(int(input())): a, b, k = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) deg_a = [0]*(a+1) deg_b = [0]*(b+1) for i in range(k): deg_a[A[i]] += 1 deg_b[B[i]] += 1 ans = 0 for i in range(k): ans += k - deg_a[A[i]] - deg_b[B[i]] + 1 print(ans // 2) ```
88,630
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls. Each class must present two couples to the ball. In Vasya's class, a boys and b girls wish to participate. But not all boys and not all girls are ready to dance in pairs. Formally, you know k possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair. For example, if a=3, b=4, k=4 and the couples (1, 2), (1, 3), (2, 2), (3, 4) are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below): * (1, 3) and (2, 2); * (3, 4) and (1, 3); But the following combinations are not possible: * (1, 3) and (1, 2) β€” the first boy enters two pairs; * (1, 2) and (2, 2) β€” the second girl enters two pairs; Find the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains three integers a, b and k (1 ≀ a, b, k ≀ 2 β‹… 10^5) β€” the number of boys and girls in the class and the number of couples ready to dance together. The second line of each test case contains k integers a_1, a_2, … a_k. (1 ≀ a_i ≀ a), where a_i is the number of the boy in the pair with the number i. The third line of each test case contains k integers b_1, b_2, … b_k. (1 ≀ b_i ≀ b), where b_i is the number of the girl in the pair with the number i. It is guaranteed that the sums of a, b, and k over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that each pair is specified at most once in one test case. Output For each test case, on a separate line print one integer β€” the number of ways to choose two pairs that match the condition above. Example Input 3 3 4 4 1 1 2 3 2 3 2 4 1 1 1 1 1 2 2 4 1 1 2 2 1 2 1 2 Output 4 0 2 Note In the first test case, the following combinations of pairs fit: * (1, 2) and (3, 4); * (1, 3) and (2, 2); * (1, 3) and (3, 4); * (2, 2) and (3, 4). There is only one pair in the second test case. In the third test case, the following combinations of pairs fit: * (1, 1) and (2, 2); * (1, 2) and (2, 1). Submitted Solution: ``` from collections import Counter def read_int(): return int(input()) def read_ints(): return map(int, input().split(' ')) t = read_int() for case_num in range(t): a, b, k = read_ints() pa = list(read_ints()) pb = list(read_ints()) ca = Counter() cb = Counter() for i in range(k): ca[pa[i]] += 1 cb[pb[i]] += 1 ans = 0 for i in range(k - 1): ca[pa[i]] -= 1 cb[pb[i]] -= 1 ans += k - i - 1 - ca[pa[i]] - cb[pb[i]] print(ans) ``` Yes
88,631
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls. Each class must present two couples to the ball. In Vasya's class, a boys and b girls wish to participate. But not all boys and not all girls are ready to dance in pairs. Formally, you know k possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair. For example, if a=3, b=4, k=4 and the couples (1, 2), (1, 3), (2, 2), (3, 4) are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below): * (1, 3) and (2, 2); * (3, 4) and (1, 3); But the following combinations are not possible: * (1, 3) and (1, 2) β€” the first boy enters two pairs; * (1, 2) and (2, 2) β€” the second girl enters two pairs; Find the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains three integers a, b and k (1 ≀ a, b, k ≀ 2 β‹… 10^5) β€” the number of boys and girls in the class and the number of couples ready to dance together. The second line of each test case contains k integers a_1, a_2, … a_k. (1 ≀ a_i ≀ a), where a_i is the number of the boy in the pair with the number i. The third line of each test case contains k integers b_1, b_2, … b_k. (1 ≀ b_i ≀ b), where b_i is the number of the girl in the pair with the number i. It is guaranteed that the sums of a, b, and k over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that each pair is specified at most once in one test case. Output For each test case, on a separate line print one integer β€” the number of ways to choose two pairs that match the condition above. Example Input 3 3 4 4 1 1 2 3 2 3 2 4 1 1 1 1 1 2 2 4 1 1 2 2 1 2 1 2 Output 4 0 2 Note In the first test case, the following combinations of pairs fit: * (1, 2) and (3, 4); * (1, 3) and (2, 2); * (1, 3) and (3, 4); * (2, 2) and (3, 4). There is only one pair in the second test case. In the third test case, the following combinations of pairs fit: * (1, 1) and (2, 2); * (1, 2) and (2, 1). Submitted Solution: ``` ###pyrival template for fast IO import os import sys from io import BytesIO, IOBase # 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") t=int(input()) while t>0: t-=1 a,b,k=[int(x) for x in input().split()] boys=[int(x) for x in input().split()] girls=[int(x) for x in input().split()] same=0 boys.sort() girls.sort() temp1=1;temp2=1 for i in range(1,k): if boys[i]==boys[i-1]: temp1+=1 else: same+=temp1*(temp1-1)//2 #print(temp1*(temp1-1)//2) temp1=1 if girls[i]==girls[i-1]: temp2+=1 else: same+=temp2*(temp2-1)//2 #print(temp2*(temp2-1)//2) temp2=1 same+=temp2*(temp2-1)//2 same+=temp1*(temp1-1)//2 sys.stdout.write(str(k*(k-1)//2-same)+"\n") ``` Yes
88,632
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls. Each class must present two couples to the ball. In Vasya's class, a boys and b girls wish to participate. But not all boys and not all girls are ready to dance in pairs. Formally, you know k possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair. For example, if a=3, b=4, k=4 and the couples (1, 2), (1, 3), (2, 2), (3, 4) are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below): * (1, 3) and (2, 2); * (3, 4) and (1, 3); But the following combinations are not possible: * (1, 3) and (1, 2) β€” the first boy enters two pairs; * (1, 2) and (2, 2) β€” the second girl enters two pairs; Find the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains three integers a, b and k (1 ≀ a, b, k ≀ 2 β‹… 10^5) β€” the number of boys and girls in the class and the number of couples ready to dance together. The second line of each test case contains k integers a_1, a_2, … a_k. (1 ≀ a_i ≀ a), where a_i is the number of the boy in the pair with the number i. The third line of each test case contains k integers b_1, b_2, … b_k. (1 ≀ b_i ≀ b), where b_i is the number of the girl in the pair with the number i. It is guaranteed that the sums of a, b, and k over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that each pair is specified at most once in one test case. Output For each test case, on a separate line print one integer β€” the number of ways to choose two pairs that match the condition above. Example Input 3 3 4 4 1 1 2 3 2 3 2 4 1 1 1 1 1 2 2 4 1 1 2 2 1 2 1 2 Output 4 0 2 Note In the first test case, the following combinations of pairs fit: * (1, 2) and (3, 4); * (1, 3) and (2, 2); * (1, 3) and (3, 4); * (2, 2) and (3, 4). There is only one pair in the second test case. In the third test case, the following combinations of pairs fit: * (1, 1) and (2, 2); * (1, 2) and (2, 1). Submitted Solution: ``` from collections import Counter t=int(input()) for z in range(t): a,b,k=[int(q)for q in input().split()] al=[int(q)for q in input().split()] bl=[int(q)for q in input().split()] alc=Counter(al) blc=Counter(bl) ans=0 for i in range(k): da=alc[al[i]] db=blc[bl[i]] ans+=(k-da-db+1) print(ans//2) ``` Yes
88,633
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls. Each class must present two couples to the ball. In Vasya's class, a boys and b girls wish to participate. But not all boys and not all girls are ready to dance in pairs. Formally, you know k possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair. For example, if a=3, b=4, k=4 and the couples (1, 2), (1, 3), (2, 2), (3, 4) are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below): * (1, 3) and (2, 2); * (3, 4) and (1, 3); But the following combinations are not possible: * (1, 3) and (1, 2) β€” the first boy enters two pairs; * (1, 2) and (2, 2) β€” the second girl enters two pairs; Find the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains three integers a, b and k (1 ≀ a, b, k ≀ 2 β‹… 10^5) β€” the number of boys and girls in the class and the number of couples ready to dance together. The second line of each test case contains k integers a_1, a_2, … a_k. (1 ≀ a_i ≀ a), where a_i is the number of the boy in the pair with the number i. The third line of each test case contains k integers b_1, b_2, … b_k. (1 ≀ b_i ≀ b), where b_i is the number of the girl in the pair with the number i. It is guaranteed that the sums of a, b, and k over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that each pair is specified at most once in one test case. Output For each test case, on a separate line print one integer β€” the number of ways to choose two pairs that match the condition above. Example Input 3 3 4 4 1 1 2 3 2 3 2 4 1 1 1 1 1 2 2 4 1 1 2 2 1 2 1 2 Output 4 0 2 Note In the first test case, the following combinations of pairs fit: * (1, 2) and (3, 4); * (1, 3) and (2, 2); * (1, 3) and (3, 4); * (2, 2) and (3, 4). There is only one pair in the second test case. In the third test case, the following combinations of pairs fit: * (1, 1) and (2, 2); * (1, 2) and (2, 1). Submitted Solution: ``` R=lambda:list(map(int,input().split())) for _ in ' '*int(input()): an,bn,k=R() a=R() b=R() edges=[] for i in range(k): edges.append([a[i], b[i]]) dega=[0]*(an+1) degb=[0]*(bn+1) for boy, girl in edges: dega[boy] += 1 degb[girl] += 1 c=0 for b, g in edges: c += (k + 1 - dega[b] - degb[g]) print(c//2) ``` Yes
88,634
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls. Each class must present two couples to the ball. In Vasya's class, a boys and b girls wish to participate. But not all boys and not all girls are ready to dance in pairs. Formally, you know k possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair. For example, if a=3, b=4, k=4 and the couples (1, 2), (1, 3), (2, 2), (3, 4) are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below): * (1, 3) and (2, 2); * (3, 4) and (1, 3); But the following combinations are not possible: * (1, 3) and (1, 2) β€” the first boy enters two pairs; * (1, 2) and (2, 2) β€” the second girl enters two pairs; Find the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains three integers a, b and k (1 ≀ a, b, k ≀ 2 β‹… 10^5) β€” the number of boys and girls in the class and the number of couples ready to dance together. The second line of each test case contains k integers a_1, a_2, … a_k. (1 ≀ a_i ≀ a), where a_i is the number of the boy in the pair with the number i. The third line of each test case contains k integers b_1, b_2, … b_k. (1 ≀ b_i ≀ b), where b_i is the number of the girl in the pair with the number i. It is guaranteed that the sums of a, b, and k over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that each pair is specified at most once in one test case. Output For each test case, on a separate line print one integer β€” the number of ways to choose two pairs that match the condition above. Example Input 3 3 4 4 1 1 2 3 2 3 2 4 1 1 1 1 1 2 2 4 1 1 2 2 1 2 1 2 Output 4 0 2 Note In the first test case, the following combinations of pairs fit: * (1, 2) and (3, 4); * (1, 3) and (2, 2); * (1, 3) and (3, 4); * (2, 2) and (3, 4). There is only one pair in the second test case. In the third test case, the following combinations of pairs fit: * (1, 1) and (2, 2); * (1, 2) and (2, 1). Submitted Solution: ``` t=int(input()) for i in range(t): l=list(map(int,input().strip().split())) l1=list(map(int,input().strip().split())) l2=list(map(int,input().strip().split())) s=0 if l[2]==1: print("1") continue for i in range(l[2]-1): count=0 for j in range(i+1,l[2]): if l1[i]==l1[j]: count+=1 if l2[i]==l2[j]: count+=1 s+=(l[2]-i)-count-1 print(s) ``` No
88,635
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls. Each class must present two couples to the ball. In Vasya's class, a boys and b girls wish to participate. But not all boys and not all girls are ready to dance in pairs. Formally, you know k possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair. For example, if a=3, b=4, k=4 and the couples (1, 2), (1, 3), (2, 2), (3, 4) are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below): * (1, 3) and (2, 2); * (3, 4) and (1, 3); But the following combinations are not possible: * (1, 3) and (1, 2) β€” the first boy enters two pairs; * (1, 2) and (2, 2) β€” the second girl enters two pairs; Find the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains three integers a, b and k (1 ≀ a, b, k ≀ 2 β‹… 10^5) β€” the number of boys and girls in the class and the number of couples ready to dance together. The second line of each test case contains k integers a_1, a_2, … a_k. (1 ≀ a_i ≀ a), where a_i is the number of the boy in the pair with the number i. The third line of each test case contains k integers b_1, b_2, … b_k. (1 ≀ b_i ≀ b), where b_i is the number of the girl in the pair with the number i. It is guaranteed that the sums of a, b, and k over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that each pair is specified at most once in one test case. Output For each test case, on a separate line print one integer β€” the number of ways to choose two pairs that match the condition above. Example Input 3 3 4 4 1 1 2 3 2 3 2 4 1 1 1 1 1 2 2 4 1 1 2 2 1 2 1 2 Output 4 0 2 Note In the first test case, the following combinations of pairs fit: * (1, 2) and (3, 4); * (1, 3) and (2, 2); * (1, 3) and (3, 4); * (2, 2) and (3, 4). There is only one pair in the second test case. In the third test case, the following combinations of pairs fit: * (1, 1) and (2, 2); * (1, 2) and (2, 1). Submitted Solution: ``` t = int(input()) def func(a,b,k,boys,girls): a = 0 for i in range(k-1): for j in range(i+1,k): if boys[i]!=boys[j] and girls[i]!=girls[j]: a+=1 return a for i in range(t): a,b,k = list(map(int,input().split())) boys = list(map(int,input().split())) girls = list(map(int,input().split())) print(a,b,k) print(boys) print(girls) print(func(a,b,k,boys,girls)) # print(func(y)) ``` No
88,636
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls. Each class must present two couples to the ball. In Vasya's class, a boys and b girls wish to participate. But not all boys and not all girls are ready to dance in pairs. Formally, you know k possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair. For example, if a=3, b=4, k=4 and the couples (1, 2), (1, 3), (2, 2), (3, 4) are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below): * (1, 3) and (2, 2); * (3, 4) and (1, 3); But the following combinations are not possible: * (1, 3) and (1, 2) β€” the first boy enters two pairs; * (1, 2) and (2, 2) β€” the second girl enters two pairs; Find the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains three integers a, b and k (1 ≀ a, b, k ≀ 2 β‹… 10^5) β€” the number of boys and girls in the class and the number of couples ready to dance together. The second line of each test case contains k integers a_1, a_2, … a_k. (1 ≀ a_i ≀ a), where a_i is the number of the boy in the pair with the number i. The third line of each test case contains k integers b_1, b_2, … b_k. (1 ≀ b_i ≀ b), where b_i is the number of the girl in the pair with the number i. It is guaranteed that the sums of a, b, and k over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that each pair is specified at most once in one test case. Output For each test case, on a separate line print one integer β€” the number of ways to choose two pairs that match the condition above. Example Input 3 3 4 4 1 1 2 3 2 3 2 4 1 1 1 1 1 2 2 4 1 1 2 2 1 2 1 2 Output 4 0 2 Note In the first test case, the following combinations of pairs fit: * (1, 2) and (3, 4); * (1, 3) and (2, 2); * (1, 3) and (3, 4); * (2, 2) and (3, 4). There is only one pair in the second test case. In the third test case, the following combinations of pairs fit: * (1, 1) and (2, 2); * (1, 2) and (2, 1). Submitted Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") t=int(input()) for _ in range(t): a,b,k=map(int,input().split()) l1=list(map(int,input().split())) l2=list(map(int,input().split())) ax,bx=set(l1),set(l2) cx=set() for i in range(k): cx.add((l1[i],l2[i])) t=(k*(k-1))//2 print(t-((k-len(ax))+(k-len(bx)))) ``` No
88,637
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls. Each class must present two couples to the ball. In Vasya's class, a boys and b girls wish to participate. But not all boys and not all girls are ready to dance in pairs. Formally, you know k possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair. For example, if a=3, b=4, k=4 and the couples (1, 2), (1, 3), (2, 2), (3, 4) are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below): * (1, 3) and (2, 2); * (3, 4) and (1, 3); But the following combinations are not possible: * (1, 3) and (1, 2) β€” the first boy enters two pairs; * (1, 2) and (2, 2) β€” the second girl enters two pairs; Find the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains three integers a, b and k (1 ≀ a, b, k ≀ 2 β‹… 10^5) β€” the number of boys and girls in the class and the number of couples ready to dance together. The second line of each test case contains k integers a_1, a_2, … a_k. (1 ≀ a_i ≀ a), where a_i is the number of the boy in the pair with the number i. The third line of each test case contains k integers b_1, b_2, … b_k. (1 ≀ b_i ≀ b), where b_i is the number of the girl in the pair with the number i. It is guaranteed that the sums of a, b, and k over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that each pair is specified at most once in one test case. Output For each test case, on a separate line print one integer β€” the number of ways to choose two pairs that match the condition above. Example Input 3 3 4 4 1 1 2 3 2 3 2 4 1 1 1 1 1 2 2 4 1 1 2 2 1 2 1 2 Output 4 0 2 Note In the first test case, the following combinations of pairs fit: * (1, 2) and (3, 4); * (1, 3) and (2, 2); * (1, 3) and (3, 4); * (2, 2) and (3, 4). There is only one pair in the second test case. In the third test case, the following combinations of pairs fit: * (1, 1) and (2, 2); * (1, 2) and (2, 1). Submitted Solution: ``` from collections import Counter for ad in range(int(input())): a,b,k=list(map(int,input().split())) x=list(map(int,input().split())) y=list(map(int,input().split())) ans=(k*(k-1))//2 p=Counter(x);q=Counter(y) for i in range(k): aa=p[i];bb=q[i] ans-=(aa*(aa-1))//2 ans-=(bb*(bb-1))//2 print(ans) ``` No
88,638
Provide tags and a correct Python 3 solution for this coding contest problem. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≀ n ≀ 200 000) β€” the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2.5 β‹… 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≀ x, y, z, w ≀ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3 Tags: brute force, hashing, implementation, math Correct Solution: ``` import sys from collections import defaultdict r=sys.stdin.readline n = int(input()) a = list(map(int, r().split())) d = {} for i in range(n): for j in range(i): # print(d) if(a[i]+a[j] in d): ii,jj = d[a[i]+a[j]] if(len(set([i,j,ii,jj]))==4): print('YES') print(i+1,j+1,ii+1,jj+1) exit(0) else: d[a[i]+a[j]] = (i,j) print('NO') ```
88,639
Provide tags and a correct Python 3 solution for this coding contest problem. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≀ n ≀ 200 000) β€” the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2.5 β‹… 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≀ x, y, z, w ≀ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3 Tags: brute force, hashing, implementation, math Correct Solution: ``` # -*- coding: utf-8 -*- """ Created on Tue Mar 23 16:06:25 2021 @author: PC-4 """ n = int(input()) A = list(map(int, input().split(" "))) def f(A, n): D = {} for j in range(n): for i in range(j): s = A[i] + A[j] if s in D: x, y = D[s] if not(i == x or i == y or j == y): print("YES") print(x + 1, y + 1, i + 1, j + 1) return D[s] = (i, j) print("NO") f(A, n) ```
88,640
Provide tags and a correct Python 3 solution for this coding contest problem. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≀ n ≀ 200 000) β€” the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2.5 β‹… 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≀ x, y, z, w ≀ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3 Tags: brute force, hashing, implementation, math Correct Solution: ``` from collections import Counter n=int(input()) m=[int(j) for j in input().split()] m=m[:10000] new={} res=[] for i in range(len(m)): for j in range(i+1, len(m)): if m[i]+m[j] in new: if i not in new[m[i]+m[j]] and j not in new[m[i]+m[j]]: z=new[m[i]+m[j]][0] x=new[m[i]+m[j]][1] res.extend([i, j, z, x]) break else: continue else: new[m[i]+m[j]]=[i, j] else: continue break if res: print("YES") print(" ".join([str(e+1) for e in res])) else: print("NO") ```
88,641
Provide tags and a correct Python 3 solution for this coding contest problem. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≀ n ≀ 200 000) β€” the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2.5 β‹… 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≀ x, y, z, w ≀ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3 Tags: brute force, hashing, implementation, math Correct Solution: ``` from collections import Counter n=int(input()) m=[int(j) for j in input().split()] m=m[:2000] new={} res=[] for i in range(len(m)): for j in range(i+1, len(m)): if m[i]+m[j] in new: if i not in new[m[i]+m[j]] and j not in new[m[i]+m[j]]: z=new[m[i]+m[j]][0] x=new[m[i]+m[j]][1] res.extend([i, j, z, x]) break else: continue else: new[m[i]+m[j]]=[i, j] else: continue break if res: print("YES") print(" ".join([str(e+1) for e in res])) else: print("NO") ```
88,642
Provide tags and a correct Python 3 solution for this coding contest problem. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≀ n ≀ 200 000) β€” the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2.5 β‹… 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≀ x, y, z, w ≀ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3 Tags: brute force, hashing, implementation, math Correct Solution: ``` def main(): n = int(input()) arr = list(map(int, input().split(' '))) cache = {} for i in range(n): for j in range(i): s = arr[i] + arr[j] if s in cache: f, t = cache[s] if i!=f and i!=t and j!=f and t!=j: print("YES") print(f+1, t+1, i+1, j+1) return cache[s] = (i, j) print("NO") if __name__ == "__main__": main() ```
88,643
Provide tags and a correct Python 3 solution for this coding contest problem. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≀ n ≀ 200 000) β€” the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2.5 β‹… 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≀ x, y, z, w ≀ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3 Tags: brute force, hashing, implementation, math Correct Solution: ``` import sys input = sys.stdin.readline from operator import itemgetter n=int(input()) A=list(map(int,input().split())) MAX=max(A)-min(A) COUNT=[[] for i in range(max(A)+1)] fl1=0 for i in range(n): COUNT[A[i]].append(i) if len(COUNT[A[i]])==4: print("YES") print(*[c+1 for c in COUNT[A[i]]]) exit() if len(COUNT[A[i]])==2: if fl1==0: fl1=A[i] else: print("YES") print(COUNT[fl1][0]+1,COUNT[A[i]][0]+1,COUNT[A[i]][1]+1,COUNT[fl1][1]+1) exit() X=[(A[i],i) for i in range(n)] SA=[[] for i in range(MAX+1)] for i in range(n): for j in range(i+1,n): sa=abs(X[j][0]-X[i][0]) for x,y in SA[sa]: if X[i][1]!=x and X[i][1]!=y and X[j][1]!=x and X[j][1]!=y: if X[i][0]<=X[j][0]: print("YES") print(X[i][1]+1,y+1,x+1,X[j][1]+1) exit() else: print("YES") print(X[j][1]+1,y+1,x+1,X[i][1]+1) exit() if X[i][0]<=X[j][0]: SA[sa].append((X[i][1],X[j][1])) else: SA[sa].append((X[j][1],X[i][1])) print("NO") ```
88,644
Provide tags and a correct Python 3 solution for this coding contest problem. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≀ n ≀ 200 000) β€” the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2.5 β‹… 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≀ x, y, z, w ≀ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3 Tags: brute force, hashing, implementation, math Correct Solution: ``` n = int(input()) def solve(arr,n): #me = max(arr) #hms = [0 for _ in range(0,2*(me)+1)] #hmi = [[] for _ in range(0,2*(me)+1)] d = {} for i in range(n): for j in range(i): s = arr[i] + arr[j] if s not in d: d[s]=(i,j) else: ii,jj = d[s] if len(set([i,j,ii,jj]))==4: print('YES') print(ii+1,jj+1,i+1,j+1) return 1 print('NO') #arr = [int(a) for a in input().split(' ')] arr = list(map(int, input().split())) solve(arr,n) ```
88,645
Provide tags and a correct Python 3 solution for this coding contest problem. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≀ n ≀ 200 000) β€” the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2.5 β‹… 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≀ x, y, z, w ≀ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3 Tags: brute force, hashing, implementation, math Correct Solution: ``` def sol(arr): s=dict() for i in range(min(4000,len(arr)-1)): for j in range(i+1,min(4001,len(arr))): key=arr[i]+arr[j] if key not in s: s[key]=i,j elif i not in s[key] and j not in s[key]: print("YES") print(s[key][0]+1,s[key][1]+1,i+1,j+1) return print("NO") input() sol([int(i) for i in input().split()]) ```
88,646
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≀ n ≀ 200 000) β€” the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2.5 β‹… 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≀ x, y, z, w ≀ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3 Submitted Solution: ``` from sys import stdin input=stdin.readline def A707(): from collections import defaultdict CAP = 2500001 n=int(input()) a=list(map(int,input().split())) d=[0]*(CAP*2) i=n-2 j=n-1 found=False while i >= 0: j = i + 1 while j < n: if d[a[i]+a[j]] != 0: ID = i*n + j for k in d[a[i]+a[j]]: if not (k % n == i or k % n == j or k//n == i or k//n == j): print('YES') print(i+1,j+1,k%n+1,k//n+1) found=True break d[a[i]+a[j]].append(ID) else: d[a[i]+a[j]] = [i*n+j] j += 1 if found: break i -= 1 if found: break if not found: print('NO') A707() ``` Yes
88,647
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≀ n ≀ 200 000) β€” the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2.5 β‹… 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≀ x, y, z, w ≀ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3 Submitted Solution: ``` n = int(input()) arr = list(map(int, input().split())) d = {} flag = True for i1 in range(n): for j1 in range(i1): if arr[i1]+arr[j1] in d: i2, j2 = d[arr[i1]+arr[j1]] if len(set([i1, i2, j1, j2]))==4: print("YES") print(j2+1, i2+1, j1+1, i1+1) flag = False break else: d[arr[i1]+arr[j1]] = (i1, j1) if flag==False: break if flag: print("NO") ``` Yes
88,648
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≀ n ≀ 200 000) β€” the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2.5 β‹… 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≀ x, y, z, w ≀ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3 Submitted Solution: ``` import sys import math import heapq import bisect from collections import Counter from collections import defaultdict from io import BytesIO, IOBase import string 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 self.BUFSIZE = 8192 def read(self): while True: b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.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, self.BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: self.os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def get_int(): return int(input()) def get_ints(): return list(map(int, input().split(' '))) def get_int_grid(n): return [get_ints() for _ in range(n)] def get_str(): return input().split(' ') def yes_no(b): if b: return "YES" else: return "NO" def binary_search(good, left, right, delta=1, right_true=False): """ Performs binary search ---------- Parameters ---------- :param good: Function used to perform the binary search :param left: Starting value of left limit :param right: Starting value of the right limit :param delta: Margin of error, defaults value of 1 for integer binary search :param right_true: Boolean, for whether the right limit is the true invariant :return: Returns the most extremal value interval [left, right] which is good function evaluates to True, alternatively returns False if no such value found """ limits = [left, right] while limits[1] - limits[0] > delta: if delta == 1: mid = sum(limits) // 2 else: mid = sum(limits) / 2 if good(mid): limits[int(right_true)] = mid else: limits[int(~right_true)] = mid if good(limits[int(right_true)]): return limits[int(right_true)] else: return False def prefix_sums(a, drop_zero=False): p = [0] for x in a: p.append(p[-1] + x) if drop_zero: return p[1:] else: return p def prefix_mins(a, drop_zero=False): p = [float('inf')] for x in a: p.append(min(p[-1], x)) if drop_zero: return p[1:] else: return p def solve_a(): n = get_int() arr = [0] dep = [0] for _ in range(n): a, b = get_ints() arr.append(a) dep.append(b) delta = get_ints() departure = 0 for idx in range(1, n + 1): arrival = (arr[idx] - dep[idx - 1] + delta[idx - 1]) + departure departure = max(dep[idx], arrival + math.ceil((dep[idx] - arr[idx])/ 2)) return arrival def solve_b(): n = get_int() a = get_ints() retval = [0] * n idx = n - 1 min_fill = n while idx >= 0: if a[idx]: min_fill = min(min_fill, idx - a[idx] + 1) if min_fill <= idx: retval[idx] = 1 idx -= 1 return retval def solve_c(): n = get_int() arr = get_ints() sums = {} for i in range(n): for j in range(i): if arr[i] + arr[j] in sums: k, l = sums[arr[i] + arr[j]] if len(set([i, j, k, l])) == 4: return [i + 1, j + 1, k + 1, l + 1] sums[arr[i] + arr[j]] = (i, j) return False ans = solve_c() if ans: print("YES") print(*ans) else: print("NO") ``` Yes
88,649
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≀ n ≀ 200 000) β€” the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2.5 β‹… 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≀ x, y, z, w ≀ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3 Submitted Solution: ``` from collections import Counter n=int(input()) m=[int(j) for j in input().split()] m=m new={} res=[] for i in range(len(m)): for j in range(i+1, len(m)): if m[i]+m[j] in new: if i not in new[m[i]+m[j]] and j not in new[m[i]+m[j]]: z=new[m[i]+m[j]][0] x=new[m[i]+m[j]][1] res.extend([i, j, z, x]) break else: continue else: new[m[i]+m[j]]=[i, j] else: continue break if res: print("YES") print(" ".join([str(e+1) for e in res])) else: print("NO") ``` Yes
88,650
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≀ n ≀ 200 000) β€” the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2.5 β‹… 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≀ x, y, z, w ≀ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3 Submitted Solution: ``` import sys input = sys.stdin.readline ############ ---- Input Functions ---- ############ def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input() return(list(s[:len(s) - 1])) def invr(): return(map(int,input().split())) n = inp() a = inlt() sums = dict() # With 8 numbers we must have a pair. Try all 8^4 combinations. def find_ans(p): n = len(p) for i in range(n): for j in range(i+1,n): for k in range(j+1,n): for l in range(k+1,n): if a[i]+a[j] == a[k] + a[l]: print(f"{i+1} {j+1} {k+1} {l+1}") exit() for i in range(n): for j in range(i+1,n): s = a[i]+a[j] if s in sums: pairs = sums[s] for k in range(len(pairs) // 2): pair = (pairs[2*k], pairs[2*k+1]) if i not in pair and j not in pair: print("YES") print(f"{i+1} {j+1} {pair[0]+1} {pair[1]+1}") exit() sums[s] = sums[s] + (i,j) if len(sums[s]) >= 8: find_ans(sums[s]) else: sums[s] = (i,j) print("NO") ``` No
88,651
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≀ n ≀ 200 000) β€” the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2.5 β‹… 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≀ x, y, z, w ≀ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3 Submitted Solution: ``` def zip_sorted(a,b): # sorted by a a,b = zip(*sorted(zip(a,b))) # sorted by b sorted(zip(a, b), key=lambda x: x[1]) return a,b import sys from collections import defaultdict input = sys.stdin.readline I = lambda : list(map(int,input().split())) S = lambda : list(map(str,input().split())) n, = I() a = I() mem1 = defaultdict(list) mem2 = defaultdict(list) count = 0 count1 = 0 for i in range(len(a)): mem1[a[i]].append(i) if len(mem1[a[i]])>=2 and a[i] not in mem2: count+=1 mem2[a[i]] = mem1[a[i]] if len(mem1[a[i]])>=4: count1+=1 if count1>=1: ans = [] for i in mem1: if len(mem1[i])>=4: for j in mem1[i][:4]: ans.append(j+1) print("YES") print(*ans) elif count>=2: count = 0 ans = [0]*4 for i in mem2: if count==0: ans[0] = mem1[i][:2][0]+1 ans[2] = mem1[i][:2][1]+1 count+=1 elif count==1: ans[1] = mem1[i][:2][0]+1 ans[3] = mem1[i][:2][1]+1 count+=1 if count==2: break print('YES') print(*ans) elif count==1: countx = 0 s = 0 ans = [] for i in mem2: s = 2*i ans = [j+1 for j in mem2[i]] for i in range(len(a)): if a[i]==(s//2): continue for j in range(i+1,len(a)): if a[i]+a[j]==s: ans.append(i+1) ans.append(j+1) countx = 1 break if countx==1: break if countx!=0: print('YES') print(*ans) else: ans = [] countx = 0 mem3 = defaultdict(list) for i in range(len(a)): for j in range(i+1,len(a)): if (a[i]+a[j]) in mem3 and (i+1) not in mem3[a[i]+a[j]][0] and (j+1) not in mem3[a[i]+a[j]][0]: countx = 1 print('YES') print(*mem3[a[i]+a[j]][0],i+1,j+1) break else: mem3[a[i]+a[j]].append([i+1,j+1]) if countx==1: break if countx==0: print('NO') else: ans = [] countx = 0 mem3 = defaultdict(list) for i in range(len(a)): for j in range(i+1,len(a)): if (a[i]+a[j]) in mem3 and (i+1) not in mem3[a[i]+a[j]][0] and (j+1) not in mem3[a[i]+a[j]][0]: countx = 1 print('YES') print(*mem3[a[i]+a[j]][0],i+1,j+1) break else: mem3[a[i]+a[j]].append([i+1,j+1]) if countx==1: break if countx==0: print('NO') ``` No
88,652
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≀ n ≀ 200 000) β€” the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2.5 β‹… 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≀ x, y, z, w ≀ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3 Submitted Solution: ``` n = int(input()) l = [int(i) for i in input().split(' ')] m = {} for i in range(0,n-1): for j in range(i+1, n): sm = l[i]+l[j] if sm in m: k,l = m[sm] print(k,l) if (k != i and k != j) and (l != i and l != j): print("YES") print(i+1,j+1,k+1,l+1) quit() else: m[sm] = [i,j] print("NO") ``` No
88,653
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≀ n ≀ 200 000) β€” the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2.5 β‹… 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≀ x, y, z, w ≀ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3 Submitted Solution: ``` n = int(input()) n_array = list(map(int, input().split())) for x_index in range(n-3): for y_index in range(x_index+1, n-2): for z_index in range(y_index+1, n-1): for w_index in range(z_index+1, n): if (n_array[x_index] + n_array[y_index] == n_array[z_index] + n_array[w_index]): print(x_index+1, y_index+1, z_index+1, w_index+1, sep = " ") exit() elif (n_array[x_index] + n_array[z_index] == n_array[y_index] + n_array[w_index]): print(x_index+1, z_index+1, y_index+1, w_index+1, sep = " ") exit() elif (n_array[x_index] + n_array[w_index] == n_array[z_index] + n_array[y_index]): print(x_index+1, w_index+1, z_index+1, y_index+1, sep = " ") exit() print("NO") ``` No
88,654
Provide tags and a correct Python 3 solution for this coding contest problem. There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m. The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate. Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed. Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens. For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. Then the descriptions of t testcases follow. The first line of each testcase contains two integers n and m (1 ≀ n ≀ 3 β‹… 10^5; 2 ≀ m ≀ 10^8) β€” the number of robots and the coordinate of the right wall. The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β€” the starting coordinates of the robots. The third line of each testcase contains n space-separated characters 'L' or 'R' β€” the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates x_i in the testcase are distinct. The sum of n over all testcases doesn't exceed 3 β‹… 10^5. Output For each testcase print n integers β€” for the i-th robot output the time it explodes at if it does and -1 otherwise. Example Input 5 7 12 1 2 3 4 9 10 11 R R L L R R R 2 10 1 6 R R 2 10 1 3 L L 1 10 5 R 7 8 6 1 7 2 3 5 4 R L R L L L L Output 1 1 1 1 2 -1 2 -1 -1 2 2 -1 -1 2 7 3 2 7 3 Note Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase: <image> Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer. After second 3 robot 6 just drive infinitely because there's no robot to collide with. Tags: data structures, greedy, implementation, sortings Correct Solution: ``` import sys def task_c(): input = sys.stdin.readline for _ in range(int(input())): n, m = map(int, input().split()) pos = list(map(int, input().split())) dir = list(map(str, input().split())) robots = [(pos[i], 1 if dir[i] == "R" else -1, i) for i in range(n)] ans = [-1] * n def solve(v): v.sort(key=lambda x: x[0]) stk = [] for x, dir, id in v: if dir == -1: if stk: x2, dir2, id2 = stk.pop() if dir2 == 1: ans[id] = ans[id2] = (x - x2) // 2 else: ans[id] = ans[id2] = (x + x2) // 2 else: stk.append((x, dir, id)) else: stk.append((x, dir, id)) while len(stk) >= 2: x, dir, id = stk.pop() x2, dir2, id2 = stk.pop() if dir2 == 1: ans[id] = ans[id2] = (2*m - x - x2) // 2 else: ans[id] = ans[id2] = (2*m - x + x2) // 2 solve([r for r in robots if r[0] % 2 == 0]) solve([r for r in robots if r[0] % 2 == 1]) print(*ans) task_c() ```
88,655
Provide tags and a correct Python 3 solution for this coding contest problem. There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m. The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate. Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed. Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens. For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. Then the descriptions of t testcases follow. The first line of each testcase contains two integers n and m (1 ≀ n ≀ 3 β‹… 10^5; 2 ≀ m ≀ 10^8) β€” the number of robots and the coordinate of the right wall. The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β€” the starting coordinates of the robots. The third line of each testcase contains n space-separated characters 'L' or 'R' β€” the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates x_i in the testcase are distinct. The sum of n over all testcases doesn't exceed 3 β‹… 10^5. Output For each testcase print n integers β€” for the i-th robot output the time it explodes at if it does and -1 otherwise. Example Input 5 7 12 1 2 3 4 9 10 11 R R L L R R R 2 10 1 6 R R 2 10 1 3 L L 1 10 5 R 7 8 6 1 7 2 3 5 4 R L R L L L L Output 1 1 1 1 2 -1 2 -1 -1 2 2 -1 -1 2 7 3 2 7 3 Note Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase: <image> Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer. After second 3 robot 6 just drive infinitely because there's no robot to collide with. Tags: data structures, greedy, implementation, sortings Correct Solution: ``` def solve(robot, m, res): robot.sort() stack = [] for x, dire, i in robot: if dire=='L': if not stack: stack.append((i, -x)) else: i2, x2 = stack[-1] res[i] = res[i2] = (x-x2)//2 stack.pop() else: stack.append((i,x)) while len(stack) >= 2: i1, x1 = stack[-1] stack.pop() x1 = m + (m-x1) i2, x2 = stack[-1] stack.pop() res[i1] = res[i2] = (x1-x2)//2 for _ in range(int(input())): n, m = map(int,input().split()) info = list(zip(map(int,input().split()),input().split())) robot = [[],[]] for i in range(n): x, dire = info[i] robot[x&1].append((x, dire, i)) res = [-1 for i in range(n)] solve(robot[0], m, res) solve(robot[1], m, res) print(*res) ```
88,656
Provide tags and a correct Python 3 solution for this coding contest problem. There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m. The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate. Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed. Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens. For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. Then the descriptions of t testcases follow. The first line of each testcase contains two integers n and m (1 ≀ n ≀ 3 β‹… 10^5; 2 ≀ m ≀ 10^8) β€” the number of robots and the coordinate of the right wall. The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β€” the starting coordinates of the robots. The third line of each testcase contains n space-separated characters 'L' or 'R' β€” the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates x_i in the testcase are distinct. The sum of n over all testcases doesn't exceed 3 β‹… 10^5. Output For each testcase print n integers β€” for the i-th robot output the time it explodes at if it does and -1 otherwise. Example Input 5 7 12 1 2 3 4 9 10 11 R R L L R R R 2 10 1 6 R R 2 10 1 3 L L 1 10 5 R 7 8 6 1 7 2 3 5 4 R L R L L L L Output 1 1 1 1 2 -1 2 -1 -1 2 2 -1 -1 2 7 3 2 7 3 Note Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase: <image> Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer. After second 3 robot 6 just drive infinitely because there's no robot to collide with. Tags: data structures, greedy, implementation, sortings Correct Solution: ``` def solve(robots,ans,m): robots.sort() stack=[] for x,dire,i in robots: if dire=='L': if not stack: stack.append((i,-x)) else: i1,x1=stack[-1] stack.pop() ans[i]=ans[i1]=(x-x1)//2 else: stack.append((i,x)) while len(stack)>=2: i1,x1=stack[-1] stack.pop() x1=m+(m-x1) i2,x2=stack[-1] stack.pop() ans[i1]=ans[i2]=(x1-x2)//2 for i in range(int(input())): n,m=map(int,input().split()) z=list(zip(map(int,input().split()),input().split())) robots=[[],[]] for i in range(n): x=z[i] robots[z[i][0]&1].append((z[i][0],z[i][1],i)) ans=[-1]*n solve(robots[0],ans,m) solve(robots[1],ans,m) print(*ans) ```
88,657
Provide tags and a correct Python 3 solution for this coding contest problem. There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m. The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate. Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed. Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens. For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. Then the descriptions of t testcases follow. The first line of each testcase contains two integers n and m (1 ≀ n ≀ 3 β‹… 10^5; 2 ≀ m ≀ 10^8) β€” the number of robots and the coordinate of the right wall. The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β€” the starting coordinates of the robots. The third line of each testcase contains n space-separated characters 'L' or 'R' β€” the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates x_i in the testcase are distinct. The sum of n over all testcases doesn't exceed 3 β‹… 10^5. Output For each testcase print n integers β€” for the i-th robot output the time it explodes at if it does and -1 otherwise. Example Input 5 7 12 1 2 3 4 9 10 11 R R L L R R R 2 10 1 6 R R 2 10 1 3 L L 1 10 5 R 7 8 6 1 7 2 3 5 4 R L R L L L L Output 1 1 1 1 2 -1 2 -1 -1 2 2 -1 -1 2 7 3 2 7 3 Note Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase: <image> Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer. After second 3 robot 6 just drive infinitely because there's no robot to collide with. Tags: data structures, greedy, implementation, sortings Correct Solution: ``` from sys import stdin, stdout import heapq from collections import defaultdict import math import bisect import io, os # for interactive problem # n = int(stdin.readline()) # print(x, flush=True) #input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline ans = [] def do(arr, m): global ans arr.sort() stack = [] for x, d, pos in arr: if not stack: stack.append((x, d, pos)) continue # bomb if d == "L" and stack[-1][1] == "R": ans[pos] = (x - stack[-1][0]) // 2 ans[stack[-1][2]] = (x - stack[-1][0]) // 2 stack.pop() continue stack.append((x, d, pos)) if not stack: return # bomb l first then pos_l = 0 while pos_l < len(stack) and stack[pos_l][1] == "L": pos_l += 1 L = stack[:pos_l] R = stack[pos_l:] L.reverse() while L: if len(L) == 1: break l1, _, pos1 = L.pop() l2, _, pos2 = L.pop() ans[pos1] = (l2 - l1) // 2 + l1 ans[pos2] = (l2 - l1) // 2 + l1 while R: if len(R) == 1: break r1, _, pos1 = R.pop() r2, _, pos2 = R.pop() ans[pos1] = (r1 - r2) // 2 + (m - r1) ans[pos2] = (r1 - r2) // 2 + (m - r1) if L and R: l, _, pos_l = L[0] r, _, pos_r = R[0] ans[pos_l] = (2 * m + l - r) // 2 ans[pos_r] = (2 * m + l - r) // 2 def main(): global ans t = int(stdin.readline()) for _ in range(t): #n = int(input()) n,m = list(map(int, stdin.readline().split())) arr = list(map(int, stdin.readline().split())) direc = list(map(str, stdin.readline().split())) ans = [-1] * n even = [] odd = [] for i in range(n): if arr[i] % 2 == 0: even.append((arr[i], direc[i], i)) else: odd.append((arr[i], direc[i], i)) do(even, m) do(odd, m) stdout.write(" ".join([str(x) for x in ans]) + "\n") main() ```
88,658
Provide tags and a correct Python 3 solution for this coding contest problem. There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m. The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate. Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed. Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens. For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. Then the descriptions of t testcases follow. The first line of each testcase contains two integers n and m (1 ≀ n ≀ 3 β‹… 10^5; 2 ≀ m ≀ 10^8) β€” the number of robots and the coordinate of the right wall. The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β€” the starting coordinates of the robots. The third line of each testcase contains n space-separated characters 'L' or 'R' β€” the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates x_i in the testcase are distinct. The sum of n over all testcases doesn't exceed 3 β‹… 10^5. Output For each testcase print n integers β€” for the i-th robot output the time it explodes at if it does and -1 otherwise. Example Input 5 7 12 1 2 3 4 9 10 11 R R L L R R R 2 10 1 6 R R 2 10 1 3 L L 1 10 5 R 7 8 6 1 7 2 3 5 4 R L R L L L L Output 1 1 1 1 2 -1 2 -1 -1 2 2 -1 -1 2 7 3 2 7 3 Note Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase: <image> Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer. After second 3 robot 6 just drive infinitely because there's no robot to collide with. Tags: data structures, greedy, implementation, sortings Correct Solution: ``` def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0x0f0f0f0f x = x + (x >> 8) x = x + (x >> 16) return x & 0x0000007f def eratosthenes(n): res=[0 for i in range(n+1)] prime=set([]) for i in range(2,n+1): if not res[i]: prime.add(i) for j in range(1,n//i+1): res[i*j]=1 return prime def factorization(n): res=[] for p in prime: if n%p==0: while n%p==0: n//=p res.append(p) if n!=1: res.append(n) return res def euler_phi(n): res = n for x in range(2,n+1): if x ** 2 > n: break if n%x==0: res = res//x * (x-1) while n%x==0: n //= x if n!=1: res = res//n * (n-1) return res def ind(b,n): res=0 while n%b==0: res+=1 n//=b return res def isPrimeMR(n): d = n - 1 d = d // (d & -d) L = [2, 3, 5, 7, 11, 13, 17] for a in L: t = d y = pow(a, t, n) if y == 1: continue while y != n - 1: y = (y * y) % n if y == 1 or t == n - 1: return 0 t <<= 1 return 1 def findFactorRho(n): from math import gcd m = 1 << n.bit_length() // 8 for c in range(1, 99): f = lambda x: (x * x + c) % n y, r, q, g = 2, 1, 1, 1 while g == 1: x = y for i in range(r): y = f(y) k = 0 while k < r and g == 1: ys = y for i in range(min(m, r - k)): y = f(y) q = q * abs(x - y) % n g = gcd(q, n) k += m r <<= 1 if g == n: g = 1 while g == 1: ys = f(ys) g = gcd(abs(x - ys), n) if g < n: if isPrimeMR(g): return g elif isPrimeMR(n // g): return n // g return findFactorRho(g) def primeFactor(n): i = 2 ret = {} rhoFlg = 0 while i*i <= n: k = 0 while n % i == 0: n //= i k += 1 if k: ret[i] = k i += 1 + i % 2 if i == 101 and n >= 2 ** 20: while n > 1: if isPrimeMR(n): ret[n], n = 1, 1 else: rhoFlg = 1 j = findFactorRho(n) k = 0 while n % j == 0: n //= j k += 1 ret[j] = k if n > 1: ret[n] = 1 if rhoFlg: ret = {x: ret[x] for x in sorted(ret)} return ret def divisors(n): res = [1] prime = primeFactor(n) for p in prime: newres = [] for d in res: for j in range(prime[p]+1): newres.append(d*p**j) res = newres res.sort() return res def xorfactorial(num): if num==0: return 0 elif num==1: return 1 elif num==2: return 3 elif num==3: return 0 else: x=baseorder(num) return (2**x)*((num-2**x+1)%2)+function(num-2**x) def xorconv(n,X,Y): if n==0: res=[(X[0]*Y[0])%mod] return res x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))] y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))] z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))] w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))] res1=xorconv(n-1,x,y) res2=xorconv(n-1,z,w) former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))] latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))] former=list(map(lambda x:x%mod,former)) latter=list(map(lambda x:x%mod,latter)) return former+latter def merge_sort(A,B): pos_A,pos_B = 0,0 n,m = len(A),len(B) res = [] while pos_A < n and pos_B < m: a,b = A[pos_A],B[pos_B] if a < b: res.append(a) pos_A += 1 else: res.append(b) pos_B += 1 res += A[pos_A:] res += B[pos_B:] return res class UnionFindVerSize(): def __init__(self, N): self._parent = [n for n in range(0, N)] self._size = [1] * N self.group = N def find_root(self, x): if self._parent[x] == x: return x self._parent[x] = self.find_root(self._parent[x]) stack = [x] while self._parent[stack[-1]]!=stack[-1]: stack.append(self._parent[stack[-1]]) for v in stack: self._parent[v] = stack[-1] return self._parent[x] def unite(self, x, y): gx = self.find_root(x) gy = self.find_root(y) if gx == gy: return self.group -= 1 if self._size[gx] < self._size[gy]: self._parent[gx] = gy self._size[gy] += self._size[gx] else: self._parent[gy] = gx self._size[gx] += self._size[gy] def get_size(self, x): return self._size[self.find_root(x)] def is_same_group(self, x, y): return self.find_root(x) == self.find_root(y) class WeightedUnionFind(): def __init__(self,N): self.parent = [i for i in range(N)] self.size = [1 for i in range(N)] self.val = [0 for i in range(N)] self.flag = True self.edge = [[] for i in range(N)] def dfs(self,v,pv): stack = [(v,pv)] new_parent = self.parent[pv] while stack: v,pv = stack.pop() self.parent[v] = new_parent for nv,w in self.edge[v]: if nv!=pv: self.val[nv] = self.val[v] + w stack.append((nv,v)) def unite(self,x,y,w): if not self.flag: return if self.parent[x]==self.parent[y]: self.flag = (self.val[x] - self.val[y] == w) return if self.size[self.parent[x]]>self.size[self.parent[y]]: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[x] += self.size[y] self.val[y] = self.val[x] - w self.dfs(y,x) else: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[y] += self.size[x] self.val[x] = self.val[y] + w self.dfs(x,y) class Dijkstra(): class Edge(): def __init__(self, _to, _cost): self.to = _to self.cost = _cost def __init__(self, V): self.G = [[] for i in range(V)] self._E = 0 self._V = V @property def E(self): return self._E @property def V(self): return self._V def add_edge(self, _from, _to, _cost): self.G[_from].append(self.Edge(_to, _cost)) self._E += 1 def shortest_path(self, s): import heapq que = [] d = [10**15] * self.V d[s] = 0 heapq.heappush(que, (0, s)) while len(que) != 0: cost, v = heapq.heappop(que) if d[v] < cost: continue for i in range(len(self.G[v])): e = self.G[v][i] if d[e.to] > d[v] + e.cost: d[e.to] = d[v] + e.cost heapq.heappush(que, (d[e.to], e.to)) return d #Z[i]:length of the longest list starting from S[i] which is also a prefix of S #O(|S|) def Z_algorithm(s): N = len(s) Z_alg = [0]*N Z_alg[0] = N i = 1 j = 0 while i < N: while i+j < N and s[j] == s[i+j]: j += 1 Z_alg[i] = j if j == 0: i += 1 continue k = 1 while i+k < N and k + Z_alg[k]<j: Z_alg[i+k] = Z_alg[k] k += 1 i += k j -= k return Z_alg class BIT(): def __init__(self,n,mod=0): self.BIT = [0]*(n+1) self.num = n self.mod = mod def query(self,idx): res_sum = 0 mod = self.mod while idx > 0: res_sum += self.BIT[idx] if mod: res_sum %= mod idx -= idx&(-idx) return res_sum #Ai += x O(logN) def update(self,idx,x): mod = self.mod while idx <= self.num: self.BIT[idx] += x if mod: self.BIT[idx] %= mod idx += idx&(-idx) return class dancinglink(): def __init__(self,n,debug=False): self.n = n self.debug = debug self._left = [i-1 for i in range(n)] self._right = [i+1 for i in range(n)] self.exist = [True for i in range(n)] def pop(self,k): if self.debug: assert self.exist[k] L = self._left[k] R = self._right[k] if L!=-1: if R!=self.n: self._right[L],self._left[R] = R,L else: self._right[L] = self.n elif R!=self.n: self._left[R] = -1 self.exist[k] = False def left(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._left[res] if res==-1: break k -= 1 return res def right(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._right[res] if res==self.n: break k -= 1 return res class SparseTable(): def __init__(self,A,merge_func,ide_ele): N=len(A) n=N.bit_length() self.table=[[ide_ele for i in range(n)] for i in range(N)] self.merge_func=merge_func for i in range(N): self.table[i][0]=A[i] for j in range(1,n): for i in range(0,N-2**j+1): f=self.table[i][j-1] s=self.table[i+2**(j-1)][j-1] self.table[i][j]=self.merge_func(f,s) def query(self,s,t): b=t-s+1 m=b.bit_length()-1 return self.merge_func(self.table[s][m],self.table[t-2**m+1][m]) class BinaryTrie: class node: def __init__(self,val): self.left = None self.right = None self.max = val def __init__(self): self.root = self.node(-10**15) def append(self,key,val): pos = self.root for i in range(29,-1,-1): pos.max = max(pos.max,val) if key>>i & 1: if pos.right is None: pos.right = self.node(val) pos = pos.right else: pos = pos.right else: if pos.left is None: pos.left = self.node(val) pos = pos.left else: pos = pos.left pos.max = max(pos.max,val) def search(self,M,xor): res = -10**15 pos = self.root for i in range(29,-1,-1): if pos is None: break if M>>i & 1: if xor>>i & 1: if pos.right: res = max(res,pos.right.max) pos = pos.left else: if pos.left: res = max(res,pos.left.max) pos = pos.right else: if xor>>i & 1: pos = pos.right else: pos = pos.left if pos: res = max(res,pos.max) return res def solveequation(edge,ans,n,m): #edge=[[to,dire,id]...] x=[0]*m used=[False]*n for v in range(n): if used[v]: continue y = dfs(v) if y!=0: return False return x def dfs(v): used[v]=True r=ans[v] for to,dire,id in edge[v]: if used[to]: continue y=dfs(to) if dire==-1: x[id]=y else: x[id]=-y r+=y return r class SegmentTree: def __init__(self, init_val, segfunc, ide_ele): n = len(init_val) self.segfunc = segfunc self.ide_ele = ide_ele self.num = 1 << (n - 1).bit_length() self.tree = [ide_ele] * 2 * self.num self.size = n for i in range(n): self.tree[self.num + i] = init_val[i] for i in range(self.num - 1, 0, -1): self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1]) def update(self, k, x): k += self.num self.tree[k] = x while k > 1: self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1]) k >>= 1 def query(self, l, r): if r==self.size: r = self.num res = self.ide_ele l += self.num r += self.num while l < r: if l & 1: res = self.segfunc(res, self.tree[l]) l += 1 if r & 1: res = self.segfunc(res, self.tree[r - 1]) l >>= 1 r >>= 1 return res def bisect_l(self,l,r,x): l += self.num r += self.num Lmin = -1 Rmin = -1 while l<r: if l & 1: if self.tree[l] <= x and Lmin==-1: Lmin = l l += 1 if r & 1: if self.tree[r-1] <=x: Rmin = r-1 l >>= 1 r >>= 1 if Lmin != -1: pos = Lmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num elif Rmin != -1: pos = Rmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num else: return -1 import sys,random,bisect from collections import deque,defaultdict from heapq import heapify,heappop,heappush from itertools import permutations from math import gcd,log input = lambda :sys.stdin.readline().rstrip() mi = lambda :map(int,input().split()) li = lambda :list(mi()) for _ in range(int(input())): n,m = mi() X = li() D = [d for d in input().split()] ans = [-1 for i in range(n)] even = [] odd = [] for i in range(n): if X[i]&1: odd.append((X[i],i)) else: even.append((X[i],i)) even.sort(key=lambda x:x[0]) odd.sort(key=lambda x:x[0]) #print(even) stack = [] for x,idx in even: if D[idx]=="L": if not stack: stack.append((-x,idx)) else: x0,idx0 = stack.pop() t = (x-x0)//2 ans[idx] = t ans[idx0] = t else: stack.append((x,idx)) even = stack[::-1] stack = [] for x,idx in even: if not stack: stack.append((2*m-x,idx)) else: x0,idx0 = stack.pop() t = (x0-x)//2 ans[idx] = t ans[idx0] = t stack = [] #print(odd) for x,idx in odd: #print(stack,D[idx]) if D[idx]=="L": if not stack: stack.append((-x,idx)) else: x0,idx0 = stack.pop() #print(x0,idx0,x,idx) t = (x-x0)//2 ans[idx] = t ans[idx0] = t else: stack.append((x,idx)) odd = stack[::-1] stack = [] for x,idx in odd: if not stack: stack.append((2*m-x,idx)) else: x0,idx0 = stack.pop() t = (x0-x)//2 ans[idx] = t ans[idx0] = t print(*ans) ```
88,659
Provide tags and a correct Python 3 solution for this coding contest problem. There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m. The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate. Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed. Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens. For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. Then the descriptions of t testcases follow. The first line of each testcase contains two integers n and m (1 ≀ n ≀ 3 β‹… 10^5; 2 ≀ m ≀ 10^8) β€” the number of robots and the coordinate of the right wall. The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β€” the starting coordinates of the robots. The third line of each testcase contains n space-separated characters 'L' or 'R' β€” the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates x_i in the testcase are distinct. The sum of n over all testcases doesn't exceed 3 β‹… 10^5. Output For each testcase print n integers β€” for the i-th robot output the time it explodes at if it does and -1 otherwise. Example Input 5 7 12 1 2 3 4 9 10 11 R R L L R R R 2 10 1 6 R R 2 10 1 3 L L 1 10 5 R 7 8 6 1 7 2 3 5 4 R L R L L L L Output 1 1 1 1 2 -1 2 -1 -1 2 2 -1 -1 2 7 3 2 7 3 Note Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase: <image> Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer. After second 3 robot 6 just drive infinitely because there's no robot to collide with. Tags: data structures, greedy, implementation, sortings Correct Solution: ``` import sys input = sys.stdin.readline for _ in range(int(input())): n,m = map(int,input().split()) time = [-1]*n # in sorted order x = list(map(int,input().split())) dir = input().split() a = sorted(list(zip(x,dir,list(range(n))))) x,dir,idx = map(list,list(zip(*a))) s = [] s2 = [] for i in range(n): if x[i] & 1: if dir[i] == 'R': s.append(i) elif s: j = s.pop() time[j] = time[i] = abs(x[j] - x[i])//2 else: if dir[i] == 'R': s2.append(i) elif s2: j = s2.pop() time[j] = time[i] = abs(x[j] - x[i]) // 2 s = [] s2 = [] for i in range(n): if time[i] == -1 and dir[i] == 'L': if x[i] & 1: if s: j = s.pop() time[j] = time[i] = abs(x[j] - x[i])//2 + x[j] else: s.append(i) else: if s2: j = s2.pop() time[j] = time[i] = abs(x[j] - x[i])//2 + x[j] else: s2.append(i) s = [] s2 = [] for i in range(n-1,-1,-1): if time[i] == -1 and dir[i] == 'R': if x[i] & 1: if s: j = s.pop() time[j] = time[i] = abs(x[j] - x[i]) // 2 + m - x[j] else: s.append(i) else: if s2: j = s2.pop() time[j] = time[i] = abs(x[j] - x[i]) // 2 + m - x[j] else: s2.append(i) L_loc = R_loc = -1 L_loc2 = R_loc2 = -1 for i in range(n): if x[i] & 1: if time[i] == -1 and dir[i] == 'L': L_loc = i else: if time[i] == -1 and dir[i] == 'L': L_loc2 = i for i in range(n-1,-1,-1): if x[i] & 1: if time[i] == -1 and dir[i] == 'R': R_loc = i else: if time[i] == -1 and dir[i] == 'R': R_loc2 = i if L_loc != -1 and R_loc != -1: time[L_loc] = time[R_loc] = (2*m - (x[R_loc]-x[L_loc]))//2 if L_loc2 != -1 and R_loc2 != -1: time[L_loc2] = time[R_loc2] = (2*m - (x[R_loc2]-x[L_loc2]))//2 true_time = [0]*n for i in range(n): true_time[idx[i]] = time[i] print(*true_time) ```
88,660
Provide tags and a correct Python 3 solution for this coding contest problem. There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m. The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate. Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed. Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens. For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. Then the descriptions of t testcases follow. The first line of each testcase contains two integers n and m (1 ≀ n ≀ 3 β‹… 10^5; 2 ≀ m ≀ 10^8) β€” the number of robots and the coordinate of the right wall. The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β€” the starting coordinates of the robots. The third line of each testcase contains n space-separated characters 'L' or 'R' β€” the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates x_i in the testcase are distinct. The sum of n over all testcases doesn't exceed 3 β‹… 10^5. Output For each testcase print n integers β€” for the i-th robot output the time it explodes at if it does and -1 otherwise. Example Input 5 7 12 1 2 3 4 9 10 11 R R L L R R R 2 10 1 6 R R 2 10 1 3 L L 1 10 5 R 7 8 6 1 7 2 3 5 4 R L R L L L L Output 1 1 1 1 2 -1 2 -1 -1 2 2 -1 -1 2 7 3 2 7 3 Note Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase: <image> Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer. After second 3 robot 6 just drive infinitely because there's no robot to collide with. Tags: data structures, greedy, implementation, sortings Correct Solution: ``` import sys import math #input = sys.stdin.readline imp = 'IMPOSSIBLE' t = int(input()) for test in range(t): n, m = list(map(int, input().split(" "))) xx = list(map(int, input().split(" "))) sorx = sorted(enumerate(xx), key=lambda z: z[1]) porx = [i[0] for i in sorx] invpor = [i[0] for i in sorted(enumerate(porx), key=lambda z: z[1])] x = [i[1] for i in sorx] res = ['' for i in range(n)] ss = input().split(" ") if test != t - 1: ss[-1] = ss[-1][0] s = [ss[i[0]] for i in sorx] lastl1 = -1 lastl2 = -1 pairs = [] r1 = [] r2 = [] #if test == t - 1: # print(porx) # print(invpor) # print(x) # print(s) for i in range(n): if x[i] % 2 == 1: if s[i] == 'L': if r1: rr = r1.pop() pairs.append([rr, i]) elif lastl1 == -1: lastl1 = i else: pairs.append([lastl1, i]) lastl1 = -1 else: r1.append(i) else: if s[i] == 'L': if r2: rr = r2.pop() pairs.append([rr, i]) elif lastl2 == -1: lastl2 = i else: pairs.append([lastl2, i]) lastl2 = -1 else: r2.append(i) lastr1 = -1 lastr2 = -1 #print(pairs) while r1: if lastr1 == -1: lastr1 = r1.pop() else: rr = r1.pop() pairs.append([lastr1, rr]) lastr1 = -1 #print(pairs) while r2: if lastr2 == -1: lastr2 = r2.pop() else: rr = r2.pop() pairs.append([lastr2, rr]) lastr2 = -1 #print(pairs) if lastr1 > -1 and (lastl1 > -1): pairs.append([lastl1, lastr1]) lastl1 = -1 lastr1 = -1 elif lastl1 > -1: res[lastl1] = '-1' elif lastr1 > -1: res[lastr1] = '-1' if lastr2 > -1 and (lastl2 > -1): pairs.append([lastl2, lastr2]) lastl2 = -1 lastr2 = -1 elif lastl2 > -1: res[lastl2] = '-1' elif lastr2 > -1: res[lastr2] = '-1' #print(res) #print(pairs) #print(s) for pair in pairs: if s[pair[0]] == 'L': if s[pair[1]] == 'L': res[pair[0]] = str((x[pair[0]] + x[pair[1]]) // 2) res[pair[1]] = str((x[pair[0]] + x[pair[1]]) // 2) else: if x[pair[0]] > x[pair[1]]: res[pair[0]] = str((x[pair[0]] - x[pair[1]]) // 2) res[pair[1]] = str((x[pair[0]] - x[pair[1]]) // 2) else: res[pair[0]] = str((x[pair[0]] + 2 * m - x[pair[1]]) // 2) res[pair[1]] = str((x[pair[0]] + 2 * m - x[pair[1]]) // 2) else: if s[pair[1]] == 'R': res[pair[0]] = str((2 * m - x[pair[0]] - x[pair[1]]) // 2) res[pair[1]] = str((2 * m - x[pair[0]] - x[pair[1]]) // 2) else: if x[pair[0]] < x[pair[1]]: res[pair[0]] = str((x[pair[1]] - x[pair[0]]) // 2) res[pair[1]] = str((x[pair[1]] - x[pair[0]]) // 2) else: res[pair[0]] = str((x[pair[1]] + 2 * m - x[pair[0]]) // 2) res[pair[1]] = str((x[pair[1]] + 2 * m - x[pair[0]]) // 2) #print(invpor) resres = [res[i] for i in invpor] print(' '.join(resres)) ```
88,661
Provide tags and a correct Python 3 solution for this coding contest problem. There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m. The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate. Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed. Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens. For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. Then the descriptions of t testcases follow. The first line of each testcase contains two integers n and m (1 ≀ n ≀ 3 β‹… 10^5; 2 ≀ m ≀ 10^8) β€” the number of robots and the coordinate of the right wall. The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β€” the starting coordinates of the robots. The third line of each testcase contains n space-separated characters 'L' or 'R' β€” the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates x_i in the testcase are distinct. The sum of n over all testcases doesn't exceed 3 β‹… 10^5. Output For each testcase print n integers β€” for the i-th robot output the time it explodes at if it does and -1 otherwise. Example Input 5 7 12 1 2 3 4 9 10 11 R R L L R R R 2 10 1 6 R R 2 10 1 3 L L 1 10 5 R 7 8 6 1 7 2 3 5 4 R L R L L L L Output 1 1 1 1 2 -1 2 -1 -1 2 2 -1 -1 2 7 3 2 7 3 Note Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase: <image> Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer. After second 3 robot 6 just drive infinitely because there's no robot to collide with. Tags: data structures, greedy, implementation, sortings Correct Solution: ``` import sys, os from io import BytesIO, IOBase from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log from collections import defaultdict as dd, deque from heapq import merge, heapify, heappop, heappush, nsmallest from bisect import bisect_left as bl, bisect_right as br, bisect # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") stdin, stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) mod = pow(10, 9) + 7 mod2 = 998244353 def inp(): return stdin.readline().strip() def iinp(): return int(inp()) def out(var, end="\n"): stdout.write(str(var)+"\n") def outa(*var, end="\n"): stdout.write(' '.join(map(str, var)) + end) def lmp(): return list(mp()) def mp(): return map(int, inp().split()) def smp(): return map(str, inp().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(m, val) for j in range(n)] def remadd(x, y): return 1 if x%y else 0 def ceil(a,b): return (a+b-1)//b S1 = 'abcdefghijklmnopqrstuvwxyz' S2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def isprime(x): if x<=1: return False if x in (2, 3): return True if x%2 == 0: return False for i in range(3, int(sqrt(x))+1, 2): if x%i == 0: return False return True def solve(arr, n, m, ansl): pre = [] for i in arr: if i[1] == 'R': pre.append(i) else: if len(pre)==0: pre.append((-i[0], 'R', i[2])) else: x = (i[0]-pre[-1][0])//2 ansl[i[2]] = x ansl[pre[-1][2]] = x pre.pop() while len(pre)>1: a = pre.pop() b = pre.pop() x = m - (a[0]+b[0])//2 ansl[a[2]] = x ansl[b[2]] = x return ansl for _ in range(int(inp())): n, m = mp() arr = lmp() s = list(inp().split()) ansl = l1d(n, -1) odd = [(arr[i], s[i], i) for i in range(n) if arr[i]%2] even = [(arr[i], s[i], i) for i in range(n) if arr[i]%2==0] odd.sort() even.sort() ansl = solve(odd, len(odd), m, ansl) ansl = solve(even, len(even), m, ansl) outa(*ansl) ```
88,662
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m. The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate. Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed. Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens. For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. Then the descriptions of t testcases follow. The first line of each testcase contains two integers n and m (1 ≀ n ≀ 3 β‹… 10^5; 2 ≀ m ≀ 10^8) β€” the number of robots and the coordinate of the right wall. The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β€” the starting coordinates of the robots. The third line of each testcase contains n space-separated characters 'L' or 'R' β€” the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates x_i in the testcase are distinct. The sum of n over all testcases doesn't exceed 3 β‹… 10^5. Output For each testcase print n integers β€” for the i-th robot output the time it explodes at if it does and -1 otherwise. Example Input 5 7 12 1 2 3 4 9 10 11 R R L L R R R 2 10 1 6 R R 2 10 1 3 L L 1 10 5 R 7 8 6 1 7 2 3 5 4 R L R L L L L Output 1 1 1 1 2 -1 2 -1 -1 2 2 -1 -1 2 7 3 2 7 3 Note Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase: <image> Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer. After second 3 robot 6 just drive infinitely because there's no robot to collide with. Submitted Solution: ``` from collections import deque def solve(n,m,x,d): even = [] odd = [] for i in range(n): if x[i] & 1: odd.append((i,x[i],d[i])) else: even.append((i,x[i],d[i])) even_solution = stacksolve(even, m) odd_solution = stacksolve(odd, m) ans = [] for i in range(n): if i in even_solution: ans.append(even_solution[i]) else: ans.append(odd_solution[i]) return ' '.join(map(str, ans)) def stacksolve(iarr, m): rdeque = deque([]) ldeque = deque([]) iarr.sort(key=lambda e:e[1]) #print(iarr) ans = {} for i,x,d in iarr: if d == 'R': rdeque.append((i,x,d)) else: if len(rdeque) > 0: li,lx,ld = i,x,d ri,rx,rd = rdeque.pop() t = abs(lx-rx) >> 1 ans[li] = t ans[ri] = t else: ldeque.append((i,x,d)) while len(ldeque) >= 2: i1,x1,d1 = ldeque.popleft() i2,x2,d2 = ldeque.popleft() t = x1 + (abs(x2-x1)//2) ans[i1] = t ans[i2] = t while len(rdeque) >= 2: i1,x1,d1 = rdeque.pop() i2,x2,d2 = rdeque.pop() t = (m-x1) + (abs(x1-x2)//2) ans[i1] = t ans[i2] = t if len(ldeque) == 1 and len(rdeque) == 1: ir,xr,dr = rdeque.pop() il,xl,dl = ldeque.pop() xa, xb = xl, m-xr minx, maxx = min(xa,xb), max(xa,xb) t = minx + ((m+maxx-minx)//2) ans[il] = t ans[ir] = t elif len(ldeque) == 1: i,x,d = ldeque.pop() ans[i] = -1 elif len(rdeque) == 1: i,x,d = rdeque.pop() ans[i] = -1 return ans if __name__ == '__main__': T = int(input()) for t in range(T): n,m = tuple(map(int, input().split())) x = list(map(int,input().split())) d = input().split() print(solve(n,m,x,d)) ``` Yes
88,663
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m. The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate. Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed. Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens. For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. Then the descriptions of t testcases follow. The first line of each testcase contains two integers n and m (1 ≀ n ≀ 3 β‹… 10^5; 2 ≀ m ≀ 10^8) β€” the number of robots and the coordinate of the right wall. The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β€” the starting coordinates of the robots. The third line of each testcase contains n space-separated characters 'L' or 'R' β€” the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates x_i in the testcase are distinct. The sum of n over all testcases doesn't exceed 3 β‹… 10^5. Output For each testcase print n integers β€” for the i-th robot output the time it explodes at if it does and -1 otherwise. Example Input 5 7 12 1 2 3 4 9 10 11 R R L L R R R 2 10 1 6 R R 2 10 1 3 L L 1 10 5 R 7 8 6 1 7 2 3 5 4 R L R L L L L Output 1 1 1 1 2 -1 2 -1 -1 2 2 -1 -1 2 7 3 2 7 3 Note Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase: <image> Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer. After second 3 robot 6 just drive infinitely because there's no robot to collide with. Submitted Solution: ``` def binarysearch(x, l): low=0 high=len(l)-1 ans=high+1 while low<=high: mid=(low+high)//2 if l[mid][0]<x: low=mid+1 else: ans=mid high=mid-1 return ans t=int(input()) for i in range(t): n, m=input().split() n=int(n) m=int(m) u=[] v=[] p={i:-1 for i in range(n)} a=list(map(int, input().split(" "))) b=input().split(" ") for i in range(n): #u is the list of coord, dir, index for odd #v for even if a[i]%2: u.append([a[i], b[i], i]) else: v.append([a[i], b[i], i]) d=[u, v] u.sort(key=lambda x:x[0]) v.sort(key=lambda x:x[0]) #sorted by coord for listi in d: rl=[] #rl is the list of right robo, elements are of the form coord, index ll=[] #ll for left robo for i in range(len(listi)): if listi[i][1]=='R': rl.append([listi[i][0], listi[i][2]]) else: ll.append([listi[i][0], listi[i][2]]) ppp=len(rl) for j in reversed(range(ppp)): #search for left robo at a coord >=right robo ans=binarysearch(rl[j][0], ll) #if such a robo exists if ans<len(ll): p[rl[j][1]]=(ll[ans][0]-rl[j][0])/2 p[ll[ans][1]]=p[rl[j][1]] ll.pop(ans) rl.pop(j) kk=len(rl) for pp in range(kk-1, 0, -2): p[rl[pp][1]]=m-(rl[pp][0]+rl[pp-1][0])/2 p[rl[pp-1][1]]=p[rl[pp][1]] rl.pop() rl.pop() lll=len(ll) for pp in range(0, lll-1, 2): p[ll[pp][1]]=(ll[pp+1][0]+ll[pp][0])/2 p[ll[pp+1][1]]=p[ll[pp][1]] if ll and p[ll[-1][1]]==-1 and rl: p[ll[-1][1]]=(ll[-1][0]-rl[0][0])/2+m p[rl[0][1]]=p[ll[-1][1]] for i in range(len(p)): print(int(p[i]), end=" ") print() ``` Yes
88,664
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m. The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate. Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed. Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens. For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. Then the descriptions of t testcases follow. The first line of each testcase contains two integers n and m (1 ≀ n ≀ 3 β‹… 10^5; 2 ≀ m ≀ 10^8) β€” the number of robots and the coordinate of the right wall. The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β€” the starting coordinates of the robots. The third line of each testcase contains n space-separated characters 'L' or 'R' β€” the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates x_i in the testcase are distinct. The sum of n over all testcases doesn't exceed 3 β‹… 10^5. Output For each testcase print n integers β€” for the i-th robot output the time it explodes at if it does and -1 otherwise. Example Input 5 7 12 1 2 3 4 9 10 11 R R L L R R R 2 10 1 6 R R 2 10 1 3 L L 1 10 5 R 7 8 6 1 7 2 3 5 4 R L R L L L L Output 1 1 1 1 2 -1 2 -1 -1 2 2 -1 -1 2 7 3 2 7 3 Note Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase: <image> Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer. After second 3 robot 6 just drive infinitely because there's no robot to collide with. Submitted Solution: ``` for cs in range(int(input())): n, m = map(int, input().split()) X = list(map(int, input().split())) D = list(map(str, input().split())) X_odd = [] X_even = [] ans = [-1 for _ in range(n)] for i in range(n): if X[i] % 2 == 1: X_odd.append([X[i], D[i], i]) else: X_even.append([X[i], D[i], i]) X_odd.sort() X_even.sort() def F(Y): stack = [] for r in Y: if len(stack) == 0: stack.append(r) else: if r[1] == 'L': if stack[-1][1] == 'L': x = (r[0] + stack[-1][0])//2 ans[r[2]] = x ans[stack[-1][2]] = x stack.pop() else: if stack[-1][1] == 'R': ans[r[2]] = (r[0] - stack[-1][0])//2 ans[stack[-1][2]] = ans[r[2]] stack.pop() else: stack.append(r) while len(stack) > 1: f = stack[-1] stack.pop() s = stack[-1] stack.pop() if f[1] == 'R' and s[1] == 'R': ans[f[2]] = ans[s[2]] = (2*m - f[0] - s[0])//2 elif f[1] == 'R' and s[1] == 'L': ans[f[2]] = ans[s[2]] = (m - f[0] + s[0] + m)//2 F(X_odd) F(X_even) print(*ans) ``` Yes
88,665
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m. The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate. Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed. Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens. For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. Then the descriptions of t testcases follow. The first line of each testcase contains two integers n and m (1 ≀ n ≀ 3 β‹… 10^5; 2 ≀ m ≀ 10^8) β€” the number of robots and the coordinate of the right wall. The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β€” the starting coordinates of the robots. The third line of each testcase contains n space-separated characters 'L' or 'R' β€” the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates x_i in the testcase are distinct. The sum of n over all testcases doesn't exceed 3 β‹… 10^5. Output For each testcase print n integers β€” for the i-th robot output the time it explodes at if it does and -1 otherwise. Example Input 5 7 12 1 2 3 4 9 10 11 R R L L R R R 2 10 1 6 R R 2 10 1 3 L L 1 10 5 R 7 8 6 1 7 2 3 5 4 R L R L L L L Output 1 1 1 1 2 -1 2 -1 -1 2 2 -1 -1 2 7 3 2 7 3 Note Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase: <image> Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer. After second 3 robot 6 just drive infinitely because there's no robot to collide with. Submitted Solution: ``` import sys import math import bisect from sys import stdin, stdout from math import gcd, floor, sqrt, log2, ceil from collections import defaultdict as dd from bisect import bisect_left as bl, bisect_right as br from bisect import insort from collections import Counter from collections import deque from heapq import heappush,heappop,heapify from itertools import permutations,combinations from itertools import accumulate as ac mod = int(1e9)+7 ip = lambda : int(stdin.readline()) inp = lambda: map(int,stdin.readline().split()) ips = lambda: stdin.readline().rstrip() out = lambda x : stdout.write(str(x)+"\n") #ans = 'Case #{}: {}'.format(_+1,ans) t = ip() for _ in range(t): n,m = inp() arr = list(inp()) s = input().split(" ") temp = [] for i in range(n): temp.append([arr[i],s[i],i]) temp.sort() arr = list(temp) even = [] odd = [] for i in range(n): if arr[i][0]%2 == 0: even.append(arr[i]) else: odd.append(arr[i]) ans = [-1]*n mark = dd(bool) nn = len(even) i = 0 stack = [] while i<nn: #print(even[i][1],even[i-1][1]) if even[i][1] == 'R': stack.append(even[i]) else: if len(stack) == 0: pass else: val = (even[i][0] - stack[-1][0])//2 pos1 = even[i][2] pos2 = stack[-1][2] ans[pos1] = val ans[pos2] = val mark[pos1] = True mark[pos2] = True stack.pop() i += 1 rem = [] left = [] right = [] for i in range(nn): ele = even[i][2] if mark[ele]: pass else: if even[i][1] == 'L': left.append(even[i]) else: right.append(even[i]) for i in range(1,len(left),2): time = left[i-1][0] - 0 val = (left[i][0]-left[i-1][0])//2 time += val pos1 = left[i][2] pos2 = left[i-1][2] ans[pos1] = time ans[pos2] = time mark[pos1] = True mark[pos2] = True rem = [] for i in range(len(left)): pos = left[i][2] if mark[pos]: pass else: rem.append(left[i]) left = list(rem) i = len(right)-1 while i-1>= 0: time = m - right[i][0] val = (right[i][0]-right[i-1][0])//2 time += val pos1 = right[i][2] pos2 = right[i-1][2] ans[pos1] = time ans[pos2] = time mark[pos1] = True mark[pos2] = True i -= 2 rem = [] for i in range(len(right)): pos = right[i][2] if mark[pos]: pass else: rem.append(right[i]) right = list(rem) if len(left) != 0 and len(right) != 0: val1 = left[0][0] val2 = right[0][0] diff1 = val1 - 0 diff2 = m - val2 if diff1<= diff2: time = 0 val2 = m val1 = 0 time += diff2 diff2 -= diff1 val1 += diff2 val = (abs(val1-val2))//2 time += val pos1 = left[0][2] pos2 = right[0][2] ans[pos1] = time ans[pos2] = time else: time = 0 val1 = 0 val2 = m time += diff1 diff1 -= diff2 val2 -= diff1 val = (abs(val1-val2))//2 time += val pos1 = left[0][2] pos2 = right[0][2] ans[pos1] = time ans[pos2] = time even = list(odd) mark = dd(bool) nn = len(even) i = 0 stack = [] while i<nn: #print(even[i][1],even[i-1][1]) if even[i][1] == 'R': stack.append(even[i]) else: if len(stack) == 0: pass else: val = (even[i][0] - stack[-1][0])//2 pos1 = even[i][2] pos2 = stack[-1][2] ans[pos1] = val ans[pos2] = val mark[pos1] = True mark[pos2] = True stack.pop() i += 1 rem = [] left = [] right = [] for i in range(nn): ele = even[i][2] if mark[ele]: pass else: if even[i][1] == 'L': left.append(even[i]) else: right.append(even[i]) for i in range(1,len(left),2): time = left[i-1][0] - 0 val = (left[i][0]-left[i-1][0])//2 time += val pos1 = left[i][2] pos2 = left[i-1][2] ans[pos1] = time ans[pos2] = time mark[pos1] = True mark[pos2] = True rem = [] for i in range(len(left)): pos = left[i][2] if mark[pos]: pass else: rem.append(left[i]) left = list(rem) i = len(right)-1 while i-1>= 0: time = m - right[i][0] val = (right[i][0]-right[i-1][0])//2 time += val pos1 = right[i][2] pos2 = right[i-1][2] ans[pos1] = time ans[pos2] = time mark[pos1] = True mark[pos2] = True i -= 2 rem = [] for i in range(len(right)): pos = right[i][2] if mark[pos]: pass else: rem.append(right[i]) right = list(rem) if len(left) != 0 and len(right) != 0: val1 = left[0][0] val2 = right[0][0] diff1 = val1 - 0 diff2 = m - val2 if diff1<= diff2: time = 0 val2 = m val1 = 0 time += diff2 diff2 -= diff1 val1 += diff2 val = (abs(val1-val2))//2 time += val pos1 = left[0][2] pos2 = right[0][2] ans[pos1] = time ans[pos2] = time else: time = 0 val1 = 0 val2 = m time += diff1 diff1 -= diff2 val2 -= diff1 val = (abs(val1-val2))//2 time += val pos1 = left[0][2] pos2 = right[0][2] ans[pos1] = time ans[pos2] = time print(*ans) ``` Yes
88,666
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m. The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate. Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed. Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens. For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. Then the descriptions of t testcases follow. The first line of each testcase contains two integers n and m (1 ≀ n ≀ 3 β‹… 10^5; 2 ≀ m ≀ 10^8) β€” the number of robots and the coordinate of the right wall. The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β€” the starting coordinates of the robots. The third line of each testcase contains n space-separated characters 'L' or 'R' β€” the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates x_i in the testcase are distinct. The sum of n over all testcases doesn't exceed 3 β‹… 10^5. Output For each testcase print n integers β€” for the i-th robot output the time it explodes at if it does and -1 otherwise. Example Input 5 7 12 1 2 3 4 9 10 11 R R L L R R R 2 10 1 6 R R 2 10 1 3 L L 1 10 5 R 7 8 6 1 7 2 3 5 4 R L R L L L L Output 1 1 1 1 2 -1 2 -1 -1 2 2 -1 -1 2 7 3 2 7 3 Note Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase: <image> Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer. After second 3 robot 6 just drive infinitely because there's no robot to collide with. Submitted Solution: ``` for _ in range(int(input())): n,m=map(int,input().split()) a=list(map(int,input().split())) pos=list(map(str,input().split())) even=[] odd=[] for i in range(n): if a[i]%2==0: even.append([a[i],pos[i],i]) else: odd.append([a[i],pos[i],i]) even.sort() odd.sort() ans=[-1]*n if len(even)>1: stack=[even[0]] for i in range(1,len(even)-1): now=even[i][1] try: curr=stack[-1][1] except: stack.append(even[i]) continue if curr==now and curr=="R": stack.append(even[i]) elif curr==now and curr=="L": t=abs((stack[-1][0]+even[i][0])//2) ans[stack[-1][2]]=t ans[even[i][2]]=t stack.pop() elif curr=="R" and now=="L": t=abs((stack[-1][0]-even[i][0])//2) ans[stack[-1][2]] = t ans[even[i][2]] = t stack.pop() elif curr=="L" and now=="R": if len(stack)==1: stack.append(even[i]) else: t = abs((stack[-1][0] - stack[-2][0]) // 2) ans[stack[-1][2]] = t ans[stack[-2][2]] = t stack.pop() stack.append(even[i]) if len(stack)>0 and len(even)>1: if stack[-1][1]=="L" and even[-1][1]=="L": t = abs((stack[-1][0] + even[-1][0]) // 2) ans[stack[-1][2]] = t ans[even[-1][2]] = t elif stack[-1][1]=="R" and even[-1][1]=="L": t = abs((stack[-1][0] - even[-1][0]) // 2) ans[stack[-1][2]] = t ans[even[-1][2]] = t elif stack[-1][1]=="L" and even[-1][1]=="R": t = m-abs((stack[-1][0] - even[-1][0]) // 2) ans[stack[-1][2]] = t ans[even[-1][2]] = t elif stack[-1][1]=="R" and even[-1][1]=="R": t=m-abs((stack[-1][0]+even[-1][0])//2) ans[stack[-1][2]] = t ans[even[-1][2]] = t while len(stack)>1: t = m - abs((stack[-1][0] + stack[-2][0]) // 2) ans[stack[-1][2]] = t ans[stack[-2][2]] = t stack.pop() if len(odd)>1: stack=[odd[0]] for i in range(1,len(odd)-1): now=odd[i][1] try: curr=stack[-1][1] except: stack.append(odd[i]) continue if curr==now and curr=="R": stack.append(odd[i]) elif curr==now and curr=="L": t=abs((stack[-1][0]+odd[i][0])//2) ans[stack[-1][2]]=t ans[odd[i][2]]=t stack.pop() elif curr=="R" and now=="L": t=abs((stack[-1][0]-odd[i][0])//2) ans[stack[-1][2]] = t ans[odd[i][2]] = t stack.pop() elif curr=="L" and now=="R": if len(stack)==1: stack.append(odd[i]) else: t = abs((stack[-1][0] - stack[-2][0]) // 2) ans[stack[-1][2]] = t ans[stack[-2][2]] = t stack.pop() stack.append(odd[i]) if len(stack)>0 and len(odd)>1: if stack[-1][1]=="L" and odd[-1][1]=="L": t = abs((stack[-1][0] + odd[-1][0]) // 2) ans[stack[-1][2]] = t ans[odd[-1][2]] = t elif stack[-1][1]=="R" and odd[-1][1]=="L": t = abs((stack[-1][0] - odd[-1][0]) // 2) ans[stack[-1][2]] = t ans[odd[-1][2]] = t elif stack[-1][1]=="L" and odd[-1][1]=="R": t = m-abs((stack[-1][0] - odd[-1][0]) // 2) ans[stack[-1][2]] = t ans[odd[-1][2]] = t elif stack[-1][1]=="R" and odd[-1][1]=="R": t=m-abs((stack[-1][0]+odd[-1][0])//2) ans[stack[-1][2]] = t ans[odd[-1][2]] = t while len(stack)>1: t = m - abs((stack[-1][0] + stack[-2][0]) // 2) ans[stack[-1][2]] = t ans[stack[-2][2]] = t stack.pop() print(*ans) ``` No
88,667
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m. The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate. Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed. Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens. For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. Then the descriptions of t testcases follow. The first line of each testcase contains two integers n and m (1 ≀ n ≀ 3 β‹… 10^5; 2 ≀ m ≀ 10^8) β€” the number of robots and the coordinate of the right wall. The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β€” the starting coordinates of the robots. The third line of each testcase contains n space-separated characters 'L' or 'R' β€” the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates x_i in the testcase are distinct. The sum of n over all testcases doesn't exceed 3 β‹… 10^5. Output For each testcase print n integers β€” for the i-th robot output the time it explodes at if it does and -1 otherwise. Example Input 5 7 12 1 2 3 4 9 10 11 R R L L R R R 2 10 1 6 R R 2 10 1 3 L L 1 10 5 R 7 8 6 1 7 2 3 5 4 R L R L L L L Output 1 1 1 1 2 -1 2 -1 -1 2 2 -1 -1 2 7 3 2 7 3 Note Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase: <image> Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer. After second 3 robot 6 just drive infinitely because there's no robot to collide with. Submitted Solution: ``` for _ in range(int(input())): n,m=map(int,input().split()) a=list(map(int,input().split())) pos=list(map(str,input().split())) even=[] odd=[] for i in range(n): if a[i]%2==0: even.append([a[i],pos[i],i]) else: odd.append([a[i],pos[i],i]) even.sort() odd.sort() ans=[-1]*n if len(even)>1: stack=[even[0]] for i in range(1,len(even)-1): now=even[i][1] try: curr=stack[-1][1] except: stack.append(even[i]) continue if curr==now and curr=="R": stack.append(even[i]) elif curr==now and curr=="L": t=abs((stack[-1][0]+even[i][0])//2) ans[stack[-1][2]]=t ans[even[i][2]]=t stack.pop() elif curr=="R" and now=="L": t=abs((stack[-1][0]-even[i][0])//2) ans[stack[-1][2]] = t ans[even[i][2]] = t stack.pop() elif curr=="L" and now=="R": if len(stack)==1: stack.append(even[i]) else: t = abs((stack[-1][0] - stack[-2][0]) // 2) ans[stack[-1][2]] = t ans[stack[-2][2]] = t stack.pop() stack.append(even[i]) if len(stack)>0 and len(even)>1: if stack[-1][1]=="L" and even[-1][1]=="L": t = abs((stack[-1][0] + even[-1][0]) // 2) ans[stack[-1][2]] = t ans[even[-1][2]] = t elif stack[-1][1]=="R" and even[-1][1]=="L": t = abs((stack[-1][0] - even[-1][0]) // 2) ans[stack[-1][2]] = t ans[even[-1][2]] = t elif stack[-1][1]=="L" and even[-1][1]=="R": t = m-abs((stack[-1][0] - even[-1][0]) // 2) ans[stack[-1][2]] = t ans[even[-1][2]] = t if len(odd)>1: stack=[odd[0]] for i in range(1,len(odd)-1): now=odd[i][1] try: curr=stack[-1][1] except: stack.append(odd[i]) continue if curr==now and curr=="R": stack.append(odd[i]) elif curr==now and curr=="L": t=abs((stack[-1][0]+odd[i][0])//2) ans[stack[-1][2]]=t ans[odd[i][2]]=t stack.pop() elif curr=="R" and now=="L": t=abs((stack[-1][0]-odd[i][0])//2) ans[stack[-1][2]] = t ans[odd[i][2]] = t stack.pop() elif curr=="L" and now=="R": if len(stack)==1: stack.append(odd[i]) else: t = abs((stack[-1][0] - stack[-2][0]) // 2) ans[stack[-1][2]] = t ans[stack[-2][2]] = t stack.pop() stack.append(odd[i]) if len(stack)>0 and len(odd)>1: if stack[-1][1]=="L" and odd[-1][1]=="L": t = abs((stack[-1][0] + odd[-1][0]) // 2) ans[stack[-1][2]] = t ans[odd[-1][2]] = t elif stack[-1][1]=="R" and odd[-1][1]=="L": t = abs((stack[-1][0] - odd[-1][0]) // 2) ans[stack[-1][2]] = t ans[odd[-1][2]] = t elif stack[-1][1]=="L" and odd[-1][1]=="R": t = m-abs((stack[-1][0] - odd[-1][0]) // 2) ans[stack[-1][2]] = t ans[odd[-1][2]] = t elif stack[-1][1]=="R" and odd[-1][1]=="R": t=m-abs((stack[-1][0]+odd[-1][0])//2) ans[stack[-1][2]] = t ans[odd[-1][2]] = t print(*ans) ``` No
88,668
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m. The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate. Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed. Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens. For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. Then the descriptions of t testcases follow. The first line of each testcase contains two integers n and m (1 ≀ n ≀ 3 β‹… 10^5; 2 ≀ m ≀ 10^8) β€” the number of robots and the coordinate of the right wall. The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β€” the starting coordinates of the robots. The third line of each testcase contains n space-separated characters 'L' or 'R' β€” the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates x_i in the testcase are distinct. The sum of n over all testcases doesn't exceed 3 β‹… 10^5. Output For each testcase print n integers β€” for the i-th robot output the time it explodes at if it does and -1 otherwise. Example Input 5 7 12 1 2 3 4 9 10 11 R R L L R R R 2 10 1 6 R R 2 10 1 3 L L 1 10 5 R 7 8 6 1 7 2 3 5 4 R L R L L L L Output 1 1 1 1 2 -1 2 -1 -1 2 2 -1 -1 2 7 3 2 7 3 Note Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase: <image> Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer. After second 3 robot 6 just drive infinitely because there's no robot to collide with. Submitted Solution: ``` def bs(l,k): if len(l)>0: lo = 0 hi = len(l)-1 while hi > lo: mid = (lo+hi)//2 if l[mid][1] >= k: hi = mid else: lo = mid+1 index = lo if l[lo][1] < k: index += 1 return index else: return 0 for _ in range(int(input())): N,M = map(int,input().split()) a = list(map(int,input().split())) L = [[],[]] R = [[],[]] d = input().split() for i in range(N): x = a[i] j = 0 if x%2 != 0: j += 1 if d[i] == "L": L[j].append((i,x)) else: R[j].append((i,x)) # for i in range(2): # L[i].sort(key= lambda a:a[1]) # R[i].sort(key= lambda a:a[1]) L1 = [[],[]] R1 = [[],[]] output = [] for i in range(2): for a in L[i]: r = bs(R[i],a[1]) if r > 0: b = R[i].pop(r-1) t = (a[1]-b[1])//2 output.append((a[0],t)) output.append((b[0],t)) else: L1[i].append(a) R1[i]=R[i] for i in range(2): while len(L1[i])>1: a = L1[i].pop(0) b = L1[i].pop(0) t = (a[1]+b[1])//2 output.append((a[0],t)) output.append((b[0],t)) while len(R1[i])>1: a = R1[i].pop() b = R1[i].pop() t = M-((a[1]+b[1])//2) output.append((a[0],t)) output.append((b[0],t)) for i in range(2): if len(L1[i]) > 0 and len(R1[i]) > 0: a = L1[i].pop() b = R1[i].pop() t = (((2*M)+a[1]-b[1])//2) output.append((a[0],t)) output.append((b[0],t)) for i in range(2): for a in L1[i]: output.append((a[0],-1)) for a in R1[i]: output.append((a[0],-1)) output.sort(key=lambda a:a[0]) for e in output[:-1]: print(e[1],end=" ") print(output[-1][1]) ``` No
88,669
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m. The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate. Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed. Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens. For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. Then the descriptions of t testcases follow. The first line of each testcase contains two integers n and m (1 ≀ n ≀ 3 β‹… 10^5; 2 ≀ m ≀ 10^8) β€” the number of robots and the coordinate of the right wall. The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β€” the starting coordinates of the robots. The third line of each testcase contains n space-separated characters 'L' or 'R' β€” the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates x_i in the testcase are distinct. The sum of n over all testcases doesn't exceed 3 β‹… 10^5. Output For each testcase print n integers β€” for the i-th robot output the time it explodes at if it does and -1 otherwise. Example Input 5 7 12 1 2 3 4 9 10 11 R R L L R R R 2 10 1 6 R R 2 10 1 3 L L 1 10 5 R 7 8 6 1 7 2 3 5 4 R L R L L L L Output 1 1 1 1 2 -1 2 -1 -1 2 2 -1 -1 2 7 3 2 7 3 Note Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase: <image> Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer. After second 3 robot 6 just drive infinitely because there's no robot to collide with. Submitted Solution: ``` for _ in range(int(input())): n,m=map(int,input().split()) a=list(map(int,input().split())) pos=list(map(str,input().split())) even=[] odd=[] for i in range(n): if a[i]%2==0: even.append([a[i],pos[i],i]) else: odd.append([a[i],pos[i],i]) even.sort() odd.sort() ans=[-1]*n if len(even)>1: stack=[even[0]] for i in range(1,len(even)-1): now=even[i][1] try: curr=stack[-1][1] except: stack.append(even[i]) continue if curr==now and curr=="R": stack.append(even[i]) elif curr==now and curr=="L": t=abs((stack[-1][0]+even[i][0])//2) ans[stack[-1][2]]=t ans[even[i][2]]=t stack.pop() elif curr=="R" and now=="L": t=abs((stack[-1][0]-even[i][0])//2) ans[stack[-1][2]] = t ans[even[i][2]] = t stack.pop() elif curr=="L" and now=="R": if len(stack)==1: stack.append(even[i]) else: t = abs((stack[-1][0] - stack[-2][0]) // 2) ans[stack[-1][2]] = t ans[stack[-2][2]] = t stack.pop() stack.append(even[i]) if len(stack)>0 and len(even)>1: if stack[-1][1]=="L" and even[-1][1]=="L": t = abs((stack[-1][0] + even[-1][0]) // 2) ans[stack[-1][2]] = t ans[even[-1][2]] = t elif stack[-1][1]=="R" and even[-1][1]=="L": t = abs((stack[-1][0] - even[-1][0]) // 2) ans[stack[-1][2]] = t ans[even[-1][2]] = t elif stack[-1][1]=="L" and even[-1][1]=="R": t = m-abs((stack[-1][0] - even[-1][0]) // 2) ans[stack[-1][2]] = t ans[even[-1][2]] = t elif stack[-1][1]=="R" and even[-1][1]=="R": t=m-abs((stack[-1][0]+even[-1][0])//2) ans[stack[-1][2]] = t ans[even[-1][2]] = t stack.pop() while len(stack)>1: t = m - abs((stack[-1][0] + stack[-2][0]) // 2) ans[stack[-1][2]] = t ans[stack[-2][2]] = t stack.pop() if len(odd)>1: stack=[odd[0]] for i in range(1,len(odd)-1): now=odd[i][1] try: curr=stack[-1][1] except: stack.append(odd[i]) continue if curr==now and curr=="R": stack.append(odd[i]) elif curr==now and curr=="L": t=abs((stack[-1][0]+odd[i][0])//2) ans[stack[-1][2]]=t ans[odd[i][2]]=t stack.pop() elif curr=="R" and now=="L": t=abs((stack[-1][0]-odd[i][0])//2) ans[stack[-1][2]] = t ans[odd[i][2]] = t stack.pop() elif curr=="L" and now=="R": if len(stack)==1: stack.append(odd[i]) else: t = abs((stack[-1][0] - stack[-2][0]) // 2) ans[stack[-1][2]] = t ans[stack[-2][2]] = t stack.pop() stack.append(odd[i]) if len(stack)>0 and len(odd)>1: if stack[-1][1]=="L" and odd[-1][1]=="L": t = abs((stack[-1][0] + odd[-1][0]) // 2) ans[stack[-1][2]] = t ans[odd[-1][2]] = t elif stack[-1][1]=="R" and odd[-1][1]=="L": t = abs((stack[-1][0] - odd[-1][0]) // 2) ans[stack[-1][2]] = t ans[odd[-1][2]] = t elif stack[-1][1]=="L" and odd[-1][1]=="R": t = m-abs((stack[-1][0] - odd[-1][0]) // 2) ans[stack[-1][2]] = t ans[odd[-1][2]] = t elif stack[-1][1]=="R" and odd[-1][1]=="R": t=m-abs((stack[-1][0]+odd[-1][0])//2) ans[stack[-1][2]] = t ans[odd[-1][2]] = t stack.pop() while len(stack)>1: t = m - abs((stack[-1][0] + stack[-2][0]) // 2) ans[stack[-1][2]] = t ans[stack[-2][2]] = t stack.pop() print(*ans) ``` No
88,670
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m. The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate. Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed. Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens. For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. Then the descriptions of t testcases follow. The first line of each testcase contains two integers n and m (1 ≀ n ≀ 3 β‹… 10^5; 2 ≀ m ≀ 10^8) β€” the number of robots and the coordinate of the right wall. The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β€” the starting coordinates of the robots. The third line of each testcase contains n space-separated characters 'L' or 'R' β€” the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates x_i in the testcase are distinct. The sum of n over all testcases doesn't exceed 3 β‹… 10^5. Output For each testcase print n integers β€” for the i-th robot output the time it explodes at if it does and -1 otherwise. Example Input 5 7 12 1 2 3 4 9 10 11 R R L L R R R 2 10 1 6 R R 2 10 1 3 L L 1 10 5 R 7 8 6 1 7 2 3 5 4 R L R L L L L Output 1 1 1 1 2 -1 2 -1 -1 2 2 -1 -1 2 7 3 2 7 3 Note Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase: <image> Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer. After second 3 robot 6 just drive infinitely because there's no robot to collide with. Submitted Solution: ``` from __future__ import print_function from sys import stdin,stdout import sys import traceback from bisect import bisect_left, bisect_right, insort from itertools import chain, repeat, starmap from math import log from operator import add, eq, ne, gt, ge, lt, le, iadd from textwrap import dedent try: from collections.abc import Sequence, MutableSequence except ImportError: from collections import Sequence, MutableSequence from functools import wraps from sys import hexversion if hexversion < 0x03000000: from itertools import imap as map # pylint: disable=redefined-builtin from itertools import izip as zip # pylint: disable=redefined-builtin try: from thread import get_ident except ImportError: from dummy_thread import get_ident else: from functools import reduce try: from _thread import get_ident except ImportError: from _dummy_thread import get_ident def recursive_repr(fillvalue='...'): "Decorator to make a repr function return fillvalue for a recursive call." # pylint: disable=missing-docstring # Copied from reprlib in Python 3 # https://hg.python.org/cpython/file/3.6/Lib/reprlib.py def decorating_function(user_function): repr_running = set() @wraps(user_function) def wrapper(self): key = id(self), get_ident() if key in repr_running: return fillvalue repr_running.add(key) try: result = user_function(self) finally: repr_running.discard(key) return result return wrapper return decorating_function class SortedList(MutableSequence): DEFAULT_LOAD_FACTOR = 1000 def __init__(self, iterable=None, key=None): assert key is None self._len = 0 self._load = self.DEFAULT_LOAD_FACTOR self._lists = [] self._maxes = [] self._index = [] self._offset = 0 if iterable is not None: self._update(iterable) def __new__(cls, iterable=None, key=None): # pylint: disable=unused-argument if key is None: return object.__new__(cls) else: if cls is SortedList: return object.__new__(SortedKeyList) else: raise TypeError('inherit SortedKeyList for key argument') @property def key(self): # pylint: disable=useless-return return None def _reset(self, load): values = reduce(iadd, self._lists, []) self._clear() self._load = load self._update(values) def clear(self): self._len = 0 del self._lists[:] del self._maxes[:] del self._index[:] self._offset = 0 _clear = clear def add(self, value): _lists = self._lists _maxes = self._maxes if _maxes: pos = bisect_right(_maxes, value) if pos == len(_maxes): pos -= 1 _lists[pos].append(value) _maxes[pos] = value else: insort(_lists[pos], value) self._expand(pos) else: _lists.append([value]) _maxes.append(value) self._len += 1 def _expand(self, pos): _load = self._load _lists = self._lists _index = self._index if len(_lists[pos]) > (_load << 1): _maxes = self._maxes _lists_pos = _lists[pos] half = _lists_pos[_load:] del _lists_pos[_load:] _maxes[pos] = _lists_pos[-1] _lists.insert(pos + 1, half) _maxes.insert(pos + 1, half[-1]) del _index[:] else: if _index: child = self._offset + pos while child: _index[child] += 1 child = (child - 1) >> 1 _index[0] += 1 def update(self, iterable): _lists = self._lists _maxes = self._maxes values = sorted(iterable) if _maxes: if len(values) * 4 >= self._len: _lists.append(values) values = reduce(iadd, _lists, []) values.sort() self._clear() else: _add = self.add for val in values: _add(val) return _load = self._load _lists.extend(values[pos:(pos + _load)] for pos in range(0, len(values), _load)) _maxes.extend(sublist[-1] for sublist in _lists) self._len = len(values) del self._index[:] _update = update def __contains__(self, value): _maxes = self._maxes if not _maxes: return False pos = bisect_left(_maxes, value) if pos == len(_maxes): return False _lists = self._lists idx = bisect_left(_lists[pos], value) return _lists[pos][idx] == value def discard(self, value): _maxes = self._maxes if not _maxes: return pos = bisect_left(_maxes, value) if pos == len(_maxes): return _lists = self._lists idx = bisect_left(_lists[pos], value) if _lists[pos][idx] == value: self._delete(pos, idx) def remove(self, value): _maxes = self._maxes if not _maxes: raise ValueError('{0!r} not in list'.format(value)) pos = bisect_left(_maxes, value) if pos == len(_maxes): raise ValueError('{0!r} not in list'.format(value)) _lists = self._lists idx = bisect_left(_lists[pos], value) if _lists[pos][idx] == value: self._delete(pos, idx) else: raise ValueError('{0!r} not in list'.format(value)) def _delete(self, pos, idx): _lists = self._lists _maxes = self._maxes _index = self._index _lists_pos = _lists[pos] del _lists_pos[idx] self._len -= 1 len_lists_pos = len(_lists_pos) if len_lists_pos > (self._load >> 1): _maxes[pos] = _lists_pos[-1] if _index: child = self._offset + pos while child > 0: _index[child] -= 1 child = (child - 1) >> 1 _index[0] -= 1 elif len(_lists) > 1: if not pos: pos += 1 prev = pos - 1 _lists[prev].extend(_lists[pos]) _maxes[prev] = _lists[prev][-1] del _lists[pos] del _maxes[pos] del _index[:] self._expand(prev) elif len_lists_pos: _maxes[pos] = _lists_pos[-1] else: del _lists[pos] del _maxes[pos] del _index[:] def _loc(self, pos, idx): if not pos: return idx _index = self._index if not _index: self._build_index() total = 0 # Increment pos to point in the index to len(self._lists[pos]). pos += self._offset # Iterate until reaching the root of the index tree at pos = 0. while pos: # Right-child nodes are at odd indices. At such indices # account the total below the left child node. if not pos & 1: total += _index[pos - 1] # Advance pos to the parent node. pos = (pos - 1) >> 1 return total + idx def _pos(self, idx): if idx < 0: last_len = len(self._lists[-1]) if (-idx) <= last_len: return len(self._lists) - 1, last_len + idx idx += self._len if idx < 0: raise IndexError('list index out of range') elif idx >= self._len: raise IndexError('list index out of range') if idx < len(self._lists[0]): return 0, idx _index = self._index if not _index: self._build_index() pos = 0 child = 1 len_index = len(_index) while child < len_index: index_child = _index[child] if idx < index_child: pos = child else: idx -= index_child pos = child + 1 child = (pos << 1) + 1 return (pos - self._offset, idx) def _build_index(self): row0 = list(map(len, self._lists)) if len(row0) == 1: self._index[:] = row0 self._offset = 0 return head = iter(row0) tail = iter(head) row1 = list(starmap(add, zip(head, tail))) if len(row0) & 1: row1.append(row0[-1]) if len(row1) == 1: self._index[:] = row1 + row0 self._offset = 1 return size = 2 ** (int(log(len(row1) - 1, 2)) + 1) row1.extend(repeat(0, size - len(row1))) tree = [row0, row1] while len(tree[-1]) > 1: head = iter(tree[-1]) tail = iter(head) row = list(starmap(add, zip(head, tail))) tree.append(row) reduce(iadd, reversed(tree), self._index) self._offset = size * 2 - 1 def __delitem__(self, index): if isinstance(index, slice): start, stop, step = index.indices(self._len) if step == 1 and start < stop: if start == 0 and stop == self._len: return self._clear() elif self._len <= 8 * (stop - start): values = self._getitem(slice(None, start)) if stop < self._len: values += self._getitem(slice(stop, None)) self._clear() return self._update(values) indices = range(start, stop, step) # Delete items from greatest index to least so # that the indices remain valid throughout iteration. if step > 0: indices = reversed(indices) _pos, _delete = self._pos, self._delete for index in indices: pos, idx = _pos(index) _delete(pos, idx) else: pos, idx = self._pos(index) self._delete(pos, idx) def __getitem__(self, index): _lists = self._lists if isinstance(index, slice): start, stop, step = index.indices(self._len) if step == 1 and start < stop: # Whole slice optimization: start to stop slices the whole # sorted list. if start == 0 and stop == self._len: return reduce(iadd, self._lists, []) start_pos, start_idx = self._pos(start) start_list = _lists[start_pos] stop_idx = start_idx + stop - start # Small slice optimization: start index and stop index are # within the start list. if len(start_list) >= stop_idx: return start_list[start_idx:stop_idx] if stop == self._len: stop_pos = len(_lists) - 1 stop_idx = len(_lists[stop_pos]) else: stop_pos, stop_idx = self._pos(stop) prefix = _lists[start_pos][start_idx:] middle = _lists[(start_pos + 1):stop_pos] result = reduce(iadd, middle, prefix) result += _lists[stop_pos][:stop_idx] return result if step == -1 and start > stop: result = self._getitem(slice(stop + 1, start + 1)) result.reverse() return result # Return a list because a negative step could # reverse the order of the items and this could # be the desired behavior. indices = range(start, stop, step) return list(self._getitem(index) for index in indices) else: if self._len: if index == 0: return _lists[0][0] elif index == -1: return _lists[-1][-1] else: raise IndexError('list index out of range') if 0 <= index < len(_lists[0]): return _lists[0][index] len_last = len(_lists[-1]) if -len_last < index < 0: return _lists[-1][len_last + index] pos, idx = self._pos(index) return _lists[pos][idx] _getitem = __getitem__ def __setitem__(self, index, value): message = 'use ``del sl[index]`` and ``sl.add(value)`` instead' raise NotImplementedError(message) def __iter__(self): return chain.from_iterable(self._lists) def __reversed__(self): return chain.from_iterable(map(reversed, reversed(self._lists))) def reverse(self): raise NotImplementedError('use ``reversed(sl)`` instead') def islice(self, start=None, stop=None, reverse=False): _len = self._len if not _len: return iter(()) start, stop, _ = slice(start, stop).indices(self._len) if start >= stop: return iter(()) _pos = self._pos min_pos, min_idx = _pos(start) if stop == _len: max_pos = len(self._lists) - 1 max_idx = len(self._lists[-1]) else: max_pos, max_idx = _pos(stop) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse) def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse): _lists = self._lists if min_pos > max_pos: return iter(()) if min_pos == max_pos: if reverse: indices = reversed(range(min_idx, max_idx)) return map(_lists[min_pos].__getitem__, indices) indices = range(min_idx, max_idx) return map(_lists[min_pos].__getitem__, indices) next_pos = min_pos + 1 if next_pos == max_pos: if reverse: min_indices = range(min_idx, len(_lists[min_pos])) max_indices = range(max_idx) return chain( map(_lists[max_pos].__getitem__, reversed(max_indices)), map(_lists[min_pos].__getitem__, reversed(min_indices)), ) min_indices = range(min_idx, len(_lists[min_pos])) max_indices = range(max_idx) return chain( map(_lists[min_pos].__getitem__, min_indices), map(_lists[max_pos].__getitem__, max_indices), ) if reverse: min_indices = range(min_idx, len(_lists[min_pos])) sublist_indices = range(next_pos, max_pos) sublists = map(_lists.__getitem__, reversed(sublist_indices)) max_indices = range(max_idx) return chain( map(_lists[max_pos].__getitem__, reversed(max_indices)), chain.from_iterable(map(reversed, sublists)), map(_lists[min_pos].__getitem__, reversed(min_indices)), ) min_indices = range(min_idx, len(_lists[min_pos])) sublist_indices = range(next_pos, max_pos) sublists = map(_lists.__getitem__, sublist_indices) max_indices = range(max_idx) return chain( map(_lists[min_pos].__getitem__, min_indices), chain.from_iterable(sublists), map(_lists[max_pos].__getitem__, max_indices), ) def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False): _maxes = self._maxes if not _maxes: return iter(()) _lists = self._lists # Calculate the minimum (pos, idx) pair. By default this location # will be inclusive in our calculation. if minimum is None: min_pos = 0 min_idx = 0 else: if inclusive[0]: min_pos = bisect_left(_maxes, minimum) if min_pos == len(_maxes): return iter(()) min_idx = bisect_left(_lists[min_pos], minimum) else: min_pos = bisect_right(_maxes, minimum) if min_pos == len(_maxes): return iter(()) min_idx = bisect_right(_lists[min_pos], minimum) # Calculate the maximum (pos, idx) pair. By default this location # will be exclusive in our calculation. if maximum is None: max_pos = len(_maxes) - 1 max_idx = len(_lists[max_pos]) else: if inclusive[1]: max_pos = bisect_right(_maxes, maximum) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_lists[max_pos]) else: max_idx = bisect_right(_lists[max_pos], maximum) else: max_pos = bisect_left(_maxes, maximum) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_lists[max_pos]) else: max_idx = bisect_left(_lists[max_pos], maximum) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse) def __len__(self): """Return the size of the sorted list. ``sl.__len__()`` <==> ``len(sl)`` :return: size of sorted list """ return self._len def bisect_left(self, value): _maxes = self._maxes if not _maxes: return 0 pos = bisect_left(_maxes, value) if pos == len(_maxes): return self._len idx = bisect_left(self._lists[pos], value) return self._loc(pos, idx) def bisect_right(self, value): _maxes = self._maxes if not _maxes: return 0 pos = bisect_right(_maxes, value) if pos == len(_maxes): return self._len idx = bisect_right(self._lists[pos], value) return self._loc(pos, idx) bisect = bisect_right _bisect_right = bisect_right def count(self, value): _maxes = self._maxes if not _maxes: return 0 pos_left = bisect_left(_maxes, value) if pos_left == len(_maxes): return 0 _lists = self._lists idx_left = bisect_left(_lists[pos_left], value) pos_right = bisect_right(_maxes, value) if pos_right == len(_maxes): return self._len - self._loc(pos_left, idx_left) idx_right = bisect_right(_lists[pos_right], value) if pos_left == pos_right: return idx_right - idx_left right = self._loc(pos_right, idx_right) left = self._loc(pos_left, idx_left) return right - left def copy(self): return self.__class__(self) __copy__ = copy def append(self, value): raise NotImplementedError('use ``sl.add(value)`` instead') def extend(self, values): raise NotImplementedError('use ``sl.update(values)`` instead') def insert(self, index, value): raise NotImplementedError('use ``sl.add(value)`` instead') def pop(self, index=-1): if not self._len: raise IndexError('pop index out of range') _lists = self._lists if index == 0: val = _lists[0][0] self._delete(0, 0) return val if index == -1: pos = len(_lists) - 1 loc = len(_lists[pos]) - 1 val = _lists[pos][loc] self._delete(pos, loc) return val if 0 <= index < len(_lists[0]): val = _lists[0][index] self._delete(0, index) return val len_last = len(_lists[-1]) if -len_last < index < 0: pos = len(_lists) - 1 loc = len_last + index val = _lists[pos][loc] self._delete(pos, loc) return val pos, idx = self._pos(index) val = _lists[pos][idx] self._delete(pos, idx) return val def index(self, value, start=None, stop=None): _len = self._len if not _len: raise ValueError('{0!r} is not in list'.format(value)) if start is None: start = 0 if start < 0: start += _len if start < 0: start = 0 if stop is None: stop = _len if stop < 0: stop += _len if stop > _len: stop = _len if stop <= start: raise ValueError('{0!r} is not in list'.format(value)) _maxes = self._maxes pos_left = bisect_left(_maxes, value) if pos_left == len(_maxes): raise ValueError('{0!r} is not in list'.format(value)) _lists = self._lists idx_left = bisect_left(_lists[pos_left], value) if _lists[pos_left][idx_left] != value: raise ValueError('{0!r} is not in list'.format(value)) stop -= 1 left = self._loc(pos_left, idx_left) if start <= left: if left <= stop: return left else: right = self._bisect_right(value) - 1 if start <= right: return start raise ValueError('{0!r} is not in list'.format(value)) def __add__(self, other): values = reduce(iadd, self._lists, []) values.extend(other) return self.__class__(values) __radd__ = __add__ def __iadd__(self, other): self._update(other) return self def __mul__(self, num): values = reduce(iadd, self._lists, []) * num return self.__class__(values) __rmul__ = __mul__ def __imul__(self, num): values = reduce(iadd, self._lists, []) * num self._clear() self._update(values) return self def __make_cmp(seq_op, symbol, doc): "Make comparator method." def comparer(self, other): "Compare method for sorted list and sequence." if not isinstance(other, Sequence): return NotImplemented self_len = self._len len_other = len(other) if self_len != len_other: if seq_op is eq: return False if seq_op is ne: return True for alpha, beta in zip(self, other): if alpha != beta: return seq_op(alpha, beta) return seq_op(self_len, len_other) seq_op_name = seq_op.__name__ comparer.__name__ = '__{0}__'.format(seq_op_name) doc_str = """Return true if and only if sorted list is {0} `other`. ``sl.__{1}__(other)`` <==> ``sl {2} other`` Comparisons use lexicographical order as with sequences. Runtime complexity: `O(n)` :param other: `other` sequence :return: true if sorted list is {0} `other` """ comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol)) return comparer __eq__ = __make_cmp(eq, '==', 'equal to') __ne__ = __make_cmp(ne, '!=', 'not equal to') __lt__ = __make_cmp(lt, '<', 'less than') __gt__ = __make_cmp(gt, '>', 'greater than') __le__ = __make_cmp(le, '<=', 'less than or equal to') __ge__ = __make_cmp(ge, '>=', 'greater than or equal to') __make_cmp = staticmethod(__make_cmp) def __reduce__(self): values = reduce(iadd, self._lists, []) return (type(self), (values,)) @recursive_repr() def __repr__(self): """Return string representation of sorted list. ``sl.__repr__()`` <==> ``repr(sl)`` :return: string representation """ return '{0}({1!r})'.format(type(self).__name__, list(self)) def _check(self): """Check invariants of sorted list. Runtime complexity: `O(n)` """ try: assert self._load >= 4 assert len(self._maxes) == len(self._lists) assert self._len == sum(len(sublist) for sublist in self._lists) # Check all sublists are sorted. for sublist in self._lists: for pos in range(1, len(sublist)): assert sublist[pos - 1] <= sublist[pos] # Check beginning/end of sublists are sorted. for pos in range(1, len(self._lists)): assert self._lists[pos - 1][-1] <= self._lists[pos][0] # Check _maxes index is the last value of each sublist. for pos in range(len(self._maxes)): assert self._maxes[pos] == self._lists[pos][-1] # Check sublist lengths are less than double load-factor. double = self._load << 1 assert all(len(sublist) <= double for sublist in self._lists) # Check sublist lengths are greater than half load-factor for all # but the last sublist. half = self._load >> 1 for pos in range(0, len(self._lists) - 1): assert len(self._lists[pos]) >= half if self._index: assert self._len == self._index[0] assert len(self._index) == self._offset + len(self._lists) # Check index leaf nodes equal length of sublists. for pos in range(len(self._lists)): leaf = self._index[self._offset + pos] assert leaf == len(self._lists[pos]) # Check index branch nodes are the sum of their children. for pos in range(self._offset): child = (pos << 1) + 1 if child >= len(self._index): assert self._index[pos] == 0 elif child + 1 == len(self._index): assert self._index[pos] == self._index[child] else: child_sum = self._index[child] + self._index[child + 1] assert child_sum == self._index[pos] except: traceback.print_exc(file=sys.stdout) raise def identity(value): "Identity function." return value class SortedKeyList(SortedList): def __init__(self, iterable=None, key=identity): self._key = key self._len = 0 self._load = self.DEFAULT_LOAD_FACTOR self._lists = [] self._keys = [] self._maxes = [] self._index = [] self._offset = 0 if iterable is not None: self._update(iterable) def __new__(cls, iterable=None, key=identity): return object.__new__(cls) @property def key(self): return self._key def clear(self): self._len = 0 del self._lists[:] del self._keys[:] del self._maxes[:] del self._index[:] _clear = clear def add(self, value): _lists = self._lists _keys = self._keys _maxes = self._maxes key = self._key(value) if _maxes: pos = bisect_right(_maxes, key) if pos == len(_maxes): pos -= 1 _lists[pos].append(value) _keys[pos].append(key) _maxes[pos] = key else: idx = bisect_right(_keys[pos], key) _lists[pos].insert(idx, value) _keys[pos].insert(idx, key) self._expand(pos) else: _lists.append([value]) _keys.append([key]) _maxes.append(key) self._len += 1 def _expand(self, pos): _lists = self._lists _keys = self._keys _index = self._index if len(_keys[pos]) > (self._load << 1): _maxes = self._maxes _load = self._load _lists_pos = _lists[pos] _keys_pos = _keys[pos] half = _lists_pos[_load:] half_keys = _keys_pos[_load:] del _lists_pos[_load:] del _keys_pos[_load:] _maxes[pos] = _keys_pos[-1] _lists.insert(pos + 1, half) _keys.insert(pos + 1, half_keys) _maxes.insert(pos + 1, half_keys[-1]) del _index[:] else: if _index: child = self._offset + pos while child: _index[child] += 1 child = (child - 1) >> 1 _index[0] += 1 def update(self, iterable): _lists = self._lists _keys = self._keys _maxes = self._maxes values = sorted(iterable, key=self._key) if _maxes: if len(values) * 4 >= self._len: _lists.append(values) values = reduce(iadd, _lists, []) values.sort(key=self._key) self._clear() else: _add = self.add for val in values: _add(val) return _load = self._load _lists.extend(values[pos:(pos + _load)] for pos in range(0, len(values), _load)) _keys.extend(list(map(self._key, _list)) for _list in _lists) _maxes.extend(sublist[-1] for sublist in _keys) self._len = len(values) del self._index[:] _update = update def __contains__(self, value): _maxes = self._maxes if not _maxes: return False key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): return False _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: return False if _lists[pos][idx] == value: return True idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: return False len_sublist = len(_keys[pos]) idx = 0 def discard(self, value): _maxes = self._maxes if not _maxes: return key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): return _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: return if _lists[pos][idx] == value: self._delete(pos, idx) return idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: return len_sublist = len(_keys[pos]) idx = 0 def remove(self, value): _maxes = self._maxes if not _maxes: raise ValueError('{0!r} not in list'.format(value)) key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): raise ValueError('{0!r} not in list'.format(value)) _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: raise ValueError('{0!r} not in list'.format(value)) if _lists[pos][idx] == value: self._delete(pos, idx) return idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: raise ValueError('{0!r} not in list'.format(value)) len_sublist = len(_keys[pos]) idx = 0 def _delete(self, pos, idx): _lists = self._lists _keys = self._keys _maxes = self._maxes _index = self._index keys_pos = _keys[pos] lists_pos = _lists[pos] del keys_pos[idx] del lists_pos[idx] self._len -= 1 len_keys_pos = len(keys_pos) if len_keys_pos > (self._load >> 1): _maxes[pos] = keys_pos[-1] if _index: child = self._offset + pos while child > 0: _index[child] -= 1 child = (child - 1) >> 1 _index[0] -= 1 elif len(_keys) > 1: if not pos: pos += 1 prev = pos - 1 _keys[prev].extend(_keys[pos]) _lists[prev].extend(_lists[pos]) _maxes[prev] = _keys[prev][-1] del _lists[pos] del _keys[pos] del _maxes[pos] del _index[:] self._expand(prev) elif len_keys_pos: _maxes[pos] = keys_pos[-1] else: del _lists[pos] del _keys[pos] del _maxes[pos] del _index[:] def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False): min_key = self._key(minimum) if minimum is not None else None max_key = self._key(maximum) if maximum is not None else None return self._irange_key( min_key=min_key, max_key=max_key, inclusive=inclusive, reverse=reverse, ) def irange_key(self, min_key=None, max_key=None, inclusive=(True, True), reverse=False): _maxes = self._maxes if not _maxes: return iter(()) _keys = self._keys if min_key is None: min_pos = 0 min_idx = 0 else: if inclusive[0]: min_pos = bisect_left(_maxes, min_key) if min_pos == len(_maxes): return iter(()) min_idx = bisect_left(_keys[min_pos], min_key) else: min_pos = bisect_right(_maxes, min_key) if min_pos == len(_maxes): return iter(()) min_idx = bisect_right(_keys[min_pos], min_key) if max_key is None: max_pos = len(_maxes) - 1 max_idx = len(_keys[max_pos]) else: if inclusive[1]: max_pos = bisect_right(_maxes, max_key) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_keys[max_pos]) else: max_idx = bisect_right(_keys[max_pos], max_key) else: max_pos = bisect_left(_maxes, max_key) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_keys[max_pos]) else: max_idx = bisect_left(_keys[max_pos], max_key) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse) _irange_key = irange_key def bisect_left(self, value): return self._bisect_key_left(self._key(value)) def bisect_right(self, value): return self._bisect_key_right(self._key(value)) bisect = bisect_right def bisect_key_left(self, key): _maxes = self._maxes if not _maxes: return 0 pos = bisect_left(_maxes, key) if pos == len(_maxes): return self._len idx = bisect_left(self._keys[pos], key) return self._loc(pos, idx) _bisect_key_left = bisect_key_left def bisect_key_right(self, key): _maxes = self._maxes if not _maxes: return 0 pos = bisect_right(_maxes, key) if pos == len(_maxes): return self._len idx = bisect_right(self._keys[pos], key) return self._loc(pos, idx) bisect_key = bisect_key_right _bisect_key_right = bisect_key_right def count(self, value): _maxes = self._maxes if not _maxes: return 0 key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): return 0 _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) total = 0 len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: return total if _lists[pos][idx] == value: total += 1 idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: return total len_sublist = len(_keys[pos]) idx = 0 def copy(self): return self.__class__(self, key=self._key) __copy__ = copy def index(self, value, start=None, stop=None): _len = self._len if not _len: raise ValueError('{0!r} is not in list'.format(value)) if start is None: start = 0 if start < 0: start += _len if start < 0: start = 0 if stop is None: stop = _len if stop < 0: stop += _len if stop > _len: stop = _len if stop <= start: raise ValueError('{0!r} is not in list'.format(value)) _maxes = self._maxes key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): raise ValueError('{0!r} is not in list'.format(value)) stop -= 1 _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: raise ValueError('{0!r} is not in list'.format(value)) if _lists[pos][idx] == value: loc = self._loc(pos, idx) if start <= loc <= stop: return loc elif loc > stop: break idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: raise ValueError('{0!r} is not in list'.format(value)) len_sublist = len(_keys[pos]) idx = 0 raise ValueError('{0!r} is not in list'.format(value)) def __add__(self, other): values = reduce(iadd, self._lists, []) values.extend(other) return self.__class__(values, key=self._key) __radd__ = __add__ def __mul__(self, num): values = reduce(iadd, self._lists, []) * num return self.__class__(values, key=self._key) def __reduce__(self): values = reduce(iadd, self._lists, []) return (type(self), (values, self.key)) @recursive_repr() def __repr__(self): type_name = type(self).__name__ return '{0}({1!r}, key={2!r})'.format(type_name, list(self), self._key) def _check(self): try: assert self._load >= 4 assert len(self._maxes) == len(self._lists) == len(self._keys) assert self._len == sum(len(sublist) for sublist in self._lists) for sublist in self._keys: for pos in range(1, len(sublist)): assert sublist[pos - 1] <= sublist[pos] for pos in range(1, len(self._keys)): assert self._keys[pos - 1][-1] <= self._keys[pos][0] for val_sublist, key_sublist in zip(self._lists, self._keys): assert len(val_sublist) == len(key_sublist) for val, key in zip(val_sublist, key_sublist): assert self._key(val) == key for pos in range(len(self._maxes)): assert self._maxes[pos] == self._keys[pos][-1] double = self._load << 1 assert all(len(sublist) <= double for sublist in self._lists) half = self._load >> 1 for pos in range(0, len(self._lists) - 1): assert len(self._lists[pos]) >= half if self._index: assert self._len == self._index[0] assert len(self._index) == self._offset + len(self._lists) for pos in range(len(self._lists)): leaf = self._index[self._offset + pos] assert leaf == len(self._lists[pos]) for pos in range(self._offset): child = (pos << 1) + 1 if child >= len(self._index): assert self._index[pos] == 0 elif child + 1 == len(self._index): assert self._index[pos] == self._index[child] else: child_sum = self._index[child] + self._index[child + 1] assert child_sum == self._index[pos] except: traceback.print_exc(file=sys.stdout) def comp(M,l,r): while len(r): pos=l.bisect_left(r[0]) if pos==len(l): break val=(l[pos]-r[0])/2 ans[m[l[pos]]]=val ans[m[r[0]]]=val l.pop(pos) r.pop(0) while len(l)>1: x1=l.pop(0) x2=l.pop(0) val=(x1+x2)/2 ans[m[x1]]=val ans[m[x2]]=val while len(r)>1: x1=r.pop(0) x2=r.pop(0) val=(M-x1+M-x2)/2 ans[m[x1]]=val ans[m[x2]]=val if len(l)==1 and len(r)==1: x1=l.pop() x2=r.pop() val=(M+M-x2+x1)/2 ans[m[x1]]=val ans[m[x2]]=val for _ in range(input()): n,M=[int(i) for i in raw_input().split()] a=[int(i) for i in raw_input().split()] s=[i for i in raw_input().split()] al=SortedList() bl=SortedList() ar=SortedList() br=SortedList() m={} ans=[-1 for i in range(n)] for i in range(n): m[a[i]]=i if a[i]%2==0: if s[i]=='L': al.add(a[i]) else: ar.add(a[i]) else: if s[i]=='L': bl.add(a[i]) else: br.add(a[i]) comp(M,al,ar) comp(M,bl,br) for i in ans: print(i,end=" ") print() ``` No
88,671
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m. The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate. Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed. Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens. For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. Then the descriptions of t testcases follow. The first line of each testcase contains two integers n and m (1 ≀ n ≀ 3 β‹… 10^5; 2 ≀ m ≀ 10^8) β€” the number of robots and the coordinate of the right wall. The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β€” the starting coordinates of the robots. The third line of each testcase contains n space-separated characters 'L' or 'R' β€” the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates x_i in the testcase are distinct. The sum of n over all testcases doesn't exceed 3 β‹… 10^5. Output For each testcase print n integers β€” for the i-th robot output the time it explodes at if it does and -1 otherwise. Example Input 5 7 12 1 2 3 4 9 10 11 R R L L R R R 2 10 1 6 R R 2 10 1 3 L L 1 10 5 R 7 8 6 1 7 2 3 5 4 R L R L L L L Output 1 1 1 1 2 -1 2 -1 -1 2 2 -1 -1 2 7 3 2 7 3 Note Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase: <image> Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer. After second 3 robot 6 just drive infinitely because there's no robot to collide with. Submitted Solution: ``` from __future__ import print_function from sys import stdin,stdout import sys import traceback from bisect import bisect_left, bisect_right, insort from itertools import chain, repeat, starmap from math import log from operator import add, eq, ne, gt, ge, lt, le, iadd from textwrap import dedent try: from collections.abc import Sequence, MutableSequence except ImportError: from collections import Sequence, MutableSequence from functools import wraps from sys import hexversion if hexversion < 0x03000000: from itertools import imap as map # pylint: disable=redefined-builtin from itertools import izip as zip # pylint: disable=redefined-builtin try: from thread import get_ident except ImportError: from dummy_thread import get_ident else: from functools import reduce try: from _thread import get_ident except ImportError: from _dummy_thread import get_ident def recursive_repr(fillvalue='...'): "Decorator to make a repr function return fillvalue for a recursive call." # pylint: disable=missing-docstring # Copied from reprlib in Python 3 # https://hg.python.org/cpython/file/3.6/Lib/reprlib.py def decorating_function(user_function): repr_running = set() @wraps(user_function) def wrapper(self): key = id(self), get_ident() if key in repr_running: return fillvalue repr_running.add(key) try: result = user_function(self) finally: repr_running.discard(key) return result return wrapper return decorating_function class SortedList(MutableSequence): DEFAULT_LOAD_FACTOR = 1000 def __init__(self, iterable=None, key=None): assert key is None self._len = 0 self._load = self.DEFAULT_LOAD_FACTOR self._lists = [] self._maxes = [] self._index = [] self._offset = 0 if iterable is not None: self._update(iterable) def __new__(cls, iterable=None, key=None): # pylint: disable=unused-argument if key is None: return object.__new__(cls) else: if cls is SortedList: return object.__new__(SortedKeyList) else: raise TypeError('inherit SortedKeyList for key argument') @property def key(self): # pylint: disable=useless-return return None def _reset(self, load): values = reduce(iadd, self._lists, []) self._clear() self._load = load self._update(values) def clear(self): self._len = 0 del self._lists[:] del self._maxes[:] del self._index[:] self._offset = 0 _clear = clear def add(self, value): _lists = self._lists _maxes = self._maxes if _maxes: pos = bisect_right(_maxes, value) if pos == len(_maxes): pos -= 1 _lists[pos].append(value) _maxes[pos] = value else: insort(_lists[pos], value) self._expand(pos) else: _lists.append([value]) _maxes.append(value) self._len += 1 def _expand(self, pos): _load = self._load _lists = self._lists _index = self._index if len(_lists[pos]) > (_load << 1): _maxes = self._maxes _lists_pos = _lists[pos] half = _lists_pos[_load:] del _lists_pos[_load:] _maxes[pos] = _lists_pos[-1] _lists.insert(pos + 1, half) _maxes.insert(pos + 1, half[-1]) del _index[:] else: if _index: child = self._offset + pos while child: _index[child] += 1 child = (child - 1) >> 1 _index[0] += 1 def update(self, iterable): _lists = self._lists _maxes = self._maxes values = sorted(iterable) if _maxes: if len(values) * 4 >= self._len: _lists.append(values) values = reduce(iadd, _lists, []) values.sort() self._clear() else: _add = self.add for val in values: _add(val) return _load = self._load _lists.extend(values[pos:(pos + _load)] for pos in range(0, len(values), _load)) _maxes.extend(sublist[-1] for sublist in _lists) self._len = len(values) del self._index[:] _update = update def __contains__(self, value): _maxes = self._maxes if not _maxes: return False pos = bisect_left(_maxes, value) if pos == len(_maxes): return False _lists = self._lists idx = bisect_left(_lists[pos], value) return _lists[pos][idx] == value def discard(self, value): _maxes = self._maxes if not _maxes: return pos = bisect_left(_maxes, value) if pos == len(_maxes): return _lists = self._lists idx = bisect_left(_lists[pos], value) if _lists[pos][idx] == value: self._delete(pos, idx) def remove(self, value): _maxes = self._maxes if not _maxes: raise ValueError('{0!r} not in list'.format(value)) pos = bisect_left(_maxes, value) if pos == len(_maxes): raise ValueError('{0!r} not in list'.format(value)) _lists = self._lists idx = bisect_left(_lists[pos], value) if _lists[pos][idx] == value: self._delete(pos, idx) else: raise ValueError('{0!r} not in list'.format(value)) def _delete(self, pos, idx): _lists = self._lists _maxes = self._maxes _index = self._index _lists_pos = _lists[pos] del _lists_pos[idx] self._len -= 1 len_lists_pos = len(_lists_pos) if len_lists_pos > (self._load >> 1): _maxes[pos] = _lists_pos[-1] if _index: child = self._offset + pos while child > 0: _index[child] -= 1 child = (child - 1) >> 1 _index[0] -= 1 elif len(_lists) > 1: if not pos: pos += 1 prev = pos - 1 _lists[prev].extend(_lists[pos]) _maxes[prev] = _lists[prev][-1] del _lists[pos] del _maxes[pos] del _index[:] self._expand(prev) elif len_lists_pos: _maxes[pos] = _lists_pos[-1] else: del _lists[pos] del _maxes[pos] del _index[:] def _loc(self, pos, idx): if not pos: return idx _index = self._index if not _index: self._build_index() total = 0 # Increment pos to point in the index to len(self._lists[pos]). pos += self._offset # Iterate until reaching the root of the index tree at pos = 0. while pos: # Right-child nodes are at odd indices. At such indices # account the total below the left child node. if not pos & 1: total += _index[pos - 1] # Advance pos to the parent node. pos = (pos - 1) >> 1 return total + idx def _pos(self, idx): if idx < 0: last_len = len(self._lists[-1]) if (-idx) <= last_len: return len(self._lists) - 1, last_len + idx idx += self._len if idx < 0: raise IndexError('list index out of range') elif idx >= self._len: raise IndexError('list index out of range') if idx < len(self._lists[0]): return 0, idx _index = self._index if not _index: self._build_index() pos = 0 child = 1 len_index = len(_index) while child < len_index: index_child = _index[child] if idx < index_child: pos = child else: idx -= index_child pos = child + 1 child = (pos << 1) + 1 return (pos - self._offset, idx) def _build_index(self): row0 = list(map(len, self._lists)) if len(row0) == 1: self._index[:] = row0 self._offset = 0 return head = iter(row0) tail = iter(head) row1 = list(starmap(add, zip(head, tail))) if len(row0) & 1: row1.append(row0[-1]) if len(row1) == 1: self._index[:] = row1 + row0 self._offset = 1 return size = 2 ** (int(log(len(row1) - 1, 2)) + 1) row1.extend(repeat(0, size - len(row1))) tree = [row0, row1] while len(tree[-1]) > 1: head = iter(tree[-1]) tail = iter(head) row = list(starmap(add, zip(head, tail))) tree.append(row) reduce(iadd, reversed(tree), self._index) self._offset = size * 2 - 1 def __delitem__(self, index): if isinstance(index, slice): start, stop, step = index.indices(self._len) if step == 1 and start < stop: if start == 0 and stop == self._len: return self._clear() elif self._len <= 8 * (stop - start): values = self._getitem(slice(None, start)) if stop < self._len: values += self._getitem(slice(stop, None)) self._clear() return self._update(values) indices = range(start, stop, step) # Delete items from greatest index to least so # that the indices remain valid throughout iteration. if step > 0: indices = reversed(indices) _pos, _delete = self._pos, self._delete for index in indices: pos, idx = _pos(index) _delete(pos, idx) else: pos, idx = self._pos(index) self._delete(pos, idx) def __getitem__(self, index): _lists = self._lists if isinstance(index, slice): start, stop, step = index.indices(self._len) if step == 1 and start < stop: # Whole slice optimization: start to stop slices the whole # sorted list. if start == 0 and stop == self._len: return reduce(iadd, self._lists, []) start_pos, start_idx = self._pos(start) start_list = _lists[start_pos] stop_idx = start_idx + stop - start # Small slice optimization: start index and stop index are # within the start list. if len(start_list) >= stop_idx: return start_list[start_idx:stop_idx] if stop == self._len: stop_pos = len(_lists) - 1 stop_idx = len(_lists[stop_pos]) else: stop_pos, stop_idx = self._pos(stop) prefix = _lists[start_pos][start_idx:] middle = _lists[(start_pos + 1):stop_pos] result = reduce(iadd, middle, prefix) result += _lists[stop_pos][:stop_idx] return result if step == -1 and start > stop: result = self._getitem(slice(stop + 1, start + 1)) result.reverse() return result # Return a list because a negative step could # reverse the order of the items and this could # be the desired behavior. indices = range(start, stop, step) return list(self._getitem(index) for index in indices) else: if self._len: if index == 0: return _lists[0][0] elif index == -1: return _lists[-1][-1] else: raise IndexError('list index out of range') if 0 <= index < len(_lists[0]): return _lists[0][index] len_last = len(_lists[-1]) if -len_last < index < 0: return _lists[-1][len_last + index] pos, idx = self._pos(index) return _lists[pos][idx] _getitem = __getitem__ def __setitem__(self, index, value): message = 'use ``del sl[index]`` and ``sl.add(value)`` instead' raise NotImplementedError(message) def __iter__(self): return chain.from_iterable(self._lists) def __reversed__(self): return chain.from_iterable(map(reversed, reversed(self._lists))) def reverse(self): raise NotImplementedError('use ``reversed(sl)`` instead') def islice(self, start=None, stop=None, reverse=False): _len = self._len if not _len: return iter(()) start, stop, _ = slice(start, stop).indices(self._len) if start >= stop: return iter(()) _pos = self._pos min_pos, min_idx = _pos(start) if stop == _len: max_pos = len(self._lists) - 1 max_idx = len(self._lists[-1]) else: max_pos, max_idx = _pos(stop) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse) def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse): _lists = self._lists if min_pos > max_pos: return iter(()) if min_pos == max_pos: if reverse: indices = reversed(range(min_idx, max_idx)) return map(_lists[min_pos].__getitem__, indices) indices = range(min_idx, max_idx) return map(_lists[min_pos].__getitem__, indices) next_pos = min_pos + 1 if next_pos == max_pos: if reverse: min_indices = range(min_idx, len(_lists[min_pos])) max_indices = range(max_idx) return chain( map(_lists[max_pos].__getitem__, reversed(max_indices)), map(_lists[min_pos].__getitem__, reversed(min_indices)), ) min_indices = range(min_idx, len(_lists[min_pos])) max_indices = range(max_idx) return chain( map(_lists[min_pos].__getitem__, min_indices), map(_lists[max_pos].__getitem__, max_indices), ) if reverse: min_indices = range(min_idx, len(_lists[min_pos])) sublist_indices = range(next_pos, max_pos) sublists = map(_lists.__getitem__, reversed(sublist_indices)) max_indices = range(max_idx) return chain( map(_lists[max_pos].__getitem__, reversed(max_indices)), chain.from_iterable(map(reversed, sublists)), map(_lists[min_pos].__getitem__, reversed(min_indices)), ) min_indices = range(min_idx, len(_lists[min_pos])) sublist_indices = range(next_pos, max_pos) sublists = map(_lists.__getitem__, sublist_indices) max_indices = range(max_idx) return chain( map(_lists[min_pos].__getitem__, min_indices), chain.from_iterable(sublists), map(_lists[max_pos].__getitem__, max_indices), ) def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False): _maxes = self._maxes if not _maxes: return iter(()) _lists = self._lists # Calculate the minimum (pos, idx) pair. By default this location # will be inclusive in our calculation. if minimum is None: min_pos = 0 min_idx = 0 else: if inclusive[0]: min_pos = bisect_left(_maxes, minimum) if min_pos == len(_maxes): return iter(()) min_idx = bisect_left(_lists[min_pos], minimum) else: min_pos = bisect_right(_maxes, minimum) if min_pos == len(_maxes): return iter(()) min_idx = bisect_right(_lists[min_pos], minimum) # Calculate the maximum (pos, idx) pair. By default this location # will be exclusive in our calculation. if maximum is None: max_pos = len(_maxes) - 1 max_idx = len(_lists[max_pos]) else: if inclusive[1]: max_pos = bisect_right(_maxes, maximum) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_lists[max_pos]) else: max_idx = bisect_right(_lists[max_pos], maximum) else: max_pos = bisect_left(_maxes, maximum) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_lists[max_pos]) else: max_idx = bisect_left(_lists[max_pos], maximum) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse) def __len__(self): """Return the size of the sorted list. ``sl.__len__()`` <==> ``len(sl)`` :return: size of sorted list """ return self._len def bisect_left(self, value): _maxes = self._maxes if not _maxes: return 0 pos = bisect_left(_maxes, value) if pos == len(_maxes): return self._len idx = bisect_left(self._lists[pos], value) return self._loc(pos, idx) def bisect_right(self, value): _maxes = self._maxes if not _maxes: return 0 pos = bisect_right(_maxes, value) if pos == len(_maxes): return self._len idx = bisect_right(self._lists[pos], value) return self._loc(pos, idx) bisect = bisect_right _bisect_right = bisect_right def count(self, value): _maxes = self._maxes if not _maxes: return 0 pos_left = bisect_left(_maxes, value) if pos_left == len(_maxes): return 0 _lists = self._lists idx_left = bisect_left(_lists[pos_left], value) pos_right = bisect_right(_maxes, value) if pos_right == len(_maxes): return self._len - self._loc(pos_left, idx_left) idx_right = bisect_right(_lists[pos_right], value) if pos_left == pos_right: return idx_right - idx_left right = self._loc(pos_right, idx_right) left = self._loc(pos_left, idx_left) return right - left def copy(self): return self.__class__(self) __copy__ = copy def append(self, value): raise NotImplementedError('use ``sl.add(value)`` instead') def extend(self, values): raise NotImplementedError('use ``sl.update(values)`` instead') def insert(self, index, value): raise NotImplementedError('use ``sl.add(value)`` instead') def pop(self, index=-1): if not self._len: raise IndexError('pop index out of range') _lists = self._lists if index == 0: val = _lists[0][0] self._delete(0, 0) return val if index == -1: pos = len(_lists) - 1 loc = len(_lists[pos]) - 1 val = _lists[pos][loc] self._delete(pos, loc) return val if 0 <= index < len(_lists[0]): val = _lists[0][index] self._delete(0, index) return val len_last = len(_lists[-1]) if -len_last < index < 0: pos = len(_lists) - 1 loc = len_last + index val = _lists[pos][loc] self._delete(pos, loc) return val pos, idx = self._pos(index) val = _lists[pos][idx] self._delete(pos, idx) return val def index(self, value, start=None, stop=None): _len = self._len if not _len: raise ValueError('{0!r} is not in list'.format(value)) if start is None: start = 0 if start < 0: start += _len if start < 0: start = 0 if stop is None: stop = _len if stop < 0: stop += _len if stop > _len: stop = _len if stop <= start: raise ValueError('{0!r} is not in list'.format(value)) _maxes = self._maxes pos_left = bisect_left(_maxes, value) if pos_left == len(_maxes): raise ValueError('{0!r} is not in list'.format(value)) _lists = self._lists idx_left = bisect_left(_lists[pos_left], value) if _lists[pos_left][idx_left] != value: raise ValueError('{0!r} is not in list'.format(value)) stop -= 1 left = self._loc(pos_left, idx_left) if start <= left: if left <= stop: return left else: right = self._bisect_right(value) - 1 if start <= right: return start raise ValueError('{0!r} is not in list'.format(value)) def __add__(self, other): values = reduce(iadd, self._lists, []) values.extend(other) return self.__class__(values) __radd__ = __add__ def __iadd__(self, other): self._update(other) return self def __mul__(self, num): values = reduce(iadd, self._lists, []) * num return self.__class__(values) __rmul__ = __mul__ def __imul__(self, num): values = reduce(iadd, self._lists, []) * num self._clear() self._update(values) return self def __make_cmp(seq_op, symbol, doc): "Make comparator method." def comparer(self, other): "Compare method for sorted list and sequence." if not isinstance(other, Sequence): return NotImplemented self_len = self._len len_other = len(other) if self_len != len_other: if seq_op is eq: return False if seq_op is ne: return True for alpha, beta in zip(self, other): if alpha != beta: return seq_op(alpha, beta) return seq_op(self_len, len_other) seq_op_name = seq_op.__name__ comparer.__name__ = '__{0}__'.format(seq_op_name) doc_str = """Return true if and only if sorted list is {0} `other`. ``sl.__{1}__(other)`` <==> ``sl {2} other`` Comparisons use lexicographical order as with sequences. Runtime complexity: `O(n)` :param other: `other` sequence :return: true if sorted list is {0} `other` """ comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol)) return comparer __eq__ = __make_cmp(eq, '==', 'equal to') __ne__ = __make_cmp(ne, '!=', 'not equal to') __lt__ = __make_cmp(lt, '<', 'less than') __gt__ = __make_cmp(gt, '>', 'greater than') __le__ = __make_cmp(le, '<=', 'less than or equal to') __ge__ = __make_cmp(ge, '>=', 'greater than or equal to') __make_cmp = staticmethod(__make_cmp) def __reduce__(self): values = reduce(iadd, self._lists, []) return (type(self), (values,)) @recursive_repr() def __repr__(self): """Return string representation of sorted list. ``sl.__repr__()`` <==> ``repr(sl)`` :return: string representation """ return '{0}({1!r})'.format(type(self).__name__, list(self)) def _check(self): """Check invariants of sorted list. Runtime complexity: `O(n)` """ try: assert self._load >= 4 assert len(self._maxes) == len(self._lists) assert self._len == sum(len(sublist) for sublist in self._lists) # Check all sublists are sorted. for sublist in self._lists: for pos in range(1, len(sublist)): assert sublist[pos - 1] <= sublist[pos] # Check beginning/end of sublists are sorted. for pos in range(1, len(self._lists)): assert self._lists[pos - 1][-1] <= self._lists[pos][0] # Check _maxes index is the last value of each sublist. for pos in range(len(self._maxes)): assert self._maxes[pos] == self._lists[pos][-1] # Check sublist lengths are less than double load-factor. double = self._load << 1 assert all(len(sublist) <= double for sublist in self._lists) # Check sublist lengths are greater than half load-factor for all # but the last sublist. half = self._load >> 1 for pos in range(0, len(self._lists) - 1): assert len(self._lists[pos]) >= half if self._index: assert self._len == self._index[0] assert len(self._index) == self._offset + len(self._lists) # Check index leaf nodes equal length of sublists. for pos in range(len(self._lists)): leaf = self._index[self._offset + pos] assert leaf == len(self._lists[pos]) # Check index branch nodes are the sum of their children. for pos in range(self._offset): child = (pos << 1) + 1 if child >= len(self._index): assert self._index[pos] == 0 elif child + 1 == len(self._index): assert self._index[pos] == self._index[child] else: child_sum = self._index[child] + self._index[child + 1] assert child_sum == self._index[pos] except: traceback.print_exc(file=sys.stdout) raise def identity(value): "Identity function." return value class SortedKeyList(SortedList): def __init__(self, iterable=None, key=identity): self._key = key self._len = 0 self._load = self.DEFAULT_LOAD_FACTOR self._lists = [] self._keys = [] self._maxes = [] self._index = [] self._offset = 0 if iterable is not None: self._update(iterable) def __new__(cls, iterable=None, key=identity): return object.__new__(cls) @property def key(self): return self._key def clear(self): self._len = 0 del self._lists[:] del self._keys[:] del self._maxes[:] del self._index[:] _clear = clear def add(self, value): _lists = self._lists _keys = self._keys _maxes = self._maxes key = self._key(value) if _maxes: pos = bisect_right(_maxes, key) if pos == len(_maxes): pos -= 1 _lists[pos].append(value) _keys[pos].append(key) _maxes[pos] = key else: idx = bisect_right(_keys[pos], key) _lists[pos].insert(idx, value) _keys[pos].insert(idx, key) self._expand(pos) else: _lists.append([value]) _keys.append([key]) _maxes.append(key) self._len += 1 def _expand(self, pos): _lists = self._lists _keys = self._keys _index = self._index if len(_keys[pos]) > (self._load << 1): _maxes = self._maxes _load = self._load _lists_pos = _lists[pos] _keys_pos = _keys[pos] half = _lists_pos[_load:] half_keys = _keys_pos[_load:] del _lists_pos[_load:] del _keys_pos[_load:] _maxes[pos] = _keys_pos[-1] _lists.insert(pos + 1, half) _keys.insert(pos + 1, half_keys) _maxes.insert(pos + 1, half_keys[-1]) del _index[:] else: if _index: child = self._offset + pos while child: _index[child] += 1 child = (child - 1) >> 1 _index[0] += 1 def update(self, iterable): _lists = self._lists _keys = self._keys _maxes = self._maxes values = sorted(iterable, key=self._key) if _maxes: if len(values) * 4 >= self._len: _lists.append(values) values = reduce(iadd, _lists, []) values.sort(key=self._key) self._clear() else: _add = self.add for val in values: _add(val) return _load = self._load _lists.extend(values[pos:(pos + _load)] for pos in range(0, len(values), _load)) _keys.extend(list(map(self._key, _list)) for _list in _lists) _maxes.extend(sublist[-1] for sublist in _keys) self._len = len(values) del self._index[:] _update = update def __contains__(self, value): _maxes = self._maxes if not _maxes: return False key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): return False _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: return False if _lists[pos][idx] == value: return True idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: return False len_sublist = len(_keys[pos]) idx = 0 def discard(self, value): _maxes = self._maxes if not _maxes: return key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): return _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: return if _lists[pos][idx] == value: self._delete(pos, idx) return idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: return len_sublist = len(_keys[pos]) idx = 0 def remove(self, value): _maxes = self._maxes if not _maxes: raise ValueError('{0!r} not in list'.format(value)) key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): raise ValueError('{0!r} not in list'.format(value)) _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: raise ValueError('{0!r} not in list'.format(value)) if _lists[pos][idx] == value: self._delete(pos, idx) return idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: raise ValueError('{0!r} not in list'.format(value)) len_sublist = len(_keys[pos]) idx = 0 def _delete(self, pos, idx): _lists = self._lists _keys = self._keys _maxes = self._maxes _index = self._index keys_pos = _keys[pos] lists_pos = _lists[pos] del keys_pos[idx] del lists_pos[idx] self._len -= 1 len_keys_pos = len(keys_pos) if len_keys_pos > (self._load >> 1): _maxes[pos] = keys_pos[-1] if _index: child = self._offset + pos while child > 0: _index[child] -= 1 child = (child - 1) >> 1 _index[0] -= 1 elif len(_keys) > 1: if not pos: pos += 1 prev = pos - 1 _keys[prev].extend(_keys[pos]) _lists[prev].extend(_lists[pos]) _maxes[prev] = _keys[prev][-1] del _lists[pos] del _keys[pos] del _maxes[pos] del _index[:] self._expand(prev) elif len_keys_pos: _maxes[pos] = keys_pos[-1] else: del _lists[pos] del _keys[pos] del _maxes[pos] del _index[:] def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False): min_key = self._key(minimum) if minimum is not None else None max_key = self._key(maximum) if maximum is not None else None return self._irange_key( min_key=min_key, max_key=max_key, inclusive=inclusive, reverse=reverse, ) def irange_key(self, min_key=None, max_key=None, inclusive=(True, True), reverse=False): _maxes = self._maxes if not _maxes: return iter(()) _keys = self._keys if min_key is None: min_pos = 0 min_idx = 0 else: if inclusive[0]: min_pos = bisect_left(_maxes, min_key) if min_pos == len(_maxes): return iter(()) min_idx = bisect_left(_keys[min_pos], min_key) else: min_pos = bisect_right(_maxes, min_key) if min_pos == len(_maxes): return iter(()) min_idx = bisect_right(_keys[min_pos], min_key) if max_key is None: max_pos = len(_maxes) - 1 max_idx = len(_keys[max_pos]) else: if inclusive[1]: max_pos = bisect_right(_maxes, max_key) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_keys[max_pos]) else: max_idx = bisect_right(_keys[max_pos], max_key) else: max_pos = bisect_left(_maxes, max_key) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_keys[max_pos]) else: max_idx = bisect_left(_keys[max_pos], max_key) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse) _irange_key = irange_key def bisect_left(self, value): return self._bisect_key_left(self._key(value)) def bisect_right(self, value): return self._bisect_key_right(self._key(value)) bisect = bisect_right def bisect_key_left(self, key): _maxes = self._maxes if not _maxes: return 0 pos = bisect_left(_maxes, key) if pos == len(_maxes): return self._len idx = bisect_left(self._keys[pos], key) return self._loc(pos, idx) _bisect_key_left = bisect_key_left def bisect_key_right(self, key): _maxes = self._maxes if not _maxes: return 0 pos = bisect_right(_maxes, key) if pos == len(_maxes): return self._len idx = bisect_right(self._keys[pos], key) return self._loc(pos, idx) bisect_key = bisect_key_right _bisect_key_right = bisect_key_right def count(self, value): _maxes = self._maxes if not _maxes: return 0 key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): return 0 _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) total = 0 len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: return total if _lists[pos][idx] == value: total += 1 idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: return total len_sublist = len(_keys[pos]) idx = 0 def copy(self): return self.__class__(self, key=self._key) __copy__ = copy def index(self, value, start=None, stop=None): _len = self._len if not _len: raise ValueError('{0!r} is not in list'.format(value)) if start is None: start = 0 if start < 0: start += _len if start < 0: start = 0 if stop is None: stop = _len if stop < 0: stop += _len if stop > _len: stop = _len if stop <= start: raise ValueError('{0!r} is not in list'.format(value)) _maxes = self._maxes key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): raise ValueError('{0!r} is not in list'.format(value)) stop -= 1 _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: raise ValueError('{0!r} is not in list'.format(value)) if _lists[pos][idx] == value: loc = self._loc(pos, idx) if start <= loc <= stop: return loc elif loc > stop: break idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: raise ValueError('{0!r} is not in list'.format(value)) len_sublist = len(_keys[pos]) idx = 0 raise ValueError('{0!r} is not in list'.format(value)) def __add__(self, other): values = reduce(iadd, self._lists, []) values.extend(other) return self.__class__(values, key=self._key) __radd__ = __add__ def __mul__(self, num): values = reduce(iadd, self._lists, []) * num return self.__class__(values, key=self._key) def __reduce__(self): values = reduce(iadd, self._lists, []) return (type(self), (values, self.key)) @recursive_repr() def __repr__(self): type_name = type(self).__name__ return '{0}({1!r}, key={2!r})'.format(type_name, list(self), self._key) def _check(self): try: assert self._load >= 4 assert len(self._maxes) == len(self._lists) == len(self._keys) assert self._len == sum(len(sublist) for sublist in self._lists) for sublist in self._keys: for pos in range(1, len(sublist)): assert sublist[pos - 1] <= sublist[pos] for pos in range(1, len(self._keys)): assert self._keys[pos - 1][-1] <= self._keys[pos][0] for val_sublist, key_sublist in zip(self._lists, self._keys): assert len(val_sublist) == len(key_sublist) for val, key in zip(val_sublist, key_sublist): assert self._key(val) == key for pos in range(len(self._maxes)): assert self._maxes[pos] == self._keys[pos][-1] double = self._load << 1 assert all(len(sublist) <= double for sublist in self._lists) half = self._load >> 1 for pos in range(0, len(self._lists) - 1): assert len(self._lists[pos]) >= half if self._index: assert self._len == self._index[0] assert len(self._index) == self._offset + len(self._lists) for pos in range(len(self._lists)): leaf = self._index[self._offset + pos] assert leaf == len(self._lists[pos]) for pos in range(self._offset): child = (pos << 1) + 1 if child >= len(self._index): assert self._index[pos] == 0 elif child + 1 == len(self._index): assert self._index[pos] == self._index[child] else: child_sum = self._index[child] + self._index[child + 1] assert child_sum == self._index[pos] except: traceback.print_exc(file=sys.stdout) def comp(M,l,r): nr=[] nl=[] while len(r): x=r.pop() val=-1 while len(l)>0 and l[-1]>x: if val!=-1: nl.append(val) val=l[-1] l.pop() if val==-1: nr.append(x) continue y=val val=(y-x)/2 ans[m[y]]=val ans[m[x]]=val while len(l): nl.append(l.pop()) l=nl[:] r=nr[:] l.sort() r.sort() l=l[::-1] while len(l)>1: x1=l.pop() x2=l.pop() val=(x1+x2)/2 ans[m[x1]]=val ans[m[x2]]=val while len(r)>1: x1=r.pop() x2=r.pop() val=(M-x1+M-x2)/2 ans[m[x1]]=val ans[m[x2]]=val if len(l)==1 and len(r)==1: x1=l.pop() x3=r.pop() x2=M-x3 common=max(x1,x2) pos1=common-x1 pos2=M-(common-x2) tot=common+(pos2-pos1)/2 ans[m[x1]]=tot ans[m[x3]]=tot for _ in range(input()): n,M=[int(i) for i in raw_input().split()] a=[int(i) for i in raw_input().split()] s=[i for i in raw_input().split()] al=[] bl=[] ar=[] br=[] m={} ans=[-1 for i in range(n)] for i in range(n): m[a[i]]=i if a[i]%2==0: if s[i]=='L': al.append(a[i]) else: ar.append(a[i]) else: if s[i]=='L': bl.append(a[i]) else: br.append(a[i]) comp(M,al,ar) comp(M,bl,br) for i in ans: print(i,end=" ") print() ``` No
88,672
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m. The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate. Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed. Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens. For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. Then the descriptions of t testcases follow. The first line of each testcase contains two integers n and m (1 ≀ n ≀ 3 β‹… 10^5; 2 ≀ m ≀ 10^8) β€” the number of robots and the coordinate of the right wall. The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β€” the starting coordinates of the robots. The third line of each testcase contains n space-separated characters 'L' or 'R' β€” the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates x_i in the testcase are distinct. The sum of n over all testcases doesn't exceed 3 β‹… 10^5. Output For each testcase print n integers β€” for the i-th robot output the time it explodes at if it does and -1 otherwise. Example Input 5 7 12 1 2 3 4 9 10 11 R R L L R R R 2 10 1 6 R R 2 10 1 3 L L 1 10 5 R 7 8 6 1 7 2 3 5 4 R L R L L L L Output 1 1 1 1 2 -1 2 -1 -1 2 2 -1 -1 2 7 3 2 7 3 Note Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase: <image> Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer. After second 3 robot 6 just drive infinitely because there's no robot to collide with. Submitted Solution: ``` from __future__ import print_function from sys import stdin,stdout import sys import traceback from bisect import bisect_left, bisect_right, insort from itertools import chain, repeat, starmap from math import log from operator import add, eq, ne, gt, ge, lt, le, iadd from textwrap import dedent try: from collections.abc import Sequence, MutableSequence except ImportError: from collections import Sequence, MutableSequence from functools import wraps from sys import hexversion if hexversion < 0x03000000: from itertools import imap as map # pylint: disable=redefined-builtin from itertools import izip as zip # pylint: disable=redefined-builtin try: from thread import get_ident except ImportError: from dummy_thread import get_ident else: from functools import reduce try: from _thread import get_ident except ImportError: from _dummy_thread import get_ident def recursive_repr(fillvalue='...'): "Decorator to make a repr function return fillvalue for a recursive call." # pylint: disable=missing-docstring # Copied from reprlib in Python 3 # https://hg.python.org/cpython/file/3.6/Lib/reprlib.py def decorating_function(user_function): repr_running = set() @wraps(user_function) def wrapper(self): key = id(self), get_ident() if key in repr_running: return fillvalue repr_running.add(key) try: result = user_function(self) finally: repr_running.discard(key) return result return wrapper return decorating_function class SortedList(MutableSequence): DEFAULT_LOAD_FACTOR = 1000 def __init__(self, iterable=None, key=None): assert key is None self._len = 0 self._load = self.DEFAULT_LOAD_FACTOR self._lists = [] self._maxes = [] self._index = [] self._offset = 0 if iterable is not None: self._update(iterable) def __new__(cls, iterable=None, key=None): # pylint: disable=unused-argument if key is None: return object.__new__(cls) else: if cls is SortedList: return object.__new__(SortedKeyList) else: raise TypeError('inherit SortedKeyList for key argument') @property def key(self): # pylint: disable=useless-return return None def _reset(self, load): values = reduce(iadd, self._lists, []) self._clear() self._load = load self._update(values) def clear(self): self._len = 0 del self._lists[:] del self._maxes[:] del self._index[:] self._offset = 0 _clear = clear def add(self, value): _lists = self._lists _maxes = self._maxes if _maxes: pos = bisect_right(_maxes, value) if pos == len(_maxes): pos -= 1 _lists[pos].append(value) _maxes[pos] = value else: insort(_lists[pos], value) self._expand(pos) else: _lists.append([value]) _maxes.append(value) self._len += 1 def _expand(self, pos): _load = self._load _lists = self._lists _index = self._index if len(_lists[pos]) > (_load << 1): _maxes = self._maxes _lists_pos = _lists[pos] half = _lists_pos[_load:] del _lists_pos[_load:] _maxes[pos] = _lists_pos[-1] _lists.insert(pos + 1, half) _maxes.insert(pos + 1, half[-1]) del _index[:] else: if _index: child = self._offset + pos while child: _index[child] += 1 child = (child - 1) >> 1 _index[0] += 1 def update(self, iterable): _lists = self._lists _maxes = self._maxes values = sorted(iterable) if _maxes: if len(values) * 4 >= self._len: _lists.append(values) values = reduce(iadd, _lists, []) values.sort() self._clear() else: _add = self.add for val in values: _add(val) return _load = self._load _lists.extend(values[pos:(pos + _load)] for pos in range(0, len(values), _load)) _maxes.extend(sublist[-1] for sublist in _lists) self._len = len(values) del self._index[:] _update = update def __contains__(self, value): _maxes = self._maxes if not _maxes: return False pos = bisect_left(_maxes, value) if pos == len(_maxes): return False _lists = self._lists idx = bisect_left(_lists[pos], value) return _lists[pos][idx] == value def discard(self, value): _maxes = self._maxes if not _maxes: return pos = bisect_left(_maxes, value) if pos == len(_maxes): return _lists = self._lists idx = bisect_left(_lists[pos], value) if _lists[pos][idx] == value: self._delete(pos, idx) def remove(self, value): _maxes = self._maxes if not _maxes: raise ValueError('{0!r} not in list'.format(value)) pos = bisect_left(_maxes, value) if pos == len(_maxes): raise ValueError('{0!r} not in list'.format(value)) _lists = self._lists idx = bisect_left(_lists[pos], value) if _lists[pos][idx] == value: self._delete(pos, idx) else: raise ValueError('{0!r} not in list'.format(value)) def _delete(self, pos, idx): _lists = self._lists _maxes = self._maxes _index = self._index _lists_pos = _lists[pos] del _lists_pos[idx] self._len -= 1 len_lists_pos = len(_lists_pos) if len_lists_pos > (self._load >> 1): _maxes[pos] = _lists_pos[-1] if _index: child = self._offset + pos while child > 0: _index[child] -= 1 child = (child - 1) >> 1 _index[0] -= 1 elif len(_lists) > 1: if not pos: pos += 1 prev = pos - 1 _lists[prev].extend(_lists[pos]) _maxes[prev] = _lists[prev][-1] del _lists[pos] del _maxes[pos] del _index[:] self._expand(prev) elif len_lists_pos: _maxes[pos] = _lists_pos[-1] else: del _lists[pos] del _maxes[pos] del _index[:] def _loc(self, pos, idx): if not pos: return idx _index = self._index if not _index: self._build_index() total = 0 # Increment pos to point in the index to len(self._lists[pos]). pos += self._offset # Iterate until reaching the root of the index tree at pos = 0. while pos: # Right-child nodes are at odd indices. At such indices # account the total below the left child node. if not pos & 1: total += _index[pos - 1] # Advance pos to the parent node. pos = (pos - 1) >> 1 return total + idx def _pos(self, idx): if idx < 0: last_len = len(self._lists[-1]) if (-idx) <= last_len: return len(self._lists) - 1, last_len + idx idx += self._len if idx < 0: raise IndexError('list index out of range') elif idx >= self._len: raise IndexError('list index out of range') if idx < len(self._lists[0]): return 0, idx _index = self._index if not _index: self._build_index() pos = 0 child = 1 len_index = len(_index) while child < len_index: index_child = _index[child] if idx < index_child: pos = child else: idx -= index_child pos = child + 1 child = (pos << 1) + 1 return (pos - self._offset, idx) def _build_index(self): row0 = list(map(len, self._lists)) if len(row0) == 1: self._index[:] = row0 self._offset = 0 return head = iter(row0) tail = iter(head) row1 = list(starmap(add, zip(head, tail))) if len(row0) & 1: row1.append(row0[-1]) if len(row1) == 1: self._index[:] = row1 + row0 self._offset = 1 return size = 2 ** (int(log(len(row1) - 1, 2)) + 1) row1.extend(repeat(0, size - len(row1))) tree = [row0, row1] while len(tree[-1]) > 1: head = iter(tree[-1]) tail = iter(head) row = list(starmap(add, zip(head, tail))) tree.append(row) reduce(iadd, reversed(tree), self._index) self._offset = size * 2 - 1 def __delitem__(self, index): if isinstance(index, slice): start, stop, step = index.indices(self._len) if step == 1 and start < stop: if start == 0 and stop == self._len: return self._clear() elif self._len <= 8 * (stop - start): values = self._getitem(slice(None, start)) if stop < self._len: values += self._getitem(slice(stop, None)) self._clear() return self._update(values) indices = range(start, stop, step) # Delete items from greatest index to least so # that the indices remain valid throughout iteration. if step > 0: indices = reversed(indices) _pos, _delete = self._pos, self._delete for index in indices: pos, idx = _pos(index) _delete(pos, idx) else: pos, idx = self._pos(index) self._delete(pos, idx) def __getitem__(self, index): _lists = self._lists if isinstance(index, slice): start, stop, step = index.indices(self._len) if step == 1 and start < stop: # Whole slice optimization: start to stop slices the whole # sorted list. if start == 0 and stop == self._len: return reduce(iadd, self._lists, []) start_pos, start_idx = self._pos(start) start_list = _lists[start_pos] stop_idx = start_idx + stop - start # Small slice optimization: start index and stop index are # within the start list. if len(start_list) >= stop_idx: return start_list[start_idx:stop_idx] if stop == self._len: stop_pos = len(_lists) - 1 stop_idx = len(_lists[stop_pos]) else: stop_pos, stop_idx = self._pos(stop) prefix = _lists[start_pos][start_idx:] middle = _lists[(start_pos + 1):stop_pos] result = reduce(iadd, middle, prefix) result += _lists[stop_pos][:stop_idx] return result if step == -1 and start > stop: result = self._getitem(slice(stop + 1, start + 1)) result.reverse() return result # Return a list because a negative step could # reverse the order of the items and this could # be the desired behavior. indices = range(start, stop, step) return list(self._getitem(index) for index in indices) else: if self._len: if index == 0: return _lists[0][0] elif index == -1: return _lists[-1][-1] else: raise IndexError('list index out of range') if 0 <= index < len(_lists[0]): return _lists[0][index] len_last = len(_lists[-1]) if -len_last < index < 0: return _lists[-1][len_last + index] pos, idx = self._pos(index) return _lists[pos][idx] _getitem = __getitem__ def __setitem__(self, index, value): message = 'use ``del sl[index]`` and ``sl.add(value)`` instead' raise NotImplementedError(message) def __iter__(self): return chain.from_iterable(self._lists) def __reversed__(self): return chain.from_iterable(map(reversed, reversed(self._lists))) def reverse(self): raise NotImplementedError('use ``reversed(sl)`` instead') def islice(self, start=None, stop=None, reverse=False): _len = self._len if not _len: return iter(()) start, stop, _ = slice(start, stop).indices(self._len) if start >= stop: return iter(()) _pos = self._pos min_pos, min_idx = _pos(start) if stop == _len: max_pos = len(self._lists) - 1 max_idx = len(self._lists[-1]) else: max_pos, max_idx = _pos(stop) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse) def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse): _lists = self._lists if min_pos > max_pos: return iter(()) if min_pos == max_pos: if reverse: indices = reversed(range(min_idx, max_idx)) return map(_lists[min_pos].__getitem__, indices) indices = range(min_idx, max_idx) return map(_lists[min_pos].__getitem__, indices) next_pos = min_pos + 1 if next_pos == max_pos: if reverse: min_indices = range(min_idx, len(_lists[min_pos])) max_indices = range(max_idx) return chain( map(_lists[max_pos].__getitem__, reversed(max_indices)), map(_lists[min_pos].__getitem__, reversed(min_indices)), ) min_indices = range(min_idx, len(_lists[min_pos])) max_indices = range(max_idx) return chain( map(_lists[min_pos].__getitem__, min_indices), map(_lists[max_pos].__getitem__, max_indices), ) if reverse: min_indices = range(min_idx, len(_lists[min_pos])) sublist_indices = range(next_pos, max_pos) sublists = map(_lists.__getitem__, reversed(sublist_indices)) max_indices = range(max_idx) return chain( map(_lists[max_pos].__getitem__, reversed(max_indices)), chain.from_iterable(map(reversed, sublists)), map(_lists[min_pos].__getitem__, reversed(min_indices)), ) min_indices = range(min_idx, len(_lists[min_pos])) sublist_indices = range(next_pos, max_pos) sublists = map(_lists.__getitem__, sublist_indices) max_indices = range(max_idx) return chain( map(_lists[min_pos].__getitem__, min_indices), chain.from_iterable(sublists), map(_lists[max_pos].__getitem__, max_indices), ) def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False): _maxes = self._maxes if not _maxes: return iter(()) _lists = self._lists # Calculate the minimum (pos, idx) pair. By default this location # will be inclusive in our calculation. if minimum is None: min_pos = 0 min_idx = 0 else: if inclusive[0]: min_pos = bisect_left(_maxes, minimum) if min_pos == len(_maxes): return iter(()) min_idx = bisect_left(_lists[min_pos], minimum) else: min_pos = bisect_right(_maxes, minimum) if min_pos == len(_maxes): return iter(()) min_idx = bisect_right(_lists[min_pos], minimum) # Calculate the maximum (pos, idx) pair. By default this location # will be exclusive in our calculation. if maximum is None: max_pos = len(_maxes) - 1 max_idx = len(_lists[max_pos]) else: if inclusive[1]: max_pos = bisect_right(_maxes, maximum) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_lists[max_pos]) else: max_idx = bisect_right(_lists[max_pos], maximum) else: max_pos = bisect_left(_maxes, maximum) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_lists[max_pos]) else: max_idx = bisect_left(_lists[max_pos], maximum) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse) def __len__(self): """Return the size of the sorted list. ``sl.__len__()`` <==> ``len(sl)`` :return: size of sorted list """ return self._len def bisect_left(self, value): _maxes = self._maxes if not _maxes: return 0 pos = bisect_left(_maxes, value) if pos == len(_maxes): return self._len idx = bisect_left(self._lists[pos], value) return self._loc(pos, idx) def bisect_right(self, value): _maxes = self._maxes if not _maxes: return 0 pos = bisect_right(_maxes, value) if pos == len(_maxes): return self._len idx = bisect_right(self._lists[pos], value) return self._loc(pos, idx) bisect = bisect_right _bisect_right = bisect_right def count(self, value): _maxes = self._maxes if not _maxes: return 0 pos_left = bisect_left(_maxes, value) if pos_left == len(_maxes): return 0 _lists = self._lists idx_left = bisect_left(_lists[pos_left], value) pos_right = bisect_right(_maxes, value) if pos_right == len(_maxes): return self._len - self._loc(pos_left, idx_left) idx_right = bisect_right(_lists[pos_right], value) if pos_left == pos_right: return idx_right - idx_left right = self._loc(pos_right, idx_right) left = self._loc(pos_left, idx_left) return right - left def copy(self): return self.__class__(self) __copy__ = copy def append(self, value): raise NotImplementedError('use ``sl.add(value)`` instead') def extend(self, values): raise NotImplementedError('use ``sl.update(values)`` instead') def insert(self, index, value): raise NotImplementedError('use ``sl.add(value)`` instead') def pop(self, index=-1): if not self._len: raise IndexError('pop index out of range') _lists = self._lists if index == 0: val = _lists[0][0] self._delete(0, 0) return val if index == -1: pos = len(_lists) - 1 loc = len(_lists[pos]) - 1 val = _lists[pos][loc] self._delete(pos, loc) return val if 0 <= index < len(_lists[0]): val = _lists[0][index] self._delete(0, index) return val len_last = len(_lists[-1]) if -len_last < index < 0: pos = len(_lists) - 1 loc = len_last + index val = _lists[pos][loc] self._delete(pos, loc) return val pos, idx = self._pos(index) val = _lists[pos][idx] self._delete(pos, idx) return val def index(self, value, start=None, stop=None): _len = self._len if not _len: raise ValueError('{0!r} is not in list'.format(value)) if start is None: start = 0 if start < 0: start += _len if start < 0: start = 0 if stop is None: stop = _len if stop < 0: stop += _len if stop > _len: stop = _len if stop <= start: raise ValueError('{0!r} is not in list'.format(value)) _maxes = self._maxes pos_left = bisect_left(_maxes, value) if pos_left == len(_maxes): raise ValueError('{0!r} is not in list'.format(value)) _lists = self._lists idx_left = bisect_left(_lists[pos_left], value) if _lists[pos_left][idx_left] != value: raise ValueError('{0!r} is not in list'.format(value)) stop -= 1 left = self._loc(pos_left, idx_left) if start <= left: if left <= stop: return left else: right = self._bisect_right(value) - 1 if start <= right: return start raise ValueError('{0!r} is not in list'.format(value)) def __add__(self, other): values = reduce(iadd, self._lists, []) values.extend(other) return self.__class__(values) __radd__ = __add__ def __iadd__(self, other): self._update(other) return self def __mul__(self, num): values = reduce(iadd, self._lists, []) * num return self.__class__(values) __rmul__ = __mul__ def __imul__(self, num): values = reduce(iadd, self._lists, []) * num self._clear() self._update(values) return self def __make_cmp(seq_op, symbol, doc): "Make comparator method." def comparer(self, other): "Compare method for sorted list and sequence." if not isinstance(other, Sequence): return NotImplemented self_len = self._len len_other = len(other) if self_len != len_other: if seq_op is eq: return False if seq_op is ne: return True for alpha, beta in zip(self, other): if alpha != beta: return seq_op(alpha, beta) return seq_op(self_len, len_other) seq_op_name = seq_op.__name__ comparer.__name__ = '__{0}__'.format(seq_op_name) doc_str = """Return true if and only if sorted list is {0} `other`. ``sl.__{1}__(other)`` <==> ``sl {2} other`` Comparisons use lexicographical order as with sequences. Runtime complexity: `O(n)` :param other: `other` sequence :return: true if sorted list is {0} `other` """ comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol)) return comparer __eq__ = __make_cmp(eq, '==', 'equal to') __ne__ = __make_cmp(ne, '!=', 'not equal to') __lt__ = __make_cmp(lt, '<', 'less than') __gt__ = __make_cmp(gt, '>', 'greater than') __le__ = __make_cmp(le, '<=', 'less than or equal to') __ge__ = __make_cmp(ge, '>=', 'greater than or equal to') __make_cmp = staticmethod(__make_cmp) def __reduce__(self): values = reduce(iadd, self._lists, []) return (type(self), (values,)) @recursive_repr() def __repr__(self): """Return string representation of sorted list. ``sl.__repr__()`` <==> ``repr(sl)`` :return: string representation """ return '{0}({1!r})'.format(type(self).__name__, list(self)) def _check(self): """Check invariants of sorted list. Runtime complexity: `O(n)` """ try: assert self._load >= 4 assert len(self._maxes) == len(self._lists) assert self._len == sum(len(sublist) for sublist in self._lists) # Check all sublists are sorted. for sublist in self._lists: for pos in range(1, len(sublist)): assert sublist[pos - 1] <= sublist[pos] # Check beginning/end of sublists are sorted. for pos in range(1, len(self._lists)): assert self._lists[pos - 1][-1] <= self._lists[pos][0] # Check _maxes index is the last value of each sublist. for pos in range(len(self._maxes)): assert self._maxes[pos] == self._lists[pos][-1] # Check sublist lengths are less than double load-factor. double = self._load << 1 assert all(len(sublist) <= double for sublist in self._lists) # Check sublist lengths are greater than half load-factor for all # but the last sublist. half = self._load >> 1 for pos in range(0, len(self._lists) - 1): assert len(self._lists[pos]) >= half if self._index: assert self._len == self._index[0] assert len(self._index) == self._offset + len(self._lists) # Check index leaf nodes equal length of sublists. for pos in range(len(self._lists)): leaf = self._index[self._offset + pos] assert leaf == len(self._lists[pos]) # Check index branch nodes are the sum of their children. for pos in range(self._offset): child = (pos << 1) + 1 if child >= len(self._index): assert self._index[pos] == 0 elif child + 1 == len(self._index): assert self._index[pos] == self._index[child] else: child_sum = self._index[child] + self._index[child + 1] assert child_sum == self._index[pos] except: traceback.print_exc(file=sys.stdout) raise def identity(value): "Identity function." return value class SortedKeyList(SortedList): def __init__(self, iterable=None, key=identity): self._key = key self._len = 0 self._load = self.DEFAULT_LOAD_FACTOR self._lists = [] self._keys = [] self._maxes = [] self._index = [] self._offset = 0 if iterable is not None: self._update(iterable) def __new__(cls, iterable=None, key=identity): return object.__new__(cls) @property def key(self): return self._key def clear(self): self._len = 0 del self._lists[:] del self._keys[:] del self._maxes[:] del self._index[:] _clear = clear def add(self, value): _lists = self._lists _keys = self._keys _maxes = self._maxes key = self._key(value) if _maxes: pos = bisect_right(_maxes, key) if pos == len(_maxes): pos -= 1 _lists[pos].append(value) _keys[pos].append(key) _maxes[pos] = key else: idx = bisect_right(_keys[pos], key) _lists[pos].insert(idx, value) _keys[pos].insert(idx, key) self._expand(pos) else: _lists.append([value]) _keys.append([key]) _maxes.append(key) self._len += 1 def _expand(self, pos): _lists = self._lists _keys = self._keys _index = self._index if len(_keys[pos]) > (self._load << 1): _maxes = self._maxes _load = self._load _lists_pos = _lists[pos] _keys_pos = _keys[pos] half = _lists_pos[_load:] half_keys = _keys_pos[_load:] del _lists_pos[_load:] del _keys_pos[_load:] _maxes[pos] = _keys_pos[-1] _lists.insert(pos + 1, half) _keys.insert(pos + 1, half_keys) _maxes.insert(pos + 1, half_keys[-1]) del _index[:] else: if _index: child = self._offset + pos while child: _index[child] += 1 child = (child - 1) >> 1 _index[0] += 1 def update(self, iterable): _lists = self._lists _keys = self._keys _maxes = self._maxes values = sorted(iterable, key=self._key) if _maxes: if len(values) * 4 >= self._len: _lists.append(values) values = reduce(iadd, _lists, []) values.sort(key=self._key) self._clear() else: _add = self.add for val in values: _add(val) return _load = self._load _lists.extend(values[pos:(pos + _load)] for pos in range(0, len(values), _load)) _keys.extend(list(map(self._key, _list)) for _list in _lists) _maxes.extend(sublist[-1] for sublist in _keys) self._len = len(values) del self._index[:] _update = update def __contains__(self, value): _maxes = self._maxes if not _maxes: return False key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): return False _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: return False if _lists[pos][idx] == value: return True idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: return False len_sublist = len(_keys[pos]) idx = 0 def discard(self, value): _maxes = self._maxes if not _maxes: return key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): return _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: return if _lists[pos][idx] == value: self._delete(pos, idx) return idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: return len_sublist = len(_keys[pos]) idx = 0 def remove(self, value): _maxes = self._maxes if not _maxes: raise ValueError('{0!r} not in list'.format(value)) key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): raise ValueError('{0!r} not in list'.format(value)) _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: raise ValueError('{0!r} not in list'.format(value)) if _lists[pos][idx] == value: self._delete(pos, idx) return idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: raise ValueError('{0!r} not in list'.format(value)) len_sublist = len(_keys[pos]) idx = 0 def _delete(self, pos, idx): _lists = self._lists _keys = self._keys _maxes = self._maxes _index = self._index keys_pos = _keys[pos] lists_pos = _lists[pos] del keys_pos[idx] del lists_pos[idx] self._len -= 1 len_keys_pos = len(keys_pos) if len_keys_pos > (self._load >> 1): _maxes[pos] = keys_pos[-1] if _index: child = self._offset + pos while child > 0: _index[child] -= 1 child = (child - 1) >> 1 _index[0] -= 1 elif len(_keys) > 1: if not pos: pos += 1 prev = pos - 1 _keys[prev].extend(_keys[pos]) _lists[prev].extend(_lists[pos]) _maxes[prev] = _keys[prev][-1] del _lists[pos] del _keys[pos] del _maxes[pos] del _index[:] self._expand(prev) elif len_keys_pos: _maxes[pos] = keys_pos[-1] else: del _lists[pos] del _keys[pos] del _maxes[pos] del _index[:] def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False): min_key = self._key(minimum) if minimum is not None else None max_key = self._key(maximum) if maximum is not None else None return self._irange_key( min_key=min_key, max_key=max_key, inclusive=inclusive, reverse=reverse, ) def irange_key(self, min_key=None, max_key=None, inclusive=(True, True), reverse=False): _maxes = self._maxes if not _maxes: return iter(()) _keys = self._keys if min_key is None: min_pos = 0 min_idx = 0 else: if inclusive[0]: min_pos = bisect_left(_maxes, min_key) if min_pos == len(_maxes): return iter(()) min_idx = bisect_left(_keys[min_pos], min_key) else: min_pos = bisect_right(_maxes, min_key) if min_pos == len(_maxes): return iter(()) min_idx = bisect_right(_keys[min_pos], min_key) if max_key is None: max_pos = len(_maxes) - 1 max_idx = len(_keys[max_pos]) else: if inclusive[1]: max_pos = bisect_right(_maxes, max_key) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_keys[max_pos]) else: max_idx = bisect_right(_keys[max_pos], max_key) else: max_pos = bisect_left(_maxes, max_key) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_keys[max_pos]) else: max_idx = bisect_left(_keys[max_pos], max_key) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse) _irange_key = irange_key def bisect_left(self, value): return self._bisect_key_left(self._key(value)) def bisect_right(self, value): return self._bisect_key_right(self._key(value)) bisect = bisect_right def bisect_key_left(self, key): _maxes = self._maxes if not _maxes: return 0 pos = bisect_left(_maxes, key) if pos == len(_maxes): return self._len idx = bisect_left(self._keys[pos], key) return self._loc(pos, idx) _bisect_key_left = bisect_key_left def bisect_key_right(self, key): _maxes = self._maxes if not _maxes: return 0 pos = bisect_right(_maxes, key) if pos == len(_maxes): return self._len idx = bisect_right(self._keys[pos], key) return self._loc(pos, idx) bisect_key = bisect_key_right _bisect_key_right = bisect_key_right def count(self, value): _maxes = self._maxes if not _maxes: return 0 key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): return 0 _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) total = 0 len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: return total if _lists[pos][idx] == value: total += 1 idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: return total len_sublist = len(_keys[pos]) idx = 0 def copy(self): return self.__class__(self, key=self._key) __copy__ = copy def index(self, value, start=None, stop=None): _len = self._len if not _len: raise ValueError('{0!r} is not in list'.format(value)) if start is None: start = 0 if start < 0: start += _len if start < 0: start = 0 if stop is None: stop = _len if stop < 0: stop += _len if stop > _len: stop = _len if stop <= start: raise ValueError('{0!r} is not in list'.format(value)) _maxes = self._maxes key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): raise ValueError('{0!r} is not in list'.format(value)) stop -= 1 _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: raise ValueError('{0!r} is not in list'.format(value)) if _lists[pos][idx] == value: loc = self._loc(pos, idx) if start <= loc <= stop: return loc elif loc > stop: break idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: raise ValueError('{0!r} is not in list'.format(value)) len_sublist = len(_keys[pos]) idx = 0 raise ValueError('{0!r} is not in list'.format(value)) def __add__(self, other): values = reduce(iadd, self._lists, []) values.extend(other) return self.__class__(values, key=self._key) __radd__ = __add__ def __mul__(self, num): values = reduce(iadd, self._lists, []) * num return self.__class__(values, key=self._key) def __reduce__(self): values = reduce(iadd, self._lists, []) return (type(self), (values, self.key)) @recursive_repr() def __repr__(self): type_name = type(self).__name__ return '{0}({1!r}, key={2!r})'.format(type_name, list(self), self._key) def _check(self): try: assert self._load >= 4 assert len(self._maxes) == len(self._lists) == len(self._keys) assert self._len == sum(len(sublist) for sublist in self._lists) for sublist in self._keys: for pos in range(1, len(sublist)): assert sublist[pos - 1] <= sublist[pos] for pos in range(1, len(self._keys)): assert self._keys[pos - 1][-1] <= self._keys[pos][0] for val_sublist, key_sublist in zip(self._lists, self._keys): assert len(val_sublist) == len(key_sublist) for val, key in zip(val_sublist, key_sublist): assert self._key(val) == key for pos in range(len(self._maxes)): assert self._maxes[pos] == self._keys[pos][-1] double = self._load << 1 assert all(len(sublist) <= double for sublist in self._lists) half = self._load >> 1 for pos in range(0, len(self._lists) - 1): assert len(self._lists[pos]) >= half if self._index: assert self._len == self._index[0] assert len(self._index) == self._offset + len(self._lists) for pos in range(len(self._lists)): leaf = self._index[self._offset + pos] assert leaf == len(self._lists[pos]) for pos in range(self._offset): child = (pos << 1) + 1 if child >= len(self._index): assert self._index[pos] == 0 elif child + 1 == len(self._index): assert self._index[pos] == self._index[child] else: child_sum = self._index[child] + self._index[child + 1] assert child_sum == self._index[pos] except: traceback.print_exc(file=sys.stdout) def comp(M,l,r): nr=[] nl=[] krr=SortedList() for i in l: krr.add(i) while len(r): x=r.pop() pos=krr.bisect_left(x) if pos==len(krr): nr.append(x) continue y=krr[pos] val=(y-x)/2 ans[m[y]]=val ans[m[x]]=val krr.pop(pos) l=[] while len(krr): l.append(krr.pop()) r=nr[:] l.sort() r.sort() l=l[::-1] while len(l)>1: x1=l.pop() x2=l.pop() val=(x1+x2)/2 ans[m[x1]]=val ans[m[x2]]=val while len(r)>1: x1=r.pop() x2=r.pop() val=(M-x1+M-x2)/2 ans[m[x1]]=val ans[m[x2]]=val if len(l)==1 and len(r)==1: x1=l.pop() x3=r.pop() x2=M-x3 common=max(x1,x2) pos1=common-x1 pos2=M-(common-x2) tot=common+(pos2-pos1)/2 ans[m[x1]]=tot ans[m[x3]]=tot for _ in range(input()): n,M=[int(i) for i in raw_input().split()] a=[int(i) for i in raw_input().split()] s=[i for i in raw_input().split()] al=[] bl=[] ar=[] br=[] m={} ans=[-1 for i in range(n)] for i in range(n): m[a[i]]=i if a[i]%2==0: if s[i]=='L': al.append(a[i]) else: ar.append(a[i]) else: if s[i]=='L': bl.append(a[i]) else: br.append(a[i]) comp(M,al,ar) comp(M,bl,br) for i in ans: print(i,end=" ") print() ``` No
88,673
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m. The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate. Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed. Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens. For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. Then the descriptions of t testcases follow. The first line of each testcase contains two integers n and m (1 ≀ n ≀ 3 β‹… 10^5; 2 ≀ m ≀ 10^8) β€” the number of robots and the coordinate of the right wall. The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β€” the starting coordinates of the robots. The third line of each testcase contains n space-separated characters 'L' or 'R' β€” the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates x_i in the testcase are distinct. The sum of n over all testcases doesn't exceed 3 β‹… 10^5. Output For each testcase print n integers β€” for the i-th robot output the time it explodes at if it does and -1 otherwise. Example Input 5 7 12 1 2 3 4 9 10 11 R R L L R R R 2 10 1 6 R R 2 10 1 3 L L 1 10 5 R 7 8 6 1 7 2 3 5 4 R L R L L L L Output 1 1 1 1 2 -1 2 -1 -1 2 2 -1 -1 2 7 3 2 7 3 Note Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase: <image> Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer. After second 3 robot 6 just drive infinitely because there's no robot to collide with. Submitted Solution: ``` from __future__ import print_function from sys import stdin,stdout import sys import traceback from bisect import bisect_left, bisect_right, insort from itertools import chain, repeat, starmap from math import log from operator import add, eq, ne, gt, ge, lt, le, iadd from textwrap import dedent try: from collections.abc import Sequence, MutableSequence except ImportError: from collections import Sequence, MutableSequence from functools import wraps from sys import hexversion if hexversion < 0x03000000: from itertools import imap as map # pylint: disable=redefined-builtin from itertools import izip as zip # pylint: disable=redefined-builtin try: from thread import get_ident except ImportError: from dummy_thread import get_ident else: from functools import reduce try: from _thread import get_ident except ImportError: from _dummy_thread import get_ident def recursive_repr(fillvalue='...'): "Decorator to make a repr function return fillvalue for a recursive call." # pylint: disable=missing-docstring # Copied from reprlib in Python 3 # https://hg.python.org/cpython/file/3.6/Lib/reprlib.py def decorating_function(user_function): repr_running = set() @wraps(user_function) def wrapper(self): key = id(self), get_ident() if key in repr_running: return fillvalue repr_running.add(key) try: result = user_function(self) finally: repr_running.discard(key) return result return wrapper return decorating_function class SortedList(MutableSequence): DEFAULT_LOAD_FACTOR = 1000 def __init__(self, iterable=None, key=None): assert key is None self._len = 0 self._load = self.DEFAULT_LOAD_FACTOR self._lists = [] self._maxes = [] self._index = [] self._offset = 0 if iterable is not None: self._update(iterable) def __new__(cls, iterable=None, key=None): # pylint: disable=unused-argument if key is None: return object.__new__(cls) else: if cls is SortedList: return object.__new__(SortedKeyList) else: raise TypeError('inherit SortedKeyList for key argument') @property def key(self): # pylint: disable=useless-return return None def _reset(self, load): values = reduce(iadd, self._lists, []) self._clear() self._load = load self._update(values) def clear(self): self._len = 0 del self._lists[:] del self._maxes[:] del self._index[:] self._offset = 0 _clear = clear def add(self, value): _lists = self._lists _maxes = self._maxes if _maxes: pos = bisect_right(_maxes, value) if pos == len(_maxes): pos -= 1 _lists[pos].append(value) _maxes[pos] = value else: insort(_lists[pos], value) self._expand(pos) else: _lists.append([value]) _maxes.append(value) self._len += 1 def _expand(self, pos): _load = self._load _lists = self._lists _index = self._index if len(_lists[pos]) > (_load << 1): _maxes = self._maxes _lists_pos = _lists[pos] half = _lists_pos[_load:] del _lists_pos[_load:] _maxes[pos] = _lists_pos[-1] _lists.insert(pos + 1, half) _maxes.insert(pos + 1, half[-1]) del _index[:] else: if _index: child = self._offset + pos while child: _index[child] += 1 child = (child - 1) >> 1 _index[0] += 1 def update(self, iterable): _lists = self._lists _maxes = self._maxes values = sorted(iterable) if _maxes: if len(values) * 4 >= self._len: _lists.append(values) values = reduce(iadd, _lists, []) values.sort() self._clear() else: _add = self.add for val in values: _add(val) return _load = self._load _lists.extend(values[pos:(pos + _load)] for pos in range(0, len(values), _load)) _maxes.extend(sublist[-1] for sublist in _lists) self._len = len(values) del self._index[:] _update = update def __contains__(self, value): _maxes = self._maxes if not _maxes: return False pos = bisect_left(_maxes, value) if pos == len(_maxes): return False _lists = self._lists idx = bisect_left(_lists[pos], value) return _lists[pos][idx] == value def discard(self, value): _maxes = self._maxes if not _maxes: return pos = bisect_left(_maxes, value) if pos == len(_maxes): return _lists = self._lists idx = bisect_left(_lists[pos], value) if _lists[pos][idx] == value: self._delete(pos, idx) def remove(self, value): _maxes = self._maxes if not _maxes: raise ValueError('{0!r} not in list'.format(value)) pos = bisect_left(_maxes, value) if pos == len(_maxes): raise ValueError('{0!r} not in list'.format(value)) _lists = self._lists idx = bisect_left(_lists[pos], value) if _lists[pos][idx] == value: self._delete(pos, idx) else: raise ValueError('{0!r} not in list'.format(value)) def _delete(self, pos, idx): _lists = self._lists _maxes = self._maxes _index = self._index _lists_pos = _lists[pos] del _lists_pos[idx] self._len -= 1 len_lists_pos = len(_lists_pos) if len_lists_pos > (self._load >> 1): _maxes[pos] = _lists_pos[-1] if _index: child = self._offset + pos while child > 0: _index[child] -= 1 child = (child - 1) >> 1 _index[0] -= 1 elif len(_lists) > 1: if not pos: pos += 1 prev = pos - 1 _lists[prev].extend(_lists[pos]) _maxes[prev] = _lists[prev][-1] del _lists[pos] del _maxes[pos] del _index[:] self._expand(prev) elif len_lists_pos: _maxes[pos] = _lists_pos[-1] else: del _lists[pos] del _maxes[pos] del _index[:] def _loc(self, pos, idx): if not pos: return idx _index = self._index if not _index: self._build_index() total = 0 # Increment pos to point in the index to len(self._lists[pos]). pos += self._offset # Iterate until reaching the root of the index tree at pos = 0. while pos: # Right-child nodes are at odd indices. At such indices # account the total below the left child node. if not pos & 1: total += _index[pos - 1] # Advance pos to the parent node. pos = (pos - 1) >> 1 return total + idx def _pos(self, idx): if idx < 0: last_len = len(self._lists[-1]) if (-idx) <= last_len: return len(self._lists) - 1, last_len + idx idx += self._len if idx < 0: raise IndexError('list index out of range') elif idx >= self._len: raise IndexError('list index out of range') if idx < len(self._lists[0]): return 0, idx _index = self._index if not _index: self._build_index() pos = 0 child = 1 len_index = len(_index) while child < len_index: index_child = _index[child] if idx < index_child: pos = child else: idx -= index_child pos = child + 1 child = (pos << 1) + 1 return (pos - self._offset, idx) def _build_index(self): row0 = list(map(len, self._lists)) if len(row0) == 1: self._index[:] = row0 self._offset = 0 return head = iter(row0) tail = iter(head) row1 = list(starmap(add, zip(head, tail))) if len(row0) & 1: row1.append(row0[-1]) if len(row1) == 1: self._index[:] = row1 + row0 self._offset = 1 return size = 2 ** (int(log(len(row1) - 1, 2)) + 1) row1.extend(repeat(0, size - len(row1))) tree = [row0, row1] while len(tree[-1]) > 1: head = iter(tree[-1]) tail = iter(head) row = list(starmap(add, zip(head, tail))) tree.append(row) reduce(iadd, reversed(tree), self._index) self._offset = size * 2 - 1 def __delitem__(self, index): if isinstance(index, slice): start, stop, step = index.indices(self._len) if step == 1 and start < stop: if start == 0 and stop == self._len: return self._clear() elif self._len <= 8 * (stop - start): values = self._getitem(slice(None, start)) if stop < self._len: values += self._getitem(slice(stop, None)) self._clear() return self._update(values) indices = range(start, stop, step) # Delete items from greatest index to least so # that the indices remain valid throughout iteration. if step > 0: indices = reversed(indices) _pos, _delete = self._pos, self._delete for index in indices: pos, idx = _pos(index) _delete(pos, idx) else: pos, idx = self._pos(index) self._delete(pos, idx) def __getitem__(self, index): _lists = self._lists if isinstance(index, slice): start, stop, step = index.indices(self._len) if step == 1 and start < stop: # Whole slice optimization: start to stop slices the whole # sorted list. if start == 0 and stop == self._len: return reduce(iadd, self._lists, []) start_pos, start_idx = self._pos(start) start_list = _lists[start_pos] stop_idx = start_idx + stop - start # Small slice optimization: start index and stop index are # within the start list. if len(start_list) >= stop_idx: return start_list[start_idx:stop_idx] if stop == self._len: stop_pos = len(_lists) - 1 stop_idx = len(_lists[stop_pos]) else: stop_pos, stop_idx = self._pos(stop) prefix = _lists[start_pos][start_idx:] middle = _lists[(start_pos + 1):stop_pos] result = reduce(iadd, middle, prefix) result += _lists[stop_pos][:stop_idx] return result if step == -1 and start > stop: result = self._getitem(slice(stop + 1, start + 1)) result.reverse() return result # Return a list because a negative step could # reverse the order of the items and this could # be the desired behavior. indices = range(start, stop, step) return list(self._getitem(index) for index in indices) else: if self._len: if index == 0: return _lists[0][0] elif index == -1: return _lists[-1][-1] else: raise IndexError('list index out of range') if 0 <= index < len(_lists[0]): return _lists[0][index] len_last = len(_lists[-1]) if -len_last < index < 0: return _lists[-1][len_last + index] pos, idx = self._pos(index) return _lists[pos][idx] _getitem = __getitem__ def __setitem__(self, index, value): message = 'use ``del sl[index]`` and ``sl.add(value)`` instead' raise NotImplementedError(message) def __iter__(self): return chain.from_iterable(self._lists) def __reversed__(self): return chain.from_iterable(map(reversed, reversed(self._lists))) def reverse(self): raise NotImplementedError('use ``reversed(sl)`` instead') def islice(self, start=None, stop=None, reverse=False): _len = self._len if not _len: return iter(()) start, stop, _ = slice(start, stop).indices(self._len) if start >= stop: return iter(()) _pos = self._pos min_pos, min_idx = _pos(start) if stop == _len: max_pos = len(self._lists) - 1 max_idx = len(self._lists[-1]) else: max_pos, max_idx = _pos(stop) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse) def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse): _lists = self._lists if min_pos > max_pos: return iter(()) if min_pos == max_pos: if reverse: indices = reversed(range(min_idx, max_idx)) return map(_lists[min_pos].__getitem__, indices) indices = range(min_idx, max_idx) return map(_lists[min_pos].__getitem__, indices) next_pos = min_pos + 1 if next_pos == max_pos: if reverse: min_indices = range(min_idx, len(_lists[min_pos])) max_indices = range(max_idx) return chain( map(_lists[max_pos].__getitem__, reversed(max_indices)), map(_lists[min_pos].__getitem__, reversed(min_indices)), ) min_indices = range(min_idx, len(_lists[min_pos])) max_indices = range(max_idx) return chain( map(_lists[min_pos].__getitem__, min_indices), map(_lists[max_pos].__getitem__, max_indices), ) if reverse: min_indices = range(min_idx, len(_lists[min_pos])) sublist_indices = range(next_pos, max_pos) sublists = map(_lists.__getitem__, reversed(sublist_indices)) max_indices = range(max_idx) return chain( map(_lists[max_pos].__getitem__, reversed(max_indices)), chain.from_iterable(map(reversed, sublists)), map(_lists[min_pos].__getitem__, reversed(min_indices)), ) min_indices = range(min_idx, len(_lists[min_pos])) sublist_indices = range(next_pos, max_pos) sublists = map(_lists.__getitem__, sublist_indices) max_indices = range(max_idx) return chain( map(_lists[min_pos].__getitem__, min_indices), chain.from_iterable(sublists), map(_lists[max_pos].__getitem__, max_indices), ) def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False): _maxes = self._maxes if not _maxes: return iter(()) _lists = self._lists # Calculate the minimum (pos, idx) pair. By default this location # will be inclusive in our calculation. if minimum is None: min_pos = 0 min_idx = 0 else: if inclusive[0]: min_pos = bisect_left(_maxes, minimum) if min_pos == len(_maxes): return iter(()) min_idx = bisect_left(_lists[min_pos], minimum) else: min_pos = bisect_right(_maxes, minimum) if min_pos == len(_maxes): return iter(()) min_idx = bisect_right(_lists[min_pos], minimum) # Calculate the maximum (pos, idx) pair. By default this location # will be exclusive in our calculation. if maximum is None: max_pos = len(_maxes) - 1 max_idx = len(_lists[max_pos]) else: if inclusive[1]: max_pos = bisect_right(_maxes, maximum) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_lists[max_pos]) else: max_idx = bisect_right(_lists[max_pos], maximum) else: max_pos = bisect_left(_maxes, maximum) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_lists[max_pos]) else: max_idx = bisect_left(_lists[max_pos], maximum) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse) def __len__(self): """Return the size of the sorted list. ``sl.__len__()`` <==> ``len(sl)`` :return: size of sorted list """ return self._len def bisect_left(self, value): _maxes = self._maxes if not _maxes: return 0 pos = bisect_left(_maxes, value) if pos == len(_maxes): return self._len idx = bisect_left(self._lists[pos], value) return self._loc(pos, idx) def bisect_right(self, value): _maxes = self._maxes if not _maxes: return 0 pos = bisect_right(_maxes, value) if pos == len(_maxes): return self._len idx = bisect_right(self._lists[pos], value) return self._loc(pos, idx) bisect = bisect_right _bisect_right = bisect_right def count(self, value): _maxes = self._maxes if not _maxes: return 0 pos_left = bisect_left(_maxes, value) if pos_left == len(_maxes): return 0 _lists = self._lists idx_left = bisect_left(_lists[pos_left], value) pos_right = bisect_right(_maxes, value) if pos_right == len(_maxes): return self._len - self._loc(pos_left, idx_left) idx_right = bisect_right(_lists[pos_right], value) if pos_left == pos_right: return idx_right - idx_left right = self._loc(pos_right, idx_right) left = self._loc(pos_left, idx_left) return right - left def copy(self): return self.__class__(self) __copy__ = copy def append(self, value): raise NotImplementedError('use ``sl.add(value)`` instead') def extend(self, values): raise NotImplementedError('use ``sl.update(values)`` instead') def insert(self, index, value): raise NotImplementedError('use ``sl.add(value)`` instead') def pop(self, index=-1): if not self._len: raise IndexError('pop index out of range') _lists = self._lists if index == 0: val = _lists[0][0] self._delete(0, 0) return val if index == -1: pos = len(_lists) - 1 loc = len(_lists[pos]) - 1 val = _lists[pos][loc] self._delete(pos, loc) return val if 0 <= index < len(_lists[0]): val = _lists[0][index] self._delete(0, index) return val len_last = len(_lists[-1]) if -len_last < index < 0: pos = len(_lists) - 1 loc = len_last + index val = _lists[pos][loc] self._delete(pos, loc) return val pos, idx = self._pos(index) val = _lists[pos][idx] self._delete(pos, idx) return val def index(self, value, start=None, stop=None): _len = self._len if not _len: raise ValueError('{0!r} is not in list'.format(value)) if start is None: start = 0 if start < 0: start += _len if start < 0: start = 0 if stop is None: stop = _len if stop < 0: stop += _len if stop > _len: stop = _len if stop <= start: raise ValueError('{0!r} is not in list'.format(value)) _maxes = self._maxes pos_left = bisect_left(_maxes, value) if pos_left == len(_maxes): raise ValueError('{0!r} is not in list'.format(value)) _lists = self._lists idx_left = bisect_left(_lists[pos_left], value) if _lists[pos_left][idx_left] != value: raise ValueError('{0!r} is not in list'.format(value)) stop -= 1 left = self._loc(pos_left, idx_left) if start <= left: if left <= stop: return left else: right = self._bisect_right(value) - 1 if start <= right: return start raise ValueError('{0!r} is not in list'.format(value)) def __add__(self, other): values = reduce(iadd, self._lists, []) values.extend(other) return self.__class__(values) __radd__ = __add__ def __iadd__(self, other): self._update(other) return self def __mul__(self, num): values = reduce(iadd, self._lists, []) * num return self.__class__(values) __rmul__ = __mul__ def __imul__(self, num): values = reduce(iadd, self._lists, []) * num self._clear() self._update(values) return self def __make_cmp(seq_op, symbol, doc): "Make comparator method." def comparer(self, other): "Compare method for sorted list and sequence." if not isinstance(other, Sequence): return NotImplemented self_len = self._len len_other = len(other) if self_len != len_other: if seq_op is eq: return False if seq_op is ne: return True for alpha, beta in zip(self, other): if alpha != beta: return seq_op(alpha, beta) return seq_op(self_len, len_other) seq_op_name = seq_op.__name__ comparer.__name__ = '__{0}__'.format(seq_op_name) doc_str = """Return true if and only if sorted list is {0} `other`. ``sl.__{1}__(other)`` <==> ``sl {2} other`` Comparisons use lexicographical order as with sequences. Runtime complexity: `O(n)` :param other: `other` sequence :return: true if sorted list is {0} `other` """ comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol)) return comparer __eq__ = __make_cmp(eq, '==', 'equal to') __ne__ = __make_cmp(ne, '!=', 'not equal to') __lt__ = __make_cmp(lt, '<', 'less than') __gt__ = __make_cmp(gt, '>', 'greater than') __le__ = __make_cmp(le, '<=', 'less than or equal to') __ge__ = __make_cmp(ge, '>=', 'greater than or equal to') __make_cmp = staticmethod(__make_cmp) def __reduce__(self): values = reduce(iadd, self._lists, []) return (type(self), (values,)) @recursive_repr() def __repr__(self): """Return string representation of sorted list. ``sl.__repr__()`` <==> ``repr(sl)`` :return: string representation """ return '{0}({1!r})'.format(type(self).__name__, list(self)) def _check(self): """Check invariants of sorted list. Runtime complexity: `O(n)` """ try: assert self._load >= 4 assert len(self._maxes) == len(self._lists) assert self._len == sum(len(sublist) for sublist in self._lists) # Check all sublists are sorted. for sublist in self._lists: for pos in range(1, len(sublist)): assert sublist[pos - 1] <= sublist[pos] # Check beginning/end of sublists are sorted. for pos in range(1, len(self._lists)): assert self._lists[pos - 1][-1] <= self._lists[pos][0] # Check _maxes index is the last value of each sublist. for pos in range(len(self._maxes)): assert self._maxes[pos] == self._lists[pos][-1] # Check sublist lengths are less than double load-factor. double = self._load << 1 assert all(len(sublist) <= double for sublist in self._lists) # Check sublist lengths are greater than half load-factor for all # but the last sublist. half = self._load >> 1 for pos in range(0, len(self._lists) - 1): assert len(self._lists[pos]) >= half if self._index: assert self._len == self._index[0] assert len(self._index) == self._offset + len(self._lists) # Check index leaf nodes equal length of sublists. for pos in range(len(self._lists)): leaf = self._index[self._offset + pos] assert leaf == len(self._lists[pos]) # Check index branch nodes are the sum of their children. for pos in range(self._offset): child = (pos << 1) + 1 if child >= len(self._index): assert self._index[pos] == 0 elif child + 1 == len(self._index): assert self._index[pos] == self._index[child] else: child_sum = self._index[child] + self._index[child + 1] assert child_sum == self._index[pos] except: traceback.print_exc(file=sys.stdout) raise def identity(value): "Identity function." return value class SortedKeyList(SortedList): def __init__(self, iterable=None, key=identity): self._key = key self._len = 0 self._load = self.DEFAULT_LOAD_FACTOR self._lists = [] self._keys = [] self._maxes = [] self._index = [] self._offset = 0 if iterable is not None: self._update(iterable) def __new__(cls, iterable=None, key=identity): return object.__new__(cls) @property def key(self): return self._key def clear(self): self._len = 0 del self._lists[:] del self._keys[:] del self._maxes[:] del self._index[:] _clear = clear def add(self, value): _lists = self._lists _keys = self._keys _maxes = self._maxes key = self._key(value) if _maxes: pos = bisect_right(_maxes, key) if pos == len(_maxes): pos -= 1 _lists[pos].append(value) _keys[pos].append(key) _maxes[pos] = key else: idx = bisect_right(_keys[pos], key) _lists[pos].insert(idx, value) _keys[pos].insert(idx, key) self._expand(pos) else: _lists.append([value]) _keys.append([key]) _maxes.append(key) self._len += 1 def _expand(self, pos): _lists = self._lists _keys = self._keys _index = self._index if len(_keys[pos]) > (self._load << 1): _maxes = self._maxes _load = self._load _lists_pos = _lists[pos] _keys_pos = _keys[pos] half = _lists_pos[_load:] half_keys = _keys_pos[_load:] del _lists_pos[_load:] del _keys_pos[_load:] _maxes[pos] = _keys_pos[-1] _lists.insert(pos + 1, half) _keys.insert(pos + 1, half_keys) _maxes.insert(pos + 1, half_keys[-1]) del _index[:] else: if _index: child = self._offset + pos while child: _index[child] += 1 child = (child - 1) >> 1 _index[0] += 1 def update(self, iterable): _lists = self._lists _keys = self._keys _maxes = self._maxes values = sorted(iterable, key=self._key) if _maxes: if len(values) * 4 >= self._len: _lists.append(values) values = reduce(iadd, _lists, []) values.sort(key=self._key) self._clear() else: _add = self.add for val in values: _add(val) return _load = self._load _lists.extend(values[pos:(pos + _load)] for pos in range(0, len(values), _load)) _keys.extend(list(map(self._key, _list)) for _list in _lists) _maxes.extend(sublist[-1] for sublist in _keys) self._len = len(values) del self._index[:] _update = update def __contains__(self, value): _maxes = self._maxes if not _maxes: return False key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): return False _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: return False if _lists[pos][idx] == value: return True idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: return False len_sublist = len(_keys[pos]) idx = 0 def discard(self, value): _maxes = self._maxes if not _maxes: return key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): return _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: return if _lists[pos][idx] == value: self._delete(pos, idx) return idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: return len_sublist = len(_keys[pos]) idx = 0 def remove(self, value): _maxes = self._maxes if not _maxes: raise ValueError('{0!r} not in list'.format(value)) key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): raise ValueError('{0!r} not in list'.format(value)) _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: raise ValueError('{0!r} not in list'.format(value)) if _lists[pos][idx] == value: self._delete(pos, idx) return idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: raise ValueError('{0!r} not in list'.format(value)) len_sublist = len(_keys[pos]) idx = 0 def _delete(self, pos, idx): _lists = self._lists _keys = self._keys _maxes = self._maxes _index = self._index keys_pos = _keys[pos] lists_pos = _lists[pos] del keys_pos[idx] del lists_pos[idx] self._len -= 1 len_keys_pos = len(keys_pos) if len_keys_pos > (self._load >> 1): _maxes[pos] = keys_pos[-1] if _index: child = self._offset + pos while child > 0: _index[child] -= 1 child = (child - 1) >> 1 _index[0] -= 1 elif len(_keys) > 1: if not pos: pos += 1 prev = pos - 1 _keys[prev].extend(_keys[pos]) _lists[prev].extend(_lists[pos]) _maxes[prev] = _keys[prev][-1] del _lists[pos] del _keys[pos] del _maxes[pos] del _index[:] self._expand(prev) elif len_keys_pos: _maxes[pos] = keys_pos[-1] else: del _lists[pos] del _keys[pos] del _maxes[pos] del _index[:] def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False): min_key = self._key(minimum) if minimum is not None else None max_key = self._key(maximum) if maximum is not None else None return self._irange_key( min_key=min_key, max_key=max_key, inclusive=inclusive, reverse=reverse, ) def irange_key(self, min_key=None, max_key=None, inclusive=(True, True), reverse=False): _maxes = self._maxes if not _maxes: return iter(()) _keys = self._keys if min_key is None: min_pos = 0 min_idx = 0 else: if inclusive[0]: min_pos = bisect_left(_maxes, min_key) if min_pos == len(_maxes): return iter(()) min_idx = bisect_left(_keys[min_pos], min_key) else: min_pos = bisect_right(_maxes, min_key) if min_pos == len(_maxes): return iter(()) min_idx = bisect_right(_keys[min_pos], min_key) if max_key is None: max_pos = len(_maxes) - 1 max_idx = len(_keys[max_pos]) else: if inclusive[1]: max_pos = bisect_right(_maxes, max_key) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_keys[max_pos]) else: max_idx = bisect_right(_keys[max_pos], max_key) else: max_pos = bisect_left(_maxes, max_key) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_keys[max_pos]) else: max_idx = bisect_left(_keys[max_pos], max_key) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse) _irange_key = irange_key def bisect_left(self, value): return self._bisect_key_left(self._key(value)) def bisect_right(self, value): return self._bisect_key_right(self._key(value)) bisect = bisect_right def bisect_key_left(self, key): _maxes = self._maxes if not _maxes: return 0 pos = bisect_left(_maxes, key) if pos == len(_maxes): return self._len idx = bisect_left(self._keys[pos], key) return self._loc(pos, idx) _bisect_key_left = bisect_key_left def bisect_key_right(self, key): _maxes = self._maxes if not _maxes: return 0 pos = bisect_right(_maxes, key) if pos == len(_maxes): return self._len idx = bisect_right(self._keys[pos], key) return self._loc(pos, idx) bisect_key = bisect_key_right _bisect_key_right = bisect_key_right def count(self, value): _maxes = self._maxes if not _maxes: return 0 key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): return 0 _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) total = 0 len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: return total if _lists[pos][idx] == value: total += 1 idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: return total len_sublist = len(_keys[pos]) idx = 0 def copy(self): return self.__class__(self, key=self._key) __copy__ = copy def index(self, value, start=None, stop=None): _len = self._len if not _len: raise ValueError('{0!r} is not in list'.format(value)) if start is None: start = 0 if start < 0: start += _len if start < 0: start = 0 if stop is None: stop = _len if stop < 0: stop += _len if stop > _len: stop = _len if stop <= start: raise ValueError('{0!r} is not in list'.format(value)) _maxes = self._maxes key = self._key(value) pos = bisect_left(_maxes, key) if pos == len(_maxes): raise ValueError('{0!r} is not in list'.format(value)) stop -= 1 _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: raise ValueError('{0!r} is not in list'.format(value)) if _lists[pos][idx] == value: loc = self._loc(pos, idx) if start <= loc <= stop: return loc elif loc > stop: break idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: raise ValueError('{0!r} is not in list'.format(value)) len_sublist = len(_keys[pos]) idx = 0 raise ValueError('{0!r} is not in list'.format(value)) def __add__(self, other): values = reduce(iadd, self._lists, []) values.extend(other) return self.__class__(values, key=self._key) __radd__ = __add__ def __mul__(self, num): values = reduce(iadd, self._lists, []) * num return self.__class__(values, key=self._key) def __reduce__(self): values = reduce(iadd, self._lists, []) return (type(self), (values, self.key)) @recursive_repr() def __repr__(self): type_name = type(self).__name__ return '{0}({1!r}, key={2!r})'.format(type_name, list(self), self._key) def _check(self): try: assert self._load >= 4 assert len(self._maxes) == len(self._lists) == len(self._keys) assert self._len == sum(len(sublist) for sublist in self._lists) for sublist in self._keys: for pos in range(1, len(sublist)): assert sublist[pos - 1] <= sublist[pos] for pos in range(1, len(self._keys)): assert self._keys[pos - 1][-1] <= self._keys[pos][0] for val_sublist, key_sublist in zip(self._lists, self._keys): assert len(val_sublist) == len(key_sublist) for val, key in zip(val_sublist, key_sublist): assert self._key(val) == key for pos in range(len(self._maxes)): assert self._maxes[pos] == self._keys[pos][-1] double = self._load << 1 assert all(len(sublist) <= double for sublist in self._lists) half = self._load >> 1 for pos in range(0, len(self._lists) - 1): assert len(self._lists[pos]) >= half if self._index: assert self._len == self._index[0] assert len(self._index) == self._offset + len(self._lists) for pos in range(len(self._lists)): leaf = self._index[self._offset + pos] assert leaf == len(self._lists[pos]) for pos in range(self._offset): child = (pos << 1) + 1 if child >= len(self._index): assert self._index[pos] == 0 elif child + 1 == len(self._index): assert self._index[pos] == self._index[child] else: child_sum = self._index[child] + self._index[child + 1] assert child_sum == self._index[pos] except: traceback.print_exc(file=sys.stdout) def comp(M,l,r): while len(r): pos=l.bisect_left(r[0]) if pos==len(l): break val=(l[pos]-r[0])/2 ans[m[l[pos]]]=val ans[m[r[0]]]=val l.pop(pos) r.pop(0) while len(l)>1: x1=l.pop(0) x2=l.pop(0) val=(x1+x2)/2 ans[m[x1]]=val ans[m[x2]]=val while len(r)>1: x1=r.pop() x2=r.pop() val=(M-x1+M-x2)/2 ans[m[x1]]=val ans[m[x2]]=val if len(l)==1 and len(r)==1: x1=l.pop() x2=r.pop() val=(M+M-x2+x1)/2 ans[m[x1]]=val ans[m[x2]]=val for _ in range(input()): n,M=[int(i) for i in raw_input().split()] a=[int(i) for i in raw_input().split()] s=[i for i in raw_input().split()] al=SortedList() bl=SortedList() ar=SortedList() br=SortedList() m={} ans=[-1 for i in range(n)] for i in range(n): m[a[i]]=i if a[i]%2==0: if s[i]=='L': al.add(a[i]) else: ar.add(a[i]) else: if s[i]=='L': bl.add(a[i]) else: br.add(a[i]) comp(M,al,ar) comp(M,bl,br) for i in ans: print(i,end=" ") print() ``` No
88,674
Provide tags and a correct Python 3 solution for this coding contest problem. Fibonacci strings are defined as follows: * f1 = Β«aΒ» * f2 = Β«bΒ» * fn = fn - 1 fn - 2, n > 2 Thus, the first five Fibonacci strings are: "a", "b", "ba", "bab", "babba". You are given a Fibonacci string and m strings si. For each string si, find the number of times it occurs in the given Fibonacci string as a substring. Input The first line contains two space-separated integers k and m β€” the number of a Fibonacci string and the number of queries, correspondingly. Next m lines contain strings si that correspond to the queries. It is guaranteed that strings si aren't empty and consist only of characters "a" and "b". The input limitations for getting 30 points are: * 1 ≀ k ≀ 3000 * 1 ≀ m ≀ 3000 * The total length of strings si doesn't exceed 3000 The input limitations for getting 100 points are: * 1 ≀ k ≀ 1018 * 1 ≀ m ≀ 104 * The total length of strings si doesn't exceed 105 Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier. Output For each string si print the number of times it occurs in the given Fibonacci string as a substring. Since the numbers can be large enough, print them modulo 1000000007 (109 + 7). Print the answers for the strings in the order in which they are given in the input. Examples Input 6 5 a b ab ba aba Output 3 5 3 3 1 Tags: matrices, strings Correct Solution: ``` F = ['', 'a', 'b', 'ba', 'bab', 'babba', 'babbabab', 'babbababbabba', 'babbababbabbababbabab', 'babbababbabbababbababbabbababbabba', 'babbababbabbababbababbabbababbabbababbababbabbababbabab', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabba', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabab', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabba', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabab'] while len(F[-3]) < 100000: F.append(F[-1] + F[-2]) d = 1000000007 def sqr(t): return [[sum(t[i][k] * t[k][j] for k in range(4)) % d for j in range(4)] for i in range(4)] def mul(a, b): return [[sum(a[i][k] * b[k][j] for k in range(4)) % d for j in range(4)] for i in range(4)] def fib(k): s, p = format(k, 'b')[:: -1], [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] t = [[[0, 1, 0, 0], [1, 1, 1, 0], [0, 0, 0, 1], [0, 0, 1, 0]]] + [0] * (len(s) - 1) for i in range(1, len(s)): t[i] = sqr(t[i - 1]) for i, k in enumerate(s): if k == '1': p = mul(p, t[i]) return p def cnt(t, p): s, i = 0, p.find(t) + 1 while i > 0: i = p.find(t, i) + 1 s += 1 return s def f(t, p, k): l = len(t) - 1 if l: x, y = cnt(t, F[k - 1][- l: ] + F[k][:l ]), cnt(t, F[k][- l: ] + F[k + 1][:l ]) else: x, y = 0, 0 a, b = cnt(t, F[k - 1]), cnt(t, F[k]) return (p[0] * a + p[1] * b + p[2] * y + p[3] * x) % d k, m = map(int, input().split()) if k > 15: x, y, z = len(F[7]), len(F[17]), len(F) - 4 a, b, c = fib(k - 7)[0], fib(k - 17)[0], fib(k - z)[0] for i in range(m): t = input() if len(t) < x: print(f(t, a, 8)) elif len(t) < y: print(f(t, b, 18)) else: print(f(t, c, z + 1)) else: p = F[k] for i in range(m): print(cnt(input(), p)) ```
88,675
Provide tags and a correct Python 3 solution for this coding contest problem. Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: * the final tournament features n teams (n is always even) * the first n / 2 teams (according to the standings) come through to the knockout stage * the standings are made on the following principle: for a victory a team gets 3 points, for a draw β€” 1 point, for a defeat β€” 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place β€” in decreasing order of the difference between scored and missed goals; in the third place β€” in the decreasing order of scored goals * it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage. Input The first input line contains the only integer n (1 ≀ n ≀ 50) β€” amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following nΒ·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 β€” names of the teams; num1, num2 (0 ≀ num1, num2 ≀ 100) β€” amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once. Output Output n / 2 lines β€” names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity. Examples Input 4 A B C D A-B 1:1 A-C 2:2 A-D 1:0 B-C 1:0 B-D 0:3 C-D 0:3 Output A D Input 2 a A a-A 2:1 Output a Tags: implementation Correct Solution: ``` n = int(input()) res = {input(): [0, 0, 0] for i in range(n)} for i in range(n * (n - 1) // 2): teams, score = input().split() team1, team2 = teams.split("-") sc1, sc2 = map(int, score.split(":")) if sc1 > sc2: res[team1][0] += 3 elif sc2 > sc1: res[team2][0] += 3 else: res[team1][0] += 1 res[team2][0] += 1 res[team1][1] += sc1 - sc2 res[team2][1] += sc2 - sc1 res[team1][2] += sc1 res[team2][2] += sc2 table = sorted(((res[key], key) for key in res), reverse=True) print("\n".join(sorted([row[1] for row in table[:n // 2]]))) ```
88,676
Provide tags and a correct Python 3 solution for this coding contest problem. Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: * the final tournament features n teams (n is always even) * the first n / 2 teams (according to the standings) come through to the knockout stage * the standings are made on the following principle: for a victory a team gets 3 points, for a draw β€” 1 point, for a defeat β€” 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place β€” in decreasing order of the difference between scored and missed goals; in the third place β€” in the decreasing order of scored goals * it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage. Input The first input line contains the only integer n (1 ≀ n ≀ 50) β€” amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following nΒ·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 β€” names of the teams; num1, num2 (0 ≀ num1, num2 ≀ 100) β€” amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once. Output Output n / 2 lines β€” names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity. Examples Input 4 A B C D A-B 1:1 A-C 2:2 A-D 1:0 B-C 1:0 B-D 0:3 C-D 0:3 Output A D Input 2 a A a-A 2:1 Output a Tags: implementation Correct Solution: ``` #this function will update information about team after each match def completeTeamInfo(team,scored,missed): team.scoredGoals += scored team.missedGoals += missed team.differenceScoredAndMissed += scored - missed #if the team scored more goals than missed, than it gains 3 points if scored > missed: team.points += 3 #if they scored the same amount of goals as they missed, team gains one point elif scored == missed: team.points += 1 #this function will sort the data according to required conditions def arrangeTeams(totals): totals.sort(key=lambda team: (team.points, team.differenceScoredAndMissed, team.scoredGoals ), reverse=True) def main(): #make a class to store all necessary data class Team: scoredGoals = 0 missedGoals = 0 differenceScoredAndMissed = 0 points = 0 def __init__(self, name): self.name = name #get teams number teamsNr = int(input()) totals = [] #get team's names for _ in range(teamsNr): name = input() totals.append(Team(name)) #for each match for _ in range(teamsNr*(teamsNr-1)//2): #get score and participant teams playingTeams,score = input().split() #because teams are given in A-C 2:2 form #we have to be more accurate in gathering data teamOne = playingTeams[:playingTeams.index('-')] teamTwo = playingTeams[playingTeams.index('-') + 1:] scoreTeamOne = int(score[:score.index(":")]) scoreTeamTwo = int(score[score.index(':') + 1:]) #for each match for team in totals: #look for team in totals and complete teams info if team.name == teamOne: completeTeamInfo(team,scoreTeamOne,scoreTeamTwo) if team.name == teamTwo: completeTeamInfo(team,scoreTeamTwo,scoreTeamOne) #arrange teams by the given conditions arrangeTeams(totals) winners = [] #we are interested only top half of the list for i in range(teamsNr//2): winners.append(totals[i].name) #but arranged in alphabetical order winners.sort() #print results for winner in winners: print(winner) main() ```
88,677
Provide tags and a correct Python 3 solution for this coding contest problem. Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: * the final tournament features n teams (n is always even) * the first n / 2 teams (according to the standings) come through to the knockout stage * the standings are made on the following principle: for a victory a team gets 3 points, for a draw β€” 1 point, for a defeat β€” 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place β€” in decreasing order of the difference between scored and missed goals; in the third place β€” in the decreasing order of scored goals * it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage. Input The first input line contains the only integer n (1 ≀ n ≀ 50) β€” amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following nΒ·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 β€” names of the teams; num1, num2 (0 ≀ num1, num2 ≀ 100) β€” amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once. Output Output n / 2 lines β€” names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity. Examples Input 4 A B C D A-B 1:1 A-C 2:2 A-D 1:0 B-C 1:0 B-D 0:3 C-D 0:3 Output A D Input 2 a A a-A 2:1 Output a Tags: implementation Correct Solution: ``` '''Problem 19A - World Football Cup''' score = {} # dict pentru a face totalurile pentru fiecare din jucatori n = int(input()) # citim nr de echipe for i in range(n): team = input() # key = numele la echipe score[team] = [0,0,0] # numele la echipa = [puncte pentru fiecare match, # diferenta intre golurile marcate si primite, # toate golurile marcate ] # citim rezultatele meciurilor for _ in range(n*(n-1)//2): data = input().split() teams = data[0].split('-') # teams = ['team_first', 'team_second'] first_team = teams[0] # first team sec_team = teams[1] # second team scores = data[1].split(':') first_tscore = int(scores[0]) # score for first_team sec_tscore = int(scores[1]) # score for sec_team # in caz ca a doua echipa a chastigat if first_tscore < sec_tscore: score[sec_team][0] += 3 # 'sec_team_name' = [3,0,0] score[sec_team][1] += sec_tscore - first_tscore # 'sec_team_name' = [3,diferenta intre goluri,0] score[sec_team][2] += sec_tscore # 'sec_team_name' = [3,diferenta intre goluri,goluri marcate in meci] # la fel si pentru echipa 1 actualizam scorurile in dictionarul score score[first_team][1] += first_tscore - sec_tscore score[first_team][2] += first_tscore # in caz ca echipa 1 a biruit if first_tscore > sec_tscore: score[first_team][0] += 3 score[first_team][1] += first_tscore - sec_tscore score[first_team][2] += first_tscore score[sec_team][1] += sec_tscore - first_tscore score[sec_team][2] += sec_tscore # in caz de egalitate elif first_tscore == sec_tscore: score[first_team][0] += 1 score[first_team][1] += first_tscore - sec_tscore score[first_team][2] += first_tscore score[sec_team][0] += 1 score[sec_team][1] += sec_tscore - first_tscore score[sec_team][2] += sec_tscore # print(score) res = [] # valorile din dictionar le salvam in lista res # team = key , # score = list of scores for each team for team, score in score.items(): res.append([score[0], score[1], score[2], team]) # : res = [[5, 1, 4, 'A'], [4, -2, 2, 'B'], [1, -4, 2, 'C'], [6, 5, 6, 'D']] res = sorted(res) # sortam lista , dupa condtitie res.reverse() # reversam lista , ca echipele cu cele mai mari scoruri sa fie primele nw = [] # lista pt echipele care sau calificat for i in range(n//2): nw.append(res[i][3]) # adougam in lisa numele acestor echipe nw = sorted(nw) print(*nw, sep='\n') # afisam numele la echipe din rand nou ```
88,678
Provide tags and a correct Python 3 solution for this coding contest problem. Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: * the final tournament features n teams (n is always even) * the first n / 2 teams (according to the standings) come through to the knockout stage * the standings are made on the following principle: for a victory a team gets 3 points, for a draw β€” 1 point, for a defeat β€” 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place β€” in decreasing order of the difference between scored and missed goals; in the third place β€” in the decreasing order of scored goals * it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage. Input The first input line contains the only integer n (1 ≀ n ≀ 50) β€” amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following nΒ·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 β€” names of the teams; num1, num2 (0 ≀ num1, num2 ≀ 100) β€” amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once. Output Output n / 2 lines β€” names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity. Examples Input 4 A B C D A-B 1:1 A-C 2:2 A-D 1:0 B-C 1:0 B-D 0:3 C-D 0:3 Output A D Input 2 a A a-A 2:1 Output a Tags: implementation Correct Solution: ``` class Info: def __init__(self, newTeamName, newPoints, newGoalDiff, newScoredGoals): self.teamName = newTeamName self.points = newPoints self.goalDiff = newGoalDiff self.scoredGoals = newScoredGoals def __str__(self): temp = '\n**************\n' temp += f'teamName: {self.teamName} \n' temp += f'points: {self.points} \n' temp += f'goalDiff: {self.goalDiff} \n' temp += f'scoredGoals: {self.scoredGoals} \n' temp += '**************\n' return temp # end of class def findIndexByName(cont: list, searchName: str) -> int: ln = len(cont) for i in range(ln): if searchName == cont[i].teamName: return i return -1 def output(cont: list): for item in cont: print(item) n, cont = int(input()), [] for i in range(n): # obj = Info(input(), 0, 0, 0) # cont.append(obj) cont.append(Info(input(), 0, 0, 0)) for i in range(n * (n - 1) // 2): line = input() dashInd = line.index('-') spaceInd = line.index(' ') colonInd = line.index(':') team1Name = line[:dashInd] team2Name = line[dashInd + 1:spaceInd] score1 = int(line[spaceInd + 1:colonInd]) score2 = int(line[colonInd + 1:]) team1Ind = findIndexByName(cont, team1Name) team2Ind = findIndexByName(cont, team2Name) # update points if score1 > score2: cont[team1Ind].points += 3 elif score1 < score2: cont[team2Ind].points += 3 else: cont[team1Ind].points += 1 cont[team2Ind].points += 1 # uptade goalDiff cont[team1Ind].goalDiff += score1 - score2 cont[team2Ind].goalDiff += score2 - score1 # update scoredGoals cont[team1Ind].scoredGoals += score1 cont[team2Ind].scoredGoals += score2 cont.sort(key=lambda it: (it.points, it.goalDiff, it.scoredGoals), reverse=True) del cont[n//2:] cont.sort(key=lambda it: it.teamName) #output(cont) for item in cont: print(item.teamName) ''' 0123456789.... line = 'barsa-real 15:10' ------------------------------- 4 A B C D A-B 1:1 A-C 2:2 A-D 1:0 B-C 1:0 B-D 0:3 C-D 0:3 points goalDiff scoredGoals A -> 1+1+3=5 A -> (1+2+1)-(1+2+0) = 4-3=1 A -> 4 B -> 1+3+0=4 B -> (1+1+0)-(1+0+3) = 2-4=-2 B -> 2 C -> 1+0+0=1 C -> (2+0+0)-(2+1+3) = 2-6=-4 C -> 2 D -> 0+3+3=6 D -> (0+3+3)-(1+0+0) = 6-1=5 D -> 6 A, B, C, D -> D, A, B, C -> D, A -> A, D 0 | teamName: 'A' | | points: 5 | | goalDiff: 1 | | scoredGoals: 4| ''' ```
88,679
Provide tags and a correct Python 3 solution for this coding contest problem. Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: * the final tournament features n teams (n is always even) * the first n / 2 teams (according to the standings) come through to the knockout stage * the standings are made on the following principle: for a victory a team gets 3 points, for a draw β€” 1 point, for a defeat β€” 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place β€” in decreasing order of the difference between scored and missed goals; in the third place β€” in the decreasing order of scored goals * it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage. Input The first input line contains the only integer n (1 ≀ n ≀ 50) β€” amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following nΒ·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 β€” names of the teams; num1, num2 (0 ≀ num1, num2 ≀ 100) β€” amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once. Output Output n / 2 lines β€” names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity. Examples Input 4 A B C D A-B 1:1 A-C 2:2 A-D 1:0 B-C 1:0 B-D 0:3 C-D 0:3 Output A D Input 2 a A a-A 2:1 Output a Tags: implementation Correct Solution: ``` #RAVENS #TEAM_2 #ESSI-DAYI_MOHSEN-LORENZO n = int(input()) team = dict() for i in range(n): team[input()] = [0,0,0] for i in range(n*(n-1)//2): a,b = input().split() t1,t2=a.split('-') g1,g2=map(int,b.split(':')) team[t1][2]+=g1 team[t2][2]+=g2 if g1 > g2:team[t1][0]+=3 elif g2 > g1:team[t2][0]+=3 else:team[t1][0]+=1;team[t2][0]+=1 team[t1][1]+=(g1-g2) team[t2][1]+=(g2-g1) te = [] for i in team.keys(): te.append([i,team[i][0],team[i][1],team[i][2]]) for j in range(n): for i in range(n-1-j): if te[i][1] > te[i+1][1]: te[i],te[i+1] = te[i+1],te[i] elif te[i][1] == te[i+1][1]: if te[i][2] > te[i+1][2]: te[i],te[i+1] = te[i+1],te[i] elif te[i][2] == te[i+1][2]: if te[i][3] > te[i+1][3]: te[i],te[i+1] = te[i+1],te[i] res = [] for i in range(n-1,n//2-1,-1): res.append(te[i][0]) res.sort() for i in range(n//2): print(res[i]) ```
88,680
Provide tags and a correct Python 3 solution for this coding contest problem. Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: * the final tournament features n teams (n is always even) * the first n / 2 teams (according to the standings) come through to the knockout stage * the standings are made on the following principle: for a victory a team gets 3 points, for a draw β€” 1 point, for a defeat β€” 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place β€” in decreasing order of the difference between scored and missed goals; in the third place β€” in the decreasing order of scored goals * it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage. Input The first input line contains the only integer n (1 ≀ n ≀ 50) β€” amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following nΒ·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 β€” names of the teams; num1, num2 (0 ≀ num1, num2 ≀ 100) β€” amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once. Output Output n / 2 lines β€” names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity. Examples Input 4 A B C D A-B 1:1 A-C 2:2 A-D 1:0 B-C 1:0 B-D 0:3 C-D 0:3 Output A D Input 2 a A a-A 2:1 Output a Tags: implementation Correct Solution: ``` import math n = int(input()) d= {} for i in range(n): d[input()] = [0,0,0] for i in range(math.factorial(n)//(2*math.factorial(n-2))): t,s = input().split() t1,t2 = t.split('-') s1,s2 = map(int,s.split(':')) if s1>s2 : d[t1][0] += 3 d[t1][1] += abs(s1-s2) d[t2][1] -= abs(s1-s2) elif s1==s2 : d[t1][0] += 1 d[t2][0] += 1 else: d[t2][0] += 3 d[t1][1] -= abs(s1-s2) d[t2][1] += abs(s1-s2) d[t1][2] += s1 d[t1][2] += s2 print(*sorted(sorted(d.keys(),key = lambda xx:\ (-d[xx][0],-d[xx][1],-d[xx][2]))[:n//2]),sep = '\n') ```
88,681
Provide tags and a correct Python 3 solution for this coding contest problem. Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: * the final tournament features n teams (n is always even) * the first n / 2 teams (according to the standings) come through to the knockout stage * the standings are made on the following principle: for a victory a team gets 3 points, for a draw β€” 1 point, for a defeat β€” 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place β€” in decreasing order of the difference between scored and missed goals; in the third place β€” in the decreasing order of scored goals * it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage. Input The first input line contains the only integer n (1 ≀ n ≀ 50) β€” amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following nΒ·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 β€” names of the teams; num1, num2 (0 ≀ num1, num2 ≀ 100) β€” amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once. Output Output n / 2 lines β€” names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity. Examples Input 4 A B C D A-B 1:1 A-C 2:2 A-D 1:0 B-C 1:0 B-D 0:3 C-D 0:3 Output A D Input 2 a A a-A 2:1 Output a Tags: implementation Correct Solution: ``` n = int(input()) # Score [points, diff, goals] score = {} for i in range(n): score[input()] = [0, 0, 0] for i in range(int(n*(n-1)/2)): s = input().split() p1 = s[0].split('-')[0] p2 = s[0].split('-')[1] s1 = int(s[1].split(':')[0]) s2 = int(s[1].split(':')[1]) score[p1][1] += s1 - s2 score[p1][2] += s1 score[p2][1] += s2 - s1 score[p2][2] += s2 if s1 > s2: score[p1][0] += 3 elif s1 == s2: score[p1][0] += 1 score[p2][0] += 1 else: score[p2][0] += 3 score = sorted(score.items(), key=lambda x: x[1][0], reverse = True) for i in range(n): for j in range(n - i - 1): if score[j][1][0] == score[j+1][1][0]: if score[j][1][1] < score[j+1][1][1]: score[j], score[j+1] = score[j+1], score[j] for i in range(n): for j in range(n - i - 1): if score[j][1][1] == score[j+1][1][1]: if score[j][1][2] < score[j+1][1][2]: score[j], score[j+1] = score[j+1], score[j] for i in sorted(score[:int(n/2)], key = lambda x : x[0]): print(i[0]) ```
88,682
Provide tags and a correct Python 3 solution for this coding contest problem. Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: * the final tournament features n teams (n is always even) * the first n / 2 teams (according to the standings) come through to the knockout stage * the standings are made on the following principle: for a victory a team gets 3 points, for a draw β€” 1 point, for a defeat β€” 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place β€” in decreasing order of the difference between scored and missed goals; in the third place β€” in the decreasing order of scored goals * it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage. Input The first input line contains the only integer n (1 ≀ n ≀ 50) β€” amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following nΒ·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 β€” names of the teams; num1, num2 (0 ≀ num1, num2 ≀ 100) β€” amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once. Output Output n / 2 lines β€” names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity. Examples Input 4 A B C D A-B 1:1 A-C 2:2 A-D 1:0 B-C 1:0 B-D 0:3 C-D 0:3 Output A D Input 2 a A a-A 2:1 Output a Tags: implementation Correct Solution: ``` n = int(input()) class Command: def __init__(self, name): self.name = name self.score = 0 self.z = 0 self.p = 0 def get_r(self): return self.z - self.p arr = {} for i in range(n): name = input() arr[name] = Command(name) for i in range((n * (n - 1)) // 2): string = input() first, second = string.split() name1, name2 = first.split('-') num1, num2 = second.split(":") num1, num2 = int(num1), int(num2) if num1 > num2: arr[name1].score += 3 elif num1 < num2: arr[name2].score += 3 else: arr[name1].score += 1 arr[name2].score += 1 arr[name1].z += num1 arr[name1].p += num2 arr[name2].z += num2 arr[name2].p += num1 arr = list(arr.values()) for i in range(len(arr)): for j in range(len(arr) - 1): if arr[j].score < arr[j + 1].score: arr[j], arr[j + 1] = arr[j + 1], arr[j] elif arr[j].score == arr[j + 1].score: if arr[j].get_r() < arr[j + 1].get_r(): arr[j], arr[j + 1] = arr[j + 1], arr[j] elif arr[j].get_r() == arr[j + 1].get_r(): if arr[j].z < arr[j + 1].z: arr[j], arr[j + 1] = arr[j + 1], arr[j] ans = [] for i in range(len(arr) // 2): ans.append(arr[i].name) ans.sort() for i in ans: print(i) ```
88,683
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: * the final tournament features n teams (n is always even) * the first n / 2 teams (according to the standings) come through to the knockout stage * the standings are made on the following principle: for a victory a team gets 3 points, for a draw β€” 1 point, for a defeat β€” 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place β€” in decreasing order of the difference between scored and missed goals; in the third place β€” in the decreasing order of scored goals * it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage. Input The first input line contains the only integer n (1 ≀ n ≀ 50) β€” amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following nΒ·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 β€” names of the teams; num1, num2 (0 ≀ num1, num2 ≀ 100) β€” amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once. Output Output n / 2 lines β€” names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity. Examples Input 4 A B C D A-B 1:1 A-C 2:2 A-D 1:0 B-C 1:0 B-D 0:3 C-D 0:3 Output A D Input 2 a A a-A 2:1 Output a Submitted Solution: ``` team_rankings = {} n = int(input()) for i in range(n): team = input() #particpating teams team_rankings[team] = [0,0,0] #[points, goal count difference, goals] for _ in range(n*(n-1)//2): #gathering data from each game data = input().split() teams = data[0].split('-') #finding the teams and their match-ups team_1 = teams[0] #team 1 team_2 = teams[1] #team 2 scores = data[1].split(':') score_t1 = int(scores[0]) #score of team 1 score_t2 = int(scores[1]) #score of team 2 #case: team 2 has won the match if score_t1 < score_t2: team_rankings[team_2][0] += 3 #gains 3 points team_rankings[team_2][1] += score_t2 - score_t1 #goal count difference team_rankings[team_2][2] += score_t2 #goals #updating for team 1 as well team_rankings[team_1][1] += score_t1 - score_t2 team_rankings[team_1][2] += score_t1 #case: team 1 has won the macth if score_t1 > score_t2: team_rankings[team_1][0] += 3 #gains 3 points team_rankings[team_1][1] += score_t1 - score_t2 #goal count difference team_rankings[team_1][2] += score_t1 #goals #updating for team 1 as well team_rankings[team_2][1] += score_t2 - score_t1 team_rankings[team_2][2] += score_t2 #case: stalemate or a tie elif score_t1 == score_t2: team_rankings[team_1][0] += 1 team_rankings[team_1][1] += score_t1 - score_t2 team_rankings[team_1][2] += score_t1 team_rankings[team_2][0] += 1 team_rankings[team_2][1] += score_t2 - score_t1 team_rankings[team_2][2] += score_t2 results = [] for team, team_rankings in team_rankings.items(): results.append([team_rankings[0], team_rankings[1], team_rankings[2], team]) results = sorted(results) #sorting the list results.reverse() #reverse the order so we get the hoghest scoring team first qualified = [] #list of qualified teams for i in range(n//2): qualified.append(results[i][3]) #adding the name of the qualified teams qualified = sorted(qualified) print(*qualified, sep='\n') ``` Yes
88,684
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: * the final tournament features n teams (n is always even) * the first n / 2 teams (according to the standings) come through to the knockout stage * the standings are made on the following principle: for a victory a team gets 3 points, for a draw β€” 1 point, for a defeat β€” 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place β€” in decreasing order of the difference between scored and missed goals; in the third place β€” in the decreasing order of scored goals * it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage. Input The first input line contains the only integer n (1 ≀ n ≀ 50) β€” amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following nΒ·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 β€” names of the teams; num1, num2 (0 ≀ num1, num2 ≀ 100) β€” amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once. Output Output n / 2 lines β€” names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity. Examples Input 4 A B C D A-B 1:1 A-C 2:2 A-D 1:0 B-C 1:0 B-D 0:3 C-D 0:3 Output A D Input 2 a A a-A 2:1 Output a Submitted Solution: ``` # -*- coding: utf-8 -*- dic,lista,final = {},[],[] n = int(input()) for i in range(n): dic[input()] = {'points': 0,'scored': 0,'missed': 0} matches = [input().split() for j in range(int(n*(n-1)/2))] for j in range(len(matches)): goals1,goals2 = int(matches[j][1].split(':')[0]),int(matches[j][1].split(':')[1]) team1,team2 = matches[j][0].split('-')[0], matches[j][0].split('-')[1] dic[team1]['scored'] += goals1; dic[team1]['missed'] += goals2 dic[team2]['scored'] += goals2; dic[team2]['missed'] += goals1 if goals1 > goals2: dic[team1]['points'] += 3 elif goals1 < goals2: dic[team2]['points'] += 3 else: dic[team1]['points'] += 1; dic[team2]['points'] += 1 for i in dic: lista.append([dic[i]['points'],dic[i]['scored']-dic[i]['missed'],dic[i]['scored'],i]) lista = sorted(lista)[::-1] for i in range(int(n/2)): final.append(lista[i][3]) final = sorted(final) for i in final: print(i) ``` Yes
88,685
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: * the final tournament features n teams (n is always even) * the first n / 2 teams (according to the standings) come through to the knockout stage * the standings are made on the following principle: for a victory a team gets 3 points, for a draw β€” 1 point, for a defeat β€” 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place β€” in decreasing order of the difference between scored and missed goals; in the third place β€” in the decreasing order of scored goals * it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage. Input The first input line contains the only integer n (1 ≀ n ≀ 50) β€” amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following nΒ·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 β€” names of the teams; num1, num2 (0 ≀ num1, num2 ≀ 100) β€” amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once. Output Output n / 2 lines β€” names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity. Examples Input 4 A B C D A-B 1:1 A-C 2:2 A-D 1:0 B-C 1:0 B-D 0:3 C-D 0:3 Output A D Input 2 a A a-A 2:1 Output a Submitted Solution: ``` clasificados = [] equipos = [] puntos = [] dg = [] gf = [] n = int(input()) for i in range(n): equipos.append(input()) puntos.append(0) dg.append(0) gf.append(0) n_partidos = (n * (n-1)) // 2 for i in range(n_partidos): partido = input() equipos_partido, resultado = partido.split() e1, e2 = equipos_partido.split('-') goles = resultado.split(':') g1, g2 = int(goles[0]) , int(goles[1]) if g1 > g2: p1 = 3 p2 = 0 elif g1 == g2: p1 = 1 p2 = 1 else: p1 = 0 p2 = 3 a = equipos.index(e1) b = equipos.index(e2) puntos[a] = puntos[a] + p1 dg[a] = dg[a] + g1 - g2 gf[a] = gf[a] + g1 puntos[b] = puntos[b] + p2 dg[b] = dg[b] + g2 - g1 gf[b] = gf[b] + g2 x = 0 for i in range(n//2): mayor = 0 for j in range(n): if mayor != j: if puntos[mayor] < puntos[j]: mayor = j elif puntos[mayor] == puntos[j]: if dg[mayor] < dg[j]: mayor = j elif dg[mayor] == dg[j]: if gf[mayor] < gf[j]: mayor = j clasificados.append(equipos[mayor]) puntos[mayor] = -1 clasificados.sort() for i in range(n//2): print(clasificados[i]) ``` Yes
88,686
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: * the final tournament features n teams (n is always even) * the first n / 2 teams (according to the standings) come through to the knockout stage * the standings are made on the following principle: for a victory a team gets 3 points, for a draw β€” 1 point, for a defeat β€” 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place β€” in decreasing order of the difference between scored and missed goals; in the third place β€” in the decreasing order of scored goals * it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage. Input The first input line contains the only integer n (1 ≀ n ≀ 50) β€” amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following nΒ·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 β€” names of the teams; num1, num2 (0 ≀ num1, num2 ≀ 100) β€” amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once. Output Output n / 2 lines β€” names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity. Examples Input 4 A B C D A-B 1:1 A-C 2:2 A-D 1:0 B-C 1:0 B-D 0:3 C-D 0:3 Output A D Input 2 a A a-A 2:1 Output a Submitted Solution: ``` score = {} n = int(input()) for i in range(n): team = input() score[team] = [0,0,0] for i in range(n*(n-1)//2): s = input().split() teams = s[0].split('-') # get team names first = teams[0] second = teams[1] # get scores scores = s[1].split(':') first_score = int(scores[0]) second_score = int(scores[1]) # when team winned if first_score < second_score: score[second][0] += 3 score[second][1] = score[second][1] + second_score - first_score score[second][2] += second_score score[first][1] = score[first][1] + first_score - second_score score[first][2] += first_score if first_score > second_score: score[first][0] += 3 score[first][1] += first_score - second_score score[first][2] += first_score score[second][1] += second_score - first_score score[second][2] += second_score # when draw elif first_score == second_score: score[first][0] += 1 score[first][1] += first_score - second_score score[first][2] += first_score score[second][0] += 1 score[second][1] += second_score - first_score score[second][2] += second_score results = [] # list of teams with 3 criteria scores for team, score in score.items(): results.append([score[0], score[1], score[2], team]) # sort results in ascending order results = sorted(results) results.reverse() nw = [] for i in range(n//2): nw.append(results[i][3]) nw = sorted(nw) print(*nw, sep='\n') ``` Yes
88,687
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: * the final tournament features n teams (n is always even) * the first n / 2 teams (according to the standings) come through to the knockout stage * the standings are made on the following principle: for a victory a team gets 3 points, for a draw β€” 1 point, for a defeat β€” 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place β€” in decreasing order of the difference between scored and missed goals; in the third place β€” in the decreasing order of scored goals * it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage. Input The first input line contains the only integer n (1 ≀ n ≀ 50) β€” amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following nΒ·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 β€” names of the teams; num1, num2 (0 ≀ num1, num2 ≀ 100) β€” amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once. Output Output n / 2 lines β€” names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity. Examples Input 4 A B C D A-B 1:1 A-C 2:2 A-D 1:0 B-C 1:0 B-D 0:3 C-D 0:3 Output A D Input 2 a A a-A 2:1 Output a Submitted Solution: ``` n = int(input()) teamScores = dict() for _ in range(n): name = input() teamScores[name] = 0 matchCount = (n)*(n-1)//2 for _ in range(matchCount): match = input().split(" ") team = match[0].split("-") score = list(map(int,match[1].split(":"))) if score[0] == score[1]: teamScores[team[0]] += 1 teamScores[team[1]] += 1 elif score[0] > score[1] : teamScores[team[0]] += 3 else: teamScores[team[1]] += 3 teams = list(teamScores.keys()) for i in range(n): for j in range(n-i-1): if teamScores[teams[j]] < teamScores[teams[j+1]] : teams[j+1],teams[j] = teams[j],teams[j+1] elif teamScores[teams[j]] == teamScores[teams[j+1]] : if teams[j+1] < teams[j] : teams[j+1],teams[j] = teams[j],teams[j+1] print(teams) teams = sorted(teams) for i in range(n//2): print(teams[i]) ``` No
88,688
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: * the final tournament features n teams (n is always even) * the first n / 2 teams (according to the standings) come through to the knockout stage * the standings are made on the following principle: for a victory a team gets 3 points, for a draw β€” 1 point, for a defeat β€” 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place β€” in decreasing order of the difference between scored and missed goals; in the third place β€” in the decreasing order of scored goals * it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage. Input The first input line contains the only integer n (1 ≀ n ≀ 50) β€” amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following nΒ·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 β€” names of the teams; num1, num2 (0 ≀ num1, num2 ≀ 100) β€” amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once. Output Output n / 2 lines β€” names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity. Examples Input 4 A B C D A-B 1:1 A-C 2:2 A-D 1:0 B-C 1:0 B-D 0:3 C-D 0:3 Output A D Input 2 a A a-A 2:1 Output a Submitted Solution: ``` n=int(input()) a1=[] a2=[] a3=[] a4=[] a5=[0]*n a6=[] goles=0 puntos=0 mayor=0 for k in range (n): x=input() a1.append(x) for l in range ((n-1)*(n)//2): b=input() a2.append(b) for a in range (n): for b in range (len(a2)): for c in range (3): if a1[a]==a2[b][c]: if c==0: goles=goles+int(a2[b][4]) if c==2: goles=goles+int(a2[b][6]) a3.append(goles) goles=0 for d in range (n): for e in range (len(a2)): for f in range (3): if a1[d]==a2[e][f]: if f==0: if int(a2[e][4])>int(a2[e][6]): puntos=puntos+3 if int(a2[e][4])==int(a2[e][6]): puntos=puntos+1 if f==2: if int(a2[e][6])>int(a2[e][4]): puntos=puntos+3 if int(a2[e][6])==int(a2[e][4]): puntos=puntos+1 a4.append(puntos) puntos=0 for g in range (n): for h in range (n): if int(a3[g])>int(a3[h]): mayor=mayor+1 if int(a3[g])==int(a3[h]): if int(a4[g])>int(a4[h]): mayor=mayor+1 po=n-mayor-1 mayor=0 a5[po]=a1[g] for la in range (n//2): a6.append(a5[la]) a6.sort() for yonax in range (len(a6)): print(a6[yonax]) ``` No
88,689
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: * the final tournament features n teams (n is always even) * the first n / 2 teams (according to the standings) come through to the knockout stage * the standings are made on the following principle: for a victory a team gets 3 points, for a draw β€” 1 point, for a defeat β€” 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place β€” in decreasing order of the difference between scored and missed goals; in the third place β€” in the decreasing order of scored goals * it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage. Input The first input line contains the only integer n (1 ≀ n ≀ 50) β€” amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following nΒ·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 β€” names of the teams; num1, num2 (0 ≀ num1, num2 ≀ 100) β€” amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once. Output Output n / 2 lines β€” names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity. Examples Input 4 A B C D A-B 1:1 A-C 2:2 A-D 1:0 B-C 1:0 B-D 0:3 C-D 0:3 Output A D Input 2 a A a-A 2:1 Output a Submitted Solution: ``` clasificados = [] equipos = [] puntos = [] dg = [] gf = [] n = int(input()) for i in range(n): equipos.append(input()) puntos.append(0) dg.append(0) gf.append(0) n_partidos = (n * (n-1)) // 2 for i in range(n_partidos): partido = input() equipos_partido, resultado = partido.split() e1, e2 = equipos_partido.split('-') goles = resultado.split(':') g1, g2 = int(goles[0]) , int(goles[1]) if g1 > g2: p1 = 3 p2 = 0 elif g1 == g2: p1 = 1 p2 = 1 else: p1 = 0 p2 = 3 a = equipos.index(e1) b = equipos.index(e2) puntos[a] = puntos[a] + p1 dg[a] = dg[a] + g1 - g2 gf[a] = gf[a] + g1 puntos[b] = puntos[b] + p2 dg[b] = dg[b] + g2 - g1 gf[b] = gf[b] + g2 x = 0 for i in range(n//2): mayor = 0 for j in range(n): if mayor != j: if puntos[mayor] < puntos[j]: mayor = j elif puntos[mayor] == puntos[j]: if dg[mayor] < dg[j]: mayor = j elif dg[mayor] == dg[j]: if gf[mayor] < gf[mayor]: mayor = j clasificados.append(equipos[mayor]) puntos[mayor] = -1 clasificados.sort() for i in range(n//2): print(clasificados[i]) ``` No
88,690
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: * the final tournament features n teams (n is always even) * the first n / 2 teams (according to the standings) come through to the knockout stage * the standings are made on the following principle: for a victory a team gets 3 points, for a draw β€” 1 point, for a defeat β€” 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place β€” in decreasing order of the difference between scored and missed goals; in the third place β€” in the decreasing order of scored goals * it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage. Input The first input line contains the only integer n (1 ≀ n ≀ 50) β€” amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following nΒ·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 β€” names of the teams; num1, num2 (0 ≀ num1, num2 ≀ 100) β€” amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once. Output Output n / 2 lines β€” names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity. Examples Input 4 A B C D A-B 1:1 A-C 2:2 A-D 1:0 B-C 1:0 B-D 0:3 C-D 0:3 Output A D Input 2 a A a-A 2:1 Output a Submitted Solution: ``` n = int(input()) d = dict() for i in range(n): d[input()] = [0, 0, 0] for i in range(n * (n - 1) // 2): t, s = input().split() t1, t2 = t.split('-') s1, s2 = [int(x) for x in s.split(':')] a = d[t1] b = d[t2] a[2] += s1 b[2] += s2 a[1] += s1 - s2 b[1] += s2 - s1 if s1 == s2: a[0] += 1 b[0] += 1 elif s1 < s2: b[0] += 3 else: a[0] += 3 print('\n'.join(b for a, b in sorted((b, a) for a, b in d.items())[n // 2: ])) ``` No
88,691
Provide tags and a correct Python 3 solution for this coding contest problem. A subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is a string x = sk1sk2... sk|x| (1 ≀ k1 < k2 < ... < k|x| ≀ |s|). You've got two strings β€” s and t. Let's consider all subsequences of string s, coinciding with string t. Is it true that each character of string s occurs in at least one of these subsequences? In other words, is it true that for all i (1 ≀ i ≀ |s|), there is such subsequence x = sk1sk2... sk|x| of string s, that x = t and for some j (1 ≀ j ≀ |x|) kj = i. Input The first line contains string s, the second line contains string t. Each line consists only of lowercase English letters. The given strings are non-empty, the length of each string does not exceed 2Β·105. Output Print "Yes" (without the quotes), if each character of the string s occurs in at least one of the described subsequences, or "No" (without the quotes) otherwise. Examples Input abab ab Output Yes Input abacaba aba Output No Input abc ba Output No Note In the first sample string t can occur in the string s as a subsequence in three ways: abab, abab and abab. In these occurrences each character of string s occurs at least once. In the second sample the 4-th character of the string s doesn't occur in any occurrence of string t. In the third sample there is no occurrence of string t in string s. Tags: data structures, dp, strings Correct Solution: ``` import bisect import string s = input() t = input() max_match = [0 for i in range(len(s))] min_match = [0 for i in range(len(s))] char_idx = [0 for i in range(30)] char_occur = [ [] for i in range(30) ] for (i, ch) in enumerate(t): idx = ord(ch) - ord('a') char_occur[idx].append(i) for ch in string.ascii_lowercase: idx = ord(ch) - ord('a') char_occur[idx].append(len(t)+1) matched = -1 for (i, ch) in enumerate(s): if matched==len(t)-1: max_match[i] = matched else: if ch == t[matched+1]: matched += 1 max_match[i] = matched matched = len(t) for (i, ch) in enumerate(s[::-1]): i = len(s) - i - 1 if matched==0: min_match[i] = matched else: if ch == t[matched-1]: matched -= 1 min_match[i] = matched for (i, ch) in enumerate(s): low = min_match[i] high = max_match[i] ch = ord(ch) - ord('a') idx = char_idx[ch] while idx<len(char_occur[ch]) and char_occur[ch][idx]<low: idx += 1 char_idx[ch] = idx if idx == len(char_occur[ch]): print("No") exit() if char_occur[ch][idx] > high: print("No") exit() print("Yes") ```
88,692
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is a string x = sk1sk2... sk|x| (1 ≀ k1 < k2 < ... < k|x| ≀ |s|). You've got two strings β€” s and t. Let's consider all subsequences of string s, coinciding with string t. Is it true that each character of string s occurs in at least one of these subsequences? In other words, is it true that for all i (1 ≀ i ≀ |s|), there is such subsequence x = sk1sk2... sk|x| of string s, that x = t and for some j (1 ≀ j ≀ |x|) kj = i. Input The first line contains string s, the second line contains string t. Each line consists only of lowercase English letters. The given strings are non-empty, the length of each string does not exceed 2Β·105. Output Print "Yes" (without the quotes), if each character of the string s occurs in at least one of the described subsequences, or "No" (without the quotes) otherwise. Examples Input abab ab Output Yes Input abacaba aba Output No Input abc ba Output No Note In the first sample string t can occur in the string s as a subsequence in three ways: abab, abab and abab. In these occurrences each character of string s occurs at least once. In the second sample the 4-th character of the string s doesn't occur in any occurrence of string t. In the third sample there is no occurrence of string t in string s. Submitted Solution: ``` import bisect import string s = input() t = input() max_match = [0 for i in range(len(s))] min_match = [0 for i in range(len(s))] char_idx = [0 for i in range(30)] char_occur = [ [] for i in range(30) ] for ch in string.ascii_lowercase: idx = ord(ch) - ord('a') char_occur[idx] = [i for (i,_ch) in enumerate(t) if ch==_ch] char_occur[idx].append(len(t)+1) matched = -1 for (i, ch) in enumerate(s): if matched==len(t)-1: max_match[i] = matched else: if ch == t[matched+1]: matched += 1 max_match[i] = matched matched = len(t) for (i, ch) in enumerate(s[::-1]): i = len(s) - i - 1 if matched==0: min_match[i] = matched else: if ch == t[matched-1]: matched -= 1 min_match[i] = matched if len(t) > 100000: for (i, ch) in enumerate(s): low = min_match[i] high = max_match[i] ch = ord(ch) - ord('a') idx = char_idx[ch] while idx<len(char_occur[ch]) and char_occur[ch][idx]<low: idx += 1 char_idx[ch] = idx if idx == len(char_occur[ch]): print("No") exit() if char_occur[ch][idx] > high: print("No") exit() print("Yes") ``` No
88,693
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is a string x = sk1sk2... sk|x| (1 ≀ k1 < k2 < ... < k|x| ≀ |s|). You've got two strings β€” s and t. Let's consider all subsequences of string s, coinciding with string t. Is it true that each character of string s occurs in at least one of these subsequences? In other words, is it true that for all i (1 ≀ i ≀ |s|), there is such subsequence x = sk1sk2... sk|x| of string s, that x = t and for some j (1 ≀ j ≀ |x|) kj = i. Input The first line contains string s, the second line contains string t. Each line consists only of lowercase English letters. The given strings are non-empty, the length of each string does not exceed 2Β·105. Output Print "Yes" (without the quotes), if each character of the string s occurs in at least one of the described subsequences, or "No" (without the quotes) otherwise. Examples Input abab ab Output Yes Input abacaba aba Output No Input abc ba Output No Note In the first sample string t can occur in the string s as a subsequence in three ways: abab, abab and abab. In these occurrences each character of string s occurs at least once. In the second sample the 4-th character of the string s doesn't occur in any occurrence of string t. In the third sample there is no occurrence of string t in string s. Submitted Solution: ``` import bisect import string s = input() t = input() max_match = [0 for i in range(len(s))] min_match = [0 for i in range(len(s))] char_idx = [0 for i in range(30)] char_occur = [ [] for i in range(30) ] matched = -1 for (i, ch) in enumerate(s): if matched==len(t)-1: max_match[i] = matched else: if ch == t[matched+1]: matched += 1 max_match[i] = matched idx = ord(ch) - ord('a') char_occur[idx].append(i) for ch in string.ascii_lowercase: idx = ord(ch) - ord('a') char_occur[idx].append(len(t)+1) matched = len(t) for (i, ch) in enumerate(s[::-1]): i = len(s) - i - 1 if matched==0: min_match[i] = matched else: if ch == t[matched-1]: matched -= 1 min_match[i] = matched for (i, ch) in enumerate(s): low = min_match[i] high = max_match[i] ch = ord(ch) - ord('a') idx = char_idx[ch] while idx<len(char_occur[ch]) and char_occur[ch][idx]<low: idx += 1 char_idx[ch] = idx if idx == len(char_occur[ch]): print("No") exit() if char_occur[ch][idx] > high: print("No") exit() print("Yes") ``` No
88,694
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is a string x = sk1sk2... sk|x| (1 ≀ k1 < k2 < ... < k|x| ≀ |s|). You've got two strings β€” s and t. Let's consider all subsequences of string s, coinciding with string t. Is it true that each character of string s occurs in at least one of these subsequences? In other words, is it true that for all i (1 ≀ i ≀ |s|), there is such subsequence x = sk1sk2... sk|x| of string s, that x = t and for some j (1 ≀ j ≀ |x|) kj = i. Input The first line contains string s, the second line contains string t. Each line consists only of lowercase English letters. The given strings are non-empty, the length of each string does not exceed 2Β·105. Output Print "Yes" (without the quotes), if each character of the string s occurs in at least one of the described subsequences, or "No" (without the quotes) otherwise. Examples Input abab ab Output Yes Input abacaba aba Output No Input abc ba Output No Note In the first sample string t can occur in the string s as a subsequence in three ways: abab, abab and abab. In these occurrences each character of string s occurs at least once. In the second sample the 4-th character of the string s doesn't occur in any occurrence of string t. In the third sample there is no occurrence of string t in string s. Submitted Solution: ``` import bisect import string s = input() t = input() max_match = [0 for i in range(len(s))] min_match = [0 for i in range(len(s))] char_idx = [0 for i in range(30)] char_occur = [ [] for i in range(30) ] for ch in string.ascii_lowercase: idx = ord(ch) - ord('a') char_occur[idx] = [i for (i,_ch) in enumerate(t) if ch==_ch] char_occur[idx].append(len(t)+1) matched = -1 for (i, ch) in enumerate(s): if matched==len(t)-1: max_match[i] = matched else: if ch == t[matched+1]: matched += 1 max_match[i] = matched matched = len(t) for (i, ch) in enumerate(s[::-1]): i = len(s) - i - 1 if matched==0: min_match[i] = matched else: if ch == t[matched-1]: matched -= 1 min_match[i] = matched if len(t) < 100000: for (i, ch) in enumerate(s): low = min_match[i] high = max_match[i] ch = ord(ch) - ord('a') idx = char_idx[ch] while idx<len(char_occur[ch]) and char_occur[ch][idx]<low: idx += 1 char_idx[ch] = idx if idx == len(char_occur[ch]): print("No") exit() if char_occur[ch][idx] > high: print("No") exit() print("Yes") ``` No
88,695
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is a string x = sk1sk2... sk|x| (1 ≀ k1 < k2 < ... < k|x| ≀ |s|). You've got two strings β€” s and t. Let's consider all subsequences of string s, coinciding with string t. Is it true that each character of string s occurs in at least one of these subsequences? In other words, is it true that for all i (1 ≀ i ≀ |s|), there is such subsequence x = sk1sk2... sk|x| of string s, that x = t and for some j (1 ≀ j ≀ |x|) kj = i. Input The first line contains string s, the second line contains string t. Each line consists only of lowercase English letters. The given strings are non-empty, the length of each string does not exceed 2Β·105. Output Print "Yes" (without the quotes), if each character of the string s occurs in at least one of the described subsequences, or "No" (without the quotes) otherwise. Examples Input abab ab Output Yes Input abacaba aba Output No Input abc ba Output No Note In the first sample string t can occur in the string s as a subsequence in three ways: abab, abab and abab. In these occurrences each character of string s occurs at least once. In the second sample the 4-th character of the string s doesn't occur in any occurrence of string t. In the third sample there is no occurrence of string t in string s. Submitted Solution: ``` import bisect import string s = input() t = input() max_match = [0 for i in range(len(s))] min_match = [0 for i in range(len(s))] char_idx = [0 for i in range(30)] char_occur = [ [] for i in range(30) ] matched = -1 for (i, ch) in enumerate(s): if matched==len(t)-1: max_match[i] = matched else: if ch == t[matched+1]: matched += 1 max_match[i] = matched idx = ord(ch) - ord('a') char_occur[idx].append(i) for ch in string.ascii_lowercase: char_occur[idx].append(len(t)+1) matched = len(t) for (i, ch) in enumerate(s[::-1]): i = len(s) - i - 1 if matched==0: min_match[i] = matched else: if ch == t[matched-1]: matched -= 1 min_match[i] = matched for (i, ch) in enumerate(s): low = min_match[i] high = max_match[i] ch = ord(ch) - ord('a') idx = char_idx[ch] while idx<len(char_occur[ch]) and char_occur[ch][idx]<low: idx += 1 char_idx[ch] = idx if idx == len(char_occur[ch]): print("No") exit() if char_occur[ch][idx] > high: print("No") exit() print("Yes") ``` No
88,696
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarpus got hold of a family tree. The found tree describes the family relations of n people, numbered from 1 to n. Every person in this tree has at most one direct ancestor. Also, each person in the tree has a name, the names are not necessarily unique. We call the man with a number a a 1-ancestor of the man with a number b, if the man with a number a is a direct ancestor of the man with a number b. We call the man with a number a a k-ancestor (k > 1) of the man with a number b, if the man with a number b has a 1-ancestor, and the man with a number a is a (k - 1)-ancestor of the 1-ancestor of the man with a number b. In the tree the family ties do not form cycles. In other words there isn't a person who is his own direct or indirect ancestor (that is, who is an x-ancestor of himself, for some x, x > 0). We call a man with a number a the k-son of the man with a number b, if the man with a number b is a k-ancestor of the man with a number a. Polycarpus is very much interested in how many sons and which sons each person has. He took a piece of paper and wrote m pairs of numbers vi, ki. Help him to learn for each pair vi, ki the number of distinct names among all names of the ki-sons of the man with number vi. Input The first line of the input contains a single integer n (1 ≀ n ≀ 105) β€” the number of people in the tree. Next n lines contain the description of people in the tree. The i-th line contains space-separated string si and integer ri (0 ≀ ri ≀ n), where si is the name of the man with a number i, and ri is either the number of the direct ancestor of the man with a number i or 0, if the man with a number i has no direct ancestor. The next line contains a single integer m (1 ≀ m ≀ 105) β€” the number of Polycarpus's records. Next m lines contain space-separated pairs of integers. The i-th line contains integers vi, ki (1 ≀ vi, ki ≀ n). It is guaranteed that the family relationships do not form cycles. The names of all people are non-empty strings, consisting of no more than 20 lowercase English letters. Output Print m whitespace-separated integers β€” the answers to Polycarpus's records. Print the answers to the records in the order, in which the records occur in the input. Examples Input 6 pasha 0 gerald 1 gerald 1 valera 2 igor 3 olesya 1 5 1 1 1 2 1 3 3 1 6 1 Output 2 2 0 1 0 Input 6 valera 0 valera 1 valera 1 gerald 0 valera 4 kolya 4 7 1 1 1 2 2 1 2 2 4 1 5 1 6 1 Output 1 0 0 0 2 0 0 Submitted Solution: ``` N = int(input()) N += 1 parents = list(map(int, input().split(" "))) parents = [0] + parents children = [] for i in range(N): children += [N * [0]] for i in range(1, N): p = parents[i] level = 1 while(p != 0): children[level][p] += 1 p = parents[p] level += 1 print("DEBUG") for i in range(N): print("level",i,"= ", children[i]) numTestCases = int(input()) for t in range(numTestCases): person, lineage_level = tuple(map(int, input().split(" "))) patriarch = person level = 0 numCousins = 0 while(patriarch != 0): patriarch = parents[patriarch] level += 1 if(level == lineage_level): numCousins = children[lineage_level][patriarch] if(numCousins > 0): # Disconsider thyself numCousins -= 1 break print(numCousins) ``` No
88,697
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarpus got hold of a family tree. The found tree describes the family relations of n people, numbered from 1 to n. Every person in this tree has at most one direct ancestor. Also, each person in the tree has a name, the names are not necessarily unique. We call the man with a number a a 1-ancestor of the man with a number b, if the man with a number a is a direct ancestor of the man with a number b. We call the man with a number a a k-ancestor (k > 1) of the man with a number b, if the man with a number b has a 1-ancestor, and the man with a number a is a (k - 1)-ancestor of the 1-ancestor of the man with a number b. In the tree the family ties do not form cycles. In other words there isn't a person who is his own direct or indirect ancestor (that is, who is an x-ancestor of himself, for some x, x > 0). We call a man with a number a the k-son of the man with a number b, if the man with a number b is a k-ancestor of the man with a number a. Polycarpus is very much interested in how many sons and which sons each person has. He took a piece of paper and wrote m pairs of numbers vi, ki. Help him to learn for each pair vi, ki the number of distinct names among all names of the ki-sons of the man with number vi. Input The first line of the input contains a single integer n (1 ≀ n ≀ 105) β€” the number of people in the tree. Next n lines contain the description of people in the tree. The i-th line contains space-separated string si and integer ri (0 ≀ ri ≀ n), where si is the name of the man with a number i, and ri is either the number of the direct ancestor of the man with a number i or 0, if the man with a number i has no direct ancestor. The next line contains a single integer m (1 ≀ m ≀ 105) β€” the number of Polycarpus's records. Next m lines contain space-separated pairs of integers. The i-th line contains integers vi, ki (1 ≀ vi, ki ≀ n). It is guaranteed that the family relationships do not form cycles. The names of all people are non-empty strings, consisting of no more than 20 lowercase English letters. Output Print m whitespace-separated integers β€” the answers to Polycarpus's records. Print the answers to the records in the order, in which the records occur in the input. Examples Input 6 pasha 0 gerald 1 gerald 1 valera 2 igor 3 olesya 1 5 1 1 1 2 1 3 3 1 6 1 Output 2 2 0 1 0 Input 6 valera 0 valera 1 valera 1 gerald 0 valera 4 kolya 4 7 1 1 1 2 2 1 2 2 4 1 5 1 6 1 Output 1 0 0 0 2 0 0 Submitted Solution: ``` import sys from collections import deque input=sys.stdin.readline n=int(input()) l= list(map(int,input().split())) dict={} for i in range(n): dict[i]=[] for i in range(n): l1=l[i] if(l1!=0): dict[l1-1].append(i) def bfs(start,n,visited,distance): # count=0 # print("lol") # distance=[0]*n # l2=[i+1] q=[start] q=deque(q) # count+=1 visited[start]=1 while (len(q)!=0): y=dict[q[0]] for j in y: if(visited[j]==0): visited[j]=1 # l2.append(j) distance[j]=distance[q[0]]+1 q.append(j) # count+=1 q.popleft() # print(distance,"wwwww") return distance # print(dict) s=0 def dfs(i,n,visited,starting,ending,distance): global s visited[i]=1 # print(i) s+=1 starting[i]=s for j in dict[i]: if(visited[j]!=1): dfs(j,n,visited,starting,ending,distance) s+=1 ending[i]=s tuple1=[i,starting[i],ending[i]] distance1=distance[i] dict1[distance1].append(tuple1) def binary_search(l,r,start,end,list1): if(r>=l): mid=(l+r)//2 s1=list1[mid][1] e1=list1[mid][2] if(start>=s1 and end<=e1): return list1[mid][0] elif(start>s1 and end>e1): return binary_search(mid+1,r,start,end,list1) elif(start<s1 and end<e1): return binary_search(l,mid-1,start,end,list1) else: return -2 else: return -2 def pth_ancestor(dict1,node,p): start=starting[node] end=ending[node] height=distance[node]-p # print(height,"llll") if(height>=0): return binary_search(0,len(dict1[height])-1,start,end,dict1[height]) else: return -2 def binary_search2(l,r,start,end,list1): if(r>=l): mid=(l+r)//2 if(mid==0 and list1[mid][1]>=start and list1[mid][2]<=end): return mid elif(mid==0): return -2 elif( mid==len(list1)-1 and list1[mid][1]<start): return -2 else: s1=list1[mid][1] if(s1>=start and list1[mid-1][1]<start and list1[mid][2]<=end): return mid elif(s1>=start and list1[mid-1][1]>start): return binary_search2(l,mid-1,start,end,list1) elif(s1<start): return binary_search2(mid+1,r,start,end,list1) else: return -2 else: return -2 def binary_search3(l,r,start,end,list1): if(r>=l): mid=(l+r)//2 if( mid==len(list1)-1 and list1[mid][2]<=end and list1[mid][1]>=start ): return mid elif((mid==0 or mid==len(list1)-1 ) and list1[mid][2]>end): return -2 else: s1=list1[mid][2] if(s1<=end and list1[mid+1][2]>end and list1[mid][1]>=start): return mid elif(s1<=end and list1[mid+1][2]<=end): return binary_search3(mid+1,r,start,end,list1) elif(s1>end): return binary_search3(l,mid-1,start,end,list1) else: return -2 else: return -2 def pth_descendants(dict1,node,p): start=starting[node] end=ending[node] height=distance[node]+p list1=dict1[height] # print(list1) if(height<=max(distance)): index1= binary_search2(0,len(list1)-1,start,end,list1) index2=binary_search3(0,len(list1)-1,start,end,list1) # print(index1,index2) if(index1!=-2 and index2!=-2): return index2-index1 else: return 0 else: return 0 visited=[0]*n distance=[0]*n for i in range(n): if(l[i]==0): print(i) bfs(i,n,visited,distance) starting=[0]*n ending=[0]*n visited=[0]*n dict1={} for i in range(n): dict1[distance[i]]=[] for i in range(n): if(l[i]==0): dfs(i,n,visited,starting,ending,distance) # print(distance) # print(dict1) result=[] m=int(input()) for i in range(m): l1= list(map(int,input().split())) node=l1[0]-1 p=l1[1] ances=pth_ancestor(dict1,node,p) # print(ances,"kkkk") if(ances!=-2): result.append(pth_descendants(dict1,ances,p)) else: result.append(0) s="" for i in range(m-1): s=s+str(result[i])+" " s=s+str(result[m-1]) print(s) # print(pth_ancestor(dict1,0,0),"lol") # pth_descendants(dict1,1,2) # print(starting) # print(ending) # print(dict1) ``` No
88,698
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarpus got hold of a family tree. The found tree describes the family relations of n people, numbered from 1 to n. Every person in this tree has at most one direct ancestor. Also, each person in the tree has a name, the names are not necessarily unique. We call the man with a number a a 1-ancestor of the man with a number b, if the man with a number a is a direct ancestor of the man with a number b. We call the man with a number a a k-ancestor (k > 1) of the man with a number b, if the man with a number b has a 1-ancestor, and the man with a number a is a (k - 1)-ancestor of the 1-ancestor of the man with a number b. In the tree the family ties do not form cycles. In other words there isn't a person who is his own direct or indirect ancestor (that is, who is an x-ancestor of himself, for some x, x > 0). We call a man with a number a the k-son of the man with a number b, if the man with a number b is a k-ancestor of the man with a number a. Polycarpus is very much interested in how many sons and which sons each person has. He took a piece of paper and wrote m pairs of numbers vi, ki. Help him to learn for each pair vi, ki the number of distinct names among all names of the ki-sons of the man with number vi. Input The first line of the input contains a single integer n (1 ≀ n ≀ 105) β€” the number of people in the tree. Next n lines contain the description of people in the tree. The i-th line contains space-separated string si and integer ri (0 ≀ ri ≀ n), where si is the name of the man with a number i, and ri is either the number of the direct ancestor of the man with a number i or 0, if the man with a number i has no direct ancestor. The next line contains a single integer m (1 ≀ m ≀ 105) β€” the number of Polycarpus's records. Next m lines contain space-separated pairs of integers. The i-th line contains integers vi, ki (1 ≀ vi, ki ≀ n). It is guaranteed that the family relationships do not form cycles. The names of all people are non-empty strings, consisting of no more than 20 lowercase English letters. Output Print m whitespace-separated integers β€” the answers to Polycarpus's records. Print the answers to the records in the order, in which the records occur in the input. Examples Input 6 pasha 0 gerald 1 gerald 1 valera 2 igor 3 olesya 1 5 1 1 1 2 1 3 3 1 6 1 Output 2 2 0 1 0 Input 6 valera 0 valera 1 valera 1 gerald 0 valera 4 kolya 4 7 1 1 1 2 2 1 2 2 4 1 5 1 6 1 Output 1 0 0 0 2 0 0 Submitted Solution: ``` import sys sys.setrecursionlimit(10**6) def fun(graph,present,depth,p,answer=0): if -1==present: return 1 if depth==p: return answer+1 else: if present in graph: for i in graph[present]: answer = fun(graph,i,depth+1,p,answer) else: return 1 return answer def original(graph,roots): for k in roots: print((fun(graph,k[0],0,k[1])-1),end = ' ') def findParent(element,p,parent): present = element while(p): if present==0: return -1 else: present=parent[present] p-=1 return present n = int(input()) graph = {} roots1 = [] roots2 = [] array = list(map(lambda x:int(x),input().split())) parent = {} for j in range(n): if array[j]==0: roots1.append(j+1) else: try: graph[array[j]].append(j+1) except: graph[array[j]]=[j+1] parent[j+1]=array[j] # print(graph) # print(parent) for j in range(int(input())): v,p = map(int,input().split()) roots2.append([findParent(v,p,parent),p]) # print(roots2) # print(graph) original(graph,roots2) ``` No
88,699