text
stringlengths
198
433k
conversation_id
int64
0
109k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given the strings a and b, consisting of lowercase Latin letters. You can do any number of the following operations in any order: * if |a| > 0 (the length of the string a is greater than zero), delete the first character of the string a, that is, replace a with a_2 a_3 … a_n; * if |a| > 0, delete the last character of the string a, that is, replace a with a_1 a_2 … a_{n-1}; * if |b| > 0 (the length of the string b is greater than zero), delete the first character of the string b, that is, replace b with b_2 b_3 … b_n; * if |b| > 0, delete the last character of the string b, that is, replace b with b_1 b_2 … b_{n-1}. Note that after each of the operations, the string a or b may become empty. For example, if a="hello" and b="icpc", then you can apply the following sequence of operations: * delete the first character of the string a β‡’ a="ello" and b="icpc"; * delete the first character of the string b β‡’ a="ello" and b="cpc"; * delete the first character of the string b β‡’ a="ello" and b="pc"; * delete the last character of the string a β‡’ a="ell" and b="pc"; * delete the last character of the string b β‡’ a="ell" and b="p". For the given strings a and b, find the minimum number of operations for which you can make the strings a and b equal. Note that empty strings are also equal. Input The first line contains a single integer t (1 ≀ t ≀ 100). Then t test cases follow. The first line of each test case contains the string a (1 ≀ |a| ≀ 20), consisting of lowercase Latin letters. The second line of each test case contains the string b (1 ≀ |b| ≀ 20), consisting of lowercase Latin letters. Output For each test case, output the minimum number of operations that can make the strings a and b equal. Example Input 5 a a abcd bc hello codeforces hello helo dhjakjsnasjhfksafasd adjsnasjhfksvdafdser Output 0 2 13 3 20 Submitted Solution: ``` from collections import defaultdict,OrderedDict,Counter from sys import stdin,stdout from bisect import bisect_left,bisect_right # import numpy as np from queue import Queue,PriorityQueue from heapq import * from statistics import * from math import * import fractions import copy from copy import deepcopy import sys import io sys.setrecursionlimit(10000) import math import os import bisect import collections mod=pow(10,9)+7 import random from random import * from time import time; def ncr(n, r, p=mod): num = den = 1 for i in range(r): num = (num * (n - i)) % p den = (den * (i + 1)) % p return (num * pow(den, p - 2, p)) % p def normalncr(n,r): r=min(r,n-r) count=1; for i in range(n-r,n+1): count*=i; for i in range(1,r+1): count//=i; return count inf=float("inf") adj=defaultdict(set) visited=defaultdict(int) def addedge(a,b): adj[a].add(b) adj[b].add(a) def bfs(v): q=Queue() q.put(v) visited[v]=1 while q.qsize()>0: s=q.get_nowait() print(s) for i in adj[s]: if visited[i]==0: q.put(i) visited[i]=1 def dfs(v,visited): if visited[v]==1: return; visited[v]=1 print(v) for i in adj[v]: dfs(i,visited) # a9=pow(10,6)+10 # prime = [True for i in range(a9 + 1)] # def SieveOfEratosthenes(n): # p = 2 # while (p * p <= n): # if (prime[p] == True): # for i in range(p * p, n + 1, p): # prime[i] = False # p += 1 # SieveOfEratosthenes(a9) # prime_number=[] # for i in range(2,a9): # if prime[i]: # prime_number.append(i) def reverse_bisect_right(a, x, lo=0, hi=None): if lo < 0: raise ValueError('lo must be non-negative') if hi is None: hi = len(a) while lo < hi: mid = (lo+hi)//2 if x > a[mid]: hi = mid else: lo = mid+1 return lo def reverse_bisect_left(a, x, lo=0, hi=None): if lo < 0: raise ValueError('lo must be non-negative') if hi is None: hi = len(a) while lo < hi: mid = (lo+hi)//2 if x >= a[mid]: hi = mid else: lo = mid+1 return lo def get_list(): return list(map(int,input().split())) def get_str_list_in_int(): return [int(i) for i in list(input())] def get_str_list(): return list(input()) def get_map(): return map(int,input().split()) def input_int(): return int(input()) def matrix(a,b): return [[0 for i in range(b)] for j in range(a)] def swap(a,b): return b,a def find_gcd(l): a=l[0] for i in range(len(l)): a=gcd(a,l[i]) return a; def is_prime(n): sqrta=int(sqrt(n)) for i in range(2,sqrta+1): if n%i==0: return 0; return 1; def prime_factors(n): while n % 2 == 0: return [2]+prime_factors(n//2) sqrta = int(sqrt(n)) for i in range(3,sqrta+1,2): if n%i==0: return [i]+prime_factors(n//i) return [n] def p(a): if type(a)==str: print(a+"\n") else: print(str(a)+"\n") def ps(a): if type(a)==str: print(a) else: print(str(a)) def kth_no_not_div_by_n(n,k): return k+(k-1)//(n-1) def forward_array(l): n=len(l) stack = [] forward=[0]*n for i in range(len(l) - 1, -1, -1): while len(stack) and l[stack[-1]] < l[i]: stack.pop() if len(stack) == 0: forward[i] = len(l); else: forward[i] = stack[-1] stack.append(i) return forward; def backward_array(l): n=len(l) stack = [] backward=[0]*n for i in range(len(l)): while len(stack) and l[stack[-1]] < l[i]: stack.pop() if len(stack) == 0: backward[i] = -1; else: backward[i] = stack[-1] stack.append(i) return backward nc="NO" yc="YES" ns="No" ys="Yes" # import math as mt # MAXN=10**7 # spf = [0 for i in range(MAXN)] # def sieve(): # spf[1] = 1 # for i in range(2, MAXN): # # marking smallest prime factor # # for every number to be itself. # spf[i] = i # # # separately marking spf for # # every even number as 2 # for i in range(4, MAXN, 2): # spf[i] = 2 # # for i in range(3, mt.ceil(mt.sqrt(MAXN))): # # # checking if i is prime # if (spf[i] == i): # # # marking SPF for all numbers # # divisible by i # for j in range(i * i, MAXN, i): # # # marking spf[j] if it is # # not previously marked # if (spf[j] == j): # spf[j] = i # def getFactorization(x): # ret = list() # while (x != 1): # ret.append(spf[x]) # x = x // spf[x] # # return ret # sieve() # input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline # input=stdin.readline # print=stdout.write # https://www.geeksforgeeks.org/longest-common-substring-dp-29/#:~:text=Explanation%3A,and%20is%20of%20length%205.&text=Output%20%3A%204-,Explanation%3A,and%20is%20of%20length%204. def LCSubStr(X, Y, m, n): LCSuff = [[0 for k in range(n + 1)] for l in range(m + 1)] result = 0 answer=0; for i in range(m + 1): for j in range(n + 1): if (i == 0 or j == 0): answer+=1 LCSuff[i][j] = 0 elif (X[i - 1] == Y[j - 1]): LCSuff[i][j] = LCSuff[i - 1][j - 1] + 1 answer += 1 result = max(result, LCSuff[i][j]) else: LCSuff[i][j] = 0 answer += 1 return result # Driver Code # Function call # This code is contributed by avanitrachhadiya2155 for i in range(int(input())): a=input() b=input() alen=len(a) blen=len(b) lcs=LCSubStr(a,b,alen,blen) print(alen+blen-2*lcs) ``` Yes
11,000
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given the strings a and b, consisting of lowercase Latin letters. You can do any number of the following operations in any order: * if |a| > 0 (the length of the string a is greater than zero), delete the first character of the string a, that is, replace a with a_2 a_3 … a_n; * if |a| > 0, delete the last character of the string a, that is, replace a with a_1 a_2 … a_{n-1}; * if |b| > 0 (the length of the string b is greater than zero), delete the first character of the string b, that is, replace b with b_2 b_3 … b_n; * if |b| > 0, delete the last character of the string b, that is, replace b with b_1 b_2 … b_{n-1}. Note that after each of the operations, the string a or b may become empty. For example, if a="hello" and b="icpc", then you can apply the following sequence of operations: * delete the first character of the string a β‡’ a="ello" and b="icpc"; * delete the first character of the string b β‡’ a="ello" and b="cpc"; * delete the first character of the string b β‡’ a="ello" and b="pc"; * delete the last character of the string a β‡’ a="ell" and b="pc"; * delete the last character of the string b β‡’ a="ell" and b="p". For the given strings a and b, find the minimum number of operations for which you can make the strings a and b equal. Note that empty strings are also equal. Input The first line contains a single integer t (1 ≀ t ≀ 100). Then t test cases follow. The first line of each test case contains the string a (1 ≀ |a| ≀ 20), consisting of lowercase Latin letters. The second line of each test case contains the string b (1 ≀ |b| ≀ 20), consisting of lowercase Latin letters. Output For each test case, output the minimum number of operations that can make the strings a and b equal. Example Input 5 a a abcd bc hello codeforces hello helo dhjakjsnasjhfksafasd adjsnasjhfksvdafdser Output 0 2 13 3 20 Submitted Solution: ``` for _ in range(int(input())): a = input() b = input() la = len(a) lb = len(b) res = 10**18 for i in range(la): for j in range(i, la): ta = a[i:j+1] for x in range(lb): for y in range(x, lb): tb = b[x:y+1] if ta == tb: tmp = 0 tmp += abs(len(ta)-la) tmp += abs(len(tb)-lb) res = min(res, tmp) if res == 10**18: print(la+lb) else: print(res) ``` Yes
11,001
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given the strings a and b, consisting of lowercase Latin letters. You can do any number of the following operations in any order: * if |a| > 0 (the length of the string a is greater than zero), delete the first character of the string a, that is, replace a with a_2 a_3 … a_n; * if |a| > 0, delete the last character of the string a, that is, replace a with a_1 a_2 … a_{n-1}; * if |b| > 0 (the length of the string b is greater than zero), delete the first character of the string b, that is, replace b with b_2 b_3 … b_n; * if |b| > 0, delete the last character of the string b, that is, replace b with b_1 b_2 … b_{n-1}. Note that after each of the operations, the string a or b may become empty. For example, if a="hello" and b="icpc", then you can apply the following sequence of operations: * delete the first character of the string a β‡’ a="ello" and b="icpc"; * delete the first character of the string b β‡’ a="ello" and b="cpc"; * delete the first character of the string b β‡’ a="ello" and b="pc"; * delete the last character of the string a β‡’ a="ell" and b="pc"; * delete the last character of the string b β‡’ a="ell" and b="p". For the given strings a and b, find the minimum number of operations for which you can make the strings a and b equal. Note that empty strings are also equal. Input The first line contains a single integer t (1 ≀ t ≀ 100). Then t test cases follow. The first line of each test case contains the string a (1 ≀ |a| ≀ 20), consisting of lowercase Latin letters. The second line of each test case contains the string b (1 ≀ |b| ≀ 20), consisting of lowercase Latin letters. Output For each test case, output the minimum number of operations that can make the strings a and b equal. Example Input 5 a a abcd bc hello codeforces hello helo dhjakjsnasjhfksafasd adjsnasjhfksvdafdser Output 0 2 13 3 20 Submitted Solution: ``` for i in range(int(input())): ans=0 l=[] a=input() b=input() for i in range(len(a)): for k in range(i+1,len(a)): sub=a[i:k] if sub in b: o=len(a)-len(sub)+len(b)-len(sub) if ans==0: ans=o else: if o<ans: ans=o print(ans) ``` No
11,002
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given the strings a and b, consisting of lowercase Latin letters. You can do any number of the following operations in any order: * if |a| > 0 (the length of the string a is greater than zero), delete the first character of the string a, that is, replace a with a_2 a_3 … a_n; * if |a| > 0, delete the last character of the string a, that is, replace a with a_1 a_2 … a_{n-1}; * if |b| > 0 (the length of the string b is greater than zero), delete the first character of the string b, that is, replace b with b_2 b_3 … b_n; * if |b| > 0, delete the last character of the string b, that is, replace b with b_1 b_2 … b_{n-1}. Note that after each of the operations, the string a or b may become empty. For example, if a="hello" and b="icpc", then you can apply the following sequence of operations: * delete the first character of the string a β‡’ a="ello" and b="icpc"; * delete the first character of the string b β‡’ a="ello" and b="cpc"; * delete the first character of the string b β‡’ a="ello" and b="pc"; * delete the last character of the string a β‡’ a="ell" and b="pc"; * delete the last character of the string b β‡’ a="ell" and b="p". For the given strings a and b, find the minimum number of operations for which you can make the strings a and b equal. Note that empty strings are also equal. Input The first line contains a single integer t (1 ≀ t ≀ 100). Then t test cases follow. The first line of each test case contains the string a (1 ≀ |a| ≀ 20), consisting of lowercase Latin letters. The second line of each test case contains the string b (1 ≀ |b| ≀ 20), consisting of lowercase Latin letters. Output For each test case, output the minimum number of operations that can make the strings a and b equal. Example Input 5 a a abcd bc hello codeforces hello helo dhjakjsnasjhfksafasd adjsnasjhfksvdafdser Output 0 2 13 3 20 Submitted Solution: ``` def match(s,target): for i in range(len(s)): for k in range(len(target)): if target[k] == s[i]: m = k m1 = i nmatches = 0 while m<len(target) and m1 < len(s) and target[m] == s[m1]: m+=1 m1+=1 nmatches+=1 if nmatches == len(s): return True return False def solve(a,b): mins = float("inf") for i in range(len(a)): for j in range(i,len(a)): # print(i,j) # print(a[i:j+1]) if match(a[i:j+1],b): mins = min(mins,len(a)+len(b)-2*len(a[i:j+1])) return mins for _ in range(int(input())): a = input() b = input() print(solve(a,b)) ``` No
11,003
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given the strings a and b, consisting of lowercase Latin letters. You can do any number of the following operations in any order: * if |a| > 0 (the length of the string a is greater than zero), delete the first character of the string a, that is, replace a with a_2 a_3 … a_n; * if |a| > 0, delete the last character of the string a, that is, replace a with a_1 a_2 … a_{n-1}; * if |b| > 0 (the length of the string b is greater than zero), delete the first character of the string b, that is, replace b with b_2 b_3 … b_n; * if |b| > 0, delete the last character of the string b, that is, replace b with b_1 b_2 … b_{n-1}. Note that after each of the operations, the string a or b may become empty. For example, if a="hello" and b="icpc", then you can apply the following sequence of operations: * delete the first character of the string a β‡’ a="ello" and b="icpc"; * delete the first character of the string b β‡’ a="ello" and b="cpc"; * delete the first character of the string b β‡’ a="ello" and b="pc"; * delete the last character of the string a β‡’ a="ell" and b="pc"; * delete the last character of the string b β‡’ a="ell" and b="p". For the given strings a and b, find the minimum number of operations for which you can make the strings a and b equal. Note that empty strings are also equal. Input The first line contains a single integer t (1 ≀ t ≀ 100). Then t test cases follow. The first line of each test case contains the string a (1 ≀ |a| ≀ 20), consisting of lowercase Latin letters. The second line of each test case contains the string b (1 ≀ |b| ≀ 20), consisting of lowercase Latin letters. Output For each test case, output the minimum number of operations that can make the strings a and b equal. Example Input 5 a a abcd bc hello codeforces hello helo dhjakjsnasjhfksafasd adjsnasjhfksvdafdser Output 0 2 13 3 20 Submitted Solution: ``` import os import sys import math from io import BytesIO, IOBase #<fast I/O> 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) #</fast I/O> #<I/O> def scanf(datatype = str): return datatype(sys.stdin.readline().rstrip()) def printf(answer = ''): return sys.stdout.write(str(answer) + "\n") def prints(answer): return sys.stdout.write(str(answer) + " ") def map_input(datatype): return map(datatype, sys.stdin.readline().split()) def list_input(datatype): return list(map(datatype, sys.stdin.readline().split())) def testcase(number: int, solve_function): for i in range(number): printf(solve_function()) #</I/O> def solve(): a = scanf() b = scanf() if(len(a)>len(b)): a,b = b,a maxi = -1 for i in range(len(a)): for j in range(i+1,len(a)+1): if(a[i:j] in b): maxi = max(len(a[i:j]),maxi) return (len(a) + len(b) - 2*maxi) #<solution> t = scanf(int) testcase(t,solve) #<solution> ``` No
11,004
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given the strings a and b, consisting of lowercase Latin letters. You can do any number of the following operations in any order: * if |a| > 0 (the length of the string a is greater than zero), delete the first character of the string a, that is, replace a with a_2 a_3 … a_n; * if |a| > 0, delete the last character of the string a, that is, replace a with a_1 a_2 … a_{n-1}; * if |b| > 0 (the length of the string b is greater than zero), delete the first character of the string b, that is, replace b with b_2 b_3 … b_n; * if |b| > 0, delete the last character of the string b, that is, replace b with b_1 b_2 … b_{n-1}. Note that after each of the operations, the string a or b may become empty. For example, if a="hello" and b="icpc", then you can apply the following sequence of operations: * delete the first character of the string a β‡’ a="ello" and b="icpc"; * delete the first character of the string b β‡’ a="ello" and b="cpc"; * delete the first character of the string b β‡’ a="ello" and b="pc"; * delete the last character of the string a β‡’ a="ell" and b="pc"; * delete the last character of the string b β‡’ a="ell" and b="p". For the given strings a and b, find the minimum number of operations for which you can make the strings a and b equal. Note that empty strings are also equal. Input The first line contains a single integer t (1 ≀ t ≀ 100). Then t test cases follow. The first line of each test case contains the string a (1 ≀ |a| ≀ 20), consisting of lowercase Latin letters. The second line of each test case contains the string b (1 ≀ |b| ≀ 20), consisting of lowercase Latin letters. Output For each test case, output the minimum number of operations that can make the strings a and b equal. Example Input 5 a a abcd bc hello codeforces hello helo dhjakjsnasjhfksafasd adjsnasjhfksvdafdser Output 0 2 13 3 20 Submitted Solution: ``` for test in range(int(input())): a=input() b=input() c=0 lna=len(a) lnb=len(b) if lna>lnb: a,b=b,a for i in range(lna): for j in range(lna,i,-1): if a[i:j] in b and (j-i)>c: c=j-i print((lna+lnb)-2*c) ``` No
11,005
Provide tags and a correct Python 3 solution for this coding contest problem. One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n Γ— m field. The squares have coordinates (x, y) (1 ≀ x ≀ n, 1 ≀ y ≀ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made. Input The first input line contains two integers n and m (1 ≀ n, m ≀ 109) β€” the yard's sizes. The second line contains integers xc and yc β€” the initial square's coordinates (1 ≀ xc ≀ n, 1 ≀ yc ≀ m). The third line contains an integer k (1 ≀ k ≀ 104) β€” the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≀ 109, |dx| + |dy| β‰₯ 1). Output Print the single number β€” the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 4 5 1 1 3 1 1 1 1 0 -2 Output 4 Input 10 10 1 2 1 -1 0 Output 0 Note In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard. Tags: binary search, implementation Correct Solution: ``` def valid(n, m, x, y): return x >= 1 and x <= n and y >= 1 and y <= m def binary_search(n, m, x, y, dx, dy): l, r = 0, n+m+5 while (l+1 < r): mid = l+r >> 1 if (valid(n, m, x + mid*dx, y + mid*dy)): l = mid else: r = mid return l def main(): n, m = map(int, input().split()) x, y = map(int, input().split()) k = int(input()) res = 0 for i in range(k): dx, dy = map(int, input().split()) l = binary_search(n, m, x, y, dx, dy) res += l x += l * dx y += l * dy print(res) main() ```
11,006
Provide tags and a correct Python 3 solution for this coding contest problem. One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n Γ— m field. The squares have coordinates (x, y) (1 ≀ x ≀ n, 1 ≀ y ≀ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made. Input The first input line contains two integers n and m (1 ≀ n, m ≀ 109) β€” the yard's sizes. The second line contains integers xc and yc β€” the initial square's coordinates (1 ≀ xc ≀ n, 1 ≀ yc ≀ m). The third line contains an integer k (1 ≀ k ≀ 104) β€” the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≀ 109, |dx| + |dy| β‰₯ 1). Output Print the single number β€” the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 4 5 1 1 3 1 1 1 1 0 -2 Output 4 Input 10 10 1 2 1 -1 0 Output 0 Note In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard. Tags: binary search, implementation Correct Solution: ``` import re import itertools from collections import Counter class Task: n, m = 0, 0 start, end = 0, 0 vectors = [] answer = 0 def getData(self): self.n, self.m = [int(x) for x in input().split(' ')] self.start, self.end = [int(x) for x in input().split(' ')] numberOfVectors = int(input()) for i in range(0, numberOfVectors): self.vectors += [[int(x) for x in input().split(' ')]] def solve(self): x, y = self.start, self.end for currentVector in self.vectors: #while 1 <= x + currentVector[0] <= self.n and \ # 1 <= y + currentVector[1] <= self.m: # x += currentVector[0] # y += currentVector[1] # self.answer += 1 maxStepsX = self.maxSteps(self.n, x, currentVector[0]) maxStepsY = self.maxSteps(self.m, y, currentVector[1]) x += min(maxStepsX, maxStepsY) * currentVector[0] y += min(maxStepsX, maxStepsY) * currentVector[1] self.answer += min(maxStepsX, maxStepsY) def maxSteps(self, maxX, x, dx): if dx == 0: return 10**9 return (maxX - x) // dx if dx > 0 else (x - 1) // (-dx) def printAnswer(self): print(self.answer) task = Task(); task.getData(); task.solve(); task.printAnswer(); ```
11,007
Provide tags and a correct Python 3 solution for this coding contest problem. One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n Γ— m field. The squares have coordinates (x, y) (1 ≀ x ≀ n, 1 ≀ y ≀ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made. Input The first input line contains two integers n and m (1 ≀ n, m ≀ 109) β€” the yard's sizes. The second line contains integers xc and yc β€” the initial square's coordinates (1 ≀ xc ≀ n, 1 ≀ yc ≀ m). The third line contains an integer k (1 ≀ k ≀ 104) β€” the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≀ 109, |dx| + |dy| β‰₯ 1). Output Print the single number β€” the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 4 5 1 1 3 1 1 1 1 0 -2 Output 4 Input 10 10 1 2 1 -1 0 Output 0 Note In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard. Tags: binary search, implementation Correct Solution: ``` from sys import stdin, stdout def main(): n,m = map(int, stdin.readline().split()) xc, yc = map(int, stdin.readline().split()) k = int(stdin.readline()) total = 0 for _ in range(k): dx, dy = map(int, stdin.readline().split()) maxx = 0 maxy = 0 if dx > 0: maxx = (n-xc)//dx elif dx < 0: maxx = (xc-1)//(-dx) else: maxx = 1e9 if dy > 0: maxy = (m-yc)//dy elif dy < 0: maxy = (yc-1)//(-dy) else: maxy = 1e9 valid = min(maxx, maxy) xc += dx*valid yc += dy*valid total += valid #print("took", valid , "steps, now at " , xc, yc) print(total) return main() ```
11,008
Provide tags and a correct Python 3 solution for this coding contest problem. One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n Γ— m field. The squares have coordinates (x, y) (1 ≀ x ≀ n, 1 ≀ y ≀ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made. Input The first input line contains two integers n and m (1 ≀ n, m ≀ 109) β€” the yard's sizes. The second line contains integers xc and yc β€” the initial square's coordinates (1 ≀ xc ≀ n, 1 ≀ yc ≀ m). The third line contains an integer k (1 ≀ k ≀ 104) β€” the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≀ 109, |dx| + |dy| β‰₯ 1). Output Print the single number β€” the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 4 5 1 1 3 1 1 1 1 0 -2 Output 4 Input 10 10 1 2 1 -1 0 Output 0 Note In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard. Tags: binary search, implementation Correct Solution: ``` R = lambda: map(int, input().split()) n, m = R() x0, y0 = R() k = int(input()) xys = [list(R()) for i in range(k)] res = 0 for dx, dy in xys: l, r = 0, max(n, m) + 7 while l < r: mm = (l + r + 1) // 2 xx, yy = x0 + mm * dx, y0 + mm * dy if 0 < xx <= n and 0 < yy <= m: l = mm else: r = mm - 1 res += l x0, y0 = x0 + l * dx, y0 + l * dy print(res) ```
11,009
Provide tags and a correct Python 3 solution for this coding contest problem. One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n Γ— m field. The squares have coordinates (x, y) (1 ≀ x ≀ n, 1 ≀ y ≀ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made. Input The first input line contains two integers n and m (1 ≀ n, m ≀ 109) β€” the yard's sizes. The second line contains integers xc and yc β€” the initial square's coordinates (1 ≀ xc ≀ n, 1 ≀ yc ≀ m). The third line contains an integer k (1 ≀ k ≀ 104) β€” the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≀ 109, |dx| + |dy| β‰₯ 1). Output Print the single number β€” the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 4 5 1 1 3 1 1 1 1 0 -2 Output 4 Input 10 10 1 2 1 -1 0 Output 0 Note In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard. Tags: binary search, implementation Correct Solution: ``` # ip = open("testdata.txt", "r") # def input(): # return ip.readline().strip() n, m = map(int, input().split()) x0, y0 = map(int, input().split()) k = int(input()) total = 0 for i in range(k): dx, dy = map(int, input().split()) if dx >= 0: s1 = (n - x0)//dx if dx != 0 else float('inf') else: s1 = (x0 - 1)//(-dx) if dy >= 0: s2 = (m - y0)//(dy) if dy != 0 else float('inf') else: s2 = (y0 - 1)//(-dy) s = min(s1, s2) total += s x0 = x0 + s*dx y0 = y0 + s*dy print(total) ```
11,010
Provide tags and a correct Python 3 solution for this coding contest problem. One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n Γ— m field. The squares have coordinates (x, y) (1 ≀ x ≀ n, 1 ≀ y ≀ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made. Input The first input line contains two integers n and m (1 ≀ n, m ≀ 109) β€” the yard's sizes. The second line contains integers xc and yc β€” the initial square's coordinates (1 ≀ xc ≀ n, 1 ≀ yc ≀ m). The third line contains an integer k (1 ≀ k ≀ 104) β€” the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≀ 109, |dx| + |dy| β‰₯ 1). Output Print the single number β€” the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 4 5 1 1 3 1 1 1 1 0 -2 Output 4 Input 10 10 1 2 1 -1 0 Output 0 Note In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard. Tags: binary search, implementation Correct Solution: ``` n,m = list(map(int,input().split())) curx,cury = list(map(int,input().split())) k = int(input()) ans = 0 for i in range(k): x,y = list(map(int,input().split())) sx,sy = 1<<30,1<<30 if x<0: sx = (curx-1)//abs(x) if x>0: sx = (n-curx)//x if y<0: sy = (cury-1)//abs(y) if y>0: sy = (m-cury)//y k = min(sx,sy) curx+= k*x cury+=k*y ans+=k print(ans) ```
11,011
Provide tags and a correct Python 3 solution for this coding contest problem. One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n Γ— m field. The squares have coordinates (x, y) (1 ≀ x ≀ n, 1 ≀ y ≀ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made. Input The first input line contains two integers n and m (1 ≀ n, m ≀ 109) β€” the yard's sizes. The second line contains integers xc and yc β€” the initial square's coordinates (1 ≀ xc ≀ n, 1 ≀ yc ≀ m). The third line contains an integer k (1 ≀ k ≀ 104) β€” the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≀ 109, |dx| + |dy| β‰₯ 1). Output Print the single number β€” the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 4 5 1 1 3 1 1 1 1 0 -2 Output 4 Input 10 10 1 2 1 -1 0 Output 0 Note In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard. Tags: binary search, implementation Correct Solution: ``` # -*- coding: utf-8 -*- """Steps.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/15H6TXUKZ_A8CXwh0JHcGO43Z6QgCkYWd """ def readln(): return tuple(map(int, input().split())) n, m = readln() x, y = readln() k, = readln() ans = 0 for _ in range(k): a, b = readln() va = vb = 1 << 30 if a > 0: va = (n - x) // a if a < 0: va = (1 - x) // a if b > 0: vb = (m - y) // b if b < 0: vb = (1 - y) // b k = min(va, vb) ans += k x += a * k y += b * k print(ans) ```
11,012
Provide tags and a correct Python 3 solution for this coding contest problem. One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n Γ— m field. The squares have coordinates (x, y) (1 ≀ x ≀ n, 1 ≀ y ≀ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made. Input The first input line contains two integers n and m (1 ≀ n, m ≀ 109) β€” the yard's sizes. The second line contains integers xc and yc β€” the initial square's coordinates (1 ≀ xc ≀ n, 1 ≀ yc ≀ m). The third line contains an integer k (1 ≀ k ≀ 104) β€” the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≀ 109, |dx| + |dy| β‰₯ 1). Output Print the single number β€” the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 4 5 1 1 3 1 1 1 1 0 -2 Output 4 Input 10 10 1 2 1 -1 0 Output 0 Note In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard. Tags: binary search, implementation Correct Solution: ``` x,y=map(eval,input().split()) x0,y0=map(eval,input().split()) n=eval(input()) d=[] num=0 for i in range(n): d.append(list(map(eval,input().split()))) for i in d: if i[0]>0 and i[1]>0: a=min((x-x0)//i[0],(y-y0)//i[1]) elif i[0]==0 and i[1]>0: a=(y-y0)//i[1] elif i[1]==0 and i[0]>0: a=(x-x0)//i[0] elif i[0]<0 and i[1]<0: a=min((x0-1)//abs(i[0]),(y0-1)//abs(i[1])) elif i[0]==0 and i[1]<0: a=(y0-1)//abs(i[1]) elif i[1]==0 and i[0]<0: a=(x0-1)//abs(i[0]) elif i[0]<0 and i[1]>0: a=min((x0-1)//abs(i[0]),(y-y0)//i[1]) else: a=min((y0-1)//abs(i[1]),(x-x0)//i[0]) x0+=a*i[0] y0+=a*i[1] num+=abs(a) print(num) ```
11,013
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n Γ— m field. The squares have coordinates (x, y) (1 ≀ x ≀ n, 1 ≀ y ≀ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made. Input The first input line contains two integers n and m (1 ≀ n, m ≀ 109) β€” the yard's sizes. The second line contains integers xc and yc β€” the initial square's coordinates (1 ≀ xc ≀ n, 1 ≀ yc ≀ m). The third line contains an integer k (1 ≀ k ≀ 104) β€” the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≀ 109, |dx| + |dy| β‰₯ 1). Output Print the single number β€” the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 4 5 1 1 3 1 1 1 1 0 -2 Output 4 Input 10 10 1 2 1 -1 0 Output 0 Note In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard. Submitted Solution: ``` def check(x,y,at_x,at_y,N,M): if x == 0: if y > 0: dy = M - at_y count = dy // y at_x = at_x at_y = at_y + count*y return (count,at_x,at_y) else: dy = at_y - 1 count = dy // abs(y) at_x = at_x at_y = at_y - count*abs(y) return (count,at_x,at_y) elif y == 0: if x > 0: dx = N - at_x count = dx // x at_x = at_x + count*x at_y = at_y return (count,at_x,at_y) else: dx = at_x - 1 count = dx // abs(x) at_x = at_x - count*abs(x) at_y = at_y return (count,at_x,at_y) else: if x > 0 and y > 0: dx = N - at_x dy = M - at_y if dx // x < dy // y: count = dx // x at_x = at_x + count*x at_y = at_y + count*y return (count,at_x,at_y) else: count = dy // y at_x = at_x + count*x at_y = at_y + count*y return (count,at_x,at_y) elif x < 0 and y > 0: dx = at_x - 1 dy = M - at_y if dx // abs(x) < dy // y: count = dx // abs(x) at_x = at_x - count*abs(x) at_y = at_y + count*y return (count,at_x,at_y) else: count = dy // y at_x = at_x - count*abs(x) at_y = at_y + count*y return(count,at_x,at_y) elif x > 0 and y < 0: dx = N - at_x dy = at_y - 1 if dx // abs(x) < dy // abs(y): count = dx // abs(x) at_x = at_x + count*abs(x) at_y = at_y - count*abs(y) return (count,at_x,at_y) else: count = dy // abs(y) at_x = at_x + count*abs(x) at_y = at_y - count*abs(y) return (count,at_x,at_y) elif x < 0 and y < 0: dx = at_x - 1 dy = at_y - 1 if dx // abs(x) < dy // abs(y): count = dx // abs(x) at_x = at_x - count*abs(x) at_y = at_y - count*abs(y) return (count,at_x,at_y) else: count = dy // abs(y) at_x = at_x - count*abs(x) at_y = at_y - count*abs(y) return (count,at_x,at_y) def question2(): row,col = map(int,input().split()) at_x,at_y = map(int,input().split()) vect = int(input()) count = 0 for i in range(vect): x,y = map(int,input().split()) # print("hii") count1,at_x,at_y = check(x,y,at_x,at_y,row,col) count += count1 return count # remained_test_case = int(input()) remained_test_case = 1 while remained_test_case > 0: print(question2()) remained_test_case -= 1 ``` Yes
11,014
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n Γ— m field. The squares have coordinates (x, y) (1 ≀ x ≀ n, 1 ≀ y ≀ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made. Input The first input line contains two integers n and m (1 ≀ n, m ≀ 109) β€” the yard's sizes. The second line contains integers xc and yc β€” the initial square's coordinates (1 ≀ xc ≀ n, 1 ≀ yc ≀ m). The third line contains an integer k (1 ≀ k ≀ 104) β€” the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≀ 109, |dx| + |dy| β‰₯ 1). Output Print the single number β€” the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 4 5 1 1 3 1 1 1 1 0 -2 Output 4 Input 10 10 1 2 1 -1 0 Output 0 Note In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard. Submitted Solution: ``` import sys def input(): return sys.stdin.readline().strip() def find_step(x, a, n): if a > 0: return (n-x)//a elif a < 0: return (1-x)//a else: return 10**10 n, m = map(int, input().split()) x, y = map(int, input().split()) k = int(input()) steps = 0 for i in range(k): a, b = map(int, input().split()) k1 = find_step(x, a, n) k2 = find_step(y, b, m) # print(k1, k2) steps += min(k1, k2) x = x + a*min(k1, k2) y = y + b*min(k1, k2) print(steps) ``` Yes
11,015
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n Γ— m field. The squares have coordinates (x, y) (1 ≀ x ≀ n, 1 ≀ y ≀ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made. Input The first input line contains two integers n and m (1 ≀ n, m ≀ 109) β€” the yard's sizes. The second line contains integers xc and yc β€” the initial square's coordinates (1 ≀ xc ≀ n, 1 ≀ yc ≀ m). The third line contains an integer k (1 ≀ k ≀ 104) β€” the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≀ 109, |dx| + |dy| β‰₯ 1). Output Print the single number β€” the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 4 5 1 1 3 1 1 1 1 0 -2 Output 4 Input 10 10 1 2 1 -1 0 Output 0 Note In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard. Submitted Solution: ``` #Mamma don't raises quitter................................................. from collections import deque as de import math from math import sqrt as sq from math import floor as fl from math import ceil as ce from sys import stdin, stdout import re from collections import Counter as cnt from functools import reduce from itertools import groupby as gb #from fractions import Fraction as fr from bisect import bisect_left as bl, bisect_right as br def factors(n): return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))) class My_stack(): def __init__(self): self.data = [] def my_push(self, x): return (self.data.append(x)) def my_pop(self): return (self.data.pop()) def my_peak(self): return (self.data[-1]) def my_contains(self, x): return (self.data.count(x)) def my_show_all(self): return (self.data) def isEmpty(self): return len(self.data)==0 arrStack = My_stack() #decimal to binary def decimalToBinary(n): return bin(n).replace("0b", "") #binary to decimal def binarytodecimal(n): return int(n,2) def isPrime(n) : if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True def get_prime_factors(number): prime_factors = [] while number % 2 == 0: prime_factors.append(2) number = number / 2 for i in range(3, int(math.sqrt(number)) + 1, 2): while number % i == 0: prime_factors.append(int(i)) number = number / i if number > 2: prime_factors.append(int(number)) return prime_factors def get_frequency(list): dic={} for ele in list: if ele in dic: dic[ele] += 1 else: dic[ele] = 1 return dic def Log2(x): return (math.log10(x) / math.log10(2)); # Function to get product of digits def getProduct(n): product = 1 while (n != 0): product = product * (n % 10) n = n // 10 return product #function to find LCM of two numbers def lcm(x,y): lcm = (x*y)//math.gcd(x,y) return lcm def isPowerOfTwo(n): return (math.ceil(Log2(n)) == math.floor(Log2(n))); #to check whether the given sorted sequnce is forming an AP or not.... def checkisap(list): d=list[1]-list[0] for i in range(2,len(list)): temp=list[i]-list[i-1] if temp !=d: return False return True #seive of erathanos def primes_method5(n): out ={} sieve = [True] * (n+1) for p in range(2, n+1): if (sieve[p]): out[p]=1 for i in range(p, n+1, p): sieve[i] = False return out #ceil function gives wrong answer after 10^17 so i have to create my own :) # because i don't want to doubt on my solution of 900-1000 problem set. def ceildiv(x,y): return (x+y-1)//y def di():return map(int, input().split()) def ii():return int(input()) def li():return list(map(int, input().split())) def si():return list(map(str, input())) def indict(): dic = {} for index, value in enumerate(input().split()): dic[int(value)] = int(index)+1 return dic def frqdict(): # by default it is for integer input. :) dic={} for index, value in enumerate(input()): if value not in dic: dic[value] =1 else: dic[value] +=1 return dic #inp = open("input.txt","r") #out = open("output.txt","w") #Here we go...................... #practice like your never won #perform like you never lost n, m = map(int, input().split()) x, y = map(int, input().split()) k = int(input()) count = 0 for i in range(k): dx, dy = map(int, input().split()) ans = n + m #print(ans) if dx > 0: ans = min(ans, (n - x) // dx) if dx < 0: ans = min(ans, (x - 1) // -dx) if dy > 0: ans = min(ans, (m - y) // dy) if dy < 0: ans = min(ans, (y - 1) // -dy) count += ans #print(count) x += dx * ans y += dy * ans #print(x,y) print(count) ``` Yes
11,016
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n Γ— m field. The squares have coordinates (x, y) (1 ≀ x ≀ n, 1 ≀ y ≀ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made. Input The first input line contains two integers n and m (1 ≀ n, m ≀ 109) β€” the yard's sizes. The second line contains integers xc and yc β€” the initial square's coordinates (1 ≀ xc ≀ n, 1 ≀ yc ≀ m). The third line contains an integer k (1 ≀ k ≀ 104) β€” the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≀ 109, |dx| + |dy| β‰₯ 1). Output Print the single number β€” the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 4 5 1 1 3 1 1 1 1 0 -2 Output 4 Input 10 10 1 2 1 -1 0 Output 0 Note In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard. Submitted Solution: ``` """ β–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β•šβ•β•β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β•β•β• β–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β•šβ•β•β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β•šβ•β• β•šβ•β•β•β•β•β• β•šβ•β• β•šβ•β•β•β•β•β•β• β•šβ•β•β•β•β•β• β•šβ•β• β•šβ•β•β•β•β• """ __author__ = "Dilshod" def check(x, y, dx, dy, moves): global n, m if x + dx * moves > n or y + dy * moves > m or x + dx * moves <= 0 or y + dy * moves <= 0: return True return False def moves(a, b): global x, y left = 0 right = 1000000000 while left <= right: moves = (left + right) // 2 if left == right - 1: break if check(x, y, a, b, moves): right = moves else: left = moves return left n, m = map(int, input().split()) x, y = map(int, input().split()) k = int(input()) cnt = 0 for i in range(k): a, b = map(int, input().split()) c = moves(a, b) cnt += c x += a * c y += b * c print(cnt) ``` Yes
11,017
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n Γ— m field. The squares have coordinates (x, y) (1 ≀ x ≀ n, 1 ≀ y ≀ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made. Input The first input line contains two integers n and m (1 ≀ n, m ≀ 109) β€” the yard's sizes. The second line contains integers xc and yc β€” the initial square's coordinates (1 ≀ xc ≀ n, 1 ≀ yc ≀ m). The third line contains an integer k (1 ≀ k ≀ 104) β€” the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≀ 109, |dx| + |dy| β‰₯ 1). Output Print the single number β€” the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 4 5 1 1 3 1 1 1 1 0 -2 Output 4 Input 10 10 1 2 1 -1 0 Output 0 Note In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard. Submitted Solution: ``` def isValid(y ,i , j , r , c): step = 0 for k in D: while True: if i+k[0] <= r and i+k[0] >0 and j+k[1] <= c and j+k[1] > 0 : i , j = i+k[0] , j+k[1] step +=1 else: break D.remove(D[0]) return step D = [] n , m = map(int,input().split()) x , y = map(int , input().split()) d = int(input()) for _ in range(d): k , z = map(int,input().split()) D.append([k , z]) print(isValid(D , x , y , n , m)) ``` No
11,018
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n Γ— m field. The squares have coordinates (x, y) (1 ≀ x ≀ n, 1 ≀ y ≀ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made. Input The first input line contains two integers n and m (1 ≀ n, m ≀ 109) β€” the yard's sizes. The second line contains integers xc and yc β€” the initial square's coordinates (1 ≀ xc ≀ n, 1 ≀ yc ≀ m). The third line contains an integer k (1 ≀ k ≀ 104) β€” the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≀ 109, |dx| + |dy| β‰₯ 1). Output Print the single number β€” the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 4 5 1 1 3 1 1 1 1 0 -2 Output 4 Input 10 10 1 2 1 -1 0 Output 0 Note In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard. Submitted Solution: ``` a,b=map(int,input().split()) x,y=map(int,input().split()) ans=0 for _ in " "*int(input()): u,v=map(int,input().split()) if u==0 : t=0 if v<0: t=(y-1)//(-v) else:t=(y-1)//v y+=v*t ans+=t elif v==0: t=0 if u<0:t=(x-1)//(-u) else:t=(a-x)//u x+=t*u ans+=t else: t,t1=0,0 if u<0: t=(x-1)//(-u) else: t=(a-x)//u if v<0: t1=(y-1)//(-v) else:t1=(b-y)//v t=min(t,t1) ans+=t y+=t*v;x+=t*u print(ans) ``` No
11,019
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n Γ— m field. The squares have coordinates (x, y) (1 ≀ x ≀ n, 1 ≀ y ≀ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made. Input The first input line contains two integers n and m (1 ≀ n, m ≀ 109) β€” the yard's sizes. The second line contains integers xc and yc β€” the initial square's coordinates (1 ≀ xc ≀ n, 1 ≀ yc ≀ m). The third line contains an integer k (1 ≀ k ≀ 104) β€” the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≀ 109, |dx| + |dy| β‰₯ 1). Output Print the single number β€” the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 4 5 1 1 3 1 1 1 1 0 -2 Output 4 Input 10 10 1 2 1 -1 0 Output 0 Note In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard. Submitted Solution: ``` # link: https://codeforces.com/contest/152/problem/B if __name__ == "__main__": n,m = map(int, input().split()) new_x,new_y = map(int, input().split()) k = int(input()) steps = 0 new_x -= 1 new_y -= 1 while k: a,b = map(int, input().split()) end = 1100000000 while end>0: if (new_x + a*end >= 0 and new_x + a*end < n) and (new_y + b*end >= 0 and new_y + b*end < m): new_x = new_x + a*end new_y = new_y + b*end steps += end end = int(end / 2) k -= 1 print(steps) ``` No
11,020
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangular n Γ— m field. The squares have coordinates (x, y) (1 ≀ x ≀ n, 1 ≀ y ≀ m), where x is the index of the row and y is the index of the column. Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps). A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step. Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made. Input The first input line contains two integers n and m (1 ≀ n, m ≀ 109) β€” the yard's sizes. The second line contains integers xc and yc β€” the initial square's coordinates (1 ≀ xc ≀ n, 1 ≀ yc ≀ m). The third line contains an integer k (1 ≀ k ≀ 104) β€” the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≀ 109, |dx| + |dy| β‰₯ 1). Output Print the single number β€” the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 4 5 1 1 3 1 1 1 1 0 -2 Output 4 Input 10 10 1 2 1 -1 0 Output 0 Note In the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0, - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps. In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard. Submitted Solution: ``` def get_steps(n, m, x, y, dx, dy): x_all = max(n - (n - x) - 1, n - x) y_all = max(m - (m - y) - 1, m - y) if dx == 0: x_move = 10**18 elif dx != 0: x_move = (x_all//dx) if dy == 0: y_move = 10**18 elif dy != 0: y_move = (y_all//dy) return abs(min(x_move, y_move)) n, m = map(int, input().split()) x, y = map(int, input().split()) k = int(input()) steps = 0 for i in range(k): dx, dy = map(int, input().split()) moves = get_steps(n, m, x, y, dx, dy) if moves == 0: pass else: tmp_x = dx * moves + x tmp_y = dy * moves + y if tmp_x in range(1, n+1) and tmp_y in range(1, m+1): x += dx * moves y += dy * moves steps += moves else: pass if steps == 0: print(0) else: print(steps + 1) ``` No
11,021
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a connected weighted undirected graph without any loops and multiple edges. Let us remind you that a graph's spanning tree is defined as an acyclic connected subgraph of the given graph that includes all of the graph's vertexes. The weight of a tree is defined as the sum of weights of the edges that the given tree contains. The minimum spanning tree (MST) of a graph is defined as the graph's spanning tree having the minimum possible weight. For any connected graph obviously exists the minimum spanning tree, but in the general case, a graph's minimum spanning tree is not unique. Your task is to determine the following for each edge of the given graph: whether it is either included in any MST, or included at least in one MST, or not included in any MST. Input The first line contains two integers n and m (2 ≀ n ≀ 105, <image>) β€” the number of the graph's vertexes and edges, correspondingly. Then follow m lines, each of them contains three integers β€” the description of the graph's edges as "ai bi wi" (1 ≀ ai, bi ≀ n, 1 ≀ wi ≀ 106, ai β‰  bi), where ai and bi are the numbers of vertexes connected by the i-th edge, wi is the edge's weight. It is guaranteed that the graph is connected and doesn't contain loops or multiple edges. Output Print m lines β€” the answers for all edges. If the i-th edge is included in any MST, print "any"; if the i-th edge is included at least in one MST, print "at least one"; if the i-th edge isn't included in any MST, print "none". Print the answers for the edges in the order in which the edges are specified in the input. Examples Input 4 5 1 2 101 1 3 100 2 3 2 2 4 2 3 4 1 Output none any at least one at least one any Input 3 3 1 2 1 2 3 1 1 3 2 Output any any none Input 3 3 1 2 1 2 3 1 1 3 1 Output at least one at least one at least one Note In the second sample the MST is unique for the given graph: it contains two first edges. In the third sample any two edges form the MST for the given graph. That means that each edge is included at least in one MST. Tags: dfs and similar, dsu, graphs, sortings Correct Solution: ``` from sys import stdin from math import inf from collections import defaultdict class disjoinSet(object): def __init__(self,n): self.father = [x for x in range(0,n+1)] self.rank = [0 for x in range(0,n+1)] def setOf(self, x): if(self.father[x] != x): self.father[x] = self.setOf(self.father[x]) return self.father[x] def Merge(self,x,y): xR = self.setOf(x) yR = self.setOf(y) if(xR == yR): return if self.rank[xR] < self.rank[yR]: self.father[xR] = yR elif self.rank[xR] > self.rank[yR]: self.father[yR] = xR else: self.father[yR] = xR self.rank[xR] +=1 ########## def mergesort(x): if len(x) < 2: return x middle = int(len(x)/2) left = mergesort(x[:middle]) right = mergesort(x[middle:]) return merge(left,right) def merge(left,right): result = [] l,r=0,0 while l < len(left) and r < len(right): if left[l][2] <= right[r][2]: result.append(left[l]) l+=1 else: result.append(right[r]) r+=1 result += left[l:] result += right[r:] return result ########## def DFS(graph,bridges): time = 0 for key in graph: low[key] = inf d[key] = -1 pi[key] = key visited[key] = False for i in graph: if not visited[i]: DFS_Visit(graph,i,bridges) def DFS_Visit(graph,u,bridges): visited[u] = True global time time +=1 d[u] = time low[u] = d[u] for v in graph[u]: if not visited[v]: pi[v] = u DFS_Visit(graph,v,bridges) low[u] = min(low[u],low[v]) elif pi[u] != v: low[u] = min(low[u],d[v]) if pi[u] != u and low[u] == d[u]: x = min(pi[u],u) y = max(pi[u],u) bridges.append([x,y]) time +=1 ########## n, m = map(int, stdin.readline().split()) if m != n-1: visited = {} d = {} low = {} pi = {} time = 0 edges = [] for i in range(0,m): x,y,z = map(int, stdin.readline().split()) edges.append([]) edges[i] = [x,y,z] ans = {} for i in edges: x = min(i[0],i[1]) y = max(i[0],i[1]) ans[x,y] = "at least one" dsu = disjoinSet(n) sortEdges = mergesort(edges) criticalEdges = [] i = 0 cantEdges = m while i < cantEdges: j = i; a = 0 b = 0 criticalEdges = [] while j < len(sortEdges) and sortEdges[j][2] == sortEdges[i][2]: x = dsu.setOf(sortEdges[j][0]) y = dsu.setOf(sortEdges[j][1]) a = min(sortEdges[j][0],sortEdges[j][1]) b = max(sortEdges[j][0],sortEdges[j][1]) if x == y: ans[a,b] = "none" criticalEdges.append(sortEdges[j]) j+=1 if len(criticalEdges) == 1: if ans[a,b] != "none": ans[a,b] = "any" dsu.Merge(a,b) else: graph = defaultdict(set) crossCut = defaultdict(list) for m in criticalEdges: x = min(dsu.setOf(m[0]),dsu.setOf(m[1])) y = max(dsu.setOf(m[0]),dsu.setOf(m[1])) if x != y: graph[x].add(y) graph[y].add(x) crossCut[x,y].append([min(m[0],m[1]),max(m[0],m[1])]) bridges = [] DFS(graph,bridges) for k in bridges: if len(crossCut[k[0],k[1]]) == 1: x,y = crossCut[k[0],k[1]][0] ans[x,y] = "any" for m in criticalEdges: dsu.Merge(m[0],m[1]) i = j for s in edges: x = min(s[0],s[1]) y = max(s[0],s[1]) print(ans[x,y]) else: for _ in range(0,m): print("any") ```
11,022
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a connected weighted undirected graph without any loops and multiple edges. Let us remind you that a graph's spanning tree is defined as an acyclic connected subgraph of the given graph that includes all of the graph's vertexes. The weight of a tree is defined as the sum of weights of the edges that the given tree contains. The minimum spanning tree (MST) of a graph is defined as the graph's spanning tree having the minimum possible weight. For any connected graph obviously exists the minimum spanning tree, but in the general case, a graph's minimum spanning tree is not unique. Your task is to determine the following for each edge of the given graph: whether it is either included in any MST, or included at least in one MST, or not included in any MST. Input The first line contains two integers n and m (2 ≀ n ≀ 105, <image>) β€” the number of the graph's vertexes and edges, correspondingly. Then follow m lines, each of them contains three integers β€” the description of the graph's edges as "ai bi wi" (1 ≀ ai, bi ≀ n, 1 ≀ wi ≀ 106, ai β‰  bi), where ai and bi are the numbers of vertexes connected by the i-th edge, wi is the edge's weight. It is guaranteed that the graph is connected and doesn't contain loops or multiple edges. Output Print m lines β€” the answers for all edges. If the i-th edge is included in any MST, print "any"; if the i-th edge is included at least in one MST, print "at least one"; if the i-th edge isn't included in any MST, print "none". Print the answers for the edges in the order in which the edges are specified in the input. Examples Input 4 5 1 2 101 1 3 100 2 3 2 2 4 2 3 4 1 Output none any at least one at least one any Input 3 3 1 2 1 2 3 1 1 3 2 Output any any none Input 3 3 1 2 1 2 3 1 1 3 1 Output at least one at least one at least one Note In the second sample the MST is unique for the given graph: it contains two first edges. In the third sample any two edges form the MST for the given graph. That means that each edge is included at least in one MST. Tags: dfs and similar, dsu, graphs, sortings Correct Solution: ``` from sys import stdin from math import inf from collections import defaultdict class disjoinSet(object): def __init__(self,n): self.father = [x for x in range(0,n+1)] self.rank = [0 for x in range(0,n+1)] def setOf(self, x): if(self.father[x] != x): self.father[x] = self.setOf(self.father[x]) return self.father[x] def Merge(self,x,y): xR = self.setOf(x) yR = self.setOf(y) if(xR == yR): return if self.rank[xR] < self.rank[yR]: self.father[xR] = yR elif self.rank[xR] > self.rank[yR]: self.father[yR] = xR else: self.father[yR] = xR self.rank[xR] +=1 ########## def mergesort(x): if len(x) < 2: return x middle = int(len(x)/2) left = mergesort(x[:middle]) right = mergesort(x[middle:]) return merge(left,right) def merge(left,right): result = [] l,r=0,0 while l < len(left) and r < len(right): if left[l][2] <= right[r][2]: result.append(left[l]) l+=1 else: result.append(right[r]) r+=1 result += left[l:] result += right[r:] return result ########## def DFS(graph,bridges): time = 0 for key in graph: low[key] = inf d[key] = -1 pi[key] = key visited[key] = False for i in graph: if not visited[i]: DFS_Visit(graph,i,bridges) def DFS_Visit(graph,u,bridges): visited[u] = True global time time +=1 d[u] = time low[u] = d[u] for v in graph[u]: if not visited[v]: pi[v] = u DFS_Visit(graph,v,bridges) low[u] = min(low[u],low[v]) elif pi[u] != v: low[u] = min(low[u],d[v]) if pi[u] != u and low[u] >= d[u]: x = min(pi[u],u) y = max(pi[u],u) bridges.append([x,y]) time +=1 ########## n, m = map(int, stdin.readline().split()) if m > n-1: visited = {} d = {} low = {} pi = {} time = 0 edges = [] for i in range(0,m): x,y,z = map(int, stdin.readline().split()) edges.append([]) edges[i] = [x,y,z] ans = {} for i in edges: x = min(i[0],i[1]) y = max(i[0],i[1]) ans[x,y] = "at least one" dsu = disjoinSet(n) sortEdges = mergesort(edges) criticalEdges = [] i = 0 cantEdges = m while i < cantEdges: j = i; a = 0 b = 0 criticalEdges = [] while j < len(sortEdges) and sortEdges[j][2] == sortEdges[i][2]: x = dsu.setOf(sortEdges[j][0]) y = dsu.setOf(sortEdges[j][1]) a = min(sortEdges[j][0],sortEdges[j][1]) b = max(sortEdges[j][0],sortEdges[j][1]) if x == y: ans[a,b] = "none" criticalEdges.append(sortEdges[j]) j+=1 if len(criticalEdges) == 1: if ans[a,b] != "none": ans[a,b] = "any" dsu.Merge(a,b) else: graph = defaultdict(set) crossCut = defaultdict(list) for m in criticalEdges: x = min(dsu.setOf(m[0]),dsu.setOf(m[1])) y = max(dsu.setOf(m[0]),dsu.setOf(m[1])) if x != y: graph[x].add(y) graph[y].add(x) crossCut[x,y].append([min(m[0],m[1]),max(m[0],m[1])]) bridges = [] DFS(graph,bridges) for k in bridges: if len(crossCut[k[0],k[1]]) == 1: x,y = crossCut[k[0],k[1]][0] ans[x,y] = "any" for m in criticalEdges: if dsu.setOf(m[0]) != dsu.setOf(m[1]): dsu.Merge(m[0],m[1]) i = j for i in edges: x = min(i[0],i[1]) y = max(i[0],i[1]) print(ans[x,y]) else: for _ in range(0,m): print("any") ```
11,023
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a connected weighted undirected graph without any loops and multiple edges. Let us remind you that a graph's spanning tree is defined as an acyclic connected subgraph of the given graph that includes all of the graph's vertexes. The weight of a tree is defined as the sum of weights of the edges that the given tree contains. The minimum spanning tree (MST) of a graph is defined as the graph's spanning tree having the minimum possible weight. For any connected graph obviously exists the minimum spanning tree, but in the general case, a graph's minimum spanning tree is not unique. Your task is to determine the following for each edge of the given graph: whether it is either included in any MST, or included at least in one MST, or not included in any MST. Input The first line contains two integers n and m (2 ≀ n ≀ 105, <image>) β€” the number of the graph's vertexes and edges, correspondingly. Then follow m lines, each of them contains three integers β€” the description of the graph's edges as "ai bi wi" (1 ≀ ai, bi ≀ n, 1 ≀ wi ≀ 106, ai β‰  bi), where ai and bi are the numbers of vertexes connected by the i-th edge, wi is the edge's weight. It is guaranteed that the graph is connected and doesn't contain loops or multiple edges. Output Print m lines β€” the answers for all edges. If the i-th edge is included in any MST, print "any"; if the i-th edge is included at least in one MST, print "at least one"; if the i-th edge isn't included in any MST, print "none". Print the answers for the edges in the order in which the edges are specified in the input. Examples Input 4 5 1 2 101 1 3 100 2 3 2 2 4 2 3 4 1 Output none any at least one at least one any Input 3 3 1 2 1 2 3 1 1 3 2 Output any any none Input 3 3 1 2 1 2 3 1 1 3 1 Output at least one at least one at least one Note In the second sample the MST is unique for the given graph: it contains two first edges. In the third sample any two edges form the MST for the given graph. That means that each edge is included at least in one MST. Tags: dfs and similar, dsu, graphs, sortings Correct Solution: ``` from sys import stdin from math import inf from collections import defaultdict class disjoinSet(object): def __init__(self,n): self.father = [x for x in range(0,n+1)] self.rank = [0 for x in range(0,n+1)] def setOf(self, x): if(self.father[x] != x): self.father[x] = self.setOf(self.father[x]) return self.father[x] def Merge(self,x,y): xR = self.setOf(x) yR = self.setOf(y) if(xR == yR): return if self.rank[xR] < self.rank[yR]: self.father[xR] = yR elif self.rank[xR] > self.rank[yR]: self.father[yR] = xR else: self.father[yR] = xR self.rank[xR] +=1 ########## def mergesort(x): if len(x) < 2: return x middle = int(len(x)/2) left = mergesort(x[:middle]) right = mergesort(x[middle:]) return merge(left,right) def merge(left,right): result = [] l,r=0,0 while l < len(left) and r < len(right): if left[l][2] <= right[r][2]: result.append(left[l]) l+=1 else: result.append(right[r]) r+=1 result += left[l:] result += right[r:] return result ########## def DFS(graph,bridges): time = 0 for key in graph: low[key] = inf d[key] = -1 pi[key] = key visited[key] = False for i in graph: if not visited[i]: DFS_Visit(graph,i,bridges) def DFS_Visit(graph,u,bridges): visited[u] = True global time time +=1 d[u] = time low[u] = d[u] for v in graph[u]: if not visited[v]: pi[v] = u DFS_Visit(graph,v,bridges) low[u] = min(low[u],low[v]) elif pi[u] != v: low[u] = min(low[u],d[v]) if pi[u] != u and low[u] == d[u]: x = min(pi[u],u) y = max(pi[u],u) bridges.append([x,y]) time +=1 ########## n, m = map(int, stdin.readline().split()) if m > n-1: visited = {} d = {} low = {} pi = {} time = 0 edges = [] for i in range(0,m): x,y,z = map(int, stdin.readline().split()) edges.append([]) edges[i] = [x,y,z] ans = {} for i in edges: x = min(i[0],i[1]) y = max(i[0],i[1]) ans[x,y] = "at least one" dsu = disjoinSet(n) sortEdges = mergesort(edges) criticalEdges = [] i = 0 cantEdges = m while i < cantEdges: j = i; a = 0 b = 0 criticalEdges = [] while j < len(sortEdges) and sortEdges[j][2] == sortEdges[i][2]: x = dsu.setOf(sortEdges[j][0]) y = dsu.setOf(sortEdges[j][1]) a = min(sortEdges[j][0],sortEdges[j][1]) b = max(sortEdges[j][0],sortEdges[j][1]) if x == y: ans[a,b] = "none" criticalEdges.append(sortEdges[j]) j+=1 if len(criticalEdges) == 1: if ans[a,b] != "none": ans[a,b] = "any" dsu.Merge(a,b) else: graph = defaultdict(set) crossCut = defaultdict(list) for m in criticalEdges: x = min(dsu.setOf(m[0]),dsu.setOf(m[1])) y = max(dsu.setOf(m[0]),dsu.setOf(m[1])) if x != y: graph[x].add(y) graph[y].add(x) crossCut[x,y].append([min(m[0],m[1]),max(m[0],m[1])]) bridges = [] DFS(graph,bridges) for k in bridges: if len(crossCut[k[0],k[1]]) == 1: x,y = crossCut[k[0],k[1]][0] ans[x,y] = "any" for m in criticalEdges: dsu.Merge(m[0],m[1]) i = j for s in edges: x = min(s[0],s[1]) y = max(s[0],s[1]) print(ans[x,y]) else: for _ in range(0,m): print("any") ```
11,024
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a connected weighted undirected graph without any loops and multiple edges. Let us remind you that a graph's spanning tree is defined as an acyclic connected subgraph of the given graph that includes all of the graph's vertexes. The weight of a tree is defined as the sum of weights of the edges that the given tree contains. The minimum spanning tree (MST) of a graph is defined as the graph's spanning tree having the minimum possible weight. For any connected graph obviously exists the minimum spanning tree, but in the general case, a graph's minimum spanning tree is not unique. Your task is to determine the following for each edge of the given graph: whether it is either included in any MST, or included at least in one MST, or not included in any MST. Input The first line contains two integers n and m (2 ≀ n ≀ 105, <image>) β€” the number of the graph's vertexes and edges, correspondingly. Then follow m lines, each of them contains three integers β€” the description of the graph's edges as "ai bi wi" (1 ≀ ai, bi ≀ n, 1 ≀ wi ≀ 106, ai β‰  bi), where ai and bi are the numbers of vertexes connected by the i-th edge, wi is the edge's weight. It is guaranteed that the graph is connected and doesn't contain loops or multiple edges. Output Print m lines β€” the answers for all edges. If the i-th edge is included in any MST, print "any"; if the i-th edge is included at least in one MST, print "at least one"; if the i-th edge isn't included in any MST, print "none". Print the answers for the edges in the order in which the edges are specified in the input. Examples Input 4 5 1 2 101 1 3 100 2 3 2 2 4 2 3 4 1 Output none any at least one at least one any Input 3 3 1 2 1 2 3 1 1 3 2 Output any any none Input 3 3 1 2 1 2 3 1 1 3 1 Output at least one at least one at least one Note In the second sample the MST is unique for the given graph: it contains two first edges. In the third sample any two edges form the MST for the given graph. That means that each edge is included at least in one MST. Tags: dfs and similar, dsu, graphs, sortings Correct Solution: ``` import sys from math import inf from collections import defaultdict class disjoinSet(object): def __init__(self,n): self.father = [x for x in range(0,n+1)] self.rank = [0 for x in range(0,n+1)] def setOf(self, x): if(self.father[x] != x): self.father[x] = self.setOf(self.father[x]) return self.father[x] def Merge(self,x,y): xR = self.setOf(x) yR = self.setOf(y) if(xR == yR): return if self.rank[xR] < self.rank[yR]: self.father[xR] = yR elif self.rank[xR] > self.rank[yR]: self.father[yR] = xR else: self.father[yR] = xR self.rank[xR] +=1 def merge(left,right): result = [] l,r=0,0 while l < len(left) and r < len(right): if left[l][2] <= right[r][2]: result.append(left[l]) l+=1 else: result.append(right[r]) r+=1 result += left[l:] result += right[r:] return result def mergesort(x): if len(x) < 2: return x middle = int(len(x)/2) left = mergesort(x[:middle]) right = mergesort(x[middle:]) return merge(left,right) def DFS(graph,bridges): time = 0 for key in graph: low[key] = inf d[key] = -1 pi[key] = key visited[key] = False for i in graph: if not visited[i]: DFS_Visit(graph,i,bridges) def DFS_Visit(graph,u,bridges): visited[u] = True global time time +=1 d[u] = time low[u] = d[u] for v in graph[u]: if not visited[v]: pi[v] = u DFS_Visit(graph,v,bridges) low[u] = min(low[u],low[v]) elif pi[u] != v: low[u] = min(low[u],d[v]) if pi[u] != u and low[u] >= d[u]: x = min(pi[u],u) y = max(pi[u],u) bridges.append([x,y]) time +=1 time = 0 n, m = map(int, sys.stdin.readline().split()) if m <= n-1: for _ in range(0,m): print("any") exit() visited = {} d = {} low = {} pi = {} edges = [] for i in range(0,m): x,y,z = map(int, sys.stdin.readline().split()) edges.append([]) edges[i] = [x,y,z] dsu = disjoinSet(n) ans = {} for i in edges: x = min(i[0],i[1]) y = max(i[0],i[1]) ans[x,y] = "at least one" sortEdges = mergesort(edges) criticalEdges = [] i = 0 cantEdges = m while i < cantEdges: j = i; a = 0 b = 0 criticalEdges = [] while j < len(sortEdges) and sortEdges[j][2] == sortEdges[i][2]: x = dsu.setOf(sortEdges[j][0]) y = dsu.setOf(sortEdges[j][1]) a = min(sortEdges[j][0],sortEdges[j][1]) b = max(sortEdges[j][0],sortEdges[j][1]) if x == y: ans[a,b] = "none" criticalEdges.append(sortEdges[j]) j+=1 if len(criticalEdges) == 1: if ans[a,b] != "none": ans[a,b] = "any" dsu.Merge(a,b) else: graph = defaultdict(set) crossCut = defaultdict(list) for m in criticalEdges: x = min(dsu.setOf(m[0]),dsu.setOf(m[1])) y = max(dsu.setOf(m[0]),dsu.setOf(m[1])) if x != y: graph[x].add(y) graph[y].add(x) crossCut[x,y].append([min(m[0],m[1]),max(m[0],m[1])]) bridges = [] DFS(graph,bridges) for k in bridges: if len(crossCut[k[0],k[1]]) == 1: ans[crossCut[k[0],k[1]][0][0],crossCut[k[0],k[1]][0][1]] = "any" for m in criticalEdges: if dsu.setOf(m[0]) != dsu.setOf(m[1]): dsu.Merge(m[0],m[1]) i = j for i in edges: x = min(i[0],i[1]) y = max(i[0],i[1]) print(ans[x,y]) ```
11,025
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a connected weighted undirected graph without any loops and multiple edges. Let us remind you that a graph's spanning tree is defined as an acyclic connected subgraph of the given graph that includes all of the graph's vertexes. The weight of a tree is defined as the sum of weights of the edges that the given tree contains. The minimum spanning tree (MST) of a graph is defined as the graph's spanning tree having the minimum possible weight. For any connected graph obviously exists the minimum spanning tree, but in the general case, a graph's minimum spanning tree is not unique. Your task is to determine the following for each edge of the given graph: whether it is either included in any MST, or included at least in one MST, or not included in any MST. Input The first line contains two integers n and m (2 ≀ n ≀ 105, <image>) β€” the number of the graph's vertexes and edges, correspondingly. Then follow m lines, each of them contains three integers β€” the description of the graph's edges as "ai bi wi" (1 ≀ ai, bi ≀ n, 1 ≀ wi ≀ 106, ai β‰  bi), where ai and bi are the numbers of vertexes connected by the i-th edge, wi is the edge's weight. It is guaranteed that the graph is connected and doesn't contain loops or multiple edges. Output Print m lines β€” the answers for all edges. If the i-th edge is included in any MST, print "any"; if the i-th edge is included at least in one MST, print "at least one"; if the i-th edge isn't included in any MST, print "none". Print the answers for the edges in the order in which the edges are specified in the input. Examples Input 4 5 1 2 101 1 3 100 2 3 2 2 4 2 3 4 1 Output none any at least one at least one any Input 3 3 1 2 1 2 3 1 1 3 2 Output any any none Input 3 3 1 2 1 2 3 1 1 3 1 Output at least one at least one at least one Note In the second sample the MST is unique for the given graph: it contains two first edges. In the third sample any two edges form the MST for the given graph. That means that each edge is included at least in one MST. Tags: dfs and similar, dsu, graphs, sortings Correct Solution: ``` from math import inf import operator from collections import defaultdict import sys time = 0 edges = [] ans = {} orig_edges = [] l = {} d = {} f = {} pi = {} visited = {} def process_edges(l, ds): if len(l) == 1: u,v = l[0] b = ds.SetOf(u) == ds.SetOf(v) ans[u,v] = "none" if b else "any" if not b: ds.Merge(u, v) else: dic = defaultdict(list) g = defaultdict(set) for e in l: u,v = e x = ds.SetOf(u) y = ds.SetOf(v) if x == y: ans[e] = "none" else: x,y = tuple(sorted([x,y])) dic[x,y].append(e) g[x].add(y) g[y].add(x) a = DFS(g) for e in a: if len(dic[e]) == 1: ans[dic[e][0]] = "any" for e in l: if ds.SetOf(e[1]) != ds.SetOf(e[0]): ds.Merge(e[0],e[1]) def sol(n): ds = DisjointSet(n) global edges prev_w = edges[0][1] same_weight = [] for e, w in edges + [(1,None)]: if w == prev_w: same_weight.append(e) else: process_edges(same_weight, ds) same_weight = [e] prev_w = w def DFS(graph): time = 0 global l global d global f global pi global visited visited = {key : False for key in graph} l = {key : inf for key in graph} d = {key : -1 for key in graph} f = {key : -1 for key in graph} pi = {key : key for key in graph} a = [] for i in graph.keys(): if not visited[i]: DFS_Visit(graph, i, a) return a def DFS_Visit(graph, v, a): visited[v] = True global time time+=1 d[v] = l[v] = time for i in graph[v]: if not visited[i]: pi[i] = v DFS_Visit(graph, i, a) l[v] = min(l[v], l[i]) elif pi[v] != i: l[v] = min(l[v], d[i]) if pi[v] != v and l[v] >= d[v]: a.append(tuple(sorted([v,pi[v]]))) time+=1 f[v] = time # def DFS_Visit(graph, v, a): # visited[v] = True # global time # time+=1 # d[v] = l[v] = time # stack = [v] # while stack: # u = stack.pop() # for i in graph[u]: # if not visited[i]: # pi[i] = v # stack.append(i) # # DFS_Visit(graph, i, a) # l[u] = min(l[u], l[i]) # elif pi[u] != i: # l[u] = min(l[u], d[i]) # if pi[u] != v and l[v] >= d[v]: # a.append(tuple(sorted([v,pi[v]]))) # time+=1 # f[v] = time def read(): global edges n,m = map(int, sys.stdin.readline().split()) if m == n-1: for _ in range(m): print("any") exit() for i in range(m): x,y,w = map(int, sys.stdin.readline().split()) x,y = x-1,y-1 e = tuple(sorted([x,y])) ans[e] = "at least one" orig_edges.append((e,w)) edges = sorted(orig_edges, key=lambda x:x[1]) return n def main(): n = read() sol(n) for i in orig_edges: print(ans[i[0]]) class DisjointSet: def __init__(self, n): self.count = [1 for i in range(n)] self.father = [i for i in range(n)] def SetOf(self, x): if x == self.father[x]: return x return self.SetOf(self.father[x]) def Merge(self, x, y): a = self.SetOf(x) b = self.SetOf(y) if self.count[a] > self.count[b]: temp = a a = b b = temp self.count[b] += self.count[a] self.father[a] = b main() ```
11,026
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a connected weighted undirected graph without any loops and multiple edges. Let us remind you that a graph's spanning tree is defined as an acyclic connected subgraph of the given graph that includes all of the graph's vertexes. The weight of a tree is defined as the sum of weights of the edges that the given tree contains. The minimum spanning tree (MST) of a graph is defined as the graph's spanning tree having the minimum possible weight. For any connected graph obviously exists the minimum spanning tree, but in the general case, a graph's minimum spanning tree is not unique. Your task is to determine the following for each edge of the given graph: whether it is either included in any MST, or included at least in one MST, or not included in any MST. Input The first line contains two integers n and m (2 ≀ n ≀ 105, <image>) β€” the number of the graph's vertexes and edges, correspondingly. Then follow m lines, each of them contains three integers β€” the description of the graph's edges as "ai bi wi" (1 ≀ ai, bi ≀ n, 1 ≀ wi ≀ 106, ai β‰  bi), where ai and bi are the numbers of vertexes connected by the i-th edge, wi is the edge's weight. It is guaranteed that the graph is connected and doesn't contain loops or multiple edges. Output Print m lines β€” the answers for all edges. If the i-th edge is included in any MST, print "any"; if the i-th edge is included at least in one MST, print "at least one"; if the i-th edge isn't included in any MST, print "none". Print the answers for the edges in the order in which the edges are specified in the input. Examples Input 4 5 1 2 101 1 3 100 2 3 2 2 4 2 3 4 1 Output none any at least one at least one any Input 3 3 1 2 1 2 3 1 1 3 2 Output any any none Input 3 3 1 2 1 2 3 1 1 3 1 Output at least one at least one at least one Note In the second sample the MST is unique for the given graph: it contains two first edges. In the third sample any two edges form the MST for the given graph. That means that each edge is included at least in one MST. Submitted Solution: ``` import sys, threading from heapq import heappop, heappush #from mygraph import MyGraph from collections import defaultdict n_nodes, n_edges = map(int, input().split()) edges = list() results = defaultdict(lambda: 'any') highest = defaultdict(lambda: -1) to_check = defaultdict(list) graph = defaultdict(list) class UDFS: def __init__(self, n): self.n = n # index is the node self.parents = [i for i in range(n)] self.ranks = [0 for i in range(n)] def __str__(self): ''' Group -> Node ''' return '\n'.join(f'{e} -> {i}' for i, e in enumerate(self.parents)) def get_group(self, a): if a == self.parents[a]: return a # Side effect for balancing the tree self.parents[a] = self.get_group(self.parents[a]) return self.parents[a] def is_parent(self, n): return n == self.get_group(n) def is_same_group(self, a, b): return self.get_group(a) == self.get_group(b) def join(self, a, b): parent_a = self.get_group(a) parent_b = self.get_group(b) if self.ranks[parent_a] > self.ranks[parent_b]: self.parents[parent_b] = parent_a else: self.parents[parent_a] = parent_b self.ranks[parent_b] += int( self.ranks[parent_a] == self.ranks[parent_b] ) def count(self): ''' Returns number of groups ''' count = 0 for n in range(self.n): count += self.is_parent(n) return count #def get_graph(nodes, label): # graph = MyGraph(graph_type='graph', size='20,11.25!', ratio='fill',label=label, fontsize=40) # # for v in range(1,nodes+1): # graph.add_nodes(v) # # return graph # #def make_original_graph(nodes, edges): # original_graph = get_graph(nodes, "Grafo Original") # # for r in range(edges): # a, b, w = map(int, input('\tInsira dois nΓ³s e o peso da aresta que existe entre eles: ').split()) # original_graph.link(a, b, str(w)) # # img_name = "original_graph" # # original_graph.save_img(img_name) # # print(f"O grafo original foi salvo em {img_name}.png!") # #def make_edges_in_mst_graph(nodes, edges): # edges_graph = get_graph(nodes, "Arestas em MSTs") # # for r in range(edges): # edges_graph.link(a, b, str(w)) # # img_name = "edges_in_mst" # # edges_graph.save_img(img_name) # # print(f"O grafo com a ocorrΓͺncias das arestas em MSTs foi salvo em {img_name}.png!") def dfs(a, depth, p): global edges global results global highest global graph if highest[a] != -1: return highest[a]; minimum = depth highest[a] = depth for (w, a, b, i) in graph[a]: ##print('@', w, a, b, i, depth) if i == p: continue nextt = dfs(b, depth + 1, i) if nextt <= depth: results[i] = 'at least one' else: results[i] = 'any' minimum = min(minimum, nextt) highest[a] = minimum return highest[a] def main(): global edges global results global highest global graph for i in range(n_edges): a, b, w = map(int, input().split()) edges.append((w, a-1, b-1, i)) edges = sorted(edges, key=lambda x: x[0]) dsu = UDFS(n_nodes) i = 0 while i < n_edges: counter = 0 j = i while j < n_edges and edges[j][0] == edges[i][0]: if dsu.get_group(edges[j][1]) == dsu.get_group(edges[j][2]): results[edges[j][3]] = 'none' else: to_check[counter] = edges[j] counter += 1 j += 1 for k in range(counter): w, a, b, i = to_check[k] ra = dsu.get_group(a) rb = dsu.get_group(b) graph[ra].append((w, ra, rb, i)) graph[rb].append((w, rb, ra, i)) for k in range(counter): #print('To check:', to_check[k][:-1], k) dfs(to_check[k][1], 0, -1) for k in range(counter): w, a, b, i = to_check[k] ra = dsu.get_group(a) rb = dsu.get_group(b) dsu.join(ra, rb) graph[ra] = list() graph[rb] = list() highest[ra] = -1 highest[rb] = -1 counter = 0 i = j for i in range(n_edges): print(results[i]) if __name__ == "__main__": sys.setrecursionlimit(2**32//2-1) threading.stack_size(10240000) thread = threading.Thread(target=main) thread.start() ``` No
11,027
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a connected weighted undirected graph without any loops and multiple edges. Let us remind you that a graph's spanning tree is defined as an acyclic connected subgraph of the given graph that includes all of the graph's vertexes. The weight of a tree is defined as the sum of weights of the edges that the given tree contains. The minimum spanning tree (MST) of a graph is defined as the graph's spanning tree having the minimum possible weight. For any connected graph obviously exists the minimum spanning tree, but in the general case, a graph's minimum spanning tree is not unique. Your task is to determine the following for each edge of the given graph: whether it is either included in any MST, or included at least in one MST, or not included in any MST. Input The first line contains two integers n and m (2 ≀ n ≀ 105, <image>) β€” the number of the graph's vertexes and edges, correspondingly. Then follow m lines, each of them contains three integers β€” the description of the graph's edges as "ai bi wi" (1 ≀ ai, bi ≀ n, 1 ≀ wi ≀ 106, ai β‰  bi), where ai and bi are the numbers of vertexes connected by the i-th edge, wi is the edge's weight. It is guaranteed that the graph is connected and doesn't contain loops or multiple edges. Output Print m lines β€” the answers for all edges. If the i-th edge is included in any MST, print "any"; if the i-th edge is included at least in one MST, print "at least one"; if the i-th edge isn't included in any MST, print "none". Print the answers for the edges in the order in which the edges are specified in the input. Examples Input 4 5 1 2 101 1 3 100 2 3 2 2 4 2 3 4 1 Output none any at least one at least one any Input 3 3 1 2 1 2 3 1 1 3 2 Output any any none Input 3 3 1 2 1 2 3 1 1 3 1 Output at least one at least one at least one Note In the second sample the MST is unique for the given graph: it contains two first edges. In the third sample any two edges form the MST for the given graph. That means that each edge is included at least in one MST. Submitted Solution: ``` from math import inf import operator from collections import defaultdict time = 0 edges = [] ans = {} orig_edges = [] def process_edges(l, ds): if len(l) == 1: u,v = l[0] b = ds.SetOf(u) == ds.SetOf(v) ans[u,v] = "none" if b else "any" if not b: ds.Merge(u, v) else: dic = defaultdict(list) g = defaultdict(set) for e in l: u,v = e x = ds.SetOf(u) y = ds.SetOf(v) if x == y: ans[e] = "none" else: x,y = tuple(sorted([x,y])) dic[x,y].append(e) g[x].add(y) g[y].add(x) a = DFS(g) for e in a: if len(dic[e]) == 1: ans[e] = "any" for e in l: if ds.SetOf(e[1]) != ds.SetOf(e[0]): ds.Merge(e[0],e[1]) def sol(n): ds = DisjointSet(n) global edges prev_w = edges[0][1] same_weight = [] for e, w in edges + [(1,None)]: if w == prev_w: same_weight.append(e) else: process_edges(same_weight, ds) same_weight = [e] prev_w = w def DFS(graph): time = 0 visited = {key : False for key in graph} l = {key : inf for key in graph} d = {key : -1 for key in graph} f = {key : -1 for key in graph} pi = {key : key for key in graph} a = [] for i in graph.keys(): if not visited[i]: DFS_Visit(graph, i, visited, d, f, l, pi, a) return a def DFS_Visit(graph, v, visited, d, f, l, pi, a): visited[v] = True global time time+=1 d[v] = l[v] = time for i in graph[v]: if not visited[i]: pi[i] = v DFS_Visit(graph, i, visited, d, f, l, pi, a) l[v] = min(l[v], l[i]) elif pi[v] != i: l[v] = min(l[v], d[i]) if pi[v] != v and l[v] >= d[v]: a.append(tuple(sorted([v,pi[v]]))) time+=1 f[v] = time def read(): global edges n,m = map(int, input().split()) for i in range(m): x,y,w = map(int, input().split()) x,y = x-1,y-1 ans[(x,y)] = "at least one" orig_edges.append(((x,y),w)) edges = sorted(orig_edges, key=lambda x:x[1]) return n def main(): n = read() sol(n) for i in orig_edges: print(ans[i[0]]) class DisjointSet: def __init__(self, n): self.count = [1 for i in range(n)] self.father = [i for i in range(n)] def SetOf(self, x): if x == self.father[x]: return x return self.SetOf(self.father[x]) def Merge(self, x, y): a = self.SetOf(x) b = self.SetOf(y) if self.count[a] > self.count[b]: temp = a a = b b = temp self.count[b] += self.count[a] self.father[a] = b main() ``` No
11,028
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a connected weighted undirected graph without any loops and multiple edges. Let us remind you that a graph's spanning tree is defined as an acyclic connected subgraph of the given graph that includes all of the graph's vertexes. The weight of a tree is defined as the sum of weights of the edges that the given tree contains. The minimum spanning tree (MST) of a graph is defined as the graph's spanning tree having the minimum possible weight. For any connected graph obviously exists the minimum spanning tree, but in the general case, a graph's minimum spanning tree is not unique. Your task is to determine the following for each edge of the given graph: whether it is either included in any MST, or included at least in one MST, or not included in any MST. Input The first line contains two integers n and m (2 ≀ n ≀ 105, <image>) β€” the number of the graph's vertexes and edges, correspondingly. Then follow m lines, each of them contains three integers β€” the description of the graph's edges as "ai bi wi" (1 ≀ ai, bi ≀ n, 1 ≀ wi ≀ 106, ai β‰  bi), where ai and bi are the numbers of vertexes connected by the i-th edge, wi is the edge's weight. It is guaranteed that the graph is connected and doesn't contain loops or multiple edges. Output Print m lines β€” the answers for all edges. If the i-th edge is included in any MST, print "any"; if the i-th edge is included at least in one MST, print "at least one"; if the i-th edge isn't included in any MST, print "none". Print the answers for the edges in the order in which the edges are specified in the input. Examples Input 4 5 1 2 101 1 3 100 2 3 2 2 4 2 3 4 1 Output none any at least one at least one any Input 3 3 1 2 1 2 3 1 1 3 2 Output any any none Input 3 3 1 2 1 2 3 1 1 3 1 Output at least one at least one at least one Note In the second sample the MST is unique for the given graph: it contains two first edges. In the third sample any two edges form the MST for the given graph. That means that each edge is included at least in one MST. Submitted Solution: ``` import sys from math import sqrt, floor, factorial, gcd from collections import deque, Counter, defaultdict inp = sys.stdin.readline read = lambda: list(map(int, inp().strip().split())) sys.setrecursionlimit(10**3) # def a(): # n = int(inp()); arr = read() # dic = {0 : 0, 1 : abs(arr[0]-arr[1])} # def func(arr, n): # # print(arr[n], n) # if n in dic: # return(dic[n]) # min_path = min(abs(arr[n]-arr[n-1])+func(arr,n-1), abs(arr[n]-arr[n-2])+func(arr,n-2)) # dic[n] = min_path # return(min_path) # print(func(arr, n-1)) # # print(dic) if __name__ == "__main__": # a() print("""none any at least one at least one any""") pass ``` No
11,029
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a connected weighted undirected graph without any loops and multiple edges. Let us remind you that a graph's spanning tree is defined as an acyclic connected subgraph of the given graph that includes all of the graph's vertexes. The weight of a tree is defined as the sum of weights of the edges that the given tree contains. The minimum spanning tree (MST) of a graph is defined as the graph's spanning tree having the minimum possible weight. For any connected graph obviously exists the minimum spanning tree, but in the general case, a graph's minimum spanning tree is not unique. Your task is to determine the following for each edge of the given graph: whether it is either included in any MST, or included at least in one MST, or not included in any MST. Input The first line contains two integers n and m (2 ≀ n ≀ 105, <image>) β€” the number of the graph's vertexes and edges, correspondingly. Then follow m lines, each of them contains three integers β€” the description of the graph's edges as "ai bi wi" (1 ≀ ai, bi ≀ n, 1 ≀ wi ≀ 106, ai β‰  bi), where ai and bi are the numbers of vertexes connected by the i-th edge, wi is the edge's weight. It is guaranteed that the graph is connected and doesn't contain loops or multiple edges. Output Print m lines β€” the answers for all edges. If the i-th edge is included in any MST, print "any"; if the i-th edge is included at least in one MST, print "at least one"; if the i-th edge isn't included in any MST, print "none". Print the answers for the edges in the order in which the edges are specified in the input. Examples Input 4 5 1 2 101 1 3 100 2 3 2 2 4 2 3 4 1 Output none any at least one at least one any Input 3 3 1 2 1 2 3 1 1 3 2 Output any any none Input 3 3 1 2 1 2 3 1 1 3 1 Output at least one at least one at least one Note In the second sample the MST is unique for the given graph: it contains two first edges. In the third sample any two edges form the MST for the given graph. That means that each edge is included at least in one MST. Submitted Solution: ``` from sys import stdin from math import inf from collections import defaultdict class disjoinSet(object): def __init__(self,n): self.father = [x for x in range(0,n+1)] self.rank = [0 for x in range(0,n+1)] def setOf(self, x): if(self.father[x] != x): self.father[x] = self.setOf(self.father[x]) return self.father[x] def Merge(self,x,y): xR = self.setOf(x) yR = self.setOf(y) if(xR == yR): return if self.rank[xR] < self.rank[yR]: self.father[xR] = yR elif self.rank[xR] > self.rank[yR]: self.father[yR] = xR else: self.father[yR] = xR self.rank[xR] +=1 ########## def mergesort(x): if len(x) < 2: return x middle = int(len(x)/2) left = mergesort(x[:middle]) right = mergesort(x[middle:]) return merge(left,right) def merge(left,right): result = [] l,r=0,0 while l < len(left) and r < len(right): if left[l][2] <= right[r][2]: result.append(left[l]) l+=1 else: result.append(right[r]) r+=1 result += left[l:] result += right[r:] return result ########## def DFS(graph,bridges): time = 0 for key in graph: low[key] = inf d[key] = -1 pi[key] = key visited[key] = False for i in graph: if not visited[i]: DFS_Visit(graph,i,bridges) def DFS_Visit(graph,u,bridges): visited[u] = True global time time +=1 d[u] = time low[u] = d[u] for v in graph[u]: if not visited[v]: pi[v] = u DFS_Visit(graph,v,bridges) low[u] = min(low[u],low[v]) elif pi[u] != v: low[u] = min(low[u],d[v]) if pi[u] != u and low[u] >= d[u]: x = min(pi[u],u) y = max(pi[u],u) bridges.append([x,y]) time +=1 ########## n, m = map(int, stdin.readline().split()) if m > n-1: visited = {} d = {} low = {} pi = {} time = 0 edges = [] for i in range(0,m): x,y,z = map(int, stdin.readline().split()) edges.append([]) edges[i] = [x,y,z] ans = {} for i in edges: x = min(i[0],i[1]) y = max(i[0],i[1]) ans[x,y] = "at least one" dsu = disjoinSet(n) sortEdges = mergesort(edges) criticalEdges = [] i = 0 cantEdges = m while i < cantEdges: j = i; a = 0 b = 0 criticalEdges = [] while j < len(sortEdges) and sortEdges[j][2] == sortEdges[i][2]: x = dsu.setOf(sortEdges[j][0]) y = dsu.setOf(sortEdges[j][1]) a = min(sortEdges[j][0],sortEdges[j][1]) b = max(sortEdges[j][0],sortEdges[j][1]) if x == y: ans[a,b] = "none" criticalEdges.append(sortEdges[j]) j+=1 if len(criticalEdges) == 1: if ans[a,b] != "none": ans[a,b] = "any" dsu.Merge(a,b) else: graph = defaultdict(set) crossCut = defaultdict(list) for m in criticalEdges: x = min(dsu.setOf(m[0]),dsu.setOf(m[1])) y = max(dsu.setOf(m[0]),dsu.setOf(m[1])) if x != y: graph[x].add(y) graph[y].add(x) crossCut[x,y].append([min(m[0],m[1]),max(m[0],m[1])]) bridges = [] DFS(graph,bridges) for k in bridges: if len(crossCut[k[0],k[1]]) == 1: #x,y = crossCut[k[0],k[1]][0] ans[k[0],k[1]] = "any" for m in criticalEdges: dsu.Merge(m[0],m[1]) i = j for s in edges: x = min(s[0],s[1]) y = max(s[0],s[1]) print(ans[x,y]) else: for _ in range(0,m): print("any") ``` No
11,030
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem you have to implement an algorithm to defragment your hard disk. The hard disk consists of a sequence of clusters, numbered by integers from 1 to n. The disk has m recorded files, the i-th file occupies clusters with numbers ai, 1, ai, 2, ..., ai, ni. These clusters are not necessarily located consecutively on the disk, but the order in which they are given corresponds to their sequence in the file (cluster ai, 1 contains the first fragment of the i-th file, cluster ai, 2 has the second fragment, etc.). Also the disc must have one or several clusters which are free from files. You are permitted to perform operations of copying the contents of cluster number i to cluster number j (i and j must be different). Moreover, if the cluster number j used to keep some information, it is lost forever. Clusters are not cleaned, but after the defragmentation is complete, some of them are simply declared unusable (although they may possibly still contain some fragments of files). Your task is to use a sequence of copy operations to ensure that each file occupies a contiguous area of memory. Each file should occupy a consecutive cluster section, the files must follow one after another from the beginning of the hard disk. After defragmentation all free (unused) clusters should be at the end of the hard disk. After defragmenting files can be placed in an arbitrary order. Clusters of each file should go consecutively from first to last. See explanatory examples in the notes. Print the sequence of operations leading to the disk defragmentation. Note that you do not have to minimize the number of operations, but it should not exceed 2n. Input The first line contains two integers n and m (1 ≀ n, m ≀ 200) β€” the number of clusters and the number of files, correspondingly. Next m lines contain descriptions of the files. The first number in the line is ni (ni β‰₯ 1), the number of clusters occupied by the i-th file. Then follow ni numbers ai, 1, ai, 2, ..., ai, ni (1 ≀ ai, j ≀ n). It is guaranteed that each cluster number occurs not more than once and <image>, that is, there exists at least one unused cluster. Numbers on each line are separated by spaces. Output In the first line print a single integer k (0 ≀ k ≀ 2n) β€” the number of operations needed to defragment the disk. Next k lines should contain the operations' descriptions as "i j" (copy the contents of the cluster number i to the cluster number j). Examples Input 7 2 2 1 2 3 3 4 5 Output 0 Input 7 2 2 1 3 3 2 4 5 Output 3 2 6 3 2 6 3 Note Let's say that a disk consists of 8 clusters and contains two files. The first file occupies two clusters and the second file occupies three clusters. Let's look at examples of correct and incorrect positions of files after defragmentation. <image> Example 2: each file must occupy a contiguous area of memory. Example 3: the order of files to each other is not important, at first the second file can be written, and then β€” the first one. Example 4: violating the order of file fragments to each other is not allowed. Example 5: unused clusters should be located at the end, and in this example the unused clusters are 3, 7, 8. Tags: implementation Correct Solution: ``` import sys n, m, *inp = map(int, sys.stdin.read().split()) inp.reverse() f = [[0 for x in range(201)] for y in range(201)] #2D Array c = [(0,0)]*201 f_size = [0]*201 def putData(f_id, s_id, c_id): global f, c f[f_id][s_id] = c_id c[c_id] = (f_id, s_id) for f_id in range(1, m+1): f_size[f_id] = inp.pop() for s_id in range(1, f_size[f_id]+1): c_id = inp.pop() putData(f_id, s_id, c_id) e_id = c[1:].index((0,0))+1 next_id = 1 op = [] for f_id in range(1, m+1): for s_id in range(1, f_size[f_id]+1): if c[next_id]==(f_id, s_id): next_id += 1 continue if c[next_id] != (0, 0): op.append((next_id, e_id)) putData(c[next_id][0], c[next_id][1], e_id) e_id = f[f_id][s_id] c[e_id] = (0,0) op.append((e_id, next_id)) putData(f_id, s_id, next_id) next_id += 1 print(len(op)) for p in op: print("%d %d" % p) ```
11,031
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem you have to implement an algorithm to defragment your hard disk. The hard disk consists of a sequence of clusters, numbered by integers from 1 to n. The disk has m recorded files, the i-th file occupies clusters with numbers ai, 1, ai, 2, ..., ai, ni. These clusters are not necessarily located consecutively on the disk, but the order in which they are given corresponds to their sequence in the file (cluster ai, 1 contains the first fragment of the i-th file, cluster ai, 2 has the second fragment, etc.). Also the disc must have one or several clusters which are free from files. You are permitted to perform operations of copying the contents of cluster number i to cluster number j (i and j must be different). Moreover, if the cluster number j used to keep some information, it is lost forever. Clusters are not cleaned, but after the defragmentation is complete, some of them are simply declared unusable (although they may possibly still contain some fragments of files). Your task is to use a sequence of copy operations to ensure that each file occupies a contiguous area of memory. Each file should occupy a consecutive cluster section, the files must follow one after another from the beginning of the hard disk. After defragmentation all free (unused) clusters should be at the end of the hard disk. After defragmenting files can be placed in an arbitrary order. Clusters of each file should go consecutively from first to last. See explanatory examples in the notes. Print the sequence of operations leading to the disk defragmentation. Note that you do not have to minimize the number of operations, but it should not exceed 2n. Input The first line contains two integers n and m (1 ≀ n, m ≀ 200) β€” the number of clusters and the number of files, correspondingly. Next m lines contain descriptions of the files. The first number in the line is ni (ni β‰₯ 1), the number of clusters occupied by the i-th file. Then follow ni numbers ai, 1, ai, 2, ..., ai, ni (1 ≀ ai, j ≀ n). It is guaranteed that each cluster number occurs not more than once and <image>, that is, there exists at least one unused cluster. Numbers on each line are separated by spaces. Output In the first line print a single integer k (0 ≀ k ≀ 2n) β€” the number of operations needed to defragment the disk. Next k lines should contain the operations' descriptions as "i j" (copy the contents of the cluster number i to the cluster number j). Examples Input 7 2 2 1 2 3 3 4 5 Output 0 Input 7 2 2 1 3 3 2 4 5 Output 3 2 6 3 2 6 3 Note Let's say that a disk consists of 8 clusters and contains two files. The first file occupies two clusters and the second file occupies three clusters. Let's look at examples of correct and incorrect positions of files after defragmentation. <image> Example 2: each file must occupy a contiguous area of memory. Example 3: the order of files to each other is not important, at first the second file can be written, and then β€” the first one. Example 4: violating the order of file fragments to each other is not allowed. Example 5: unused clusters should be located at the end, and in this example the unused clusters are 3, 7, 8. Tags: implementation Correct Solution: ``` n, m = map(int, input().split()) mem = [-1] * 205 d = [] for i in range(m): f = list(map(int, input().split()))[1:] for j in f: mem[j] = i d.append(f) free = -1 for i in range(1, n+1): if mem[i] == -1: free = i break res, cnt = [], 0 for x in range(m): for i in range(len(d[x])): cnt += 1 if d[x][i] == cnt: continue y = mem[cnt] if y == -1: res.append((d[x][i], cnt)) mem[d[x][i]] = -1 free = d[x][i] d[x][i] = cnt mem[cnt] = x continue for j in range(len(d[y])): if d[y][j] == cnt: res.append((cnt, free)) res.append((d[x][i], cnt)) d[y][j] = free mem[free] = y free = d[x][i] mem[free] = -1 d[x][i] = cnt mem[cnt] = x print(len(res)) for (x, y) in res: print(x, y) ```
11,032
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem you have to implement an algorithm to defragment your hard disk. The hard disk consists of a sequence of clusters, numbered by integers from 1 to n. The disk has m recorded files, the i-th file occupies clusters with numbers ai, 1, ai, 2, ..., ai, ni. These clusters are not necessarily located consecutively on the disk, but the order in which they are given corresponds to their sequence in the file (cluster ai, 1 contains the first fragment of the i-th file, cluster ai, 2 has the second fragment, etc.). Also the disc must have one or several clusters which are free from files. You are permitted to perform operations of copying the contents of cluster number i to cluster number j (i and j must be different). Moreover, if the cluster number j used to keep some information, it is lost forever. Clusters are not cleaned, but after the defragmentation is complete, some of them are simply declared unusable (although they may possibly still contain some fragments of files). Your task is to use a sequence of copy operations to ensure that each file occupies a contiguous area of memory. Each file should occupy a consecutive cluster section, the files must follow one after another from the beginning of the hard disk. After defragmentation all free (unused) clusters should be at the end of the hard disk. After defragmenting files can be placed in an arbitrary order. Clusters of each file should go consecutively from first to last. See explanatory examples in the notes. Print the sequence of operations leading to the disk defragmentation. Note that you do not have to minimize the number of operations, but it should not exceed 2n. Input The first line contains two integers n and m (1 ≀ n, m ≀ 200) β€” the number of clusters and the number of files, correspondingly. Next m lines contain descriptions of the files. The first number in the line is ni (ni β‰₯ 1), the number of clusters occupied by the i-th file. Then follow ni numbers ai, 1, ai, 2, ..., ai, ni (1 ≀ ai, j ≀ n). It is guaranteed that each cluster number occurs not more than once and <image>, that is, there exists at least one unused cluster. Numbers on each line are separated by spaces. Output In the first line print a single integer k (0 ≀ k ≀ 2n) β€” the number of operations needed to defragment the disk. Next k lines should contain the operations' descriptions as "i j" (copy the contents of the cluster number i to the cluster number j). Examples Input 7 2 2 1 2 3 3 4 5 Output 0 Input 7 2 2 1 3 3 2 4 5 Output 3 2 6 3 2 6 3 Note Let's say that a disk consists of 8 clusters and contains two files. The first file occupies two clusters and the second file occupies three clusters. Let's look at examples of correct and incorrect positions of files after defragmentation. <image> Example 2: each file must occupy a contiguous area of memory. Example 3: the order of files to each other is not important, at first the second file can be written, and then β€” the first one. Example 4: violating the order of file fragments to each other is not allowed. Example 5: unused clusters should be located at the end, and in this example the unused clusters are 3, 7, 8. Submitted Solution: ``` """ Brandt Smith, Peter Haddad and Lemuel Gorion codeforces.com Problem 180A """ c, f = input().split(' ') hd = [0] * int(c) total_count = 0 moves = [] for i in range(int(f)): file = input().split() for x in range(1,len(file)): hd[int(file[x]) - 1] = [i + 1,x] while True: count = 0 zeros = [] for i in range(len(hd)): if hd[i] == 0: zeros.append(i) for i in range(len(hd) - 1): if hd[i] == 0 and hd[i + 1] == 0: continue elif hd[i] != 0 and hd[i + 1] == 0: continue elif hd[i] == 0 and hd[i + 1] != 0: if hd[i - 1] != 0 and i - 1 != -1 and (hd[i - 1][0] > hd[i + 1][0] or hd[i - 1][1] > hd[i + 1][1]): moves.append([i, i + 1]) moves.append([i + 2, i]) temp = hd[i - 1] hd[i - 1] = hd[i + 1] hd[i] = temp hd[i + 1] = 0 count += 2 else: if hd[i - 1] == 0: moves.append([i + 2, i]) temp = hd[i + 1] hd[i + 1] = hd[i - 1] hd[i - 1] = temp else: moves.append([i + 2, i + 1]) temp = hd[i + 1] hd[i + 1] = hd[i] hd[i] = temp count += 1 elif hd[i][0] > hd[i + 1][0]: t = zeros.pop() moves.append([i + 1, t]) moves.append([i + 2, i + 1]) moves.append([t, i + 2]) zeros.append(t) temp = hd[i + 1] hd[i + 1] = hd[i] hd[i] = temp count += 3 elif hd[i][0] == hd[i + 1][0] and hd[i][1] > hd[i + 1][1]: t = zeros.pop() moves.append([i + 1, t]) moves.append([i + 2, i + 1]) moves.append([t, i + 2]) zeros.append(t) temp = hd[i + 1] hd[i + 1] = hd[i] hd[i] = temp count += 3 total_count += count if count == 0: break print(total_count) if total_count > 0: for move in moves: print(move[0], move[1]) ``` No
11,033
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem you have to implement an algorithm to defragment your hard disk. The hard disk consists of a sequence of clusters, numbered by integers from 1 to n. The disk has m recorded files, the i-th file occupies clusters with numbers ai, 1, ai, 2, ..., ai, ni. These clusters are not necessarily located consecutively on the disk, but the order in which they are given corresponds to their sequence in the file (cluster ai, 1 contains the first fragment of the i-th file, cluster ai, 2 has the second fragment, etc.). Also the disc must have one or several clusters which are free from files. You are permitted to perform operations of copying the contents of cluster number i to cluster number j (i and j must be different). Moreover, if the cluster number j used to keep some information, it is lost forever. Clusters are not cleaned, but after the defragmentation is complete, some of them are simply declared unusable (although they may possibly still contain some fragments of files). Your task is to use a sequence of copy operations to ensure that each file occupies a contiguous area of memory. Each file should occupy a consecutive cluster section, the files must follow one after another from the beginning of the hard disk. After defragmentation all free (unused) clusters should be at the end of the hard disk. After defragmenting files can be placed in an arbitrary order. Clusters of each file should go consecutively from first to last. See explanatory examples in the notes. Print the sequence of operations leading to the disk defragmentation. Note that you do not have to minimize the number of operations, but it should not exceed 2n. Input The first line contains two integers n and m (1 ≀ n, m ≀ 200) β€” the number of clusters and the number of files, correspondingly. Next m lines contain descriptions of the files. The first number in the line is ni (ni β‰₯ 1), the number of clusters occupied by the i-th file. Then follow ni numbers ai, 1, ai, 2, ..., ai, ni (1 ≀ ai, j ≀ n). It is guaranteed that each cluster number occurs not more than once and <image>, that is, there exists at least one unused cluster. Numbers on each line are separated by spaces. Output In the first line print a single integer k (0 ≀ k ≀ 2n) β€” the number of operations needed to defragment the disk. Next k lines should contain the operations' descriptions as "i j" (copy the contents of the cluster number i to the cluster number j). Examples Input 7 2 2 1 2 3 3 4 5 Output 0 Input 7 2 2 1 3 3 2 4 5 Output 3 2 6 3 2 6 3 Note Let's say that a disk consists of 8 clusters and contains two files. The first file occupies two clusters and the second file occupies three clusters. Let's look at examples of correct and incorrect positions of files after defragmentation. <image> Example 2: each file must occupy a contiguous area of memory. Example 3: the order of files to each other is not important, at first the second file can be written, and then β€” the first one. Example 4: violating the order of file fragments to each other is not allowed. Example 5: unused clusters should be located at the end, and in this example the unused clusters are 3, 7, 8. Submitted Solution: ``` """ Brandt Smith, Peter Haddad and Lemuel Gorion codeforces.com Problem 180A """ c, f = input().split(' ') hd = [0] * int(c) total_count = 0 moves = [] for i in range(int(f)): file = input().split() for x in range(1,len(file)): hd[int(file[x]) - 1] = [i + 1,x] while True: count = 0 zeros = [] for i in range(len(hd)): if hd[i] == 0: zeros.append(i) for i in range(len(hd) - 1): if hd[i] == 0 and hd[i + 1] == 0: continue elif hd[i] != 0 and hd[i + 1] == 0: continue elif hd[i] == 0 and hd[i + 1] != 0: if hd[i - 1] != 0 and (hd[i - 1][0] > hd[i + 1][0] or hd[i - 1][1] > hd[i + 1][1]): moves.append([i, i + 1]) moves.append([i + 2, i]) temp = hd[i - 1] hd[i - 1] = hd[i + 1] hd[i] = temp hd[i + 1] = 0 count += 2 else: moves.append([i + 2, i + 1]) temp = hd[i + 1] hd[i + 1] = hd[i] hd[i] = temp count += 1 elif hd[i][0] > hd[i + 1][0]: t = zeros.pop() moves.append([i + 1, t]) moves.append([i + 2, i + 1]) moves.append([t, i + 2]) temp = hd[i + 1] hd[i + 1] = hd[i] hd[i] = temp count += 3 elif hd[i][0] == hd[i + 1][0] and hd[i][1] > hd[i + 1][1]: t = zeros.pop() moves.append([i + 1, t]) moves.append([i + 2, i + 1]) moves.append([t, i + 2]) temp = hd[i + 1] hd[i + 1] = hd[i] hd[i] = temp count += 3 total_count += count if count == 0: break print(total_count) if total_count > 0: for move in moves: print(move[0], move[1]) ``` No
11,034
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem you have to implement an algorithm to defragment your hard disk. The hard disk consists of a sequence of clusters, numbered by integers from 1 to n. The disk has m recorded files, the i-th file occupies clusters with numbers ai, 1, ai, 2, ..., ai, ni. These clusters are not necessarily located consecutively on the disk, but the order in which they are given corresponds to their sequence in the file (cluster ai, 1 contains the first fragment of the i-th file, cluster ai, 2 has the second fragment, etc.). Also the disc must have one or several clusters which are free from files. You are permitted to perform operations of copying the contents of cluster number i to cluster number j (i and j must be different). Moreover, if the cluster number j used to keep some information, it is lost forever. Clusters are not cleaned, but after the defragmentation is complete, some of them are simply declared unusable (although they may possibly still contain some fragments of files). Your task is to use a sequence of copy operations to ensure that each file occupies a contiguous area of memory. Each file should occupy a consecutive cluster section, the files must follow one after another from the beginning of the hard disk. After defragmentation all free (unused) clusters should be at the end of the hard disk. After defragmenting files can be placed in an arbitrary order. Clusters of each file should go consecutively from first to last. See explanatory examples in the notes. Print the sequence of operations leading to the disk defragmentation. Note that you do not have to minimize the number of operations, but it should not exceed 2n. Input The first line contains two integers n and m (1 ≀ n, m ≀ 200) β€” the number of clusters and the number of files, correspondingly. Next m lines contain descriptions of the files. The first number in the line is ni (ni β‰₯ 1), the number of clusters occupied by the i-th file. Then follow ni numbers ai, 1, ai, 2, ..., ai, ni (1 ≀ ai, j ≀ n). It is guaranteed that each cluster number occurs not more than once and <image>, that is, there exists at least one unused cluster. Numbers on each line are separated by spaces. Output In the first line print a single integer k (0 ≀ k ≀ 2n) β€” the number of operations needed to defragment the disk. Next k lines should contain the operations' descriptions as "i j" (copy the contents of the cluster number i to the cluster number j). Examples Input 7 2 2 1 2 3 3 4 5 Output 0 Input 7 2 2 1 3 3 2 4 5 Output 3 2 6 3 2 6 3 Note Let's say that a disk consists of 8 clusters and contains two files. The first file occupies two clusters and the second file occupies three clusters. Let's look at examples of correct and incorrect positions of files after defragmentation. <image> Example 2: each file must occupy a contiguous area of memory. Example 3: the order of files to each other is not important, at first the second file can be written, and then β€” the first one. Example 4: violating the order of file fragments to each other is not allowed. Example 5: unused clusters should be located at the end, and in this example the unused clusters are 3, 7, 8. Submitted Solution: ``` """ Brandt Smith, Peter Haddad and Lemuel Gorion codeforces.com Problem 180A """ c, f = input().split(' ') hd = [0] * int(c) total_count = 0 zeros = [] moves = [] for i in range(int(f)): file = input().split() for x in range(1,len(file)): hd[int(file[x]) - 1] = [i + 1,x] for x in range(len(hd)): if hd[x] == 0: zeros.append(x) while True: count = 0 for i in range(len(hd) - 1): if hd[i] == 0 and hd[i + 1] == 0: continue elif hd[i] != 0 and hd[i + 1] == 0: continue elif hd[i] == 0 and hd[i + 1] != 0: moves.append([i + 2, i + 1]) temp = hd[i + 1] hd[i + 1] = hd[i] hd[i] = temp count += 1 elif hd[i][0] > hd[i + 1][0]: t = zeros.pop() moves.append([i + 1, t]) moves.append([i + 2, i + 1]) moves.append([t, i + 2]) zeros.append(t) temp = hd[i + 1] hd[i + 1] = hd[i] hd[i] = temp count += 3 elif hd[i][0] == hd[i + 1][0] and hd[i][1] > hd[i + 1][1]: t = zeros.pop() moves.append([i + 1, t]) moves.append([i + 2, i + 1]) moves.append([t, i + 2]) zeros.append(t) temp = hd[i + 1] hd[i + 1] = hd[i] hd[i] = temp count += 3 total_count += count if count == 0: break print(total_count) if total_count > 0: for move in moves: print(move[0], move[1]) ``` No
11,035
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem you have to implement an algorithm to defragment your hard disk. The hard disk consists of a sequence of clusters, numbered by integers from 1 to n. The disk has m recorded files, the i-th file occupies clusters with numbers ai, 1, ai, 2, ..., ai, ni. These clusters are not necessarily located consecutively on the disk, but the order in which they are given corresponds to their sequence in the file (cluster ai, 1 contains the first fragment of the i-th file, cluster ai, 2 has the second fragment, etc.). Also the disc must have one or several clusters which are free from files. You are permitted to perform operations of copying the contents of cluster number i to cluster number j (i and j must be different). Moreover, if the cluster number j used to keep some information, it is lost forever. Clusters are not cleaned, but after the defragmentation is complete, some of them are simply declared unusable (although they may possibly still contain some fragments of files). Your task is to use a sequence of copy operations to ensure that each file occupies a contiguous area of memory. Each file should occupy a consecutive cluster section, the files must follow one after another from the beginning of the hard disk. After defragmentation all free (unused) clusters should be at the end of the hard disk. After defragmenting files can be placed in an arbitrary order. Clusters of each file should go consecutively from first to last. See explanatory examples in the notes. Print the sequence of operations leading to the disk defragmentation. Note that you do not have to minimize the number of operations, but it should not exceed 2n. Input The first line contains two integers n and m (1 ≀ n, m ≀ 200) β€” the number of clusters and the number of files, correspondingly. Next m lines contain descriptions of the files. The first number in the line is ni (ni β‰₯ 1), the number of clusters occupied by the i-th file. Then follow ni numbers ai, 1, ai, 2, ..., ai, ni (1 ≀ ai, j ≀ n). It is guaranteed that each cluster number occurs not more than once and <image>, that is, there exists at least one unused cluster. Numbers on each line are separated by spaces. Output In the first line print a single integer k (0 ≀ k ≀ 2n) β€” the number of operations needed to defragment the disk. Next k lines should contain the operations' descriptions as "i j" (copy the contents of the cluster number i to the cluster number j). Examples Input 7 2 2 1 2 3 3 4 5 Output 0 Input 7 2 2 1 3 3 2 4 5 Output 3 2 6 3 2 6 3 Note Let's say that a disk consists of 8 clusters and contains two files. The first file occupies two clusters and the second file occupies three clusters. Let's look at examples of correct and incorrect positions of files after defragmentation. <image> Example 2: each file must occupy a contiguous area of memory. Example 3: the order of files to each other is not important, at first the second file can be written, and then β€” the first one. Example 4: violating the order of file fragments to each other is not allowed. Example 5: unused clusters should be located at the end, and in this example the unused clusters are 3, 7, 8. Submitted Solution: ``` """ Brandt Smith, Peter Haddad and Lemuel Gorion codeforces.com Problem 180A """ c, f = input().split(' ') hd = [0] * int(c) total_count = 0 moves = [] for i in range(int(f)): file = input().split() for x in range(1,len(file)): hd[int(file[x]) - 1] = [i + 1,x] while True: count = 0 zeros = [] for i in range(len(hd)): if hd[i] == 0: zeros.append(i) print(hd,zeros) for i in range(len(hd) - 1): if hd[i] == 0 and hd[i + 1] == 0: continue elif hd[i] != 0 and hd[i + 1] == 0: continue elif hd[i] == 0 and hd[i + 1] != 0: if hd[i - 1] != 0 and i - 1 != -1 and (hd[i - 1][0] > hd[i + 1][0] or hd[i - 1][1] > hd[i + 1][1]): moves.append([i, i + 1]) moves.append([i + 2, i]) temp = hd[i - 1] hd[i - 1] = hd[i + 1] hd[i] = temp hd[i + 1] = 0 count += 2 else: if hd[i - 1] == 0: moves.append([i + 2, i]) temp = hd[i + 1] hd[i + 1] = hd[i - 1] hd[i - 1] = temp else: moves.append([i + 2, i + 1]) temp = hd[i + 1] hd[i + 1] = hd[i] hd[i] = temp count += 1 elif hd[i][0] > hd[i + 1][0]: t = zeros.pop() moves.append([i + 1, t]) moves.append([i + 2, i + 1]) moves.append([t, i + 2]) temp = hd[i + 1] hd[i + 1] = hd[i] hd[i] = temp count += 3 elif hd[i][0] == hd[i + 1][0] and hd[i][1] > hd[i + 1][1]: t = zeros.pop() moves.append([i + 1, t]) moves.append([i + 2, i + 1]) moves.append([t, i + 2]) temp = hd[i + 1] hd[i + 1] = hd[i] hd[i] = temp count += 3 total_count += count if count == 0: break print(total_count) if total_count > 0: for move in moves: print(move[0], move[1]) ``` No
11,036
Provide tags and a correct Python 3 solution for this coding contest problem. One not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game. He took a checkered white square piece of paper, consisting of n Γ— n cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the piece of paper. Since Valera was keen on everything square, he wondered, how many moves (i.e. times the boy paints a square black) he should make till a black square with side 3 can be found on the piece of paper. But Valera does not know the answer to this question, so he asks you to help him. Your task is to find the minimum number of moves, till the checkered piece of paper has at least one black square with side of 3. Otherwise determine that such move does not exist. Input The first line contains two integers n and m (1 ≀ n ≀ 1000, 1 ≀ m ≀ min(nΒ·n, 105)) β€” the size of the squared piece of paper and the number of moves, correspondingly. Then, m lines contain the description of the moves. The i-th line contains two integers xi, yi (1 ≀ xi, yi ≀ n) β€” the number of row and column of the square that gets painted on the i-th move. All numbers on the lines are separated by single spaces. It is guaranteed that all moves are different. The moves are numbered starting from 1 in the order, in which they are given in the input. The columns of the squared piece of paper are numbered starting from 1, from the left to the right. The rows of the squared piece of paper are numbered starting from 1, from top to bottom. Output On a single line print the answer to the problem β€” the minimum number of the move after which the piece of paper has a black square with side 3. If no such move exists, print -1. Examples Input 4 11 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 3 3 4 1 Output 10 Input 4 12 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 4 2 4 1 3 1 Output -1 Tags: brute force, implementation Correct Solution: ``` n, m = map(int, input().split()) arr = [[0] * (n+4) for _ in range(n+4)] for c in range(m): x, y = map(int, input().split()) for i in range(x, x + 3): for j in range(y, y + 3): arr[i][j] += 1 if arr[i][j] == 9: print(c + 1) exit() print(-1) ```
11,037
Provide tags and a correct Python 3 solution for this coding contest problem. One not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game. He took a checkered white square piece of paper, consisting of n Γ— n cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the piece of paper. Since Valera was keen on everything square, he wondered, how many moves (i.e. times the boy paints a square black) he should make till a black square with side 3 can be found on the piece of paper. But Valera does not know the answer to this question, so he asks you to help him. Your task is to find the minimum number of moves, till the checkered piece of paper has at least one black square with side of 3. Otherwise determine that such move does not exist. Input The first line contains two integers n and m (1 ≀ n ≀ 1000, 1 ≀ m ≀ min(nΒ·n, 105)) β€” the size of the squared piece of paper and the number of moves, correspondingly. Then, m lines contain the description of the moves. The i-th line contains two integers xi, yi (1 ≀ xi, yi ≀ n) β€” the number of row and column of the square that gets painted on the i-th move. All numbers on the lines are separated by single spaces. It is guaranteed that all moves are different. The moves are numbered starting from 1 in the order, in which they are given in the input. The columns of the squared piece of paper are numbered starting from 1, from the left to the right. The rows of the squared piece of paper are numbered starting from 1, from top to bottom. Output On a single line print the answer to the problem β€” the minimum number of the move after which the piece of paper has a black square with side 3. If no such move exists, print -1. Examples Input 4 11 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 3 3 4 1 Output 10 Input 4 12 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 4 2 4 1 3 1 Output -1 Tags: brute force, implementation Correct Solution: ``` a,b=map(int,input().split()) z=[[0]*(a+4) for i in range(a+4)] def gh(i,j): for i1 in range(i-2,i+1): for j1 in range(j-2,j+1): if i1<1 or j1<1:continue ok=True for i2 in range(i1,i1+3): for j2 in range(j1,j1+3): if z[i2][j2]==0:ok=False;break if not(ok):break if ok:return ok return False for _ in range(1,b+1): u,v=map(int,input().split()) z[u][v]=1 if gh(u,v):exit(print(_)) print(-1) ```
11,038
Provide tags and a correct Python 3 solution for this coding contest problem. One not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game. He took a checkered white square piece of paper, consisting of n Γ— n cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the piece of paper. Since Valera was keen on everything square, he wondered, how many moves (i.e. times the boy paints a square black) he should make till a black square with side 3 can be found on the piece of paper. But Valera does not know the answer to this question, so he asks you to help him. Your task is to find the minimum number of moves, till the checkered piece of paper has at least one black square with side of 3. Otherwise determine that such move does not exist. Input The first line contains two integers n and m (1 ≀ n ≀ 1000, 1 ≀ m ≀ min(nΒ·n, 105)) β€” the size of the squared piece of paper and the number of moves, correspondingly. Then, m lines contain the description of the moves. The i-th line contains two integers xi, yi (1 ≀ xi, yi ≀ n) β€” the number of row and column of the square that gets painted on the i-th move. All numbers on the lines are separated by single spaces. It is guaranteed that all moves are different. The moves are numbered starting from 1 in the order, in which they are given in the input. The columns of the squared piece of paper are numbered starting from 1, from the left to the right. The rows of the squared piece of paper are numbered starting from 1, from top to bottom. Output On a single line print the answer to the problem β€” the minimum number of the move after which the piece of paper has a black square with side 3. If no such move exists, print -1. Examples Input 4 11 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 3 3 4 1 Output 10 Input 4 12 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 4 2 4 1 3 1 Output -1 Tags: brute force, implementation Correct Solution: ``` n,m = map(int,input().split()) grid = [[0 for i in range(n)] for j in range(n)] for tc in range(m): r,c = map(int,input().split()) r -= 1 c -= 1 ok = False for i in range(r-1,r+2): for j in range(c-1,c+2): # print(i,j) if 0 <= i and i < n and 0 <= j and j < n: grid[i][j] += 1 if grid[i][j] == 9: ok = True if ok: print(tc+1) exit() print(-1) ```
11,039
Provide tags and a correct Python 3 solution for this coding contest problem. One not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game. He took a checkered white square piece of paper, consisting of n Γ— n cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the piece of paper. Since Valera was keen on everything square, he wondered, how many moves (i.e. times the boy paints a square black) he should make till a black square with side 3 can be found on the piece of paper. But Valera does not know the answer to this question, so he asks you to help him. Your task is to find the minimum number of moves, till the checkered piece of paper has at least one black square with side of 3. Otherwise determine that such move does not exist. Input The first line contains two integers n and m (1 ≀ n ≀ 1000, 1 ≀ m ≀ min(nΒ·n, 105)) β€” the size of the squared piece of paper and the number of moves, correspondingly. Then, m lines contain the description of the moves. The i-th line contains two integers xi, yi (1 ≀ xi, yi ≀ n) β€” the number of row and column of the square that gets painted on the i-th move. All numbers on the lines are separated by single spaces. It is guaranteed that all moves are different. The moves are numbered starting from 1 in the order, in which they are given in the input. The columns of the squared piece of paper are numbered starting from 1, from the left to the right. The rows of the squared piece of paper are numbered starting from 1, from top to bottom. Output On a single line print the answer to the problem β€” the minimum number of the move after which the piece of paper has a black square with side 3. If no such move exists, print -1. Examples Input 4 11 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 3 3 4 1 Output 10 Input 4 12 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 4 2 4 1 3 1 Output -1 Tags: brute force, implementation Correct Solution: ``` from sys import stdin a,b=map(int,stdin.readline().split()) z=[[0]*(a+4) for i in range(a+4)] def gh(i,j): for i1 in range(i-2,i+1): for j1 in range(j-2,j+1): if i1<1 or j1<1:continue ok=True for i2 in range(i1,i1+3): for j2 in range(j1,j1+3): if z[i2][j2]==0:ok=False;break if not(ok):break if ok:return ok return False for _ in range(1,b+1): u,v=map(int,stdin.readline().split()) z[u][v]=1 if gh(u,v):exit(print(_)) print(-1) ```
11,040
Provide tags and a correct Python 3 solution for this coding contest problem. One not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game. He took a checkered white square piece of paper, consisting of n Γ— n cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the piece of paper. Since Valera was keen on everything square, he wondered, how many moves (i.e. times the boy paints a square black) he should make till a black square with side 3 can be found on the piece of paper. But Valera does not know the answer to this question, so he asks you to help him. Your task is to find the minimum number of moves, till the checkered piece of paper has at least one black square with side of 3. Otherwise determine that such move does not exist. Input The first line contains two integers n and m (1 ≀ n ≀ 1000, 1 ≀ m ≀ min(nΒ·n, 105)) β€” the size of the squared piece of paper and the number of moves, correspondingly. Then, m lines contain the description of the moves. The i-th line contains two integers xi, yi (1 ≀ xi, yi ≀ n) β€” the number of row and column of the square that gets painted on the i-th move. All numbers on the lines are separated by single spaces. It is guaranteed that all moves are different. The moves are numbered starting from 1 in the order, in which they are given in the input. The columns of the squared piece of paper are numbered starting from 1, from the left to the right. The rows of the squared piece of paper are numbered starting from 1, from top to bottom. Output On a single line print the answer to the problem β€” the minimum number of the move after which the piece of paper has a black square with side 3. If no such move exists, print -1. Examples Input 4 11 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 3 3 4 1 Output 10 Input 4 12 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 4 2 4 1 3 1 Output -1 Tags: brute force, implementation Correct Solution: ``` def f(): n, m = map(int, input().split()) p = [[0] * (n + 2) for i in range(n + 2)] for k in range(m): x, y = map(int, input().split()) for i in range(x - 1, x + 2): for j in range(y - 1, y + 2): if p[i][j] == 8: return k + 1 p[i][j] += 1 return -1 print(f()) ```
11,041
Provide tags and a correct Python 3 solution for this coding contest problem. One not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game. He took a checkered white square piece of paper, consisting of n Γ— n cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the piece of paper. Since Valera was keen on everything square, he wondered, how many moves (i.e. times the boy paints a square black) he should make till a black square with side 3 can be found on the piece of paper. But Valera does not know the answer to this question, so he asks you to help him. Your task is to find the minimum number of moves, till the checkered piece of paper has at least one black square with side of 3. Otherwise determine that such move does not exist. Input The first line contains two integers n and m (1 ≀ n ≀ 1000, 1 ≀ m ≀ min(nΒ·n, 105)) β€” the size of the squared piece of paper and the number of moves, correspondingly. Then, m lines contain the description of the moves. The i-th line contains two integers xi, yi (1 ≀ xi, yi ≀ n) β€” the number of row and column of the square that gets painted on the i-th move. All numbers on the lines are separated by single spaces. It is guaranteed that all moves are different. The moves are numbered starting from 1 in the order, in which they are given in the input. The columns of the squared piece of paper are numbered starting from 1, from the left to the right. The rows of the squared piece of paper are numbered starting from 1, from top to bottom. Output On a single line print the answer to the problem β€” the minimum number of the move after which the piece of paper has a black square with side 3. If no such move exists, print -1. Examples Input 4 11 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 3 3 4 1 Output 10 Input 4 12 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 4 2 4 1 3 1 Output -1 Tags: brute force, implementation Correct Solution: ``` def f(): n, m = map(int, input().split()) p = [[0] * (n + 2) for i in range(n + 2)] for k in range(m): x, y = map(int, input().split()) for i in range(x - 1, x + 2): for j in range(y - 1, y + 2): if p[i][j] == 8: return k + 1 p[i][j] += 1 return -1 print(f()) # Made By Mostafa_Khaled ```
11,042
Provide tags and a correct Python 3 solution for this coding contest problem. One not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game. He took a checkered white square piece of paper, consisting of n Γ— n cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the piece of paper. Since Valera was keen on everything square, he wondered, how many moves (i.e. times the boy paints a square black) he should make till a black square with side 3 can be found on the piece of paper. But Valera does not know the answer to this question, so he asks you to help him. Your task is to find the minimum number of moves, till the checkered piece of paper has at least one black square with side of 3. Otherwise determine that such move does not exist. Input The first line contains two integers n and m (1 ≀ n ≀ 1000, 1 ≀ m ≀ min(nΒ·n, 105)) β€” the size of the squared piece of paper and the number of moves, correspondingly. Then, m lines contain the description of the moves. The i-th line contains two integers xi, yi (1 ≀ xi, yi ≀ n) β€” the number of row and column of the square that gets painted on the i-th move. All numbers on the lines are separated by single spaces. It is guaranteed that all moves are different. The moves are numbered starting from 1 in the order, in which they are given in the input. The columns of the squared piece of paper are numbered starting from 1, from the left to the right. The rows of the squared piece of paper are numbered starting from 1, from top to bottom. Output On a single line print the answer to the problem β€” the minimum number of the move after which the piece of paper has a black square with side 3. If no such move exists, print -1. Examples Input 4 11 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 3 3 4 1 Output 10 Input 4 12 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 4 2 4 1 3 1 Output -1 Tags: brute force, implementation Correct Solution: ``` import math from sys import stdin from math import ceil import sys if __name__ == '__main__': numbers = list(map(int, input().split())) n = numbers[0] m = numbers[1] moves = [[0] * (n + 4) for _ in range(n + 4)] for i in range(m): listOfMoves = list(map(int, input().split())) x = listOfMoves[0] y = listOfMoves[1] for a in range(x, x + 3): for b in range(y, y + 3): moves[a][b] = moves[a][b] + 1 if moves[a][b] == 9: print(i + 1) quit() print(-1) ```
11,043
Provide tags and a correct Python 3 solution for this coding contest problem. One not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game. He took a checkered white square piece of paper, consisting of n Γ— n cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the piece of paper. Since Valera was keen on everything square, he wondered, how many moves (i.e. times the boy paints a square black) he should make till a black square with side 3 can be found on the piece of paper. But Valera does not know the answer to this question, so he asks you to help him. Your task is to find the minimum number of moves, till the checkered piece of paper has at least one black square with side of 3. Otherwise determine that such move does not exist. Input The first line contains two integers n and m (1 ≀ n ≀ 1000, 1 ≀ m ≀ min(nΒ·n, 105)) β€” the size of the squared piece of paper and the number of moves, correspondingly. Then, m lines contain the description of the moves. The i-th line contains two integers xi, yi (1 ≀ xi, yi ≀ n) β€” the number of row and column of the square that gets painted on the i-th move. All numbers on the lines are separated by single spaces. It is guaranteed that all moves are different. The moves are numbered starting from 1 in the order, in which they are given in the input. The columns of the squared piece of paper are numbered starting from 1, from the left to the right. The rows of the squared piece of paper are numbered starting from 1, from top to bottom. Output On a single line print the answer to the problem β€” the minimum number of the move after which the piece of paper has a black square with side 3. If no such move exists, print -1. Examples Input 4 11 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 3 3 4 1 Output 10 Input 4 12 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 4 2 4 1 3 1 Output -1 Tags: brute force, implementation Correct Solution: ``` R=lambda:map(int,input().split()) n,m=R() if n<3 or m<9: print(-1) exit() a=[[0]*(n-2) for i in range(n-2)] for i in range(1,m+1): x,y=R() x-=1 y-=1 for x0 in range(x-2,x+1): for y0 in range(y-2,y+1): if x0<0 or y0<0 or x0>=n-2 or y0>=n-2: continue a[x0][y0]+=1 if a[x0][y0]==9: print(i) exit() print(-1) ```
11,044
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game. He took a checkered white square piece of paper, consisting of n Γ— n cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the piece of paper. Since Valera was keen on everything square, he wondered, how many moves (i.e. times the boy paints a square black) he should make till a black square with side 3 can be found on the piece of paper. But Valera does not know the answer to this question, so he asks you to help him. Your task is to find the minimum number of moves, till the checkered piece of paper has at least one black square with side of 3. Otherwise determine that such move does not exist. Input The first line contains two integers n and m (1 ≀ n ≀ 1000, 1 ≀ m ≀ min(nΒ·n, 105)) β€” the size of the squared piece of paper and the number of moves, correspondingly. Then, m lines contain the description of the moves. The i-th line contains two integers xi, yi (1 ≀ xi, yi ≀ n) β€” the number of row and column of the square that gets painted on the i-th move. All numbers on the lines are separated by single spaces. It is guaranteed that all moves are different. The moves are numbered starting from 1 in the order, in which they are given in the input. The columns of the squared piece of paper are numbered starting from 1, from the left to the right. The rows of the squared piece of paper are numbered starting from 1, from top to bottom. Output On a single line print the answer to the problem β€” the minimum number of the move after which the piece of paper has a black square with side 3. If no such move exists, print -1. Examples Input 4 11 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 3 3 4 1 Output 10 Input 4 12 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 4 2 4 1 3 1 Output -1 Submitted Solution: ``` def solve_case(): n, m = map(int, input().split()) count = [None] * n for i in range(n): count[i] = [0] * n ans = -1 for k in range(m): x, y = map(int, input().split()) x -= 1 y -= 1 found = False for i in range(x-2, x+1): for j in range(y-2, y+1): if i >= 0 and i < n and j >= 0 and j < n: count[i][j] += 1 if count[i][j] == 9: found = True if found: ans = k + 1 break print(ans) solve_case() ``` Yes
11,045
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game. He took a checkered white square piece of paper, consisting of n Γ— n cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the piece of paper. Since Valera was keen on everything square, he wondered, how many moves (i.e. times the boy paints a square black) he should make till a black square with side 3 can be found on the piece of paper. But Valera does not know the answer to this question, so he asks you to help him. Your task is to find the minimum number of moves, till the checkered piece of paper has at least one black square with side of 3. Otherwise determine that such move does not exist. Input The first line contains two integers n and m (1 ≀ n ≀ 1000, 1 ≀ m ≀ min(nΒ·n, 105)) β€” the size of the squared piece of paper and the number of moves, correspondingly. Then, m lines contain the description of the moves. The i-th line contains two integers xi, yi (1 ≀ xi, yi ≀ n) β€” the number of row and column of the square that gets painted on the i-th move. All numbers on the lines are separated by single spaces. It is guaranteed that all moves are different. The moves are numbered starting from 1 in the order, in which they are given in the input. The columns of the squared piece of paper are numbered starting from 1, from the left to the right. The rows of the squared piece of paper are numbered starting from 1, from top to bottom. Output On a single line print the answer to the problem β€” the minimum number of the move after which the piece of paper has a black square with side 3. If no such move exists, print -1. Examples Input 4 11 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 3 3 4 1 Output 10 Input 4 12 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 4 2 4 1 3 1 Output -1 Submitted Solution: ``` n, m = map(int, input().split()) c = [[0] * (n + 4) for _ in range(n + 4)] for l in range(m): x, y = map(int, input().split()) for i in range(x, x + 3): for j in range(y, y + 3): c[i][j] += 1 if c[i][j] == 9: print(l + 1) quit() print(-1) ``` Yes
11,046
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game. He took a checkered white square piece of paper, consisting of n Γ— n cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the piece of paper. Since Valera was keen on everything square, he wondered, how many moves (i.e. times the boy paints a square black) he should make till a black square with side 3 can be found on the piece of paper. But Valera does not know the answer to this question, so he asks you to help him. Your task is to find the minimum number of moves, till the checkered piece of paper has at least one black square with side of 3. Otherwise determine that such move does not exist. Input The first line contains two integers n and m (1 ≀ n ≀ 1000, 1 ≀ m ≀ min(nΒ·n, 105)) β€” the size of the squared piece of paper and the number of moves, correspondingly. Then, m lines contain the description of the moves. The i-th line contains two integers xi, yi (1 ≀ xi, yi ≀ n) β€” the number of row and column of the square that gets painted on the i-th move. All numbers on the lines are separated by single spaces. It is guaranteed that all moves are different. The moves are numbered starting from 1 in the order, in which they are given in the input. The columns of the squared piece of paper are numbered starting from 1, from the left to the right. The rows of the squared piece of paper are numbered starting from 1, from top to bottom. Output On a single line print the answer to the problem β€” the minimum number of the move after which the piece of paper has a black square with side 3. If no such move exists, print -1. Examples Input 4 11 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 3 3 4 1 Output 10 Input 4 12 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 4 2 4 1 3 1 Output -1 Submitted Solution: ``` n, m = map(int, input().split()) a = [[0 for i in range(n + 2)] for i in range(n + 2)] answer = -1 for i in range(m): x, y = map(int, input().split()) a[x-1][y-1] += 1 a[x-1][y] += 1 a[x-1][y+1] += 1 a[x][y-1] += 1 a[x][y] += 1 a[x][y+1] += 1 a[x+1][y-1] += 1 a[x+1][y] += 1 a[x+1][y+1] += 1 if max(a[x-1][y-1], a[x-1][y], a[x-1][y+1], a[x][y-1], a[x][y], a[x][y+1], a[x+1][y-1], a[x+1][y], a[x+1][y+1]) == 9: answer = i + 1 break print(answer) ``` Yes
11,047
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game. He took a checkered white square piece of paper, consisting of n Γ— n cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the piece of paper. Since Valera was keen on everything square, he wondered, how many moves (i.e. times the boy paints a square black) he should make till a black square with side 3 can be found on the piece of paper. But Valera does not know the answer to this question, so he asks you to help him. Your task is to find the minimum number of moves, till the checkered piece of paper has at least one black square with side of 3. Otherwise determine that such move does not exist. Input The first line contains two integers n and m (1 ≀ n ≀ 1000, 1 ≀ m ≀ min(nΒ·n, 105)) β€” the size of the squared piece of paper and the number of moves, correspondingly. Then, m lines contain the description of the moves. The i-th line contains two integers xi, yi (1 ≀ xi, yi ≀ n) β€” the number of row and column of the square that gets painted on the i-th move. All numbers on the lines are separated by single spaces. It is guaranteed that all moves are different. The moves are numbered starting from 1 in the order, in which they are given in the input. The columns of the squared piece of paper are numbered starting from 1, from the left to the right. The rows of the squared piece of paper are numbered starting from 1, from top to bottom. Output On a single line print the answer to the problem β€” the minimum number of the move after which the piece of paper has a black square with side 3. If no such move exists, print -1. Examples Input 4 11 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 3 3 4 1 Output 10 Input 4 12 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 4 2 4 1 3 1 Output -1 Submitted Solution: ``` read = lambda: map(int, input().split()) xy = [[0]*1002 for i in range(1002)] n, m = read() for i in range(m): x, y = read() for j in range(x-1, x+2): for k in range(y-1, y+2): xy[j][k] += 1 if xy[j][k] is 9: print(i+1) exit() print(-1) ``` Yes
11,048
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game. He took a checkered white square piece of paper, consisting of n Γ— n cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the piece of paper. Since Valera was keen on everything square, he wondered, how many moves (i.e. times the boy paints a square black) he should make till a black square with side 3 can be found on the piece of paper. But Valera does not know the answer to this question, so he asks you to help him. Your task is to find the minimum number of moves, till the checkered piece of paper has at least one black square with side of 3. Otherwise determine that such move does not exist. Input The first line contains two integers n and m (1 ≀ n ≀ 1000, 1 ≀ m ≀ min(nΒ·n, 105)) β€” the size of the squared piece of paper and the number of moves, correspondingly. Then, m lines contain the description of the moves. The i-th line contains two integers xi, yi (1 ≀ xi, yi ≀ n) β€” the number of row and column of the square that gets painted on the i-th move. All numbers on the lines are separated by single spaces. It is guaranteed that all moves are different. The moves are numbered starting from 1 in the order, in which they are given in the input. The columns of the squared piece of paper are numbered starting from 1, from the left to the right. The rows of the squared piece of paper are numbered starting from 1, from top to bottom. Output On a single line print the answer to the problem β€” the minimum number of the move after which the piece of paper has a black square with side 3. If no such move exists, print -1. Examples Input 4 11 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 3 3 4 1 Output 10 Input 4 12 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 4 2 4 1 3 1 Output -1 Submitted Solution: ``` import bisect import os import gc import sys from io import BytesIO, IOBase from collections import Counter from collections import deque import heapq import math import statistics def sin(): return input() def ain(): return list(map(int, sin().split())) def sain(): return input().split() def iin(): return int(sin()) MAX = float('inf') MIN = float('-inf') MOD = 1000000007 def sieve(n): prime = [True for i in range(n+1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n+1, p): prime[i] = False p += 1 s = set() for p in range(2, n+1): if prime[p]: s.add(p) return s def readTree(n, m): adj = [deque([]) for _ in range(n+1)] for _ in range(m): u,v = ain() adj[u].append(v) adj[v].append(u) return adj def main(): n,m = ain() arr = [[0]*n for _ in range(n)] d = {} for i in range(m): x,y = ain() arr[x-1][y-1] = 1 d[str(x-1)+str(y-1)] = i ans = MAX for i in range(n-2): for j in range(n-2): ss = set() if str(i)+str(j) in d: for k in range(3): for m in range(3): if arr[i+k][j+m] == 1: ss.add(d[str(i+k)+str(j+m)]) if len(ss) == 9: ans = min(ans, max(ss)) if ans == MAX: print(-1) else: print(ans+1) # Fast IO Template starts 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 Template ends if __name__ == "__main__": main() ``` No
11,049
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game. He took a checkered white square piece of paper, consisting of n Γ— n cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the piece of paper. Since Valera was keen on everything square, he wondered, how many moves (i.e. times the boy paints a square black) he should make till a black square with side 3 can be found on the piece of paper. But Valera does not know the answer to this question, so he asks you to help him. Your task is to find the minimum number of moves, till the checkered piece of paper has at least one black square with side of 3. Otherwise determine that such move does not exist. Input The first line contains two integers n and m (1 ≀ n ≀ 1000, 1 ≀ m ≀ min(nΒ·n, 105)) β€” the size of the squared piece of paper and the number of moves, correspondingly. Then, m lines contain the description of the moves. The i-th line contains two integers xi, yi (1 ≀ xi, yi ≀ n) β€” the number of row and column of the square that gets painted on the i-th move. All numbers on the lines are separated by single spaces. It is guaranteed that all moves are different. The moves are numbered starting from 1 in the order, in which they are given in the input. The columns of the squared piece of paper are numbered starting from 1, from the left to the right. The rows of the squared piece of paper are numbered starting from 1, from top to bottom. Output On a single line print the answer to the problem β€” the minimum number of the move after which the piece of paper has a black square with side 3. If no such move exists, print -1. Examples Input 4 11 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 3 3 4 1 Output 10 Input 4 12 1 1 1 2 1 3 2 2 2 3 1 4 2 4 3 4 3 2 4 2 4 1 3 1 Output -1 Submitted Solution: ``` def f(): n, m = map(int, input().split()) k, p = 1, [[0] * (n + 1) for i in range(n + 1)] for i in range(m): x, y = map(int, input().split()) p[x][y] = 1 if k > 8: for i in range(max(x - 2, 1), min(x + 2, n) - 1): for j in range(max(y - 2, 1), min(y + 2, n) - 1): if k == 10: print(i, j, p[i][j: j + 3] + p[i + 1][j: j + 3] + p[i + 2][j: j + 3]) if [1, 1, 1] == p[i][j: j + 3] == p[i + 1][j: j + 3] == p[i + 2][j: j + 3]: return k k += 1 return -1 print(f()) ``` No
11,050
Provide tags and a correct Python 3 solution for this coding contest problem. Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades. Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party. Input The first line contains four space-separated integers s1, s2, s3, s4 (1 ≀ s1, s2, s3, s4 ≀ 109) β€” the colors of horseshoes Valera has. Consider all possible colors indexed with integers. Output Print a single integer β€” the minimum number of horseshoes Valera needs to buy. Examples Input 1 7 3 3 Output 1 Input 7 7 7 7 Output 3 Tags: implementation Correct Solution: ``` s = sorted(list(map(int, input().split()))) d = 3 for i in range(3): if(s[i] != s[i+1]): d -= 1 print(d) ```
11,051
Provide tags and a correct Python 3 solution for this coding contest problem. Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades. Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party. Input The first line contains four space-separated integers s1, s2, s3, s4 (1 ≀ s1, s2, s3, s4 ≀ 109) β€” the colors of horseshoes Valera has. Consider all possible colors indexed with integers. Output Print a single integer β€” the minimum number of horseshoes Valera needs to buy. Examples Input 1 7 3 3 Output 1 Input 7 7 7 7 Output 3 Tags: implementation Correct Solution: ``` arr = [int(i) for i in input().split()] arr.sort() c = 0 for i in range(3): if arr[i]==arr[i+1]: c += 1 print(c) ```
11,052
Provide tags and a correct Python 3 solution for this coding contest problem. Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades. Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party. Input The first line contains four space-separated integers s1, s2, s3, s4 (1 ≀ s1, s2, s3, s4 ≀ 109) β€” the colors of horseshoes Valera has. Consider all possible colors indexed with integers. Output Print a single integer β€” the minimum number of horseshoes Valera needs to buy. Examples Input 1 7 3 3 Output 1 Input 7 7 7 7 Output 3 Tags: implementation Correct Solution: ``` l = [int(x) for x in input().split()] l = set(l) print(4-len(l)) ```
11,053
Provide tags and a correct Python 3 solution for this coding contest problem. Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades. Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party. Input The first line contains four space-separated integers s1, s2, s3, s4 (1 ≀ s1, s2, s3, s4 ≀ 109) β€” the colors of horseshoes Valera has. Consider all possible colors indexed with integers. Output Print a single integer β€” the minimum number of horseshoes Valera needs to buy. Examples Input 1 7 3 3 Output 1 Input 7 7 7 7 Output 3 Tags: implementation Correct Solution: ``` def s(a): u=set() u.update(a) return 4-len(u) a=map(int,input().split(" ")) print(s(a)) ```
11,054
Provide tags and a correct Python 3 solution for this coding contest problem. Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades. Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party. Input The first line contains four space-separated integers s1, s2, s3, s4 (1 ≀ s1, s2, s3, s4 ≀ 109) β€” the colors of horseshoes Valera has. Consider all possible colors indexed with integers. Output Print a single integer β€” the minimum number of horseshoes Valera needs to buy. Examples Input 1 7 3 3 Output 1 Input 7 7 7 7 Output 3 Tags: implementation Correct Solution: ``` colors = list(map(int, input().split(' '))) print(4-len(list(set(colors)))) ```
11,055
Provide tags and a correct Python 3 solution for this coding contest problem. Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades. Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party. Input The first line contains four space-separated integers s1, s2, s3, s4 (1 ≀ s1, s2, s3, s4 ≀ 109) β€” the colors of horseshoes Valera has. Consider all possible colors indexed with integers. Output Print a single integer β€” the minimum number of horseshoes Valera needs to buy. Examples Input 1 7 3 3 Output 1 Input 7 7 7 7 Output 3 Tags: implementation Correct Solution: ``` shoes_coulur =list(map(int,input().split())) uni_colur =[] for i in shoes_coulur : if i not in uni_colur : uni_colur.append(i) print(len(shoes_coulur)-len(uni_colur)) ```
11,056
Provide tags and a correct Python 3 solution for this coding contest problem. Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades. Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party. Input The first line contains four space-separated integers s1, s2, s3, s4 (1 ≀ s1, s2, s3, s4 ≀ 109) β€” the colors of horseshoes Valera has. Consider all possible colors indexed with integers. Output Print a single integer β€” the minimum number of horseshoes Valera needs to buy. Examples Input 1 7 3 3 Output 1 Input 7 7 7 7 Output 3 Tags: implementation Correct Solution: ``` s=list(map(int,input().split())) print(len(s)-len(set(s))) ```
11,057
Provide tags and a correct Python 3 solution for this coding contest problem. Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades. Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party. Input The first line contains four space-separated integers s1, s2, s3, s4 (1 ≀ s1, s2, s3, s4 ≀ 109) β€” the colors of horseshoes Valera has. Consider all possible colors indexed with integers. Output Print a single integer β€” the minimum number of horseshoes Valera needs to buy. Examples Input 1 7 3 3 Output 1 Input 7 7 7 7 Output 3 Tags: implementation Correct Solution: ``` a=input().split() b=len(a) c=len(set(a)) print(b-c) ```
11,058
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades. Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party. Input The first line contains four space-separated integers s1, s2, s3, s4 (1 ≀ s1, s2, s3, s4 ≀ 109) β€” the colors of horseshoes Valera has. Consider all possible colors indexed with integers. Output Print a single integer β€” the minimum number of horseshoes Valera needs to buy. Examples Input 1 7 3 3 Output 1 Input 7 7 7 7 Output 3 Submitted Solution: ``` s = list(map(int, input().split())) b = set(s) print(int(len(s)) - len(b)) ``` Yes
11,059
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades. Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party. Input The first line contains four space-separated integers s1, s2, s3, s4 (1 ≀ s1, s2, s3, s4 ≀ 109) β€” the colors of horseshoes Valera has. Consider all possible colors indexed with integers. Output Print a single integer β€” the minimum number of horseshoes Valera needs to buy. Examples Input 1 7 3 3 Output 1 Input 7 7 7 7 Output 3 Submitted Solution: ``` s = input().split(" ") x = [] for i in s: if i not in x: x.append(i) print(4-len(x)) ``` Yes
11,060
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades. Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party. Input The first line contains four space-separated integers s1, s2, s3, s4 (1 ≀ s1, s2, s3, s4 ≀ 109) β€” the colors of horseshoes Valera has. Consider all possible colors indexed with integers. Output Print a single integer β€” the minimum number of horseshoes Valera needs to buy. Examples Input 1 7 3 3 Output 1 Input 7 7 7 7 Output 3 Submitted Solution: ``` s = list(map(int, input().split())) differList = [] for i in s: if i not in differList: differList.append(i) result = 4 - len(differList) print(result) ``` Yes
11,061
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades. Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party. Input The first line contains four space-separated integers s1, s2, s3, s4 (1 ≀ s1, s2, s3, s4 ≀ 109) β€” the colors of horseshoes Valera has. Consider all possible colors indexed with integers. Output Print a single integer β€” the minimum number of horseshoes Valera needs to buy. Examples Input 1 7 3 3 Output 1 Input 7 7 7 7 Output 3 Submitted Solution: ``` x = list(map(int,input().split())) q = len(set(x)) print(4-q) ``` Yes
11,062
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades. Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party. Input The first line contains four space-separated integers s1, s2, s3, s4 (1 ≀ s1, s2, s3, s4 ≀ 109) β€” the colors of horseshoes Valera has. Consider all possible colors indexed with integers. Output Print a single integer β€” the minimum number of horseshoes Valera needs to buy. Examples Input 1 7 3 3 Output 1 Input 7 7 7 7 Output 3 Submitted Solution: ``` set1 = set(input()) print(5-len(set1)) ``` No
11,063
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades. Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party. Input The first line contains four space-separated integers s1, s2, s3, s4 (1 ≀ s1, s2, s3, s4 ≀ 109) β€” the colors of horseshoes Valera has. Consider all possible colors indexed with integers. Output Print a single integer β€” the minimum number of horseshoes Valera needs to buy. Examples Input 1 7 3 3 Output 1 Input 7 7 7 7 Output 3 Submitted Solution: ``` x = input().split() d = {} c = 0 for i in x: if i in d.keys(): d[i] = d[i] + 1 else: d[i] = 1 for j in d.values(): if j > 1: c = c + j elif j == 1: c = c + 0 else: pass if c == 0: print("0") if c == 4: print("2") else: print(c-1) ``` No
11,064
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades. Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party. Input The first line contains four space-separated integers s1, s2, s3, s4 (1 ≀ s1, s2, s3, s4 ≀ 109) β€” the colors of horseshoes Valera has. Consider all possible colors indexed with integers. Output Print a single integer β€” the minimum number of horseshoes Valera needs to buy. Examples Input 1 7 3 3 Output 1 Input 7 7 7 7 Output 3 Submitted Solution: ``` arr = [int(i) for i in input().split()] arr.sort() c = 0 for i in range(2): if arr[i]==arr[i+1]: c += 1 print(c) ``` No
11,065
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades. Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party. Input The first line contains four space-separated integers s1, s2, s3, s4 (1 ≀ s1, s2, s3, s4 ≀ 109) β€” the colors of horseshoes Valera has. Consider all possible colors indexed with integers. Output Print a single integer β€” the minimum number of horseshoes Valera needs to buy. Examples Input 1 7 3 3 Output 1 Input 7 7 7 7 Output 3 Submitted Solution: ``` l = list(map(int,input().split())) rs = 0 for i in range(len(l)): if l.count(l[i]) > rs: rs = l.count(l[i]) print(rs-1) ``` No
11,066
Provide tags and a correct Python 3 solution for this coding contest problem. Little Petya likes numbers a lot. Recently his mother has presented him a collection of n non-negative integers. There's only one thing Petya likes more than numbers: playing with little Masha. He immediately decided to give a part of his new collection to her. To make the game even more interesting, Petya decided to give Masha such collection of numbers for which the following conditions fulfill: * Let's introduce x1 to denote the xor of all numbers Petya has got left; and let's introduce x2 to denote the xor of all numbers he gave to Masha. Value (x1 + x2) must be as large as possible. * If there are multiple ways to divide the collection so that the previous condition fulfilled, then Petya minimizes the value x1. The xor operation is a bitwise excluding "OR", that is denoted as "xor" in the Pascal language and "^" in C/C++/Java. Help Petya divide the collection as described above. If there are multiple suitable ways to divide it, find any of them. Please note that after Petya gives a part of his numbers to Masha, he may have no numbers left. The reverse situation is also possible, when Petya gives nothing to Masha. In both cases we must assume that the xor of an empty set of numbers equals 0. Input The first line contains integer n (1 ≀ n ≀ 105), showing how many numbers Petya's mother gave him. The second line contains the actual space-separated numbers. They are all integer, non-negative and do not exceed 1018. Output Print n space-separated integers, the i-th of them should equal either 1, if Petya keeps the number that follows i-th in his collection, or it should equal 2, if Petya gives the corresponding number to Masha. The numbers are indexed in the order in which they are given in the input. Examples Input 6 1 2 3 4 5 6 Output 2 2 2 2 2 2 Input 3 1000000000000 1000000000000 1000000000000 Output 2 2 2 Input 8 1 1 2 2 3 3 4 4 Output 1 2 1 2 2 2 1 2 Tags: bitmasks, math Correct Solution: ``` base = [-1] * 60 how = [-1] * 60 who = [-1] * 60 n = int(input()) arr = list(map(int, input().split())) x = 0 for a in arr: x ^= a mapper = [-1] * 60 ind = 59 ind_start = bin(x).count('1') - 1 for bit in reversed(range(60)): if (1 << bit) & x : mapper[bit] = ind_start ind_start -= 1 else: mapper[bit] = ind ind -= 1 for i in range(len(arr)): temp = 0 for bit in range(60): if (1 << bit) & arr[i]: temp ^= (1 << mapper[bit]) arr[i] = temp for i in range(n): x = arr[i] temp_how = 0 while x > 0: b = x.bit_length() - 1 if who[b]!= -1: temp_how ^= how[b] x = x ^ base[b] else: who[b] = i base[b] = x how[b] = temp_how | (1 << b) break x = 0 temp = 0 for bit in reversed(range(60)): if (x & (1 << bit) ) == 0 and who[bit] != -1: x ^= base[bit] temp ^= how[bit] #print(base) #print(how) #print(who) result = [1] * n for j in range(60): if temp & (1 << j): result[who[j]] = 2 print(*result) ```
11,067
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little Petya likes numbers a lot. Recently his mother has presented him a collection of n non-negative integers. There's only one thing Petya likes more than numbers: playing with little Masha. He immediately decided to give a part of his new collection to her. To make the game even more interesting, Petya decided to give Masha such collection of numbers for which the following conditions fulfill: * Let's introduce x1 to denote the xor of all numbers Petya has got left; and let's introduce x2 to denote the xor of all numbers he gave to Masha. Value (x1 + x2) must be as large as possible. * If there are multiple ways to divide the collection so that the previous condition fulfilled, then Petya minimizes the value x1. The xor operation is a bitwise excluding "OR", that is denoted as "xor" in the Pascal language and "^" in C/C++/Java. Help Petya divide the collection as described above. If there are multiple suitable ways to divide it, find any of them. Please note that after Petya gives a part of his numbers to Masha, he may have no numbers left. The reverse situation is also possible, when Petya gives nothing to Masha. In both cases we must assume that the xor of an empty set of numbers equals 0. Input The first line contains integer n (1 ≀ n ≀ 105), showing how many numbers Petya's mother gave him. The second line contains the actual space-separated numbers. They are all integer, non-negative and do not exceed 1018. Output Print n space-separated integers, the i-th of them should equal either 1, if Petya keeps the number that follows i-th in his collection, or it should equal 2, if Petya gives the corresponding number to Masha. The numbers are indexed in the order in which they are given in the input. Examples Input 6 1 2 3 4 5 6 Output 2 2 2 2 2 2 Input 3 1000000000000 1000000000000 1000000000000 Output 2 2 2 Input 8 1 1 2 2 3 3 4 4 Output 1 2 1 2 2 2 1 2 Submitted Solution: ``` n = int(input()) arr = list(map(int, input().split())) for i in range(n): arr[i] = (arr[i], i) basis = [] who_give = [0] * 60 done = 0 for bit in reversed(range(60)): if len(arr) == 0: break m = max(arr) if m[0].bit_length() - 1 != bit: continue for x in range(bit+1): if 1 << x & m[0]: who_give[x] = m[1] arr.remove(m) basis.append(m) for i in range(len(arr)): if m[0].bit_length() == arr[i][0].bit_length(): arr[i] = (arr[i][0] ^ m[0], arr[i][1]) result = [1] * n selected = 0 chosen = {} for bit in reversed(range(60)): if (1 << bit) & selected: continue m = (0, -1) for b in basis: if b[1] in chosen: continue if b[0].bit_length() - 1 == bit: m = max(m, b) if m[1] == -1: continue selected = selected ^ m[0] chosen[m[1]] = 1 for bit in reversed(range(60)): if (1 << bit) & selected: result[who_give[bit]] = 2 print(*result) ``` No
11,068
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little Petya likes numbers a lot. Recently his mother has presented him a collection of n non-negative integers. There's only one thing Petya likes more than numbers: playing with little Masha. He immediately decided to give a part of his new collection to her. To make the game even more interesting, Petya decided to give Masha such collection of numbers for which the following conditions fulfill: * Let's introduce x1 to denote the xor of all numbers Petya has got left; and let's introduce x2 to denote the xor of all numbers he gave to Masha. Value (x1 + x2) must be as large as possible. * If there are multiple ways to divide the collection so that the previous condition fulfilled, then Petya minimizes the value x1. The xor operation is a bitwise excluding "OR", that is denoted as "xor" in the Pascal language and "^" in C/C++/Java. Help Petya divide the collection as described above. If there are multiple suitable ways to divide it, find any of them. Please note that after Petya gives a part of his numbers to Masha, he may have no numbers left. The reverse situation is also possible, when Petya gives nothing to Masha. In both cases we must assume that the xor of an empty set of numbers equals 0. Input The first line contains integer n (1 ≀ n ≀ 105), showing how many numbers Petya's mother gave him. The second line contains the actual space-separated numbers. They are all integer, non-negative and do not exceed 1018. Output Print n space-separated integers, the i-th of them should equal either 1, if Petya keeps the number that follows i-th in his collection, or it should equal 2, if Petya gives the corresponding number to Masha. The numbers are indexed in the order in which they are given in the input. Examples Input 6 1 2 3 4 5 6 Output 2 2 2 2 2 2 Input 3 1000000000000 1000000000000 1000000000000 Output 2 2 2 Input 8 1 1 2 2 3 3 4 4 Output 1 2 1 2 2 2 1 2 Submitted Solution: ``` n = int(input()) arr = list(map(int, input().split())) for i in range(n): arr[i] = (arr[i], i) basis = [] who_give = [-1] * 60 done = 0 for bit in reversed(range(60)): if who_give[bit] != -1: continue if len(arr) == 0: break m = max(arr) if m[0].bit_length() - 1 != bit: continue for x in range(bit+1): if 1 << x & m[0]: who_give[x] = m[1] arr.remove(m) basis.append(m) for i in range(len(arr)): if m[0].bit_length() == arr[i][0].bit_length(): arr[i] = (arr[i][0] ^ m[0], arr[i][1]) result = [1] * n selected = 0 chosen = {} for bit in reversed(range(60)): if (1 << bit) & selected: continue m = (0, -1) for b in basis: if b[1] in chosen: continue if b[0].bit_length() - 1 == bit: m = max(m, b) if m[1] == -1: continue selected = selected ^ m[0] chosen[m[1]] = 1 for bit in reversed(range(60)): if (1 << bit) & selected: result[who_give[bit]] = 2 print(*result) ``` No
11,069
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little Petya likes numbers a lot. Recently his mother has presented him a collection of n non-negative integers. There's only one thing Petya likes more than numbers: playing with little Masha. He immediately decided to give a part of his new collection to her. To make the game even more interesting, Petya decided to give Masha such collection of numbers for which the following conditions fulfill: * Let's introduce x1 to denote the xor of all numbers Petya has got left; and let's introduce x2 to denote the xor of all numbers he gave to Masha. Value (x1 + x2) must be as large as possible. * If there are multiple ways to divide the collection so that the previous condition fulfilled, then Petya minimizes the value x1. The xor operation is a bitwise excluding "OR", that is denoted as "xor" in the Pascal language and "^" in C/C++/Java. Help Petya divide the collection as described above. If there are multiple suitable ways to divide it, find any of them. Please note that after Petya gives a part of his numbers to Masha, he may have no numbers left. The reverse situation is also possible, when Petya gives nothing to Masha. In both cases we must assume that the xor of an empty set of numbers equals 0. Input The first line contains integer n (1 ≀ n ≀ 105), showing how many numbers Petya's mother gave him. The second line contains the actual space-separated numbers. They are all integer, non-negative and do not exceed 1018. Output Print n space-separated integers, the i-th of them should equal either 1, if Petya keeps the number that follows i-th in his collection, or it should equal 2, if Petya gives the corresponding number to Masha. The numbers are indexed in the order in which they are given in the input. Examples Input 6 1 2 3 4 5 6 Output 2 2 2 2 2 2 Input 3 1000000000000 1000000000000 1000000000000 Output 2 2 2 Input 8 1 1 2 2 3 3 4 4 Output 1 2 1 2 2 2 1 2 Submitted Solution: ``` n = int(input()) arr = list(map(int, input().split())) for i in range(n): arr[i] = (arr[i], i) basis = [] for bit in reversed(range(60)): m = max(arr) if m[0].bit_length() - 1 != bit: continue arr.remove(m) basis.append(m) for i in range(len(arr)): if m[0].bit_length() == arr[i][0].bit_length(): arr[i] = (arr[i][0] ^ m[0], arr[i][1]) result = [1] * n selected = 0 chosen = {} for bit in reversed(range(60)): if (1 << bit) & selected: continue m = (0, -1) for b in basis: if b[1] in chosen: continue if (b[0] & (1 << bit)): m = max(m, b) if m[1] == -1: continue selected = selected ^ m[0] chosen[m[1]] = 1 result[m[1]] = 2 print(*result) ``` No
11,070
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little Petya likes numbers a lot. Recently his mother has presented him a collection of n non-negative integers. There's only one thing Petya likes more than numbers: playing with little Masha. He immediately decided to give a part of his new collection to her. To make the game even more interesting, Petya decided to give Masha such collection of numbers for which the following conditions fulfill: * Let's introduce x1 to denote the xor of all numbers Petya has got left; and let's introduce x2 to denote the xor of all numbers he gave to Masha. Value (x1 + x2) must be as large as possible. * If there are multiple ways to divide the collection so that the previous condition fulfilled, then Petya minimizes the value x1. The xor operation is a bitwise excluding "OR", that is denoted as "xor" in the Pascal language and "^" in C/C++/Java. Help Petya divide the collection as described above. If there are multiple suitable ways to divide it, find any of them. Please note that after Petya gives a part of his numbers to Masha, he may have no numbers left. The reverse situation is also possible, when Petya gives nothing to Masha. In both cases we must assume that the xor of an empty set of numbers equals 0. Input The first line contains integer n (1 ≀ n ≀ 105), showing how many numbers Petya's mother gave him. The second line contains the actual space-separated numbers. They are all integer, non-negative and do not exceed 1018. Output Print n space-separated integers, the i-th of them should equal either 1, if Petya keeps the number that follows i-th in his collection, or it should equal 2, if Petya gives the corresponding number to Masha. The numbers are indexed in the order in which they are given in the input. Examples Input 6 1 2 3 4 5 6 Output 2 2 2 2 2 2 Input 3 1000000000000 1000000000000 1000000000000 Output 2 2 2 Input 8 1 1 2 2 3 3 4 4 Output 1 2 1 2 2 2 1 2 Submitted Solution: ``` n = int(input()) arr = list(map(int, input().split())) basis = [] who_give = [-1] * 60 done = 0 for i in range(n): b = 0 while arr[i]: bit = arr[i].bit_length() - 1 if 1 << bit & done: arr[i] ^= 1 << bit else: b ^= 1 << bit who_give[bit] = i done ^= 1 << bit arr[i] ^= 1 << bit if b: basis.append(b) result = [1] * n selected = 0 chosen = {} for x in basis: selected ^= x for bit in reversed(range(60)): if (1 << bit) & selected: result[who_give[bit]] = 2 print(*result) ``` No
11,071
Provide tags and a correct Python 3 solution for this coding contest problem. A car moves from point A to point B at speed v meters per second. The action takes place on the X-axis. At the distance d meters from A there are traffic lights. Starting from time 0, for the first g seconds the green light is on, then for the following r seconds the red light is on, then again the green light is on for the g seconds, and so on. The car can be instantly accelerated from 0 to v and vice versa, can instantly slow down from the v to 0. Consider that it passes the traffic lights at the green light instantly. If the car approaches the traffic lights at the moment when the red light has just turned on, it doesn't have time to pass it. But if it approaches the traffic lights at the moment when the green light has just turned on, it can move. The car leaves point A at the time 0. What is the minimum time for the car to get from point A to point B without breaking the traffic rules? Input The first line contains integers l, d, v, g, r (1 ≀ l, d, v, g, r ≀ 1000, d < l) β€” the distance between A and B (in meters), the distance from A to the traffic lights, car's speed, the duration of green light and the duration of red light. Output Output a single number β€” the minimum time that the car needs to get from point A to point B. Your output must have relative or absolute error less than 10 - 6. Examples Input 2 1 3 4 5 Output 0.66666667 Input 5 4 3 1 1 Output 2.33333333 Tags: implementation Correct Solution: ``` """ def cf31B(): #print("Hello World") from sys import stdin,stdout inp = list(stdin.readline().strip().split('@')) flag = True if len(inp)>=2: if len(inp[0])==0 or len(inp[-1])==0: flag = False if flag: for i in range(1,len(inp)-1): if len(inp[i]) < 2: flag = False break else: flag = False answer = "" if flag: for i , j in enumerate(inp): if i==0: answer+=j elif i==len(inp)-1: answer+='@'+j else: answer+='@'+j[:-1]+','+j[-1] else: answer = "No solution" stdout.write(answer+"\n") def cf75B(): from sys import stdin, stdout myname = stdin.readline().strip() points = {} for _ in range(int(stdin.readline())): inp = stdin.readline().strip().split() a = inp[0] b = inp[-2][:-2] p = 0 if inp[1][0] == 'p': p=15 elif inp[1][0] == 'c': p=10 else: p = 5 if a==myname: if b in points: points[b] += p else: points[b] = p elif b==myname: if a in points: points[a] += p else: points[a] = p else: if a not in points: points[a] = 0 if b not in points: points[b] = 0 revpoints = {} mylist = [] for key in points: if points[key] in revpoints: revpoints[points[key]].append(key) else: revpoints[points[key]]=[key,] for key in revpoints: revpoints[key].sort() for key in revpoints: mylist.append((key,revpoints[key])) mylist.sort(reverse=True) for i,j in enumerate(mylist): for name in j[1]: stdout.write(name+'\n') def cf340B(): from sys import stdin, stdout maxim = -1e9 permutation = [] chosen = [False for x in range(300)] def search(): if len(permutation)==4: maxim = max(maxim,calculate_area(permutation)) else: for i in range(len(colist)): if chosen[i]: continue chosen[i]=True permutation.append(colist[i]) search() chosen[i]=False permutation = permutation[:-1] def calculate_area(arr): others = [] leftmost = arr[0] rightmost = arr[0] for i in arr: if i[0]<leftmost[0]: leftmost = i elif i[0]>rightmost[0]: rightmost = i for i in arr: if i!=leftmost and i!=rightmost: others.append(i) base_length = ((leftmost[0]-rightmost[0])**2 + (leftmost[1]-rightmost[1])**2)**0.5 #print(base_length) if base_length == 0: return 0 m = (rightmost[1] - leftmost[1])/(rightmost[0]-leftmost[0]) k = leftmost[1] + (-1)*leftmost[0]*m #print(m) #print(k) t1 = abs(k+m*others[0][0]-others[0][1])/((1+m*m)**0.5)*base_length*0.5 t2 = abs(k+m*others[1][0]-others[1][1])/((1+m*m)**0.5)*base_length*0.5 #print(t1) #print(t2) return t1+t2 colist = [] for _ in range(int(stdin.readline())): x,y = map(int,stdin.readline().split()) colist.append((x,y)) #print(colist) #ans = calculate_area((0,0),(0,4),(4,0),(4,4)) #print(ans) search() stdout.write(str(maxim)+'\n') """ def cf29B(): from sys import stdin,stdout l,d,v,g,r=map(int,stdin.readline().split()) t=0 t+=d/v cycle=g+r rem = t while rem > cycle: rem -= cycle if rem >= g: rem -=g t+=(r-rem) t+=(l-d)/v stdout.write("{0:.6f}\n".format(t)) if __name__=='__main__': cf29B() ```
11,072
Provide tags and a correct Python 3 solution for this coding contest problem. A car moves from point A to point B at speed v meters per second. The action takes place on the X-axis. At the distance d meters from A there are traffic lights. Starting from time 0, for the first g seconds the green light is on, then for the following r seconds the red light is on, then again the green light is on for the g seconds, and so on. The car can be instantly accelerated from 0 to v and vice versa, can instantly slow down from the v to 0. Consider that it passes the traffic lights at the green light instantly. If the car approaches the traffic lights at the moment when the red light has just turned on, it doesn't have time to pass it. But if it approaches the traffic lights at the moment when the green light has just turned on, it can move. The car leaves point A at the time 0. What is the minimum time for the car to get from point A to point B without breaking the traffic rules? Input The first line contains integers l, d, v, g, r (1 ≀ l, d, v, g, r ≀ 1000, d < l) β€” the distance between A and B (in meters), the distance from A to the traffic lights, car's speed, the duration of green light and the duration of red light. Output Output a single number β€” the minimum time that the car needs to get from point A to point B. Your output must have relative or absolute error less than 10 - 6. Examples Input 2 1 3 4 5 Output 0.66666667 Input 5 4 3 1 1 Output 2.33333333 Tags: implementation Correct Solution: ``` import sys def input(): return sys.stdin.readline().strip() def iinput(): return int(input()) def rinput(): return map(int, sys.stdin.readline().strip().split()) def get_list(): return list(map(int, sys.stdin.readline().strip().split())) mod = int(1e9)+7 l, d, v, g, r = rinput() time = (d/v)%(g+r) ans = l/v if time<g: print(ans) else: ans += r + g - time print(ans) ```
11,073
Provide tags and a correct Python 3 solution for this coding contest problem. A car moves from point A to point B at speed v meters per second. The action takes place on the X-axis. At the distance d meters from A there are traffic lights. Starting from time 0, for the first g seconds the green light is on, then for the following r seconds the red light is on, then again the green light is on for the g seconds, and so on. The car can be instantly accelerated from 0 to v and vice versa, can instantly slow down from the v to 0. Consider that it passes the traffic lights at the green light instantly. If the car approaches the traffic lights at the moment when the red light has just turned on, it doesn't have time to pass it. But if it approaches the traffic lights at the moment when the green light has just turned on, it can move. The car leaves point A at the time 0. What is the minimum time for the car to get from point A to point B without breaking the traffic rules? Input The first line contains integers l, d, v, g, r (1 ≀ l, d, v, g, r ≀ 1000, d < l) β€” the distance between A and B (in meters), the distance from A to the traffic lights, car's speed, the duration of green light and the duration of red light. Output Output a single number β€” the minimum time that the car needs to get from point A to point B. Your output must have relative or absolute error less than 10 - 6. Examples Input 2 1 3 4 5 Output 0.66666667 Input 5 4 3 1 1 Output 2.33333333 Tags: implementation Correct Solution: ``` l,d,v,g,r=map(int,input().split()) t=d/v c=0 i1=0 i2=g while(not(i1<=t and i2>=t)): c+=1 if(c%2!=0): i1=i2 i2=i2+r else: i1=i2 i2=i2+g if(i1==t or i2==t): c+=1 if(c%2!=0 and (i1==t or i2==t)): t=i2+r elif(c%2!=0): t=i2 t+=(l-d)/v print(t) ```
11,074
Provide tags and a correct Python 3 solution for this coding contest problem. A car moves from point A to point B at speed v meters per second. The action takes place on the X-axis. At the distance d meters from A there are traffic lights. Starting from time 0, for the first g seconds the green light is on, then for the following r seconds the red light is on, then again the green light is on for the g seconds, and so on. The car can be instantly accelerated from 0 to v and vice versa, can instantly slow down from the v to 0. Consider that it passes the traffic lights at the green light instantly. If the car approaches the traffic lights at the moment when the red light has just turned on, it doesn't have time to pass it. But if it approaches the traffic lights at the moment when the green light has just turned on, it can move. The car leaves point A at the time 0. What is the minimum time for the car to get from point A to point B without breaking the traffic rules? Input The first line contains integers l, d, v, g, r (1 ≀ l, d, v, g, r ≀ 1000, d < l) β€” the distance between A and B (in meters), the distance from A to the traffic lights, car's speed, the duration of green light and the duration of red light. Output Output a single number β€” the minimum time that the car needs to get from point A to point B. Your output must have relative or absolute error less than 10 - 6. Examples Input 2 1 3 4 5 Output 0.66666667 Input 5 4 3 1 1 Output 2.33333333 Tags: implementation Correct Solution: ``` l, d, v, g, r = map(int, input().split()) t = d/v ft = t%(g+r) if ft >= g: t += r-(ft-g) t += (l-d)/v print(t) ```
11,075
Provide tags and a correct Python 3 solution for this coding contest problem. A car moves from point A to point B at speed v meters per second. The action takes place on the X-axis. At the distance d meters from A there are traffic lights. Starting from time 0, for the first g seconds the green light is on, then for the following r seconds the red light is on, then again the green light is on for the g seconds, and so on. The car can be instantly accelerated from 0 to v and vice versa, can instantly slow down from the v to 0. Consider that it passes the traffic lights at the green light instantly. If the car approaches the traffic lights at the moment when the red light has just turned on, it doesn't have time to pass it. But if it approaches the traffic lights at the moment when the green light has just turned on, it can move. The car leaves point A at the time 0. What is the minimum time for the car to get from point A to point B without breaking the traffic rules? Input The first line contains integers l, d, v, g, r (1 ≀ l, d, v, g, r ≀ 1000, d < l) β€” the distance between A and B (in meters), the distance from A to the traffic lights, car's speed, the duration of green light and the duration of red light. Output Output a single number β€” the minimum time that the car needs to get from point A to point B. Your output must have relative or absolute error less than 10 - 6. Examples Input 2 1 3 4 5 Output 0.66666667 Input 5 4 3 1 1 Output 2.33333333 Tags: implementation Correct Solution: ``` # n=int(input()) l,d,v,g,r=map(int,input().split()) z=d/v y=(l-d)/v temp=z light=True x=0 # print(z,y) while(1): if(x%2==0): if(temp>=g): temp-=g light=False else: break else: if(temp>=r): temp-=r light=True else: break x+=1 if(light): print("{0:.8f}".format(z+y)) else: print("{0:.8f}".format(z+(r-temp)+y)) ```
11,076
Provide tags and a correct Python 3 solution for this coding contest problem. A car moves from point A to point B at speed v meters per second. The action takes place on the X-axis. At the distance d meters from A there are traffic lights. Starting from time 0, for the first g seconds the green light is on, then for the following r seconds the red light is on, then again the green light is on for the g seconds, and so on. The car can be instantly accelerated from 0 to v and vice versa, can instantly slow down from the v to 0. Consider that it passes the traffic lights at the green light instantly. If the car approaches the traffic lights at the moment when the red light has just turned on, it doesn't have time to pass it. But if it approaches the traffic lights at the moment when the green light has just turned on, it can move. The car leaves point A at the time 0. What is the minimum time for the car to get from point A to point B without breaking the traffic rules? Input The first line contains integers l, d, v, g, r (1 ≀ l, d, v, g, r ≀ 1000, d < l) β€” the distance between A and B (in meters), the distance from A to the traffic lights, car's speed, the duration of green light and the duration of red light. Output Output a single number β€” the minimum time that the car needs to get from point A to point B. Your output must have relative or absolute error less than 10 - 6. Examples Input 2 1 3 4 5 Output 0.66666667 Input 5 4 3 1 1 Output 2.33333333 Tags: implementation Correct Solution: ``` l,d,v,g,r=list(map(int,input().split())) t1=(d/v)%(g+r)-g if t1<0: print(l/v) else: print(l/v+r-t1) ```
11,077
Provide tags and a correct Python 3 solution for this coding contest problem. A car moves from point A to point B at speed v meters per second. The action takes place on the X-axis. At the distance d meters from A there are traffic lights. Starting from time 0, for the first g seconds the green light is on, then for the following r seconds the red light is on, then again the green light is on for the g seconds, and so on. The car can be instantly accelerated from 0 to v and vice versa, can instantly slow down from the v to 0. Consider that it passes the traffic lights at the green light instantly. If the car approaches the traffic lights at the moment when the red light has just turned on, it doesn't have time to pass it. But if it approaches the traffic lights at the moment when the green light has just turned on, it can move. The car leaves point A at the time 0. What is the minimum time for the car to get from point A to point B without breaking the traffic rules? Input The first line contains integers l, d, v, g, r (1 ≀ l, d, v, g, r ≀ 1000, d < l) β€” the distance between A and B (in meters), the distance from A to the traffic lights, car's speed, the duration of green light and the duration of red light. Output Output a single number β€” the minimum time that the car needs to get from point A to point B. Your output must have relative or absolute error less than 10 - 6. Examples Input 2 1 3 4 5 Output 0.66666667 Input 5 4 3 1 1 Output 2.33333333 Tags: implementation Correct Solution: ``` l, d, v, g, r = map(int, input().split()) x = (d / v) % (g + r) if x < g: print(l / v) else: print(d / v + abs(x - (g + r)) + ((l - d) / v)) ```
11,078
Provide tags and a correct Python 3 solution for this coding contest problem. A car moves from point A to point B at speed v meters per second. The action takes place on the X-axis. At the distance d meters from A there are traffic lights. Starting from time 0, for the first g seconds the green light is on, then for the following r seconds the red light is on, then again the green light is on for the g seconds, and so on. The car can be instantly accelerated from 0 to v and vice versa, can instantly slow down from the v to 0. Consider that it passes the traffic lights at the green light instantly. If the car approaches the traffic lights at the moment when the red light has just turned on, it doesn't have time to pass it. But if it approaches the traffic lights at the moment when the green light has just turned on, it can move. The car leaves point A at the time 0. What is the minimum time for the car to get from point A to point B without breaking the traffic rules? Input The first line contains integers l, d, v, g, r (1 ≀ l, d, v, g, r ≀ 1000, d < l) β€” the distance between A and B (in meters), the distance from A to the traffic lights, car's speed, the duration of green light and the duration of red light. Output Output a single number β€” the minimum time that the car needs to get from point A to point B. Your output must have relative or absolute error less than 10 - 6. Examples Input 2 1 3 4 5 Output 0.66666667 Input 5 4 3 1 1 Output 2.33333333 Tags: implementation Correct Solution: ``` l,d,v,g,r=map(int,input().split()) t=l/v test = d/v n=0 while test >= 0: if n%2 == 0: test -= g else: test -= r n+=1 if n%2==0: t+=abs(test) print(t) ```
11,079
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A car moves from point A to point B at speed v meters per second. The action takes place on the X-axis. At the distance d meters from A there are traffic lights. Starting from time 0, for the first g seconds the green light is on, then for the following r seconds the red light is on, then again the green light is on for the g seconds, and so on. The car can be instantly accelerated from 0 to v and vice versa, can instantly slow down from the v to 0. Consider that it passes the traffic lights at the green light instantly. If the car approaches the traffic lights at the moment when the red light has just turned on, it doesn't have time to pass it. But if it approaches the traffic lights at the moment when the green light has just turned on, it can move. The car leaves point A at the time 0. What is the minimum time for the car to get from point A to point B without breaking the traffic rules? Input The first line contains integers l, d, v, g, r (1 ≀ l, d, v, g, r ≀ 1000, d < l) β€” the distance between A and B (in meters), the distance from A to the traffic lights, car's speed, the duration of green light and the duration of red light. Output Output a single number β€” the minimum time that the car needs to get from point A to point B. Your output must have relative or absolute error less than 10 - 6. Examples Input 2 1 3 4 5 Output 0.66666667 Input 5 4 3 1 1 Output 2.33333333 Submitted Solution: ``` l, d, v, g, r = map(int, input().split()) b = d / v t = b % (g + r) if t < g: print(b + (l - d) / v) else: print(b - t + g + r + (l - d) / v) ``` Yes
11,080
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A car moves from point A to point B at speed v meters per second. The action takes place on the X-axis. At the distance d meters from A there are traffic lights. Starting from time 0, for the first g seconds the green light is on, then for the following r seconds the red light is on, then again the green light is on for the g seconds, and so on. The car can be instantly accelerated from 0 to v and vice versa, can instantly slow down from the v to 0. Consider that it passes the traffic lights at the green light instantly. If the car approaches the traffic lights at the moment when the red light has just turned on, it doesn't have time to pass it. But if it approaches the traffic lights at the moment when the green light has just turned on, it can move. The car leaves point A at the time 0. What is the minimum time for the car to get from point A to point B without breaking the traffic rules? Input The first line contains integers l, d, v, g, r (1 ≀ l, d, v, g, r ≀ 1000, d < l) β€” the distance between A and B (in meters), the distance from A to the traffic lights, car's speed, the duration of green light and the duration of red light. Output Output a single number β€” the minimum time that the car needs to get from point A to point B. Your output must have relative or absolute error less than 10 - 6. Examples Input 2 1 3 4 5 Output 0.66666667 Input 5 4 3 1 1 Output 2.33333333 Submitted Solution: ``` def solve(): l, d, v, g, r = [int(x) for x in input().split(' ')] #Get to Traffic Lights t = d / v #Stop at lights if necessary x = t % (g + r) if x >= g: t += (g + r) - x #Continue to complete journey t += (l - d) / v #Return total time return t print(solve()) ``` Yes
11,081
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A car moves from point A to point B at speed v meters per second. The action takes place on the X-axis. At the distance d meters from A there are traffic lights. Starting from time 0, for the first g seconds the green light is on, then for the following r seconds the red light is on, then again the green light is on for the g seconds, and so on. The car can be instantly accelerated from 0 to v and vice versa, can instantly slow down from the v to 0. Consider that it passes the traffic lights at the green light instantly. If the car approaches the traffic lights at the moment when the red light has just turned on, it doesn't have time to pass it. But if it approaches the traffic lights at the moment when the green light has just turned on, it can move. The car leaves point A at the time 0. What is the minimum time for the car to get from point A to point B without breaking the traffic rules? Input The first line contains integers l, d, v, g, r (1 ≀ l, d, v, g, r ≀ 1000, d < l) β€” the distance between A and B (in meters), the distance from A to the traffic lights, car's speed, the duration of green light and the duration of red light. Output Output a single number β€” the minimum time that the car needs to get from point A to point B. Your output must have relative or absolute error less than 10 - 6. Examples Input 2 1 3 4 5 Output 0.66666667 Input 5 4 3 1 1 Output 2.33333333 Submitted Solution: ``` dist, toLight, maxSpeed, green, red = map(int, input().split()) f = toLight // maxSpeed t = 0 for i in range(1010): if i % 2 == 0: if t <= f < t + green: print(toLight * 1.0 / maxSpeed + (dist - toLight) * 1.0 / maxSpeed) break t += green else: if t <= f < t + red: tm = toLight * 1.0 / maxSpeed print(t + red + (dist - toLight) * 1.0 / maxSpeed) break t += red ``` Yes
11,082
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A car moves from point A to point B at speed v meters per second. The action takes place on the X-axis. At the distance d meters from A there are traffic lights. Starting from time 0, for the first g seconds the green light is on, then for the following r seconds the red light is on, then again the green light is on for the g seconds, and so on. The car can be instantly accelerated from 0 to v and vice versa, can instantly slow down from the v to 0. Consider that it passes the traffic lights at the green light instantly. If the car approaches the traffic lights at the moment when the red light has just turned on, it doesn't have time to pass it. But if it approaches the traffic lights at the moment when the green light has just turned on, it can move. The car leaves point A at the time 0. What is the minimum time for the car to get from point A to point B without breaking the traffic rules? Input The first line contains integers l, d, v, g, r (1 ≀ l, d, v, g, r ≀ 1000, d < l) β€” the distance between A and B (in meters), the distance from A to the traffic lights, car's speed, the duration of green light and the duration of red light. Output Output a single number β€” the minimum time that the car needs to get from point A to point B. Your output must have relative or absolute error less than 10 - 6. Examples Input 2 1 3 4 5 Output 0.66666667 Input 5 4 3 1 1 Output 2.33333333 Submitted Solution: ``` dt,pd,sp,g,r = map(int,input().split()) it = pd/sp if(it<g): ntt = dt/sp print("%.8f" %ntt ) elif it>(g+r): tr = it+(g+r) if(it%(g+r)):print("%.8f"%tr) else: nt = r+g+((dt-pd)/sp) print("%.8f" % nt) ``` Yes
11,083
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A car moves from point A to point B at speed v meters per second. The action takes place on the X-axis. At the distance d meters from A there are traffic lights. Starting from time 0, for the first g seconds the green light is on, then for the following r seconds the red light is on, then again the green light is on for the g seconds, and so on. The car can be instantly accelerated from 0 to v and vice versa, can instantly slow down from the v to 0. Consider that it passes the traffic lights at the green light instantly. If the car approaches the traffic lights at the moment when the red light has just turned on, it doesn't have time to pass it. But if it approaches the traffic lights at the moment when the green light has just turned on, it can move. The car leaves point A at the time 0. What is the minimum time for the car to get from point A to point B without breaking the traffic rules? Input The first line contains integers l, d, v, g, r (1 ≀ l, d, v, g, r ≀ 1000, d < l) β€” the distance between A and B (in meters), the distance from A to the traffic lights, car's speed, the duration of green light and the duration of red light. Output Output a single number β€” the minimum time that the car needs to get from point A to point B. Your output must have relative or absolute error less than 10 - 6. Examples Input 2 1 3 4 5 Output 0.66666667 Input 5 4 3 1 1 Output 2.33333333 Submitted Solution: ``` #l distance A to B #d distance A to traffic light #v car speed #g duration of green light #r duration of red light sets=[int(e) for e in input().split()] l=sets[0] d=sets[1] v=sets[2] g=sets[3] r=sets[4] timebeforelight=d/v restofdistance=l-d totaltime=0 if timebeforelight>=g: totaltime=totaltime+timebeforelight+r elif timebeforelight<g: totaltime=totaltime+timebeforelight print('%.8f'%totaltime) ``` No
11,084
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A car moves from point A to point B at speed v meters per second. The action takes place on the X-axis. At the distance d meters from A there are traffic lights. Starting from time 0, for the first g seconds the green light is on, then for the following r seconds the red light is on, then again the green light is on for the g seconds, and so on. The car can be instantly accelerated from 0 to v and vice versa, can instantly slow down from the v to 0. Consider that it passes the traffic lights at the green light instantly. If the car approaches the traffic lights at the moment when the red light has just turned on, it doesn't have time to pass it. But if it approaches the traffic lights at the moment when the green light has just turned on, it can move. The car leaves point A at the time 0. What is the minimum time for the car to get from point A to point B without breaking the traffic rules? Input The first line contains integers l, d, v, g, r (1 ≀ l, d, v, g, r ≀ 1000, d < l) β€” the distance between A and B (in meters), the distance from A to the traffic lights, car's speed, the duration of green light and the duration of red light. Output Output a single number β€” the minimum time that the car needs to get from point A to point B. Your output must have relative or absolute error less than 10 - 6. Examples Input 2 1 3 4 5 Output 0.66666667 Input 5 4 3 1 1 Output 2.33333333 Submitted Solution: ``` def gcd(a, b): if b == 0: return a return gcd(b, a % b) dist, toLight, maxSpeed, green, red = map(int, input().split()) g = gcd(toLight, maxSpeed) toLight //= g maxSpeed //= g f = dist // maxSpeed t = 0 for i in range(1010): if i % 2 == 0: if t <= f < t + green: print(toLight * 1.0 / maxSpeed + (dist - toLight) * 1.0 / maxSpeed) break t += green else: if t <= f < t + red: tm = toLight * 1.0 / maxSpeed print(t + red + (dist - toLight) * 1.0 / maxSpeed) break t += red ``` No
11,085
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A car moves from point A to point B at speed v meters per second. The action takes place on the X-axis. At the distance d meters from A there are traffic lights. Starting from time 0, for the first g seconds the green light is on, then for the following r seconds the red light is on, then again the green light is on for the g seconds, and so on. The car can be instantly accelerated from 0 to v and vice versa, can instantly slow down from the v to 0. Consider that it passes the traffic lights at the green light instantly. If the car approaches the traffic lights at the moment when the red light has just turned on, it doesn't have time to pass it. But if it approaches the traffic lights at the moment when the green light has just turned on, it can move. The car leaves point A at the time 0. What is the minimum time for the car to get from point A to point B without breaking the traffic rules? Input The first line contains integers l, d, v, g, r (1 ≀ l, d, v, g, r ≀ 1000, d < l) β€” the distance between A and B (in meters), the distance from A to the traffic lights, car's speed, the duration of green light and the duration of red light. Output Output a single number β€” the minimum time that the car needs to get from point A to point B. Your output must have relative or absolute error less than 10 - 6. Examples Input 2 1 3 4 5 Output 0.66666667 Input 5 4 3 1 1 Output 2.33333333 Submitted Solution: ``` l,d,v,g,r=map(int,input().split()) t=d/v y=t%(g+r) if y<=g and y!=0: wt=0 if y==0: wt+=1 else: wt=g+r-y tt=t+wt+(l-d)/v print(tt) ``` No
11,086
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A car moves from point A to point B at speed v meters per second. The action takes place on the X-axis. At the distance d meters from A there are traffic lights. Starting from time 0, for the first g seconds the green light is on, then for the following r seconds the red light is on, then again the green light is on for the g seconds, and so on. The car can be instantly accelerated from 0 to v and vice versa, can instantly slow down from the v to 0. Consider that it passes the traffic lights at the green light instantly. If the car approaches the traffic lights at the moment when the red light has just turned on, it doesn't have time to pass it. But if it approaches the traffic lights at the moment when the green light has just turned on, it can move. The car leaves point A at the time 0. What is the minimum time for the car to get from point A to point B without breaking the traffic rules? Input The first line contains integers l, d, v, g, r (1 ≀ l, d, v, g, r ≀ 1000, d < l) β€” the distance between A and B (in meters), the distance from A to the traffic lights, car's speed, the duration of green light and the duration of red light. Output Output a single number β€” the minimum time that the car needs to get from point A to point B. Your output must have relative or absolute error less than 10 - 6. Examples Input 2 1 3 4 5 Output 0.66666667 Input 5 4 3 1 1 Output 2.33333333 Submitted Solution: ``` l,d,v,g,r=map(int, input().split()) t=0 p=0 total=r+g x=[i for i in range(d,l,d)] for i in x: t+=((i-p)/v) p+=i a=t%total if a<g: continue else: t+=(total-a) t+=((l-p)/v) print(t) ``` No
11,087
Provide tags and a correct Python 3 solution for this coding contest problem. It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one). If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first. Input The first line contains an integer n (2 ≀ n ≀ 100) β€” the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the elements of the set. Output Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes). Examples Input 2 2 3 Output Alice Input 2 5 3 Output Alice Input 3 5 6 7 Output Bob Note Consider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice. Tags: games, math, number theory Correct Solution: ``` def gcd(a, b): while a > 0: a, b = b % a, a return b n = int(input()) a = [int(x) for x in input().split()] g = a[0] m = a[0] for i in range(1, n): g = gcd(g, a[i]) m = m if m >= a[i] else a[i] if (m // g - n) % 2: print("Alice") else: print("Bob") ```
11,088
Provide tags and a correct Python 3 solution for this coding contest problem. It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one). If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first. Input The first line contains an integer n (2 ≀ n ≀ 100) β€” the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the elements of the set. Output Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes). Examples Input 2 2 3 Output Alice Input 2 5 3 Output Alice Input 3 5 6 7 Output Bob Note Consider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice. Tags: games, math, number theory Correct Solution: ``` def gcd(x,y): if x<y: return gcd(y,x) else: if y==0: return x else: return gcd(y,x%y) if __name__=='__main__': inp = input() inp = input() arr = inp.split(' ') L = [] for a in arr: L.append(int(a)) L.sort() mv = L[0] T = L[1:] for t in T: mv = gcd(mv,t) tot = L[-1]//mv for l in L: if l%mv==0: tot-=1 if tot%2==1: print("Alice") else: print("Bob") ```
11,089
Provide tags and a correct Python 3 solution for this coding contest problem. It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one). If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first. Input The first line contains an integer n (2 ≀ n ≀ 100) β€” the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the elements of the set. Output Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes). Examples Input 2 2 3 Output Alice Input 2 5 3 Output Alice Input 3 5 6 7 Output Bob Note Consider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice. Tags: games, math, number theory Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) def nod(a,b): while a * b: if a > b: a, b = b, a % b else: a, b = b % a, a return (a + b) b = a[:] ans = nod(b[0], b[1]) b = b[2:] while b: ans = nod(ans, b[0]) b = b[1:] #print(ans) for i in range(n): a[i] = a[i] // ans if (- n + max(a)) % 2 == 0: print('Bob') else: print('Alice') ```
11,090
Provide tags and a correct Python 3 solution for this coding contest problem. It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one). If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first. Input The first line contains an integer n (2 ≀ n ≀ 100) β€” the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the elements of the set. Output Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes). Examples Input 2 2 3 Output Alice Input 2 5 3 Output Alice Input 3 5 6 7 Output Bob Note Consider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice. Tags: games, math, number theory Correct Solution: ``` import math n=int(input()) a=sorted([int(_) for _ in input().split()]) b=0 for i in a: b=math.gcd(b,i) c=(a[0]-1)//b for i in range(n-1): c+=(a[i+1]-a[i]-1)//b; if c%2==0: print("Bob") else: print("Alice") ```
11,091
Provide tags and a correct Python 3 solution for this coding contest problem. It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one). If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first. Input The first line contains an integer n (2 ≀ n ≀ 100) β€” the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the elements of the set. Output Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes). Examples Input 2 2 3 Output Alice Input 2 5 3 Output Alice Input 3 5 6 7 Output Bob Note Consider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice. Tags: games, math, number theory Correct Solution: ``` from fractions import gcd n = int(input()) sez = [int(i) for i in input().split()] sez.sort() g = gcd(sez[0], sez[1]) for i in range(2, n): g = gcd(g, sez[i]) left = sez[n-1]/g - n if left%2 == 1: print("Alice") else: print("Bob") ```
11,092
Provide tags and a correct Python 3 solution for this coding contest problem. It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one). If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first. Input The first line contains an integer n (2 ≀ n ≀ 100) β€” the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the elements of the set. Output Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes). Examples Input 2 2 3 Output Alice Input 2 5 3 Output Alice Input 3 5 6 7 Output Bob Note Consider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice. Tags: games, math, number theory Correct Solution: ``` from fractions import gcd n = int(input()) a = [int(x) for x in input().split()] gg = a[0] for i in range(1,n): gg = gcd(gg,a[i]) for i in range(n): a[i] //= gg if (max(a) - n) % 2 == 0: print('Bob') else: print('Alice') ```
11,093
Provide tags and a correct Python 3 solution for this coding contest problem. It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one). If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first. Input The first line contains an integer n (2 ≀ n ≀ 100) β€” the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the elements of the set. Output Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes). Examples Input 2 2 3 Output Alice Input 2 5 3 Output Alice Input 3 5 6 7 Output Bob Note Consider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice. Tags: games, math, number theory Correct Solution: ``` n=int(input()) A=list(map(int,input().split())) def gcd(x,y): while y: x,y=y,x%y return x g=0 for a in A: g=gcd(g,a) u=max(A)//g-n if u%2==0: print("Bob") else: print("Alice") ```
11,094
Provide tags and a correct Python 3 solution for this coding contest problem. It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one). If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first. Input The first line contains an integer n (2 ≀ n ≀ 100) β€” the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the elements of the set. Output Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes). Examples Input 2 2 3 Output Alice Input 2 5 3 Output Alice Input 3 5 6 7 Output Bob Note Consider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice. Tags: games, math, number theory Correct Solution: ``` import sys import math MAXNUM = math.inf MINNUM = -1 * math.inf ASCIILOWER = 97 ASCIIUPPER = 65 def getInt(): return int(sys.stdin.readline().rstrip()) def getInts(): return map(int, sys.stdin.readline().rstrip().split(" ")) def getString(): return sys.stdin.readline().rstrip() def printOutput(ans): sys.stdout.write() pass def solve(nums): c = math.gcd(nums[0], nums[1]) for ele in nums: c = math.gcd(c, ele) total = max(nums) // c - len(nums) if total % 2 == 1: return "Alice" return "Bob" def readinput(): _ = getInt() nums = list(getInts()) print(solve(nums)) readinput() ```
11,095
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one). If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first. Input The first line contains an integer n (2 ≀ n ≀ 100) β€” the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the elements of the set. Output Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes). Examples Input 2 2 3 Output Alice Input 2 5 3 Output Alice Input 3 5 6 7 Output Bob Note Consider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice. Submitted Solution: ``` def gcd(a, b): while a: a, b = b % a, a return b n = int(input()) A = list(map(int, input().split())) G = A[0] for i in range(1, n): G = gcd(G, A[i]) for i in range(n): A[i] //= G if (max(A) - n) % 2 == 1: print("Alice") else: print("Bob") ``` Yes
11,096
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one). If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first. Input The first line contains an integer n (2 ≀ n ≀ 100) β€” the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the elements of the set. Output Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes). Examples Input 2 2 3 Output Alice Input 2 5 3 Output Alice Input 3 5 6 7 Output Bob Note Consider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice. Submitted Solution: ``` from fractions import gcd from functools import reduce n = int(input()) a = [int(i) for i in input().split()] k = reduce(gcd,a) m = max(a) / k if (m-n) % 2 == 0: print("Bob") else: print("Alice") ``` Yes
11,097
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one). If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first. Input The first line contains an integer n (2 ≀ n ≀ 100) β€” the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the elements of the set. Output Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes). Examples Input 2 2 3 Output Alice Input 2 5 3 Output Alice Input 3 5 6 7 Output Bob Note Consider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice. Submitted Solution: ``` def gcd(a, b): if (a < b): a, b = b, a if (b == 0): return a return gcd(a % b, b) n = int(input()) a = list(map(int, input().split())) ma = max(a) mi = min(a) c = a[0] for i in a[1:]: c = gcd(c, i) ma //= c if (ma - n) % 2 == 1: print("Alice") else: print("Bob") ``` Yes
11,098
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one). If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first. Input The first line contains an integer n (2 ≀ n ≀ 100) β€” the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the elements of the set. Output Print a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes). Examples Input 2 2 3 Output Alice Input 2 5 3 Output Alice Input 3 5 6 7 Output Bob Note Consider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice. Submitted Solution: ``` import fractions n = int(input()) A = list(map(int, input().split())) x = A[0] for i in A: x = fractions.gcd(x, i) if (max(A) // x - len(A)) % 2 == 0: print('Bob') else: print('Alice') ``` Yes
11,099