text
stringlengths
198
433k
conversation_id
int64
0
109k
Provide tags and a correct Python 3 solution for this coding contest problem. Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility. Initially Sam has a list with a single element n. Then he has to perform certain operations on this list. In each operation Sam must remove any element x, such that x > 1, from the list and insert at the same position <image>, <image>, <image> sequentially. He must continue with these operations until all the elements in the list are either 0 or 1. Now the masters want the total number of 1s in the range l to r (1-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test? Input The first line contains three integers n, l, r (0 ≤ n < 250, 0 ≤ r - l ≤ 105, r ≥ 1, l ≥ 1) – initial element and the range l to r. It is guaranteed that r is not greater than the length of the final list. Output Output the total number of 1s in the range l to r in the final sequence. Examples Input 7 2 5 Output 4 Input 10 3 10 Output 5 Note Consider first example: <image> Elements on positions from 2-nd to 5-th in list is [1, 1, 1, 1]. The number of ones is 4. For the second example: <image> Elements on positions from 3-rd to 10-th in list is [1, 1, 1, 0, 1, 0, 1, 0]. The number of ones is 5. Tags: constructive algorithms, dfs and similar, divide and conquer Correct Solution: ``` from math import * n,l,r=map(int,input().split()) li=[] if n==0: li=[0] while n>0: li=[n%2]+li n=n//2 cnt=0 for i in range(l,r+1): if li[int(log((i&(-i)),2))]==1: cnt+=1 print(cnt) ```
97,500
Provide tags and a correct Python 3 solution for this coding contest problem. Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility. Initially Sam has a list with a single element n. Then he has to perform certain operations on this list. In each operation Sam must remove any element x, such that x > 1, from the list and insert at the same position <image>, <image>, <image> sequentially. He must continue with these operations until all the elements in the list are either 0 or 1. Now the masters want the total number of 1s in the range l to r (1-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test? Input The first line contains three integers n, l, r (0 ≤ n < 250, 0 ≤ r - l ≤ 105, r ≥ 1, l ≥ 1) – initial element and the range l to r. It is guaranteed that r is not greater than the length of the final list. Output Output the total number of 1s in the range l to r in the final sequence. Examples Input 7 2 5 Output 4 Input 10 3 10 Output 5 Note Consider first example: <image> Elements on positions from 2-nd to 5-th in list is [1, 1, 1, 1]. The number of ones is 4. For the second example: <image> Elements on positions from 3-rd to 10-th in list is [1, 1, 1, 0, 1, 0, 1, 0]. The number of ones is 5. Tags: constructive algorithms, dfs and similar, divide and conquer Correct Solution: ``` import sys,math # FASTEST IO from io import BytesIO, IOBase from types import GeneratorType BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: self.os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) # End of FASTEST IO def func(n,m,q): if m==1: return 1 x=m//2 if x+1==q: return n%2 else: if q>x+1: q-=(x+1) return func(n//2,m//2,q) def main(): n,l,r=map(int,sys.stdin.readline().strip().split()) count=0 if n>=1: m=2**(int(math.log(n,2))+1)-1 for i in range(l,r+1): if func(n,m,i)==1: count+=1 sys.stdout.write(str(count)+'\n') main() ```
97,501
Provide tags and a correct Python 3 solution for this coding contest problem. Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility. Initially Sam has a list with a single element n. Then he has to perform certain operations on this list. In each operation Sam must remove any element x, such that x > 1, from the list and insert at the same position <image>, <image>, <image> sequentially. He must continue with these operations until all the elements in the list are either 0 or 1. Now the masters want the total number of 1s in the range l to r (1-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test? Input The first line contains three integers n, l, r (0 ≤ n < 250, 0 ≤ r - l ≤ 105, r ≥ 1, l ≥ 1) – initial element and the range l to r. It is guaranteed that r is not greater than the length of the final list. Output Output the total number of 1s in the range l to r in the final sequence. Examples Input 7 2 5 Output 4 Input 10 3 10 Output 5 Note Consider first example: <image> Elements on positions from 2-nd to 5-th in list is [1, 1, 1, 1]. The number of ones is 4. For the second example: <image> Elements on positions from 3-rd to 10-th in list is [1, 1, 1, 0, 1, 0, 1, 0]. The number of ones is 5. Tags: constructive algorithms, dfs and similar, divide and conquer Correct Solution: ``` import math n, l, r = map(int, input().split()) ls = list(map(int, list(bin(n)[2:]))) rs = 0 for i in range(l, r + 1): rs += ls[int(math.log2(i & -i))] print(rs) ```
97,502
Provide tags and a correct Python 3 solution for this coding contest problem. Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility. Initially Sam has a list with a single element n. Then he has to perform certain operations on this list. In each operation Sam must remove any element x, such that x > 1, from the list and insert at the same position <image>, <image>, <image> sequentially. He must continue with these operations until all the elements in the list are either 0 or 1. Now the masters want the total number of 1s in the range l to r (1-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test? Input The first line contains three integers n, l, r (0 ≤ n < 250, 0 ≤ r - l ≤ 105, r ≥ 1, l ≥ 1) – initial element and the range l to r. It is guaranteed that r is not greater than the length of the final list. Output Output the total number of 1s in the range l to r in the final sequence. Examples Input 7 2 5 Output 4 Input 10 3 10 Output 5 Note Consider first example: <image> Elements on positions from 2-nd to 5-th in list is [1, 1, 1, 1]. The number of ones is 4. For the second example: <image> Elements on positions from 3-rd to 10-th in list is [1, 1, 1, 0, 1, 0, 1, 0]. The number of ones is 5. Tags: constructive algorithms, dfs and similar, divide and conquer Correct Solution: ``` from sys import stdin from collections import deque #from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin def ii(): return int(stdin.readline()) def fi(): return float(stdin.readline()) def mi(): return map(int, stdin.readline().split()) def fmi(): return map(float, stdin.readline().split()) def li(): return list(mi()) def lsi(): x=list(stdin.readline()) x.pop() return x def si(): return stdin.readline() ############# CODE STARTS HERE ############# a=[] n, l, r=mi() while n>1: a.append(n%2) n//=2 if n: a.append(1) a.reverse() #print(a) i, s, j=2, 0, 0 while j<len(a): if a[j]: x=(l//i)*i+(i//2) if x<l: x+=i y=(r//i)*i+(i//2) if y<=r: y+=i s+=((y-x)//i) i+=i j+=1 print(s) ```
97,503
Provide tags and a correct Python 3 solution for this coding contest problem. Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility. Initially Sam has a list with a single element n. Then he has to perform certain operations on this list. In each operation Sam must remove any element x, such that x > 1, from the list and insert at the same position <image>, <image>, <image> sequentially. He must continue with these operations until all the elements in the list are either 0 or 1. Now the masters want the total number of 1s in the range l to r (1-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test? Input The first line contains three integers n, l, r (0 ≤ n < 250, 0 ≤ r - l ≤ 105, r ≥ 1, l ≥ 1) – initial element and the range l to r. It is guaranteed that r is not greater than the length of the final list. Output Output the total number of 1s in the range l to r in the final sequence. Examples Input 7 2 5 Output 4 Input 10 3 10 Output 5 Note Consider first example: <image> Elements on positions from 2-nd to 5-th in list is [1, 1, 1, 1]. The number of ones is 4. For the second example: <image> Elements on positions from 3-rd to 10-th in list is [1, 1, 1, 0, 1, 0, 1, 0]. The number of ones is 5. Tags: constructive algorithms, dfs and similar, divide and conquer Correct Solution: ``` #!/usr/bin/python3 from functools import lru_cache @lru_cache(maxsize=None) def length(n): if n <= 1: return 1 return 2 * length(n // 2) + 1 @lru_cache(maxsize=None) def solve(n, l, r): if l > r: return 0 if n <= 1: assert l == r and l == 1 return n mid = length(n // 2) + 1 if r < mid: return solve(n // 2, l, r) elif l > mid: return solve(n // 2, l - mid, r - mid) else: return (n % 2) + solve(n // 2, l, mid - 1) + solve(n // 2, 1, r - mid) n, l, r = map(int, input().split()) print(solve(n, l, r)) ```
97,504
Provide tags and a correct Python 3 solution for this coding contest problem. Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility. Initially Sam has a list with a single element n. Then he has to perform certain operations on this list. In each operation Sam must remove any element x, such that x > 1, from the list and insert at the same position <image>, <image>, <image> sequentially. He must continue with these operations until all the elements in the list are either 0 or 1. Now the masters want the total number of 1s in the range l to r (1-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test? Input The first line contains three integers n, l, r (0 ≤ n < 250, 0 ≤ r - l ≤ 105, r ≥ 1, l ≥ 1) – initial element and the range l to r. It is guaranteed that r is not greater than the length of the final list. Output Output the total number of 1s in the range l to r in the final sequence. Examples Input 7 2 5 Output 4 Input 10 3 10 Output 5 Note Consider first example: <image> Elements on positions from 2-nd to 5-th in list is [1, 1, 1, 1]. The number of ones is 4. For the second example: <image> Elements on positions from 3-rd to 10-th in list is [1, 1, 1, 0, 1, 0, 1, 0]. The number of ones is 5. Tags: constructive algorithms, dfs and similar, divide and conquer Correct Solution: ``` a = {0:0,1:1} x = input().split() n = int(x[0]) l = int(x[1]) r = int(x[2]) def search(p,left,right): mid = (left+right)>>1 if (right < l or left > r): return 0 if p in a: return a[p] if r<=mid: return search(p>>1,left,mid-1)+(r==mid and p%2) if l>=mid: return search(p>>1,mid+1,right)+(l==mid and p%2) return search(p>>1,left,mid)+(l<=mid and mid <= r and p%2)+search(p>>1,mid+1,right) print(search(n,1,2**(len(bin(n))-2)-1)) ```
97,505
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility. Initially Sam has a list with a single element n. Then he has to perform certain operations on this list. In each operation Sam must remove any element x, such that x > 1, from the list and insert at the same position <image>, <image>, <image> sequentially. He must continue with these operations until all the elements in the list are either 0 or 1. Now the masters want the total number of 1s in the range l to r (1-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test? Input The first line contains three integers n, l, r (0 ≤ n < 250, 0 ≤ r - l ≤ 105, r ≥ 1, l ≥ 1) – initial element and the range l to r. It is guaranteed that r is not greater than the length of the final list. Output Output the total number of 1s in the range l to r in the final sequence. Examples Input 7 2 5 Output 4 Input 10 3 10 Output 5 Note Consider first example: <image> Elements on positions from 2-nd to 5-th in list is [1, 1, 1, 1]. The number of ones is 4. For the second example: <image> Elements on positions from 3-rd to 10-th in list is [1, 1, 1, 0, 1, 0, 1, 0]. The number of ones is 5. Submitted Solution: ``` n, l, r = map(int, input().split()) s = '' a = [] k = n while k > 1: a.append(k % 2) k = k // 2 a.append(k) ans = 0 for i in range(l - 1, r): s = "0" + bin(i)[2:] cur = 1 while s[-cur] != "0": cur += 1 ans += a[-cur] print(ans) ``` Yes
97,506
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility. Initially Sam has a list with a single element n. Then he has to perform certain operations on this list. In each operation Sam must remove any element x, such that x > 1, from the list and insert at the same position <image>, <image>, <image> sequentially. He must continue with these operations until all the elements in the list are either 0 or 1. Now the masters want the total number of 1s in the range l to r (1-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test? Input The first line contains three integers n, l, r (0 ≤ n < 250, 0 ≤ r - l ≤ 105, r ≥ 1, l ≥ 1) – initial element and the range l to r. It is guaranteed that r is not greater than the length of the final list. Output Output the total number of 1s in the range l to r in the final sequence. Examples Input 7 2 5 Output 4 Input 10 3 10 Output 5 Note Consider first example: <image> Elements on positions from 2-nd to 5-th in list is [1, 1, 1, 1]. The number of ones is 4. For the second example: <image> Elements on positions from 3-rd to 10-th in list is [1, 1, 1, 0, 1, 0, 1, 0]. The number of ones is 5. Submitted Solution: ``` import sys def debug(x, table): for name, val in table.items(): if x is val: print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr) return None def solve(): n, l, r = map(int, input().split()) ans = f(n, r) - f(n, l - 1) print(ans) def f(n, i): if n == 0: return 0 if i == 0: return 0 mx = 2**(n.bit_length()) if i == mx//2: return n//2 + n%2 elif i < mx//2: return f(n//2, i) else: return n//2 + n%2 + f(n//2, i - mx//2) if __name__ == '__main__': solve() ``` Yes
97,507
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility. Initially Sam has a list with a single element n. Then he has to perform certain operations on this list. In each operation Sam must remove any element x, such that x > 1, from the list and insert at the same position <image>, <image>, <image> sequentially. He must continue with these operations until all the elements in the list are either 0 or 1. Now the masters want the total number of 1s in the range l to r (1-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test? Input The first line contains three integers n, l, r (0 ≤ n < 250, 0 ≤ r - l ≤ 105, r ≥ 1, l ≥ 1) – initial element and the range l to r. It is guaranteed that r is not greater than the length of the final list. Output Output the total number of 1s in the range l to r in the final sequence. Examples Input 7 2 5 Output 4 Input 10 3 10 Output 5 Note Consider first example: <image> Elements on positions from 2-nd to 5-th in list is [1, 1, 1, 1]. The number of ones is 4. For the second example: <image> Elements on positions from 3-rd to 10-th in list is [1, 1, 1, 0, 1, 0, 1, 0]. The number of ones is 5. Submitted Solution: ``` n, l, r = map(int, input().split()) binl = tuple(map(int, bin(n)[2:])) # print(binl) res = 0 for i in range(len(binl)): if not binl[i]: # print(i, binl[i], "skipped") continue cur = (1 << i) + (((l >> (i + 1)) - 1) << (i + 1)) # print(i, cur) dif = 1 << (i + 1) while cur <= r: if cur >= l: res += 1 cur += dif print(res) ``` Yes
97,508
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility. Initially Sam has a list with a single element n. Then he has to perform certain operations on this list. In each operation Sam must remove any element x, such that x > 1, from the list and insert at the same position <image>, <image>, <image> sequentially. He must continue with these operations until all the elements in the list are either 0 or 1. Now the masters want the total number of 1s in the range l to r (1-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test? Input The first line contains three integers n, l, r (0 ≤ n < 250, 0 ≤ r - l ≤ 105, r ≥ 1, l ≥ 1) – initial element and the range l to r. It is guaranteed that r is not greater than the length of the final list. Output Output the total number of 1s in the range l to r in the final sequence. Examples Input 7 2 5 Output 4 Input 10 3 10 Output 5 Note Consider first example: <image> Elements on positions from 2-nd to 5-th in list is [1, 1, 1, 1]. The number of ones is 4. For the second example: <image> Elements on positions from 3-rd to 10-th in list is [1, 1, 1, 0, 1, 0, 1, 0]. The number of ones is 5. Submitted Solution: ``` import sys #sys.stdin=open("data.txt") input=sys.stdin.readline n,l,r=map(int,input().split()) a1=0 layers=1 while layers*2<=n: layers*=2 # abacaba pattern for i in range(l,r+1): layer=layers while i%2==0: layer//=2 i//=2 if (n//layer)%2==1: a1+=1 #print(i,n&layer) print(a1) ``` Yes
97,509
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility. Initially Sam has a list with a single element n. Then he has to perform certain operations on this list. In each operation Sam must remove any element x, such that x > 1, from the list and insert at the same position <image>, <image>, <image> sequentially. He must continue with these operations until all the elements in the list are either 0 or 1. Now the masters want the total number of 1s in the range l to r (1-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test? Input The first line contains three integers n, l, r (0 ≤ n < 250, 0 ≤ r - l ≤ 105, r ≥ 1, l ≥ 1) – initial element and the range l to r. It is guaranteed that r is not greater than the length of the final list. Output Output the total number of 1s in the range l to r in the final sequence. Examples Input 7 2 5 Output 4 Input 10 3 10 Output 5 Note Consider first example: <image> Elements on positions from 2-nd to 5-th in list is [1, 1, 1, 1]. The number of ones is 4. For the second example: <image> Elements on positions from 3-rd to 10-th in list is [1, 1, 1, 0, 1, 0, 1, 0]. The number of ones is 5. Submitted Solution: ``` def gen(n,temp): if n==1 or n==0: temp.append(n) return gen(n//2,temp) s=temp if n%2==0: temp.append(0) else: temp.append(1) temp+=s return temp query=list(map(int,input().split())) arr=gen(query[0],temp=[]) count=0 for i in range(query[1]-1,query[2]): if arr[i]==1: count+=1 print(count) ``` No
97,510
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility. Initially Sam has a list with a single element n. Then he has to perform certain operations on this list. In each operation Sam must remove any element x, such that x > 1, from the list and insert at the same position <image>, <image>, <image> sequentially. He must continue with these operations until all the elements in the list are either 0 or 1. Now the masters want the total number of 1s in the range l to r (1-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test? Input The first line contains three integers n, l, r (0 ≤ n < 250, 0 ≤ r - l ≤ 105, r ≥ 1, l ≥ 1) – initial element and the range l to r. It is guaranteed that r is not greater than the length of the final list. Output Output the total number of 1s in the range l to r in the final sequence. Examples Input 7 2 5 Output 4 Input 10 3 10 Output 5 Note Consider first example: <image> Elements on positions from 2-nd to 5-th in list is [1, 1, 1, 1]. The number of ones is 4. For the second example: <image> Elements on positions from 3-rd to 10-th in list is [1, 1, 1, 0, 1, 0, 1, 0]. The number of ones is 5. Submitted Solution: ``` import math n,l,r = input().split() n=int(n) l=int(l) r=int(r) def func(n): if n==0: return 1 elif n==1: return 0 elif n==2: return 1 else: return 2*func(math.floor(n/2))+func(n%2) zeroes = func(n) dig = n+zeroes print(math.floor(((r-l+1)/dig)*n)) ``` No
97,511
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility. Initially Sam has a list with a single element n. Then he has to perform certain operations on this list. In each operation Sam must remove any element x, such that x > 1, from the list and insert at the same position <image>, <image>, <image> sequentially. He must continue with these operations until all the elements in the list are either 0 or 1. Now the masters want the total number of 1s in the range l to r (1-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test? Input The first line contains three integers n, l, r (0 ≤ n < 250, 0 ≤ r - l ≤ 105, r ≥ 1, l ≥ 1) – initial element and the range l to r. It is guaranteed that r is not greater than the length of the final list. Output Output the total number of 1s in the range l to r in the final sequence. Examples Input 7 2 5 Output 4 Input 10 3 10 Output 5 Note Consider first example: <image> Elements on positions from 2-nd to 5-th in list is [1, 1, 1, 1]. The number of ones is 4. For the second example: <image> Elements on positions from 3-rd to 10-th in list is [1, 1, 1, 0, 1, 0, 1, 0]. The number of ones is 5. Submitted Solution: ``` def rec(n): global d if n<=1: d.append(n) return n else: return (rec(n//2),rec(n%2),rec(n//2)) n,l,r=map(int,input().split()) ans=0 d=[] rec(n) for i in d[l:r+1]: if i==1: ans+=1 print(ans) ``` No
97,512
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility. Initially Sam has a list with a single element n. Then he has to perform certain operations on this list. In each operation Sam must remove any element x, such that x > 1, from the list and insert at the same position <image>, <image>, <image> sequentially. He must continue with these operations until all the elements in the list are either 0 or 1. Now the masters want the total number of 1s in the range l to r (1-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test? Input The first line contains three integers n, l, r (0 ≤ n < 250, 0 ≤ r - l ≤ 105, r ≥ 1, l ≥ 1) – initial element and the range l to r. It is guaranteed that r is not greater than the length of the final list. Output Output the total number of 1s in the range l to r in the final sequence. Examples Input 7 2 5 Output 4 Input 10 3 10 Output 5 Note Consider first example: <image> Elements on positions from 2-nd to 5-th in list is [1, 1, 1, 1]. The number of ones is 4. For the second example: <image> Elements on positions from 3-rd to 10-th in list is [1, 1, 1, 0, 1, 0, 1, 0]. The number of ones is 5. Submitted Solution: ``` """ Created by Henrikh Kantuni on 2/20/17 """ if __name__ == "__main__": n, l, r = input().split() n, l, r = int(n), int(l), int(r) li = [] memo = {} m = n while m // 2 > 1: li.append(m // 2) m //= 2 if len(li) == 1: memo[li[0]] = str(li[0] // 2) + str(li[0] % 2) + str(li[0] // 2) else: for i in range(len(li) - 2, -1, -1): if li[i - 1] not in memo: memo[li[i - 1]] = str(li[i - 1] // 2) + str(li[i - 1] % 2) + str(li[i - 1] // 2) previous = memo[li[i - 1]] memo[li[i]] = previous + str(li[i] % 2) + previous answer = memo[n // 2] + str(n % 2) + memo[n // 2] answer = list(answer) answer = answer[l - 1:r] answer = [a for a in answer if a == '1'] print(len(answer)) ``` No
97,513
Provide tags and a correct Python 3 solution for this coding contest problem. There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct. It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates. It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. Input The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. Output Print two integer numbers — the minimal distance and the quantity of pairs with this distance. Examples Input 4 6 -3 0 4 Output 2 1 Input 3 -2 0 2 Output 2 2 Note In the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. Tags: implementation, sortings Correct Solution: ``` import math n=int(input()) li=[int(x) for x in input().split()] li.sort() diff=math.inf c=0 for i in range(n-1): temp=li[i+1]-li[i] if temp==diff: c+=1 elif temp<diff: diff = temp c=1 print(diff,c) ```
97,514
Provide tags and a correct Python 3 solution for this coding contest problem. There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct. It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates. It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. Input The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. Output Print two integer numbers — the minimal distance and the quantity of pairs with this distance. Examples Input 4 6 -3 0 4 Output 2 1 Input 3 -2 0 2 Output 2 2 Note In the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. Tags: implementation, sortings Correct Solution: ``` n=int(input()) m=sorted(map(int,input().split())) d = [m[i]-m[i-1] for i in range(1,n)] a=min(d) print(a, d.count(a)) ```
97,515
Provide tags and a correct Python 3 solution for this coding contest problem. There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct. It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates. It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. Input The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. Output Print two integer numbers — the minimal distance and the quantity of pairs with this distance. Examples Input 4 6 -3 0 4 Output 2 1 Input 3 -2 0 2 Output 2 2 Note In the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. Tags: implementation, sortings Correct Solution: ``` n = int(input()) cities = sorted(map(int, input().split())) mn = float("inf") count = 0 for i in range(1, n): dist = cities[i] - cities[i - 1] if dist < mn: mn = dist count = 1 elif dist == mn: count += 1 print(mn, count) ```
97,516
Provide tags and a correct Python 3 solution for this coding contest problem. There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct. It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates. It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. Input The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. Output Print two integer numbers — the minimal distance and the quantity of pairs with this distance. Examples Input 4 6 -3 0 4 Output 2 1 Input 3 -2 0 2 Output 2 2 Note In the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. Tags: implementation, sortings Correct Solution: ``` #!/usr/bin/python3 # Copyright (C) 2017 Sayutin Dmitry. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; version 3 # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. def main(): input() a = list(map(int, input().split())) a.sort() mn, cnt = 10 ** 18, 0 for i in range(1, len(a)): f = a[i] - a[i - 1] if f == mn: cnt += 1 if f < mn: mn, cnt = f, 1 print(mn, cnt) main() ```
97,517
Provide tags and a correct Python 3 solution for this coding contest problem. There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct. It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates. It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. Input The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. Output Print two integer numbers — the minimal distance and the quantity of pairs with this distance. Examples Input 4 6 -3 0 4 Output 2 1 Input 3 -2 0 2 Output 2 2 Note In the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. Tags: implementation, sortings Correct Solution: ``` n=int(input()) a=[int(x) for x in input().split()] a=sorted(a) m=1<<31 i=1 #print(a) for j in range(n-1): d=abs(a[j]-a[j+1]) if d<m: m=d i=1 elif d==m: i+=1 print(m,i) ```
97,518
Provide tags and a correct Python 3 solution for this coding contest problem. There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct. It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates. It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. Input The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. Output Print two integer numbers — the minimal distance and the quantity of pairs with this distance. Examples Input 4 6 -3 0 4 Output 2 1 Input 3 -2 0 2 Output 2 2 Note In the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. Tags: implementation, sortings Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) a.sort() c = 0 m = 2000000005 f = 0 for i in range(n - 1): if abs(a[i] - a[i+1]) < m: m = abs(a[i] - a[i+1]) c = 1 elif abs(a[i] - a[i+1]) == m: c += 1 else: continue print(m, c) ```
97,519
Provide tags and a correct Python 3 solution for this coding contest problem. There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct. It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates. It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. Input The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. Output Print two integer numbers — the minimal distance and the quantity of pairs with this distance. Examples Input 4 6 -3 0 4 Output 2 1 Input 3 -2 0 2 Output 2 2 Note In the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. Tags: implementation, sortings Correct Solution: ``` #from statistics import median #import collections #aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0] #from fractions import gcd #from itertools import combinations # (string,3) 3回 #from collections import deque from collections import defaultdict #import bisect # # d = m - k[i] - k[j] # if kk[bisect.bisect_right(kk,d) - 1] == d: # # # # pythonで無理なときは、pypyでやると正解するかも!! # # import sys sys.setrecursionlimit(10000000) mod = 10**9 + 7 #mod = 9982443453 def readInts(): return list(map(int,input().split())) def I(): return int(input()) n = I() dic = defaultdict(int) A = readInts() A = sorted(A) MIN = float('inf') for i in range(n-1): m = abs(A[i] - A[i+1]) dic[m] += 1 if MIN > m: MIN = m print(MIN,dic[MIN]) ```
97,520
Provide tags and a correct Python 3 solution for this coding contest problem. There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct. It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates. It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. Input The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. Output Print two integer numbers — the minimal distance and the quantity of pairs with this distance. Examples Input 4 6 -3 0 4 Output 2 1 Input 3 -2 0 2 Output 2 2 Note In the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. Tags: implementation, sortings Correct Solution: ``` def main(): input() a = map(int, input().split()) a = sorted(a) d = [a[i + 1] - a[i] for i in range(len(a) - 1)] m = int(2 * 1e9 + 1) c = 0 for x in d: if x < m: m = x c = 1 elif x == m: c += 1 print(m, c) if __name__ == '__main__': # import sys # sys.stdin = open("A.txt") main() ```
97,521
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct. It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates. It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. Input The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. Output Print two integer numbers — the minimal distance and the quantity of pairs with this distance. Examples Input 4 6 -3 0 4 Output 2 1 Input 3 -2 0 2 Output 2 2 Note In the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. Submitted Solution: ``` n=int(input()) a=sorted(list(map(int,input().split()))) diff= 20000000000 c=0 for i in range(1,n): if abs(a[i]-a[i-1]) < diff: diff=abs(a[i]-a[i-1]) for i in range(1, n): if abs(a[i]-a[i-1])== diff: c+=1 print(diff, c) ``` Yes
97,522
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct. It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates. It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. Input The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. Output Print two integer numbers — the minimal distance and the quantity of pairs with this distance. Examples Input 4 6 -3 0 4 Output 2 1 Input 3 -2 0 2 Output 2 2 Note In the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. Submitted Solution: ``` n = int(input()) mn = 2 * 10 ** 9 + 1 a = [int(i) for i in input().split()] a.sort() cnt = 0 for i in range(n-1): x = abs(a[i] - a[i+1]) if x < mn: mn = x cnt = 1 elif x == mn: cnt = cnt + 1 print(mn, cnt) ``` Yes
97,523
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct. It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates. It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. Input The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. Output Print two integer numbers — the minimal distance and the quantity of pairs with this distance. Examples Input 4 6 -3 0 4 Output 2 1 Input 3 -2 0 2 Output 2 2 Note In the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. Submitted Solution: ``` n = int(input()) coords = sorted(map(int, input().split())) diffs = [coords[i]-coords[i-1] for i in range(1,n)] minimum = min(diffs) total = diffs.count(minimum) print(minimum, total) ``` Yes
97,524
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct. It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates. It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. Input The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. Output Print two integer numbers — the minimal distance and the quantity of pairs with this distance. Examples Input 4 6 -3 0 4 Output 2 1 Input 3 -2 0 2 Output 2 2 Note In the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. Submitted Solution: ``` n = int(input()) a = sorted(map(int, input().split())) d, c = 10000000000000000000000000, 1 for x in range(n-1): dx = a[x+1]-a[x] if dx < d: d = dx c = 1 elif dx == d: c += 1 print(d,c) ``` Yes
97,525
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct. It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates. It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. Input The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. Output Print two integer numbers — the minimal distance and the quantity of pairs with this distance. Examples Input 4 6 -3 0 4 Output 2 1 Input 3 -2 0 2 Output 2 2 Note In the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. Submitted Solution: ``` n = int(input()) points = [int(x) for x in input().split(" ")] points.sort() min = 99999999999999 count = 0 for i in range(len(points) - 1): distance = abs(points[i+1] - points[i]) if distance < min: min = distance count = 1 elif min == distance: count += 1 print("{0} {1}".format(distance, count)) ``` No
97,526
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct. It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates. It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. Input The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. Output Print two integer numbers — the minimal distance and the quantity of pairs with this distance. Examples Input 4 6 -3 0 4 Output 2 1 Input 3 -2 0 2 Output 2 2 Note In the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. Submitted Solution: ``` def getilist(): return list(map(int, input().split())) n = int(input()) a = sorted(getilist()) lb = 2e9 c = 0 for i in range(n-1): c += 1 t = abs(a[i] - a[i+1]) if t < lb: lb = t c = 1 print(lb, c) ``` No
97,527
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct. It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates. It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. Input The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. Output Print two integer numbers — the minimal distance and the quantity of pairs with this distance. Examples Input 4 6 -3 0 4 Output 2 1 Input 3 -2 0 2 Output 2 2 Note In the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. Submitted Solution: ``` input() cities = input().split() cities = list(map(int, cities)) min_dist = 9999 min_count = 0 for idx, x in enumerate(cities): for y in cities[idx + 1:]: xy = abs(x - y) if xy < min_dist: min_dist = xy min_count = 1 continue if xy == min_dist: min_count += 1 print("{} {}".format(min_dist, min_count)) ``` No
97,528
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct. It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates. It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance. Input The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct. Output Print two integer numbers — the minimal distance and the quantity of pairs with this distance. Examples Input 4 6 -3 0 4 Output 2 1 Input 3 -2 0 2 Output 2 2 Note In the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance. Submitted Solution: ``` import sys input=sys.stdin.readline from collections import defaultdict as dc from collections import Counter from bisect import bisect_right, bisect_left import math from operator import itemgetter from heapq import heapify, heappop, heappush from queue import PriorityQueue as pq n=int(input()) l=list(map(int,input().split())) l.sort() x=dc(int) m=sys.maxsize for i in range(n-1): p=abs(l[i]-l[i+1]) x[p]+=1 m=min(m,p) print(p,x[p]) ``` No
97,529
Provide tags and a correct Python 3 solution for this coding contest problem. On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost of item xj is axj + xj·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k. Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task? Input The first line contains two integers n and S (1 ≤ n ≤ 105 and 1 ≤ S ≤ 109) — the number of souvenirs in the market and Sagheer's budget. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the base costs of the souvenirs. Output On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs. Examples Input 3 11 2 3 5 Output 2 11 Input 4 100 1 2 5 6 Output 4 54 Input 1 7 7 Output 0 0 Note In the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items. In the second example, he can buy all items as they will cost him [5, 10, 17, 22]. In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it. Tags: binary search, sortings Correct Solution: ``` n,s=[int(i) for i in input().split()] ll=[int(i) for i in input().split()] curr=0; l=0 h=n while l<=h : mid = (h+l)//2; k=ll[:] for i in range(n):k[i]=(i+1)*mid+ll[i]; k.sort(); #print(k) sm=sum(k[:mid]) #print(mid,sm) if sm<=s: curr=mid l=mid+1 ans=sm else: h=mid-1 print(curr,ans) ```
97,530
Provide tags and a correct Python 3 solution for this coding contest problem. On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost of item xj is axj + xj·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k. Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task? Input The first line contains two integers n and S (1 ≤ n ≤ 105 and 1 ≤ S ≤ 109) — the number of souvenirs in the market and Sagheer's budget. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the base costs of the souvenirs. Output On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs. Examples Input 3 11 2 3 5 Output 2 11 Input 4 100 1 2 5 6 Output 4 54 Input 1 7 7 Output 0 0 Note In the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items. In the second example, he can buy all items as they will cost him [5, 10, 17, 22]. In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it. Tags: binary search, sortings Correct Solution: ``` n ,mm = list(map(int, input().split())) ar = list(map(int, input().split())) pr = list(ar) def check(curr): for i in range(0,n): pr[i] = ar[i] + curr*(i+1) pr.sort() ans=0 for i in range(0, curr): ans = ans + pr[i] return ans def BS(l,r): if r==l+1 : if check(r)<=mm: return r return l m = l+r m = m//2 if check(m)<=mm: return BS(m,r) return BS(l,m) ans = BS(0,n) print(ans,end = ' ') print(check(ans)) ```
97,531
Provide tags and a correct Python 3 solution for this coding contest problem. On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost of item xj is axj + xj·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k. Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task? Input The first line contains two integers n and S (1 ≤ n ≤ 105 and 1 ≤ S ≤ 109) — the number of souvenirs in the market and Sagheer's budget. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the base costs of the souvenirs. Output On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs. Examples Input 3 11 2 3 5 Output 2 11 Input 4 100 1 2 5 6 Output 4 54 Input 1 7 7 Output 0 0 Note In the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items. In the second example, he can buy all items as they will cost him [5, 10, 17, 22]. In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it. Tags: binary search, sortings Correct Solution: ``` def check(li,mid,c): s = [] for i in range(len(li)): s.append(li[i] + mid*(i+1)) s.sort() x = 0 for i in range(mid): x += s[i] if x > c: return False,x return True,x def main(li,c): start = 0 end = len(li) ans = -1 sol = -1 while start<=end: mid = (start+end)//2 z,y = check(li,mid,c) if z == True: ans = mid sol = y start = mid+1 else: end = mid-1 print(ans,sol) n,c = [int(x) for x in input().split()] li = [int(x) for x in input().split()] main(li,c) ```
97,532
Provide tags and a correct Python 3 solution for this coding contest problem. On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost of item xj is axj + xj·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k. Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task? Input The first line contains two integers n and S (1 ≤ n ≤ 105 and 1 ≤ S ≤ 109) — the number of souvenirs in the market and Sagheer's budget. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the base costs of the souvenirs. Output On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs. Examples Input 3 11 2 3 5 Output 2 11 Input 4 100 1 2 5 6 Output 4 54 Input 1 7 7 Output 0 0 Note In the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items. In the second example, he can buy all items as they will cost him [5, 10, 17, 22]. In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it. Tags: binary search, sortings Correct Solution: ``` #!/usr/bin/python3 cost = 0 n, s = map(int, input().split()) a = list(map(int, input().split())) def funcMonotonic(a, s, k): global cost costs = [a[i] + (i + 1) * k for i in range(n)] costs.sort() cost = sum(costs[:k]) return cost <= s left, right = 0, n + 1 while left + 1 < right: middle = (left + right) // 2 if funcMonotonic(a, s, middle): left = middle else: right = middle funcMonotonic(a, s, left) print(left, cost) ```
97,533
Provide tags and a correct Python 3 solution for this coding contest problem. On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost of item xj is axj + xj·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k. Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task? Input The first line contains two integers n and S (1 ≤ n ≤ 105 and 1 ≤ S ≤ 109) — the number of souvenirs in the market and Sagheer's budget. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the base costs of the souvenirs. Output On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs. Examples Input 3 11 2 3 5 Output 2 11 Input 4 100 1 2 5 6 Output 4 54 Input 1 7 7 Output 0 0 Note In the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items. In the second example, he can buy all items as they will cost him [5, 10, 17, 22]. In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it. Tags: binary search, sortings Correct Solution: ``` import sys def sol(k): B=[0]*n for i in range(n): B[i]=A[i]+k*(i+1) B.sort() res=0 for i in range(k): res+=B[i] return res #main code n,s=map(int,sys.stdin.readline().split()) A=list(map(int,sys.stdin.readline().split())) #Binary search for the value k l=0 r=n+1 while(l<r-1): mid=(l+r)//2 if sol(mid)<=s: l=mid else: r=mid print(l,sol(l)) ```
97,534
Provide tags and a correct Python 3 solution for this coding contest problem. On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost of item xj is axj + xj·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k. Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task? Input The first line contains two integers n and S (1 ≤ n ≤ 105 and 1 ≤ S ≤ 109) — the number of souvenirs in the market and Sagheer's budget. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the base costs of the souvenirs. Output On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs. Examples Input 3 11 2 3 5 Output 2 11 Input 4 100 1 2 5 6 Output 4 54 Input 1 7 7 Output 0 0 Note In the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items. In the second example, he can buy all items as they will cost him [5, 10, 17, 22]. In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it. Tags: binary search, sortings Correct Solution: ``` n,S=map(int,input().split()) l=list(map(int,input().split())) l2,r=0,n v=0 while l2!=r : l1=[] m=(l2+r+1)//2 for i in range(n) : l1.append(l[i]+(i+1)*m) l1=sorted(l1) for i in range(1,n) : l1[i]+=l1[i-1] if l1[m-1]>S : r=m-1 else : l2=m v=l1[m-1] print(l2,v) ```
97,535
Provide tags and a correct Python 3 solution for this coding contest problem. On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost of item xj is axj + xj·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k. Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task? Input The first line contains two integers n and S (1 ≤ n ≤ 105 and 1 ≤ S ≤ 109) — the number of souvenirs in the market and Sagheer's budget. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the base costs of the souvenirs. Output On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs. Examples Input 3 11 2 3 5 Output 2 11 Input 4 100 1 2 5 6 Output 4 54 Input 1 7 7 Output 0 0 Note In the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items. In the second example, he can buy all items as they will cost him [5, 10, 17, 22]. In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it. Tags: binary search, sortings Correct Solution: ``` n,s=map(int,input().split()) a=list(map(int,input().split())) beg=0 end=n def trier(k) : p = sorted([a[i]+ k*(i+1) for i in range(n)]) som = sum(p[0:k]) return 0 if som>s else som l = 0 r = n while l < r : k = (l +r +1)//2 if trier(k) : l = k else : r = k - 1 print(l,trier(l)) ```
97,536
Provide tags and a correct Python 3 solution for this coding contest problem. On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost of item xj is axj + xj·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k. Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task? Input The first line contains two integers n and S (1 ≤ n ≤ 105 and 1 ≤ S ≤ 109) — the number of souvenirs in the market and Sagheer's budget. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the base costs of the souvenirs. Output On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs. Examples Input 3 11 2 3 5 Output 2 11 Input 4 100 1 2 5 6 Output 4 54 Input 1 7 7 Output 0 0 Note In the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items. In the second example, he can buy all items as they will cost him [5, 10, 17, 22]. In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it. Tags: binary search, sortings Correct Solution: ``` n,S = map(int,input().split()) st = input().split(' ') cost = [int(num) for num in st] l,r,Smin,k = 0,n+1,0,0 for _ in range(20): k = int((l+r)/2) a = list() for i in range(n): a.append(cost[i] + k*(i+1)) a.sort() s = 0 for i in range(k): s += a[i] if(s <= S): l = k Smin = s; else: r = k print(k,int(Smin)) ```
97,537
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost of item xj is axj + xj·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k. Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task? Input The first line contains two integers n and S (1 ≤ n ≤ 105 and 1 ≤ S ≤ 109) — the number of souvenirs in the market and Sagheer's budget. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the base costs of the souvenirs. Output On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs. Examples Input 3 11 2 3 5 Output 2 11 Input 4 100 1 2 5 6 Output 4 54 Input 1 7 7 Output 0 0 Note In the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items. In the second example, he can buy all items as they will cost him [5, 10, 17, 22]. In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it. Submitted Solution: ``` # Sagheer and Nubian Market import sys import math import collections from pprint import pprint as pp mod = 998244353 MAX = 10**10 def vector(size, val=0): vec = [val for i in range(size)] return vec def matrix(rowNum, colNum, val=0): mat = [] for i in range(rowNum): collumn = [val for j in range(colNum)] mat.append(collumn) return mat n, s = map(int, input().split()) a = list(map(int, input().split())) def fun(m): cnt = 0 b = [a[i] + m * (i + 1) for i in range(n)] b.sort() for i in range(m): cnt += b[i] return [cnt <= s, cnt] l, h, ans, cost = 0, n, 0, 0 while l <= h: m = (l + h) // 2 temp = fun(m) if temp[0]: ans = m cost = temp[1] l = m + 1 else: h = m - 1 print('%d %d' % (ans, cost)) ``` Yes
97,538
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost of item xj is axj + xj·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k. Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task? Input The first line contains two integers n and S (1 ≤ n ≤ 105 and 1 ≤ S ≤ 109) — the number of souvenirs in the market and Sagheer's budget. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the base costs of the souvenirs. Output On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs. Examples Input 3 11 2 3 5 Output 2 11 Input 4 100 1 2 5 6 Output 4 54 Input 1 7 7 Output 0 0 Note In the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items. In the second example, he can buy all items as they will cost him [5, 10, 17, 22]. In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it. Submitted Solution: ``` n, S = map(int, input().split()) a = list(map(int, input().split())) #a.insert(0, 0) #a = sorted(a) l = 0 r = n realValue = 0 realMid = 0 mid = 0 while l <= r: mid = l + (r - l) // 2 value = 0 b = [] for i in range(n): b.append(a[i] + ((i + 1) * mid)) b = sorted(b) for i in range(mid): value += b[i] #print(realMid, realValue, 'L:', l, 'R:', r) if value <= S: realMid = mid realValue = value if S <= value: r = mid - 1 else: l = mid + 1 if realValue > S: print('0 0') else: print(realMid, realValue) ``` Yes
97,539
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost of item xj is axj + xj·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k. Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task? Input The first line contains two integers n and S (1 ≤ n ≤ 105 and 1 ≤ S ≤ 109) — the number of souvenirs in the market and Sagheer's budget. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the base costs of the souvenirs. Output On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs. Examples Input 3 11 2 3 5 Output 2 11 Input 4 100 1 2 5 6 Output 4 54 Input 1 7 7 Output 0 0 Note In the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items. In the second example, he can buy all items as they will cost him [5, 10, 17, 22]. In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it. Submitted Solution: ``` import sys def sol(k): B=[0]*n for i in range(n): B[i]=A[i]+k*(i+1) B.sort() res=0 for i in range(k): res+=B[i] return res #main code n,s=map(int,input().split()) A=list(map(int,input().split())) #Binary search for the value k l=0 r=n+1 while(l<r-1): mid=(l+r)//2 if sol(mid)<=s: l=mid else: r=mid print(l,sol(l)) ``` Yes
97,540
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost of item xj is axj + xj·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k. Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task? Input The first line contains two integers n and S (1 ≤ n ≤ 105 and 1 ≤ S ≤ 109) — the number of souvenirs in the market and Sagheer's budget. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the base costs of the souvenirs. Output On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs. Examples Input 3 11 2 3 5 Output 2 11 Input 4 100 1 2 5 6 Output 4 54 Input 1 7 7 Output 0 0 Note In the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items. In the second example, he can buy all items as they will cost him [5, 10, 17, 22]. In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it. Submitted Solution: ``` def canBuy(k): fullCost = [(i + 1) * k + cost[i] for i in range(0, n)] fullCost = sorted(fullCost) fullSum = sum(fullCost[:k]) return fullSum <= money def canBuyCost(k): fullCost = [(i + 1) * k + cost[i] for i in range(0, n)] fullCost = sorted(fullCost) fullSum = sum(fullCost[:k]) return fullSum if fullSum <= money else -1 n, money = [int(x) for x in input().split()] cost = [int(x) for x in input().split()] left = 0 right = n while left < right - 1: mid = (left + right) // 2 if canBuy(mid): left = mid else: right = mid rightRes = canBuyCost(right) if rightRes == -1: print(left, canBuyCost(left)) else: print(right, rightRes) ``` Yes
97,541
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost of item xj is axj + xj·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k. Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task? Input The first line contains two integers n and S (1 ≤ n ≤ 105 and 1 ≤ S ≤ 109) — the number of souvenirs in the market and Sagheer's budget. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the base costs of the souvenirs. Output On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs. Examples Input 3 11 2 3 5 Output 2 11 Input 4 100 1 2 5 6 Output 4 54 Input 1 7 7 Output 0 0 Note In the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items. In the second example, he can buy all items as they will cost him [5, 10, 17, 22]. In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it. Submitted Solution: ``` n, s = map(int, input().split()) l = sorted(list(map(int, input().split()))) k = 0 st = 0 mk = 0 ma = [] for j in range(1, n + 1): s1 = s s2 = 0 k1 = 0 for i in range(j): if s1 <= 0: break s1 -= (l[i] + ((i + 1) * j)) if s1 < 0: break s2 += (l[i] + ((i + 1) * j)) k1 += 1 if k1 > mk: mk = k1 k = j st = s2 print(k, st) ``` No
97,542
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost of item xj is axj + xj·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k. Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task? Input The first line contains two integers n and S (1 ≤ n ≤ 105 and 1 ≤ S ≤ 109) — the number of souvenirs in the market and Sagheer's budget. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the base costs of the souvenirs. Output On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs. Examples Input 3 11 2 3 5 Output 2 11 Input 4 100 1 2 5 6 Output 4 54 Input 1 7 7 Output 0 0 Note In the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items. In the second example, he can buy all items as they will cost him [5, 10, 17, 22]. In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it. Submitted Solution: ``` max_cost=0 print("Input the value of n & S") input1=input() n = [int(l) for l in input1.split()][0] S = [int(li) for li in input1.split()][1] #S = input1.split(" ")[1] print("Input the cost of item") cost = [int(l) for l in input().split()] k=int(2*(S-sum(cost))/n*(n+1)) if (n<k): k=n if (S-(cost[0]+1))<=0: k=0 max_cost=0 print(k,max_cost) else: for i in range(0,k): S=S-cost[i] if S<=0: break max_cost=max_cost+cost[i]+(i+1)*k print(k,max_cost) ``` No
97,543
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost of item xj is axj + xj·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k. Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task? Input The first line contains two integers n and S (1 ≤ n ≤ 105 and 1 ≤ S ≤ 109) — the number of souvenirs in the market and Sagheer's budget. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the base costs of the souvenirs. Output On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs. Examples Input 3 11 2 3 5 Output 2 11 Input 4 100 1 2 5 6 Output 4 54 Input 1 7 7 Output 0 0 Note In the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items. In the second example, he can buy all items as they will cost him [5, 10, 17, 22]. In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it. Submitted Solution: ``` n,S = map(int,input().split()) arr = list(map(int,input().split())) for i in range(1,n): arr[i]+=arr[i-1] l,r = 0,n ac = 0 while l<r: k = (l+r+1)>>1 at = [x+(i+1)*k for i,x in enumerate(arr)] at.sort() cost = sum(at[:k]) if cost<=S: l = k ac = cost else: r = k-1 print(l,ac) ``` No
97,544
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost of item xj is axj + xj·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k. Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task? Input The first line contains two integers n and S (1 ≤ n ≤ 105 and 1 ≤ S ≤ 109) — the number of souvenirs in the market and Sagheer's budget. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the base costs of the souvenirs. Output On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs. Examples Input 3 11 2 3 5 Output 2 11 Input 4 100 1 2 5 6 Output 4 54 Input 1 7 7 Output 0 0 Note In the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items. In the second example, he can buy all items as they will cost him [5, 10, 17, 22]. In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it. Submitted Solution: ``` n,s=map(int,input().split()) a=list(map(int,input().split())) a.sort() arr=[0]*n arr1=[a[0]]*n j=1 for i in range(1,n+1): arr[i-1]=i*j j+=(i+1) for k in range(1,n): arr1[k]=arr1[k-1]+a[k] count=0 ss=0 for x in range(n): if arr[x]+arr1[x]<s: arr[x]+arr1[x] count+=1 ss=arr[x]+arr1[x] elif arr[x]+arr1[x]==s: count+=1 ss=arr[x]+arr1[x] break else: break print(count,ss) ``` No
97,545
Provide tags and a correct Python 3 solution for this coding contest problem. Your friend has n cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'. For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true. To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true. Input The first and only line of input will contain a string s (1 ≤ |s| ≤ 50), denoting the sides of the cards that you can see on the table currently. Each character of s is either a lowercase English letter or a digit. Output Print a single integer, the minimum number of cards you must turn over to verify your claim. Examples Input ee Output 2 Input z Output 0 Input 0ay1 Output 2 Note In the first sample, we must turn over both cards. Note that even though both cards have the same letter, they could possibly have different numbers on the other side. In the second sample, we don't need to turn over any cards. The statement is vacuously true, since you know your friend has no cards with a vowel on them. In the third sample, we need to flip the second and fourth cards. Tags: brute force, implementation Correct Solution: ``` cards = input() flips = 0 for i in range(0, len(cards)): if(cards[i] in '0123456789'): if(int(cards[i])%2 != 0): flips +=1 else: if(cards[i] in 'aeiou'): flips +=1 print(flips) ```
97,546
Provide tags and a correct Python 3 solution for this coding contest problem. Your friend has n cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'. For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true. To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true. Input The first and only line of input will contain a string s (1 ≤ |s| ≤ 50), denoting the sides of the cards that you can see on the table currently. Each character of s is either a lowercase English letter or a digit. Output Print a single integer, the minimum number of cards you must turn over to verify your claim. Examples Input ee Output 2 Input z Output 0 Input 0ay1 Output 2 Note In the first sample, we must turn over both cards. Note that even though both cards have the same letter, they could possibly have different numbers on the other side. In the second sample, we don't need to turn over any cards. The statement is vacuously true, since you know your friend has no cards with a vowel on them. In the third sample, we need to flip the second and fourth cards. Tags: brute force, implementation Correct Solution: ``` test_string = input() turns = 0 for char in test_string: if char in ['1', '3', '5', '7', '9', 'a', 'e', 'i', 'o', 'u']: turns += 1 print(turns) ```
97,547
Provide tags and a correct Python 3 solution for this coding contest problem. Your friend has n cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'. For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true. To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true. Input The first and only line of input will contain a string s (1 ≤ |s| ≤ 50), denoting the sides of the cards that you can see on the table currently. Each character of s is either a lowercase English letter or a digit. Output Print a single integer, the minimum number of cards you must turn over to verify your claim. Examples Input ee Output 2 Input z Output 0 Input 0ay1 Output 2 Note In the first sample, we must turn over both cards. Note that even though both cards have the same letter, they could possibly have different numbers on the other side. In the second sample, we don't need to turn over any cards. The statement is vacuously true, since you know your friend has no cards with a vowel on them. In the third sample, we need to flip the second and fourth cards. Tags: brute force, implementation Correct Solution: ``` s = input("") count = 0 for i in s: if i in "aeiou13579": count +=1 print (count) ```
97,548
Provide tags and a correct Python 3 solution for this coding contest problem. Your friend has n cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'. For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true. To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true. Input The first and only line of input will contain a string s (1 ≤ |s| ≤ 50), denoting the sides of the cards that you can see on the table currently. Each character of s is either a lowercase English letter or a digit. Output Print a single integer, the minimum number of cards you must turn over to verify your claim. Examples Input ee Output 2 Input z Output 0 Input 0ay1 Output 2 Note In the first sample, we must turn over both cards. Note that even though both cards have the same letter, they could possibly have different numbers on the other side. In the second sample, we don't need to turn over any cards. The statement is vacuously true, since you know your friend has no cards with a vowel on them. In the third sample, we need to flip the second and fourth cards. Tags: brute force, implementation Correct Solution: ``` s = input() cnt = 0 for c in s: if c in '13579': cnt += 1 elif c in 'aeiou': cnt += 1 print(cnt) ```
97,549
Provide tags and a correct Python 3 solution for this coding contest problem. Your friend has n cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'. For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true. To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true. Input The first and only line of input will contain a string s (1 ≤ |s| ≤ 50), denoting the sides of the cards that you can see on the table currently. Each character of s is either a lowercase English letter or a digit. Output Print a single integer, the minimum number of cards you must turn over to verify your claim. Examples Input ee Output 2 Input z Output 0 Input 0ay1 Output 2 Note In the first sample, we must turn over both cards. Note that even though both cards have the same letter, they could possibly have different numbers on the other side. In the second sample, we don't need to turn over any cards. The statement is vacuously true, since you know your friend has no cards with a vowel on them. In the third sample, we need to flip the second and fourth cards. Tags: brute force, implementation Correct Solution: ``` s = input() c=0 for i in range(len(s)): if s[i] == 'a' or \ s[i] == 'e' or \ s[i] == 'i' or \ s[i] == 'o' or \ s[i] == 'u' or \ s[i] == '1' or \ s[i] == '3' or \ s[i] == '5' or \ s[i] == '7' or \ s[i] == '9': c = c + 1 print(c) ```
97,550
Provide tags and a correct Python 3 solution for this coding contest problem. Your friend has n cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'. For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true. To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true. Input The first and only line of input will contain a string s (1 ≤ |s| ≤ 50), denoting the sides of the cards that you can see on the table currently. Each character of s is either a lowercase English letter or a digit. Output Print a single integer, the minimum number of cards you must turn over to verify your claim. Examples Input ee Output 2 Input z Output 0 Input 0ay1 Output 2 Note In the first sample, we must turn over both cards. Note that even though both cards have the same letter, they could possibly have different numbers on the other side. In the second sample, we don't need to turn over any cards. The statement is vacuously true, since you know your friend has no cards with a vowel on them. In the third sample, we need to flip the second and fourth cards. Tags: brute force, implementation Correct Solution: ``` print(sum(x in 'aeiou13579' for x in input())) ```
97,551
Provide tags and a correct Python 3 solution for this coding contest problem. Your friend has n cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'. For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true. To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true. Input The first and only line of input will contain a string s (1 ≤ |s| ≤ 50), denoting the sides of the cards that you can see on the table currently. Each character of s is either a lowercase English letter or a digit. Output Print a single integer, the minimum number of cards you must turn over to verify your claim. Examples Input ee Output 2 Input z Output 0 Input 0ay1 Output 2 Note In the first sample, we must turn over both cards. Note that even though both cards have the same letter, they could possibly have different numbers on the other side. In the second sample, we don't need to turn over any cards. The statement is vacuously true, since you know your friend has no cards with a vowel on them. In the third sample, we need to flip the second and fourth cards. Tags: brute force, implementation Correct Solution: ``` s = input() result = 0 for c in s: if c in ['a', 'e', 'i', 'o', 'u', '1', '3', '5', '7', '9']: result += 1 print(result) ```
97,552
Provide tags and a correct Python 3 solution for this coding contest problem. Your friend has n cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'. For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true. To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true. Input The first and only line of input will contain a string s (1 ≤ |s| ≤ 50), denoting the sides of the cards that you can see on the table currently. Each character of s is either a lowercase English letter or a digit. Output Print a single integer, the minimum number of cards you must turn over to verify your claim. Examples Input ee Output 2 Input z Output 0 Input 0ay1 Output 2 Note In the first sample, we must turn over both cards. Note that even though both cards have the same letter, they could possibly have different numbers on the other side. In the second sample, we don't need to turn over any cards. The statement is vacuously true, since you know your friend has no cards with a vowel on them. In the third sample, we need to flip the second and fourth cards. Tags: brute force, implementation Correct Solution: ``` s = input() l = len(s) match = ['a','e','i','u','o'] match_num = ['0','2','4','6','8'] count = 0 for i in range(l): if s[i].isdigit(): if not (s[i] in match_num): count += 1 else: if s[i] in match: count += 1 print(count) ```
97,553
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Your friend has n cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'. For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true. To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true. Input The first and only line of input will contain a string s (1 ≤ |s| ≤ 50), denoting the sides of the cards that you can see on the table currently. Each character of s is either a lowercase English letter or a digit. Output Print a single integer, the minimum number of cards you must turn over to verify your claim. Examples Input ee Output 2 Input z Output 0 Input 0ay1 Output 2 Note In the first sample, we must turn over both cards. Note that even though both cards have the same letter, they could possibly have different numbers on the other side. In the second sample, we don't need to turn over any cards. The statement is vacuously true, since you know your friend has no cards with a vowel on them. In the third sample, we need to flip the second and fourth cards. Submitted Solution: ``` s = input() cnt = 0 for c in s: cnt += 1 if "aeiou13579".find(c) != -1 else 0 print(cnt) ``` Yes
97,554
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Your friend has n cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'. For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true. To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true. Input The first and only line of input will contain a string s (1 ≤ |s| ≤ 50), denoting the sides of the cards that you can see on the table currently. Each character of s is either a lowercase English letter or a digit. Output Print a single integer, the minimum number of cards you must turn over to verify your claim. Examples Input ee Output 2 Input z Output 0 Input 0ay1 Output 2 Note In the first sample, we must turn over both cards. Note that even though both cards have the same letter, they could possibly have different numbers on the other side. In the second sample, we don't need to turn over any cards. The statement is vacuously true, since you know your friend has no cards with a vowel on them. In the third sample, we need to flip the second and fourth cards. Submitted Solution: ``` cards = input() relevants = ['a', 'e', 'i', 'o', 'u', '1', '3', '5', '7', '9'] count = 0 for i in cards: if(i in relevants): count += 1 print(count) ``` Yes
97,555
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Your friend has n cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'. For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true. To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true. Input The first and only line of input will contain a string s (1 ≤ |s| ≤ 50), denoting the sides of the cards that you can see on the table currently. Each character of s is either a lowercase English letter or a digit. Output Print a single integer, the minimum number of cards you must turn over to verify your claim. Examples Input ee Output 2 Input z Output 0 Input 0ay1 Output 2 Note In the first sample, we must turn over both cards. Note that even though both cards have the same letter, they could possibly have different numbers on the other side. In the second sample, we don't need to turn over any cards. The statement is vacuously true, since you know your friend has no cards with a vowel on them. In the third sample, we need to flip the second and fourth cards. Submitted Solution: ``` ins = input() cnt = sum([1 for x in ins if x in "aeiou13579"]) print(cnt) ``` Yes
97,556
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Your friend has n cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'. For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true. To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true. Input The first and only line of input will contain a string s (1 ≤ |s| ≤ 50), denoting the sides of the cards that you can see on the table currently. Each character of s is either a lowercase English letter or a digit. Output Print a single integer, the minimum number of cards you must turn over to verify your claim. Examples Input ee Output 2 Input z Output 0 Input 0ay1 Output 2 Note In the first sample, we must turn over both cards. Note that even though both cards have the same letter, they could possibly have different numbers on the other side. In the second sample, we don't need to turn over any cards. The statement is vacuously true, since you know your friend has no cards with a vowel on them. In the third sample, we need to flip the second and fourth cards. Submitted Solution: ``` s = input() print(sum(1 for c in s if c in 'aeiou13579')) ``` Yes
97,557
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Your friend has n cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'. For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true. To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true. Input The first and only line of input will contain a string s (1 ≤ |s| ≤ 50), denoting the sides of the cards that you can see on the table currently. Each character of s is either a lowercase English letter or a digit. Output Print a single integer, the minimum number of cards you must turn over to verify your claim. Examples Input ee Output 2 Input z Output 0 Input 0ay1 Output 2 Note In the first sample, we must turn over both cards. Note that even though both cards have the same letter, they could possibly have different numbers on the other side. In the second sample, we don't need to turn over any cards. The statement is vacuously true, since you know your friend has no cards with a vowel on them. In the third sample, we need to flip the second and fourth cards. Submitted Solution: ``` l=list(input()) x=["a","o","e","i","u"] x2=["0","1","2","3","4","5","6","7","8","9"] x1=[0,2,4,6,8] d=0 x3,x4=[],[] for i in range(len(l)): if l[i] in x2: x3.append(l[i]) else: x4.append(l[i]) for i in range(len(x3)): if not x3[i] in x1: d=d+1 for j in range(len(x4)): if x4[i] in x: d=d+1 print(d) ``` No
97,558
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Your friend has n cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'. For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true. To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true. Input The first and only line of input will contain a string s (1 ≤ |s| ≤ 50), denoting the sides of the cards that you can see on the table currently. Each character of s is either a lowercase English letter or a digit. Output Print a single integer, the minimum number of cards you must turn over to verify your claim. Examples Input ee Output 2 Input z Output 0 Input 0ay1 Output 2 Note In the first sample, we must turn over both cards. Note that even though both cards have the same letter, they could possibly have different numbers on the other side. In the second sample, we don't need to turn over any cards. The statement is vacuously true, since you know your friend has no cards with a vowel on them. In the third sample, we need to flip the second and fourth cards. Submitted Solution: ``` import sys lst = list(sys.stdin.read()) try: lst.remove('\n') except: pass count = 0 vowels = set(['i', 'e', 'a', 'o', 'u']) for item in lst: try: i = int(item) if i % 2 == 1: print(item) count += 1 except: s = str(item) if s in vowels: print(item) count += 1 print(count) ``` No
97,559
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Your friend has n cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'. For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true. To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true. Input The first and only line of input will contain a string s (1 ≤ |s| ≤ 50), denoting the sides of the cards that you can see on the table currently. Each character of s is either a lowercase English letter or a digit. Output Print a single integer, the minimum number of cards you must turn over to verify your claim. Examples Input ee Output 2 Input z Output 0 Input 0ay1 Output 2 Note In the first sample, we must turn over both cards. Note that even though both cards have the same letter, they could possibly have different numbers on the other side. In the second sample, we don't need to turn over any cards. The statement is vacuously true, since you know your friend has no cards with a vowel on them. In the third sample, we need to flip the second and fourth cards. Submitted Solution: ``` cards = input() vowels = "aeiou02468" total = 0 for c in cards: if c in vowels: total += 1 print(total) ``` No
97,560
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Your friend has n cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'. For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true. To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true. Input The first and only line of input will contain a string s (1 ≤ |s| ≤ 50), denoting the sides of the cards that you can see on the table currently. Each character of s is either a lowercase English letter or a digit. Output Print a single integer, the minimum number of cards you must turn over to verify your claim. Examples Input ee Output 2 Input z Output 0 Input 0ay1 Output 2 Note In the first sample, we must turn over both cards. Note that even though both cards have the same letter, they could possibly have different numbers on the other side. In the second sample, we don't need to turn over any cards. The statement is vacuously true, since you know your friend has no cards with a vowel on them. In the third sample, we need to flip the second and fourth cards. Submitted Solution: ``` s = input() cnt = 0 lis = ["a", "e", "i", "o", "u"] for i in s: if i in lis: cnt += 1 print(cnt) ``` No
97,561
Provide tags and a correct Python 3 solution for this coding contest problem. Arcady is a copywriter. His today's task is to type up an already well-designed story using his favorite text editor. Arcady types words, punctuation signs and spaces one after another. Each letter and each sign (including line feed) requires one keyboard click in order to be printed. Moreover, when Arcady has a non-empty prefix of some word on the screen, the editor proposes a possible autocompletion for this word, more precisely one of the already printed words such that its prefix matches the currently printed prefix if this word is unique. For example, if Arcady has already printed «codeforces», «coding» and «codeforces» once again, then there will be no autocompletion attempt for «cod», but if he proceeds with «code», the editor will propose «codeforces». With a single click Arcady can follow the editor's proposal, i.e. to transform the current prefix to it. Note that no additional symbols are printed after the autocompletion (no spaces, line feeds, etc). What is the minimum number of keyboard clicks Arcady has to perform to print the entire text, if he is not allowed to move the cursor or erase the already printed symbols? A word here is a contiguous sequence of latin letters bordered by spaces, punctuation signs and line/text beginnings/ends. Arcady uses only lowercase letters. For example, there are 20 words in «it's well-known that tic-tac-toe is a paper-and-pencil game for two players, x and o.». Input The only line contains Arcady's text, consisting only of lowercase latin letters, spaces, line feeds and the following punctuation signs: «.», «,», «?», «!», «'» and «-». The total amount of symbols doesn't exceed 3·105. It's guaranteed that all lines are non-empty. Output Print a single integer — the minimum number of clicks. Examples Input snow affects sports such as skiing, snowboarding, and snowmachine travel. snowboarding is a recreational activity and olympic and paralympic sport. Output 141 Input 'co-co-co, codeforces?!' Output 25 Input thun-thun-thunder, thunder, thunder thunder, thun-, thunder thun-thun-thunder, thunder thunder, feel the thunder lightning then the thunder thunder, feel the thunder lightning then the thunder thunder, thunder Output 183 Note In sample case one it's optimal to use autocompletion for the first instance of «snowboarding» after typing up «sn» and for the second instance of «snowboarding» after typing up «snowb». This will save 7 clicks. In sample case two it doesn't matter whether to use autocompletion or not. Tags: *special, strings, trees Correct Solution: ``` # python3 # utf-8 class Trie: def __init__(self): self.letter___node = {} self.words_nr = 0 def add_word(self, word): word = word + '$' curr_node = self for letter in word: if letter not in curr_node.letter___node: curr_node.letter___node[letter] = Trie() curr_node.words_nr += 1 curr_node = curr_node.letter___node[letter] def check_word(self, word): word = word + '$' curr_node = self for letter in word: if letter not in curr_node.letter___node: return False curr_node = curr_node.letter___node[letter] return True def count_word(self, word): word = word + '$' curr_node = self curr_state = 0 presses_saved = 0 for letter in word: if letter not in curr_node.letter___node: if curr_state == 1: # print(presses_saved) if '$' in curr_node.letter___node: return min(len(word) - 1, len(word) - 1 - presses_saved + 1 ) else: return len(word) - 1 if curr_state == 0: return len(word) - 1 if curr_node.words_nr > 1: curr_node = curr_node.letter___node[letter] elif curr_node.words_nr == 1: # print(letter, presses_saved) if curr_state == 0: curr_state = 1 presses_saved += 1 curr_node = curr_node.letter___node[letter] elif curr_node.words_nr == 0: if curr_state == 1: return min(len(word) - 1, len(word) - 1 - presses_saved + 1 ) elif curr_state == 0: return len(word) - 1 if curr_node.words_nr == 0: presses_saved -= 1 if curr_state == 1: return min(len(word) - 1, len(word) - 1 - presses_saved + 1 ) elif curr_state == 0: return len(word) - 1 text = '' while(1): try: line = input() if line == '': raise Exception('e') text += line + '\n' except: break # print(text) ans = 0 syms = ['\n', '.', ',', '?', '!', "'", '-'] for sym in syms: text = text.replace(sym, ' ') ans += text.count(' ') idx___word = text.split(' ') root = Trie() root.add_word('$') root.add_word('$$') for word in idx___word: if word == '': continue count = root.count_word(word) check = root.check_word(word) # print(word, check, count) ans += count if not check: root.add_word(word) print(ans) ```
97,562
Provide tags and a correct Python 3 solution for this coding contest problem. Arcady is a copywriter. His today's task is to type up an already well-designed story using his favorite text editor. Arcady types words, punctuation signs and spaces one after another. Each letter and each sign (including line feed) requires one keyboard click in order to be printed. Moreover, when Arcady has a non-empty prefix of some word on the screen, the editor proposes a possible autocompletion for this word, more precisely one of the already printed words such that its prefix matches the currently printed prefix if this word is unique. For example, if Arcady has already printed «codeforces», «coding» and «codeforces» once again, then there will be no autocompletion attempt for «cod», but if he proceeds with «code», the editor will propose «codeforces». With a single click Arcady can follow the editor's proposal, i.e. to transform the current prefix to it. Note that no additional symbols are printed after the autocompletion (no spaces, line feeds, etc). What is the minimum number of keyboard clicks Arcady has to perform to print the entire text, if he is not allowed to move the cursor or erase the already printed symbols? A word here is a contiguous sequence of latin letters bordered by spaces, punctuation signs and line/text beginnings/ends. Arcady uses only lowercase letters. For example, there are 20 words in «it's well-known that tic-tac-toe is a paper-and-pencil game for two players, x and o.». Input The only line contains Arcady's text, consisting only of lowercase latin letters, spaces, line feeds and the following punctuation signs: «.», «,», «?», «!», «'» and «-». The total amount of symbols doesn't exceed 3·105. It's guaranteed that all lines are non-empty. Output Print a single integer — the minimum number of clicks. Examples Input snow affects sports such as skiing, snowboarding, and snowmachine travel. snowboarding is a recreational activity and olympic and paralympic sport. Output 141 Input 'co-co-co, codeforces?!' Output 25 Input thun-thun-thunder, thunder, thunder thunder, thun-, thunder thun-thun-thunder, thunder thunder, feel the thunder lightning then the thunder thunder, feel the thunder lightning then the thunder thunder, thunder Output 183 Note In sample case one it's optimal to use autocompletion for the first instance of «snowboarding» after typing up «sn» and for the second instance of «snowboarding» after typing up «snowb». This will save 7 clicks. In sample case two it doesn't matter whether to use autocompletion or not. Tags: *special, strings, trees Correct Solution: ``` class Ddict: def __init__(self): self.dicts={} def add(self,key): d=self.dicts for i in key: if i not in d: d[i]={} d=d[i] d[' ']='' def find(self,key): if key=='': return '','' d=self.dicts q=[] h=[key[0]] for i in key: if i not in d: if ' ' in d and len(d)==1: return ''.join(q),''.join(h) return '','' q.append(i) if len(d)!=1: h=q[:] d=d[i] if ' ' in d and len(d)==1: return ''.join(q),''.join(h) return '','' words = Ddict() ans=0 while True: try: x=input() if not x: break except: break ans+=len(x)+1 ws=[[]] for i in x: if i in '.,?!\'- ': if ws[-1]: ws.append([]) else: ws[-1].append(i) ws=list(map(lambda e:''.join(e),ws)) for w in ws: next_word,helped_word = words.find(w) if next_word and next_word!=helped_word: ans-=len(next_word)-len(helped_word)-1 words.add(w) print(ans) ```
97,563
Provide tags and a correct Python 3 solution for this coding contest problem. Arcady is a copywriter. His today's task is to type up an already well-designed story using his favorite text editor. Arcady types words, punctuation signs and spaces one after another. Each letter and each sign (including line feed) requires one keyboard click in order to be printed. Moreover, when Arcady has a non-empty prefix of some word on the screen, the editor proposes a possible autocompletion for this word, more precisely one of the already printed words such that its prefix matches the currently printed prefix if this word is unique. For example, if Arcady has already printed «codeforces», «coding» and «codeforces» once again, then there will be no autocompletion attempt for «cod», but if he proceeds with «code», the editor will propose «codeforces». With a single click Arcady can follow the editor's proposal, i.e. to transform the current prefix to it. Note that no additional symbols are printed after the autocompletion (no spaces, line feeds, etc). What is the minimum number of keyboard clicks Arcady has to perform to print the entire text, if he is not allowed to move the cursor or erase the already printed symbols? A word here is a contiguous sequence of latin letters bordered by spaces, punctuation signs and line/text beginnings/ends. Arcady uses only lowercase letters. For example, there are 20 words in «it's well-known that tic-tac-toe is a paper-and-pencil game for two players, x and o.». Input The only line contains Arcady's text, consisting only of lowercase latin letters, spaces, line feeds and the following punctuation signs: «.», «,», «?», «!», «'» and «-». The total amount of symbols doesn't exceed 3·105. It's guaranteed that all lines are non-empty. Output Print a single integer — the minimum number of clicks. Examples Input snow affects sports such as skiing, snowboarding, and snowmachine travel. snowboarding is a recreational activity and olympic and paralympic sport. Output 141 Input 'co-co-co, codeforces?!' Output 25 Input thun-thun-thunder, thunder, thunder thunder, thun-, thunder thun-thun-thunder, thunder thunder, feel the thunder lightning then the thunder thunder, feel the thunder lightning then the thunder thunder, thunder Output 183 Note In sample case one it's optimal to use autocompletion for the first instance of «snowboarding» after typing up «sn» and for the second instance of «snowboarding» after typing up «snowb». This will save 7 clicks. In sample case two it doesn't matter whether to use autocompletion or not. Tags: *special, strings, trees Correct Solution: ``` # ------------------- fast io -------------------- 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") # ------------------- fast io -------------------- class Trie: class Node: def __init__(self, char: int = 1): self.char = char self.children = [] self.counter = 1 def __init__(self): self.root = Trie.Node() self.ans = 0 def add(self, word): node = self.root for char in word: found_in_child = False for child in node.children: if child.char == char: child.counter += 1 node = child found_in_child = True break if not found_in_child: new_node = Trie.Node(char) node.children.append(new_node) node = new_node def query(self, prefix, root=None): if not root: root = self.root node = root if not root.children: return 0 prefix = [prefix] for char in prefix: char_not_found = True for child in node.children: if child.char == char: char_not_found = False node = child break if char_not_found: return 0 return node a = [] tr = Trie() while True: try: s = input() if not s:break except EOFError: break a += [s] def calc(s): node = tr.root found = False ind = -1 its = 0 for char in s: if not found: ind += 1 next = tr.query(char, node) if not next: break if next.counter == 1 and not found: found = True node = next its += 1 if found and node.counter == 1: if not node.children: tr.ans += min(len(s), ind + 2 + len(s)-its) elif node.children: tr.ans += len(s) else: tr.ans += min(len(s), ind + 2) else: tr.ans += len(s) if not (its == len(s) and not node.children): tr.add(s) for s in a: tr.ans += 1 cur = [] if 1: for k in s: if not k.isalpha(): tr.ans += 1 if cur: calc(cur) cur = [] else: cur += [ord(k)] if cur: calc(cur) print(tr.ans) ```
97,564
Provide tags and a correct Python 3 solution for this coding contest problem. Arcady is a copywriter. His today's task is to type up an already well-designed story using his favorite text editor. Arcady types words, punctuation signs and spaces one after another. Each letter and each sign (including line feed) requires one keyboard click in order to be printed. Moreover, when Arcady has a non-empty prefix of some word on the screen, the editor proposes a possible autocompletion for this word, more precisely one of the already printed words such that its prefix matches the currently printed prefix if this word is unique. For example, if Arcady has already printed «codeforces», «coding» and «codeforces» once again, then there will be no autocompletion attempt for «cod», but if he proceeds with «code», the editor will propose «codeforces». With a single click Arcady can follow the editor's proposal, i.e. to transform the current prefix to it. Note that no additional symbols are printed after the autocompletion (no spaces, line feeds, etc). What is the minimum number of keyboard clicks Arcady has to perform to print the entire text, if he is not allowed to move the cursor or erase the already printed symbols? A word here is a contiguous sequence of latin letters bordered by spaces, punctuation signs and line/text beginnings/ends. Arcady uses only lowercase letters. For example, there are 20 words in «it's well-known that tic-tac-toe is a paper-and-pencil game for two players, x and o.». Input The only line contains Arcady's text, consisting only of lowercase latin letters, spaces, line feeds and the following punctuation signs: «.», «,», «?», «!», «'» and «-». The total amount of symbols doesn't exceed 3·105. It's guaranteed that all lines are non-empty. Output Print a single integer — the minimum number of clicks. Examples Input snow affects sports such as skiing, snowboarding, and snowmachine travel. snowboarding is a recreational activity and olympic and paralympic sport. Output 141 Input 'co-co-co, codeforces?!' Output 25 Input thun-thun-thunder, thunder, thunder thunder, thun-, thunder thun-thun-thunder, thunder thunder, feel the thunder lightning then the thunder thunder, feel the thunder lightning then the thunder thunder, thunder Output 183 Note In sample case one it's optimal to use autocompletion for the first instance of «snowboarding» after typing up «sn» and for the second instance of «snowboarding» after typing up «snowb». This will save 7 clicks. In sample case two it doesn't matter whether to use autocompletion or not. Tags: *special, strings, trees Correct Solution: ``` import sys import re SEPARATORS = "[.,? !'-]" class TrieNode(object): def __init__(self): self.terminal = False self.go = {} self.count = 0 def insert(node, s): nodes = [node] unique, auto = 0, 0 for c in s: if c not in node.go: node.go[c] = TrieNode() node = node.go[c] nodes.append(node) if node.count == 1: unique += 1 if node.terminal: auto = max(unique - 2, 0) if not node.terminal: node.terminal = True for node in nodes: node.count += 1 return auto root = TrieNode() answer = 0 for line in sys.stdin: answer += len(line) for word in filter(None, re.split(SEPARATORS, line.strip())): answer -= insert(root, word) print(answer) ```
97,565
Provide tags and a correct Python 3 solution for this coding contest problem. Arcady is a copywriter. His today's task is to type up an already well-designed story using his favorite text editor. Arcady types words, punctuation signs and spaces one after another. Each letter and each sign (including line feed) requires one keyboard click in order to be printed. Moreover, when Arcady has a non-empty prefix of some word on the screen, the editor proposes a possible autocompletion for this word, more precisely one of the already printed words such that its prefix matches the currently printed prefix if this word is unique. For example, if Arcady has already printed «codeforces», «coding» and «codeforces» once again, then there will be no autocompletion attempt for «cod», but if he proceeds with «code», the editor will propose «codeforces». With a single click Arcady can follow the editor's proposal, i.e. to transform the current prefix to it. Note that no additional symbols are printed after the autocompletion (no spaces, line feeds, etc). What is the minimum number of keyboard clicks Arcady has to perform to print the entire text, if he is not allowed to move the cursor or erase the already printed symbols? A word here is a contiguous sequence of latin letters bordered by spaces, punctuation signs and line/text beginnings/ends. Arcady uses only lowercase letters. For example, there are 20 words in «it's well-known that tic-tac-toe is a paper-and-pencil game for two players, x and o.». Input The only line contains Arcady's text, consisting only of lowercase latin letters, spaces, line feeds and the following punctuation signs: «.», «,», «?», «!», «'» and «-». The total amount of symbols doesn't exceed 3·105. It's guaranteed that all lines are non-empty. Output Print a single integer — the minimum number of clicks. Examples Input snow affects sports such as skiing, snowboarding, and snowmachine travel. snowboarding is a recreational activity and olympic and paralympic sport. Output 141 Input 'co-co-co, codeforces?!' Output 25 Input thun-thun-thunder, thunder, thunder thunder, thun-, thunder thun-thun-thunder, thunder thunder, feel the thunder lightning then the thunder thunder, feel the thunder lightning then the thunder thunder, thunder Output 183 Note In sample case one it's optimal to use autocompletion for the first instance of «snowboarding» after typing up «sn» and for the second instance of «snowboarding» after typing up «snowb». This will save 7 clicks. In sample case two it doesn't matter whether to use autocompletion or not. Tags: *special, strings, trees Correct Solution: ``` import sys def read_text(): text = '' for line in sys.stdin: text += line return text # def read_text(): # text = '' # next_line = input() # while len(next_line) > 0: # text += next_line + '\n' # next_line = input() # return text def matching_word(word, bor, symbol, search): if symbol in search: search = search[symbol] word_found = 'size' in search and search['size'] == 1 return get_match(word, bor) if word_found else 0, search return 0, () def contains_word(word, bor): search = bor for symbol in word: if symbol in search: search = search[symbol] else: return False words_left = 0 for key, value in search.items(): if key == 'size': continue words_left += value['size'] return search['size'] - words_left == 1 def get_match(word, bor): search = bor match = '' for symbol in word: match += symbol search = search[symbol] while len(search.keys()) == 2: symbol = next(filter(lambda item: item != 'size', search.keys())) match += symbol search = search[symbol] return match def add_to_bor(word, bor): search = bor for symbol in word: if symbol not in search: search[symbol] = dict([('size', 0)]) search = search[symbol] search['size'] += 1 def replace_index(text, start, match): index = start for symbol in match: if symbol == text[index]: index += 1 else: return -1 return start + len(match) - 1 def get_updated_search(word, bor): search = bor for symbol in word: search = search[symbol] return search text = list(read_text()) text_size = len(text) bor = dict() separators = ['.', ',', '?', '!', '\'', '-', ' ', '\n'] typed = 0 index = 0 word = '' search = bor match = 0 while index < text_size: symbol = text[index] typed += 1 if symbol not in separators: word += symbol if match != -1: match, search = matching_word(word, bor, symbol, search) if match != 0 and match != word: new_index = replace_index(text, index + 1 - len(word), match) if new_index != -1: typed += 1 index = new_index word = match search = get_updated_search(word, bor) else: match = -1 elif len(word) > 0: if not contains_word(word, bor): add_to_bor(word, bor) search = bor word = '' match = 0 index += 1 print(typed) ```
97,566
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Arcady is a copywriter. His today's task is to type up an already well-designed story using his favorite text editor. Arcady types words, punctuation signs and spaces one after another. Each letter and each sign (including line feed) requires one keyboard click in order to be printed. Moreover, when Arcady has a non-empty prefix of some word on the screen, the editor proposes a possible autocompletion for this word, more precisely one of the already printed words such that its prefix matches the currently printed prefix if this word is unique. For example, if Arcady has already printed «codeforces», «coding» and «codeforces» once again, then there will be no autocompletion attempt for «cod», but if he proceeds with «code», the editor will propose «codeforces». With a single click Arcady can follow the editor's proposal, i.e. to transform the current prefix to it. Note that no additional symbols are printed after the autocompletion (no spaces, line feeds, etc). What is the minimum number of keyboard clicks Arcady has to perform to print the entire text, if he is not allowed to move the cursor or erase the already printed symbols? A word here is a contiguous sequence of latin letters bordered by spaces, punctuation signs and line/text beginnings/ends. Arcady uses only lowercase letters. For example, there are 20 words in «it's well-known that tic-tac-toe is a paper-and-pencil game for two players, x and o.». Input The only line contains Arcady's text, consisting only of lowercase latin letters, spaces, line feeds and the following punctuation signs: «.», «,», «?», «!», «'» and «-». The total amount of symbols doesn't exceed 3·105. It's guaranteed that all lines are non-empty. Output Print a single integer — the minimum number of clicks. Examples Input snow affects sports such as skiing, snowboarding, and snowmachine travel. snowboarding is a recreational activity and olympic and paralympic sport. Output 141 Input 'co-co-co, codeforces?!' Output 25 Input thun-thun-thunder, thunder, thunder thunder, thun-, thunder thun-thun-thunder, thunder thunder, feel the thunder lightning then the thunder thunder, feel the thunder lightning then the thunder thunder, thunder Output 183 Note In sample case one it's optimal to use autocompletion for the first instance of «snowboarding» after typing up «sn» and for the second instance of «snowboarding» after typing up «snowb». This will save 7 clicks. In sample case two it doesn't matter whether to use autocompletion or not. Submitted Solution: ``` def main(file = None): text = "" part = input() while part: text += part +'\n' try: part = input() except EOFError: part = "" total = len(text) word = "" for l in text: if l.isalpha(): word += l elif word: short = shortcut(word) total -= short update(word) word = "" return total prev = set() def shortcut(word): for i in range(1, len(word)-2): occ = 0 part = word[:i] for auto in prev: if auto.startswith(part) and auto != part: occ += 1 latest = auto if occ == 1 and word.startswith(latest): return len(latest)-len(part)-1 return 0 def update(word): prev.add(word) if __name__ == '__main__': print(main()) ``` No
97,567
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Arcady is a copywriter. His today's task is to type up an already well-designed story using his favorite text editor. Arcady types words, punctuation signs and spaces one after another. Each letter and each sign (including line feed) requires one keyboard click in order to be printed. Moreover, when Arcady has a non-empty prefix of some word on the screen, the editor proposes a possible autocompletion for this word, more precisely one of the already printed words such that its prefix matches the currently printed prefix if this word is unique. For example, if Arcady has already printed «codeforces», «coding» and «codeforces» once again, then there will be no autocompletion attempt for «cod», but if he proceeds with «code», the editor will propose «codeforces». With a single click Arcady can follow the editor's proposal, i.e. to transform the current prefix to it. Note that no additional symbols are printed after the autocompletion (no spaces, line feeds, etc). What is the minimum number of keyboard clicks Arcady has to perform to print the entire text, if he is not allowed to move the cursor or erase the already printed symbols? A word here is a contiguous sequence of latin letters bordered by spaces, punctuation signs and line/text beginnings/ends. Arcady uses only lowercase letters. For example, there are 20 words in «it's well-known that tic-tac-toe is a paper-and-pencil game for two players, x and o.». Input The only line contains Arcady's text, consisting only of lowercase latin letters, spaces, line feeds and the following punctuation signs: «.», «,», «?», «!», «'» and «-». The total amount of symbols doesn't exceed 3·105. It's guaranteed that all lines are non-empty. Output Print a single integer — the minimum number of clicks. Examples Input snow affects sports such as skiing, snowboarding, and snowmachine travel. snowboarding is a recreational activity and olympic and paralympic sport. Output 141 Input 'co-co-co, codeforces?!' Output 25 Input thun-thun-thunder, thunder, thunder thunder, thun-, thunder thun-thun-thunder, thunder thunder, feel the thunder lightning then the thunder thunder, feel the thunder lightning then the thunder thunder, thunder Output 183 Note In sample case one it's optimal to use autocompletion for the first instance of «snowboarding» after typing up «sn» and for the second instance of «snowboarding» after typing up «snowb». This will save 7 clicks. In sample case two it doesn't matter whether to use autocompletion or not. Submitted Solution: ``` import fileinput words_stack = dict() words = list() def get_similar(word): was_new = False end = False count = 0 need_write = 0 new_word_count = 0 for i in range(1,len(word) + 1): little_word = word[0:i] if not words_stack.get(little_word): if i == len(word): words_stack[little_word] = 1 else: words_stack[little_word] = 2 new_word_count += 1 if not was_new: for j in range(1, i): little_word = word[0:j] words_stack[little_word] = 3 was_new = True else: number_word = words_stack[little_word] if number_word == 1: end = True count += 1 elif number_word == 2: count += 1 else: need_write += 1 if end: return (new_word_count + 2 + need_write) if count >= 2 else (new_word_count + count + need_write) else: return new_word_count + count + need_write answer = 0 word = str("") prep = str("") for line in fileinput.input(): for char in list(line): if char in ["'", ',', ' ', '\n', '.', '-', '!', '?']: plus = get_similar(word) answer += plus word = "" prep += char else: plus = get_similar(prep) answer += plus prep = "" word += str(char) answer += get_similar(prep) answer += get_similar(word) print(answer) ``` No
97,568
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Arcady is a copywriter. His today's task is to type up an already well-designed story using his favorite text editor. Arcady types words, punctuation signs and spaces one after another. Each letter and each sign (including line feed) requires one keyboard click in order to be printed. Moreover, when Arcady has a non-empty prefix of some word on the screen, the editor proposes a possible autocompletion for this word, more precisely one of the already printed words such that its prefix matches the currently printed prefix if this word is unique. For example, if Arcady has already printed «codeforces», «coding» and «codeforces» once again, then there will be no autocompletion attempt for «cod», but if he proceeds with «code», the editor will propose «codeforces». With a single click Arcady can follow the editor's proposal, i.e. to transform the current prefix to it. Note that no additional symbols are printed after the autocompletion (no spaces, line feeds, etc). What is the minimum number of keyboard clicks Arcady has to perform to print the entire text, if he is not allowed to move the cursor or erase the already printed symbols? A word here is a contiguous sequence of latin letters bordered by spaces, punctuation signs and line/text beginnings/ends. Arcady uses only lowercase letters. For example, there are 20 words in «it's well-known that tic-tac-toe is a paper-and-pencil game for two players, x and o.». Input The only line contains Arcady's text, consisting only of lowercase latin letters, spaces, line feeds and the following punctuation signs: «.», «,», «?», «!», «'» and «-». The total amount of symbols doesn't exceed 3·105. It's guaranteed that all lines are non-empty. Output Print a single integer — the minimum number of clicks. Examples Input snow affects sports such as skiing, snowboarding, and snowmachine travel. snowboarding is a recreational activity and olympic and paralympic sport. Output 141 Input 'co-co-co, codeforces?!' Output 25 Input thun-thun-thunder, thunder, thunder thunder, thun-, thunder thun-thun-thunder, thunder thunder, feel the thunder lightning then the thunder thunder, feel the thunder lightning then the thunder thunder, thunder Output 183 Note In sample case one it's optimal to use autocompletion for the first instance of «snowboarding» after typing up «sn» and for the second instance of «snowboarding» after typing up «snowb». This will save 7 clicks. In sample case two it doesn't matter whether to use autocompletion or not. Submitted Solution: ``` import sys def next_word_start(str, beg): for i in range(beg, len(str)): if str[i] in punctuation: return i return len(str) def was_semi_typed(words, lookup): max_size = 0 res = "" for word in words: similarity = 0 if len(lookup) < len(word): continue for i in range(len(word)): if word[i] == lookup[i]: similarity += 1 if max_size < similarity and i == len(word) - 1: max_size = similarity res = word else: break return res prefixes = set() punctuation = ['.', ',', '?', '-', '!', '\'', ' ', '\n'] inp = sys.stdin.readlines() data = "" for lines in inp: data += lines.title().lower() words = set() non_unique_prefixes = set() result = 0 i = 0 last_word_end = -1 while i < len(data): word_ended = data[i] in punctuation if word_ended: words.add(data[last_word_end + 1 : i]) last_word_end = i # we have printed a punt mark result += 1 i += 1 else: current_prefix = data[last_word_end + 1 : i + 1] if current_prefix in non_unique_prefixes: # if it's in non unique, we need to continue typing letters result += 1 i += 1 continue if not (current_prefix in prefixes): prefixes.add(current_prefix) result += 1 i += 1 else: # seems to be we have this word. lookup front to know what the word is... next_space = next_word_start(data, last_word_end + 1) lookup = data[last_word_end + 1 : next_space] # need to know if this word is part of smth. E.g: we can suggest "test", but user printed "tested". semi_typed = was_semi_typed(words, lookup) suggestion_size = len(was_semi_typed(words, lookup)) if semi_typed in words and semi_typed != '' and current_prefix != semi_typed: result += 2 # +1 because we printed a new letter, +1 because we accept hint append = len(lookup) - suggestion_size # внутри надо удалить префиксы слова semi_typed и добавить новый # например. Мы написали слова thun, затем по букве t предлагаем ввести "thun". Если пользователь принял # подсказку и дополнил её чем-то, например, "thunder", то нельзя реагировать на t, th, thu, thun # (добавить их в список non-unique и удалить из unique(prefixes). При этом в unique добавить thund, # как новый префикс для реагирования if append > 0: for j in range(len(semi_typed)): if semi_typed[:j + 1] in prefixes: prefixes.remove(semi_typed[:j + 1]) non_unique_prefixes.add(semi_typed[:j + 1]) # добавляем все уникальные префиксы нашего слова for k in range(len(lookup)): if not (lookup[:len(semi_typed) + k] in non_unique_prefixes): prefixes.add(lookup[:len(semi_typed) + k]) # добавляем наше новое слово в словарь:) words.add(lookup) result += append # problem is here. Hopefully fixed i = next_space # todo last_word_end = i else: prefixes.remove(current_prefix) non_unique_prefixes.add(current_prefix) i += 1 result += 1 print(result) ``` No
97,569
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Arcady is a copywriter. His today's task is to type up an already well-designed story using his favorite text editor. Arcady types words, punctuation signs and spaces one after another. Each letter and each sign (including line feed) requires one keyboard click in order to be printed. Moreover, when Arcady has a non-empty prefix of some word on the screen, the editor proposes a possible autocompletion for this word, more precisely one of the already printed words such that its prefix matches the currently printed prefix if this word is unique. For example, if Arcady has already printed «codeforces», «coding» and «codeforces» once again, then there will be no autocompletion attempt for «cod», but if he proceeds with «code», the editor will propose «codeforces». With a single click Arcady can follow the editor's proposal, i.e. to transform the current prefix to it. Note that no additional symbols are printed after the autocompletion (no spaces, line feeds, etc). What is the minimum number of keyboard clicks Arcady has to perform to print the entire text, if he is not allowed to move the cursor or erase the already printed symbols? A word here is a contiguous sequence of latin letters bordered by spaces, punctuation signs and line/text beginnings/ends. Arcady uses only lowercase letters. For example, there are 20 words in «it's well-known that tic-tac-toe is a paper-and-pencil game for two players, x and o.». Input The only line contains Arcady's text, consisting only of lowercase latin letters, spaces, line feeds and the following punctuation signs: «.», «,», «?», «!», «'» and «-». The total amount of symbols doesn't exceed 3·105. It's guaranteed that all lines are non-empty. Output Print a single integer — the minimum number of clicks. Examples Input snow affects sports such as skiing, snowboarding, and snowmachine travel. snowboarding is a recreational activity and olympic and paralympic sport. Output 141 Input 'co-co-co, codeforces?!' Output 25 Input thun-thun-thunder, thunder, thunder thunder, thun-, thunder thun-thun-thunder, thunder thunder, feel the thunder lightning then the thunder thunder, feel the thunder lightning then the thunder thunder, thunder Output 183 Note In sample case one it's optimal to use autocompletion for the first instance of «snowboarding» after typing up «sn» and for the second instance of «snowboarding» after typing up «snowb». This will save 7 clicks. In sample case two it doesn't matter whether to use autocompletion or not. Submitted Solution: ``` import sys def read_text(): text = '' for line in sys.stdin: text += line return text def matching_word(word, bor, symbol, search): if symbol in search: search = search[symbol] word_found = 'size' in search and search['size'] == 1 return get_match(word, bor) if word_found else 0, search return 0, () def contains_word(word, bor): search = bor for symbol in word: if symbol in search: search = search[symbol] else: return False return len(search.keys()) > 0 def get_match(word, bor): search = bor match = '' for symbol in word: match += symbol search = search[symbol] while len(search.keys()) == 2: symbol = next(filter(lambda item: item != 'size', search.keys())) match += symbol search = search[symbol] return match def add_to_bor(word, bor): search = bor for symbol in word: if symbol not in search: search[symbol] = dict([('size', 0)]) search = search[symbol] search['size'] += 1 def replace_index(text, start, match): index = start for symbol in match: if symbol == text[index]: index += 1 else: return -1 return start + len(match) - 1 text = list(read_text()) text_size = len(text) bor = dict() separators = ['.', ',', '?', '!', '\'', '-', ' ', '\n'] typed = 0 index = 0 word = '' search = bor while index < text_size: symbol = text[index] typed += 1 if symbol not in separators: word += symbol match, search = matching_word(word, bor, symbol, search) if match != 0 and match != word: new_index = replace_index(text, index + 1 - len(word), match) if new_index != -1: typed += 1 index = new_index word = match elif len(word) > 0: if not contains_word(word, bor): add_to_bor(word, bor) search = bor word = '' index += 1 print(typed) ``` No
97,570
Provide tags and a correct Python 3 solution for this coding contest problem. The stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct. Two rebel spies have provided her with the maps of the solar system. Each map is an N × N grid, where each cell is either occupied by a star or empty. To see whether the information is correct, Heidi needs to know whether the two maps are of the same solar system, or if possibly one of the spies is actually an Empire double agent, feeding her false information. Unfortunately, spies may have accidentally rotated a map by 90, 180, or 270 degrees, or flipped it along the vertical or the horizontal axis, before delivering it to Heidi. If Heidi can rotate or flip the maps so that two of them become identical, then those maps are of the same solar system. Otherwise, there are traitors in the Rebel ranks! Help Heidi find out. Input The first line of the input contains one number N (1 ≤ N ≤ 10) – the dimension of each map. Next N lines each contain N characters, depicting the first map: 'X' indicates a star, while 'O' indicates an empty quadrant of space. Next N lines each contain N characters, depicting the second map in the same format. Output The only line of output should contain the word Yes if the maps are identical, or No if it is impossible to match them by performing rotations and translations. Examples Input 4 XOOO XXOO OOOO XXXX XOOO XOOO XOXO XOXX Output Yes Input 2 XX OO XO OX Output No Note In the first test, you can match the first map to the second map by first flipping the first map along the vertical axis, and then by rotating it 90 degrees clockwise. Tags: implementation Correct Solution: ``` N = int(input()) first = [] second = [] for i in range(N): first.append([s for s in input()]) for i in range(N): second.append([s for s in input()]) def rotate_90(matrix): return list(zip(*matrix[::-1])) def flip(matrix): return matrix[::-1] def compare_matrices(first, second): for i in range(N): for j in range(N): if first[i][j] != second[i][j]: return False return True def wrap(first, second): if compare_matrices(first, second) == True: return 'Yes' hold_first = first[::] for _ in range(3): first = rotate_90(first) if compare_matrices(first, second) == True: return 'Yes' first = hold_first first = flip(first) if compare_matrices(first, second) == True: return 'Yes' for _ in range(3): first = rotate_90(first) if compare_matrices(first, second) == True: return 'Yes' return 'No' print(wrap(first, second)) ```
97,571
Provide tags and a correct Python 3 solution for this coding contest problem. The stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct. Two rebel spies have provided her with the maps of the solar system. Each map is an N × N grid, where each cell is either occupied by a star or empty. To see whether the information is correct, Heidi needs to know whether the two maps are of the same solar system, or if possibly one of the spies is actually an Empire double agent, feeding her false information. Unfortunately, spies may have accidentally rotated a map by 90, 180, or 270 degrees, or flipped it along the vertical or the horizontal axis, before delivering it to Heidi. If Heidi can rotate or flip the maps so that two of them become identical, then those maps are of the same solar system. Otherwise, there are traitors in the Rebel ranks! Help Heidi find out. Input The first line of the input contains one number N (1 ≤ N ≤ 10) – the dimension of each map. Next N lines each contain N characters, depicting the first map: 'X' indicates a star, while 'O' indicates an empty quadrant of space. Next N lines each contain N characters, depicting the second map in the same format. Output The only line of output should contain the word Yes if the maps are identical, or No if it is impossible to match them by performing rotations and translations. Examples Input 4 XOOO XXOO OOOO XXXX XOOO XOOO XOXO XOXX Output Yes Input 2 XX OO XO OX Output No Note In the first test, you can match the first map to the second map by first flipping the first map along the vertical axis, and then by rotating it 90 degrees clockwise. Tags: implementation Correct Solution: ``` N = int(input()) s1 = [list(input()) for i in range(N)] s2 = [list(input()) for i in range(N)] def rotate(s): ret = [[None for i in range(N)] for j in range(N)] for i in range(N): for j in range(N): ret[i][j] = s[j][N-1-i] return ret def v_mirror(s): return list(reversed(s)) def h_mirror(s): return [list(reversed(row)) for row in s] def solve(): global s1 for i in range(4): if s1 == s2: return True if v_mirror(s1) == s2: return True if h_mirror(s1) == s2: return True if v_mirror(h_mirror(s1)) == s2: return True s1 = rotate(s1) return False print('Yes' if solve() else 'No') ```
97,572
Provide tags and a correct Python 3 solution for this coding contest problem. The stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct. Two rebel spies have provided her with the maps of the solar system. Each map is an N × N grid, where each cell is either occupied by a star or empty. To see whether the information is correct, Heidi needs to know whether the two maps are of the same solar system, or if possibly one of the spies is actually an Empire double agent, feeding her false information. Unfortunately, spies may have accidentally rotated a map by 90, 180, or 270 degrees, or flipped it along the vertical or the horizontal axis, before delivering it to Heidi. If Heidi can rotate or flip the maps so that two of them become identical, then those maps are of the same solar system. Otherwise, there are traitors in the Rebel ranks! Help Heidi find out. Input The first line of the input contains one number N (1 ≤ N ≤ 10) – the dimension of each map. Next N lines each contain N characters, depicting the first map: 'X' indicates a star, while 'O' indicates an empty quadrant of space. Next N lines each contain N characters, depicting the second map in the same format. Output The only line of output should contain the word Yes if the maps are identical, or No if it is impossible to match them by performing rotations and translations. Examples Input 4 XOOO XXOO OOOO XXXX XOOO XOOO XOXO XOXX Output Yes Input 2 XX OO XO OX Output No Note In the first test, you can match the first map to the second map by first flipping the first map along the vertical axis, and then by rotating it 90 degrees clockwise. Tags: implementation Correct Solution: ``` import copy n = int(input()) flg=0 mat1 = [] mat2 = [] mats = [] for i in range(0, n): mat1.append(tuple(input().strip())) for i in range(0, n): mat2.append(tuple(input().strip())) mats.append(mat2) matu = copy.copy(mat2) matv = copy.copy(mat2) matv = list(zip(*matv)) mats.append(matv) mattem = copy.copy(matu) for i in range(0, 3): mattem = list(zip(*list(reversed(mattem)))) mats.append(mattem) mattem = copy.copy(matv) for i in range(0, 3): mattem = list(zip(*list(reversed(mattem)))) mats.append(mattem) flg = 0 for cmat in mats: flg2 = 1 for ri in range(0, n): if cmat[ri]!=mat1[ri]: flg2=0 break if flg2==1: flg=1 break if flg==1: print("Yes") else: print("No") ```
97,573
Provide tags and a correct Python 3 solution for this coding contest problem. The stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct. Two rebel spies have provided her with the maps of the solar system. Each map is an N × N grid, where each cell is either occupied by a star or empty. To see whether the information is correct, Heidi needs to know whether the two maps are of the same solar system, or if possibly one of the spies is actually an Empire double agent, feeding her false information. Unfortunately, spies may have accidentally rotated a map by 90, 180, or 270 degrees, or flipped it along the vertical or the horizontal axis, before delivering it to Heidi. If Heidi can rotate or flip the maps so that two of them become identical, then those maps are of the same solar system. Otherwise, there are traitors in the Rebel ranks! Help Heidi find out. Input The first line of the input contains one number N (1 ≤ N ≤ 10) – the dimension of each map. Next N lines each contain N characters, depicting the first map: 'X' indicates a star, while 'O' indicates an empty quadrant of space. Next N lines each contain N characters, depicting the second map in the same format. Output The only line of output should contain the word Yes if the maps are identical, or No if it is impossible to match them by performing rotations and translations. Examples Input 4 XOOO XXOO OOOO XXXX XOOO XOOO XOXO XOXX Output Yes Input 2 XX OO XO OX Output No Note In the first test, you can match the first map to the second map by first flipping the first map along the vertical axis, and then by rotating it 90 degrees clockwise. Tags: implementation Correct Solution: ``` n=int(input()) ns=[] for i in range(n): s=input() ns.append(s) ns2=[] for i in range(n): s=input() ns2.append(s) def rotate(i,j): return j,n-1-i def flip(i,j): return j,i def main(): same=True for i in range(n): # 0 for j in range(n): if ns[i][j]!=ns2[i][j]: same=False break if same==False: break if same: return True same=True for i in range(n): # 1 for j in range(n): a, b = rotate(i, j) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same=True for i in range(n): # 2 for j in range(n): a, b = rotate(i, j) a, b = rotate(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same=True for i in range(n): for j in range(n): # 3 a, b = rotate(i, j) a, b = rotate(a, b) a, b = rotate(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same=True for i in range(n): # 0 for j in range(n): a,b=flip(i,j) if ns[a][b]!=ns2[i][j]: same=False break if same==False: break if same: return True same=True for i in range(n): # 1 for j in range(n): a, b = rotate(i, j) a, b = flip(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same=True for i in range(n): # 2 for j in range(n): a, b = rotate(i, j) a, b = rotate(a, b) a, b = flip(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True same=True for i in range(n): for j in range(n): # 3 a, b = rotate(i, j) a, b = rotate(a, b) a, b = rotate(a, b) a, b = flip(a, b) if ns[i][j] != ns2[a][b]: same = False break if same == False: break if same: return True else: return False if main(): print('Yes') else: print('No') ```
97,574
Provide tags and a correct Python 3 solution for this coding contest problem. The stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct. Two rebel spies have provided her with the maps of the solar system. Each map is an N × N grid, where each cell is either occupied by a star or empty. To see whether the information is correct, Heidi needs to know whether the two maps are of the same solar system, or if possibly one of the spies is actually an Empire double agent, feeding her false information. Unfortunately, spies may have accidentally rotated a map by 90, 180, or 270 degrees, or flipped it along the vertical or the horizontal axis, before delivering it to Heidi. If Heidi can rotate or flip the maps so that two of them become identical, then those maps are of the same solar system. Otherwise, there are traitors in the Rebel ranks! Help Heidi find out. Input The first line of the input contains one number N (1 ≤ N ≤ 10) – the dimension of each map. Next N lines each contain N characters, depicting the first map: 'X' indicates a star, while 'O' indicates an empty quadrant of space. Next N lines each contain N characters, depicting the second map in the same format. Output The only line of output should contain the word Yes if the maps are identical, or No if it is impossible to match them by performing rotations and translations. Examples Input 4 XOOO XXOO OOOO XXXX XOOO XOOO XOXO XOXX Output Yes Input 2 XX OO XO OX Output No Note In the first test, you can match the first map to the second map by first flipping the first map along the vertical axis, and then by rotating it 90 degrees clockwise. Tags: implementation Correct Solution: ``` N = int(input()) m1 = [] m2 = [] ms = [] for n in range(N): m1.append(input()) for n in range(N): m2.append(input()) ms = [ m2, [x[::-1] for x in m2], [x for x in reversed(m2)], ] a = [] for m in ms: a.append(m) a.append([x[::-1] for x in reversed(m)]) a.append([''.join(m[j][i] for j in range(N - 1, -1, -1)) for i in range(N)]) a.append([''.join(m[j][i] for j in range(N)) for i in range(N - 1, -1, -1)]) ms = a print(['NO', 'YES'][m1 in ms]) ```
97,575
Provide tags and a correct Python 3 solution for this coding contest problem. The stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct. Two rebel spies have provided her with the maps of the solar system. Each map is an N × N grid, where each cell is either occupied by a star or empty. To see whether the information is correct, Heidi needs to know whether the two maps are of the same solar system, or if possibly one of the spies is actually an Empire double agent, feeding her false information. Unfortunately, spies may have accidentally rotated a map by 90, 180, or 270 degrees, or flipped it along the vertical or the horizontal axis, before delivering it to Heidi. If Heidi can rotate or flip the maps so that two of them become identical, then those maps are of the same solar system. Otherwise, there are traitors in the Rebel ranks! Help Heidi find out. Input The first line of the input contains one number N (1 ≤ N ≤ 10) – the dimension of each map. Next N lines each contain N characters, depicting the first map: 'X' indicates a star, while 'O' indicates an empty quadrant of space. Next N lines each contain N characters, depicting the second map in the same format. Output The only line of output should contain the word Yes if the maps are identical, or No if it is impossible to match them by performing rotations and translations. Examples Input 4 XOOO XXOO OOOO XXXX XOOO XOOO XOXO XOXX Output Yes Input 2 XX OO XO OX Output No Note In the first test, you can match the first map to the second map by first flipping the first map along the vertical axis, and then by rotating it 90 degrees clockwise. Tags: implementation Correct Solution: ``` #!/usr/bin/python3 import copy def rotate90(n, f): return [[f[n - j - 1][i] for j in range(n)] for i in range(n)] def fliphor(n, f): return [[f[i][n - j - 1] for j in range(n)] for i in range(n)] def flipver(n, f): return [[f[n - i - 1][j] for j in range(n)] for i in range(n)] def eq(n, f, g): for i in range(n): for j in range(n): if f[i][j] != g[i][j]: return False return True n = int(input()) f = [list(input()) for i in range(n)] g = [list(input()) for i in range(n)] for doflipv in range(2): for dofliph in range(2): for nrot in range(4): h = copy.deepcopy(f) if dofliph == 1: h = fliphor(n, h) if doflipv == 1: h = flipver(n, h) for i in range(nrot): h = rotate90(n, h) if eq(n, h, g): print("Yes") exit(0) print("No") ```
97,576
Provide tags and a correct Python 3 solution for this coding contest problem. The stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct. Two rebel spies have provided her with the maps of the solar system. Each map is an N × N grid, where each cell is either occupied by a star or empty. To see whether the information is correct, Heidi needs to know whether the two maps are of the same solar system, or if possibly one of the spies is actually an Empire double agent, feeding her false information. Unfortunately, spies may have accidentally rotated a map by 90, 180, or 270 degrees, or flipped it along the vertical or the horizontal axis, before delivering it to Heidi. If Heidi can rotate or flip the maps so that two of them become identical, then those maps are of the same solar system. Otherwise, there are traitors in the Rebel ranks! Help Heidi find out. Input The first line of the input contains one number N (1 ≤ N ≤ 10) – the dimension of each map. Next N lines each contain N characters, depicting the first map: 'X' indicates a star, while 'O' indicates an empty quadrant of space. Next N lines each contain N characters, depicting the second map in the same format. Output The only line of output should contain the word Yes if the maps are identical, or No if it is impossible to match them by performing rotations and translations. Examples Input 4 XOOO XXOO OOOO XXXX XOOO XOOO XOXO XOXX Output Yes Input 2 XX OO XO OX Output No Note In the first test, you can match the first map to the second map by first flipping the first map along the vertical axis, and then by rotating it 90 degrees clockwise. Tags: implementation Correct Solution: ``` from collections import deque, defaultdict, Counter from itertools import product, groupby, permutations, combinations from math import gcd, floor, inf, log2, sqrt, log10 from bisect import bisect_right, bisect_left from statistics import mode from string import ascii_uppercase cases = int(input()) matrix1 = [] for _ in range(cases): matrix1.append(list(input())) matrix2 = [] for _ in range(cases): matrix2.append(list(input())) def transpose(matrix): return [list(x) for x in zip(*matrix)] def reverse_row(matrix): return matrix[::-1] def reverse_column(matrix): return [x[::-1] for x in matrix] def rotate_90(matrix): """this is counterclockwise, which is same as 270 clockwise""" return reverse_row(transpose(matrix)) def rotate_180(matrix): """same for both clockwise and counterclockwise""" return reverse_row(reverse_column(matrix)) def rotate_270(matrix): """this is counterclockwise, which is same as 90 clockwise""" return reverse_column(transpose(matrix)) if matrix1 == matrix2 or matrix1 == reverse_row(matrix2) or matrix1 == reverse_column(matrix2) \ or matrix1 == rotate_90(matrix2) or matrix1 == rotate_180(matrix2) or matrix1 == rotate_270(matrix2): print("Yes") exit() matrix2 = reverse_row(matrix2) if matrix1 == matrix2 or matrix1 == reverse_row(matrix2) or matrix1 == reverse_column(matrix2) \ or matrix1 == rotate_90(matrix2) or matrix1 == rotate_180(matrix2) or matrix1 == rotate_270(matrix2): print("Yes") exit() matrix2 = reverse_column(matrix2) if matrix1 == matrix2 or matrix1 == reverse_row(matrix2) or matrix1 == reverse_column(matrix2) \ or matrix1 == rotate_90(matrix2) or matrix1 == rotate_180(matrix2) or matrix1 == rotate_270(matrix2): print("Yes") exit() matrix2 = transpose(matrix2) if matrix1 == matrix2 or matrix1 == reverse_row(matrix2) or matrix1 == reverse_column(matrix2) \ or matrix1 == rotate_90(matrix2) or matrix1 == rotate_180(matrix2) or matrix1 == rotate_270(matrix2): print("Yes") exit() else: print("No") ```
97,577
Provide tags and a correct Python 3 solution for this coding contest problem. The stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct. Two rebel spies have provided her with the maps of the solar system. Each map is an N × N grid, where each cell is either occupied by a star or empty. To see whether the information is correct, Heidi needs to know whether the two maps are of the same solar system, or if possibly one of the spies is actually an Empire double agent, feeding her false information. Unfortunately, spies may have accidentally rotated a map by 90, 180, or 270 degrees, or flipped it along the vertical or the horizontal axis, before delivering it to Heidi. If Heidi can rotate or flip the maps so that two of them become identical, then those maps are of the same solar system. Otherwise, there are traitors in the Rebel ranks! Help Heidi find out. Input The first line of the input contains one number N (1 ≤ N ≤ 10) – the dimension of each map. Next N lines each contain N characters, depicting the first map: 'X' indicates a star, while 'O' indicates an empty quadrant of space. Next N lines each contain N characters, depicting the second map in the same format. Output The only line of output should contain the word Yes if the maps are identical, or No if it is impossible to match them by performing rotations and translations. Examples Input 4 XOOO XXOO OOOO XXXX XOOO XOOO XOXO XOXX Output Yes Input 2 XX OO XO OX Output No Note In the first test, you can match the first map to the second map by first flipping the first map along the vertical axis, and then by rotating it 90 degrees clockwise. Tags: implementation Correct Solution: ``` def check(x, y): return ''.join([''.join(s) for s in x]) == ''.join([''.join(s) for s in y]) re = int(input()) a = [list(input()) for i in range(re)] b = [list(input()) for i in range(re)] for i in range(4): for j in range(2): if check(a, b): print('Yes') exit(0) b = b[::-1] for j in range(2): if check(a, b): print('Yes') exit(0) b = [s[::-1] for s in b] c = [['' for t in range(re)] for u in range(re)] for t in range(re): for u in range(re): c[t][u] = b[u][re - t - 1] b = c[:] if check(a, b): print('Yes') exit(0) print('No') ```
97,578
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct. Two rebel spies have provided her with the maps of the solar system. Each map is an N × N grid, where each cell is either occupied by a star or empty. To see whether the information is correct, Heidi needs to know whether the two maps are of the same solar system, or if possibly one of the spies is actually an Empire double agent, feeding her false information. Unfortunately, spies may have accidentally rotated a map by 90, 180, or 270 degrees, or flipped it along the vertical or the horizontal axis, before delivering it to Heidi. If Heidi can rotate or flip the maps so that two of them become identical, then those maps are of the same solar system. Otherwise, there are traitors in the Rebel ranks! Help Heidi find out. Input The first line of the input contains one number N (1 ≤ N ≤ 10) – the dimension of each map. Next N lines each contain N characters, depicting the first map: 'X' indicates a star, while 'O' indicates an empty quadrant of space. Next N lines each contain N characters, depicting the second map in the same format. Output The only line of output should contain the word Yes if the maps are identical, or No if it is impossible to match them by performing rotations and translations. Examples Input 4 XOOO XXOO OOOO XXXX XOOO XOOO XOXO XOXX Output Yes Input 2 XX OO XO OX Output No Note In the first test, you can match the first map to the second map by first flipping the first map along the vertical axis, and then by rotating it 90 degrees clockwise. Submitted Solution: ``` from sys import stdin n = int(stdin.readline()) def eq(m1, m2): for i in range(n): if m1[i] != m2[i]: return False return True def fleq(m1, m2): return eq(m1, m2) or eq(m1, fliph(m2)) or eq(m1, flipv(m2)) def fliph(m): return [row[::-1] for row in m] def flipv(m): return m[::-1] def rot(m): mr = ['' for _ in range(n)] for i in range(n): x = '' for j in range(n): x = x + m[j][n-i-1] mr[i] = x return mr u = [stdin.readline()[:-1] for _ in range(n)] v = [stdin.readline()[:-1] for _ in range(n)] v90 = rot(v) v180 = rot(v90) v270 = rot(v180) if fleq(u, v) or fleq(u, v90) or fleq(u, v180) or fleq(u, v270): print('Yes') else: print('No') ``` Yes
97,579
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct. Two rebel spies have provided her with the maps of the solar system. Each map is an N × N grid, where each cell is either occupied by a star or empty. To see whether the information is correct, Heidi needs to know whether the two maps are of the same solar system, or if possibly one of the spies is actually an Empire double agent, feeding her false information. Unfortunately, spies may have accidentally rotated a map by 90, 180, or 270 degrees, or flipped it along the vertical or the horizontal axis, before delivering it to Heidi. If Heidi can rotate or flip the maps so that two of them become identical, then those maps are of the same solar system. Otherwise, there are traitors in the Rebel ranks! Help Heidi find out. Input The first line of the input contains one number N (1 ≤ N ≤ 10) – the dimension of each map. Next N lines each contain N characters, depicting the first map: 'X' indicates a star, while 'O' indicates an empty quadrant of space. Next N lines each contain N characters, depicting the second map in the same format. Output The only line of output should contain the word Yes if the maps are identical, or No if it is impossible to match them by performing rotations and translations. Examples Input 4 XOOO XXOO OOOO XXXX XOOO XOOO XOXO XOXX Output Yes Input 2 XX OO XO OX Output No Note In the first test, you can match the first map to the second map by first flipping the first map along the vertical axis, and then by rotating it 90 degrees clockwise. Submitted Solution: ``` N = int(input()) map1 = [] map2 = [] for _ in range(N): map1 += [input()] for _ in range(N): map2 += [input()] equal1 = True equal2 = True equal3 = True equal4 = True equal5 = True equal6 = True equal7 = True equal8 = True for i in range(N): for j in range(N): if map1[i][j] != map2[i][j]: equal1 = False if map1[i][j] != map2[j][N - i - 1]: equal2 = False if map1[i][j] != map2[N - i - 1][N - j - 1]: equal3 = False if map1[i][j] != map2[N - j - 1][N - i - 1]: equal4 = False if map1[i][j] != map2[i][N - j - 1]: equal5 = False if map1[i][j] != map2[N - i - 1][j]: equal6 = False if map1[i][j] != map2[N - j - 1][i]: equal7 = False if map1[i][j] != map2[j][i]: equal8 = False if equal1 or equal2 or equal3 or equal4 or equal5 or equal6 or equal7 or equal8: print('yes') else: print('no') ``` Yes
97,580
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct. Two rebel spies have provided her with the maps of the solar system. Each map is an N × N grid, where each cell is either occupied by a star or empty. To see whether the information is correct, Heidi needs to know whether the two maps are of the same solar system, or if possibly one of the spies is actually an Empire double agent, feeding her false information. Unfortunately, spies may have accidentally rotated a map by 90, 180, or 270 degrees, or flipped it along the vertical or the horizontal axis, before delivering it to Heidi. If Heidi can rotate or flip the maps so that two of them become identical, then those maps are of the same solar system. Otherwise, there are traitors in the Rebel ranks! Help Heidi find out. Input The first line of the input contains one number N (1 ≤ N ≤ 10) – the dimension of each map. Next N lines each contain N characters, depicting the first map: 'X' indicates a star, while 'O' indicates an empty quadrant of space. Next N lines each contain N characters, depicting the second map in the same format. Output The only line of output should contain the word Yes if the maps are identical, or No if it is impossible to match them by performing rotations and translations. Examples Input 4 XOOO XXOO OOOO XXXX XOOO XOOO XOXO XOXX Output Yes Input 2 XX OO XO OX Output No Note In the first test, you can match the first map to the second map by first flipping the first map along the vertical axis, and then by rotating it 90 degrees clockwise. Submitted Solution: ``` n=int(input()) a=[] b=[] for i in range(n): a.append(input()) for i in range(n): b.append(input()) def h(d): c=[] for i in range(n): c.append(d[n-i-1]) return c def r(d): c=[] for i in range(n): temp="" for j in range(n): temp+=d[j][n-i-1] c.append(temp) return c yes=0 for i in range(4): if a==b: print('YES') yes=1 break a=r(a) if yes==0: a=h(a) for i in range(4): if a==b: print('YES') yes=1 break a=r(a) if yes==0: print('NO') ``` Yes
97,581
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct. Two rebel spies have provided her with the maps of the solar system. Each map is an N × N grid, where each cell is either occupied by a star or empty. To see whether the information is correct, Heidi needs to know whether the two maps are of the same solar system, or if possibly one of the spies is actually an Empire double agent, feeding her false information. Unfortunately, spies may have accidentally rotated a map by 90, 180, or 270 degrees, or flipped it along the vertical or the horizontal axis, before delivering it to Heidi. If Heidi can rotate or flip the maps so that two of them become identical, then those maps are of the same solar system. Otherwise, there are traitors in the Rebel ranks! Help Heidi find out. Input The first line of the input contains one number N (1 ≤ N ≤ 10) – the dimension of each map. Next N lines each contain N characters, depicting the first map: 'X' indicates a star, while 'O' indicates an empty quadrant of space. Next N lines each contain N characters, depicting the second map in the same format. Output The only line of output should contain the word Yes if the maps are identical, or No if it is impossible to match them by performing rotations and translations. Examples Input 4 XOOO XXOO OOOO XXXX XOOO XOOO XOXO XOXX Output Yes Input 2 XX OO XO OX Output No Note In the first test, you can match the first map to the second map by first flipping the first map along the vertical axis, and then by rotating it 90 degrees clockwise. Submitted Solution: ``` def solve(board): n=len(board) ans=0 for i in range(n): for j in range(n): if board[i][j] is 'X': ans+=2**(i*n+j) return ans def reverse_array(arr): for i in range(len(arr)): arr[i].reverse() def rotate(matrix, degree): if degree == 0: return matrix elif degree > 0: return rotate(zip(*matrix[::-1]), degree-90) else: return rotate(zip(*matrix)[::-1], degree+90) def make_list(board): board=list(board) arr=[] for i in range(len(list(board))): arr.append(list(board[i])) return arr def add_rotations(board,st): for i in range(4): st.add(solve(board)) reverse_array(board) st.add(solve(board)) reverse_array(board) board=make_list(rotate(board, 90)) n=int(input()) arr1=[] arr2=[] for _ in range(n): arr1.append(list(input().strip())) for _ in range(n): arr2.append(list(input().strip())) s=set() s.add(solve(arr1)) add_rotations(arr1,s) l1=len(s) #print(s,arr1,arr2) s.add(solve(arr2)) add_rotations(arr2,s) #print(s) l2=len(s) if l1==l2: print("Yes") else: print("No") ``` Yes
97,582
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct. Two rebel spies have provided her with the maps of the solar system. Each map is an N × N grid, where each cell is either occupied by a star or empty. To see whether the information is correct, Heidi needs to know whether the two maps are of the same solar system, or if possibly one of the spies is actually an Empire double agent, feeding her false information. Unfortunately, spies may have accidentally rotated a map by 90, 180, or 270 degrees, or flipped it along the vertical or the horizontal axis, before delivering it to Heidi. If Heidi can rotate or flip the maps so that two of them become identical, then those maps are of the same solar system. Otherwise, there are traitors in the Rebel ranks! Help Heidi find out. Input The first line of the input contains one number N (1 ≤ N ≤ 10) – the dimension of each map. Next N lines each contain N characters, depicting the first map: 'X' indicates a star, while 'O' indicates an empty quadrant of space. Next N lines each contain N characters, depicting the second map in the same format. Output The only line of output should contain the word Yes if the maps are identical, or No if it is impossible to match them by performing rotations and translations. Examples Input 4 XOOO XXOO OOOO XXXX XOOO XOOO XOXO XOXX Output Yes Input 2 XX OO XO OX Output No Note In the first test, you can match the first map to the second map by first flipping the first map along the vertical axis, and then by rotating it 90 degrees clockwise. Submitted Solution: ``` n = int(input()) def rot(l): return [list(reversed(x)) for x in zip(*l)] def reflect_h(new_l): l = new_l for i in range(len(l)): o = len(l[i]) for j in range(o // 2): temp = l[i][j] l[i][j] = l[i][o - j - 1] l[i][o - j - 1] = temp return l def reflect_v(new_l): l = new_l p = len(l) // 2 for i in range(p): temp = l[i] l[i] = l[p - i - 1] l[p - i - 1] = temp return l grid_1 = [] grid_2 = [] for i in range(n): grid_1.append([a for a in input()]) for i in range(n): grid_2.append([a for a in input()]) if grid_2 in [grid_1,rot(grid_1),rot(rot(grid_1)),rot(rot(rot(grid_1))),reflect_v(grid_1),rot(reflect_v(grid_1)),rot(rot(reflect_v(grid_1))),rot(rot(rot(reflect_v(grid_1)))),reflect_h(grid_1),rot(reflect_h(grid_1)),rot(rot(reflect_h(grid_1))),rot(rot(rot(reflect_h(grid_1))))]: print("Yes") else: print("No") print(grid_1) ``` No
97,583
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct. Two rebel spies have provided her with the maps of the solar system. Each map is an N × N grid, where each cell is either occupied by a star or empty. To see whether the information is correct, Heidi needs to know whether the two maps are of the same solar system, or if possibly one of the spies is actually an Empire double agent, feeding her false information. Unfortunately, spies may have accidentally rotated a map by 90, 180, or 270 degrees, or flipped it along the vertical or the horizontal axis, before delivering it to Heidi. If Heidi can rotate or flip the maps so that two of them become identical, then those maps are of the same solar system. Otherwise, there are traitors in the Rebel ranks! Help Heidi find out. Input The first line of the input contains one number N (1 ≤ N ≤ 10) – the dimension of each map. Next N lines each contain N characters, depicting the first map: 'X' indicates a star, while 'O' indicates an empty quadrant of space. Next N lines each contain N characters, depicting the second map in the same format. Output The only line of output should contain the word Yes if the maps are identical, or No if it is impossible to match them by performing rotations and translations. Examples Input 4 XOOO XXOO OOOO XXXX XOOO XOOO XOXO XOXX Output Yes Input 2 XX OO XO OX Output No Note In the first test, you can match the first map to the second map by first flipping the first map along the vertical axis, and then by rotating it 90 degrees clockwise. Submitted Solution: ``` ##https://codeforces.com/problemset/problem/958/A1 from copy import deepcopy def GenerateMap(n): positions = [] for i in range(0,n): positions.append([]) return positions def Rotate(a, times): rotated = [] for i in range(0,n): rotated.append([]) counter = len(a) for i in rotated: counter-=1 for j in a: i.append(j[counter]) for i in (0, times-1): counter = len(a) x = deepcopy(rotated) for j in rotated: j.clear() counter-=1 for k in x: j.append(k[counter]) return rotated def Flip(a): flipped = [] for i in reversed(a): flipped.append(i) return flipped def CheckMaps(a,b): if a == b: return "Yes" elif Rotate(a, 1) == b: return "Yes" elif Rotate(a, 2) == b: return "Yes" elif Rotate(a, 3) == b: return "Yes" elif Flip(a) == b: return "Yes" elif Flip(Rotate(a, 1)) == b: return "Yes" elif Flip(Rotate(a, 2)) == b: return "Yes" elif Flip(Rotate(a, 3)) == b: return "Yes" else: return "No" n = int(input()) a = GenerateMap(n) b = GenerateMap(n) for i in range(0,n): x = [] x[:] = input() a[i] = x for i in range(0,n): x = [] x[:] = input() b[i] = x print(CheckMaps(a,b)) ``` No
97,584
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct. Two rebel spies have provided her with the maps of the solar system. Each map is an N × N grid, where each cell is either occupied by a star or empty. To see whether the information is correct, Heidi needs to know whether the two maps are of the same solar system, or if possibly one of the spies is actually an Empire double agent, feeding her false information. Unfortunately, spies may have accidentally rotated a map by 90, 180, or 270 degrees, or flipped it along the vertical or the horizontal axis, before delivering it to Heidi. If Heidi can rotate or flip the maps so that two of them become identical, then those maps are of the same solar system. Otherwise, there are traitors in the Rebel ranks! Help Heidi find out. Input The first line of the input contains one number N (1 ≤ N ≤ 10) – the dimension of each map. Next N lines each contain N characters, depicting the first map: 'X' indicates a star, while 'O' indicates an empty quadrant of space. Next N lines each contain N characters, depicting the second map in the same format. Output The only line of output should contain the word Yes if the maps are identical, or No if it is impossible to match them by performing rotations and translations. Examples Input 4 XOOO XXOO OOOO XXXX XOOO XOOO XOXO XOXX Output Yes Input 2 XX OO XO OX Output No Note In the first test, you can match the first map to the second map by first flipping the first map along the vertical axis, and then by rotating it 90 degrees clockwise. Submitted Solution: ``` def vf(mtrx): mtrx = mtrx.copy() n = len(mtrx) for row in mtrx: for i in range(n // 2): tmp = row[n - i - 1] row[n - i - 1] = row[i] row[i] = tmp return mtrx def hf(mtrx): mtrx = mtrx.copy() n = len(mtrx) for j in range(n): for i in range(n // 2): tmp = mtrx[n - i - 1][j] mtrx[n - i - 1][j] = mtrx[i][j] mtrx[i][j] = tmp return mtrx def rotate(mtrx): n = len(mtrx) rmtrx = [] for i in range(n): row = [] for j in range(n): row.append(mtrx[j][i]) rmtrx.append(row) return rmtrx if __name__ == '__main__': n = int(input()) m1 = [] for _ in range(n): m1.append(list(input())) m2 = [] for _ in range(n): m2.append(list(input())) poss = False for i in range(4): if m1 == m2 or vf(m1) == m2 or hf(m1) == m2 or vf(hf(m1)) == m2: poss = True break m1 = rotate(m1) print('Yes' if poss else 'No') ``` No
97,585
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct. Two rebel spies have provided her with the maps of the solar system. Each map is an N × N grid, where each cell is either occupied by a star or empty. To see whether the information is correct, Heidi needs to know whether the two maps are of the same solar system, or if possibly one of the spies is actually an Empire double agent, feeding her false information. Unfortunately, spies may have accidentally rotated a map by 90, 180, or 270 degrees, or flipped it along the vertical or the horizontal axis, before delivering it to Heidi. If Heidi can rotate or flip the maps so that two of them become identical, then those maps are of the same solar system. Otherwise, there are traitors in the Rebel ranks! Help Heidi find out. Input The first line of the input contains one number N (1 ≤ N ≤ 10) – the dimension of each map. Next N lines each contain N characters, depicting the first map: 'X' indicates a star, while 'O' indicates an empty quadrant of space. Next N lines each contain N characters, depicting the second map in the same format. Output The only line of output should contain the word Yes if the maps are identical, or No if it is impossible to match them by performing rotations and translations. Examples Input 4 XOOO XXOO OOOO XXXX XOOO XOOO XOXO XOXX Output Yes Input 2 XX OO XO OX Output No Note In the first test, you can match the first map to the second map by first flipping the first map along the vertical axis, and then by rotating it 90 degrees clockwise. Submitted Solution: ``` n = int(input()) def rot(l): return [list(reversed(x)) for x in zip(*l)] def reflect_h(new_l): for g in new_l: g = g[::-1] return new_l def reflect_v(new_l): l = new_l p = len(l) // 2 for i in range(p): temp = l[i] l[i] = l[p - i - 1] l[p - i - 1] = temp return l grid_1 = [] grid_2 = [] for i in range(n): r = list(input()) print(r) grid_1.append(r) for i in range(n): grid_2.append(list(input())) v = reflect_v(grid_1) h = reflect_h(grid_1) if grid_2 in [grid_1,rot(grid_1),rot(rot(grid_1)),rot(rot(rot(grid_1))),v,rot(v),rot(rot(v)),rot(rot(rot(v))),h,rot(h),rot(rot(h)),rot(rot(rot(h)))]: print("Yes") else: print("No") ``` No
97,586
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petr is a detective in Braginsk. Somebody stole a huge amount of money from a bank and Petr is to catch him. Somebody told Petr that some luxurious car moves along the roads without stopping. Petr knows that it is the robbers who drive the car. The roads in Braginsk are one-directional and each of them connects two intersections. Petr wants to select one intersection such that if the robbers continue to drive the roads indefinitely, they will sooner or later come to that intersection. The initial position of the robbers is unknown. Find such an intersection that fits the requirements. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 10^5, 2 ≤ m ≤ 5 ⋅ 10^5) — the number of intersections and the number of directed roads in Braginsk, respectively. Each of the next m lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i) — the start and finish of the i-th directed road. It is guaranteed that the robbers can move along the roads indefinitely. Output Print a single integer k — the intersection Petr needs to choose. If there are multiple answers, print any. If there are no such intersections, print -1. Examples Input 5 6 1 2 2 3 3 1 3 4 4 5 5 3 Output 3 Input 3 3 1 2 2 3 3 1 Output 1 Note In the first example the robbers can move, for example, along the following routes: (1-2-3-1), (3-4-5-3), (1-2-3-4-5-3-1). We can show that if Petr chooses the 3-rd intersection, he will eventually meet the robbers independently of their route. Submitted Solution: ``` from collections import defaultdict from operator import itemgetter def find_path(graph, start, end, path=[]): path = path + [start] if start == end: return path if graph.get(start,0) == 0: return None for node in graph[start]: if node not in path: newpath = find_path(graph, node, end, path) if newpath: return newpath return None n , k = input().split() n , k =[int(n) , int(k) ] map = defaultdict(int) map2 = defaultdict(set) for i in range(k) : a , b = input().split() a , b =[int(a) , int(b) ] map[a] += 1 map[b] += 1 map2[a].add(b) map = sorted(map.items(), key=itemgetter(1),reverse = True) case = True for i in range(1,n+1) : if find_path(map2,map[0][0],i) == None : case = False break if case : print(map[0][0]) else : print(-1) ``` No
97,587
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petr is a detective in Braginsk. Somebody stole a huge amount of money from a bank and Petr is to catch him. Somebody told Petr that some luxurious car moves along the roads without stopping. Petr knows that it is the robbers who drive the car. The roads in Braginsk are one-directional and each of them connects two intersections. Petr wants to select one intersection such that if the robbers continue to drive the roads indefinitely, they will sooner or later come to that intersection. The initial position of the robbers is unknown. Find such an intersection that fits the requirements. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 10^5, 2 ≤ m ≤ 5 ⋅ 10^5) — the number of intersections and the number of directed roads in Braginsk, respectively. Each of the next m lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i) — the start and finish of the i-th directed road. It is guaranteed that the robbers can move along the roads indefinitely. Output Print a single integer k — the intersection Petr needs to choose. If there are multiple answers, print any. If there are no such intersections, print -1. Examples Input 5 6 1 2 2 3 3 1 3 4 4 5 5 3 Output 3 Input 3 3 1 2 2 3 3 1 Output 1 Note In the first example the robbers can move, for example, along the following routes: (1-2-3-1), (3-4-5-3), (1-2-3-4-5-3-1). We can show that if Petr chooses the 3-rd intersection, he will eventually meet the robbers independently of their route. Submitted Solution: ``` from collections import defaultdict graph=defaultdict(list) a=list(map(int,input().split())) l=[0]*(a[0]+1) for i in range(a[1]): b=list(map(int,input().split())) l[b[1]]=l[b[1]]+1 graph[b[0]].append(b[1]) vis=[False]*(a[0]+1) vis[1]=True nu=0 stack=[1] while(len(stack)!=0): di=stack.pop() vis[di]=True nu+=1 for val in graph[di]: if(vis[val]==False): stack.append(val) if(a[0]>a[1] or nu<a[0]): print("-1") else: c=l[1] t=1 for i in range(2,a[0]+1): if(c<=l[i]): c=l[i] t=i print(t) ``` No
97,588
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petr is a detective in Braginsk. Somebody stole a huge amount of money from a bank and Petr is to catch him. Somebody told Petr that some luxurious car moves along the roads without stopping. Petr knows that it is the robbers who drive the car. The roads in Braginsk are one-directional and each of them connects two intersections. Petr wants to select one intersection such that if the robbers continue to drive the roads indefinitely, they will sooner or later come to that intersection. The initial position of the robbers is unknown. Find such an intersection that fits the requirements. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 10^5, 2 ≤ m ≤ 5 ⋅ 10^5) — the number of intersections and the number of directed roads in Braginsk, respectively. Each of the next m lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i) — the start and finish of the i-th directed road. It is guaranteed that the robbers can move along the roads indefinitely. Output Print a single integer k — the intersection Petr needs to choose. If there are multiple answers, print any. If there are no such intersections, print -1. Examples Input 5 6 1 2 2 3 3 1 3 4 4 5 5 3 Output 3 Input 3 3 1 2 2 3 3 1 Output 1 Note In the first example the robbers can move, for example, along the following routes: (1-2-3-1), (3-4-5-3), (1-2-3-4-5-3-1). We can show that if Petr chooses the 3-rd intersection, he will eventually meet the robbers independently of their route. Submitted Solution: ``` from collections import defaultdict from operator import itemgetter def find_path(graph, start, end, path=[]): path = path + [start] if start == end: return path if graph.get(start,0) == 0: return None for node in graph[start]: if node not in path: newpath = find_path(graph, node, end, path) if newpath: return newpath return None n , k = input().split() n , k =[int(n) , int(k) ] map = defaultdict(int) map2 = defaultdict(set) for i in range(k) : a , b = input().split() a , b =[int(a) , int(b) ] map[a] += 1 map[b] += 1 map2[a].add(b) map = sorted(map.items(), key=itemgetter(1),reverse = True) case = True for inter,road in map : s = set() for i in range(1,n+1) : road = find_path(map2,inter,i) if road == None : case = False break else : s.add(len(road)) if n not in s : case = False if not case : break if case : print(map[0][0]) else : print(-1) ``` No
97,589
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petr is a detective in Braginsk. Somebody stole a huge amount of money from a bank and Petr is to catch him. Somebody told Petr that some luxurious car moves along the roads without stopping. Petr knows that it is the robbers who drive the car. The roads in Braginsk are one-directional and each of them connects two intersections. Petr wants to select one intersection such that if the robbers continue to drive the roads indefinitely, they will sooner or later come to that intersection. The initial position of the robbers is unknown. Find such an intersection that fits the requirements. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 10^5, 2 ≤ m ≤ 5 ⋅ 10^5) — the number of intersections and the number of directed roads in Braginsk, respectively. Each of the next m lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i) — the start and finish of the i-th directed road. It is guaranteed that the robbers can move along the roads indefinitely. Output Print a single integer k — the intersection Petr needs to choose. If there are multiple answers, print any. If there are no such intersections, print -1. Examples Input 5 6 1 2 2 3 3 1 3 4 4 5 5 3 Output 3 Input 3 3 1 2 2 3 3 1 Output 1 Note In the first example the robbers can move, for example, along the following routes: (1-2-3-1), (3-4-5-3), (1-2-3-4-5-3-1). We can show that if Petr chooses the 3-rd intersection, he will eventually meet the robbers independently of their route. Submitted Solution: ``` import collections; def getIntList(): return list(map(int, input().split())); def getTransIntList(n): first=getIntList(); m=len(first); result=[[0]*n for _ in range(m)]; for i in range(m): result[i][0]=first[i]; for j in range(1, n): curr=getIntList(); for i in range(m): result[i][j]=curr[i]; return result; n, m =getIntList(); Arcs=[]; for _ in range(m): u, v=getIntList(); Arcs.append((u-1, v-1)); prevVerts=[set() for _ in range(n)]; nextCount=[0 for _ in range(n)]; for a in Arcs: u, v=a; prevVerts[v].add(u); nextCount[u]+=1; #Удаляем тупики Verts=set(range(n)); badVerts=set(); deq=collections.deque(); for v in range(n): if nextCount[v]==0: deq.append(v); while len(deq)>0: v=deq.pop(); badVerts.add(v); for u in prevVerts[v]: nextCount[u]-=1; if nextCount[u]==0: deq.append(u); Verts-=badVerts; seen=set(); def solve(): for v in Verts: if v in seen: continue; currSeen=set(); deq=collections.deque([v]); nextRemoved=[0 for _ in range(n)]; while len(deq)>0: v1=deq.pop(); currSeen.add(v1); for u in prevVerts[v1]: if u in currSeen: continue; nextRemoved[u]+=1; if nextCount[u]==nextRemoved[u]: deq.append(u); #print(v, currSeen) if len(currSeen)==len(Verts): return v+1; seen.update(currSeen); return -1; print(solve()); ``` No
97,590
Provide a correct Python 3 solution for this coding contest problem. You are given two integer arrays a_0, a_1, ..., a_{N - 1} and b_0, b_1, ..., b_{M - 1}. Calculate the array c_0, c_1, ..., c_{(N - 1) + (M - 1)}, defined by c_i = \sum_{j = 0}^i a_j b_{i - j} \bmod 998244353. Constraints * 1 \leq N, M \leq 524288 * 0 \leq a_i, b_i < 998244353 * All values in Input are integer. Input Input is given from Standard Input in the following format: N M a_0 a_1 ... a_{N-1} b_0 b_1 ... b_{M-1} Output Print the answer in the following format: c_0 c_1 ... c_{(N - 1) + (M - 1)} Output Print the answer in the following format: c_0 c_1 ... c_{(N - 1) + (M - 1)} Examples Input 4 5 1 2 3 4 5 6 7 8 9 Output 5 16 34 60 70 70 59 36 Input 1 1 10000000 10000000 Output 871938225 "Correct Solution: ``` def primitive_root(m): if m == 2: return 1 if m == 167772161: return 3 if m == 469762049: return 3 if m == 754974721: return 11 if m == 998244353: return 3 divs = [0] * 20 cnt = 1 x = (m - 1) // 2 while x % 2 == 0: x //= 2 i = 3 while i * i <= x: if x % i == 0: divs[cnt] = i cnt += 1 while x % i == 0: x //= i i += 2 if x > 1: divs[cnt] = x cnt += 1 g = 2 while True: ok = True for i in range(cnt): if pow(g, (m - 1) // divs[i], m) == 1: ok = False break if ok: return g g += 1 def inv_gcd(a, b): a %= b if a == 0: return b, 0 s = b t = a m0 = 0 m1 = 1 while t: u = s // t s -= t * u m0 -= m1 * u s, t = t, s m0, m1 = m1, m0 if m0 < 0: m0 += b // s return s, m0 def butterfly(arr, mod): g = primitive_root(mod) n = len(arr) h = (n - 1).bit_length() first = True sum_e = [0] * 30 if first: first = False es = [0] * 30 ies = [0] * 30 m = mod - 1 cnt2 = (m & -m).bit_length() - 1 e = pow(g, m >> cnt2, mod) ie = pow(e, mod - 2, mod) for i in range(cnt2 - 1)[::-1]: es[i] = e ies[i] = ie e *= e e %= mod ie *= ie ie %= mod now = 1 for i in range(cnt2 - 2): sum_e[i] = es[i] * now % mod now *= ies[i] now %= mod for ph in range(1, h + 1): w = 1 << (ph - 1) p = 1 << (h - ph) now = 1 for s in range(w): offset = s << (h - ph + 1) for i in range(p): l = arr[i + offset] r = arr[i + offset + p] * now arr[i + offset] = (l + r) % mod arr[i + offset + p] = (l - r) % mod now *= sum_e[(~s & -~s).bit_length() - 1] now %= mod def butterfly_inv(arr, mod): g = primitive_root(mod) n = len(arr) h = (n - 1).bit_length() first = True sum_ie = [0] * 30 if first: first = False es = [0] * 30 ies = [0] * 30 m = mod - 1 cnt2 = (m & -m).bit_length() - 1 e = pow(g, m >> cnt2, mod) ie = pow(e, mod - 2, mod) for i in range(cnt2 - 1)[::-1]: es[i] = e ies[i] = ie e *= e e %= mod ie *= ie ie %= mod now = 1 for i in range(cnt2 - 2): sum_ie[i] = ies[i] * now % mod now *= es[i] now %= mod for ph in range(1, h + 1)[::-1]: w = 1 << (ph - 1) p = 1 << (h - ph) inow = 1 for s in range(w): offset = s << (h - ph + 1) for i in range(p): l = arr[i + offset] r = arr[i + offset + p] arr[i + offset] = (l + r) % mod arr[i + offset + p] = (mod + l - r) * inow % mod inow *= sum_ie[(~s & -~s).bit_length() - 1] inow %= mod def convolution(a, b, mod=998244353): n = len(a) m = len(b) if not n or not m: return [] if min(n, m) <= 60: if n < m: n, m = m, n a, b = b, a res = [0] * (n + m - 1) for i in range(n): for j in range(m): res[i + j] += a[i] * b[j] res[i + j] %= mod return res z = 1 << (n + m - 2).bit_length() a += [0] * (z - n) b += [0] * (z - m) butterfly(a, mod) butterfly(b, mod) for i in range(z): a[i] *= b[i] a[i] %= mod butterfly_inv(a, mod) a = a[:n + m - 1] iz = pow(z, mod - 2, mod) for i in range(n + m - 1): a[i] *= iz a[i] %= mod return a def convolution_ll(a, b): n = len(a) m = len(b) if not n or not m: return [] mod1 = 754974721 mod2 = 167772161 mod3 = 469762049 m2m3 = mod2 * mod3 m1m3 = mod1 * mod3 m1m2 = mod1 * mod2 m1m2m3 = mod1 * mod2 * mod3 i1 = inv_gcd(m2m3, mod1)[1] i2 = inv_gcd(m1m3, mod2)[1] i3 = inv_gcd(m1m2, mod3)[1] c1 = convolution(a.copy(), b.copy(), mod1) c2 = convolution(a.copy(), b.copy(), mod2) c3 = convolution(a.copy(), b.copy(), mod3) c = [0] * (n + m - 1) for i in range(n + m - 1): x = 0 x += (c1[i] * i1) % mod1 * m2m3 x += (c2[i] * i2) % mod2 * m1m3 x += (c3[i] * i3) % mod3 * m1m2 x %= m1m2m3 c[i] = x return c N, M = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) print(*convolution(A, B)) ```
97,591
Provide a correct Python 3 solution for this coding contest problem. You are given two integer arrays a_0, a_1, ..., a_{N - 1} and b_0, b_1, ..., b_{M - 1}. Calculate the array c_0, c_1, ..., c_{(N - 1) + (M - 1)}, defined by c_i = \sum_{j = 0}^i a_j b_{i - j} \bmod 998244353. Constraints * 1 \leq N, M \leq 524288 * 0 \leq a_i, b_i < 998244353 * All values in Input are integer. Input Input is given from Standard Input in the following format: N M a_0 a_1 ... a_{N-1} b_0 b_1 ... b_{M-1} Output Print the answer in the following format: c_0 c_1 ... c_{(N - 1) + (M - 1)} Output Print the answer in the following format: c_0 c_1 ... c_{(N - 1) + (M - 1)} Examples Input 4 5 1 2 3 4 5 6 7 8 9 Output 5 16 34 60 70 70 59 36 Input 1 1 10000000 10000000 Output 871938225 "Correct Solution: ``` p, g = 998244353, 3 invg = pow(g, p-2, p) W = [pow(g, (p - 1) >> i, p) for i in range(24)] iW = [pow(invg, (p - 1) >> i, p) for i in range(24)] def convolve(a, b): def fft(f): for l in range(k)[::-1]: d = 1 << l u = 1 for i in range(d): for j in range(i, n, 2*d): f[j], f[j+d] = (f[j] + f[j+d]) % p, u * (f[j] - f[j+d]) % p u = u * W[l+1] % p def ifft(f): for l in range(k): d = 1 << l u = 1 for i in range(d): for j in range(i, n, 2*d): f[j+d] *= u f[j], f[j+d] = (f[j] + f[j+d]) % p, (f[j] - f[j+d]) % p u = u * iW[l+1] % p n0, n1 = len(a), len(b) k = (max(n0, n1) - 1).bit_length() + 1 n = 1 << k a = a + [0] * (n-n0) b = b + [0] * (n-n1) fft(a), fft(b) for i in range(n): a[i] = a[i] * b[i] % p ifft(a) invn = pow(n, p - 2, p) return [a[i] * invn % p for i in range(n0 + n1 - 1)] N, M = map(int, input().split()) A = [int(a) for a in input().split()] B = [int(a) for a in input().split()] print(*convolve(A, B)) ```
97,592
Provide a correct Python 3 solution for this coding contest problem. You are given two integer arrays a_0, a_1, ..., a_{N - 1} and b_0, b_1, ..., b_{M - 1}. Calculate the array c_0, c_1, ..., c_{(N - 1) + (M - 1)}, defined by c_i = \sum_{j = 0}^i a_j b_{i - j} \bmod 998244353. Constraints * 1 \leq N, M \leq 524288 * 0 \leq a_i, b_i < 998244353 * All values in Input are integer. Input Input is given from Standard Input in the following format: N M a_0 a_1 ... a_{N-1} b_0 b_1 ... b_{M-1} Output Print the answer in the following format: c_0 c_1 ... c_{(N - 1) + (M - 1)} Output Print the answer in the following format: c_0 c_1 ... c_{(N - 1) + (M - 1)} Examples Input 4 5 1 2 3 4 5 6 7 8 9 Output 5 16 34 60 70 70 59 36 Input 1 1 10000000 10000000 Output 871938225 "Correct Solution: ``` class NTT: def __init__(self, convolution_rank, binary_level): self.cr = convolution_rank self.bl = binary_level self.modulo_list = [1]*convolution_rank self.primal_root_list = [1]*convolution_rank self.bin_list = [1]*(binary_level+1) self.primal_base_matrix = [0]*((binary_level+1)*convolution_rank) self.inverse_base_matrix = [0]*((binary_level+1)*convolution_rank) for i in range(binary_level): self.bin_list[i+1] = self.bin_list[i] * 2 def doubling(self, n, m, modulo=0): y = 1 tmp = m bas = n while tmp: if tmp % 2: y *= bas if modulo: y %= modulo bas *= bas if modulo: bas %= modulo tmp >>= 1 return y def powlimit(self, n): y = 1 cnt = 0 while y < n: y *= 2 cnt += 1 return y, cnt def IsPrime(self, num): p = 2 if num <= 1: return False while p * p <= num: if num % p == 0: return False p += 1 return True def extgcd(self, a, b, c): x, y, u, v, k, l = 1, 0, 0, 1, a, b while l: x, y, u, v = u, v, x - u * (k // l), y - v * (k // l) k, l = l, k % l if c % k: return "No Solution" return x * c, y * c def inved(self, a, modulo): x, y = self.extgcd(a, modulo, 1) return (x+modulo)%modulo def root_manual(self): for i in range(self.cr): r = 1 flg = True while flg: fflg = True for j in range(self.bl): if self.doubling(r, self.bin_list[j], self.modulo_list[i]) == 1: fflg = False if self.doubling(r, self.bin_list[-1], self.modulo_list[i]) != 1: fflg = False if fflg: flg = False else: r += 1 if r >= self.modulo_list[i]: break self.primal_root_list[i] = r def make_prime_root(self): cnt = 0 j = 1 last = self.bin_list[-1] while cnt < self.cr: if self.IsPrime(j*last+1): flg = True r = 1 while flg: fflg = True for i in range(self.bl): if self.doubling(r, self.bin_list[i], j*last+1) == 1: fflg = False if self.doubling(r, last, j*last+1) != 1: fflg = False if fflg: flg = False else: r += 1 if r >= j*last+1: break if flg==False: self.modulo_list[cnt] = j*last+1 self.primal_root_list[cnt] = r cnt += 1 j += 2 def make_basis(self): for i in range(self.cr): for j in range(self.bl): tmp = self.doubling(2, self.bl-j) self.primal_base_matrix[i*(self.bl+1)+j] = self.doubling(self.primal_root_list[i], tmp, self.modulo_list[i]) self.inverse_base_matrix[i*(self.bl+1)+j] = self.inved(self.primal_base_matrix[i*(self.bl+1)+j], self.modulo_list[i]) def NTT(self, f, n, idx, depth, inverse=False, surface=True): mod = self.modulo_list[idx] i2 = self.inved(2, mod) if inverse: seed = self.primal_base_matrix[idx*(self.bl+1)+depth] else: seed = self.inverse_base_matrix[idx*(self.bl+1)+depth] if n == 1: return f if n == 2: xf = [(f[0] + f[1])%mod, (f[0] - f[1])%mod] if inverse * surface: xf[0] *= i2 xf[0] %= mod xf[1] *= i2 xf[1] %= mod return xf hn = n // 2 fe = [f[2*i+0] for i in range(hn)] fo = [f[2*i+1] for i in range(hn)] fe = self.NTT(fe, hn, idx, depth-1, inverse, False) fo = self.NTT(fo, hn, idx, depth-1, inverse, False) xf = [0 for _ in range(n)] grow = 1 for i in range(hn): right = (fo[i] * grow) % mod xf[i+0*hn] = (fe[i] + right) % mod xf[i+1*hn] = (fe[i] - right) % mod grow *= seed grow %= mod if inverse * surface: invn = self.inved(n, mod) for i in range(n): xf[i] *= invn xf[i] %= mod return xf def second_NTT(self, f, n, idx, depth, inverse=False): res = [0 for _ in range(n)] tmp = [0 for _ in range(n)] MOD = self.modulo_list[idx] ipl = self.inved(n, MOD) for i in range(n): bas = 1 pos = 0 for j in range(depth, 0, -1): pos += bas * ((i>>(j-1)) % 2) bas *= 2 res[i] = f[pos] for i in range(depth): grow = 1 seed = inverse * self.primal_base_matrix[idx*(self.bl+1)+i+1] + (1 - inverse) * self.inverse_base_matrix[idx*(self.bl+1)+i+1] for k in range(1<<i): for j in range(1<<(depth-i-1)): tmp[j*(1<<(i+1))+k+0*(1<<i)] = (res[j*(1<<(i+1))+k] + grow * res[j*(1<<(i+1))+k+(1<<i)]) % MOD tmp[j*(1<<(i+1))+k+1*(1<<i)] = (res[j*(1<<(i+1))+k] - grow * res[j*(1<<(i+1))+k+(1<<i)]) % MOD grow *= seed grow %= MOD for j in range(n): res[j] = tmp[j] if inverse: for i in range(n): res[i] *= ipl res[i] %= MOD return res def CRT(self, num, a_list, m_list): r = a_list[0] bas = m_list[0] x, y = 0, 0 for i in range(1, num): x, y = self.extgcd(bas, -m_list[i], -a_list[i]-r) r += bas * x bas *= m_list[i] return r % bas N, M = map(int, input().split()) ntt = NTT(1, 23) ntt.modulo_list[0] = 998244353 ntt.root_manual() ntt.make_basis() A = list(map(int, input().split())) B = list(map(int, input().split())) pl, cnt = ntt.powlimit(N+M) A = A[:] + [0 for _ in range(pl-N)] B = B[:] + [0 for _ in range(pl-M)] X = ntt.second_NTT(A, pl, 0, cnt) Y = ntt.second_NTT(B, pl, 0, cnt) Z = [X[i]*Y[i]%ntt.modulo_list[0] for i in range(pl)] Z = ntt.second_NTT(Z, pl, 0, cnt, True) for i in range(N+M-1): print(Z[i], end = ' '*(i!=N+M-2)) print() ```
97,593
Provide a correct Python 3 solution for this coding contest problem. You are given two integer arrays a_0, a_1, ..., a_{N - 1} and b_0, b_1, ..., b_{M - 1}. Calculate the array c_0, c_1, ..., c_{(N - 1) + (M - 1)}, defined by c_i = \sum_{j = 0}^i a_j b_{i - j} \bmod 998244353. Constraints * 1 \leq N, M \leq 524288 * 0 \leq a_i, b_i < 998244353 * All values in Input are integer. Input Input is given from Standard Input in the following format: N M a_0 a_1 ... a_{N-1} b_0 b_1 ... b_{M-1} Output Print the answer in the following format: c_0 c_1 ... c_{(N - 1) + (M - 1)} Output Print the answer in the following format: c_0 c_1 ... c_{(N - 1) + (M - 1)} Examples Input 4 5 1 2 3 4 5 6 7 8 9 Output 5 16 34 60 70 70 59 36 Input 1 1 10000000 10000000 Output 871938225 "Correct Solution: ``` # AC Library Python版 # Author Koki_tkg ''' internal_type_traits以外は翻訳しました。 practiceは一応全部ACしていますが, practiceで使っていない関数などの動作は未確認なので保証はしません。 また,C++版をほぼそのまま書き換えているので速度は出ません。 (2020/09/13 by Koki_tkg) ''' # --------------------<< Library Start >>-------------------- # # convolution.py class convolution: def __init__(self, a: list, b: list, mod: int): self.a, self.b = a, b self.n, self.m = len(a), len(b) self.MOD = mod self.g = primitive_root_constexpr(self.MOD) def convolution(self) -> list: n, m = self.n, self.m a, b = self.a, self.b if not n or not m: return [] if min(n, m) <= 60: if n < m: n, m = m, n a, b = b, a ans = [0] * (n + m - 1) for i in range(n): for j in range(m): ans[i + j] += a[i] * b[j] % self.MOD ans[i + j] %= self.MOD return ans z = 1 << ceil_pow2(n + m - 1) a = self.resize(a, z) a = self.butterfly(a) b = self.resize(b, z) b = self.butterfly(b) for i in range(z): a[i] = a[i] * b[i] % self.MOD a = self.butterfly_inv(a) a = a[:n + m - 1] iz = self.inv(z) a = [x * iz % self.MOD for x in a] return a def butterfly(self, a: list) -> list: n = len(a) h = ceil_pow2(n) first = True sum_e = [0] * 30 m = self.MOD if first: first = False es, ies = [0] * 30, [0] * 30 cnt2 = bsf(m - 1) e = self.mypow(self.g, (m - 1) >> cnt2); ie = self.inv(e) for i in range(cnt2, 1, -1): es[i - 2] = e ies[i - 2] = ie e = e * e % m ie = ie * ie % m now = 1 for i in range(cnt2 - 2): sum_e[i] = es[i] * now % m now = now * ies[i] % m for ph in range(1, h + 1): w = 1 << (ph - 1); p = 1 << (h - ph) now = 1 for s in range(w): offset = s << (h - ph + 1) for i in range(p): l = a[i + offset] % m r = a[i + offset + p] * now % m a[i + offset] = (l + r) % m a[i + offset + p] = (l - r) % m now = now * sum_e[bsf(~s)] % m return a def butterfly_inv(self, a: list) -> list: n = len(a) h = ceil_pow2(n) first = True sum_ie = [0] * 30 m = self.MOD if first: first = False es, ies = [0] * 30, [0] * 30 cnt2 = bsf(m - 1) e = self.mypow(self.g, (m - 1) >> cnt2); ie = self.inv(e) for i in range(cnt2, 1, -1): es[i - 2] = e ies[i - 2] = ie e = e * e % m ie = ie * ie % m now = 1 for i in range(cnt2 - 2): sum_ie[i] = ies[i] * now % m now = es[i] * now % m for ph in range(h, 0, -1): w = 1 << (ph - 1); p = 1 << (h - ph) inow = 1 for s in range(w): offset = s << (h - ph + 1) for i in range(p): l = a[i + offset] % m r = a[i + offset + p] % m a[i + offset] = (l + r) % m a[i + offset + p] = (m + l - r) * inow % m inow = sum_ie[bsf(~s)] * inow % m return a @staticmethod def resize(array: list, sz: int) -> list: new_array = array + [0] * (sz - len(array)) return new_array def inv(self, x: int): if is_prime_constexpr(self.MOD): assert x return self.mypow(x, self.MOD - 2) else: eg = inv_gcd(x) assert eg[0] == 1 return eg[1] def mypow(self, x: int, n: int) -> int: assert 0 <= n r = 1; m = self.MOD while n: if n & 1: r = r * x % m x = x * x % m n >>= 1 return r # dsu.py class dsu: def __init__(self, n: int): self._n = n self.parent_or_size = [-1] * self._n def merge(self, a: int, b: int) -> int: assert 0 <= a and a < self._n assert 0 <= b and a < self._n x = self.leader(a); y = self.leader(b) if x == y: return x if -self.parent_or_size[x] < -self.parent_or_size[y]: x, y = y, x self.parent_or_size[x] += self.parent_or_size[y] self.parent_or_size[y] = x return x def same(self, a: int, b: int) -> bool: assert 0 <= a and a < self._n assert 0 <= b and a < self._n return self.leader(a) == self.leader(b) def leader(self, a: int) -> int: assert 0 <= a and a < self._n if self.parent_or_size[a] < 0: return a self.parent_or_size[a] = self.leader(self.parent_or_size[a]) return self.parent_or_size[a] def size(self, a: int) -> int: assert 0 <= a and a < self._n return -self.parent_or_size[self.leader(a)] def groups(self): leader_buf = [0] * self._n; group_size = [0] * self._n for i in range(self._n): leader_buf[i] = self.leader(i) group_size[leader_buf[i]] += 1 result = [[] for _ in range(self._n)] for i in range(self._n): result[leader_buf[i]].append(i) result = [v for v in result if v] return result # fenwicktree.py class fenwick_tree: def __init__(self, n): self._n = n self.data = [0] * n def add(self, p: int, x: int): assert 0 <= p and p <= self._n p += 1 while p <= self._n: self.data[p - 1] += x p += p & -p def sum(self, l: int, r: int) -> int: assert 0 <= l and l <= r and r <= self._n return self.__sum(r) - self.__sum(l) def __sum(self, r: int) -> int: s = 0 while r > 0: s += self.data[r - 1] r -= r & -r return s # internal_bit.py def ceil_pow2(n: int) -> int: x = 0 while (1 << x) < n: x += 1 return x def bsf(n: int) -> int: return (n & -n).bit_length() - 1 # internal_math.py def safe_mod(x: int, m: int) -> int: x %= m if x < 0: x += m return x class barrett: def __init__(self, m: int): self._m = m self.im = -1 // (m + 1) def umod(self): return self._m def mul(self, a: int, b: int) -> int: z = a z *= b x = (z * im) >> 64 v = z - x * self._m if self._m <= v: v += self._m return v def pow_mod_constexpr(x: int, n: int, m: int) -> int: if m == 1: return 0 _m = m; r = 1; y = safe_mod(x, m) while n: if n & 1: r = (r * y) % _m y = (y * y) % _m n >>= 1 return r def is_prime_constexpr(n: int) -> bool: if n <= 1: return False if n == 2 or n == 7 or n == 61: return True if n % 2 == 0: return False d = n - 1 while d % 2 == 0: d //= 2 for a in [2, 7, 61]: t = d y = pow_mod_constexpr(a, t, n) while t != n - 1 and y != 1 and y != n - 1: y = y * y % n t <<= 1 if y != n - 1 and t % 2 == 0: return False return True def inv_gcd(self, a: int, b: int) -> tuple: a = safe_mod(a, b) if a == 0: return (b, 0) s = b; t = a; m0 = 0; m1 = 1 while t: u = s // t s -= t * u m0 -= m1 * u tmp = s; s = t; t = tmp; tmp = m0; m0 = m1; m1 = tmp if m0 < 0: m0 += b // s return (s, m0) def primitive_root_constexpr(m: int) -> int: if m == 2: return 1 if m == 167772161: return 3 if m == 469762049: return 3 if m == 754974721: return 11 if m == 998244353: return 3 divs = [0] * 20 divs[0] = 2 cnt = 1 x = (m - 1) // 2 while x % 2 == 0: x //= 2 i = 3 while i * i <= x: if x % i == 0: divs[cnt] = i; cnt += 1 while x % i == 0: x //= i i += 2 if x > 1: divs[cnt] = x; cnt += 1 g = 2 while True: ok = True for i in range(cnt): if pow_mod_constexpr(g, (m - 1) // div[i], m) == 1: ok = False break if ok: return g g += 1 # internal_queue.py class simple_queue: def __init__(self): self.payload = [] self.pos = 0 def size(self): return len(self.payload) - self.pos def empty(self): return self.pos == len(self.payload) def push(self, t: int): self.payload.append(t) def front(self): return self.payload[self.pos] def clear(self): self.payload.clear(); pos = 0 def pop(self): self.pos += 1 def pop_front(self): self.pos += 1; return self.payload[~-self.pos] # internal_scc.py class csr: def __init__(self, n: int, edges: list): from copy import deepcopy self.start = [0] * (n + 1) self.elist = [[] for _ in range(len(edges))] for e in edges: self.start[e[0] + 1] += 1 for i in range(1, n + 1): self.start[i] += self.start[i - 1] counter = deepcopy(self.start) for e in edges: self.elist[counter[e[0]]] = e[1]; counter[e[0]] += 1 class scc_graph: # private edges = [] # public def __init__(self, n: int): self._n = n self.now_ord = 0; self.group_num = 0 def num_vertices(self): return self._n def add_edge(self, _from: int, _to: int): self.edges.append((_from, [_to])) def scc_ids(self): g = csr(self._n, self.edges) visited = []; low = [0] * self._n; ord = [-1] * self._n; ids = [0] * self._n def dfs(s, v: int): low[v] = ord[v] = self.now_ord; self.now_ord += 1 visited.append(v) for i in range(g.start[v], g.start[v + 1]): to = g.elist[i][0] if ord[to] == -1: s(s, to) low[v] = min(low[v], low[to]) else: low[v] = min(low[v], ord[to]) if low[v] == ord[v]: while True: u = visited.pop() ord[u] = self._n ids[u] = self.group_num if u == v: break self.group_num += 1 for i in range(self._n): if ord[i] == -1: dfs(dfs, i) for i in range(self._n): ids[i] = self.group_num - 1 - ids[i] return (self.group_num, ids) def scc(self): ids = self.scc_ids() group_num = ids[0] counts = [0] * group_num for x in ids[1]: counts[x] += 1 groups = [[] for _ in range(group_num)] for i in range(self._n): groups[ids[1][i]].append(i) return groups # internal_type_traits.py # lazysegtree.py ''' def op(l, r): return def e(): return def mapping(l, r): return def composition(l, r): return def id(): return 0 ''' class lazy_segtree: def __init__(self, op, e, mapping, composition, id, v: list): self.op = op; self.e = e; self.mapping = mapping; self.composition = composition; self.id = id self._n = len(v) self.log = ceil_pow2(self._n) self.size = 1 << self.log self.lz = [self.id()] * self.size self.d = [self.e()] * (2 * self.size) for i in range(self._n): self.d[self.size + i] = v[i] for i in range(self.size - 1, 0, -1): self.__update(i) def set_(self, p: int, x: int): assert 0 <= p and p < self._n p += self.size for i in range(self.log, 0, -1): self.__push(p >> i) self.d[p] = x for i in range(1, self.log + 1): self.__update(p >> 1) def get(self, p: int): assert 0 <= p and p < self._n p += self.size for i in range(self.log, 0, -1): self.__push(p >> i) return self.d[p] def prod(self, l: int, r: int): assert 0 <= l and l <= r and r <= self._n if l == r: return self.e() l += self.size; r += self.size for i in range(self.log, 0, -1): if ((l >> i) << i) != l: self.__push(l >> i) if ((r >> i) << i) != r: self.__push(r >> i) sml, smr = self.e(), self.e() while l < r: if l & 1: sml = self.op(sml, self.d[l]); l += 1 if r & 1: r -= 1; smr = self.op(self.d[r], smr) l >>= 1; r >>= 1 return self.op(sml, smr) def all_prod(self): return self.d[1] def apply(self, p: int, f): assert 0 <= p and p < self._n p += self.size for i in range(self.log, 0, -1): self.__push(p >> i) self.d[p] = self.mapping(f, self.d[p]) for i in range(1, self.log + 1): self.__update(p >> 1) def apply(self, l: int, r: int, f): assert 0 <= l and l <= r and r <= self._n if l == r: return l += self.size; r += self.size for i in range(self.log, 0, -1): if ((l >> i) << i) != l: self.__push(l >> i) if ((r >> i) << i) != r: self.__push((r - 1) >> i) l2, r2 = l, r while l < r: if l & 1: self.__all_apply(l, f); l += 1 if r & 1: r -= 1; self.__all_apply(r, f) l >>= 1; r >>= 1 l, r = l2, r2 for i in range(1, self.log + 1): if ((l >> i) << i) != l: self.__update(l >> i) if ((r >> i) << i) != r: self.__update(r >> i) def max_right(self, l: int, g): assert 0 <= l and l <= self._n if l == self._n: return self._n l += self.size for i in range(self.log, 0, -1): self.__push(l >> i) sm = self.e() while True: while l % 2 == 0: l >>= 1 if not g(self.op(sm, self.d[l])): while l < self.size: self.__push(l) l = 2 * l if g(self.op(sm, self.d[l])): sm = self.op(sm, self.d[l]) l += 1 return l - self.size sm = self.op(sm, self.d[l]) l += 1 if (l & -l) == l: break return self._n def min_left(self, r: int, g): assert 0 <= r and r <= self._n if r == 0: return 0 r += self.size for i in range(self.log, 0, -1): self.__push(r >> i) sm = self.e() while True: r -= 1 while r > 1 and r % 2: r >>= 1 if not g(self.op(self.d[r], sm)): while r < self.size: self.__push(r) r = 2 * r + 1 if g(self.op(self.d[r], sm)): sm = self.op(self.d[r], sm) r -= 1 return r + 1 - self.size sm = self.op(self.d[r], sm) if (r & -r) == r: break return 0 # private def __update(self, k: int): self.d[k] = self.op(self.d[k * 2], self.d[k * 2 + 1]) def __all_apply(self, k: int, f): self.d[k] = self.mapping(f, self.d[k]) if k < self.size: self.lz[k] = self.composition(f, self.lz[k]) def __push(self, k: int): self.__all_apply(2 * k, self.lz[k]) self.__all_apply(2 * k + 1, self.lz[k]) self.lz[k] = self.id() # math def pow_mod(x: int, n: int, m: int) -> int: assert 0 <= n and 1 <= m if m == 1: return 0 bt = barrett(m) r = 1; y = safe_mod(x, m) while n: if n & 1: r = bt.mul(r, y) y = bt.mul(y, y) n >>= 1 return n def inv_mod(x: int, m: int) -> int: assert 1 <= m z = inv_gcd(x, m) assert z[0] == 1 return z[1] def crt(r: list, m: list) -> tuple: assert len(r) == len(m) n = len(r) r0 = 0; m0 = 1 for i in range(n): assert 1 <= m[i] r1 = safe_mod(r[i], m[i]); m1 = m[i] if m0 < m1: r0, r1 = r1, r0 m0, m1 = m1, m0 if m0 % m1 == 0: if r0 % m1 != r1: return (0, 0) continue g, im = inv_gcd(m0, m1) u1 = m1 // g if (r1 - r0) % g: return (0, 0) x = (r1 - r0) // g % u1 * im % u1 r0 += x * m0 m0 *= u1 if r0 < 0: r0 += m0 return (r0, m0) def floor_sum(n: int, m: int, a: int, b: int) -> int: ans = 0 if a >= m: ans += (n - 1) * n * (a // m) // 2 a %= m if b >= m: ans += n * (b // m) bb %= m y_max = (a * n + b) // m; x_max = (y_max * m - b) if y_max == 0: return ans ans += (n - (x_max + a - 1) // a) * y_max ans += floor_sum(y_max, a, m, (a - x_max % a) % a) return ans # maxflow.py # from collections import deque class mf_graph: numeric_limits_max = 10 ** 18 def __init__(self, n: int): self._n = n self.g = [[] for _ in range(self._n)] self.pos = [] def add_edge(self, _from: int, _to: int, cap: int) -> int: assert 0 <= _from and _from < self._n assert 0 <= _to and _to < self._n assert 0 <= cap m = len(self.pos) self.pos.append((_from, len(self.g[_from]))) self.g[_from].append(self._edge(_to, len(self.g[_to]), cap)) self.g[_to].append(self._edge(_from, len(self.g[_from]) - 1, 0)) return m class edge: def __init__(s, _from: int, _to: int, cap: int, flow: int): s._from = _from; s._to = _to; s.cap = cap; s.flow = flow def get_edge(self, i: int) -> edge: m = len(self.pos) assert 0 <= i and i < m _e = self.g[self.pos[i][0]][self.pos[i][1]] _re = self.g[_e.to][_e.rev] return self.edge(self.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap) def edges(self) -> list: m = len(self.pos) result = [self.get_edge(i) for i in range(m)] return result def change_edge(self, i: int, new_cap: int, new_flow: int): m = len(self.pos) assert 0 <= i and i < m assert 0 <= new_flow and new_flow <= new_cap _e = self.g[self.pos[i][0]][self.pos[i][1]] _re = self.g[_e.to][_e.rev] _e.cap = new_cap - new_flow _re.cap = new_flow def flow(self, s: int, t: int): return self.flow_(s, t, self.numeric_limits_max) def flow_(self, s: int, t: int, flow_limit: int) -> int: assert 0 <= s and s < self._n assert 0 <= t and t < self._n level = [0] * self._n; it = [0] * self._n def bfs(): for i in range(self._n): level[i] = -1 level[s] = 0 que = deque([s]) while que: v = que.popleft() for e in self.g[v]: if e.cap == 0 or level[e.to] >= 0: continue level[e.to] = level[v] + 1 if e.to == t: return que.append(e.to) def dfs(self_, v: int, up: int) -> int: if v == s: return up res = 0 level_v = level[v] for i in range(it[v], len(self.g[v])): it[v] = i e = self.g[v][i] if level_v <= level[e.to] or self.g[e.to][e.rev].cap == 0: continue d = self_(self_, e.to, min(up - res, self.g[e.to][e.rev].cap)) if d <= 0: continue self.g[v][i].cap += d self.g[e.to][e.rev].cap -= d res += d if res == up: break return res flow = 0 while flow < flow_limit: bfs() if level[t] == -1: break for i in range(self._n): it[i] = 0 while flow < flow_limit: f = dfs(dfs, t, flow_limit - flow) if not f: break flow += f return flow def min_cut(self, s: int) -> list: visited = [False] * self._n que = deque([s]) while que: p = que.popleft() visited[p] = True for e in self.g[p]: if e.cap and not visited[e.to]: visited[e.to] = True que.append(e.to) return visited class _edge: def __init__(s, to: int, rev: int, cap: int): s.to = to; s.rev = rev; s.cap = cap # mincostflow.py # from heapq import heappop, heappush class mcf_graph: numeric_limits_max = 10 ** 18 def __init__(self, n: int): self._n = n self.g = [[] for _ in range(n)] self.pos = [] def add_edge(self, _from: int, _to: int, cap: int, cost: int) -> int: assert 0 <= _from and _from < self._n assert 0 <= _to and _to < self._n m = len(self.pos) self.pos.append((_from, len(self.g[_from]))) self.g[_from].append(self._edge(_to, len(self.g[_to]), cap, cost)) self.g[_to].append(self._edge(_from, len(self.g[_from]) - 1, 0, -cost)) return m class edge: def __init__(s, _from: int, _to: int, cap: int, flow: int, cost: int): s._from = _from; s._to = _to; s.cap = cap; s.flow = flow; s.cost = cost def get_edge(self, i: int) -> edge: m = len(self.pos) assert 0 <= i and i < m _e = self.g[self.pos[i][0]][self.pos[i][1]] _re = self.g[_e.to][_e.rev] return self.edge(self.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap, _e.cost) def edges(self) -> list: m = len(self.pos) result = [self.get_edge(i) for i in range(m)] return result def flow(self, s: int, t: int) -> edge: return self.flow_(s, t, self.numeric_limits_max) def flow_(self, s: int, t: int, flow_limit: int) -> edge: return self.__slope(s, t, flow_limit)[-1] def slope(self, s: int, t: int) -> list: return self.slope_(s, t, self.numeric_limits_max) def slope_(self, s: int, t: int, flow_limit: int) -> list: return self.__slope(s, t, flow_limit) def __slope(self, s: int, t: int, flow_limit: int) -> list: assert 0 <= s and s < self._n assert 0 <= t and t < self._n assert s != t dual = [0] * self._n; dist = [0] * self._n pv, pe = [-1] * self._n, [-1] * self._n vis = [False] * self._n def dual_ref(): for i in range(self._n): dist[i] = self.numeric_limits_max pv[i] = -1 pe[i] = -1 vis[i] = False class Q: def __init__(s, key: int, to: int): s.key = key; s.to = to def __lt__(s, r): return s.key < r.key que = [] dist[s] = 0 heappush(que, Q(0, s)) while que: v = heappop(que).to if vis[v]: continue vis[v] = True if v == t: break for i in range(len(self.g[v])): e = self.g[v][i] if vis[e.to] or not e.cap: continue cost = e.cost - dual[e.to] + dual[v] if dist[e.to] - dist[v] > cost: dist[e.to] = dist[v] + cost pv[e.to] = v pe[e.to] = i heappush(que, Q(dist[e.to], e.to)) if not vis[t]: return False for v in range(self._n): if not vis[v]: continue dual[v] -= dist[t] - dist[v] return True flow = 0 cost = 0; prev_cost = -1 result = [] result.append((flow, cost)) while flow < flow_limit: if not dual_ref(): break c = flow_limit - flow v = t while v != s: c = min(c, self.g[pv[v]][pe[v]].cap) v = pv[v] v = t while v != s: e = self.g[pv[v]][pe[v]] e.cap -= c self.g[v][e.rev].cap += c v = pv[v] d = -dual[s] flow += c cost += c * d if prev_cost == d: result.pop() result.append((flow, cost)) prev_cost = cost return result class _edge: def __init__(s, to: int, rev: int, cap: int, cost: int): s.to = to; s.rev = rev; s.cap = cap; s.cost = cost # modint.py class Mint: modint1000000007 = 1000000007 modint998244353 = 998244353 def __init__(self, v: int = 0): self.m = self.modint1000000007 # self.m = self.modint998244353 self.x = v % self.__umod() def inv(self): if is_prime_constexpr(self.__umod()): assert self.x return self.pow_(self.__umod() - 2) else: eg = inv_gcd(self.x, self.m) assert eg[0] == 1 return eg[2] def __str__(self): return str(self.x) def __le__(self, other): return self.x <= Mint.__get_val(other) def __lt__(self, other): return self.x < Mint.__get_val(other) def __ge__(self, other): return self.x >= Mint.__get_val(other) def __gt(self, other): return self.x > Mint.__get_val(other) def __eq__(self, other): return self.x == Mint.__get_val(other) def __iadd__(self, other): self.x += Mint.__get_val(other) if self.x >= self.__umod(): self.x -= self.__umod() return self def __add__(self, other): _v = Mint(self.x); _v += other return _v def __isub__(self, other): self.x -= Mint.__get_val(other) if self.x >= self.__umod(): self.x += self.__umod() return self def __sub__(self, other): _v = Mint(self.x); _v -= other return _v def __rsub__(self, other): _v = Mint(Mint.__get_val(other)); _v -= self return _v def __imul__(self, other): self.x =self.x * Mint.__get_val(other) % self.__umod() return self def __mul__(self, other): _v = Mint(self.x); _v *= other return _v def __itruediv__(self, other): self.x = self.x / Mint.__get_val(other) % self.__umod() return self def __truediv__(self, other): _v = Mint(self.x); _v /= other return _v def __rtruediv__(self, other): _v = Mint(Mint.__get_val(other)); _v /= self return _v def __ifloordiv__(self, other): other = other if isinstance(other, Mint) else Mint(other) self *= other.inv() return self def __floordiv__(self, other): _v = Mint(self.x); _v //= other return _v def __rfloordiv__(self, other): _v = Mint(Mint.__get_val(other)); _v //= self return _v def __pow__(self, other): _v = Mint(pow(self.x, Mint.__get_val(other), self.__umod())) return _v def __rpow__(self, other): _v = Mint(pow(Mint.__get_val(other), self.x, self.__umod())) return _v def __imod__(self, other): self.x %= Mint.__get_val(other) return self def __mod__(self, other): _v = Mint(self.x); _v %= other return _v def __rmod__(self, other): _v = Mint(Mint.__get_val(other)); _v %= self return _v def __ilshift__(self, other): self.x <<= Mint.__get_val(other) return self def __irshift__(self, other): self.x >>= Mint.__get_val(other) return self def __lshift__(self, other): _v = Mint(self.x); _v <<= other return _v def __rshift__(self, other): _v = Mint(self.x); _v >>= other return _v def __rlshift__(self, other): _v = Mint(Mint.__get_val(other)); _v <<= self return _v def __rrshift__(self, other): _v = Mint(Mint.__get_val(other)); _v >>= self return _v __repr__ = __str__ __radd__ = __add__ __rmul__ = __mul__ def __umod(self): return self.m @staticmethod def __get_val(val): return val.x if isinstance(val, Mint) else val def pow_(self, n: int): assert 0 <= n x = Mint(self.x); r = 1 while n: if n & 1: r *= x x *= x n >>= 1 return r def val(self): return self.x def mod(self): return self.m def raw(self, v): x = Mint() x.x = v return x # scc.py class scc_graph_sub: # public def __init__(self, n): self.internal = scc_graph(n) def add_edge(self, _from, _to): n = self.internal.num_vertices() assert 0 <= _from and _from < n assert 0 <= _to and _to < n self.internal.add_edge(_from, _to) def scc(self): return self.internal.scc() # segtree.py ''' def e(): return def op(l, r): return def f(): return ''' class segtree: def __init__(self, op, e, v: list): self._n = len(v) self.log = ceil_pow2(self._n) self.size = 1 << self.log self.op = op; self.e = e self.d = [self.e()] * (self.size * 2) for i in range(self._n): self.d[self.size + i] = v[i] for i in range(self.size - 1, 0, -1): self.__update(i) def set_(self, p: int, x: int): assert 0 <= p and p < self._n p += self.size self.d[p] = x for i in range(1, self.log + 1): self.__update(p >> i) def get(self, p: int): assert 0 <= p and p < self._n return self.d[p + self.size] def prod(self, l: int, r: int): assert 0 <= l and l <= r and r <= self._n l += self.size; r += self.size sml, smr = self.e(), self.e() while l < r: if l & 1: sml = self.op(sml, self.d[l]); l += 1 if r & 1: r -= 1; smr = self.op(self.d[r], smr) l >>= 1; r >>= 1 return self.op(sml, smr) def all_prod(self): return self.d[1] def max_right(self, l: int, f): assert 0 <= l and l <= self._n assert f(self.e()) if l == self._n: return self._n l += self.size sm = self.e() while True: while l % 2 == 0: l >>= 1 if not f(self.op(sm, self.d[l])): while l < self.size: l = 2 * l if f(self.op(sm, self.d[l])): sm = self.op(sm, self.d[l]) l += 1 return l - self.size sm = self.op(sm, self.d[l]) l += 1 if (l & -l) == l: break return self._n def min_left(self, r: int, f): assert 0 <= r and r <= self._n assert f(self.e()) if r == 0: return 0 r += self.size sm = self.e() while True: r -= 1 while r > 1 and r % 2: r >>= 1 if not f(self.op(self.d[r], sm)): while r < self.size: r = 2 * r + 1 if f(self.op(self.d[r], sm)): sm = self.op(self.d[r], sm) r -= 1 return r + 1 - self.size sm = self.op(self.d[r], sm) if (r & -r) == r: break return 0 def __update(self, k: int): self.d[k] = self.op(self.d[k * 2], self.d[k * 2 + 1]) # string.py def sa_native(s: list): from functools import cmp_to_key def mycmp(r, l): if l == r: return -1 while l < n and r < n: if s[l] != s[r]: return 1 if s[l] < s[r] else -1 l += 1 r += 1 return 1 if l == n else -1 n = len(s) sa = [i for i in range(n)] sa.sort(key=cmp_to_key(mycmp)) return sa def sa_doubling(s: list): from functools import cmp_to_key def mycmp(y, x): if rnk[x] != rnk[y]: return 1 if rnk[x] < rnk[y] else -1 rx = rnk[x + k] if x + k < n else - 1 ry = rnk[y + k] if y + k < n else - 1 return 1 if rx < ry else -1 n = len(s) sa = [i for i in range(n)]; rnk = s; tmp = [0] * n; k = 1 while k < n: sa.sort(key=cmp_to_key(mycmp)) tmp[sa[0]] = 0 for i in range(1, n): tmp[sa[i]] = tmp[sa[i - 1]] if mycmp(sa[i], sa[i - 1]): tmp[sa[i]] += 1 tmp, rnk = rnk, tmp k *= 2 return sa def sa_is(s: list, upper: int): THRESHOLD_NATIVE = 10 THRESHOLD_DOUBLING = 40 n = len(s) if n == 0: return [] if n == 1: return [0] if n == 2: if s[0] < s[1]: return [0, 1] else: return [1, 0] if n < THRESHOLD_NATIVE: return sa_native(s) if n < THRESHOLD_DOUBLING: return sa_doubling(s) sa = [0] * n ls = [False] * n for i in range(n - 2, -1, -1): ls[i] = ls[i + 1] if s[i] == s[i + 1] else s[i] < s[i + 1] sum_l = [0] * (upper + 1); sum_s = [0] * (upper + 1) for i in range(n): if not ls[i]: sum_s[s[i]] += 1 else: sum_l[s[i] + 1] += 1 for i in range(upper + 1): sum_s[i] += sum_l[i] if i < upper: sum_l[i + 1] += sum_s[i] def induce(lms: list): from copy import copy for i in range(n): sa[i] = -1 buf = copy(sum_s) for d in lms: if d == n: continue sa[buf[s[d]]] = d; buf[s[d]] += 1 buf = copy(sum_l) sa[buf[s[n - 1]]] = n - 1; buf[s[n - 1]] += 1 for i in range(n): v = sa[i] if v >= 1 and not ls[v - 1]: sa[buf[s[v - 1]]] = v - 1; buf[s[v - 1]] += 1 buf = copy(sum_l) for i in range(n - 1, -1, -1): v = sa[i] if v >= 1 and ls[v - 1]: buf[s[v - 1] + 1] -= 1; sa[buf[s[v - 1] + 1]] = v - 1 lms_map = [-1] * (n + 1) m = 0 for i in range(1, n): if not ls[i - 1] and ls[i]: lms_map[i] = m; m += 1 lms = [i for i in range(1, n) if not ls[i - 1] and ls[i]] induce(lms) if m: sorted_lms = [v for v in sa if lms_map[v] != -1] rec_s = [0] * m rec_upper = 0 rec_s[lms_map[sorted_lms[0]]] = 0 for i in range(1, m): l = sorted_lms[i - 1]; r = sorted_lms[i] end_l = lms[lms_map[l] + 1] if lms_map[l] + 1 < m else n end_r = lms[lms_map[r] + 1] if lms_map[r] + 1 < m else n same = True if end_l - l != end_r - r: same = False else: while l < end_l: if s[l] != s[r]: break l += 1 r += 1 if l == n or s[l] != s[r]: same = False if not same: rec_upper += 1 rec_s[lms_map[sorted_lms[i]]] = rec_upper rec_sa = sa_is(rec_s, rec_upper) for i in range(m): sorted_lms[i] = lms[rec_sa[i]] induce(sorted_lms) return sa def suffix_array(s: list, upper: int): assert 0 <= upper for d in s: assert 0 <= d and d <= upper sa = sa_is(s, upper) return sa def suffix_array2(s: list): from functools import cmp_to_key n = len(s) idx = [i for i in range(n)] idx.sort(key=cmp_to_key(lambda l, r: s[l] < s[r])) s2 = [0] * n now = 0 for i in range(n): if i and s[idx[i - 1]] != s[idx[i]]: now += 1 s2[idx[i]] = now return sa_is(s2, now) def suffix_array3(s: str): n = len(s) s2 = list(map(ord, s)) return sa_is(s2, 255) def lcp_array(s: list, sa: list): n = len(s) assert n >= 1 rnk = [0] * n for i in range(n): rnk[sa[i]] = i lcp = [0] * (n - 1) h = 0 for i in range(n): if h > 0: h -= 1 if rnk[i] == 0: continue j = sa[rnk[i] - 1] while j + h < n and i + h < n: if s[j + h] != s[i + h]: break h += 1 lcp[rnk[i] - 1] = h return lcp def lcp_array2(s: str, sa: list): n = len(s) s2 = list(map(ord, s)) return lcp_array(s2, sa) def z_algorithm(s: list): n = len(s) if n == 0: return [] z = [-1] * n z[0] = 0; j = 0 for i in range(1, n): k = z[i] = 0 if j + z[j] <= i else min(j + z[j] - i, z[i - j]) while i + k < n and s[k] == s[i + k]: k += 1 z[i] = k if j + z[j] < i + z[i]: j = i z[0] = n return z def z_algorithm2(s: str): n = len(s) s2 = list(map(ord, s)) return z_algorithm(s2) # twosat.py class two_sat: def __init__(self, n: int): self._n = n self.scc = scc_graph(2 * n) self._answer = [False] * n def add_clause(self, i: int, f: bool, j: int, g: bool): assert 0 <= i and i < self._n assert 0 <= j and j < self._n self.scc.add_edge(2 * i + (not f), 2 * j + g) self.scc.add_edge(2 * j + (not g), 2 * i + f) def satisfiable(self) -> bool: _id = self.scc.scc_ids()[1] for i in range(self._n): if _id[2 * i] == _id[2 * i + 1]: return False self._answer[i] = _id[2 * i] < _id[2 * i + 1] return True def answer(self): return self._answer # --------------------<< Library End >>-------------------- # import sys sys.setrecursionlimit(10 ** 6) MOD = 10 ** 9 + 7 INF = 10 ** 9 PI = 3.14159265358979323846 def read_str(): return sys.stdin.readline().strip() def read_int(): return int(sys.stdin.readline().strip()) def read_ints(): return map(int, sys.stdin.readline().strip().split()) def read_ints2(x): return map(lambda num: int(num) - x, sys.stdin.readline().strip().split()) def read_str_list(): return list(sys.stdin.readline().strip().split()) def read_int_list(): return list(map(int, sys.stdin.readline().strip().split())) def GCD(a: int, b: int) -> int: return b if a%b==0 else GCD(b, a%b) def LCM(a: int, b: int) -> int: return (a * b) // GCD(a, b) def Main_A(): n, q = read_ints() d = dsu(n) for _ in range(q): t, u, v = read_ints() if t == 0: d.merge(u, v) else: print(int(d.same(u, v))) def Main_B(): n, q = read_ints() a = read_int_list() fw = fenwick_tree(n) for i, x in enumerate(a): fw.add(i, x) for _ in range(q): query = read_int_list() if query[0] == 0: fw.add(query[1], query[2]) else: print(fw.sum(query[1], query[2])) def Main_C(): for _ in range(read_int()): n, m, a, b = read_ints() print(floor_sum(n, m, a, b)) #from collections import deque def Main_D(): n, m = read_ints() grid = [list(read_str()) for _ in range(n)] mf = mf_graph(n * m + 2) start = n * m end = start + 1 dir = [(1, 0), (0, 1)] for y in range(n): for x in range(m): if (y + x) % 2 == 0: mf.add_edge(start, m*y + x, 1) else: mf.add_edge(m*y + x, end, 1) if grid[y][x] == '.': for dy, dx in dir: ny = y + dy; nx = x + dx if ny < n and nx < m and grid[ny][nx] == '.': f, t = y*m + x, ny*m + nx if (y + x) % 2: f, t = t, f mf.add_edge(f, t, 1) ans = mf.flow(start, end) for y in range(n): for x in range(m): for e in mf.g[y * m + x]: to, rev, cap = e.to, e.rev, e.cap ny, nx = divmod(to, m) if (y + x) % 2 == 0 and cap == 0 and to != start and to != end and (y*m+x) != start and (y*m+x) != end: if y + 1 == ny: grid[y][x] = 'v'; grid[ny][nx] = '^' elif y == ny + 1: grid[y][x] = '^'; grid[ny][nx] = 'v' elif x + 1 == nx: grid[y][x] = '>'; grid[ny][nx] = '<' elif x == nx + 1: grid[y][x] = '<'; grid[ny][nx] = '>' print(ans) print(*[''.join(ret) for ret in grid], sep='\n') #from heapq import heappop, heappush def Main_E(): n, k = read_ints() a = [read_int_list() for _ in range(n)] mcf = mcf_graph(n * 2 + 2) s = n * 2 t = n * 2 + 1 for i in range(n): mcf.add_edge(s, i, k, 0) mcf.add_edge(i + n, t, k, 0) mcf.add_edge(s, t, n * k, INF) for i in range(n): for j in range(n): mcf.add_edge(i, n + j, 1, INF - a[i][j]) result = mcf.flow_(s, t, n * k) print(n * k * INF - result[1]) grid = [['.'] * n for _ in range(n)] edges = mcf.edges() for e in edges: if e._from == s or e._to == t or e.flow == 0: continue grid[e._from][e._to - n] = 'X' print(*[''.join(g) for g in grid], sep='\n') def Main_F(): MOD = 998244353 n, m = read_ints() a = read_int_list() b = read_int_list() a = [x % MOD for x in a] b = [x % MOD for x in b] cnv = convolution(a,b,MOD) ans = cnv.convolution() print(*ans) def Main_G(): sys.setrecursionlimit(10 ** 6) n, m = read_ints() scc = scc_graph(n) for _ in range(m): a, b = read_ints() scc.add_edge(a, b) ans = scc.scc() print(len(ans)) for v in ans: print(len(v), ' '.join(map(str, v[::-1]))) def Main_H(): n, d = read_ints() xy = [read_int_list() for _ in range(n)] tw = two_sat(n) for i in range(n): for j in range(i + 1, n): for x in range(2): if abs(xy[i][0] - xy[j][0]) < d: tw.add_clause(i, False, j, False) if abs(xy[i][0] - xy[j][1]) < d: tw.add_clause(i, False, j, True) if abs(xy[i][1] - xy[j][0]) < d: tw.add_clause(i, True, j, False) if abs(xy[i][1] - xy[j][1]) < d: tw.add_clause(i, True, j, True) if not tw.satisfiable(): print('No') exit() print('Yes') ans = tw.answer() for i, flag in enumerate(ans): print(xy[i][0] if flag else xy[i][1]) def Main_I(): s = read_str() sa = suffix_array3(s) ans = len(s) * (len(s) + 1) // 2 for x in lcp_array2(s, sa): ans -= x print(ans) def Main_J(): def op(l, r): return max(l, r) def e(): return -1 def f(n): return n < r n, q = read_ints() a = read_int_list() seg = segtree(op, e, a) query = [(read_ints()) for _ in range(q)] for i in range(q): t, l, r = query[i] if t == 1: seg.set_(~-l, r) elif t == 2: print(seg.prod(~-l, r)) else: print(seg.max_right(~-l, f) + 1) def Main_K(): p = 998244353 def op(l, r): l1, l2 = l >> 32, l % (1 << 32) r1, r2 = r >> 32, r % (1 << 32) return (((l1 + r1) % p) << 32) + l2 + r2 def e(): return 0 def mapping(l, r): l1, l2 = l >> 32, l % (1 << 32) r1, r2 = r >> 32, r % (1 << 32) return (((l1 * r1 + l2 * r2) % p) << 32) + r2 def composition(l, r): l1, l2 = l >> 32, l % (1 << 32) r1, r2 = r >> 32, r % (1 << 32) return ((l1 * r1 % p) << 32) + (l1 * r2 + l2) % p def id(): return 1 << 32 n, q = read_ints() A = read_int_list() A = [(x << 32) + 1 for x in A] seg = lazy_segtree(op, e, mapping, composition, id, A) ans = [] for _ in range(q): query = read_int_list() if query[0] == 0: l, r, b, c = query[1:] seg.apply(l, r, (b << 32) + c) else: l, r = query[1:] print(seg.prod(l, r) >> 32) def Main_L(): def op(l: tuple, r: tuple): return (l[0] + r[0], l[1] + r[1], l[2] + r[2] + l[1] * r[0]) def e(): return (0, 0, 0) def mapping(l:bool, r: tuple): if not l: return r return (r[1], r[0], r[1] * r[0] - r[2]) def composition(l: bool, r: bool): return l ^ r def id(): return False n, q = read_ints() A = read_int_list() query = [(read_ints()) for _ in range(q)] a = [(1, 0, 0) if i == 0 else (0, 1, 0) for i in A] seg = lazy_segtree(op, e, mapping, composition, id, a) for t, l, r in query: if t == 1: seg.apply(~-l, r, True) else: print(seg.prod(~-l, r)[2]) if __name__ == '__main__': Main_F() ```
97,594
Provide a correct Python 3 solution for this coding contest problem. You are given two integer arrays a_0, a_1, ..., a_{N - 1} and b_0, b_1, ..., b_{M - 1}. Calculate the array c_0, c_1, ..., c_{(N - 1) + (M - 1)}, defined by c_i = \sum_{j = 0}^i a_j b_{i - j} \bmod 998244353. Constraints * 1 \leq N, M \leq 524288 * 0 \leq a_i, b_i < 998244353 * All values in Input are integer. Input Input is given from Standard Input in the following format: N M a_0 a_1 ... a_{N-1} b_0 b_1 ... b_{M-1} Output Print the answer in the following format: c_0 c_1 ... c_{(N - 1) + (M - 1)} Output Print the answer in the following format: c_0 c_1 ... c_{(N - 1) + (M - 1)} Examples Input 4 5 1 2 3 4 5 6 7 8 9 Output 5 16 34 60 70 70 59 36 Input 1 1 10000000 10000000 Output 871938225 "Correct Solution: ``` MOD=[469762049,2281701377,2483027969] D=dict() def DFTm(A,proot,mod,s): n=1<<s m=n>>1 if n==1: return 0 X,Y=[],[] for i in range(0,n,2): X.append(A[i]) Y.append(A[i+1]) DFTm(X,proot,mod,s-1) DFTm(Y,proot,mod,s-1) a,b=1,0 if D.get((proot,s),-1)==-1: b=pow(proot,(mod-1)>>s,mod) D[(proot,s)]=b else: b=D[(proot,s)] for i in range(n): A[i]=(X[i&(m-1)]+a*Y[i&(m-1)])%mod a=a*b%mod def FFTm(X,Y,mod): n=1 c=0 while len(X)+len(Y)>n: n<<=1 c+=1 A=X[:] B=Y[:] while len(A)<n: A.append(0) while len(B)<n: B.append(0) DFTm(A,3,mod,c) DFTm(B,3,mod,c) for i in range(n): A[i]=A[i]*B[i]%mod DFTm(A,pow(3,mod-2,mod),mod,c) z=pow(n,mod-2,mod) for i in range(n): A[i]=A[i]*z%mod return A N,M=map(int,input().split()) print(*FFTm(list(map(int,input().split())),list(map(int,input().split())),998244353)[:N+M-1]) ```
97,595
Provide a correct Python 3 solution for this coding contest problem. You are given two integer arrays a_0, a_1, ..., a_{N - 1} and b_0, b_1, ..., b_{M - 1}. Calculate the array c_0, c_1, ..., c_{(N - 1) + (M - 1)}, defined by c_i = \sum_{j = 0}^i a_j b_{i - j} \bmod 998244353. Constraints * 1 \leq N, M \leq 524288 * 0 \leq a_i, b_i < 998244353 * All values in Input are integer. Input Input is given from Standard Input in the following format: N M a_0 a_1 ... a_{N-1} b_0 b_1 ... b_{M-1} Output Print the answer in the following format: c_0 c_1 ... c_{(N - 1) + (M - 1)} Output Print the answer in the following format: c_0 c_1 ... c_{(N - 1) + (M - 1)} Examples Input 4 5 1 2 3 4 5 6 7 8 9 Output 5 16 34 60 70 70 59 36 Input 1 1 10000000 10000000 Output 871938225 "Correct Solution: ``` MOD = None sum_e = (911660635, 509520358, 369330050, 332049552, 983190778, 123842337, 238493703, 975955924, 603855026, 856644456, 131300601, 842657263, 730768835, 942482514, 806263778, 151565301, 510815449, 503497456, 743006876, 741047443, 56250497, 0, 0, 0, 0, 0, 0, 0, 0, 0) sum_ie = (86583718, 372528824, 373294451, 645684063, 112220581, 692852209, 155456985, 797128860, 90816748, 860285882, 927414960, 354738543, 109331171, 293255632, 535113200, 308540755, 121186627, 608385704, 438932459, 359477183, 824071951, 0, 0, 0, 0, 0, 0, 0, 0, 0) class Convolution: # ROOT = 3 def __init__(self, mod): global MOD MOD = mod # self.MOD = mod def __butterfly(self, arr): n = len(arr) h = (n - 1).bit_length() # MOD = self.MOD for ph in range(1, h + 1): w = 1 << (ph - 1) p = 1 << (h - ph) now = 1 for s in range(w): offset = s << (h - ph + 1) for i in range(p): l = arr[i + offset] r = arr[i + offset + p] * now arr[i + offset] = (l + r) % MOD arr[i + offset + p] = (l - r) % MOD now *= sum_e[(~s & -~s).bit_length() - 1] now %= MOD def __butterfly_inv(self, arr): n = len(arr) h = (n - 1).bit_length() # MOD = self.MOD for ph in range(1, h + 1)[::-1]: w = 1 << (ph - 1) p = 1 << (h - ph) inow = 1 for s in range(w): offset = s << (h - ph + 1) for i in range(p): l = arr[i + offset] r = arr[i + offset + p] arr[i + offset] = (l + r) % MOD arr[i + offset + p] = (MOD + l - r) * inow % MOD inow *= sum_ie[(~s & -~s).bit_length() - 1] inow %= MOD def __call__(self, a, b): n = len(a) m = len(b) # MOD = self.MOD if not n or not m: return [] if min(n, m) <= 50: if n < m: n, m = m, n a, b = b, a res = [0] * (n + m - 1) for i in range(n): for j in range(m): res[i + j] += a[i] * b[j] res[i + j] %= MOD return res z = 1 << (n + m - 2).bit_length() a += [0] * (z - n) b += [0] * (z - m) self.__butterfly(a) self.__butterfly(b) for i in range(z): a[i] *= b[i] a[i] %= MOD self.__butterfly_inv(a) a = a[:n + m - 1] iz = pow(z, MOD - 2, MOD) for i in range(n + m - 1): a[i] *= iz a[i] %= MOD return a def atcoder_practice2_f(): import sys input = sys.stdin.buffer.readline N, M = map(int, input().split()) A = [int(x) for x in input().split()] B = [int(x) for x in input().split()] convolution = Convolution(998244353) print(*convolution(A, B)) if __name__ == "__main__": atcoder_practice2_f() ```
97,596
Provide a correct Python 3 solution for this coding contest problem. You are given two integer arrays a_0, a_1, ..., a_{N - 1} and b_0, b_1, ..., b_{M - 1}. Calculate the array c_0, c_1, ..., c_{(N - 1) + (M - 1)}, defined by c_i = \sum_{j = 0}^i a_j b_{i - j} \bmod 998244353. Constraints * 1 \leq N, M \leq 524288 * 0 \leq a_i, b_i < 998244353 * All values in Input are integer. Input Input is given from Standard Input in the following format: N M a_0 a_1 ... a_{N-1} b_0 b_1 ... b_{M-1} Output Print the answer in the following format: c_0 c_1 ... c_{(N - 1) + (M - 1)} Output Print the answer in the following format: c_0 c_1 ... c_{(N - 1) + (M - 1)} Examples Input 4 5 1 2 3 4 5 6 7 8 9 Output 5 16 34 60 70 70 59 36 Input 1 1 10000000 10000000 Output 871938225 "Correct Solution: ``` p, g, ig = 998244353, 3, 332748118 W = [pow(g, (p - 1) >> i, p) for i in range(24)] iW = [pow(ig, (p - 1) >> i, p) for i in range(24)] def fft(k, f): for l in range(k, 0, -1): d = 1 << l - 1 U = [1] for i in range(d): U.append(U[-1] * W[l] % p) for i in range(1 << k - l): for j in range(d): s = i * 2 * d + j t = s + d f[s], f[t] = (f[s] + f[t]) % p, U[j] * (f[s] - f[t]) % p def ifft(k, f): for l in range(1, k + 1): d = 1 << l - 1 U = [1] for i in range(d): U.append(U[-1] * iW[l] % p) for i in range(1 << k - l): for j in range(d): s = i * 2 * d + j t = s + d f[s], f[t] = (f[s] + f[t] * U[j]) % p, (f[s] - f[t] * U[j]) % p def convolve(a, b): n0 = len(a) + len(b) - 1 k = (n0).bit_length() n = 1 << k a = a + [0] * (n - len(a)) b = b + [0] * (n - len(b)) fft(k, a), fft(k, b) for i in range(n): a[i] = a[i] * b[i] % p ifft(k, a) invn = pow(n, p - 2, p) for i in range(n0): a[i] = a[i] * invn % p del a[n0:] return a N, M = map(int, input().split()) A = [int(a) for a in input().split()] B = [int(a) for a in input().split()] print(*convolve(A, B)) ```
97,597
Provide a correct Python 3 solution for this coding contest problem. You are given two integer arrays a_0, a_1, ..., a_{N - 1} and b_0, b_1, ..., b_{M - 1}. Calculate the array c_0, c_1, ..., c_{(N - 1) + (M - 1)}, defined by c_i = \sum_{j = 0}^i a_j b_{i - j} \bmod 998244353. Constraints * 1 \leq N, M \leq 524288 * 0 \leq a_i, b_i < 998244353 * All values in Input are integer. Input Input is given from Standard Input in the following format: N M a_0 a_1 ... a_{N-1} b_0 b_1 ... b_{M-1} Output Print the answer in the following format: c_0 c_1 ... c_{(N - 1) + (M - 1)} Output Print the answer in the following format: c_0 c_1 ... c_{(N - 1) + (M - 1)} Examples Input 4 5 1 2 3 4 5 6 7 8 9 Output 5 16 34 60 70 70 59 36 Input 1 1 10000000 10000000 Output 871938225 "Correct Solution: ``` MOD = 998244353 ROOT = 3 class Convolution_998244353(): def __init__(self): self.sum_e = [911660635, 509520358, 369330050, 332049552, 983190778, 123842337, 238493703, 975955924, 603855026, 856644456, 131300601, 842657263, 730768835, 942482514, 806263778, 151565301, 510815449, 503497456, 743006876, 741047443, 56250497, 0, 0, 0, 0, 0, 0, 0, 0, 0] self.sum_ie = [86583718, 372528824, 373294451, 645684063, 112220581, 692852209, 155456985, 797128860, 90816748, 860285882, 927414960, 354738543, 109331171, 293255632, 535113200, 308540755, 121186627, 608385704, 438932459, 359477183, 824071951, 0, 0, 0, 0, 0, 0, 0, 0, 0] def butterfly(self, arr): n = len(arr) h = (n - 1).bit_length() for ph in range(1, h + 1): w = 1 << (ph - 1) p = 1 << (h - ph) now = 1 for s in range(w): offset = s << (h - ph + 1) for i in range(p): l = arr[i + offset] r = arr[i + offset + p] * now arr[i + offset] = (l + r) % MOD arr[i + offset + p] = (l - r) % MOD now *= self.sum_e[(~s & -~s).bit_length() - 1] now %= MOD def butterfly_inv(self, arr): n = len(arr) h = (n - 1).bit_length() for ph in range(1, h + 1)[::-1]: w = 1 << (ph - 1) p = 1 << (h - ph) inow = 1 for s in range(w): offset = s << (h - ph + 1) for i in range(p): l = arr[i + offset] r = arr[i + offset + p] arr[i + offset] = (l + r) % MOD arr[i + offset + p] = (MOD + l - r) * inow % MOD inow *= self.sum_ie[(~s & -~s).bit_length() - 1] inow %= MOD def convolution(self, a, b): n = len(a) m = len(b) if not n or not m: return [] if min(n, m) <= 50: if n < m: n, m = m, n a, b = b, a res = [0] * (n + m - 1) for i in range(n): for j in range(m): res[i + j] += a[i] * b[j] res[i + j] %= MOD return res z = 1 << (n + m - 2).bit_length() a += [0] * (z - n) b += [0] * (z - m) self.butterfly(a) self.butterfly(b) for i in range(z): a[i] *= b[i] a[i] %= MOD self.butterfly_inv(a) a = a[:n + m - 1] iz = pow(z, MOD - 2, MOD) for i in range(n + m - 1): a[i] *= iz a[i] %= MOD return a def autocorrelation(self, a): n = len(a) if not n: return [] if n <= 50: res = [0] * (2 * n - 1) for i in range(n): for j in range(n): res[i + j] += a[i] * a[j] res[i + j] %= MOD return res z = 1 << (2 * n - 2).bit_length() a += [0] * (z - n) self.butterfly(a) for i in range(a): a[i] *= a[i] a[i] %= MOD self.butterfly_inv(a) a = a[:2 * n - 1] iz = pow(z, MOD - 2, MOD) for i in range(2 * n - 1): a[i] *= iz a[i] %= MOD return a import sys input = sys.stdin.buffer.readline N, M = map(int, input().split()) A = [int(x) for x in input().split()] B = [int(x) for x in input().split()] cv = Convolution_998244353() print(*cv.convolution(A, B)) ```
97,598
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two integer arrays a_0, a_1, ..., a_{N - 1} and b_0, b_1, ..., b_{M - 1}. Calculate the array c_0, c_1, ..., c_{(N - 1) + (M - 1)}, defined by c_i = \sum_{j = 0}^i a_j b_{i - j} \bmod 998244353. Constraints * 1 \leq N, M \leq 524288 * 0 \leq a_i, b_i < 998244353 * All values in Input are integer. Input Input is given from Standard Input in the following format: N M a_0 a_1 ... a_{N-1} b_0 b_1 ... b_{M-1} Output Print the answer in the following format: c_0 c_1 ... c_{(N - 1) + (M - 1)} Output Print the answer in the following format: c_0 c_1 ... c_{(N - 1) + (M - 1)} Examples Input 4 5 1 2 3 4 5 6 7 8 9 Output 5 16 34 60 70 70 59 36 Input 1 1 10000000 10000000 Output 871938225 Submitted Solution: ``` N,M = map(int,input().split()) A = list(map(int,input().split())) B = list(map(int,input().split())) MOD = 998244353 class Convolution: def __init__(self): pass def _ceil_pow2(self, n): assert n >= 0 x = 0 while (1<<x) < n: x += 1 return x def _bsf(self, n): assert n >= 1 return len(bin(n & -n)) - 3 def _butterfly(self,a,mod): n = len(a) h = self._ceil_pow2(n) self.sum_e = [0] * 30 es = [0] * 30 ies = [0] * 30 cnt2 = self._bsf(mod - 1) g = 3 #primitive_root ?? e = pow(g, (mod-1)>>cnt2, mod) ie = pow(e,mod-2,mod) for i in range(cnt2,1,-1): es[i-2] = e ies[i-2] = ie e *= e e %= mod ie *= ie ie %= mod now = 1 for i in range(cnt2 - 2): self.sum_e[i] = (es[i] * now) % mod now *= ies[i] now %= mod for ph in range(1,h+1): w = 1 << (ph-1) p = 1 << (h-ph) now = 1 for s in range(w): offset = s << (h - ph + 1) for i in range(p): l = a[i + offset] r = a[i + offset + p] * now a[i + offset] = (l+r) % mod a[i + offset + p] = (l-r) % mod now *= self.sum_e[self._bsf(((1<<32)-1)^s)] now %= mod def _butterfly_inv(self,a,mod): n = len(a) h = self._ceil_pow2(n) self.sum_ie = [0] * 30 es = [0] * 30 ies = [0] * 30 cnt2 = self._bsf(mod - 1) g = 3 #primitive_root ?? e = pow(g, (mod-1)>>cnt2, mod) ie = pow(e,mod-2,mod) for i in range(cnt2,1,-1): es[i-2] = e ies[i-2] = ie e *= e e %= mod ie *= ie ie %= mod now = 1 for i in range(cnt2 - 2): self.sum_ie[i] = (ies[i] * now) % mod now *= es[i] now %= mod for ph in range(h,0,-1): w = 1 << (ph-1) p = 1 << (h-ph) inow = 1 for s in range(w): offset = s << (h - ph + 1) for i in range(p): l = a[i + offset] r = a[i + offset + p] a[i + offset] = (l+r) % mod a[i + offset + p] = ((l-r) * inow) % mod inow *= self.sum_ie[self._bsf(((1<<32)-1)^s)] inow %= mod def convolution_mod(self, a, b, mod): n,m = len(a),len(b) if n==0 or m==0: return [] if min(n,m) <= 60: if n < m: a,b,n,m = b,a,m,n ans = [0] * (n+m-1) for i in range(n): for j in range(m): ans[i+j] += a[i] * b[j] ans[i+j] %= mod return ans z = 1 << self._ceil_pow2(n+m-1) a += [0] * (z-n) self._butterfly(a,mod) b += [0] * (z-m) self._butterfly(b,mod) for i in range(z): a[i] *= b[i] a[i] %= mod self._butterfly_inv(a,mod) a = a[:n+m-1] iz = pow(z,mod-2,mod) for i in range(n+m-1): a[i] *= iz a[i] %= mod return a ans = Convolution().convolution_mod(A,B,MOD) print(*ans) ``` Yes
97,599