text
stringlengths
198
433k
conversation_id
int64
0
109k
Provide a correct Python 3 solution for this coding contest problem. For given a sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$, print the previous permutation and the next permutation in lexicographic order. Constraints * $1 \leq n \leq 9$ * $a_i$ consist of $1, 2, ..., n$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ... \; a_{n-1}$ Output Print the previous permutation, the given sequence and the next permutation in the 1st, 2nd and 3rd lines respectively. Separate adjacency elements by a space character. Note that if there is no permutation, print nothing in the corresponding line. Examples Input 3 2 1 3 Output 1 3 2 2 1 3 2 3 1 Input 3 3 2 1 Output 3 1 2 3 2 1 "Correct Solution: ``` # AOJ ITP2_5_C: Permutation # Python3 2018.6.24 bal4u def next_permutation(a): # if list has less than two elements, has no next permutation. if len(a) < 2: return False # step 1: find max i for a[i] > a[i+1] i = len(a)-2 while i >= 0 and a[i] >= a[i+1]: i -= 1 if i < 0: return False j = i + 1 # step 2: find max k for a[k] > a[i] k = len(a) - 1 while a[i] >= a[k]: k -= 1 # step 3: swap a[i] and a[k] (a[i], a[k]) = (a[k], a[i]) # step 4: reverse a[j:] a[j:] = a[:j-1:-1] return True def prev_permutation(a): # if list has less than two elements, has no prev permutation. if len(a) < 2: return False # step 1: find max i for a[i] < a[i+1] i = len(a)-2 while i >= 0 and a[i] <= a[i+1]: i -= 1 if i < 0: return False j = i + 1 # step 2: find max k for a[k] < a[i] k = len(a) - 1 while a[i] <= a[k]: k -= 1 # step 3: swap a[i] and a[k] (a[i], a[k]) = (a[k], a[i]) # step 4: reverse a[j:] a[j:] = a[:j-1:-1] return True n = int(input()) a = list(map(int, input().split())) n, p = list(a), list(a) if prev_permutation(p): print(*p) print(*a) if next_permutation(n): print(*n) ```
85,000
Provide a correct Python 3 solution for this coding contest problem. For given a sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$, print the previous permutation and the next permutation in lexicographic order. Constraints * $1 \leq n \leq 9$ * $a_i$ consist of $1, 2, ..., n$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ... \; a_{n-1}$ Output Print the previous permutation, the given sequence and the next permutation in the 1st, 2nd and 3rd lines respectively. Separate adjacency elements by a space character. Note that if there is no permutation, print nothing in the corresponding line. Examples Input 3 2 1 3 Output 1 3 2 2 1 3 2 3 1 Input 3 3 2 1 Output 3 1 2 3 2 1 "Correct Solution: ``` import operator def permutations(li): """Returns a list of previous, current, and next permutations of li. >>> permutations([1, 2]) [[1, 2], [2, 1]] >>> permutations([1, 3, 2]) [[1, 2, 3], [1, 3, 2], [2, 1, 3]] """ def perm(op): def func(xs): i = len(xs) - 1 while i > 0 and op(xs[i-1], xs[i]): i -= 1 if i > 0: i -= 1 j = i + 1 while j < len(xs) and op(xs[j], xs[i]): j += 1 xs[i], xs[j-1] = xs[j-1], xs[i] return xs[:i+1] + list(reversed(xs[i+1:])) else: return None return func prev_perm = perm(operator.lt) next_perm = perm(operator.gt) ps = [] pp = prev_perm(li[:]) if pp is not None: ps.append(pp) ps.append(li[:]) np = next_perm(li[:]) if np is not None: ps.append(np) return ps def run(): n = int(input()) li = [int(x) for x in input().split()] assert(n == len(li)) for ps in permutations(li): print(" ".join([str(x) for x in ps])) if __name__ == '__main__': run() ```
85,001
Provide a correct Python 3 solution for this coding contest problem. For given a sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$, print the previous permutation and the next permutation in lexicographic order. Constraints * $1 \leq n \leq 9$ * $a_i$ consist of $1, 2, ..., n$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ... \; a_{n-1}$ Output Print the previous permutation, the given sequence and the next permutation in the 1st, 2nd and 3rd lines respectively. Separate adjacency elements by a space character. Note that if there is no permutation, print nothing in the corresponding line. Examples Input 3 2 1 3 Output 1 3 2 2 1 3 2 3 1 Input 3 3 2 1 Output 3 1 2 3 2 1 "Correct Solution: ``` from itertools import permutations # INPUT n = int(input()) A = tuple(input().split()) # PROCESS, OUTPUT str_num = "" for num in range(1, n + 1): str_num += str(num) flag_break = False list_num_previous = None for list_num in permutations(str_num): if flag_break: # next print(*list_num) break if list_num == A: if list_num_previous != None: # previous print(*list_num_previous) # now print(*list_num) flag_break = True list_num_previous = list_num ```
85,002
Provide a correct Python 3 solution for this coding contest problem. For given a sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$, print the previous permutation and the next permutation in lexicographic order. Constraints * $1 \leq n \leq 9$ * $a_i$ consist of $1, 2, ..., n$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ... \; a_{n-1}$ Output Print the previous permutation, the given sequence and the next permutation in the 1st, 2nd and 3rd lines respectively. Separate adjacency elements by a space character. Note that if there is no permutation, print nothing in the corresponding line. Examples Input 3 2 1 3 Output 1 3 2 2 1 3 2 3 1 Input 3 3 2 1 Output 3 1 2 3 2 1 "Correct Solution: ``` def resolve(): import itertools n = int(input()) target = tuple(int(i) for i in input().split()) before = None found = False for a in sorted(itertools.permutations(target)): if found: print(*a) return elif a == target: if before is not None: print(*before) print(*target) found = True else: before = a resolve() ```
85,003
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For given a sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$, print the previous permutation and the next permutation in lexicographic order. Constraints * $1 \leq n \leq 9$ * $a_i$ consist of $1, 2, ..., n$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ... \; a_{n-1}$ Output Print the previous permutation, the given sequence and the next permutation in the 1st, 2nd and 3rd lines respectively. Separate adjacency elements by a space character. Note that if there is no permutation, print nothing in the corresponding line. Examples Input 3 2 1 3 Output 1 3 2 2 1 3 2 3 1 Input 3 3 2 1 Output 3 1 2 3 2 1 Submitted Solution: ``` import itertools from typing import List, Tuple def print_elems(elems): print(" ".join([str(elem) for elem in elems])) if __name__ == "__main__": n = int(input()) nums = tuple(map(lambda x: int(x), input().split())) nums_permutated = list(itertools.permutations(sorted(nums))) if (1 == len(nums_permutated)): print(nums[0]) exit(0) for idx in range(1, len(nums_permutated)): if (nums == nums_permutated[idx - 1]): print_elems(nums_permutated[idx - 1]) print_elems(nums_permutated[idx]) exit(0) if (nums == nums_permutated[idx]): print_elems(nums_permutated[idx - 1]) print_elems(nums_permutated[idx]) if (idx != len(nums_permutated) - 1): print_elems(nums_permutated[idx + 1]) exit(0) ``` Yes
85,004
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For given a sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$, print the previous permutation and the next permutation in lexicographic order. Constraints * $1 \leq n \leq 9$ * $a_i$ consist of $1, 2, ..., n$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ... \; a_{n-1}$ Output Print the previous permutation, the given sequence and the next permutation in the 1st, 2nd and 3rd lines respectively. Separate adjacency elements by a space character. Note that if there is no permutation, print nothing in the corresponding line. Examples Input 3 2 1 3 Output 1 3 2 2 1 3 2 3 1 Input 3 3 2 1 Output 3 1 2 3 2 1 Submitted Solution: ``` # http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP2_5_C&lang=jp # Enumeration : python3 # 2018.12.01 yonezawa import sys input = sys.stdin.readline from collections import deque class enumeration: def __init__(self,n): self.n = n self.depth = 0 self.wnum = 0 self.nq = [] self.bits = [ pow(2,i) for i in range(n+1) ] self.mk_permutation(0,0,0) def mk_permutation(self,depth,bflag,wnum): if self.n == depth: self.nq.append(wnum) return for i in range(1,self.n+1): if bflag & self.bits[i-1] != 0: continue self.mk_permutation(depth + 1,bflag + self.bits[i-1],wnum*10+i) def printList(self): l = self.nq self.nq.sort() for i in l: self.printInttoStr(i) def printInttoStr(self,i): c = "" for j in str(i): c += j + " " print(c.strip()) def solve(self,tc): pos = self.nq.index(tc) if (pos != 0 ): self.printInttoStr(self.nq[pos-1]) self.printInttoStr(tc) if (pos + 1 != len(self.nq) ): self.printInttoStr(self.nq[pos+1]) def main(): n = int(input()) tc = 0 for i in list(map(int,input().split())): tc = tc * 10 + i e = enumeration(n) e.solve(tc) if __name__ == '__main__': main() ``` Yes
85,005
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For given a sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$, print the previous permutation and the next permutation in lexicographic order. Constraints * $1 \leq n \leq 9$ * $a_i$ consist of $1, 2, ..., n$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ... \; a_{n-1}$ Output Print the previous permutation, the given sequence and the next permutation in the 1st, 2nd and 3rd lines respectively. Separate adjacency elements by a space character. Note that if there is no permutation, print nothing in the corresponding line. Examples Input 3 2 1 3 Output 1 3 2 2 1 3 2 3 1 Input 3 3 2 1 Output 3 1 2 3 2 1 Submitted Solution: ``` from itertools import permutations input() L = [int(x) for x in input().split()] k = tuple(L) prev = None L.sort() f = 0 for s in permutations(L): if s == k: if prev: print(*prev) print(*s) f += 1 else: if f > 0: print(*s) break prev = s ``` Yes
85,006
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For given a sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$, print the previous permutation and the next permutation in lexicographic order. Constraints * $1 \leq n \leq 9$ * $a_i$ consist of $1, 2, ..., n$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ... \; a_{n-1}$ Output Print the previous permutation, the given sequence and the next permutation in the 1st, 2nd and 3rd lines respectively. Separate adjacency elements by a space character. Note that if there is no permutation, print nothing in the corresponding line. Examples Input 3 2 1 3 Output 1 3 2 2 1 3 2 3 1 Input 3 3 2 1 Output 3 1 2 3 2 1 Submitted Solution: ``` def next_permutation(a): # if list has less than two elements, has no next permutation if len(a) < 2: return False # step1 : find max i for a[i] > a[i+1] i = len(a) - 2 while i >= 0 and a[i] >= a[i+1]: i -= 1 if i < 0: return False j = i + 1 # step2 : find max k for a[k] > a[i] k = len(a) - 1 while a[i] >= a[k]: k -= 1 # step3 : swap a[i] and a[k] (a[i], a[k]) = (a[k], a[i]) # step4 : reverse a[j:] a[j:] = a[:j-1:-1] return True def prev_permutation(a): # if list has less than two elements, has no prev permutation if len(a) < 2: return False # step1 : find max i for a[i] < a[i+1] i = len(a) - 2 while i >= 0 and a[i] <= a[i+1]: i -= 1 if i < 0: return False j = i + 1 # step2 : find max k for a[k] < a[i] k = len(a) - 1 while a[i] <= a[k]: k -= 1 # step3 : swap a[i] and a[k] (a[i], a[k]) = (a[k], a[i]) # step4 : reverse a[j:] a[j:] = a[:j-1:-1] return True n = int(input()) a = list(map(int, input().split())) n, p = list(a), list(a) if prev_permutation(p): print(*p) print(*a) if next_permutation(n): print(*n) ``` Yes
85,007
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Imur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant i and participant i + 1 (1 ≤ i ≤ n - 1) are adjacent, as well as participant n and participant 1. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice. As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers i and <image> sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists. You can ask questions of form «which number was received by student i?», and the goal is to determine whether the desired pair exists in no more than 60 questions. Input At the beginning the even integer n (2 ≤ n ≤ 100 000) is given — the total number of students. You are allowed to ask no more than 60 questions. Output To ask the question about the student i (1 ≤ i ≤ n), you should print «? i». Then from standard output you can read the number ai received by student i ( - 109 ≤ ai ≤ 109). When you find the desired pair, you should print «! i», where i is any student who belongs to the pair (1 ≤ i ≤ n). If you determined that such pair doesn't exist, you should output «! -1». In both cases you should immediately terminate the program. The query that contains your answer is not counted towards the limit of 60 queries. Please make sure to flush the standard output after each command. For example, in C++ use function fflush(stdout), in Java call System.out.flush(), in Pascal use flush(output) and stdout.flush() for Python language. Hacking Use the following format for hacking: In the first line, print one even integer n (2 ≤ n ≤ 100 000) — the total number of students. In the second line print n integers ai ( - 109 ≤ ai ≤ 109) separated by spaces, where ai is the number to give to i-th student. Any two adjacent elements, including n and 1, must differ by 1 or - 1. The hacked solution will not have direct access to the sequence ai. Examples Input 8 <span class="tex-span"></span> 2 <span class="tex-span"></span> 2 Output <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 8 <span class="tex-span"></span> ! 4 Input 6 <span class="tex-span"></span> 1 <span class="tex-span"></span> 2 <span class="tex-span"></span> 3 <span class="tex-span"></span> 2 <span class="tex-span"></span> 1 <span class="tex-span"></span> 0 Output <span class="tex-span"></span> ? 1 <span class="tex-span"></span> ? 2 <span class="tex-span"></span> ? 3 <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 5 <span class="tex-span"></span> ? 6 <span class="tex-span"></span> ! -1 Note Input-output in statements illustrates example interaction. In the first sample the selected sequence is 1, 2, 1, 2, 3, 4, 3, 2 In the second sample the selection sequence is 1, 2, 3, 2, 1, 0. Tags: binary search, interactive Correct Solution: ``` class Solver: def solve(self): self.num_people = int(input()) if self.num_people % 4 == 2: return -1 return self.find_zero_pair() def find_zero_pair(self): begin = 1 end = self.num_people // 2 + 1 begin_value = self.func(begin) if begin_value == 0: return begin while begin < end: mid = (begin + end) // 2 mid_value = self.func(mid) if mid_value == 0: return mid elif begin_value * mid_value > 0: begin = mid + 1 else: end = mid - 1 return begin def func(self, pos): opposite = (pos - 1 + self.num_people // 2) % self.num_people + 1 return self.get_value(pos) - self.get_value(opposite) def get_value(self, pos): print('? {}'.format(pos)) value = int(input()) return value solver = Solver() pair = solver.solve() print('! {}'.format(pair)) ```
85,008
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Imur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant i and participant i + 1 (1 ≤ i ≤ n - 1) are adjacent, as well as participant n and participant 1. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice. As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers i and <image> sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists. You can ask questions of form «which number was received by student i?», and the goal is to determine whether the desired pair exists in no more than 60 questions. Input At the beginning the even integer n (2 ≤ n ≤ 100 000) is given — the total number of students. You are allowed to ask no more than 60 questions. Output To ask the question about the student i (1 ≤ i ≤ n), you should print «? i». Then from standard output you can read the number ai received by student i ( - 109 ≤ ai ≤ 109). When you find the desired pair, you should print «! i», where i is any student who belongs to the pair (1 ≤ i ≤ n). If you determined that such pair doesn't exist, you should output «! -1». In both cases you should immediately terminate the program. The query that contains your answer is not counted towards the limit of 60 queries. Please make sure to flush the standard output after each command. For example, in C++ use function fflush(stdout), in Java call System.out.flush(), in Pascal use flush(output) and stdout.flush() for Python language. Hacking Use the following format for hacking: In the first line, print one even integer n (2 ≤ n ≤ 100 000) — the total number of students. In the second line print n integers ai ( - 109 ≤ ai ≤ 109) separated by spaces, where ai is the number to give to i-th student. Any two adjacent elements, including n and 1, must differ by 1 or - 1. The hacked solution will not have direct access to the sequence ai. Examples Input 8 <span class="tex-span"></span> 2 <span class="tex-span"></span> 2 Output <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 8 <span class="tex-span"></span> ! 4 Input 6 <span class="tex-span"></span> 1 <span class="tex-span"></span> 2 <span class="tex-span"></span> 3 <span class="tex-span"></span> 2 <span class="tex-span"></span> 1 <span class="tex-span"></span> 0 Output <span class="tex-span"></span> ? 1 <span class="tex-span"></span> ? 2 <span class="tex-span"></span> ? 3 <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 5 <span class="tex-span"></span> ? 6 <span class="tex-span"></span> ! -1 Note Input-output in statements illustrates example interaction. In the first sample the selected sequence is 1, 2, 1, 2, 3, 4, 3, 2 In the second sample the selection sequence is 1, 2, 3, 2, 1, 0. Tags: binary search, interactive Correct Solution: ``` # this sequence is a bit scary # 8 # 1 2 3 2 3 2 1 0 import sys #sys.stdin=open("data.txt") #input=sys.stdin.readline got=[10**18]*100005 def getnum(i): if got[i]==10**18: print("? %d"%i) sys.stdout.flush() got[i]=int(input()) return got[i] n=int(input()) if n%4==2: # the opposite person has a different parity print("! -1") else: lo=1 hi=n//2+1 t1=getnum(lo) t2=getnum(hi) lo2=t1-t2 hi2=t2-t1 if lo2==0: print("! 1") else: # binary search # let's hope that 1 <= mid <= n/2 while lo<hi: mid=(lo+hi)//2 #print(lo,hi,mid) mid2=getnum(mid)-getnum(mid+n//2) if mid2==0: print("! %d"%mid) break if (lo2>0) == (mid2>0): lo=mid+1 else: hi=mid-1 else: print("! %d"%lo) sys.stdout.flush() ```
85,009
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Imur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant i and participant i + 1 (1 ≤ i ≤ n - 1) are adjacent, as well as participant n and participant 1. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice. As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers i and <image> sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists. You can ask questions of form «which number was received by student i?», and the goal is to determine whether the desired pair exists in no more than 60 questions. Input At the beginning the even integer n (2 ≤ n ≤ 100 000) is given — the total number of students. You are allowed to ask no more than 60 questions. Output To ask the question about the student i (1 ≤ i ≤ n), you should print «? i». Then from standard output you can read the number ai received by student i ( - 109 ≤ ai ≤ 109). When you find the desired pair, you should print «! i», where i is any student who belongs to the pair (1 ≤ i ≤ n). If you determined that such pair doesn't exist, you should output «! -1». In both cases you should immediately terminate the program. The query that contains your answer is not counted towards the limit of 60 queries. Please make sure to flush the standard output after each command. For example, in C++ use function fflush(stdout), in Java call System.out.flush(), in Pascal use flush(output) and stdout.flush() for Python language. Hacking Use the following format for hacking: In the first line, print one even integer n (2 ≤ n ≤ 100 000) — the total number of students. In the second line print n integers ai ( - 109 ≤ ai ≤ 109) separated by spaces, where ai is the number to give to i-th student. Any two adjacent elements, including n and 1, must differ by 1 or - 1. The hacked solution will not have direct access to the sequence ai. Examples Input 8 <span class="tex-span"></span> 2 <span class="tex-span"></span> 2 Output <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 8 <span class="tex-span"></span> ! 4 Input 6 <span class="tex-span"></span> 1 <span class="tex-span"></span> 2 <span class="tex-span"></span> 3 <span class="tex-span"></span> 2 <span class="tex-span"></span> 1 <span class="tex-span"></span> 0 Output <span class="tex-span"></span> ? 1 <span class="tex-span"></span> ? 2 <span class="tex-span"></span> ? 3 <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 5 <span class="tex-span"></span> ? 6 <span class="tex-span"></span> ! -1 Note Input-output in statements illustrates example interaction. In the first sample the selected sequence is 1, 2, 1, 2, 3, 4, 3, 2 In the second sample the selection sequence is 1, 2, 3, 2, 1, 0. Tags: binary search, interactive Correct Solution: ``` from sys import stdout n = int(input()) if n % 4 == 2: print("! -1") exit(0) print("?", 1) stdout.flush() a = int(input()) print("?", 1 + n // 2) stdout.flush() b = int(input()) if a == b: print("!", 1) exit(0) l = 1 r = 1 + n // 2 while(l != r): mid = ( l + r ) // 2 print("?", mid) stdout.flush() c = int(input()) print("?", mid + n // 2) stdout.flush() d = int(input()) if c == d: print("!", mid) exit(0) if a < b: if c < d: l = mid + 1 else: r = mid else: if c > d: l = mid + 1 else: r = mid print("!", l) ```
85,010
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Imur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant i and participant i + 1 (1 ≤ i ≤ n - 1) are adjacent, as well as participant n and participant 1. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice. As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers i and <image> sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists. You can ask questions of form «which number was received by student i?», and the goal is to determine whether the desired pair exists in no more than 60 questions. Input At the beginning the even integer n (2 ≤ n ≤ 100 000) is given — the total number of students. You are allowed to ask no more than 60 questions. Output To ask the question about the student i (1 ≤ i ≤ n), you should print «? i». Then from standard output you can read the number ai received by student i ( - 109 ≤ ai ≤ 109). When you find the desired pair, you should print «! i», where i is any student who belongs to the pair (1 ≤ i ≤ n). If you determined that such pair doesn't exist, you should output «! -1». In both cases you should immediately terminate the program. The query that contains your answer is not counted towards the limit of 60 queries. Please make sure to flush the standard output after each command. For example, in C++ use function fflush(stdout), in Java call System.out.flush(), in Pascal use flush(output) and stdout.flush() for Python language. Hacking Use the following format for hacking: In the first line, print one even integer n (2 ≤ n ≤ 100 000) — the total number of students. In the second line print n integers ai ( - 109 ≤ ai ≤ 109) separated by spaces, where ai is the number to give to i-th student. Any two adjacent elements, including n and 1, must differ by 1 or - 1. The hacked solution will not have direct access to the sequence ai. Examples Input 8 <span class="tex-span"></span> 2 <span class="tex-span"></span> 2 Output <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 8 <span class="tex-span"></span> ! 4 Input 6 <span class="tex-span"></span> 1 <span class="tex-span"></span> 2 <span class="tex-span"></span> 3 <span class="tex-span"></span> 2 <span class="tex-span"></span> 1 <span class="tex-span"></span> 0 Output <span class="tex-span"></span> ? 1 <span class="tex-span"></span> ? 2 <span class="tex-span"></span> ? 3 <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 5 <span class="tex-span"></span> ? 6 <span class="tex-span"></span> ! -1 Note Input-output in statements illustrates example interaction. In the first sample the selected sequence is 1, 2, 1, 2, 3, 4, 3, 2 In the second sample the selection sequence is 1, 2, 3, 2, 1, 0. Tags: binary search, interactive Correct Solution: ``` from sys import stdout n = int(input()) if n % 4 == 2: print('!', -1) exit(0) l = 1 r = l + n // 2 memo = [-1] * (n + 1) def check(i): if memo[i] == -1: print('?', i) stdout.flush() memo[i] = int(input()) return memo[i] while r >= l: a = check(l) b = check(l + n // 2) if a == b: print('!', l) exit(0) mid = (l + r) >> 1 c = check(mid) d = check(mid + n // 2) if c == d: print('!', mid) exit(0) if (a < b and c < d) or (a > b and c > d): l = mid + 1 else: r = mid ```
85,011
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Imur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant i and participant i + 1 (1 ≤ i ≤ n - 1) are adjacent, as well as participant n and participant 1. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice. As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers i and <image> sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists. You can ask questions of form «which number was received by student i?», and the goal is to determine whether the desired pair exists in no more than 60 questions. Input At the beginning the even integer n (2 ≤ n ≤ 100 000) is given — the total number of students. You are allowed to ask no more than 60 questions. Output To ask the question about the student i (1 ≤ i ≤ n), you should print «? i». Then from standard output you can read the number ai received by student i ( - 109 ≤ ai ≤ 109). When you find the desired pair, you should print «! i», where i is any student who belongs to the pair (1 ≤ i ≤ n). If you determined that such pair doesn't exist, you should output «! -1». In both cases you should immediately terminate the program. The query that contains your answer is not counted towards the limit of 60 queries. Please make sure to flush the standard output after each command. For example, in C++ use function fflush(stdout), in Java call System.out.flush(), in Pascal use flush(output) and stdout.flush() for Python language. Hacking Use the following format for hacking: In the first line, print one even integer n (2 ≤ n ≤ 100 000) — the total number of students. In the second line print n integers ai ( - 109 ≤ ai ≤ 109) separated by spaces, where ai is the number to give to i-th student. Any two adjacent elements, including n and 1, must differ by 1 or - 1. The hacked solution will not have direct access to the sequence ai. Examples Input 8 <span class="tex-span"></span> 2 <span class="tex-span"></span> 2 Output <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 8 <span class="tex-span"></span> ! 4 Input 6 <span class="tex-span"></span> 1 <span class="tex-span"></span> 2 <span class="tex-span"></span> 3 <span class="tex-span"></span> 2 <span class="tex-span"></span> 1 <span class="tex-span"></span> 0 Output <span class="tex-span"></span> ? 1 <span class="tex-span"></span> ? 2 <span class="tex-span"></span> ? 3 <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 5 <span class="tex-span"></span> ? 6 <span class="tex-span"></span> ! -1 Note Input-output in statements illustrates example interaction. In the first sample the selected sequence is 1, 2, 1, 2, 3, 4, 3, 2 In the second sample the selection sequence is 1, 2, 3, 2, 1, 0. Tags: binary search, interactive Correct Solution: ``` from sys import stdout n = int(input()) if n % 4 == 2: print("! -1") exit(0) print("?", 1) stdout.flush() a = int(input()) print("?", 1 + n // 2) stdout.flush() b = int(input()) if a == b: print("!", 1) exit(0) l = 1 r = 1 + n // 2 while(l != r): mid = ( l + r ) // 2 print("?", mid) stdout.flush() c = int(input()) print("?", mid + n // 2) stdout.flush() d = int(input()) if c == d: print("!", mid) exit(0) if a < b: if c < d: l = mid + 1 else: r = mid else: if c > d: l = mid + 1 else: r = mid print("!", l) # Made By Mostafa_Khaled ```
85,012
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Imur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant i and participant i + 1 (1 ≤ i ≤ n - 1) are adjacent, as well as participant n and participant 1. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice. As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers i and <image> sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists. You can ask questions of form «which number was received by student i?», and the goal is to determine whether the desired pair exists in no more than 60 questions. Input At the beginning the even integer n (2 ≤ n ≤ 100 000) is given — the total number of students. You are allowed to ask no more than 60 questions. Output To ask the question about the student i (1 ≤ i ≤ n), you should print «? i». Then from standard output you can read the number ai received by student i ( - 109 ≤ ai ≤ 109). When you find the desired pair, you should print «! i», where i is any student who belongs to the pair (1 ≤ i ≤ n). If you determined that such pair doesn't exist, you should output «! -1». In both cases you should immediately terminate the program. The query that contains your answer is not counted towards the limit of 60 queries. Please make sure to flush the standard output after each command. For example, in C++ use function fflush(stdout), in Java call System.out.flush(), in Pascal use flush(output) and stdout.flush() for Python language. Hacking Use the following format for hacking: In the first line, print one even integer n (2 ≤ n ≤ 100 000) — the total number of students. In the second line print n integers ai ( - 109 ≤ ai ≤ 109) separated by spaces, where ai is the number to give to i-th student. Any two adjacent elements, including n and 1, must differ by 1 or - 1. The hacked solution will not have direct access to the sequence ai. Examples Input 8 <span class="tex-span"></span> 2 <span class="tex-span"></span> 2 Output <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 8 <span class="tex-span"></span> ! 4 Input 6 <span class="tex-span"></span> 1 <span class="tex-span"></span> 2 <span class="tex-span"></span> 3 <span class="tex-span"></span> 2 <span class="tex-span"></span> 1 <span class="tex-span"></span> 0 Output <span class="tex-span"></span> ? 1 <span class="tex-span"></span> ? 2 <span class="tex-span"></span> ? 3 <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 5 <span class="tex-span"></span> ? 6 <span class="tex-span"></span> ! -1 Note Input-output in statements illustrates example interaction. In the first sample the selected sequence is 1, 2, 1, 2, 3, 4, 3, 2 In the second sample the selection sequence is 1, 2, 3, 2, 1, 0. Tags: binary search, interactive Correct Solution: ``` #!/usr/bin/env python3 import sys def ask(i): print('?', i + 1) sys.stdout.flush() a_i = int(input()) return a_i def answer(i): print('!', i + 1 if i != -1 else -1) sys.exit() def has_intersection(l1, r1, l2, r2): if l1 <= l2 and r2 <= r1: return True if l2 <= l1 and r1 <= r2: return True return False n = int(input()) assert n >= 2 and n % 2 == 0 if (n // 2) % 2 == 1: answer(-1) else: assert n % 4 == 0 l1 = 0 r1 = n // 2 a_l1 = ask(l1) a_r1 = ask(r1) if a_l1 == a_r1: answer(0) a_l2 = a_r1 a_r2 = a_l1 # print('binary search [', l1, ',', r1, ') ->', (l1 + r1) // 2, file=sys.stderr) while True: m1 = (l1 + r1) // 2 m2 = (m1 + n // 2) % n a_m1 = ask(m1) a_m2 = ask(m2) if a_m1 == a_m2: answer(m1) if has_intersection(a_l1, a_m1, a_l2, a_m2): r1 = m1 a_r1 = a_m1 a_r2 = a_m2 else: assert has_intersection(a_m1, a_r1, a_m2, a_r2) l1 = m1 a_l1 = a_m1 a_l2 = a_m2 # print('binary search [', l1, ',', r1, ') ->', (l1 + r1) // 2, file=sys.stderr) assert False ```
85,013
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Imur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant i and participant i + 1 (1 ≤ i ≤ n - 1) are adjacent, as well as participant n and participant 1. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice. As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers i and <image> sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists. You can ask questions of form «which number was received by student i?», and the goal is to determine whether the desired pair exists in no more than 60 questions. Input At the beginning the even integer n (2 ≤ n ≤ 100 000) is given — the total number of students. You are allowed to ask no more than 60 questions. Output To ask the question about the student i (1 ≤ i ≤ n), you should print «? i». Then from standard output you can read the number ai received by student i ( - 109 ≤ ai ≤ 109). When you find the desired pair, you should print «! i», where i is any student who belongs to the pair (1 ≤ i ≤ n). If you determined that such pair doesn't exist, you should output «! -1». In both cases you should immediately terminate the program. The query that contains your answer is not counted towards the limit of 60 queries. Please make sure to flush the standard output after each command. For example, in C++ use function fflush(stdout), in Java call System.out.flush(), in Pascal use flush(output) and stdout.flush() for Python language. Hacking Use the following format for hacking: In the first line, print one even integer n (2 ≤ n ≤ 100 000) — the total number of students. In the second line print n integers ai ( - 109 ≤ ai ≤ 109) separated by spaces, where ai is the number to give to i-th student. Any two adjacent elements, including n and 1, must differ by 1 or - 1. The hacked solution will not have direct access to the sequence ai. Examples Input 8 <span class="tex-span"></span> 2 <span class="tex-span"></span> 2 Output <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 8 <span class="tex-span"></span> ! 4 Input 6 <span class="tex-span"></span> 1 <span class="tex-span"></span> 2 <span class="tex-span"></span> 3 <span class="tex-span"></span> 2 <span class="tex-span"></span> 1 <span class="tex-span"></span> 0 Output <span class="tex-span"></span> ? 1 <span class="tex-span"></span> ? 2 <span class="tex-span"></span> ? 3 <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 5 <span class="tex-span"></span> ? 6 <span class="tex-span"></span> ! -1 Note Input-output in statements illustrates example interaction. In the first sample the selected sequence is 1, 2, 1, 2, 3, 4, 3, 2 In the second sample the selection sequence is 1, 2, 3, 2, 1, 0. Tags: binary search, interactive Correct Solution: ``` import sys def ask(x): print('? %d'%x) sys.stdout.flush() x=int(input()) return x n=int(input()) t=n//2 if t&1: print('! -1') sys.stdout.flush() sys.exit() l=1 r=n while l<r: mid=(l+r)>>1 if ask(mid)>=ask((mid+t-1)%n+1): r=mid else: l=mid+1 print('! %d'%l) sys.stdout.flush() ```
85,014
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Imur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant i and participant i + 1 (1 ≤ i ≤ n - 1) are adjacent, as well as participant n and participant 1. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice. As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers i and <image> sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists. You can ask questions of form «which number was received by student i?», and the goal is to determine whether the desired pair exists in no more than 60 questions. Input At the beginning the even integer n (2 ≤ n ≤ 100 000) is given — the total number of students. You are allowed to ask no more than 60 questions. Output To ask the question about the student i (1 ≤ i ≤ n), you should print «? i». Then from standard output you can read the number ai received by student i ( - 109 ≤ ai ≤ 109). When you find the desired pair, you should print «! i», where i is any student who belongs to the pair (1 ≤ i ≤ n). If you determined that such pair doesn't exist, you should output «! -1». In both cases you should immediately terminate the program. The query that contains your answer is not counted towards the limit of 60 queries. Please make sure to flush the standard output after each command. For example, in C++ use function fflush(stdout), in Java call System.out.flush(), in Pascal use flush(output) and stdout.flush() for Python language. Hacking Use the following format for hacking: In the first line, print one even integer n (2 ≤ n ≤ 100 000) — the total number of students. In the second line print n integers ai ( - 109 ≤ ai ≤ 109) separated by spaces, where ai is the number to give to i-th student. Any two adjacent elements, including n and 1, must differ by 1 or - 1. The hacked solution will not have direct access to the sequence ai. Examples Input 8 <span class="tex-span"></span> 2 <span class="tex-span"></span> 2 Output <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 8 <span class="tex-span"></span> ! 4 Input 6 <span class="tex-span"></span> 1 <span class="tex-span"></span> 2 <span class="tex-span"></span> 3 <span class="tex-span"></span> 2 <span class="tex-span"></span> 1 <span class="tex-span"></span> 0 Output <span class="tex-span"></span> ? 1 <span class="tex-span"></span> ? 2 <span class="tex-span"></span> ? 3 <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 5 <span class="tex-span"></span> ? 6 <span class="tex-span"></span> ! -1 Note Input-output in statements illustrates example interaction. In the first sample the selected sequence is 1, 2, 1, 2, 3, 4, 3, 2 In the second sample the selection sequence is 1, 2, 3, 2, 1, 0. Tags: binary search, interactive Correct Solution: ``` USE_STDIO = True import sys if not USE_STDIO: try: import mypc except: pass def get_two(x, n): print('?', x) sys.stdout.flush() a = int(input()) x += n // 2 if x > n: x -= n print('?', x) sys.stdout.flush() b = int(input()) return a, b def answer(x): print('!', x) sys.stdout.flush() def main(): n, = map(int, input().split(' ')) if n % 4 != 0: answer(-1) return x, y = get_two(1, n) if x == y: answer(1) return l, r = 2, n // 2 for _ in range(30): mid = (l + r) // 2 xn, yn = get_two(mid, n) if xn == yn: answer(mid) return if (yn - xn) * (y - x) > 0: l = mid + 1 else: r = mid - 1 answer(-1) if __name__ == '__main__': main() ```
85,015
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an interactive problem. Imur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant i and participant i + 1 (1 ≤ i ≤ n - 1) are adjacent, as well as participant n and participant 1. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice. As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers i and <image> sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists. You can ask questions of form «which number was received by student i?», and the goal is to determine whether the desired pair exists in no more than 60 questions. Input At the beginning the even integer n (2 ≤ n ≤ 100 000) is given — the total number of students. You are allowed to ask no more than 60 questions. Output To ask the question about the student i (1 ≤ i ≤ n), you should print «? i». Then from standard output you can read the number ai received by student i ( - 109 ≤ ai ≤ 109). When you find the desired pair, you should print «! i», where i is any student who belongs to the pair (1 ≤ i ≤ n). If you determined that such pair doesn't exist, you should output «! -1». In both cases you should immediately terminate the program. The query that contains your answer is not counted towards the limit of 60 queries. Please make sure to flush the standard output after each command. For example, in C++ use function fflush(stdout), in Java call System.out.flush(), in Pascal use flush(output) and stdout.flush() for Python language. Hacking Use the following format for hacking: In the first line, print one even integer n (2 ≤ n ≤ 100 000) — the total number of students. In the second line print n integers ai ( - 109 ≤ ai ≤ 109) separated by spaces, where ai is the number to give to i-th student. Any two adjacent elements, including n and 1, must differ by 1 or - 1. The hacked solution will not have direct access to the sequence ai. Examples Input 8 <span class="tex-span"></span> 2 <span class="tex-span"></span> 2 Output <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 8 <span class="tex-span"></span> ! 4 Input 6 <span class="tex-span"></span> 1 <span class="tex-span"></span> 2 <span class="tex-span"></span> 3 <span class="tex-span"></span> 2 <span class="tex-span"></span> 1 <span class="tex-span"></span> 0 Output <span class="tex-span"></span> ? 1 <span class="tex-span"></span> ? 2 <span class="tex-span"></span> ? 3 <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 5 <span class="tex-span"></span> ? 6 <span class="tex-span"></span> ! -1 Note Input-output in statements illustrates example interaction. In the first sample the selected sequence is 1, 2, 1, 2, 3, 4, 3, 2 In the second sample the selection sequence is 1, 2, 3, 2, 1, 0. Submitted Solution: ``` import sys def printans(i): print("! %d"%i, flush=True) sys.exit(0) def fullgetdiff(i, m): print("? %d"%i, flush=True) ai = int(input()) print("? %d"%(i+m), flush=True) aim = int(input()) return ai-aim n = int(input()) if n//2%2: printans(-1) getdiff = lambda i: fullgetdiff(i, n//2) d1 = getdiff(1) if d1==0: printans(1) lo, hi = 2, n//2 while lo <= hi: mid = (lo+hi)//2 dmid = getdiff(mid) if dmid == 0: printans(mid) if d1*dmid > 0: lo = mid+1 else: hi = mid-1 ``` Yes
85,016
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an interactive problem. Imur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant i and participant i + 1 (1 ≤ i ≤ n - 1) are adjacent, as well as participant n and participant 1. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice. As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers i and <image> sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists. You can ask questions of form «which number was received by student i?», and the goal is to determine whether the desired pair exists in no more than 60 questions. Input At the beginning the even integer n (2 ≤ n ≤ 100 000) is given — the total number of students. You are allowed to ask no more than 60 questions. Output To ask the question about the student i (1 ≤ i ≤ n), you should print «? i». Then from standard output you can read the number ai received by student i ( - 109 ≤ ai ≤ 109). When you find the desired pair, you should print «! i», where i is any student who belongs to the pair (1 ≤ i ≤ n). If you determined that such pair doesn't exist, you should output «! -1». In both cases you should immediately terminate the program. The query that contains your answer is not counted towards the limit of 60 queries. Please make sure to flush the standard output after each command. For example, in C++ use function fflush(stdout), in Java call System.out.flush(), in Pascal use flush(output) and stdout.flush() for Python language. Hacking Use the following format for hacking: In the first line, print one even integer n (2 ≤ n ≤ 100 000) — the total number of students. In the second line print n integers ai ( - 109 ≤ ai ≤ 109) separated by spaces, where ai is the number to give to i-th student. Any two adjacent elements, including n and 1, must differ by 1 or - 1. The hacked solution will not have direct access to the sequence ai. Examples Input 8 <span class="tex-span"></span> 2 <span class="tex-span"></span> 2 Output <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 8 <span class="tex-span"></span> ! 4 Input 6 <span class="tex-span"></span> 1 <span class="tex-span"></span> 2 <span class="tex-span"></span> 3 <span class="tex-span"></span> 2 <span class="tex-span"></span> 1 <span class="tex-span"></span> 0 Output <span class="tex-span"></span> ? 1 <span class="tex-span"></span> ? 2 <span class="tex-span"></span> ? 3 <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 5 <span class="tex-span"></span> ? 6 <span class="tex-span"></span> ! -1 Note Input-output in statements illustrates example interaction. In the first sample the selected sequence is 1, 2, 1, 2, 3, 4, 3, 2 In the second sample the selection sequence is 1, 2, 3, 2, 1, 0. Submitted Solution: ``` n=int(input()) if n%4==2: print('!', '-1') exit() def qry(i): print('?', i+1, flush=True) a=int(input()) return a def qry2(i): a=qry(i+n//2)-qry(i) if a==0: print('!', i+1) exit() return a a=qry2(0) lb,rb=1,n//2-1 while lb<=rb: mb=(lb+rb)//2 b=qry2(mb) if (a>0)==(b>0): lb=mb+1 else: rb=mb-1 ``` Yes
85,017
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an interactive problem. Imur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant i and participant i + 1 (1 ≤ i ≤ n - 1) are adjacent, as well as participant n and participant 1. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice. As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers i and <image> sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists. You can ask questions of form «which number was received by student i?», and the goal is to determine whether the desired pair exists in no more than 60 questions. Input At the beginning the even integer n (2 ≤ n ≤ 100 000) is given — the total number of students. You are allowed to ask no more than 60 questions. Output To ask the question about the student i (1 ≤ i ≤ n), you should print «? i». Then from standard output you can read the number ai received by student i ( - 109 ≤ ai ≤ 109). When you find the desired pair, you should print «! i», where i is any student who belongs to the pair (1 ≤ i ≤ n). If you determined that such pair doesn't exist, you should output «! -1». In both cases you should immediately terminate the program. The query that contains your answer is not counted towards the limit of 60 queries. Please make sure to flush the standard output after each command. For example, in C++ use function fflush(stdout), in Java call System.out.flush(), in Pascal use flush(output) and stdout.flush() for Python language. Hacking Use the following format for hacking: In the first line, print one even integer n (2 ≤ n ≤ 100 000) — the total number of students. In the second line print n integers ai ( - 109 ≤ ai ≤ 109) separated by spaces, where ai is the number to give to i-th student. Any two adjacent elements, including n and 1, must differ by 1 or - 1. The hacked solution will not have direct access to the sequence ai. Examples Input 8 <span class="tex-span"></span> 2 <span class="tex-span"></span> 2 Output <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 8 <span class="tex-span"></span> ! 4 Input 6 <span class="tex-span"></span> 1 <span class="tex-span"></span> 2 <span class="tex-span"></span> 3 <span class="tex-span"></span> 2 <span class="tex-span"></span> 1 <span class="tex-span"></span> 0 Output <span class="tex-span"></span> ? 1 <span class="tex-span"></span> ? 2 <span class="tex-span"></span> ? 3 <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 5 <span class="tex-span"></span> ? 6 <span class="tex-span"></span> ! -1 Note Input-output in statements illustrates example interaction. In the first sample the selected sequence is 1, 2, 1, 2, 3, 4, 3, 2 In the second sample the selection sequence is 1, 2, 3, 2, 1, 0. Submitted Solution: ``` def inp(): return input() def sep(): return map(int, inp().strip().split(" ")) def lis(): return list(sep()) def N(): return int(inp()) def testcase(t): for p in range(t): solve() def solve(): n=N() diff=n//2 print("?",1,flush=True) x1=N() print("?",1+diff,flush=True) x2=N() if x1==x2: print("!",1,flush=True) return d1=x2-x1 l=1 h=1+ diff i=2 while(i<=60): m=(l+h)//2 print("?",m, flush=True) x1 = N() print("?",m + diff, flush=True) x2 = N() if x1 == x2: print("!",m,flush=True) return d2=x2-x1 if d2*d1>0: l=m else: h=m d1=d2 i+=1 print("!",-1,flush=True) return solve() # testcase(int(inp())) ``` No
85,018
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an interactive problem. Imur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant i and participant i + 1 (1 ≤ i ≤ n - 1) are adjacent, as well as participant n and participant 1. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice. As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers i and <image> sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists. You can ask questions of form «which number was received by student i?», and the goal is to determine whether the desired pair exists in no more than 60 questions. Input At the beginning the even integer n (2 ≤ n ≤ 100 000) is given — the total number of students. You are allowed to ask no more than 60 questions. Output To ask the question about the student i (1 ≤ i ≤ n), you should print «? i». Then from standard output you can read the number ai received by student i ( - 109 ≤ ai ≤ 109). When you find the desired pair, you should print «! i», where i is any student who belongs to the pair (1 ≤ i ≤ n). If you determined that such pair doesn't exist, you should output «! -1». In both cases you should immediately terminate the program. The query that contains your answer is not counted towards the limit of 60 queries. Please make sure to flush the standard output after each command. For example, in C++ use function fflush(stdout), in Java call System.out.flush(), in Pascal use flush(output) and stdout.flush() for Python language. Hacking Use the following format for hacking: In the first line, print one even integer n (2 ≤ n ≤ 100 000) — the total number of students. In the second line print n integers ai ( - 109 ≤ ai ≤ 109) separated by spaces, where ai is the number to give to i-th student. Any two adjacent elements, including n and 1, must differ by 1 or - 1. The hacked solution will not have direct access to the sequence ai. Examples Input 8 <span class="tex-span"></span> 2 <span class="tex-span"></span> 2 Output <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 8 <span class="tex-span"></span> ! 4 Input 6 <span class="tex-span"></span> 1 <span class="tex-span"></span> 2 <span class="tex-span"></span> 3 <span class="tex-span"></span> 2 <span class="tex-span"></span> 1 <span class="tex-span"></span> 0 Output <span class="tex-span"></span> ? 1 <span class="tex-span"></span> ? 2 <span class="tex-span"></span> ? 3 <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 5 <span class="tex-span"></span> ? 6 <span class="tex-span"></span> ! -1 Note Input-output in statements illustrates example interaction. In the first sample the selected sequence is 1, 2, 1, 2, 3, 4, 3, 2 In the second sample the selection sequence is 1, 2, 3, 2, 1, 0. Submitted Solution: ``` # this sequence is a bit scary # 8 # 1 2 3 2 3 2 1 0 import sys #sys.stdin=open("data.txt") #input=sys.stdin.readline got=[10**18]*100005 def getnum(i): if got[i]==10**18: print(i) sys.stdout.flush() got[i]=int(input()) return got[i] n=int(input()) if n%4==2: # the opposite person has a different parity print("! -1") else: lo=1 hi=n//2+1 t1=getnum(lo) t2=getnum(hi) lo2=t1-t2 hi2=t2-t1 if lo2==0: print("! 1") else: # binary search # let's hope that 1 <= mid <= n/2 while lo<hi: mid=(lo+hi)//2 #print(lo,hi,mid) mid2=getnum(mid)-getnum(mid+n//2) if mid2==0: print("! %d"%mid) break if (lo2>0) == (mid2>0): lo=mid+1 else: hi=mid-1 else: print("! %d"%lo) sys.stdout.flush() ``` No
85,019
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an interactive problem. Imur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant i and participant i + 1 (1 ≤ i ≤ n - 1) are adjacent, as well as participant n and participant 1. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice. As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers i and <image> sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists. You can ask questions of form «which number was received by student i?», and the goal is to determine whether the desired pair exists in no more than 60 questions. Input At the beginning the even integer n (2 ≤ n ≤ 100 000) is given — the total number of students. You are allowed to ask no more than 60 questions. Output To ask the question about the student i (1 ≤ i ≤ n), you should print «? i». Then from standard output you can read the number ai received by student i ( - 109 ≤ ai ≤ 109). When you find the desired pair, you should print «! i», where i is any student who belongs to the pair (1 ≤ i ≤ n). If you determined that such pair doesn't exist, you should output «! -1». In both cases you should immediately terminate the program. The query that contains your answer is not counted towards the limit of 60 queries. Please make sure to flush the standard output after each command. For example, in C++ use function fflush(stdout), in Java call System.out.flush(), in Pascal use flush(output) and stdout.flush() for Python language. Hacking Use the following format for hacking: In the first line, print one even integer n (2 ≤ n ≤ 100 000) — the total number of students. In the second line print n integers ai ( - 109 ≤ ai ≤ 109) separated by spaces, where ai is the number to give to i-th student. Any two adjacent elements, including n and 1, must differ by 1 or - 1. The hacked solution will not have direct access to the sequence ai. Examples Input 8 <span class="tex-span"></span> 2 <span class="tex-span"></span> 2 Output <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 8 <span class="tex-span"></span> ! 4 Input 6 <span class="tex-span"></span> 1 <span class="tex-span"></span> 2 <span class="tex-span"></span> 3 <span class="tex-span"></span> 2 <span class="tex-span"></span> 1 <span class="tex-span"></span> 0 Output <span class="tex-span"></span> ? 1 <span class="tex-span"></span> ? 2 <span class="tex-span"></span> ? 3 <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 5 <span class="tex-span"></span> ? 6 <span class="tex-span"></span> ! -1 Note Input-output in statements illustrates example interaction. In the first sample the selected sequence is 1, 2, 1, 2, 3, 4, 3, 2 In the second sample the selection sequence is 1, 2, 3, 2, 1, 0. Submitted Solution: ``` import sys n = int(input()) print('? 0') sys.stdout.flush() b0 = int(input()) print('? ' + n//2) sys.stdout.flush() bn2 = int(input()) bn2 -= b0 b0 = -bn2 if (bn2) % 2 == 1: print('! -1') sys.stdout.flush() else: l = 0; r = n//2 while bn2 != 0 or b0 != 0: m = (r-l)//2 print('? '+m) sys.stdout.flush() c = int(input()) print('? '+(m+n//2)) sys.stdout.flush() d = int(input()) if c-d<0 and b0<0 or c-d>0 and b0>0: b0 = c-d l = m else: bn2 = c-d r = m if bn2 == 0: print('! '+r) sys.stdout.flush() else: print('! '+l) sys.stdout.flush() ``` No
85,020
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an interactive problem. Imur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant i and participant i + 1 (1 ≤ i ≤ n - 1) are adjacent, as well as participant n and participant 1. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice. As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers i and <image> sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists. You can ask questions of form «which number was received by student i?», and the goal is to determine whether the desired pair exists in no more than 60 questions. Input At the beginning the even integer n (2 ≤ n ≤ 100 000) is given — the total number of students. You are allowed to ask no more than 60 questions. Output To ask the question about the student i (1 ≤ i ≤ n), you should print «? i». Then from standard output you can read the number ai received by student i ( - 109 ≤ ai ≤ 109). When you find the desired pair, you should print «! i», where i is any student who belongs to the pair (1 ≤ i ≤ n). If you determined that such pair doesn't exist, you should output «! -1». In both cases you should immediately terminate the program. The query that contains your answer is not counted towards the limit of 60 queries. Please make sure to flush the standard output after each command. For example, in C++ use function fflush(stdout), in Java call System.out.flush(), in Pascal use flush(output) and stdout.flush() for Python language. Hacking Use the following format for hacking: In the first line, print one even integer n (2 ≤ n ≤ 100 000) — the total number of students. In the second line print n integers ai ( - 109 ≤ ai ≤ 109) separated by spaces, where ai is the number to give to i-th student. Any two adjacent elements, including n and 1, must differ by 1 or - 1. The hacked solution will not have direct access to the sequence ai. Examples Input 8 <span class="tex-span"></span> 2 <span class="tex-span"></span> 2 Output <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 8 <span class="tex-span"></span> ! 4 Input 6 <span class="tex-span"></span> 1 <span class="tex-span"></span> 2 <span class="tex-span"></span> 3 <span class="tex-span"></span> 2 <span class="tex-span"></span> 1 <span class="tex-span"></span> 0 Output <span class="tex-span"></span> ? 1 <span class="tex-span"></span> ? 2 <span class="tex-span"></span> ? 3 <span class="tex-span"></span> ? 4 <span class="tex-span"></span> ? 5 <span class="tex-span"></span> ? 6 <span class="tex-span"></span> ! -1 Note Input-output in statements illustrates example interaction. In the first sample the selected sequence is 1, 2, 1, 2, 3, 4, 3, 2 In the second sample the selection sequence is 1, 2, 3, 2, 1, 0. Submitted Solution: ``` import sys def ask(x): print(x) sys.stdout.flush() x=int(input()) return x n=int(input()) if (n>>1)&1: print('! -1') sys.exit() l=1 r=n while l<r: mid=(l+r)>>1 if ask(mid)>=ask((mid+n//2)%n): r=mid else: l=mid+1 print('! %d'%l) ``` No
85,021
Provide tags and a correct Python 3 solution for this coding contest problem. There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available. Let k be the maximum number of people sitting on one bench after additional m people came to the park. Calculate the minimum possible k and the maximum possible k. Nobody leaves the taken seat during the whole process. Input The first line contains a single integer n (1 ≤ n ≤ 100) — the number of benches in the park. The second line contains a single integer m (1 ≤ m ≤ 10 000) — the number of people additionally coming to the park. Each of the next n lines contains a single integer a_i (1 ≤ a_i ≤ 100) — the initial number of people on the i-th bench. Output Print the minimum possible k and the maximum possible k, where k is the maximum number of people sitting on one bench after additional m people came to the park. Examples Input 4 6 1 1 1 1 Output 3 7 Input 1 10 5 Output 15 15 Input 3 6 1 6 5 Output 6 12 Input 3 7 1 6 5 Output 7 13 Note In the first example, each of four benches is occupied by a single person. The minimum k is 3. For example, it is possible to achieve if two newcomers occupy the first bench, one occupies the second bench, one occupies the third bench, and two remaining — the fourth bench. The maximum k is 7. That requires all six new people to occupy the same bench. The second example has its minimum k equal to 15 and maximum k equal to 15, as there is just a single bench in the park and all 10 people will occupy it. Tags: binary search, implementation Correct Solution: ``` n = int(input().strip()) m = int(input().strip()) max = 0 total = 0 for i in range(n): a = int(input().strip()) if (a > max): max = a total += a if (total + m <= n * max): print(max) else: print((total+m-1)//n+1) print(m + max) ```
85,022
Provide tags and a correct Python 3 solution for this coding contest problem. There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available. Let k be the maximum number of people sitting on one bench after additional m people came to the park. Calculate the minimum possible k and the maximum possible k. Nobody leaves the taken seat during the whole process. Input The first line contains a single integer n (1 ≤ n ≤ 100) — the number of benches in the park. The second line contains a single integer m (1 ≤ m ≤ 10 000) — the number of people additionally coming to the park. Each of the next n lines contains a single integer a_i (1 ≤ a_i ≤ 100) — the initial number of people on the i-th bench. Output Print the minimum possible k and the maximum possible k, where k is the maximum number of people sitting on one bench after additional m people came to the park. Examples Input 4 6 1 1 1 1 Output 3 7 Input 1 10 5 Output 15 15 Input 3 6 1 6 5 Output 6 12 Input 3 7 1 6 5 Output 7 13 Note In the first example, each of four benches is occupied by a single person. The minimum k is 3. For example, it is possible to achieve if two newcomers occupy the first bench, one occupies the second bench, one occupies the third bench, and two remaining — the fourth bench. The maximum k is 7. That requires all six new people to occupy the same bench. The second example has its minimum k equal to 15 and maximum k equal to 15, as there is just a single bench in the park and all 10 people will occupy it. Tags: binary search, implementation Correct Solution: ``` import math for i in range(1): n=int(input()) m=int(input()) l=[] s=0 for i in range(n): k=int(input()) s+=k l.append(k) print(max((m+s+n-1)//n,max(l)),(max(l)+m)) ```
85,023
Provide tags and a correct Python 3 solution for this coding contest problem. There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available. Let k be the maximum number of people sitting on one bench after additional m people came to the park. Calculate the minimum possible k and the maximum possible k. Nobody leaves the taken seat during the whole process. Input The first line contains a single integer n (1 ≤ n ≤ 100) — the number of benches in the park. The second line contains a single integer m (1 ≤ m ≤ 10 000) — the number of people additionally coming to the park. Each of the next n lines contains a single integer a_i (1 ≤ a_i ≤ 100) — the initial number of people on the i-th bench. Output Print the minimum possible k and the maximum possible k, where k is the maximum number of people sitting on one bench after additional m people came to the park. Examples Input 4 6 1 1 1 1 Output 3 7 Input 1 10 5 Output 15 15 Input 3 6 1 6 5 Output 6 12 Input 3 7 1 6 5 Output 7 13 Note In the first example, each of four benches is occupied by a single person. The minimum k is 3. For example, it is possible to achieve if two newcomers occupy the first bench, one occupies the second bench, one occupies the third bench, and two remaining — the fourth bench. The maximum k is 7. That requires all six new people to occupy the same bench. The second example has its minimum k equal to 15 and maximum k equal to 15, as there is just a single bench in the park and all 10 people will occupy it. Tags: binary search, implementation Correct Solution: ``` from collections import defaultdict, deque, Counter from sys import stdin, stdout from heapq import heappush, heappop import math import io import os import math import bisect #?############################################################ def isPrime(x): for i in range(2, x): if i*i > x: break if (x % i == 0): return False return True #?############################################################ def ncr(n, r, p): num = den = 1 for i in range(r): num = (num * (n - i)) % p den = (den * (i + 1)) % p return (num * pow(den, p - 2, p)) % p #?############################################################ def primeFactors(n): l = [] while n % 2 == 0: l.append(2) n = n / 2 for i in range(3, int(math.sqrt(n))+1, 2): while n % i == 0: l.append(int(i)) n = n / i if n > 2: l.append(n) return list(set(l)) #?############################################################ def power(x, y, p): res = 1 x = x % p if (x == 0): return 0 while (y > 0): if ((y & 1) == 1): res = (res * x) % p y = y >> 1 x = (x * x) % p return res #?############################################################ 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 return prime #?############################################################ def digits(n): c = 0 while (n > 0): n //= 10 c += 1 return c #?############################################################ def ceil(n, x): if (n % x == 0): return n//x return n//x+1 #?############################################################ def mapin(): return map(int, input().split()) #?############################################################ # input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline # python3 15.py<in>op input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n =int(input()) m =int(input()) l = [] for i in range(n): a = int(input()) l.append(a) l.sort() a = l[-1]+m b = l[-1]*n - sum(l) if(b >= m): print(l[-1], a) else: m-=b c = l[-1] if(m%n == 0): print(c+ m//n, a) else: print(c+ 1+ m//n, a) ```
85,024
Provide tags and a correct Python 3 solution for this coding contest problem. There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available. Let k be the maximum number of people sitting on one bench after additional m people came to the park. Calculate the minimum possible k and the maximum possible k. Nobody leaves the taken seat during the whole process. Input The first line contains a single integer n (1 ≤ n ≤ 100) — the number of benches in the park. The second line contains a single integer m (1 ≤ m ≤ 10 000) — the number of people additionally coming to the park. Each of the next n lines contains a single integer a_i (1 ≤ a_i ≤ 100) — the initial number of people on the i-th bench. Output Print the minimum possible k and the maximum possible k, where k is the maximum number of people sitting on one bench after additional m people came to the park. Examples Input 4 6 1 1 1 1 Output 3 7 Input 1 10 5 Output 15 15 Input 3 6 1 6 5 Output 6 12 Input 3 7 1 6 5 Output 7 13 Note In the first example, each of four benches is occupied by a single person. The minimum k is 3. For example, it is possible to achieve if two newcomers occupy the first bench, one occupies the second bench, one occupies the third bench, and two remaining — the fourth bench. The maximum k is 7. That requires all six new people to occupy the same bench. The second example has its minimum k equal to 15 and maximum k equal to 15, as there is just a single bench in the park and all 10 people will occupy it. Tags: binary search, implementation Correct Solution: ``` def indmin(m): a=min(m) for i in range(len(m)): if m[i] == a: return i a=int(input()) b=int(input()) m=[] ind=0 d=0 for i in range(a): m.append(int(input())) c=list(m) for i in range(b): c[indmin(c)]+=1 d=max(m) + b print(max(c),d) ```
85,025
Provide tags and a correct Python 3 solution for this coding contest problem. There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available. Let k be the maximum number of people sitting on one bench after additional m people came to the park. Calculate the minimum possible k and the maximum possible k. Nobody leaves the taken seat during the whole process. Input The first line contains a single integer n (1 ≤ n ≤ 100) — the number of benches in the park. The second line contains a single integer m (1 ≤ m ≤ 10 000) — the number of people additionally coming to the park. Each of the next n lines contains a single integer a_i (1 ≤ a_i ≤ 100) — the initial number of people on the i-th bench. Output Print the minimum possible k and the maximum possible k, where k is the maximum number of people sitting on one bench after additional m people came to the park. Examples Input 4 6 1 1 1 1 Output 3 7 Input 1 10 5 Output 15 15 Input 3 6 1 6 5 Output 6 12 Input 3 7 1 6 5 Output 7 13 Note In the first example, each of four benches is occupied by a single person. The minimum k is 3. For example, it is possible to achieve if two newcomers occupy the first bench, one occupies the second bench, one occupies the third bench, and two remaining — the fourth bench. The maximum k is 7. That requires all six new people to occupy the same bench. The second example has its minimum k equal to 15 and maximum k equal to 15, as there is just a single bench in the park and all 10 people will occupy it. Tags: binary search, implementation Correct Solution: ``` n = int(input()) m = int(input()) bench = [int(input()) for i in range(n)] mx = max(bench) + m for i in range(m): bench[bench.index(min(bench))] += 1 print(max(bench), mx) ```
85,026
Provide tags and a correct Python 3 solution for this coding contest problem. There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available. Let k be the maximum number of people sitting on one bench after additional m people came to the park. Calculate the minimum possible k and the maximum possible k. Nobody leaves the taken seat during the whole process. Input The first line contains a single integer n (1 ≤ n ≤ 100) — the number of benches in the park. The second line contains a single integer m (1 ≤ m ≤ 10 000) — the number of people additionally coming to the park. Each of the next n lines contains a single integer a_i (1 ≤ a_i ≤ 100) — the initial number of people on the i-th bench. Output Print the minimum possible k and the maximum possible k, where k is the maximum number of people sitting on one bench after additional m people came to the park. Examples Input 4 6 1 1 1 1 Output 3 7 Input 1 10 5 Output 15 15 Input 3 6 1 6 5 Output 6 12 Input 3 7 1 6 5 Output 7 13 Note In the first example, each of four benches is occupied by a single person. The minimum k is 3. For example, it is possible to achieve if two newcomers occupy the first bench, one occupies the second bench, one occupies the third bench, and two remaining — the fourth bench. The maximum k is 7. That requires all six new people to occupy the same bench. The second example has its minimum k equal to 15 and maximum k equal to 15, as there is just a single bench in the park and all 10 people will occupy it. Tags: binary search, implementation Correct Solution: ``` #510_A n = int(input()) p = int(input()) ms = [] for i in range(0, n): m = int(input()) ms.append(m) mx = max(ms) m2 = mx + p diffs = sum([mx - i for i in ms]) if p < diffs: m1 = mx else: m1 = (p - diffs) if m1 % n != 0: m1 = m1 // n + 1 else: m1 = m1 // n m1 += mx print(m1, m2) ```
85,027
Provide tags and a correct Python 3 solution for this coding contest problem. There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available. Let k be the maximum number of people sitting on one bench after additional m people came to the park. Calculate the minimum possible k and the maximum possible k. Nobody leaves the taken seat during the whole process. Input The first line contains a single integer n (1 ≤ n ≤ 100) — the number of benches in the park. The second line contains a single integer m (1 ≤ m ≤ 10 000) — the number of people additionally coming to the park. Each of the next n lines contains a single integer a_i (1 ≤ a_i ≤ 100) — the initial number of people on the i-th bench. Output Print the minimum possible k and the maximum possible k, where k is the maximum number of people sitting on one bench after additional m people came to the park. Examples Input 4 6 1 1 1 1 Output 3 7 Input 1 10 5 Output 15 15 Input 3 6 1 6 5 Output 6 12 Input 3 7 1 6 5 Output 7 13 Note In the first example, each of four benches is occupied by a single person. The minimum k is 3. For example, it is possible to achieve if two newcomers occupy the first bench, one occupies the second bench, one occupies the third bench, and two remaining — the fourth bench. The maximum k is 7. That requires all six new people to occupy the same bench. The second example has its minimum k equal to 15 and maximum k equal to 15, as there is just a single bench in the park and all 10 people will occupy it. Tags: binary search, implementation Correct Solution: ``` import math n = int(input()) m = int(input()) abc = m a = [] ans = 0 for i in range(n): x = int(input()) a.append(x) a.sort() for j in range(len(a)): ans += a[-1] - a[j] if j == len(a) - 1: if ans >= m: ans = max(a) else: ans = math.ceil((m - ans) / n) + max(a) print(ans, max(a) + abc) ```
85,028
Provide tags and a correct Python 3 solution for this coding contest problem. There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available. Let k be the maximum number of people sitting on one bench after additional m people came to the park. Calculate the minimum possible k and the maximum possible k. Nobody leaves the taken seat during the whole process. Input The first line contains a single integer n (1 ≤ n ≤ 100) — the number of benches in the park. The second line contains a single integer m (1 ≤ m ≤ 10 000) — the number of people additionally coming to the park. Each of the next n lines contains a single integer a_i (1 ≤ a_i ≤ 100) — the initial number of people on the i-th bench. Output Print the minimum possible k and the maximum possible k, where k is the maximum number of people sitting on one bench after additional m people came to the park. Examples Input 4 6 1 1 1 1 Output 3 7 Input 1 10 5 Output 15 15 Input 3 6 1 6 5 Output 6 12 Input 3 7 1 6 5 Output 7 13 Note In the first example, each of four benches is occupied by a single person. The minimum k is 3. For example, it is possible to achieve if two newcomers occupy the first bench, one occupies the second bench, one occupies the third bench, and two remaining — the fourth bench. The maximum k is 7. That requires all six new people to occupy the same bench. The second example has its minimum k equal to 15 and maximum k equal to 15, as there is just a single bench in the park and all 10 people will occupy it. Tags: binary search, implementation Correct Solution: ``` def inp(): return list(map(int,input().split())) n,=inp() m,=inp() a = [int(input()) for i in range(n)] s=sum(a) mx=max(a) mi= max([mx, int((s+m+n-1)/n)]) mx= mx + m print(mi,mx) ```
85,029
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available. Let k be the maximum number of people sitting on one bench after additional m people came to the park. Calculate the minimum possible k and the maximum possible k. Nobody leaves the taken seat during the whole process. Input The first line contains a single integer n (1 ≤ n ≤ 100) — the number of benches in the park. The second line contains a single integer m (1 ≤ m ≤ 10 000) — the number of people additionally coming to the park. Each of the next n lines contains a single integer a_i (1 ≤ a_i ≤ 100) — the initial number of people on the i-th bench. Output Print the minimum possible k and the maximum possible k, where k is the maximum number of people sitting on one bench after additional m people came to the park. Examples Input 4 6 1 1 1 1 Output 3 7 Input 1 10 5 Output 15 15 Input 3 6 1 6 5 Output 6 12 Input 3 7 1 6 5 Output 7 13 Note In the first example, each of four benches is occupied by a single person. The minimum k is 3. For example, it is possible to achieve if two newcomers occupy the first bench, one occupies the second bench, one occupies the third bench, and two remaining — the fourth bench. The maximum k is 7. That requires all six new people to occupy the same bench. The second example has its minimum k equal to 15 and maximum k equal to 15, as there is just a single bench in the park and all 10 people will occupy it. Submitted Solution: ``` def mi(): return map(int, input().split()) n = int(input()) m = int(input()) a = [0]*n for i in range(n): a[i] = int(input()) ma = max(a) maxk = ma+m a.sort() import math for i in a: m-=min(m,ma-i) if m==0: print (ma, maxk) else: print (ma+math.ceil(m/n), maxk) ``` Yes
85,030
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available. Let k be the maximum number of people sitting on one bench after additional m people came to the park. Calculate the minimum possible k and the maximum possible k. Nobody leaves the taken seat during the whole process. Input The first line contains a single integer n (1 ≤ n ≤ 100) — the number of benches in the park. The second line contains a single integer m (1 ≤ m ≤ 10 000) — the number of people additionally coming to the park. Each of the next n lines contains a single integer a_i (1 ≤ a_i ≤ 100) — the initial number of people on the i-th bench. Output Print the minimum possible k and the maximum possible k, where k is the maximum number of people sitting on one bench after additional m people came to the park. Examples Input 4 6 1 1 1 1 Output 3 7 Input 1 10 5 Output 15 15 Input 3 6 1 6 5 Output 6 12 Input 3 7 1 6 5 Output 7 13 Note In the first example, each of four benches is occupied by a single person. The minimum k is 3. For example, it is possible to achieve if two newcomers occupy the first bench, one occupies the second bench, one occupies the third bench, and two remaining — the fourth bench. The maximum k is 7. That requires all six new people to occupy the same bench. The second example has its minimum k equal to 15 and maximum k equal to 15, as there is just a single bench in the park and all 10 people will occupy it. Submitted Solution: ``` from math import ceil n = int(input().strip()) m = int(input().strip()) k = [] for i in range(n): ai = int(input().strip()) k.append(ai) if n==1: print(m+ai,m+ai) else: mx = max(k) l = max(k)+m ''' ans = max(k)*n-m if ans>: print(m,l) else: print(abs(m-n)+max(k),l) ''' h = max(mx,ceil((sum(k)+m)/n)) print(h,l) ``` Yes
85,031
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available. Let k be the maximum number of people sitting on one bench after additional m people came to the park. Calculate the minimum possible k and the maximum possible k. Nobody leaves the taken seat during the whole process. Input The first line contains a single integer n (1 ≤ n ≤ 100) — the number of benches in the park. The second line contains a single integer m (1 ≤ m ≤ 10 000) — the number of people additionally coming to the park. Each of the next n lines contains a single integer a_i (1 ≤ a_i ≤ 100) — the initial number of people on the i-th bench. Output Print the minimum possible k and the maximum possible k, where k is the maximum number of people sitting on one bench after additional m people came to the park. Examples Input 4 6 1 1 1 1 Output 3 7 Input 1 10 5 Output 15 15 Input 3 6 1 6 5 Output 6 12 Input 3 7 1 6 5 Output 7 13 Note In the first example, each of four benches is occupied by a single person. The minimum k is 3. For example, it is possible to achieve if two newcomers occupy the first bench, one occupies the second bench, one occupies the third bench, and two remaining — the fourth bench. The maximum k is 7. That requires all six new people to occupy the same bench. The second example has its minimum k equal to 15 and maximum k equal to 15, as there is just a single bench in the park and all 10 people will occupy it. Submitted Solution: ``` n=int(input()) m=int(input()) l=[int(input()) for i in range(n)] print(max((sum(l)+n+m-1)//n,max(l)),max(l)+m) ``` Yes
85,032
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available. Let k be the maximum number of people sitting on one bench after additional m people came to the park. Calculate the minimum possible k and the maximum possible k. Nobody leaves the taken seat during the whole process. Input The first line contains a single integer n (1 ≤ n ≤ 100) — the number of benches in the park. The second line contains a single integer m (1 ≤ m ≤ 10 000) — the number of people additionally coming to the park. Each of the next n lines contains a single integer a_i (1 ≤ a_i ≤ 100) — the initial number of people on the i-th bench. Output Print the minimum possible k and the maximum possible k, where k is the maximum number of people sitting on one bench after additional m people came to the park. Examples Input 4 6 1 1 1 1 Output 3 7 Input 1 10 5 Output 15 15 Input 3 6 1 6 5 Output 6 12 Input 3 7 1 6 5 Output 7 13 Note In the first example, each of four benches is occupied by a single person. The minimum k is 3. For example, it is possible to achieve if two newcomers occupy the first bench, one occupies the second bench, one occupies the third bench, and two remaining — the fourth bench. The maximum k is 7. That requires all six new people to occupy the same bench. The second example has its minimum k equal to 15 and maximum k equal to 15, as there is just a single bench in the park and all 10 people will occupy it. Submitted Solution: ``` from math import * n=int(input()) m=int(input()) l=[] for u in range(n): l.append(int(input())) s=sum(l)+m c=ceil(s/n) q=max(l) k=0 for i in range(n): f=l[i]+m if(f>k): k=f if(c>=q): print(c,k) else: print(q,k) ``` Yes
85,033
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available. Let k be the maximum number of people sitting on one bench after additional m people came to the park. Calculate the minimum possible k and the maximum possible k. Nobody leaves the taken seat during the whole process. Input The first line contains a single integer n (1 ≤ n ≤ 100) — the number of benches in the park. The second line contains a single integer m (1 ≤ m ≤ 10 000) — the number of people additionally coming to the park. Each of the next n lines contains a single integer a_i (1 ≤ a_i ≤ 100) — the initial number of people on the i-th bench. Output Print the minimum possible k and the maximum possible k, where k is the maximum number of people sitting on one bench after additional m people came to the park. Examples Input 4 6 1 1 1 1 Output 3 7 Input 1 10 5 Output 15 15 Input 3 6 1 6 5 Output 6 12 Input 3 7 1 6 5 Output 7 13 Note In the first example, each of four benches is occupied by a single person. The minimum k is 3. For example, it is possible to achieve if two newcomers occupy the first bench, one occupies the second bench, one occupies the third bench, and two remaining — the fourth bench. The maximum k is 7. That requires all six new people to occupy the same bench. The second example has its minimum k equal to 15 and maximum k equal to 15, as there is just a single bench in the park and all 10 people will occupy it. Submitted Solution: ``` import sys #sys.stdin=open('in','r') #sys.stdout=open('out','w') #import math #import queue #import random #sys.setrecursionlimit(int(1e6)) input = sys.stdin.readline ############ ---- USER DEFINED INPUT FUNCTIONS ---- ############ def inp(): return(int(input())) def inara(): return(list(map(int,input().split()))) def insr(): s = input() return(list(s[:len(s) - 1])) def invr(): return(map(int,input().split())) ################################################################ ############ ---- THE ACTUAL CODE STARTS BELOW ---- ############ n=inp() m=inp() a=[0]*n for i in range(n): a[i]=inp() mini=min(a) hi=m lo=mini while hi>=lo: mid=(hi+lo)//2 temp=m for x in a: if x<=mid: temp-=min(temp,mid-x) if temp==0: mini=mid hi=mid-1 else: lo=mid+1 maxi=max(a)+m print(mini,maxi) ``` No
85,034
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available. Let k be the maximum number of people sitting on one bench after additional m people came to the park. Calculate the minimum possible k and the maximum possible k. Nobody leaves the taken seat during the whole process. Input The first line contains a single integer n (1 ≤ n ≤ 100) — the number of benches in the park. The second line contains a single integer m (1 ≤ m ≤ 10 000) — the number of people additionally coming to the park. Each of the next n lines contains a single integer a_i (1 ≤ a_i ≤ 100) — the initial number of people on the i-th bench. Output Print the minimum possible k and the maximum possible k, where k is the maximum number of people sitting on one bench after additional m people came to the park. Examples Input 4 6 1 1 1 1 Output 3 7 Input 1 10 5 Output 15 15 Input 3 6 1 6 5 Output 6 12 Input 3 7 1 6 5 Output 7 13 Note In the first example, each of four benches is occupied by a single person. The minimum k is 3. For example, it is possible to achieve if two newcomers occupy the first bench, one occupies the second bench, one occupies the third bench, and two remaining — the fourth bench. The maximum k is 7. That requires all six new people to occupy the same bench. The second example has its minimum k equal to 15 and maximum k equal to 15, as there is just a single bench in the park and all 10 people will occupy it. Submitted Solution: ``` x=int(input()) a=int(input()) l=[] for _ in range(x): d=int(input()) l+=[d] max=max(l)+a s=a//x if a%x==0: print(min(l)+s,max) else: print(min(l)+s+1,max) ``` No
85,035
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available. Let k be the maximum number of people sitting on one bench after additional m people came to the park. Calculate the minimum possible k and the maximum possible k. Nobody leaves the taken seat during the whole process. Input The first line contains a single integer n (1 ≤ n ≤ 100) — the number of benches in the park. The second line contains a single integer m (1 ≤ m ≤ 10 000) — the number of people additionally coming to the park. Each of the next n lines contains a single integer a_i (1 ≤ a_i ≤ 100) — the initial number of people on the i-th bench. Output Print the minimum possible k and the maximum possible k, where k is the maximum number of people sitting on one bench after additional m people came to the park. Examples Input 4 6 1 1 1 1 Output 3 7 Input 1 10 5 Output 15 15 Input 3 6 1 6 5 Output 6 12 Input 3 7 1 6 5 Output 7 13 Note In the first example, each of four benches is occupied by a single person. The minimum k is 3. For example, it is possible to achieve if two newcomers occupy the first bench, one occupies the second bench, one occupies the third bench, and two remaining — the fourth bench. The maximum k is 7. That requires all six new people to occupy the same bench. The second example has its minimum k equal to 15 and maximum k equal to 15, as there is just a single bench in the park and all 10 people will occupy it. Submitted Solution: ``` #------------------------------------------------------------------------------- #http://codeforces.com/contest/1042/problem/A #------------------------------------------------------------------------------- def main(): n = int(input()) m = int(input()) a = [] for i in range(n): a.append(int(input())) M = max(a) MAX = M + m for i in range(n): while(a[i] < M): if m < 0: break a[i]+= 1 m-=1 average = m//n m = m%n if average: for i in range(n): a[i]+=average m-=1 for i in range(n): if not m: break a[i]+=1 m-=1 MIN = max(a) print(MIN) print(MAX) if __name__ == '__main__': main() ``` No
85,036
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available. Let k be the maximum number of people sitting on one bench after additional m people came to the park. Calculate the minimum possible k and the maximum possible k. Nobody leaves the taken seat during the whole process. Input The first line contains a single integer n (1 ≤ n ≤ 100) — the number of benches in the park. The second line contains a single integer m (1 ≤ m ≤ 10 000) — the number of people additionally coming to the park. Each of the next n lines contains a single integer a_i (1 ≤ a_i ≤ 100) — the initial number of people on the i-th bench. Output Print the minimum possible k and the maximum possible k, where k is the maximum number of people sitting on one bench after additional m people came to the park. Examples Input 4 6 1 1 1 1 Output 3 7 Input 1 10 5 Output 15 15 Input 3 6 1 6 5 Output 6 12 Input 3 7 1 6 5 Output 7 13 Note In the first example, each of four benches is occupied by a single person. The minimum k is 3. For example, it is possible to achieve if two newcomers occupy the first bench, one occupies the second bench, one occupies the third bench, and two remaining — the fourth bench. The maximum k is 7. That requires all six new people to occupy the same bench. The second example has its minimum k equal to 15 and maximum k equal to 15, as there is just a single bench in the park and all 10 people will occupy it. Submitted Solution: ``` n1 = input() n = int(n1) m1 = input() m = int(m1) benches = [] i = 0 while i < n: benches.append(input()) i = i + 1 maxi = int(max(benches)) + m i = 0 while i < n: #przerobione m m = m - int(abs(int(benches[i]) - int(max(benches)))) i += 1 mini = int(max(benches)) + (m // n) if m % n != 0: mini += 1 print(f"{mini} {maxi}") ``` No
85,037
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. n players are going to play a rock-paper-scissors tournament. As you probably know, in a one-on-one match of rock-paper-scissors, two players choose their shapes independently. The outcome is then determined depending on the chosen shapes: "paper" beats "rock", "rock" beats "scissors", "scissors" beat "paper", and two equal shapes result in a draw. At the start of the tournament all players will stand in a row, with their numbers increasing from 1 for the leftmost player, to n for the rightmost player. Each player has a pre-chosen shape that they will use in every game throughout the tournament. Here's how the tournament is conducted: * If there is only one player left, he is declared the champion. * Otherwise, two adjacent players in the row are chosen arbitrarily, and they play the next match. The losing player is eliminated from the tournament and leaves his place in the row (with his former neighbours becoming adjacent). If the game is a draw, the losing player is determined by a coin toss. The organizers are informed about all players' favoured shapes. They wish to find out the total number of players who have a chance of becoming the tournament champion (that is, there is a suitable way to choose the order of the games and manipulate the coin tosses). However, some players are still optimizing their strategy, and can inform the organizers about their new shapes. Can you find the number of possible champions after each such request? Input The first line contains two integers n and q — the number of players and requests respectively (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ q ≤ 2 ⋅ 10^5). The second line contains a string of n characters. The i-th of these characters is "R", "P", or "S" if the player i was going to play "rock", "paper", or "scissors" before all requests respectively. The following q lines describe the requests. The j-th of these lines contain an integer p_j and a character c_j meaning that the player p_j is going to use the shape described by the character c_j from this moment (1 ≤ p_j ≤ n). Output Print q + 1 integers r_0, …, r_q, where r_k is the number of possible champions after processing k requests. Example Input 3 5 RPS 1 S 2 R 3 P 1 P 2 P Output 2 2 1 2 2 3 Submitted Solution: ``` b = input().split() b = [int(i) for i in b] n, m = b pl = list(input()) count = 0 count1 = 0 count2 = 0 cs = [] if 'P' in pl and 'R' in pl and 'S' in pl: for i in pl: if i == 'R': count1 += 1 elif i == 'P': count2 += 1 if count2 >= count1: for i in pl: if i == 'R' or i == 'S': count += 1 cs.append(count) else: for i in pl: if i == 'R': count += 1 cs.append(count) count = 0 count1 = 0 count2 = 0 elif (('P' not in pl and 'S' not in pl) or ('P' not in pl and 'R' not in pl) or ('R' not in pl and 'S' not in pl)): cs.append(n) elif 'P' not in pl: for i in pl: if i == 'R': count += 1 cs.append(count) count = 0 elif 'S' not in pl: for i in pl: if i == 'P': count += 1 cs.append(count) count = 0 elif 'R' not in pl: for i in pl: if i == 'S': count += 1 cs.append(count) count = 0 for i in range(m): b = input().split() num = int(b[0]) symb = b[1] pl[num - 1] = symb if 'P' in pl and 'R' in pl and 'S' in pl: for i in pl: if i == 'R': count1 += 1 elif i == 'P': count2 += 1 if count2 >= count1: for i in pl: if i == 'R' or i == 'S': count += 1 cs.append(count) else: for i in pl: if i == 'R': count += 1 cs.append(count) count = 0 count1 = 0 count2 = 0 elif (('P' not in pl and 'S' not in pl) or ('P' not in pl and 'R' not in pl) or ('R' not in pl and 'S' not in pl)): cs.append(n) elif 'P' not in pl: for i in pl: if i == 'R': count += 1 cs.append(count) count = 0 elif 'S' not in pl: for i in pl: if i == 'P': count += 1 cs.append(count) count = 0 elif 'R' not in pl: for i in pl: if i == 'S': count += 1 cs.append(count) count = 0 for i in cs: print(i) ``` No
85,038
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. n players are going to play a rock-paper-scissors tournament. As you probably know, in a one-on-one match of rock-paper-scissors, two players choose their shapes independently. The outcome is then determined depending on the chosen shapes: "paper" beats "rock", "rock" beats "scissors", "scissors" beat "paper", and two equal shapes result in a draw. At the start of the tournament all players will stand in a row, with their numbers increasing from 1 for the leftmost player, to n for the rightmost player. Each player has a pre-chosen shape that they will use in every game throughout the tournament. Here's how the tournament is conducted: * If there is only one player left, he is declared the champion. * Otherwise, two adjacent players in the row are chosen arbitrarily, and they play the next match. The losing player is eliminated from the tournament and leaves his place in the row (with his former neighbours becoming adjacent). If the game is a draw, the losing player is determined by a coin toss. The organizers are informed about all players' favoured shapes. They wish to find out the total number of players who have a chance of becoming the tournament champion (that is, there is a suitable way to choose the order of the games and manipulate the coin tosses). However, some players are still optimizing their strategy, and can inform the organizers about their new shapes. Can you find the number of possible champions after each such request? Input The first line contains two integers n and q — the number of players and requests respectively (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ q ≤ 2 ⋅ 10^5). The second line contains a string of n characters. The i-th of these characters is "R", "P", or "S" if the player i was going to play "rock", "paper", or "scissors" before all requests respectively. The following q lines describe the requests. The j-th of these lines contain an integer p_j and a character c_j meaning that the player p_j is going to use the shape described by the character c_j from this moment (1 ≤ p_j ≤ n). Output Print q + 1 integers r_0, …, r_q, where r_k is the number of possible champions after processing k requests. Example Input 3 5 RPS 1 S 2 R 3 P 1 P 2 P Output 2 2 1 2 2 3 Submitted Solution: ``` from math import * n, k = map(int, input().split()) if n == 0: print(0) exit else: for c in range(1, 100000): if n / c < k: print(floor(k * c + n / c)) break ``` No
85,039
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. n players are going to play a rock-paper-scissors tournament. As you probably know, in a one-on-one match of rock-paper-scissors, two players choose their shapes independently. The outcome is then determined depending on the chosen shapes: "paper" beats "rock", "rock" beats "scissors", "scissors" beat "paper", and two equal shapes result in a draw. At the start of the tournament all players will stand in a row, with their numbers increasing from 1 for the leftmost player, to n for the rightmost player. Each player has a pre-chosen shape that they will use in every game throughout the tournament. Here's how the tournament is conducted: * If there is only one player left, he is declared the champion. * Otherwise, two adjacent players in the row are chosen arbitrarily, and they play the next match. The losing player is eliminated from the tournament and leaves his place in the row (with his former neighbours becoming adjacent). If the game is a draw, the losing player is determined by a coin toss. The organizers are informed about all players' favoured shapes. They wish to find out the total number of players who have a chance of becoming the tournament champion (that is, there is a suitable way to choose the order of the games and manipulate the coin tosses). However, some players are still optimizing their strategy, and can inform the organizers about their new shapes. Can you find the number of possible champions after each such request? Input The first line contains two integers n and q — the number of players and requests respectively (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ q ≤ 2 ⋅ 10^5). The second line contains a string of n characters. The i-th of these characters is "R", "P", or "S" if the player i was going to play "rock", "paper", or "scissors" before all requests respectively. The following q lines describe the requests. The j-th of these lines contain an integer p_j and a character c_j meaning that the player p_j is going to use the shape described by the character c_j from this moment (1 ≤ p_j ≤ n). Output Print q + 1 integers r_0, …, r_q, where r_k is the number of possible champions after processing k requests. Example Input 3 5 RPS 1 S 2 R 3 P 1 P 2 P Output 2 2 1 2 2 3 Submitted Solution: ``` b = input().split() b = [int(i) for i in b] n, m = b pl = list(input()) count = 0 cs = [] if 'P' in pl and 'R' in pl and 'S' in pl: for i in pl: if i == 'R' or i == 'S': count += 1 cs.append(count) count = 0 elif (('P' not in pl and 'S' not in pl) or ('P' not in pl and 'R' not in pl) or ('R' not in pl and 'S' not in pl)): cs.append(n) elif 'P' not in pl: for i in pl: if i == 'R': count += 1 cs.append(count) count = 0 elif 'S' not in pl: for i in pl: if i == 'P': count += 1 cs.append(count) count = 0 elif 'R' not in pl: for i in pl: if i == 'S': count += 1 cs.append(count) count = 0 for i in range(m): b = input().split() num = int(b[0]) symb = b[1] pl[num - 1] = symb if 'P' in pl and 'R' in pl and 'S' in pl: for i in pl: if i == 'R' or i == 'S': count += 1 cs.append(count) count = 0 elif (('P' not in pl and 'S' not in pl) or ('P' not in pl and 'R' not in pl) or ('R' not in pl and 'S' not in pl)): cs.append(n) elif 'P' not in pl: for i in pl: if i == 'R': count += 1 cs.append(count) count = 0 elif 'S' not in pl: for i in pl: if i == 'P': count += 1 cs.append(count) count = 0 elif 'R' not in pl: for i in pl: if i == 'S': count += 1 cs.append(count) count = 0 for i in cs: print(i) ``` No
85,040
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. n players are going to play a rock-paper-scissors tournament. As you probably know, in a one-on-one match of rock-paper-scissors, two players choose their shapes independently. The outcome is then determined depending on the chosen shapes: "paper" beats "rock", "rock" beats "scissors", "scissors" beat "paper", and two equal shapes result in a draw. At the start of the tournament all players will stand in a row, with their numbers increasing from 1 for the leftmost player, to n for the rightmost player. Each player has a pre-chosen shape that they will use in every game throughout the tournament. Here's how the tournament is conducted: * If there is only one player left, he is declared the champion. * Otherwise, two adjacent players in the row are chosen arbitrarily, and they play the next match. The losing player is eliminated from the tournament and leaves his place in the row (with his former neighbours becoming adjacent). If the game is a draw, the losing player is determined by a coin toss. The organizers are informed about all players' favoured shapes. They wish to find out the total number of players who have a chance of becoming the tournament champion (that is, there is a suitable way to choose the order of the games and manipulate the coin tosses). However, some players are still optimizing their strategy, and can inform the organizers about their new shapes. Can you find the number of possible champions after each such request? Input The first line contains two integers n and q — the number of players and requests respectively (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ q ≤ 2 ⋅ 10^5). The second line contains a string of n characters. The i-th of these characters is "R", "P", or "S" if the player i was going to play "rock", "paper", or "scissors" before all requests respectively. The following q lines describe the requests. The j-th of these lines contain an integer p_j and a character c_j meaning that the player p_j is going to use the shape described by the character c_j from this moment (1 ≤ p_j ≤ n). Output Print q + 1 integers r_0, …, r_q, where r_k is the number of possible champions after processing k requests. Example Input 3 5 RPS 1 S 2 R 3 P 1 P 2 P Output 2 2 1 2 2 3 Submitted Solution: ``` def rps(x,y): d = {'R': 1, 'S': 2, 'P': 3} return ((d[x] - d[y]) + 1) % 3 - 1 n,q=map(int, input().split()) ig=input() t=0 a=[] for i in range(n): a.append(0) rez=[] fl=False if (ig==('R')*n) | (ig==('S')*n) | (ig==('P')*n): fl=True for i in range(0,n-1): if rps(ig[i], ig[i+1])==(-1): a[i]+=1 elif rps(ig[i], ig[i+1])==1: a[i+1]+=1 if fl==False: for i in range(n): if a[i]>0: t+=1 a[i]=0 else: t=n rez.append(t) for i in range(q): s=input() p=[] p=s.split() u=int(p[0]) y=p[1] ig=ig[0:u-1]+y+ig[(u):(len(ig))] t=0 fl=False if (ig==('R')*n) | (ig==('S')*n) | (ig==('P')*n): fl=True for i in range(0,n-1): if rps(ig[i], ig[i+1])==(-1): a[i]+=1 elif rps(ig[i], ig[i+1])==1: a[i+1]+=1 if fl==False: for i in range(n): if a[i]>0: t+=1 a[i]=0 else: t=n rez.append(t) for i in range(q+1): print(rez[i]) ``` No
85,041
Provide tags and a correct Python 3 solution for this coding contest problem. Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded. Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it. A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: * x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length); * in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. Input The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively. The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. Output Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record. Examples Input 3 2 1 2 1 3 Output 1 2 3 Input 5 5 1 4 3 4 5 4 3 2 1 5 Output 1 4 3 2 5 Input 10 10 1 4 6 8 2 5 3 7 9 4 5 6 3 4 8 10 8 9 1 10 Output 1 4 3 7 9 8 6 5 2 10 Note In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one. In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one. Tags: data structures, dfs and similar, graphs, greedy, shortest paths Correct Solution: ``` # n,m = map(int,input().split()) # G = [[] for _ in range(n+1)] # V = [1]*(n+1) # for i in range(m): # x,y = map(int,input().split()) # G[x].append(y) # G[y].append(x) # l = [1] # V[1] = 0 # q = [] # q.extend(G[1]) # while len(q)>0: # q.sort() # if q[0] not in l: l.append(q[0]) # V[q[0]] = 0 # for x in G[q.pop(0)]: # if V[x]: q.append(x) # print(*l) from heapq import* n,m= map(int,input().split()) V=[0,0]+[1]*(n-1) g=[[]for _ in V] for _ in [0]*m: u,v= map(int,input().split()) g[u].append(v) g[v].append(u) h=[1] l = [] while h: u=heappop(h) l.append(u) for v in g[u]: if V[v]: V[v]=0 heappush(h,v) print(*l) ```
85,042
Provide tags and a correct Python 3 solution for this coding contest problem. Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded. Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it. A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: * x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length); * in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. Input The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively. The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. Output Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record. Examples Input 3 2 1 2 1 3 Output 1 2 3 Input 5 5 1 4 3 4 5 4 3 2 1 5 Output 1 4 3 2 5 Input 10 10 1 4 6 8 2 5 3 7 9 4 5 6 3 4 8 10 8 9 1 10 Output 1 4 3 7 9 8 6 5 2 10 Note In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one. In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one. Tags: data structures, dfs and similar, graphs, greedy, shortest paths Correct Solution: ``` import heapq from collections import defaultdict graph = defaultdict(list) n,m = list(map(int,input().split())) for i in range(m): u,v = list(map(int,input().split())) u-=1 v-=1 graph[u].append(v) graph[v].append(u) visited = [False for i in range(n)] q = [0] heapq.heapify(q) visited[0] = True while q!=[]: u = heapq.heappop(q) print(u+1,end=' ') for v in graph[u]: if visited[v]==False: visited[v]=True heapq.heappush(q,v) ```
85,043
Provide tags and a correct Python 3 solution for this coding contest problem. Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded. Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it. A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: * x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length); * in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. Input The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively. The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. Output Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record. Examples Input 3 2 1 2 1 3 Output 1 2 3 Input 5 5 1 4 3 4 5 4 3 2 1 5 Output 1 4 3 2 5 Input 10 10 1 4 6 8 2 5 3 7 9 4 5 6 3 4 8 10 8 9 1 10 Output 1 4 3 7 9 8 6 5 2 10 Note In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one. In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one. Tags: data structures, dfs and similar, graphs, greedy, shortest paths Correct Solution: ``` import heapq n, m = map(int,input().split()) vertices = [ [] for i in range(n)] for _ in range(m): v1, v2 = map(int,input().split()) vertices[v1-1].append(v2-1) vertices[v2 - 1].append(v1 - 1) heap = [] heapq.heappush(heap,0) vis = set() ans = [] while not len(heap)==0: v = heapq.heappop(heap) vis.add(v) ans.append(v+1) for node in vertices[v]: if not node in vis: vis.add(node) heapq.heappush(heap,node) print(*ans) ```
85,044
Provide tags and a correct Python 3 solution for this coding contest problem. Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded. Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it. A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: * x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length); * in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. Input The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively. The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. Output Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record. Examples Input 3 2 1 2 1 3 Output 1 2 3 Input 5 5 1 4 3 4 5 4 3 2 1 5 Output 1 4 3 2 5 Input 10 10 1 4 6 8 2 5 3 7 9 4 5 6 3 4 8 10 8 9 1 10 Output 1 4 3 7 9 8 6 5 2 10 Note In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one. In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one. Tags: data structures, dfs and similar, graphs, greedy, shortest paths Correct Solution: ``` import math #import math #------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #-------------------game starts now----------------------------------------------------import math import heapq from collections import defaultdict n,m=map(int,input().split()) s=set() ans=[] d=defaultdict(list) for i in range(m): a,b=map(int,input().split()) d[a].append(b) d[b].append(a) ans.append(1) s.add(1) st=[] e=1 scur=set() heapq.heapify(st) for j in range(n-1): for i in d[e]: if i in s or i in scur: continue heapq.heappush(st,i) scur.add(i) e=heapq.heappop(st) scur.remove(e) ans.append(e) s.add(e) print(*ans,sep=" ") ```
85,045
Provide tags and a correct Python 3 solution for this coding contest problem. Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded. Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it. A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: * x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length); * in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. Input The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively. The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. Output Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record. Examples Input 3 2 1 2 1 3 Output 1 2 3 Input 5 5 1 4 3 4 5 4 3 2 1 5 Output 1 4 3 2 5 Input 10 10 1 4 6 8 2 5 3 7 9 4 5 6 3 4 8 10 8 9 1 10 Output 1 4 3 7 9 8 6 5 2 10 Note In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one. In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one. Tags: data structures, dfs and similar, graphs, greedy, shortest paths Correct Solution: ``` import sys from heapq import heappush,heappop from collections import defaultdict as dd def get_array(): return list(map(int, sys.stdin.readline().split())) def get_ints(): return map(int, sys.stdin.readline().split()) def input(): return sys.stdin.readline().strip('\n') visited = [0]*(10**5 + 10) l = dd(list) queue = [] ans = [] def bfs(): c = 1 while c != 0: vertex = heappop(queue) c-=1 ans.append(vertex) visited[vertex] = 1 for i in l[vertex]: if visited[i] == 0: heappush(queue,i) visited[i] = 1 c+=1 n , k = get_ints() for _ in range(k): a,b = get_ints() if a!=b: l[a].append(b) l[b].append(a) heappush(queue,1) bfs() print(*ans) ```
85,046
Provide tags and a correct Python 3 solution for this coding contest problem. Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded. Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it. A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: * x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length); * in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. Input The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively. The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. Output Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record. Examples Input 3 2 1 2 1 3 Output 1 2 3 Input 5 5 1 4 3 4 5 4 3 2 1 5 Output 1 4 3 2 5 Input 10 10 1 4 6 8 2 5 3 7 9 4 5 6 3 4 8 10 8 9 1 10 Output 1 4 3 7 9 8 6 5 2 10 Note In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one. In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one. Tags: data structures, dfs and similar, graphs, greedy, shortest paths Correct Solution: ``` from collections import defaultdict import heapq graph=defaultdict(list) nodes,edges=map(int,input().split()) for i in range(edges): vertex1,vertex2=map(int,input().split()) graph[vertex1].append(vertex2) graph[vertex2].append(vertex1) start=[1] visited=set() answer=[] while start: node=heapq.heappop(start) if node not in visited: visited.add(node) answer.append(node) for w in graph[node]: heapq.heappush(start,w) print(*answer) ```
85,047
Provide tags and a correct Python 3 solution for this coding contest problem. Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded. Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it. A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: * x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length); * in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. Input The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively. The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. Output Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record. Examples Input 3 2 1 2 1 3 Output 1 2 3 Input 5 5 1 4 3 4 5 4 3 2 1 5 Output 1 4 3 2 5 Input 10 10 1 4 6 8 2 5 3 7 9 4 5 6 3 4 8 10 8 9 1 10 Output 1 4 3 7 9 8 6 5 2 10 Note In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one. In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one. Tags: data structures, dfs and similar, graphs, greedy, shortest paths Correct Solution: ``` from heapq import heappush, heappop n, m = map(int, input().split()) adj = [[] for i in range(n+1)] for i in range(m): u, v = map(int, input().split()) adj[u].append(v) adj[v].append(u) v = [False for i in range(n+1)] q = [] perm = [] v[1] = True heappush(q, 1) while q: e = heappop(q) perm += [e] for i in adj[e]: if not v[i]: v[i] = True heappush(q, i) print(*perm) ```
85,048
Provide tags and a correct Python 3 solution for this coding contest problem. Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded. Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it. A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: * x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length); * in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. Input The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively. The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. Output Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record. Examples Input 3 2 1 2 1 3 Output 1 2 3 Input 5 5 1 4 3 4 5 4 3 2 1 5 Output 1 4 3 2 5 Input 10 10 1 4 6 8 2 5 3 7 9 4 5 6 3 4 8 10 8 9 1 10 Output 1 4 3 7 9 8 6 5 2 10 Note In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one. In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one. Tags: data structures, dfs and similar, graphs, greedy, shortest paths Correct Solution: ``` from sys import stdin,stdout from itertools import combinations from collections import defaultdict,OrderedDict import math import heapq def listIn(): return list((map(int,stdin.readline().strip().split()))) def stringListIn(): return([x for x in stdin.readline().split()]) def intIn(): return (int(stdin.readline())) def stringIn(): return (stdin.readline().strip()) def dfs(root,parent): vis[root]=1 q=[root] heapq.heapify(q) while(q): r=heapq.heappop(q) res.append(r) lis=sorted(g[r]) for i in range(len(lis)): if vis[lis[i]]==0: #print(lis[i],q) heapq.heappush(q,lis[i]) vis[lis[i]]=1 if __name__=="__main__": n,m=listIn() g=[[] for i in range(n+1)] for i in range(m): u,v=listIn() g[u].append(v) g[v].append(u) vis=[0]*(n+1) res=[] dfs(1,-1) print(*res) ```
85,049
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded. Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it. A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: * x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length); * in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. Input The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively. The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. Output Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record. Examples Input 3 2 1 2 1 3 Output 1 2 3 Input 5 5 1 4 3 4 5 4 3 2 1 5 Output 1 4 3 2 5 Input 10 10 1 4 6 8 2 5 3 7 9 4 5 6 3 4 8 10 8 9 1 10 Output 1 4 3 7 9 8 6 5 2 10 Note In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one. In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one. Submitted Solution: ``` from collections import defaultdict import heapq n, m = map(int, input().split()) graph = defaultdict(list) for i in range(m): a, b = map(int, input().split()) graph[a].append(b) graph[b].append(a) for i in range(n): graph[i].sort() visited = [0 for i in range(n + 1)] ans = [] q = [] heapq.heappush(q, 1) visited[1] = 1 while q: v = heapq.heappop(q) ans.append(v) # visited[v] = 1 for i in graph[v]: if visited[i] == 0: heapq.heappush(q, i) visited[i] = 1 # getOrder(1, graph, ans, visited) for i in ans: print(i, end=' ') print('') ``` Yes
85,050
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded. Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it. A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: * x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length); * in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. Input The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively. The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. Output Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record. Examples Input 3 2 1 2 1 3 Output 1 2 3 Input 5 5 1 4 3 4 5 4 3 2 1 5 Output 1 4 3 2 5 Input 10 10 1 4 6 8 2 5 3 7 9 4 5 6 3 4 8 10 8 9 1 10 Output 1 4 3 7 9 8 6 5 2 10 Note In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one. In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one. Submitted Solution: ``` from heapq import heappop, heappush n, m = map(int, input().split()) vis = [0]*2+[1]*(n-1) #nunca vamos a pasar por 0 y se parte en 1, por eso el resto es 1 A=[] for i in range(n+1): #es n+1, porque la primera posicion es 1 y no 0 A.append([]) for i in range(m): x, y = map(int, input().split()) #se interconectan los vertices x, y A[x].append(y) A[y].append(x) rec = [1] #partimos al inicio while rec: pos = heappop(rec) print(pos) #se printea la posicion en que se está for i in A[pos]: if vis[i]: #si es un "1" significa que aun no se printea el valor, por lo tanto vamos a pasar por ahí vis[i] = 0 #no hay que volver a printear el vlaor por el que vamos a pasar heappush(rec, i) ``` Yes
85,051
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded. Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it. A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: * x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length); * in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. Input The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively. The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. Output Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record. Examples Input 3 2 1 2 1 3 Output 1 2 3 Input 5 5 1 4 3 4 5 4 3 2 1 5 Output 1 4 3 2 5 Input 10 10 1 4 6 8 2 5 3 7 9 4 5 6 3 4 8 10 8 9 1 10 Output 1 4 3 7 9 8 6 5 2 10 Note In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one. In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one. Submitted Solution: ``` import heapq a, b = list(input().split(" ")) a = int(a) b = int(b) g = [[] for i in range(a)] for i in range(b): u, v = list(input().split(" ")) u = int(u) - 1 v = int(v) - 1 g[u] += [v] g[v] += [u] visited = [False for i in range(a)] for j in range(a): if(visited[j] == False): l = [j] heapq.heapify(l) ans = [] while(len(l) != 0): u = heapq.heappop(l) visited[u] = True ans += [u + 1] for i in g[u]: if(visited[i] == True): continue heapq.heappush(l, i) visited[i] = True for i in ans: print(i, end=' ') print() ``` Yes
85,052
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded. Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it. A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: * x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length); * in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. Input The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively. The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. Output Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record. Examples Input 3 2 1 2 1 3 Output 1 2 3 Input 5 5 1 4 3 4 5 4 3 2 1 5 Output 1 4 3 2 5 Input 10 10 1 4 6 8 2 5 3 7 9 4 5 6 3 4 8 10 8 9 1 10 Output 1 4 3 7 9 8 6 5 2 10 Note In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one. In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one. Submitted Solution: ``` from heapq import * n, m = map(int, input().split()) g = {} for _ in range(m): u, v = map(int, input().split()) g.setdefault(u, set()).add(v) g.setdefault(v, set()).add(u) d = [] V = set() h = [1] while h: v = heappop(h) if v in V: continue V.add(v) d.append(v) for u in g[v]: heappush(h, u) print(*d) ``` Yes
85,053
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded. Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it. A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: * x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length); * in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. Input The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively. The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. Output Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record. Examples Input 3 2 1 2 1 3 Output 1 2 3 Input 5 5 1 4 3 4 5 4 3 2 1 5 Output 1 4 3 2 5 Input 10 10 1 4 6 8 2 5 3 7 9 4 5 6 3 4 8 10 8 9 1 10 Output 1 4 3 7 9 8 6 5 2 10 Note In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one. In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one. Submitted Solution: ``` from heapq import * n,m=map(int,input().split()) d=[[]]*(n+1) for i in range(m): a,b=map(int,input().split()) d[a].append(b) d[b].append(a) vis=[0,0]+[1]*(n-1) oldv=[1] while oldv: act=heappop(oldv) print(act) for a in d[act]: if vis[a]==1: vis[a]=0 heappush(oldv,a) ``` No
85,054
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded. Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it. A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: * x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length); * in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. Input The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively. The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. Output Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record. Examples Input 3 2 1 2 1 3 Output 1 2 3 Input 5 5 1 4 3 4 5 4 3 2 1 5 Output 1 4 3 2 5 Input 10 10 1 4 6 8 2 5 3 7 9 4 5 6 3 4 8 10 8 9 1 10 Output 1 4 3 7 9 8 6 5 2 10 Note In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one. In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one. Submitted Solution: ``` n,m=map(int,input().split()) graph=[[] for _ in range(n)] for i in range(m): u,v=map(int,input().split()) graph[u-1].append(v-1) graph[v-1].append(u-1) q=[] q=[0] visited={0:True} l=[] while q: a=q.pop() l.append(a+1) graph[a].sort() graph[a].reverse() for i in graph[a]: if i not in visited: visited[i]=True q.append(i) print(" ".join(str(x) for x in l)) ``` No
85,055
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded. Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it. A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: * x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length); * in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. Input The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively. The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. Output Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record. Examples Input 3 2 1 2 1 3 Output 1 2 3 Input 5 5 1 4 3 4 5 4 3 2 1 5 Output 1 4 3 2 5 Input 10 10 1 4 6 8 2 5 3 7 9 4 5 6 3 4 8 10 8 9 1 10 Output 1 4 3 7 9 8 6 5 2 10 Note In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one. In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one. Submitted Solution: ``` n,m = map(int,input().split(' ')) li = [[] for i in range(n+1)] check = [0 for i in range(n+1)] hubo = [] check[0] = 1 def dfs(l,c,h): cc =1 while cc != n: h.sort() #idx = 0 #while c[h[idx]] == 1: #idx += 1 print(h[0],end=' ') c[h[0]] = 1 cc += 1 tt = list(filter(lambda x: c[x] == 0,li[h[0]])) h = h[1:] + tt for _ in range(m): u,v = map(int,input().split(' ')) li[u].append(v) li[v].append(u) '''for i in li: i.sort()''' li[1].sort() #print(li) print(1,end=' ') check[1] = 1 hubo = li[1] dfs(li[1],check,hubo) ``` No
85,056
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded. Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it. A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: * x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length); * in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. Input The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively. The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. Output Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record. Examples Input 3 2 1 2 1 3 Output 1 2 3 Input 5 5 1 4 3 4 5 4 3 2 1 5 Output 1 4 3 2 5 Input 10 10 1 4 6 8 2 5 3 7 9 4 5 6 3 4 8 10 8 9 1 10 Output 1 4 3 7 9 8 6 5 2 10 Note In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one. In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one. Submitted Solution: ``` visited = [] def dfs(graph,node): global visited if node not in visited: visited.append(node) for n in sorted(graph[node]): dfs(graph,n) def D(): n , m = map( int , input().split() ) graph = {i:[] for i in range(1,n+1)} for i in range(m): a , b = map( int , input().split() ) graph[a].append(b) graph[b].append(a) dfs(graph, 1) print(" ".join([str(x) for x in visited])) D() ``` No
85,057
Provide tags and a correct Python 3 solution for this coding contest problem. You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i. You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than k (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than 5. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter). It is possible that some students not be included in any team at all. Your task is to report the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 5000) — the number of students and the maximum number of teams, correspondingly. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is a programming skill of the i-th student. Output Print one integer — the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. Examples Input 5 2 1 2 15 15 15 Output 5 Input 6 1 36 4 1 25 9 16 Output 2 Input 4 4 1 10 100 1000 Output 4 Tags: dp, sortings, two pointers Correct Solution: ``` import sys input=sys.stdin.readline n,k=map(int,input().split()) a=list(map(int,input().split())) a.sort() cnt=[0]*n for i in range(n): while i+cnt[i]<n and a[cnt[i]+i]-a[i]<=5: cnt[i]+=1 dp=[[0]*(k+1) for i in range(n+1)] for i in range(n): for j in range(k+1): dp[i+1][j]=max(dp[i+1][j],dp[i][j]) if j+1<=k and i+cnt[i]<=n: dp[i+cnt[i]][j+1]=max(dp[i+cnt[i]][j+1],dp[i][j]+cnt[i]) print(dp[n][k]) ```
85,058
Provide tags and a correct Python 3 solution for this coding contest problem. You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i. You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than k (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than 5. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter). It is possible that some students not be included in any team at all. Your task is to report the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 5000) — the number of students and the maximum number of teams, correspondingly. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is a programming skill of the i-th student. Output Print one integer — the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. Examples Input 5 2 1 2 15 15 15 Output 5 Input 6 1 36 4 1 25 9 16 Output 2 Input 4 4 1 10 100 1000 Output 4 Tags: dp, sortings, two pointers Correct Solution: ``` # Legends Always Come Up with Solution # Author: Manvir Singh import os import sys from io import BytesIO, IOBase from array import array def main(): n,k=map(int,input().split()) a=sorted(map(int,input().split())) dp=[array("i",[0]*(k+1)) for _ in range(n+1)] l=1 for i in range(1,n+1): while l<n+1 and a[l-1]-a[i-1]<=5: for j in range(1,k+1): dp[l][j]=max(dp[l][j],dp[l-1][j],dp[i-1][j-1]+l-i+1) l+=1 print(max(max(i) for i in dp)) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": main() ```
85,059
Provide tags and a correct Python 3 solution for this coding contest problem. You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i. You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than k (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than 5. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter). It is possible that some students not be included in any team at all. Your task is to report the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 5000) — the number of students and the maximum number of teams, correspondingly. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is a programming skill of the i-th student. Output Print one integer — the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. Examples Input 5 2 1 2 15 15 15 Output 5 Input 6 1 36 4 1 25 9 16 Output 2 Input 4 4 1 10 100 1000 Output 4 Tags: dp, sortings, two pointers Correct Solution: ``` n, k = map(int, input().split()) a = sorted(list(map(int, input().split()))) i = 0 j = 0 ans = 0 start = [0] * n for _ in range(n): while j < i and a[i] - a[j] > 5: j += 1 start[i] = j i += 1 dp = [([0] * (k + 1)) for _ in range(n)] for i in range(1, k+1): dp[0][i] = 1 for i in range(1, n): for j in range(1, k+1): lastgroup = 0 if start[i] >= 1: lastgroup = dp[start[i]-1][j-1] dp[i][j] = max(dp[i-1][j], lastgroup + (i - start[i]) + 1) print(dp[-1][-1]) ```
85,060
Provide tags and a correct Python 3 solution for this coding contest problem. You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i. You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than k (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than 5. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter). It is possible that some students not be included in any team at all. Your task is to report the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 5000) — the number of students and the maximum number of teams, correspondingly. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is a programming skill of the i-th student. Output Print one integer — the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. Examples Input 5 2 1 2 15 15 15 Output 5 Input 6 1 36 4 1 25 9 16 Output 2 Input 4 4 1 10 100 1000 Output 4 Tags: dp, sortings, two pointers Correct Solution: ``` import sys import math input = sys.stdin.readline from functools import cmp_to_key; def pi(): return(int(input())) def pl(): return(int(input(), 16)) def ti(): return(list(map(int,input().split()))) def ts(): s = input() return(list(s[:len(s) - 1])) def invr(): return(map(int,input().split())) mod = 998244353; f = []; def fact(n,m): global f; f = [1 for i in range(n+1)]; f[0] = 1; for i in range(1,n+1): f[i] = (f[i-1]*i)%m; def fast_mod_exp(a,b,m): res = 1; while b > 0: if b & 1: res = (res*a)%m; a = (a*a)%m; b = b >> 1; return res; def inverseMod(n,m): return fast_mod_exp(n,m-2,m); def ncr(n,r,m): if r == 0: return 1; return ((f[n]*inverseMod(f[n-r],m))%m*inverseMod(f[r],m))%m; def main(): D(); dp = []; def D(): [n,k] = ti(); a = ti(); a = sorted(a); cnt = [0 for i in range(n)]; for i in range(n): c = 0; for j in range(i,n): if a[j]-a[i] <= 5: c+=1; else:break; cnt[i] = c; global dp; dp = [[0 for j in range(k+1)] for i in range(n+1)]; ans = 0; for i in range(n): for j in range(k+1): dp[i+1][j] = max(dp[i+1][j], dp[i][j]); if j+1 <= k: dp[i+cnt[i]][j+1] = max(dp[i+cnt[i]][j+1], dp[i][j]+cnt[i]); print(dp[n][k]); main(); ```
85,061
Provide tags and a correct Python 3 solution for this coding contest problem. You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i. You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than k (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than 5. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter). It is possible that some students not be included in any team at all. Your task is to report the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 5000) — the number of students and the maximum number of teams, correspondingly. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is a programming skill of the i-th student. Output Print one integer — the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. Examples Input 5 2 1 2 15 15 15 Output 5 Input 6 1 36 4 1 25 9 16 Output 2 Input 4 4 1 10 100 1000 Output 4 Tags: dp, sortings, two pointers Correct Solution: ``` import heapq arr = input() N,K = [int(x) for x in arr.split(' ')] arr = input() arr = [int(x) for x in arr.split(' ')] arr.sort() data = [[0]*N for _ in range(K)] left = 0 right = 0 res = 0 while left<N and right<N: if arr[right]>arr[left]+5: #res = max(res,right-left) left += 1 else: data[0][right] = max(data[0][right-1],right-left+1) right += 1 #res = max(res,right-left) for i in range(K): data[i][0] = 1 #print(data) for j in range(1,K): left = 0 right = 0 res = 0 while left<N and right<N: if arr[right]>arr[left]+5: left += 1 else: #print(left,right) if left >= 1 and right>=1: data[j][right] = max(data[j][right-1],data[j][right],data[j-1][left-1] + right-left+1) elif left==0 and right>=1: data[j][right] = max(data[j][right-1],data[j][right],right-left+1) right += 1 #print(data) print(data[K-1][N-1]) ```
85,062
Provide tags and a correct Python 3 solution for this coding contest problem. You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i. You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than k (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than 5. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter). It is possible that some students not be included in any team at all. Your task is to report the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 5000) — the number of students and the maximum number of teams, correspondingly. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is a programming skill of the i-th student. Output Print one integer — the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. Examples Input 5 2 1 2 15 15 15 Output 5 Input 6 1 36 4 1 25 9 16 Output 2 Input 4 4 1 10 100 1000 Output 4 Tags: dp, sortings, two pointers Correct Solution: ``` n, K = map(int, input().split()) arr = sorted(map(int, input().split())) freq = {} for x in arr: freq[x] = freq.get(x, 0)+1 arr = sorted(freq.keys()) freq = [freq[x] for x in arr] n = len(arr) dp = [[0 for _ in range(n+1)] for _ in range(2)] for k in range(1, K+1): for i in range(n-1, -1, -1): j = i curr = 0 curr_ans = dp[k&1][i+1] while j < n and abs(arr[i]-arr[j]) <= 5: curr += freq[j] curr_ans = max(curr_ans, curr+dp[1-(k&1)][j+1]) j += 1 dp[k&1][i] = curr_ans print(dp[K&1][0]) ```
85,063
Provide tags and a correct Python 3 solution for this coding contest problem. You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i. You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than k (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than 5. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter). It is possible that some students not be included in any team at all. Your task is to report the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 5000) — the number of students and the maximum number of teams, correspondingly. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is a programming skill of the i-th student. Output Print one integer — the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. Examples Input 5 2 1 2 15 15 15 Output 5 Input 6 1 36 4 1 25 9 16 Output 2 Input 4 4 1 10 100 1000 Output 4 Tags: dp, sortings, two pointers Correct Solution: ``` n,k=[int(x) for x in input().split()] a=[int(x) for x in input().split()] a.sort() index={} for i in range(n): index[a[i]]=i dp=[[1]*(k+1) for i in range(n+1)] for i in range(n+1): dp[i][0]=0 for i in range(k+1): dp[0][i]=0 for i in range(1,n+1): for item in range(5,-1,-1): if a[i-1]+item in index: counter=index[a[i-1]+item]-i+1 break for j in range(k+1): if i>0: dp[i][j]=max(dp[i-1][j],dp[i][j]) if j<k: dp[i+counter][j+1]=max(dp[i+counter][j+1],dp[i-1][j]+counter+1) print(dp[n][k]) ```
85,064
Provide tags and a correct Python 3 solution for this coding contest problem. You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i. You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than k (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than 5. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter). It is possible that some students not be included in any team at all. Your task is to report the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 5000) — the number of students and the maximum number of teams, correspondingly. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is a programming skill of the i-th student. Output Print one integer — the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. Examples Input 5 2 1 2 15 15 15 Output 5 Input 6 1 36 4 1 25 9 16 Output 2 Input 4 4 1 10 100 1000 Output 4 Tags: dp, sortings, two pointers Correct Solution: ``` # Legends Always Come Up with Solution # Author: Manvir Singh import os import sys from io import BytesIO, IOBase from math import inf def main(): n,k=map(int,input().split()) a=sorted(map(int,input().split())) dp=[[0]*(k+1) for _ in range(n+1)] l=1 for i in range(1,n+1): while l<n+1 and a[l-1]-a[i-1]<=5: for j in range(1,k+1): dp[l][j]=max(dp[l][j],dp[l-1][j],dp[i-1][j-1]+l-i+1) l+=1 print(max(max(i) for i in dp)) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": main() ```
85,065
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i. You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than k (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than 5. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter). It is possible that some students not be included in any team at all. Your task is to report the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 5000) — the number of students and the maximum number of teams, correspondingly. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is a programming skill of the i-th student. Output Print one integer — the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. Examples Input 5 2 1 2 15 15 15 Output 5 Input 6 1 36 4 1 25 9 16 Output 2 Input 4 4 1 10 100 1000 Output 4 Submitted Solution: ``` n,k=map(int,input().split()) arr=sorted(list(map(int,input().split()))) cnti=[0 for i in range(n)] for i in range(n): count=0 for j in range(i,n): if arr[j] -arr[i] <=5: count+=1 continue break cnti[i] =count dp=[[0 for i in range(k+1)] for j in range(n+1)] for i in range(n): for j in range(k+1): dp[i+1][j]=max(dp[i+1][j],dp[i][j]) if j<k: dp[i+cnti[i]][j+1] =max(dp[i+cnti[i]][j+1] ,dp[i][j] +cnti[i]) print(dp[n][k]) ``` Yes
85,066
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i. You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than k (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than 5. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter). It is possible that some students not be included in any team at all. Your task is to report the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 5000) — the number of students and the maximum number of teams, correspondingly. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is a programming skill of the i-th student. Output Print one integer — the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. Examples Input 5 2 1 2 15 15 15 Output 5 Input 6 1 36 4 1 25 9 16 Output 2 Input 4 4 1 10 100 1000 Output 4 Submitted Solution: ``` from bisect import bisect_right import sys def input(): return sys.stdin.readline().rstrip() def slv(): n, k = map(int, input().split()) a = list(map(int, input().split())) a.sort() dp = [[0]*(k + 1) for i in range(n + 1)] ans = 0 for ni in range(1, n + 1): v = a[ni - 1] cnt = bisect_right(a, v - 6) for gi in range(1, k + 1): dp[ni][gi] = dp[cnt][gi - 1] + (ni - cnt) dp[ni][gi] = max(dp[ni][gi], dp[ni][gi - 1], dp[ni - 1][gi]) ans = max(dp[ni][k] for ni in range(1, n + 1)) print(ans) return def main(): t = 1 for i in range(t): slv() return if __name__ == "__main__": main() ``` Yes
85,067
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i. You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than k (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than 5. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter). It is possible that some students not be included in any team at all. Your task is to report the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 5000) — the number of students and the maximum number of teams, correspondingly. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is a programming skill of the i-th student. Output Print one integer — the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. Examples Input 5 2 1 2 15 15 15 Output 5 Input 6 1 36 4 1 25 9 16 Output 2 Input 4 4 1 10 100 1000 Output 4 Submitted Solution: ``` #DORIME from sys import stdin input=stdin.readline from collections import defaultdict def f(a,n,k): cnt=[0]*(n) a=sorted(a) for i in range(n): while i+cnt[i]<n and a[i+cnt[i]]-a[i]<=5: # get shit after the other shit which has absdif (5) cnt[i]+=1 dp=[[0]*(k+1) for i in range(n+1)] for i in range(n): for j in range(k+1): dp[i+1][j]=max(dp[i+1][j],dp[i][j]) #just random bs if j+1<=k: dp[i+cnt[i]][j+1]=max(dp[i+cnt[i]][j+1],dp[i][j]+cnt[i]) # make a team with min value =a[i] # print(dp) return (dp[n][k]) n,k=map(int,input().strip().split()) print(f([*map(int,input().strip().split())],n,k)) ``` Yes
85,068
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i. You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than k (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than 5. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter). It is possible that some students not be included in any team at all. Your task is to report the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 5000) — the number of students and the maximum number of teams, correspondingly. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is a programming skill of the i-th student. Output Print one integer — the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. Examples Input 5 2 1 2 15 15 15 Output 5 Input 6 1 36 4 1 25 9 16 Output 2 Input 4 4 1 10 100 1000 Output 4 Submitted Solution: ``` from collections import defaultdict import heapq import sys input = sys.stdin.readline n, k = map(int, input().split()) a = list(map(int, input().split())) s = set() cnt = defaultdict(lambda : 0) for i in a: cnt[i] += 1 s.add(i) s = list(s) s.sort() ok = [] c, d = [], [] for i in s: c0, d0 = 0, 0 for j in range(6): c0 += cnt[i + j] d0 += min(cnt[i + j], 1) c.append(c0) d.append(d0) m = len(s) dp = [0] * (m + 1) for _ in range(k): dp0 = [0] * (m + 1) for i in range(m): j = i + d[i] if j > m: break dp0[j] = max(dp0[j], dp[i] + c[i]) ma = 0 for i in range(m + 1): ma = max(ma, dp0[i]) dp[i] = ma if dp[-1] == n: break ans = dp[-1] print(ans) ``` Yes
85,069
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i. You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than k (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than 5. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter). It is possible that some students not be included in any team at all. Your task is to report the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 5000) — the number of students and the maximum number of teams, correspondingly. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is a programming skill of the i-th student. Output Print one integer — the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. Examples Input 5 2 1 2 15 15 15 Output 5 Input 6 1 36 4 1 25 9 16 Output 2 Input 4 4 1 10 100 1000 Output 4 Submitted Solution: ``` from collections import defaultdict def solve(n, k, nums): nums.sort() new_nums = [0] for i in range(1, n): x = min(nums[i] - nums[i-1], 6) new_nums.append(new_nums[-1] + x) cand_count = new_nums[-1] candidates = [0] * cand_count for n in new_nums: for i in range(n-5, n+1): if 0 <= i < cand_count: candidates[i] += 1 prev = [None] * cand_count max_val = 0 for i in range(cand_count): max_val = max(max_val, candidates[i]) prev[i] = max_val #print(candidates) #print(prev) for ki in range(1, k): new = [None] * cand_count new[0:6] = prev[0:6] for i in range(6, cand_count): new[i] = max(new[i-1], prev[i-6]+candidates[i]) prev = new #print(new) print(prev[-1]) def solve_from_stdin(): n, k = map(int, input().split()) nums = list(map(int, input().split())) solve(n, k, nums) def test(): n, k = 5000, 5000 nums = list(range(0, 5*n, 5)) solve(n, k, nums) solve_from_stdin() ``` No
85,070
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i. You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than k (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than 5. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter). It is possible that some students not be included in any team at all. Your task is to report the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 5000) — the number of students and the maximum number of teams, correspondingly. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is a programming skill of the i-th student. Output Print one integer — the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. Examples Input 5 2 1 2 15 15 15 Output 5 Input 6 1 36 4 1 25 9 16 Output 2 Input 4 4 1 10 100 1000 Output 4 Submitted Solution: ``` import sys import math input = sys.stdin.readline from functools import cmp_to_key; def pi(): return(int(input())) def pl(): return(int(input(), 16)) def ti(): return(list(map(int,input().split()))) def ts(): s = input() return(list(s[:len(s) - 1])) def invr(): return(map(int,input().split())) mod = 998244353; f = []; def fact(n,m): global f; f = [1 for i in range(n+1)]; f[0] = 1; for i in range(1,n+1): f[i] = (f[i-1]*i)%m; def fast_mod_exp(a,b,m): res = 1; while b > 0: if b & 1: res = (res*a)%m; a = (a*a)%m; b = b >> 1; return res; def inverseMod(n,m): return fast_mod_exp(n,m-2,m); def ncr(n,r,m): if r == 0: return 1; return ((f[n]*inverseMod(f[n-r],m))%m*inverseMod(f[r],m))%m; def main(): D(); dp = []; def solve(st,k,n,a): if st >= n: return 0; if k <= 0: return 0; mx = 0; if dp[k][st] != -1: return dp[k][st]; for i in range(st,n): if a[i]-a[st] <= 5: mx = max(mx,i-st+1+solve(i+1,k-1,n,a)); dp[k][st] = mx; return mx; def D(): [n,k] = ti(); a = ti(); a = sorted(a); global dp; dp = [[-1 for j in range(n)] for i in range(k+1)]; print(solve(0,k,n,a)); main(); ``` No
85,071
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i. You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than k (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than 5. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter). It is possible that some students not be included in any team at all. Your task is to report the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 5000) — the number of students and the maximum number of teams, correspondingly. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is a programming skill of the i-th student. Output Print one integer — the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. Examples Input 5 2 1 2 15 15 15 Output 5 Input 6 1 36 4 1 25 9 16 Output 2 Input 4 4 1 10 100 1000 Output 4 Submitted Solution: ``` n, K = map(int, input().split()) arr = sorted(map(int, input().split())) freq = {} for x in arr: freq[x] = freq.get(x, 0)+1 arr = sorted(freq.keys()) n = len(arr) dp = [[0 for _ in range(n+1)] for _ in range(2)] for k in range(1, K+1): for i in range(n-1, -1, -1): j = i ans = dp[k&1][j] curr = 0 while j < n and abs(arr[i]-arr[j]) <= 5: curr += freq[arr[i]] ans = max(ans, curr+dp[1-(k&1)][j+1]) j += 1 dp[k&1][i] = ans print(max(max(dp[0]), max(dp[1]))) ``` No
85,072
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i. You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than k (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than 5. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter). It is possible that some students not be included in any team at all. Your task is to report the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 5000) — the number of students and the maximum number of teams, correspondingly. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is a programming skill of the i-th student. Output Print one integer — the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams. Examples Input 5 2 1 2 15 15 15 Output 5 Input 6 1 36 4 1 25 9 16 Output 2 Input 4 4 1 10 100 1000 Output 4 Submitted Solution: ``` from collections import Counter from heapq import heapify, heappush, heappop n,k=map(int,input().split()) a=[int(x ) for x in input().split()] z=Counter(a) a=sorted(list(set(a))) p=[] for i in range(len(a)): s=z[a[i]] c=0 for j in range(1,6): heappush(p, (-s, i, j )) if (i-j)>-1: if a[i]-a[i-j]<=5: s+=z[a[i-j]] else: c=0 break else: c=0 break if c==1: heappush(p,(-s,i,6)) #print(p) x=[0]*len(a) #print(p) an=0 while k!=0: #print(p) xx=heappop(p) #print(xx,an) tt=0 for i in range(xx[2]): tt|=x[xx[1]-i] if not tt: for i in range(xx[2]): x[xx[1]-i]=1 an-=xx[0] k-=1 if not p: break #print(x) #print(a) print(an) ``` No
85,073
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You can choose any non-negative integer D (i.e. D ≥ 0), and for each a_i you can: * add D (only once), i. e. perform a_i := a_i + D, or * subtract D (only once), i. e. perform a_i := a_i - D, or * leave the value of a_i unchanged. It is possible that after an operation the value a_i becomes negative. Your goal is to choose such minimum non-negative integer D and perform changes in such a way, that all a_i are equal (i.e. a_1=a_2=...=a_n). Print the required D or, if it is impossible to choose such value D, print -1. For example, for array [2, 8] the value D=3 is minimum possible because you can obtain the array [5, 5] if you will add D to 2 and subtract D from 8. And for array [1, 4, 7, 7] the value D=3 is also minimum possible. You can add it to 1 and subtract it from 7 and obtain the array [4, 4, 4, 4]. Input The first line of the input contains one integer n (1 ≤ n ≤ 100) — the number of elements in a. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100) — the sequence a. Output Print one integer — the minimum non-negative integer value D such that if you add this value to some a_i, subtract this value from some a_i and leave some a_i without changes, all obtained values become equal. If it is impossible to choose such value D, print -1. Examples Input 6 1 4 4 7 4 1 Output 3 Input 5 2 2 5 2 5 Output 3 Input 4 1 3 3 7 Output -1 Input 2 2 8 Output 3 Tags: math Correct Solution: ``` n = int(input()) A = list(map(int, input().split())) if len(set(A)) == 1: print(0) exit(0) A.sort() x = A[-1] - A[0] heh = x if x % 2 == 0: heh = x // 2 for kek in heh, x: s = set() for elem in A: if elem > A[0] + kek: s.add(elem - kek) elif elem < A[0] + kek: s.add(elem + kek) if len(s) == 1 and A[0] + kek in s: print(kek) exit(0) print(-1) ```
85,074
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You can choose any non-negative integer D (i.e. D ≥ 0), and for each a_i you can: * add D (only once), i. e. perform a_i := a_i + D, or * subtract D (only once), i. e. perform a_i := a_i - D, or * leave the value of a_i unchanged. It is possible that after an operation the value a_i becomes negative. Your goal is to choose such minimum non-negative integer D and perform changes in such a way, that all a_i are equal (i.e. a_1=a_2=...=a_n). Print the required D or, if it is impossible to choose such value D, print -1. For example, for array [2, 8] the value D=3 is minimum possible because you can obtain the array [5, 5] if you will add D to 2 and subtract D from 8. And for array [1, 4, 7, 7] the value D=3 is also minimum possible. You can add it to 1 and subtract it from 7 and obtain the array [4, 4, 4, 4]. Input The first line of the input contains one integer n (1 ≤ n ≤ 100) — the number of elements in a. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100) — the sequence a. Output Print one integer — the minimum non-negative integer value D such that if you add this value to some a_i, subtract this value from some a_i and leave some a_i without changes, all obtained values become equal. If it is impossible to choose such value D, print -1. Examples Input 6 1 4 4 7 4 1 Output 3 Input 5 2 2 5 2 5 Output 3 Input 4 1 3 3 7 Output -1 Input 2 2 8 Output 3 Tags: math Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) uniq = set(a) mi = min(uniq) ma = max(uniq) if 2 < len(uniq) <= 3: if (mi + ma) % 2 == 0 and (mi + ma) // 2 == sum(uniq - {mi, ma}): print(ma - sum(uniq - {mi, ma})) else: print(-1) elif len(uniq) == 2: if mi % 2 == ma % 2: print((ma - mi) // 2) else: print(ma - mi) elif len(uniq) == 1: print(0) else: print(-1) ```
85,075
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You can choose any non-negative integer D (i.e. D ≥ 0), and for each a_i you can: * add D (only once), i. e. perform a_i := a_i + D, or * subtract D (only once), i. e. perform a_i := a_i - D, or * leave the value of a_i unchanged. It is possible that after an operation the value a_i becomes negative. Your goal is to choose such minimum non-negative integer D and perform changes in such a way, that all a_i are equal (i.e. a_1=a_2=...=a_n). Print the required D or, if it is impossible to choose such value D, print -1. For example, for array [2, 8] the value D=3 is minimum possible because you can obtain the array [5, 5] if you will add D to 2 and subtract D from 8. And for array [1, 4, 7, 7] the value D=3 is also minimum possible. You can add it to 1 and subtract it from 7 and obtain the array [4, 4, 4, 4]. Input The first line of the input contains one integer n (1 ≤ n ≤ 100) — the number of elements in a. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100) — the sequence a. Output Print one integer — the minimum non-negative integer value D such that if you add this value to some a_i, subtract this value from some a_i and leave some a_i without changes, all obtained values become equal. If it is impossible to choose such value D, print -1. Examples Input 6 1 4 4 7 4 1 Output 3 Input 5 2 2 5 2 5 Output 3 Input 4 1 3 3 7 Output -1 Input 2 2 8 Output 3 Tags: math Correct Solution: ``` def main(): input() s = set([int(x) for x in input().split()]) n = len(s) if n == 2 or n ==3: s = list(s) s.sort() if n == 3: if (s[2]-s[0])%2 == 0: if (((s[2]-s[0])//2 + s[0] == s[1]) and (s[2] - (s[2]-s[0])//2 == s[1])): print((s[2]-s[0])//2) else: print(-1) else: print(-1) else: if (s[1]-s[0])%2 == 0: print((s[1]-s[0])//2) else: print(s[1]-s[0]) elif n == 1: print(0) else: print(-1) if __name__ == '__main__': main() ```
85,076
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You can choose any non-negative integer D (i.e. D ≥ 0), and for each a_i you can: * add D (only once), i. e. perform a_i := a_i + D, or * subtract D (only once), i. e. perform a_i := a_i - D, or * leave the value of a_i unchanged. It is possible that after an operation the value a_i becomes negative. Your goal is to choose such minimum non-negative integer D and perform changes in such a way, that all a_i are equal (i.e. a_1=a_2=...=a_n). Print the required D or, if it is impossible to choose such value D, print -1. For example, for array [2, 8] the value D=3 is minimum possible because you can obtain the array [5, 5] if you will add D to 2 and subtract D from 8. And for array [1, 4, 7, 7] the value D=3 is also minimum possible. You can add it to 1 and subtract it from 7 and obtain the array [4, 4, 4, 4]. Input The first line of the input contains one integer n (1 ≤ n ≤ 100) — the number of elements in a. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100) — the sequence a. Output Print one integer — the minimum non-negative integer value D such that if you add this value to some a_i, subtract this value from some a_i and leave some a_i without changes, all obtained values become equal. If it is impossible to choose such value D, print -1. Examples Input 6 1 4 4 7 4 1 Output 3 Input 5 2 2 5 2 5 Output 3 Input 4 1 3 3 7 Output -1 Input 2 2 8 Output 3 Tags: math Correct Solution: ``` # cook your dish here n=int(input()) l = list(map(int,input().split())) l=list(set(l)) l.sort() n=-1 d=-1 if(len(l)==1): d=0 elif len(l)==2: if (l[1]-l[0])%2==0: d = (l[1]-l[0])//2 n=l[0]+d else: d = l[1]-l[0] n = l[0] elif len(l)==3: if l[2]-l[1]==l[1]-l[0]: d = (l[1]-l[0]) else: d=-1 print(d) ```
85,077
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You can choose any non-negative integer D (i.e. D ≥ 0), and for each a_i you can: * add D (only once), i. e. perform a_i := a_i + D, or * subtract D (only once), i. e. perform a_i := a_i - D, or * leave the value of a_i unchanged. It is possible that after an operation the value a_i becomes negative. Your goal is to choose such minimum non-negative integer D and perform changes in such a way, that all a_i are equal (i.e. a_1=a_2=...=a_n). Print the required D or, if it is impossible to choose such value D, print -1. For example, for array [2, 8] the value D=3 is minimum possible because you can obtain the array [5, 5] if you will add D to 2 and subtract D from 8. And for array [1, 4, 7, 7] the value D=3 is also minimum possible. You can add it to 1 and subtract it from 7 and obtain the array [4, 4, 4, 4]. Input The first line of the input contains one integer n (1 ≤ n ≤ 100) — the number of elements in a. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100) — the sequence a. Output Print one integer — the minimum non-negative integer value D such that if you add this value to some a_i, subtract this value from some a_i and leave some a_i without changes, all obtained values become equal. If it is impossible to choose such value D, print -1. Examples Input 6 1 4 4 7 4 1 Output 3 Input 5 2 2 5 2 5 Output 3 Input 4 1 3 3 7 Output -1 Input 2 2 8 Output 3 Tags: math Correct Solution: ``` #make_them_equal n = int(input()); a = list(set([int(num) for num in input().split()])) a.sort() # def equal(b): # diffArray=[] # for j in range(0,len(b)-1): # diff = b[j+1]-b[j] # if diff != 0: # diffArray.append(diff); # j += 1; # #print(diffArray) # valArray=[] # for k in range(0,len(diffArray)-1): # if diffArray[k+1]==diffArray[k]: # valArray.append(True); # elif diffArray[k+1] !=diffArray[k]: # valArray.append(False); # k +=1; # #print(valArray) # if all(valArray) == True: # return(diffArray[0]); # elif all(valArray)== False: # return('-1'); if len(a) > 3: print('-1'); elif len(a) == 1: print(0); elif len(a) == 2: diff = a[1] - a[0] if diff % 2: print(diff) else: print(int(diff / 2)) else: diff1 = a[1] - a[0] diff2 = a[2] - a[1] if diff1 != diff2: print(-1) else: print(diff1) ```
85,078
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You can choose any non-negative integer D (i.e. D ≥ 0), and for each a_i you can: * add D (only once), i. e. perform a_i := a_i + D, or * subtract D (only once), i. e. perform a_i := a_i - D, or * leave the value of a_i unchanged. It is possible that after an operation the value a_i becomes negative. Your goal is to choose such minimum non-negative integer D and perform changes in such a way, that all a_i are equal (i.e. a_1=a_2=...=a_n). Print the required D or, if it is impossible to choose such value D, print -1. For example, for array [2, 8] the value D=3 is minimum possible because you can obtain the array [5, 5] if you will add D to 2 and subtract D from 8. And for array [1, 4, 7, 7] the value D=3 is also minimum possible. You can add it to 1 and subtract it from 7 and obtain the array [4, 4, 4, 4]. Input The first line of the input contains one integer n (1 ≤ n ≤ 100) — the number of elements in a. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100) — the sequence a. Output Print one integer — the minimum non-negative integer value D such that if you add this value to some a_i, subtract this value from some a_i and leave some a_i without changes, all obtained values become equal. If it is impossible to choose such value D, print -1. Examples Input 6 1 4 4 7 4 1 Output 3 Input 5 2 2 5 2 5 Output 3 Input 4 1 3 3 7 Output -1 Input 2 2 8 Output 3 Tags: math Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) def solve(): if len(set(a)) == 1: return 0 INF = 1 << 30 ret = INF for target in range(1, 101): delta = INF for num in a: if num > target: if delta == INF: delta = num - target elif delta != num - target: delta = INF break elif num < target: if delta == INF: delta = target - num elif delta != target - num: delta = INF break ret = min(ret, delta) return ret if ret != INF else -1 print(solve()) ```
85,079
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You can choose any non-negative integer D (i.e. D ≥ 0), and for each a_i you can: * add D (only once), i. e. perform a_i := a_i + D, or * subtract D (only once), i. e. perform a_i := a_i - D, or * leave the value of a_i unchanged. It is possible that after an operation the value a_i becomes negative. Your goal is to choose such minimum non-negative integer D and perform changes in such a way, that all a_i are equal (i.e. a_1=a_2=...=a_n). Print the required D or, if it is impossible to choose such value D, print -1. For example, for array [2, 8] the value D=3 is minimum possible because you can obtain the array [5, 5] if you will add D to 2 and subtract D from 8. And for array [1, 4, 7, 7] the value D=3 is also minimum possible. You can add it to 1 and subtract it from 7 and obtain the array [4, 4, 4, 4]. Input The first line of the input contains one integer n (1 ≤ n ≤ 100) — the number of elements in a. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100) — the sequence a. Output Print one integer — the minimum non-negative integer value D such that if you add this value to some a_i, subtract this value from some a_i and leave some a_i without changes, all obtained values become equal. If it is impossible to choose such value D, print -1. Examples Input 6 1 4 4 7 4 1 Output 3 Input 5 2 2 5 2 5 Output 3 Input 4 1 3 3 7 Output -1 Input 2 2 8 Output 3 Tags: math Correct Solution: ``` n = int(input()) lst = [int(x) for x in input().split()] lst = list(set(lst)) lst.sort() last = lst[0] count = len(lst) - 1 # for curr in lst: # print(curr) flag = True dif1,dif2 = 0,0 if count > 2: flag = False if count == 2: dif1 = lst[1] - lst[0] dif2 = lst[2] - lst[1] if dif1 != dif2: flag = False if flag: if count == 2: print(dif1) elif count == 1: dif1 = lst[1] - lst[0] if dif1%2 != 0: print(dif1) else : print(int(dif1/2)) else: print(0) else: print(int(-1)) ```
85,080
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You can choose any non-negative integer D (i.e. D ≥ 0), and for each a_i you can: * add D (only once), i. e. perform a_i := a_i + D, or * subtract D (only once), i. e. perform a_i := a_i - D, or * leave the value of a_i unchanged. It is possible that after an operation the value a_i becomes negative. Your goal is to choose such minimum non-negative integer D and perform changes in such a way, that all a_i are equal (i.e. a_1=a_2=...=a_n). Print the required D or, if it is impossible to choose such value D, print -1. For example, for array [2, 8] the value D=3 is minimum possible because you can obtain the array [5, 5] if you will add D to 2 and subtract D from 8. And for array [1, 4, 7, 7] the value D=3 is also minimum possible. You can add it to 1 and subtract it from 7 and obtain the array [4, 4, 4, 4]. Input The first line of the input contains one integer n (1 ≤ n ≤ 100) — the number of elements in a. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100) — the sequence a. Output Print one integer — the minimum non-negative integer value D such that if you add this value to some a_i, subtract this value from some a_i and leave some a_i without changes, all obtained values become equal. If it is impossible to choose such value D, print -1. Examples Input 6 1 4 4 7 4 1 Output 3 Input 5 2 2 5 2 5 Output 3 Input 4 1 3 3 7 Output -1 Input 2 2 8 Output 3 Tags: math Correct Solution: ``` a = int(input()) b = list(map(int, input().split())) x = set(b) xs = list(x) xs.sort() if len(xs) == 2: if sum(xs) % 2 != 0:print(xs[1] - xs[0]) else:print(int(sum(xs)/2) - xs[0]) elif len(xs) == 3: if xs[-1] - xs[1] == xs[1] - xs[0]: print(xs[1] - xs[0]) else:print(-1) elif len(xs) == 1: print(0) else: print(-1) ```
85,081
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You can choose any non-negative integer D (i.e. D ≥ 0), and for each a_i you can: * add D (only once), i. e. perform a_i := a_i + D, or * subtract D (only once), i. e. perform a_i := a_i - D, or * leave the value of a_i unchanged. It is possible that after an operation the value a_i becomes negative. Your goal is to choose such minimum non-negative integer D and perform changes in such a way, that all a_i are equal (i.e. a_1=a_2=...=a_n). Print the required D or, if it is impossible to choose such value D, print -1. For example, for array [2, 8] the value D=3 is minimum possible because you can obtain the array [5, 5] if you will add D to 2 and subtract D from 8. And for array [1, 4, 7, 7] the value D=3 is also minimum possible. You can add it to 1 and subtract it from 7 and obtain the array [4, 4, 4, 4]. Input The first line of the input contains one integer n (1 ≤ n ≤ 100) — the number of elements in a. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100) — the sequence a. Output Print one integer — the minimum non-negative integer value D such that if you add this value to some a_i, subtract this value from some a_i and leave some a_i without changes, all obtained values become equal. If it is impossible to choose such value D, print -1. Examples Input 6 1 4 4 7 4 1 Output 3 Input 5 2 2 5 2 5 Output 3 Input 4 1 3 3 7 Output -1 Input 2 2 8 Output 3 Submitted Solution: ``` import math n=input() a=list(map(lambda x:int(x),input().split())) a_min=min(a) a_max=max(a) isFind=False ans=math.inf for i in range(a_min,a_max+1): diff=0 flag=True for j in a: if j-i==0: continue else: if diff==0: diff=abs(i-j) elif abs(j-i)!=diff: flag=False break if flag: ans=min(ans,diff) isFind=True if not isFind: print(-1) else: print(ans) ``` Yes
85,082
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You can choose any non-negative integer D (i.e. D ≥ 0), and for each a_i you can: * add D (only once), i. e. perform a_i := a_i + D, or * subtract D (only once), i. e. perform a_i := a_i - D, or * leave the value of a_i unchanged. It is possible that after an operation the value a_i becomes negative. Your goal is to choose such minimum non-negative integer D and perform changes in such a way, that all a_i are equal (i.e. a_1=a_2=...=a_n). Print the required D or, if it is impossible to choose such value D, print -1. For example, for array [2, 8] the value D=3 is minimum possible because you can obtain the array [5, 5] if you will add D to 2 and subtract D from 8. And for array [1, 4, 7, 7] the value D=3 is also minimum possible. You can add it to 1 and subtract it from 7 and obtain the array [4, 4, 4, 4]. Input The first line of the input contains one integer n (1 ≤ n ≤ 100) — the number of elements in a. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100) — the sequence a. Output Print one integer — the minimum non-negative integer value D such that if you add this value to some a_i, subtract this value from some a_i and leave some a_i without changes, all obtained values become equal. If it is impossible to choose such value D, print -1. Examples Input 6 1 4 4 7 4 1 Output 3 Input 5 2 2 5 2 5 Output 3 Input 4 1 3 3 7 Output -1 Input 2 2 8 Output 3 Submitted Solution: ``` import math as mt import collections as cc import sys I=lambda:set(map(int,input().split())) n,=I() l=sorted(I()) if len(l)==1: print(0) elif len(l)==2: t=(abs(l[0]-l[-1])) d=abs(l[0]-l[-1]) tt=t+1 if d%2==0: tt=d//2 print(min(d,tt)) elif len(l)==3: d=l[1]-l[0] dd=l[2]-l[1] if d==dd: print(d) else: print(-1) else: print(-1) ``` Yes
85,083
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You can choose any non-negative integer D (i.e. D ≥ 0), and for each a_i you can: * add D (only once), i. e. perform a_i := a_i + D, or * subtract D (only once), i. e. perform a_i := a_i - D, or * leave the value of a_i unchanged. It is possible that after an operation the value a_i becomes negative. Your goal is to choose such minimum non-negative integer D and perform changes in such a way, that all a_i are equal (i.e. a_1=a_2=...=a_n). Print the required D or, if it is impossible to choose such value D, print -1. For example, for array [2, 8] the value D=3 is minimum possible because you can obtain the array [5, 5] if you will add D to 2 and subtract D from 8. And for array [1, 4, 7, 7] the value D=3 is also minimum possible. You can add it to 1 and subtract it from 7 and obtain the array [4, 4, 4, 4]. Input The first line of the input contains one integer n (1 ≤ n ≤ 100) — the number of elements in a. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100) — the sequence a. Output Print one integer — the minimum non-negative integer value D such that if you add this value to some a_i, subtract this value from some a_i and leave some a_i without changes, all obtained values become equal. If it is impossible to choose such value D, print -1. Examples Input 6 1 4 4 7 4 1 Output 3 Input 5 2 2 5 2 5 Output 3 Input 4 1 3 3 7 Output -1 Input 2 2 8 Output 3 Submitted Solution: ``` def solve(A): unique_elems = set(A) if len(unique_elems) == 1: return 0 if len(unique_elems) == 2: mn, mx = sorted(unique_elems) candidate = mx - mn D = candidate // 2 if mx - D == mn + D: return D else: return candidate max_A, min_A = max(A), min(A) mid_val = (max_A + min_A) // 2 D = mid_val - min_A for x in A: if x < mid_val and (x + D) != mid_val: return -1 elif x > mid_val and (x - D) != mid_val: return -1 return D n = int(input()) A = list(map(int, input().split())) print(solve(A)) ``` Yes
85,084
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You can choose any non-negative integer D (i.e. D ≥ 0), and for each a_i you can: * add D (only once), i. e. perform a_i := a_i + D, or * subtract D (only once), i. e. perform a_i := a_i - D, or * leave the value of a_i unchanged. It is possible that after an operation the value a_i becomes negative. Your goal is to choose such minimum non-negative integer D and perform changes in such a way, that all a_i are equal (i.e. a_1=a_2=...=a_n). Print the required D or, if it is impossible to choose such value D, print -1. For example, for array [2, 8] the value D=3 is minimum possible because you can obtain the array [5, 5] if you will add D to 2 and subtract D from 8. And for array [1, 4, 7, 7] the value D=3 is also minimum possible. You can add it to 1 and subtract it from 7 and obtain the array [4, 4, 4, 4]. Input The first line of the input contains one integer n (1 ≤ n ≤ 100) — the number of elements in a. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100) — the sequence a. Output Print one integer — the minimum non-negative integer value D such that if you add this value to some a_i, subtract this value from some a_i and leave some a_i without changes, all obtained values become equal. If it is impossible to choose such value D, print -1. Examples Input 6 1 4 4 7 4 1 Output 3 Input 5 2 2 5 2 5 Output 3 Input 4 1 3 3 7 Output -1 Input 2 2 8 Output 3 Submitted Solution: ``` n = int(input()) lst = sorted(list(set(map(int, input().split())))) if len(lst) >= 4: print(-1) else: if len(lst) == 1: print(0) elif len(lst) == 2: bet = (lst[1] + lst[0]) // 2 if bet - lst[0] == lst[1] - bet: print(bet - lst[0]) else: print(lst[1] - lst[0]) else: if lst[2] - lst[1] == lst[1] - lst[0]: print(lst[1] - lst[0]) else: print(-1) ``` Yes
85,085
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You can choose any non-negative integer D (i.e. D ≥ 0), and for each a_i you can: * add D (only once), i. e. perform a_i := a_i + D, or * subtract D (only once), i. e. perform a_i := a_i - D, or * leave the value of a_i unchanged. It is possible that after an operation the value a_i becomes negative. Your goal is to choose such minimum non-negative integer D and perform changes in such a way, that all a_i are equal (i.e. a_1=a_2=...=a_n). Print the required D or, if it is impossible to choose such value D, print -1. For example, for array [2, 8] the value D=3 is minimum possible because you can obtain the array [5, 5] if you will add D to 2 and subtract D from 8. And for array [1, 4, 7, 7] the value D=3 is also minimum possible. You can add it to 1 and subtract it from 7 and obtain the array [4, 4, 4, 4]. Input The first line of the input contains one integer n (1 ≤ n ≤ 100) — the number of elements in a. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100) — the sequence a. Output Print one integer — the minimum non-negative integer value D such that if you add this value to some a_i, subtract this value from some a_i and leave some a_i without changes, all obtained values become equal. If it is impossible to choose such value D, print -1. Examples Input 6 1 4 4 7 4 1 Output 3 Input 5 2 2 5 2 5 Output 3 Input 4 1 3 3 7 Output -1 Input 2 2 8 Output 3 Submitted Solution: ``` n=int(input()) a=[int(a) for a in input().split()] a.sort() s=set() min1=-9999 for i in a: s.add(i) if i>min1: min2=min1 min1=i if len(s)==2: print (max(a)-min(a)) elif len(s)==3: if (min2-min(a)==max(a)-min2): print (min2-min(a)) else: print (-1) else: print (-1) ``` No
85,086
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You can choose any non-negative integer D (i.e. D ≥ 0), and for each a_i you can: * add D (only once), i. e. perform a_i := a_i + D, or * subtract D (only once), i. e. perform a_i := a_i - D, or * leave the value of a_i unchanged. It is possible that after an operation the value a_i becomes negative. Your goal is to choose such minimum non-negative integer D and perform changes in such a way, that all a_i are equal (i.e. a_1=a_2=...=a_n). Print the required D or, if it is impossible to choose such value D, print -1. For example, for array [2, 8] the value D=3 is minimum possible because you can obtain the array [5, 5] if you will add D to 2 and subtract D from 8. And for array [1, 4, 7, 7] the value D=3 is also minimum possible. You can add it to 1 and subtract it from 7 and obtain the array [4, 4, 4, 4]. Input The first line of the input contains one integer n (1 ≤ n ≤ 100) — the number of elements in a. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100) — the sequence a. Output Print one integer — the minimum non-negative integer value D such that if you add this value to some a_i, subtract this value from some a_i and leave some a_i without changes, all obtained values become equal. If it is impossible to choose such value D, print -1. Examples Input 6 1 4 4 7 4 1 Output 3 Input 5 2 2 5 2 5 Output 3 Input 4 1 3 3 7 Output -1 Input 2 2 8 Output 3 Submitted Solution: ``` import os import sys def log(*args, **kwargs): if os.environ.get('CODEFR'): print(*args, **kwargs) n = int(input()) a = sorted(list(set(list(map(int, input().split()))))) if len(a) == 1: print(0) sys.exit(0) if len(a) == 2: result = (abs(a[0] - a[1]) / 2) if result != int(result): print(-1) else: print(int(result)) sys.exit(0) if len(a) == 3: if a[2] - a[1] == a[1] - a[0]: print(abs(a[0] - a[1])) else: print(-1) sys.exit(0) if len(a) > 3: print(-1) sys.exit(0) ``` No
85,087
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You can choose any non-negative integer D (i.e. D ≥ 0), and for each a_i you can: * add D (only once), i. e. perform a_i := a_i + D, or * subtract D (only once), i. e. perform a_i := a_i - D, or * leave the value of a_i unchanged. It is possible that after an operation the value a_i becomes negative. Your goal is to choose such minimum non-negative integer D and perform changes in such a way, that all a_i are equal (i.e. a_1=a_2=...=a_n). Print the required D or, if it is impossible to choose such value D, print -1. For example, for array [2, 8] the value D=3 is minimum possible because you can obtain the array [5, 5] if you will add D to 2 and subtract D from 8. And for array [1, 4, 7, 7] the value D=3 is also minimum possible. You can add it to 1 and subtract it from 7 and obtain the array [4, 4, 4, 4]. Input The first line of the input contains one integer n (1 ≤ n ≤ 100) — the number of elements in a. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100) — the sequence a. Output Print one integer — the minimum non-negative integer value D such that if you add this value to some a_i, subtract this value from some a_i and leave some a_i without changes, all obtained values become equal. If it is impossible to choose such value D, print -1. Examples Input 6 1 4 4 7 4 1 Output 3 Input 5 2 2 5 2 5 Output 3 Input 4 1 3 3 7 Output -1 Input 2 2 8 Output 3 Submitted Solution: ``` n=int(input()) a=[int(i) for i in input().split()] c=list(set(a)) if(len(c)==1): print(0) elif(len(c)==2): if(abs(c[1]-c[0])%2==0): print(abs(c[1]-c[0])//2) else: print(abs(c[1]-c[0])) elif(len(c)==3): if(abs(c[2]-c[1])==abs(c[1]-c[0])): print(abs(c[2]-c[1])) else: print(-1) else: print(-1) ``` No
85,088
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a_1, a_2, ..., a_n consisting of n integers. You can choose any non-negative integer D (i.e. D ≥ 0), and for each a_i you can: * add D (only once), i. e. perform a_i := a_i + D, or * subtract D (only once), i. e. perform a_i := a_i - D, or * leave the value of a_i unchanged. It is possible that after an operation the value a_i becomes negative. Your goal is to choose such minimum non-negative integer D and perform changes in such a way, that all a_i are equal (i.e. a_1=a_2=...=a_n). Print the required D or, if it is impossible to choose such value D, print -1. For example, for array [2, 8] the value D=3 is minimum possible because you can obtain the array [5, 5] if you will add D to 2 and subtract D from 8. And for array [1, 4, 7, 7] the value D=3 is also minimum possible. You can add it to 1 and subtract it from 7 and obtain the array [4, 4, 4, 4]. Input The first line of the input contains one integer n (1 ≤ n ≤ 100) — the number of elements in a. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100) — the sequence a. Output Print one integer — the minimum non-negative integer value D such that if you add this value to some a_i, subtract this value from some a_i and leave some a_i without changes, all obtained values become equal. If it is impossible to choose such value D, print -1. Examples Input 6 1 4 4 7 4 1 Output 3 Input 5 2 2 5 2 5 Output 3 Input 4 1 3 3 7 Output -1 Input 2 2 8 Output 3 Submitted Solution: ``` sizes=int(input()) number = list(map(int, list(input().split()))) l=[] for i in range(sizes): l.append(number[i]) mi=min(l) ma=max(l) li = list(set(l)) if len(li)==1: print(0) elif len(li)==3: difference = (ma-mi)/2 if ma-difference==mi+difference==li[1]: print(int(difference)) elif len(li)==2: difference = ma-mi print(int(difference)) else: print(-1) ``` No
85,089
Provide tags and a correct Python 3 solution for this coding contest problem. Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only T seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains n Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number t_i is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds). Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either t_i seconds or t_i + 1 seconds to solve the i-th crossword, equiprobably (with probability 1/2 he solves the crossword in exactly t_i seconds, and with probability 1/2 he has to spend an additional second to finish the crossword). All these events are independent. After T seconds pass (or after solving the last crossword, if he manages to do it in less than T seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate E — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as E = ∑ _{i = 0}^{n} i p_i, where p_i is the probability that Adilbek will solve exactly i crosswords. We can represent E as rational fraction P/Q with Q > 0. To give the answer, you should print P ⋅ Q^{-1} mod (10^9 + 7). Input The first line contains two integers n and T (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ T ≤ 2 ⋅ 10^{14}) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains n integers t_1, t_2, ..., t_n (1 ≤ t_i ≤ 10^9), where t_i is the time it takes a crossword expert to solve the i-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them. Output Print one integer — the expected value of the number of crosswords Adilbek solves in T seconds, expressed in the form of P ⋅ Q^{-1} mod (10^9 + 7). Examples Input 3 5 2 2 2 Output 750000007 Input 3 5 2 1 2 Output 125000003 Note The answer for the first sample is equal to 14/8. The answer for the second sample is equal to 17/8. Tags: combinatorics, dp, number theory, probabilities, two pointers Correct Solution: ``` mod = 10 ** 9 + 7 MAX = 2 * 10 ** 5+2 r = [1] * MAX factorial = [1] * MAX rfactorial = [1] * MAX rp = [1] * MAX #Permite precalcular factorial hasta "MAX", para evitar tener que calcularlo varias veces #dentro de la ejecucion del programa. for i in range(2, MAX): factorial[i] = i * factorial[i - 1] % mod r[i] = mod - (mod // i) * r[mod%i] % mod rfactorial[i] = rfactorial[i-1] * r[i] % mod #Calcula el inverso de "p" para evitar usar fracciones racionales. for i in range(1, MAX): rp[i] = rp[i - 1] * (mod + 1) // 2 % mod n, T = list(map(int, input().split())) t = list(map(int, input().split())) t.append(10**10+1) #Permite calcular las Combinacione de n en k. def Combination(n,k): return factorial[n]*rfactorial[k]*rfactorial[n-k] S=0 E=0 for i in range(0,n+1): sim = 0 for add in range(2): l_, r_ = max(0, T-S-t[i] + add), min(i, T-S) for x in range(l_, r_+1): sim += Combination(i,x) * rp[i+1] E = (E + i * sim) % mod S += t[i] print(E) ```
85,090
Provide tags and a correct Python 3 solution for this coding contest problem. Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only T seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains n Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number t_i is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds). Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either t_i seconds or t_i + 1 seconds to solve the i-th crossword, equiprobably (with probability 1/2 he solves the crossword in exactly t_i seconds, and with probability 1/2 he has to spend an additional second to finish the crossword). All these events are independent. After T seconds pass (or after solving the last crossword, if he manages to do it in less than T seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate E — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as E = ∑ _{i = 0}^{n} i p_i, where p_i is the probability that Adilbek will solve exactly i crosswords. We can represent E as rational fraction P/Q with Q > 0. To give the answer, you should print P ⋅ Q^{-1} mod (10^9 + 7). Input The first line contains two integers n and T (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ T ≤ 2 ⋅ 10^{14}) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains n integers t_1, t_2, ..., t_n (1 ≤ t_i ≤ 10^9), where t_i is the time it takes a crossword expert to solve the i-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them. Output Print one integer — the expected value of the number of crosswords Adilbek solves in T seconds, expressed in the form of P ⋅ Q^{-1} mod (10^9 + 7). Examples Input 3 5 2 2 2 Output 750000007 Input 3 5 2 1 2 Output 125000003 Note The answer for the first sample is equal to 14/8. The answer for the second sample is equal to 17/8. Tags: combinatorics, dp, number theory, probabilities, two pointers Correct Solution: ``` MOD = 10 ** 9 + 7 MAX = 5 * 10 ** 5 fac, ifac = [1] * MAX, [1] * MAX for i in range(2, MAX): fac[i] = fac[i - 1] * i % MOD ifac[-1] = pow(fac[-1], MOD - 2, MOD) for i in range(MAX - 2, 1, -1): ifac[i] = ifac[i + 1] * (i + 1) % MOD ipow2 = [1] * MAX for i in range(1, MAX): ipow2[i] = ipow2[i - 1] * (MOD + 1) // 2 % MOD choose = lambda n, k: fac[n] * ifac[k] % MOD * ifac[n - k] % MOD n, t = map(int, input().split()) a = list(map(int, input().split())) s = 0 p = [1] + [0] * (n + 1) k = cur = 0 for i in range(n): s += a[i] if s > t: break if s + i + 1 <= t: p[i + 1] = 1 continue if not cur: k = t - s for j in range(k + 1): cur += choose(i + 1, j) cur %= MOD else: cur = cur * 2 - choose(i, k) while k > t - s: cur -= choose(i + 1, k) k -= 1 cur %= MOD p[i + 1] = cur * ipow2[i + 1] % MOD print(sum((p[i] - p[i + 1]) * i % MOD for i in range(1, n + 1)) % MOD) ```
85,091
Provide tags and a correct Python 3 solution for this coding contest problem. Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only T seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains n Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number t_i is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds). Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either t_i seconds or t_i + 1 seconds to solve the i-th crossword, equiprobably (with probability 1/2 he solves the crossword in exactly t_i seconds, and with probability 1/2 he has to spend an additional second to finish the crossword). All these events are independent. After T seconds pass (or after solving the last crossword, if he manages to do it in less than T seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate E — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as E = ∑ _{i = 0}^{n} i p_i, where p_i is the probability that Adilbek will solve exactly i crosswords. We can represent E as rational fraction P/Q with Q > 0. To give the answer, you should print P ⋅ Q^{-1} mod (10^9 + 7). Input The first line contains two integers n and T (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ T ≤ 2 ⋅ 10^{14}) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains n integers t_1, t_2, ..., t_n (1 ≤ t_i ≤ 10^9), where t_i is the time it takes a crossword expert to solve the i-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them. Output Print one integer — the expected value of the number of crosswords Adilbek solves in T seconds, expressed in the form of P ⋅ Q^{-1} mod (10^9 + 7). Examples Input 3 5 2 2 2 Output 750000007 Input 3 5 2 1 2 Output 125000003 Note The answer for the first sample is equal to 14/8. The answer for the second sample is equal to 17/8. Tags: combinatorics, dp, number theory, probabilities, two pointers Correct Solution: ``` from sys import stdin, stdout, exit mod = 10**9 + 7 def modinv(x): return pow(x, mod-2, mod) N = 2*10**5 + 10 facts = [1]*N for i in range(1,N): facts[i] = facts[i-1] * i facts[i] %= mod def binom(n, k): ans = modinv(facts[k]) * modinv(facts[n-k]) ans %= mod ans *= facts[n] ans %= mod return ans #print("Finished preprocess") n, T = map(int, stdin.readline().split()) ts = list(map(int, stdin.readline().split())) ans = 0 total = sum(ts) running = total last_idx = n-1 while running > T: running -= ts[last_idx] last_idx -= 1 #print(last_idx+1) last_bd = -1 last_sum = 0 idx = last_idx while running + idx + 1 > T: bd = T - running # print("time remaining for", idx+1, "flips is", bd) cur_sum = last_sum + (binom(idx+1, last_bd) if last_bd >= 0 else 0) cur_sum *= modinv(2) cur_sum %= mod for fresh in range(last_bd+1, bd+1): cur_sum += binom(idx+1, fresh) cur_sum %= mod # print("pr of", idx+1, "flips is", cur_sum, cur_sum / (2**(idx+1))) ans += cur_sum * modinv(pow(2, idx+1, mod)) ans %= mod running -= ts[idx] last_bd = bd last_sum = cur_sum idx -= 1 #print(idx+1, "freebies") ans += idx+1 ans %= mod print(ans) ```
85,092
Provide tags and a correct Python 3 solution for this coding contest problem. Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only T seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains n Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number t_i is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds). Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either t_i seconds or t_i + 1 seconds to solve the i-th crossword, equiprobably (with probability 1/2 he solves the crossword in exactly t_i seconds, and with probability 1/2 he has to spend an additional second to finish the crossword). All these events are independent. After T seconds pass (or after solving the last crossword, if he manages to do it in less than T seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate E — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as E = ∑ _{i = 0}^{n} i p_i, where p_i is the probability that Adilbek will solve exactly i crosswords. We can represent E as rational fraction P/Q with Q > 0. To give the answer, you should print P ⋅ Q^{-1} mod (10^9 + 7). Input The first line contains two integers n and T (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ T ≤ 2 ⋅ 10^{14}) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains n integers t_1, t_2, ..., t_n (1 ≤ t_i ≤ 10^9), where t_i is the time it takes a crossword expert to solve the i-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them. Output Print one integer — the expected value of the number of crosswords Adilbek solves in T seconds, expressed in the form of P ⋅ Q^{-1} mod (10^9 + 7). Examples Input 3 5 2 2 2 Output 750000007 Input 3 5 2 1 2 Output 125000003 Note The answer for the first sample is equal to 14/8. The answer for the second sample is equal to 17/8. Tags: combinatorics, dp, number theory, probabilities, two pointers Correct Solution: ``` mod = 10 ** 9 + 7 MAX = 2 * 10 ** 5+2 r = [1] * MAX factorial = [1] * MAX rfactorial = [1] * MAX rp = [1] * MAX for i in range(2, MAX): factorial[i] = i * factorial[i - 1] % mod r[i] = mod - (mod // i) * r[mod%i] % mod rfactorial[i] = rfactorial[i-1] * r[i] % mod for i in range(1, MAX): rp[i] = rp[i - 1] * (mod + 1) // 2 % mod n, T = list(map(int, input().split())) t = list(map(int, input().split())) t.append(10**10+1) def Combination(n,k): return factorial[n]*rfactorial[k]*rfactorial[n-k] S=0 EX=0 for i in range(len(t)): cof = rp[1] for add in range(2): l_, r_ = max(0, T-S-t[i] + add), min(i, T-S) for x in range(l_, r_+1): EX = ( EX + i * Combination(i,x) * rp[i+1]) % mod S += t[i] print(EX) ```
85,093
Provide tags and a correct Python 3 solution for this coding contest problem. Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only T seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains n Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number t_i is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds). Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either t_i seconds or t_i + 1 seconds to solve the i-th crossword, equiprobably (with probability 1/2 he solves the crossword in exactly t_i seconds, and with probability 1/2 he has to spend an additional second to finish the crossword). All these events are independent. After T seconds pass (or after solving the last crossword, if he manages to do it in less than T seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate E — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as E = ∑ _{i = 0}^{n} i p_i, where p_i is the probability that Adilbek will solve exactly i crosswords. We can represent E as rational fraction P/Q with Q > 0. To give the answer, you should print P ⋅ Q^{-1} mod (10^9 + 7). Input The first line contains two integers n and T (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ T ≤ 2 ⋅ 10^{14}) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains n integers t_1, t_2, ..., t_n (1 ≤ t_i ≤ 10^9), where t_i is the time it takes a crossword expert to solve the i-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them. Output Print one integer — the expected value of the number of crosswords Adilbek solves in T seconds, expressed in the form of P ⋅ Q^{-1} mod (10^9 + 7). Examples Input 3 5 2 2 2 Output 750000007 Input 3 5 2 1 2 Output 125000003 Note The answer for the first sample is equal to 14/8. The answer for the second sample is equal to 17/8. Tags: combinatorics, dp, number theory, probabilities, two pointers Correct Solution: ``` mod = 10 ** 9 + 7 MAX = 2 * 10 ** 5+2 n, T = list(map(int, input().split())) t = [0] t += list(map(int, input().split())) t += [MAX] r = [1] * MAX factorial = [1] * MAX rfactorial = [1] * MAX rp = [1] * MAX sim = 0 sim_n = 0 sim_k = 0 E=0 S = [t[0]]*len(t) for i in range(1,len(t)): S[i] = S[i-1]+t[i] #Permite precalcular factorial hasta "MAX", para evitar tener que calcularlo varias veces #dentro de la ejecucion del programa. for i in range(2, MAX): factorial[i] = i * factorial[i - 1] % mod r[i] = mod - (mod // i) * r[mod%i] % mod rfactorial[i] = rfactorial[i-1] * r[i] % mod #Calcula el inverso de "p" para evitar usar fracciones racionales. for i in range(1, MAX): rp[i] = rp[i - 1] * (mod + 1) // 2 % mod #Permite calcular las Combinaciones de n en k. def Combination(n,k): if n < k: return 0 return factorial[n]*rfactorial[k]*rfactorial[n-k] def simC(x): aux = 0 mi = min(x,T-S[x]) for i in range(0,mi+1): aux += Combination(x,i)%mod return x,mi,aux def next_simC( next_x): mi1 = min(next_x,T-S[next_x]) aux_sim = 2*sim % mod aux_sim = (aux_sim + Combination(sim_n,sim_k + 1))%mod aux_sim_n = sim_n + 1 aux_sim_k = sim_k + 1 while aux_sim_k > mi1: aux_sim = (aux_sim - Combination(aux_sim_n,aux_sim_k)) % mod aux_sim_k -= 1 return aux_sim_n, aux_sim_k, aux_sim i = 1 while i <= n and S[i] + i <= T: i +=1 E +=1 if i <= n: sim_n,sim_k,sim = simC(i) for x in range(i,n+1): E = (E + rp[x]*sim)%mod if T-S[x+1] < 0: break sim_n,sim_k,sim = next_simC(x+1) print(E) ```
85,094
Provide tags and a correct Python 3 solution for this coding contest problem. Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only T seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains n Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number t_i is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds). Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either t_i seconds or t_i + 1 seconds to solve the i-th crossword, equiprobably (with probability 1/2 he solves the crossword in exactly t_i seconds, and with probability 1/2 he has to spend an additional second to finish the crossword). All these events are independent. After T seconds pass (or after solving the last crossword, if he manages to do it in less than T seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate E — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as E = ∑ _{i = 0}^{n} i p_i, where p_i is the probability that Adilbek will solve exactly i crosswords. We can represent E as rational fraction P/Q with Q > 0. To give the answer, you should print P ⋅ Q^{-1} mod (10^9 + 7). Input The first line contains two integers n and T (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ T ≤ 2 ⋅ 10^{14}) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains n integers t_1, t_2, ..., t_n (1 ≤ t_i ≤ 10^9), where t_i is the time it takes a crossword expert to solve the i-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them. Output Print one integer — the expected value of the number of crosswords Adilbek solves in T seconds, expressed in the form of P ⋅ Q^{-1} mod (10^9 + 7). Examples Input 3 5 2 2 2 Output 750000007 Input 3 5 2 1 2 Output 125000003 Note The answer for the first sample is equal to 14/8. The answer for the second sample is equal to 17/8. Tags: combinatorics, dp, number theory, probabilities, two pointers Correct Solution: ``` mod = 10 ** 9 + 7 MAX = 2 * 10 ** 5 + 10 r = [1] * MAX f = [1] * MAX rf = [1] * MAX rp2 = [1] * MAX for i in range(2, MAX): f[i] = f[i - 1] * i % mod r[i] = mod - (mod // i) * r[mod%i] % mod rf[i] = rf[i-1] * r[i] % mod for i in range(1, MAX): rp2[i] = rp2[i - 1] * (mod + 1) // 2 % mod n, T = list(map(int, input().split())) t = list(map(int, input().split())) t.append(10**14+1) S=0 E=0 for i in range(len(t)): cof = rp2[1] for add in range(2): l_, r_ = max(0, T-S-(t[i]-add)), min(i, T-S) for x in range(l_, r_+1): E = ( E + i * (f[i]*rf[x]*rf[i-x]) * rp2[i] * cof ) % mod S += t[i] print(E) ```
85,095
Provide tags and a correct Python 3 solution for this coding contest problem. Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only T seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains n Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number t_i is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds). Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either t_i seconds or t_i + 1 seconds to solve the i-th crossword, equiprobably (with probability 1/2 he solves the crossword in exactly t_i seconds, and with probability 1/2 he has to spend an additional second to finish the crossword). All these events are independent. After T seconds pass (or after solving the last crossword, if he manages to do it in less than T seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate E — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as E = ∑ _{i = 0}^{n} i p_i, where p_i is the probability that Adilbek will solve exactly i crosswords. We can represent E as rational fraction P/Q with Q > 0. To give the answer, you should print P ⋅ Q^{-1} mod (10^9 + 7). Input The first line contains two integers n and T (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ T ≤ 2 ⋅ 10^{14}) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains n integers t_1, t_2, ..., t_n (1 ≤ t_i ≤ 10^9), where t_i is the time it takes a crossword expert to solve the i-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them. Output Print one integer — the expected value of the number of crosswords Adilbek solves in T seconds, expressed in the form of P ⋅ Q^{-1} mod (10^9 + 7). Examples Input 3 5 2 2 2 Output 750000007 Input 3 5 2 1 2 Output 125000003 Note The answer for the first sample is equal to 14/8. The answer for the second sample is equal to 17/8. Tags: combinatorics, dp, number theory, probabilities, two pointers Correct Solution: ``` mod = 10 ** 9 + 7 MAX = 2 * 10 ** 5+1 r = [1] * MAX factorial = [1] * MAX rfactorial = [1] * MAX rp = [1] * MAX for i in range(2, MAX): factorial[i] = i * factorial[i - 1] % mod r[i] = mod - (mod // i) * r[mod%i] % mod rfactorial[i] = rfactorial[i-1] * r[i] % mod for i in range(1, MAX): rp[i] = rp[i - 1] * (mod + 1) // 2 % mod n, T = list(map(int, input().split())) t = list(map(int, input().split())) t.append(10**10+1) S=0 EX=0 for i in range(len(t)): cof = rp[1] for add in range(2): l_, r_ = max(0, T-S-t[i] + add), min(i, T-S) for x in range(l_, r_+1): EX = ( EX + i*(factorial[i]*rfactorial[x]*rfactorial[i-x]) * rp[i]*cof) % mod S += t[i] print(EX) ```
85,096
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only T seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains n Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number t_i is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds). Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either t_i seconds or t_i + 1 seconds to solve the i-th crossword, equiprobably (with probability 1/2 he solves the crossword in exactly t_i seconds, and with probability 1/2 he has to spend an additional second to finish the crossword). All these events are independent. After T seconds pass (or after solving the last crossword, if he manages to do it in less than T seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate E — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as E = ∑ _{i = 0}^{n} i p_i, where p_i is the probability that Adilbek will solve exactly i crosswords. We can represent E as rational fraction P/Q with Q > 0. To give the answer, you should print P ⋅ Q^{-1} mod (10^9 + 7). Input The first line contains two integers n and T (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ T ≤ 2 ⋅ 10^{14}) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains n integers t_1, t_2, ..., t_n (1 ≤ t_i ≤ 10^9), where t_i is the time it takes a crossword expert to solve the i-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them. Output Print one integer — the expected value of the number of crosswords Adilbek solves in T seconds, expressed in the form of P ⋅ Q^{-1} mod (10^9 + 7). Examples Input 3 5 2 2 2 Output 750000007 Input 3 5 2 1 2 Output 125000003 Note The answer for the first sample is equal to 14/8. The answer for the second sample is equal to 17/8. Submitted Solution: ``` from itertools import combinations from math import factorial mod = 10**9 + 7 n,T = map(int,input().split()) ti = [0] for i in map(int,input().split()): ti.append(i) ans = 0 def Modulo(a): b = mod residuo = 0 x = a // b residuo = a - (x*b) return residuo def Pow(a,x): ans = 1 while(x): if x&1: ans = ans*a%mod a=a*a%mod x = x>>1 return ans def Min(i): sim=0 for j in range(1,i+1): sim += ti[j] return min(T - sim,i) def Pi(i): sim = 0 mi = Min(i) for k in range(0,mi+1): sim += Modulo(int(factorial(i)/(factorial(k)*factorial(i-k)))) return sim * Pow(2**i,mod-2) for i in range(1,n+1): ans += Pi(i) ans = Modulo(ans) print(ans) print(17/8) ``` No
85,097
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only T seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains n Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number t_i is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds). Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either t_i seconds or t_i + 1 seconds to solve the i-th crossword, equiprobably (with probability 1/2 he solves the crossword in exactly t_i seconds, and with probability 1/2 he has to spend an additional second to finish the crossword). All these events are independent. After T seconds pass (or after solving the last crossword, if he manages to do it in less than T seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate E — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as E = ∑ _{i = 0}^{n} i p_i, where p_i is the probability that Adilbek will solve exactly i crosswords. We can represent E as rational fraction P/Q with Q > 0. To give the answer, you should print P ⋅ Q^{-1} mod (10^9 + 7). Input The first line contains two integers n and T (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ T ≤ 2 ⋅ 10^{14}) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains n integers t_1, t_2, ..., t_n (1 ≤ t_i ≤ 10^9), where t_i is the time it takes a crossword expert to solve the i-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them. Output Print one integer — the expected value of the number of crosswords Adilbek solves in T seconds, expressed in the form of P ⋅ Q^{-1} mod (10^9 + 7). Examples Input 3 5 2 2 2 Output 750000007 Input 3 5 2 1 2 Output 125000003 Note The answer for the first sample is equal to 14/8. The answer for the second sample is equal to 17/8. Submitted Solution: ``` mod = 10 ** 9 + 7 MAX = 2 * 10 ** 5 r = [1] * MAX factorial = [1] * MAX rfactorial = [1] * MAX rp = [1] * MAX for i in range(2, MAX): factorial[i] = i * factorial[i - 1] % mod r[i] = mod - (mod // i) * r[mod%i] % mod rfactorial[i] = rfactorial[i-1] * r[i] % mod for i in range(1, MAX): rp[i] = rp[i - 1] * (mod + 1) // 2 % mod n, T = list(map(int, input().split())) t = list(map(int, input().split())) t.append(10**14+1) S=0 EX=0 for i in range(n): cof = rp[1] for add in range(2): l_, r_ = max(0, T-S-t[i] + add), min(i, T-S) for x in range(l_, r_+1): EX = ( EX + i*(factorial[i]*(rfactorial[x]*rfactorial[i-x])) * rp[i]*cof) % mod S += t[i] print(EX) ``` No
85,098
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only T seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains n Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number t_i is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds). Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either t_i seconds or t_i + 1 seconds to solve the i-th crossword, equiprobably (with probability 1/2 he solves the crossword in exactly t_i seconds, and with probability 1/2 he has to spend an additional second to finish the crossword). All these events are independent. After T seconds pass (or after solving the last crossword, if he manages to do it in less than T seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate E — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as E = ∑ _{i = 0}^{n} i p_i, where p_i is the probability that Adilbek will solve exactly i crosswords. We can represent E as rational fraction P/Q with Q > 0. To give the answer, you should print P ⋅ Q^{-1} mod (10^9 + 7). Input The first line contains two integers n and T (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ T ≤ 2 ⋅ 10^{14}) — the number of crosswords and the time Adilbek has to spend, respectively. The second line contains n integers t_1, t_2, ..., t_n (1 ≤ t_i ≤ 10^9), where t_i is the time it takes a crossword expert to solve the i-th crossword. Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them. Output Print one integer — the expected value of the number of crosswords Adilbek solves in T seconds, expressed in the form of P ⋅ Q^{-1} mod (10^9 + 7). Examples Input 3 5 2 2 2 Output 750000007 Input 3 5 2 1 2 Output 125000003 Note The answer for the first sample is equal to 14/8. The answer for the second sample is equal to 17/8. Submitted Solution: ``` from sys import stdin, stdout, exit mod = 10**9 + 7 def gcd(x, y): if x > y: res = gcd(y, x) tmp = res[1] res[1] = res[2] res[2] = tmp return res if x == 0: return [y, 0, 1] res = gcd(y%x, x) tmp = res[1] res[1] = res[2] - tmp * (y // x) res[2] = tmp return res def modinv(x, m): res = gcd(x, m) res[1] %= m return res[1] N = 2*10**5 + 10 facts = [1]*N for i in range(1,N): facts[i] = facts[i-1] * i facts[i] %= mod def binom(n, k): ans = modinv(facts[k], mod) * modinv(facts[n-k], mod) ans %= mod ans *= facts[n] ans %= mod return ans #print("Finished preprocess") n, T = map(int, stdin.readline().split()) ts = list(map(int, stdin.readline().split())) ans = 0 total = sum(ts) running = total last_idx = n-1 while running > T: running -= ts[last_idx] last_idx -= 1 last_bd = -1 last_sum = 0 idx = last_idx while running + idx >= T: bd = T - running # print("time remaining for", idx, "is", bd) cur_sum = last_sum + binom(idx+2, last_bd) if last_bd >= 0 else 0 cur_sum *= modinv(2, mod) cur_sum %= mod for fresh in range(last_bd+1, bd+1): cur_sum += binom(idx+1, fresh) cur_sum %= mod # print("pr of", idx, "is", cur_sum / (2**(idx+1))) ans += cur_sum * modinv(pow(2, idx+1, mod), mod) ans %= mod running -= ts[idx] last_bd = bd last_sum = cur_sum idx -= 1 ans += idx+1 ans %= mod print(ans) ``` No
85,099