text
stringlengths
198
433k
conversation_id
int64
0
109k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A process RAM is a sequence of bytes that are indexed from 1 to n. Polycarpus's program contains such instructions as "memset", that is, the operations of filling memory cells on a segment with some value. The details are: the code only contains m instructions that look like "set13 a_i l_i". Instruction i fills a continuous memory segment of length li, starting from cell number ai, (that it cells with numbers ai, ai + 1, ..., ai + li - 1) with values 13. In Polycarpus's code, the optimizer's task is to remove the maximum number of instructions from his code in such a way that the remaining instructions set value 13 in all the memory bytes that got this value from the code before the optimization. Also, the value 13 should be set only in the memory bytes that got this value from the code before the optimization. Your task is to implement the optimizer for such program. Input The first line contains integers n and m (1 ≤ n ≤ 2·106, 1 ≤ m ≤ 2·105) — the number of bytes (memory cells) and the number of instructions in Polycarpus's code. Then m lines follow, each line contains a pair of integers ai, li (1 ≤ ai ≤ n, 1 ≤ li ≤ n - ai + 1). Output Print in the first line the sought maximum number of instructions that can be removed from the code. In the second line print the numbers of the instructions. The instructions are numbered from 1 to m in the order they appeared in the input. If there are multiple solutions, print any of them. Examples Input 10 4 3 3 3 1 4 1 9 2 Output 2 2 3 Input 1 1 1 1 Output 0 Submitted Solution: ``` #!/usr/bin/env python3 def is_inside(a, b): if a[0] > b[0] and a[0]+a[1] < b[0]+b[1]: return True return False n, m = map(int, input().split()) a = [list(map(int, input().split())) for i in range(m)] res = [] for i in range(m): for j in range(m): if i != j and i not in res and is_inside(a[i], a[j]): res.append(i) print(len(res)) for i in res: print(i + 1, end=' ') ``` No
89,600
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A process RAM is a sequence of bytes that are indexed from 1 to n. Polycarpus's program contains such instructions as "memset", that is, the operations of filling memory cells on a segment with some value. The details are: the code only contains m instructions that look like "set13 a_i l_i". Instruction i fills a continuous memory segment of length li, starting from cell number ai, (that it cells with numbers ai, ai + 1, ..., ai + li - 1) with values 13. In Polycarpus's code, the optimizer's task is to remove the maximum number of instructions from his code in such a way that the remaining instructions set value 13 in all the memory bytes that got this value from the code before the optimization. Also, the value 13 should be set only in the memory bytes that got this value from the code before the optimization. Your task is to implement the optimizer for such program. Input The first line contains integers n and m (1 ≤ n ≤ 2·106, 1 ≤ m ≤ 2·105) — the number of bytes (memory cells) and the number of instructions in Polycarpus's code. Then m lines follow, each line contains a pair of integers ai, li (1 ≤ ai ≤ n, 1 ≤ li ≤ n - ai + 1). Output Print in the first line the sought maximum number of instructions that can be removed from the code. In the second line print the numbers of the instructions. The instructions are numbered from 1 to m in the order they appeared in the input. If there are multiple solutions, print any of them. Examples Input 10 4 3 3 3 1 4 1 9 2 Output 2 2 3 Input 1 1 1 1 Output 0 Submitted Solution: ``` #!/usr/bin/env python3 def is_inside(a, b): if a[0] >= b[0] and a[0]+a[1] <= b[0]+b[1]: return True return False n, m = map(int, input().split()) a = [list(map(int, input().split())) for i in range(m)] res = [] for i in range(m): for j in range(m): if i != j and j not in res and is_inside(a[i], a[j]): res.append(i) print(len(res)) for i in res: print(i + 1, end=' ') ``` No
89,601
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A process RAM is a sequence of bytes that are indexed from 1 to n. Polycarpus's program contains such instructions as "memset", that is, the operations of filling memory cells on a segment with some value. The details are: the code only contains m instructions that look like "set13 a_i l_i". Instruction i fills a continuous memory segment of length li, starting from cell number ai, (that it cells with numbers ai, ai + 1, ..., ai + li - 1) with values 13. In Polycarpus's code, the optimizer's task is to remove the maximum number of instructions from his code in such a way that the remaining instructions set value 13 in all the memory bytes that got this value from the code before the optimization. Also, the value 13 should be set only in the memory bytes that got this value from the code before the optimization. Your task is to implement the optimizer for such program. Input The first line contains integers n and m (1 ≤ n ≤ 2·106, 1 ≤ m ≤ 2·105) — the number of bytes (memory cells) and the number of instructions in Polycarpus's code. Then m lines follow, each line contains a pair of integers ai, li (1 ≤ ai ≤ n, 1 ≤ li ≤ n - ai + 1). Output Print in the first line the sought maximum number of instructions that can be removed from the code. In the second line print the numbers of the instructions. The instructions are numbered from 1 to m in the order they appeared in the input. If there are multiple solutions, print any of them. Examples Input 10 4 3 3 3 1 4 1 9 2 Output 2 2 3 Input 1 1 1 1 Output 0 Submitted Solution: ``` #!/usr/bin/env python3 def is_inside(a, b): if a[0] >= b[0] and a[0]+a[1] <= b[0]+b[1]: return True return False n, m = map(int, input().split()) a = [list(map(int, input().split())) for i in range(m)] res = [] for i in range(m): for j in range(m): if i != j and j not in res and is_inside(a[i], a[j]): res.append(i) break print(len(res)) for i in res: print(i + 1, end=' ') ``` No
89,602
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms. Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions: 1. Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units; 2. Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items. Input The first line contains five integers n, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104). The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100). Output In the single line print a single number — the answer to the problem. Examples Input 3 4 4 19 1 42 3 99 Output 576 Input 4 7 2 3 9 1 2 3 4 Output 34 Note Consider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units. The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units. Tags: brute force, greedy, math Correct Solution: ``` n, l, r, ql, qr = map(int, input().split()) w = [0] + list(map(int, input().split())) for i in range(1, n + 1): w[i] += w[i - 1] s = w[n] print(min(l * w[i] + r * (s - w[i]) + ql * max(0, 2 * i - n - 1) + qr * max(0, n - 2 * i - 1) for i in range(n + 1))) ```
89,603
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms. Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions: 1. Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units; 2. Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items. Input The first line contains five integers n, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104). The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100). Output In the single line print a single number — the answer to the problem. Examples Input 3 4 4 19 1 42 3 99 Output 576 Input 4 7 2 3 9 1 2 3 4 Output 34 Note Consider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units. The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units. Tags: brute force, greedy, math Correct Solution: ``` from __future__ import division, print_function import os import sys from io import BytesIO, IOBase from math import inf def main(): n, l, r, ql, qr = [ int(x) for x in input().split() ] weight = [ int(x) for x in input().split() ] preffix = [0] * n preffix[0] = weight[0] for i in range(1, n): preffix[i] = preffix[i-1] + weight[i] suffix = [0] * n suffix[n-1] = weight[n-1] for i in range(n - 2, -1, -1): suffix[i] = weight[i] + suffix[i+1] bestAnswer = inf for i in range(-1, n): leftToRemove = i + 1 rightToRemove = n - leftToRemove if leftToRemove > rightToRemove: numOfNotCanceled = max(leftToRemove - rightToRemove - 1, 0) total = ( (preffix[i] if i >= 0 else 0) * l + (suffix[i+1] if i < n - 1 else 0) * r + numOfNotCanceled * ql ) else: numOfNotCanceled = max(rightToRemove - leftToRemove - 1, 0) total = ( (preffix[i] if i >= 0 else 0) * l + (suffix[i+1] if i < n - 1 else 0) * r + numOfNotCanceled * qr ) bestAnswer = min(bestAnswer, total) print(bestAnswer) BUFFSIZE = 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, BUFFSIZE)) 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, BUFFSIZE)) 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") input = lambda: sys.stdin.readline().rstrip("\r\n") def print(*args, **kwargs): sep = kwargs.pop("sep", " ") file = kwargs.pop("file", sys.stdout) atStart = True for x in args: if not atStart: file.write(sep) file.write(str(x)) atStart = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) main() ```
89,604
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms. Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions: 1. Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units; 2. Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items. Input The first line contains five integers n, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104). The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100). Output In the single line print a single number — the answer to the problem. Examples Input 3 4 4 19 1 42 3 99 Output 576 Input 4 7 2 3 9 1 2 3 4 Output 34 Note Consider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units. The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units. Tags: brute force, greedy, math Correct Solution: ``` def solve(lst, l, r, left, right): left_sum = [0] right_sum = [0] * (len(lst) + 1) cum_sum = 0 for i in range(len(lst)): cum_sum += lst[i] left_sum.append(cum_sum) cum_sum = 0 for i in reversed(range(len(lst))): cum_sum += lst[i] right_sum[i] = cum_sum #print(lst, left_sum, right_sum) min_cost = float('inf') for i in range(len(lst)+1): cost = left_sum[i] * l + right_sum[i]*r #print(i, cost, left_sum[i],l, right_sum[i], r) if i > n-i: cost += left * (2*i -n -1) elif i < n - i: cost += right *(n - 1- 2*i) #print(cost) min_cost = min(min_cost, cost) return min_cost n, l, r, left, right = list(map(int, input().split())) lst = list(map(int, input().split())) print(solve(lst, l, r, left, right)) ```
89,605
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms. Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions: 1. Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units; 2. Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items. Input The first line contains five integers n, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104). The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100). Output In the single line print a single number — the answer to the problem. Examples Input 3 4 4 19 1 42 3 99 Output 576 Input 4 7 2 3 9 1 2 3 4 Output 34 Note Consider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units. The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units. Tags: brute force, greedy, math Correct Solution: ``` import sys from os import path if(path.exists('input.txt')): sys.stdin = open("input.txt", "r") sys.stdout = open("output.txt", "w") N = 10**5 + 5 n, l, r, q1, q2 = map(int, input().split()) w = [int(x) for x in input().split()] pre = [0] * N for i in range(n): pre[i + 1] = pre[i] + w[i] ans = 10**18 for i in range(n + 1): curr = pre[i] * l + (pre[n] - pre[i]) * r x, y = i, n - i if(x < y): curr += q2 * (y - x - 1) elif(x > y): curr += q1 * (x - y - 1) ans = min(ans, curr) print(ans) ```
89,606
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms. Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions: 1. Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units; 2. Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items. Input The first line contains five integers n, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104). The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100). Output In the single line print a single number — the answer to the problem. Examples Input 3 4 4 19 1 42 3 99 Output 576 Input 4 7 2 3 9 1 2 3 4 Output 34 Note Consider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units. The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units. Tags: brute force, greedy, math Correct Solution: ``` #------------------------template--------------------------# import os import sys from math import * from collections import * from fractions import * from bisect import * from heapq import* from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ALPHA='abcdefghijklmnopqrstuvwxyz' M=998244353 EPS=1e-6 def value():return tuple(map(int,input().split())) def array():return [int(i) for i in input().split()] def Int():return int(input()) def Str():return input() def arrayS():return [i for i in input().split()] #-------------------------code---------------------------# # vsInput() n,l,r,ql,qr=value() w=array() ans=inf tot=sum(w) cur=w[0] for i in range(1,n): tans=cur*l+(tot-cur)*r lefts=i rights=n-i if(lefts>rights+1): extra=lefts-rights-1 tans+=extra*ql if(rights>lefts+1): extra=rights-lefts-1 tans+=extra*qr # print(tans,lefts,rights) ans=min(ans,tans) cur+=w[i] ans=min(ans,tot*l+n*ql-ql,tot*r+n*qr-qr) print(ans) ```
89,607
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms. Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions: 1. Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units; 2. Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items. Input The first line contains five integers n, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104). The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100). Output In the single line print a single number — the answer to the problem. Examples Input 3 4 4 19 1 42 3 99 Output 576 Input 4 7 2 3 9 1 2 3 4 Output 34 Note Consider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units. The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units. Tags: brute force, greedy, math Correct Solution: ``` n, l, r, ql, qr = list(map(int, input().split())) w = list(map(int, input().split())) sum = 0 sums = [] for i in range(n): sum += w[i] sums.append(sum) min = r * sum + qr * (n - 1) for i in range(n): ss = l * sums[i] + r * (sum - sums[i]) if i + 1 > n - i - 1 and i - n + i + 1 > 0: ss += ql * (i - n + i + 1) elif i + 1 < n - i - 1 and n - i - 2 - i > 1: ss += qr * (n - i - 2 - i - 1) if ss < min: min = ss print(min) ```
89,608
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms. Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions: 1. Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units; 2. Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items. Input The first line contains five integers n, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104). The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100). Output In the single line print a single number — the answer to the problem. Examples Input 3 4 4 19 1 42 3 99 Output 576 Input 4 7 2 3 9 1 2 3 4 Output 34 Note Consider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units. The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units. Tags: brute force, greedy, math Correct Solution: ``` n, l, r, Ql, Qr = map(int, input().split()) s, v = [0] * (n + 1), 2 * 10 ** 9 for i, wi in enumerate(map(int, input().split())): s[i + 1] = s[i] + wi for lc in range(0, n + 1): rc = n - lc c = s[lc] * l + (s[n] - s[lc]) * r if lc > rc + 1: c += (lc - rc - 1) * Ql elif rc > lc + 1: c += (rc - lc - 1) * Qr v = min(v, c) print(v) ```
89,609
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms. Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions: 1. Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units; 2. Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items. Input The first line contains five integers n, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104). The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100). Output In the single line print a single number — the answer to the problem. Examples Input 3 4 4 19 1 42 3 99 Output 576 Input 4 7 2 3 9 1 2 3 4 Output 34 Note Consider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units. The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units. Tags: brute force, greedy, math Correct Solution: ``` n,l,r,ql,qr=map(int,input().split()) arr=[int(i) for i in input().split()] #brute force is the mother of all approaches mini=10**20 sm=sum(arr) appaji=0 curr=0 for i in range(n+1): if i>0: curr+=arr[i-1] now=curr*l+(sm-curr)*r j=n-i if i>j: now+=(i-j-1)*ql # appaji 1 if j>i: now+=(j-i-1)*qr #appaji 2 mini=min(mini,now) print(mini) ```
89,610
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms. Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions: 1. Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units; 2. Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items. Input The first line contains five integers n, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104). The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100). Output In the single line print a single number — the answer to the problem. Examples Input 3 4 4 19 1 42 3 99 Output 576 Input 4 7 2 3 9 1 2 3 4 Output 34 Note Consider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units. The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units. Submitted Solution: ``` #!/usr/bin/python3 import sys n, l, r, ql, qr = map(int, sys.stdin.readline().strip().split()) w = [int(x) for x in sys.stdin.readline().strip().split()] s = [0] for i in range(0, n): s.append(s[-1] + w[i]) def cost(left): right = n - left diff = left - right bonus = 0 if diff > 0: # left part is larger bonus = ql * (diff - 1) elif diff < 0: # right part is larger bonus = qr * (-diff - 1) return bonus + l * s[left] + r * (s[n] - s[left]) best = cost(0) for left in range(1, n+1): c = cost(left) if c < best: best = c print(best) ``` Yes
89,611
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms. Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions: 1. Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units; 2. Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items. Input The first line contains five integers n, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104). The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100). Output In the single line print a single number — the answer to the problem. Examples Input 3 4 4 19 1 42 3 99 Output 576 Input 4 7 2 3 9 1 2 3 4 Output 34 Note Consider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units. The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units. Submitted Solution: ``` n, l, r, p, q = map(int, input().split()) arr = list(map(int, input().split())) res, s, d = int(1<<62), sum(arr), 0 for i in range(n+1): if i > 0: d += arr[i-1] t = d * l + (s - d) * r j = n - i if i > j: t += (i - j - 1) * p if i < j: t += (j - i - 1) * q res = min(res, t) print(res) ``` Yes
89,612
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms. Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions: 1. Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units; 2. Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items. Input The first line contains five integers n, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104). The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100). Output In the single line print a single number — the answer to the problem. Examples Input 3 4 4 19 1 42 3 99 Output 576 Input 4 7 2 3 9 1 2 3 4 Output 34 Note Consider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units. The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units. Submitted Solution: ``` import sys from math import log2,floor,ceil,sqrt # import bisect # from collections import deque Ri = lambda : [int(x) for x in sys.stdin.readline().split()] ri = lambda : sys.stdin.readline().strip() def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)] def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') INF = 10 ** 18 MOD = 10**9+7 n,l,r,ql,qr = Ri() a = Ri() lsumm = [0]*(n+1) rsumm = [0]*(n+1) ite= 1 for i in range(0,n): lsumm[i+1] = lsumm[i]+a[i] for i in range(n-1,-1,-1): rsumm[ite] = rsumm[ite-1]+a[i] ite+=1 # print(lsumm,rsumm) tans = INF for i in range(0,n+1): ans = lsumm[i]*l+rsumm[n-i]*r if i < n-i : ans+=(n-i-i-1)*qr elif i > n-i : ans+=(i-(n-i)-1)*ql tans = min(tans,ans) print(tans) ``` Yes
89,613
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms. Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions: 1. Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units; 2. Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items. Input The first line contains five integers n, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104). The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100). Output In the single line print a single number — the answer to the problem. Examples Input 3 4 4 19 1 42 3 99 Output 576 Input 4 7 2 3 9 1 2 3 4 Output 34 Note Consider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units. The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units. Submitted Solution: ``` n, l, r, Ql, Qr = [int(x) for x in input().split(' ')] w = [int(x) for x in input().split(' ')]; sum = [0 for x in range(n+1)]; for i in range(1, n+1): sum[i] = sum[i-1] + w[i-1]; ans = 2**32; for k in range(0, n+1): temp = sum[k]*l + (sum[n] - sum[k])*r; if (2*k > n): temp += (2*k-n-1)*Ql; elif (2*k < n): temp += (n-2*k-1)*Qr; ans = min(ans, temp); print(ans); ``` Yes
89,614
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms. Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions: 1. Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units; 2. Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items. Input The first line contains five integers n, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104). The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100). Output In the single line print a single number — the answer to the problem. Examples Input 3 4 4 19 1 42 3 99 Output 576 Input 4 7 2 3 9 1 2 3 4 Output 34 Note Consider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units. The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units. Submitted Solution: ``` from __future__ import division, print_function import os import sys from io import BytesIO, IOBase from math import inf def main(): n, l, r, ql, qr = [ int(x) for x in input().split() ] weight = [ int(x) for x in input().split() ] preffix = [0] * n preffix[0] = weight[0] for i in range(1, n): preffix[i] = preffix[i-1] + weight[i] suffix = [0] * n suffix[n-1] = weight[n-1] for i in range(n - 2, -1, -1): suffix[i] = weight[i] + suffix[i+1] bestAnswer = inf for i in range(n): leftToRemove = i + 1 rightToRemove = n - leftToRemove if leftToRemove > rightToRemove: numOfNotCanceled = max(leftToRemove - rightToRemove - 1, 0) total = ( preffix[i] * l + (suffix[i+1] if i < n - 1 else 0) * r + numOfNotCanceled * ql ) else: numOfNotCanceled = max(rightToRemove - leftToRemove - 1, 0) total = ( preffix[i] * l + (suffix[i+1] if i < n - 1 else 0) * r + numOfNotCanceled * qr ) bestAnswer = min(bestAnswer, total) print(bestAnswer) BUFFSIZE = 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, BUFFSIZE)) 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, BUFFSIZE)) 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") input = lambda: sys.stdin.readline().rstrip("\r\n") def print(*args, **kwargs): sep = kwargs.pop("sep", " ") file = kwargs.pop("file", sys.stdout) atStart = True for x in args: if not atStart: file.write(sep) file.write(str(x)) atStart = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) main() ``` No
89,615
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms. Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions: 1. Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units; 2. Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items. Input The first line contains five integers n, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104). The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100). Output In the single line print a single number — the answer to the problem. Examples Input 3 4 4 19 1 42 3 99 Output 576 Input 4 7 2 3 9 1 2 3 4 Output 34 Note Consider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units. The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units. Submitted Solution: ``` n, l, r, q1, q2 = map(int, input().split()) item = list(map(int, input().split())) pre = [item[0]] + [ 0 for i in range(1, n)] suf = [ 0 for i in range(0, n-1)] + [item[n-1], 0] for i in range(1, n): pre[i] = pre[i-1] + item[i] for i in range(n-2, -1, -1): suf[i] = suf[i+1] + item[i] # print(pre, suf) ans = 1e20 for i in range(0, n): a, b = i, n-i c = pre[i]*l + suf[i+1]*r + (q2*(a-b-1) if a>b else q1*(b-a-1) if b>a else 0) # print(c) ans = min(ans, c) print(ans) ``` No
89,616
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms. Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions: 1. Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units; 2. Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items. Input The first line contains five integers n, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104). The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100). Output In the single line print a single number — the answer to the problem. Examples Input 3 4 4 19 1 42 3 99 Output 576 Input 4 7 2 3 9 1 2 3 4 Output 34 Note Consider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units. The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units. Submitted Solution: ``` n, l, r, q1, q2 = map(int, input().split()) item = list(map(int, input().split())) pre = [item[0]] + [ 0 for i in range(1, n)] suf = [ 0 for i in range(0, n-1)] + [item[n-1], 0] for i in range(1, n): pre[i] = pre[i-1] + item[i] for i in range(n-2, -1, -1): suf[i] = suf[i+1] + item[i] print(q1, q2) # print(pre, suf) ans = 1e20 for i in range(0, n): a, b = i+1, n-i-1 c = pre[i]*l + suf[i+1]*r + (q1*(a-b-1) if a>b else q2*(b-a-1) if b>a else 0) # print(c) ans = min(ans, c) print(ans) ``` No
89,617
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms. Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions: 1. Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units; 2. Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items. Input The first line contains five integers n, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104). The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100). Output In the single line print a single number — the answer to the problem. Examples Input 3 4 4 19 1 42 3 99 Output 576 Input 4 7 2 3 9 1 2 3 4 Output 34 Note Consider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units. The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units. Submitted Solution: ``` import sys def get_ints(): return list(map(int, sys.stdin.readline().strip().split())) arr = get_ints() n = arr[0] l = arr[1] r = arr[2] ql = arr[3] qr = arr[4] arr = get_ints() arr = sorted(arr) if l == r : sums = l*sum(arr) print(sums) elif l < r : #print(arr) rightindex = len(arr) - 1 leftindex = 0 ans = 0 flag = 0 while leftindex <= rightindex: if flag == 0: ans += arr[rightindex] * l flag = 1 rightindex -= 1 elif flag == 1 : if arr[leftindex] * r <= arr[leftindex] * l + ql: flag = 0 ans += arr[leftindex] * r leftindex += 1 else: ans += arr[leftindex] * l + ql leftindex += 1 print(ans) else: rightindex = len(arr) - 1 leftindex = 0 ans = 0 flag = 0 while leftindex <= rightindex: if flag == 0: ans += arr[rightindex] * r flag = 1 rightindex -= 1 elif flag == 1 : if arr[leftindex] * l <= arr[leftindex] * r + qr: flag = 0 ans += arr[leftindex] * l leftindex += 1 else: ans += arr[leftindex] * r + qr leftindex += 1 print(ans) ``` No
89,618
Provide tags and a correct Python 3 solution for this coding contest problem. Two semifinals have just been in the running tournament. Each semifinal had n participants. There are n participants advancing to the finals, they are chosen as follows: from each semifinal, we choose k people (0 ≤ 2k ≤ n) who showed the best result in their semifinals and all other places in the finals go to the people who haven't ranked in the top k in their semifinal but got to the n - 2k of the best among the others. The tournament organizers hasn't yet determined the k value, so the participants want to know who else has any chance to get to the finals and who can go home. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of participants in each semifinal. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109) — the results of the i-th participant (the number of milliseconds he needs to cover the semifinals distance) of the first and second semifinals, correspondingly. All results are distinct. Sequences a1, a2, ..., an and b1, b2, ..., bn are sorted in ascending order, i.e. in the order the participants finished in the corresponding semifinal. Output Print two strings consisting of n characters, each equals either "0" or "1". The first line should correspond to the participants of the first semifinal, the second line should correspond to the participants of the second semifinal. The i-th character in the j-th line should equal "1" if the i-th participant of the j-th semifinal has any chances to advance to the finals, otherwise it should equal a "0". Examples Input 4 9840 9920 9860 9980 9930 10020 10040 10090 Output 1110 1100 Input 4 9900 9850 9940 9930 10000 10020 10060 10110 Output 1100 1100 Note Consider the first sample. Each semifinal has 4 participants. The results of the first semifinal are 9840, 9860, 9930, 10040. The results of the second semifinal are 9920, 9980, 10020, 10090. * If k = 0, the finalists are determined by the time only, so players 9840, 9860, 9920 and 9930 advance to the finals. * If k = 1, the winners from both semifinals move to the finals (with results 9840 and 9920), and the other places are determined by the time (these places go to the sportsmen who run the distance in 9860 and 9930 milliseconds). * If k = 2, then first and second places advance from each seminfial, these are participants with results 9840, 9860, 9920 and 9980 milliseconds. Tags: implementation, sortings Correct Solution: ``` def semifinals(l1,l2): output1=[0]*len(l1) output2=[0]*len(l2) n=len(l1) k = len(l1)//2 output1[0:k]=[1]*k output2[0:k]=[1]*k i = k while i < len(l1): if l1[i]<l2[n-i-1]: output1[i]=1 if l2[i]<l1[n-i-1]: output2[i]=1 i+=1 output1=''.join([str(x) for x in output1]) output2=''.join([str(x) for x in output2]) return (output1,output2) n=int(input()) l1=[] l2=[] for i in range(n): a = [int(x) for x in input().split()] l1.append(a[0]) l2.append(a[1]) print (semifinals(l1,l2)[0]) print (semifinals(l1,l2)[1]) ```
89,619
Provide tags and a correct Python 3 solution for this coding contest problem. Two semifinals have just been in the running tournament. Each semifinal had n participants. There are n participants advancing to the finals, they are chosen as follows: from each semifinal, we choose k people (0 ≤ 2k ≤ n) who showed the best result in their semifinals and all other places in the finals go to the people who haven't ranked in the top k in their semifinal but got to the n - 2k of the best among the others. The tournament organizers hasn't yet determined the k value, so the participants want to know who else has any chance to get to the finals and who can go home. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of participants in each semifinal. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109) — the results of the i-th participant (the number of milliseconds he needs to cover the semifinals distance) of the first and second semifinals, correspondingly. All results are distinct. Sequences a1, a2, ..., an and b1, b2, ..., bn are sorted in ascending order, i.e. in the order the participants finished in the corresponding semifinal. Output Print two strings consisting of n characters, each equals either "0" or "1". The first line should correspond to the participants of the first semifinal, the second line should correspond to the participants of the second semifinal. The i-th character in the j-th line should equal "1" if the i-th participant of the j-th semifinal has any chances to advance to the finals, otherwise it should equal a "0". Examples Input 4 9840 9920 9860 9980 9930 10020 10040 10090 Output 1110 1100 Input 4 9900 9850 9940 9930 10000 10020 10060 10110 Output 1100 1100 Note Consider the first sample. Each semifinal has 4 participants. The results of the first semifinal are 9840, 9860, 9930, 10040. The results of the second semifinal are 9920, 9980, 10020, 10090. * If k = 0, the finalists are determined by the time only, so players 9840, 9860, 9920 and 9930 advance to the finals. * If k = 1, the winners from both semifinals move to the finals (with results 9840 and 9920), and the other places are determined by the time (these places go to the sportsmen who run the distance in 9860 and 9930 milliseconds). * If k = 2, then first and second places advance from each seminfial, these are participants with results 9840, 9860, 9920 and 9980 milliseconds. Tags: implementation, sortings Correct Solution: ``` n = int(input()) p1=['0' for _ in range(n)] p2=['0' for _ in range(n)] t1=[] t2=[] for i in range(n): a, b = map(int, input().split()) t1.append((a,i)) t2.append((b,i)) t2.sort() t1.sort() for k in range((n//2)): p1[t1[k][1]]='1' p2[t2[k][1]]='1' i=0 j=0 for k in range(n): if t1[i][0]<t2[j][0]: p1[t1[i][1]]='1' i+=1 else: p2[t2[j][1]]='1' j+=1 print("".join(p1)) print("".join(p2)) ```
89,620
Provide tags and a correct Python 3 solution for this coding contest problem. Two semifinals have just been in the running tournament. Each semifinal had n participants. There are n participants advancing to the finals, they are chosen as follows: from each semifinal, we choose k people (0 ≤ 2k ≤ n) who showed the best result in their semifinals and all other places in the finals go to the people who haven't ranked in the top k in their semifinal but got to the n - 2k of the best among the others. The tournament organizers hasn't yet determined the k value, so the participants want to know who else has any chance to get to the finals and who can go home. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of participants in each semifinal. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109) — the results of the i-th participant (the number of milliseconds he needs to cover the semifinals distance) of the first and second semifinals, correspondingly. All results are distinct. Sequences a1, a2, ..., an and b1, b2, ..., bn are sorted in ascending order, i.e. in the order the participants finished in the corresponding semifinal. Output Print two strings consisting of n characters, each equals either "0" or "1". The first line should correspond to the participants of the first semifinal, the second line should correspond to the participants of the second semifinal. The i-th character in the j-th line should equal "1" if the i-th participant of the j-th semifinal has any chances to advance to the finals, otherwise it should equal a "0". Examples Input 4 9840 9920 9860 9980 9930 10020 10040 10090 Output 1110 1100 Input 4 9900 9850 9940 9930 10000 10020 10060 10110 Output 1100 1100 Note Consider the first sample. Each semifinal has 4 participants. The results of the first semifinal are 9840, 9860, 9930, 10040. The results of the second semifinal are 9920, 9980, 10020, 10090. * If k = 0, the finalists are determined by the time only, so players 9840, 9860, 9920 and 9930 advance to the finals. * If k = 1, the winners from both semifinals move to the finals (with results 9840 and 9920), and the other places are determined by the time (these places go to the sportsmen who run the distance in 9860 and 9930 milliseconds). * If k = 2, then first and second places advance from each seminfial, these are participants with results 9840, 9860, 9920 and 9980 milliseconds. Tags: implementation, sortings Correct Solution: ``` def chose_p(arr, brr, k): n = len(arr) crr = [] for i in range(k): crr.append(arr[i]) arr[i] = 0 for i in range(k): crr.append(brr[i]) brr[i] = 0 drr = [x for x in arr if x] + [x for x in brr if x] drr.sort() for i in range(n - 2 * k): crr.append(drr[i]) return crr if __name__ == '__main__': n = int(input()) arr = [] brr = [] for _ in range(n): x, y = map(int, input().split()) arr.append(x) brr.append(y) s = set() crr = chose_p(arr[:], brr[:], 0) drr = chose_p(arr[:], brr[:], n // 2) s.update(crr, drr) for i, x in enumerate(arr): arr[i] = str(int(x in s)) for i, x in enumerate(brr): brr[i] = str(int(x in s)) print(''.join(arr)) print(''.join(brr)) ```
89,621
Provide tags and a correct Python 3 solution for this coding contest problem. Two semifinals have just been in the running tournament. Each semifinal had n participants. There are n participants advancing to the finals, they are chosen as follows: from each semifinal, we choose k people (0 ≤ 2k ≤ n) who showed the best result in their semifinals and all other places in the finals go to the people who haven't ranked in the top k in their semifinal but got to the n - 2k of the best among the others. The tournament organizers hasn't yet determined the k value, so the participants want to know who else has any chance to get to the finals and who can go home. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of participants in each semifinal. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109) — the results of the i-th participant (the number of milliseconds he needs to cover the semifinals distance) of the first and second semifinals, correspondingly. All results are distinct. Sequences a1, a2, ..., an and b1, b2, ..., bn are sorted in ascending order, i.e. in the order the participants finished in the corresponding semifinal. Output Print two strings consisting of n characters, each equals either "0" or "1". The first line should correspond to the participants of the first semifinal, the second line should correspond to the participants of the second semifinal. The i-th character in the j-th line should equal "1" if the i-th participant of the j-th semifinal has any chances to advance to the finals, otherwise it should equal a "0". Examples Input 4 9840 9920 9860 9980 9930 10020 10040 10090 Output 1110 1100 Input 4 9900 9850 9940 9930 10000 10020 10060 10110 Output 1100 1100 Note Consider the first sample. Each semifinal has 4 participants. The results of the first semifinal are 9840, 9860, 9930, 10040. The results of the second semifinal are 9920, 9980, 10020, 10090. * If k = 0, the finalists are determined by the time only, so players 9840, 9860, 9920 and 9930 advance to the finals. * If k = 1, the winners from both semifinals move to the finals (with results 9840 and 9920), and the other places are determined by the time (these places go to the sportsmen who run the distance in 9860 and 9930 milliseconds). * If k = 2, then first and second places advance from each seminfial, these are participants with results 9840, 9860, 9920 and 9980 milliseconds. Tags: implementation, sortings Correct Solution: ``` import sys from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush from math import * from collections import defaultdict as dd, deque, Counter as C from itertools import combinations as comb, permutations as perm from bisect import bisect_left as bl, bisect_right as br, bisect from time import perf_counter from fractions import Fraction import copy import time starttime = time.time() mod = int(pow(10, 9) + 7) mod2 = 998244353 # from sys import stdin # input = stdin.readline def data(): return sys.stdin.readline().strip() def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end) def L(): return list(sp()) def sl(): return list(ssp()) def sp(): return map(int, data().split()) def ssp(): return map(str, data().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)] try: # sys.setrecursionlimit(int(pow(10,6))) sys.stdin = open("input.txt", "r") # sys.stdout = open("../output.txt", "w") except: pass def pmat(A): for ele in A: print(ele,end="\n") n=L()[0] A=[] B=[] for i in range(n): a,b=L() A.append(a) B.append(b) Z=sorted(A+B)[n-1] for i in range(n): if i<n//2 or A[i]<=Z: print(1,end="") else: print(0,end="") print() for i in range(n): if i<n//2 or B[i]<=Z: print(1,end="") else: print(0,end="") print() endtime = time.time() # print(f"Runtime of the program is {endtime - starttime}") ```
89,622
Provide tags and a correct Python 3 solution for this coding contest problem. Two semifinals have just been in the running tournament. Each semifinal had n participants. There are n participants advancing to the finals, they are chosen as follows: from each semifinal, we choose k people (0 ≤ 2k ≤ n) who showed the best result in their semifinals and all other places in the finals go to the people who haven't ranked in the top k in their semifinal but got to the n - 2k of the best among the others. The tournament organizers hasn't yet determined the k value, so the participants want to know who else has any chance to get to the finals and who can go home. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of participants in each semifinal. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109) — the results of the i-th participant (the number of milliseconds he needs to cover the semifinals distance) of the first and second semifinals, correspondingly. All results are distinct. Sequences a1, a2, ..., an and b1, b2, ..., bn are sorted in ascending order, i.e. in the order the participants finished in the corresponding semifinal. Output Print two strings consisting of n characters, each equals either "0" or "1". The first line should correspond to the participants of the first semifinal, the second line should correspond to the participants of the second semifinal. The i-th character in the j-th line should equal "1" if the i-th participant of the j-th semifinal has any chances to advance to the finals, otherwise it should equal a "0". Examples Input 4 9840 9920 9860 9980 9930 10020 10040 10090 Output 1110 1100 Input 4 9900 9850 9940 9930 10000 10020 10060 10110 Output 1100 1100 Note Consider the first sample. Each semifinal has 4 participants. The results of the first semifinal are 9840, 9860, 9930, 10040. The results of the second semifinal are 9920, 9980, 10020, 10090. * If k = 0, the finalists are determined by the time only, so players 9840, 9860, 9920 and 9930 advance to the finals. * If k = 1, the winners from both semifinals move to the finals (with results 9840 and 9920), and the other places are determined by the time (these places go to the sportsmen who run the distance in 9860 and 9930 milliseconds). * If k = 2, then first and second places advance from each seminfial, these are participants with results 9840, 9860, 9920 and 9980 milliseconds. Tags: implementation, sortings Correct Solution: ``` n=int(input()) k=[] a=[] b=[] for i in range(n): A,B=map(int, input().split()) a.append(A) b.append(B) la=0 lb=0 aind=[0]*n bind=[0]*n for i in range(n): if a[la]<b[lb]: aind[la]=1 la+=1 else: bind[lb]=1 lb+=1 for i in range(n//2): aind[i]=1 bind[i]=1 for i in aind: print(i,end='') print('') for i in bind: print(i,end='') ```
89,623
Provide tags and a correct Python 3 solution for this coding contest problem. Two semifinals have just been in the running tournament. Each semifinal had n participants. There are n participants advancing to the finals, they are chosen as follows: from each semifinal, we choose k people (0 ≤ 2k ≤ n) who showed the best result in their semifinals and all other places in the finals go to the people who haven't ranked in the top k in their semifinal but got to the n - 2k of the best among the others. The tournament organizers hasn't yet determined the k value, so the participants want to know who else has any chance to get to the finals and who can go home. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of participants in each semifinal. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109) — the results of the i-th participant (the number of milliseconds he needs to cover the semifinals distance) of the first and second semifinals, correspondingly. All results are distinct. Sequences a1, a2, ..., an and b1, b2, ..., bn are sorted in ascending order, i.e. in the order the participants finished in the corresponding semifinal. Output Print two strings consisting of n characters, each equals either "0" or "1". The first line should correspond to the participants of the first semifinal, the second line should correspond to the participants of the second semifinal. The i-th character in the j-th line should equal "1" if the i-th participant of the j-th semifinal has any chances to advance to the finals, otherwise it should equal a "0". Examples Input 4 9840 9920 9860 9980 9930 10020 10040 10090 Output 1110 1100 Input 4 9900 9850 9940 9930 10000 10020 10060 10110 Output 1100 1100 Note Consider the first sample. Each semifinal has 4 participants. The results of the first semifinal are 9840, 9860, 9930, 10040. The results of the second semifinal are 9920, 9980, 10020, 10090. * If k = 0, the finalists are determined by the time only, so players 9840, 9860, 9920 and 9930 advance to the finals. * If k = 1, the winners from both semifinals move to the finals (with results 9840 and 9920), and the other places are determined by the time (these places go to the sportsmen who run the distance in 9860 and 9930 milliseconds). * If k = 2, then first and second places advance from each seminfial, these are participants with results 9840, 9860, 9920 and 9980 milliseconds. Tags: implementation, sortings Correct Solution: ``` n = int(input()) a = [None] * n b = [None] * n for i in range(n): a[i], b[i] = map(int, input().split()) for i in range(n): if i < n // 2 or a[i] < b[n - i - 1]: print(1, end = "") else: print(0, end = "") print() for i in range(n): if i < n // 2 or b[i] < a[n - i - 1]: print(1, end = "") else: print(0, end = "") ```
89,624
Provide tags and a correct Python 3 solution for this coding contest problem. Two semifinals have just been in the running tournament. Each semifinal had n participants. There are n participants advancing to the finals, they are chosen as follows: from each semifinal, we choose k people (0 ≤ 2k ≤ n) who showed the best result in their semifinals and all other places in the finals go to the people who haven't ranked in the top k in their semifinal but got to the n - 2k of the best among the others. The tournament organizers hasn't yet determined the k value, so the participants want to know who else has any chance to get to the finals and who can go home. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of participants in each semifinal. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109) — the results of the i-th participant (the number of milliseconds he needs to cover the semifinals distance) of the first and second semifinals, correspondingly. All results are distinct. Sequences a1, a2, ..., an and b1, b2, ..., bn are sorted in ascending order, i.e. in the order the participants finished in the corresponding semifinal. Output Print two strings consisting of n characters, each equals either "0" or "1". The first line should correspond to the participants of the first semifinal, the second line should correspond to the participants of the second semifinal. The i-th character in the j-th line should equal "1" if the i-th participant of the j-th semifinal has any chances to advance to the finals, otherwise it should equal a "0". Examples Input 4 9840 9920 9860 9980 9930 10020 10040 10090 Output 1110 1100 Input 4 9900 9850 9940 9930 10000 10020 10060 10110 Output 1100 1100 Note Consider the first sample. Each semifinal has 4 participants. The results of the first semifinal are 9840, 9860, 9930, 10040. The results of the second semifinal are 9920, 9980, 10020, 10090. * If k = 0, the finalists are determined by the time only, so players 9840, 9860, 9920 and 9930 advance to the finals. * If k = 1, the winners from both semifinals move to the finals (with results 9840 and 9920), and the other places are determined by the time (these places go to the sportsmen who run the distance in 9860 and 9930 milliseconds). * If k = 2, then first and second places advance from each seminfial, these are participants with results 9840, 9860, 9920 and 9980 milliseconds. Tags: implementation, sortings Correct Solution: ``` n = int(input()) sem1 = [] sem2 = [] l = [0,0] for cont in range(0,n): l = list(map(int, input().split())) sem1.append(l[0]) sem2.append(l[1]) kmax = int(n/2) max1 = 0 max2 = 0 for cont in range(0,n): if sem1[max1] < sem2[max2]: max1 += 1 else: max2 += 1 ris1 = ['1']*(max([max1,kmax])) ris2 = ['1']*max([max2,kmax]) ris1 = ris1 + ['0']*(n-len(ris1)) ris2 = ris2 + ['0']*(n-len(ris2)) print(''.join(ris1)) print(''.join(ris2)) ```
89,625
Provide tags and a correct Python 3 solution for this coding contest problem. Two semifinals have just been in the running tournament. Each semifinal had n participants. There are n participants advancing to the finals, they are chosen as follows: from each semifinal, we choose k people (0 ≤ 2k ≤ n) who showed the best result in their semifinals and all other places in the finals go to the people who haven't ranked in the top k in their semifinal but got to the n - 2k of the best among the others. The tournament organizers hasn't yet determined the k value, so the participants want to know who else has any chance to get to the finals and who can go home. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of participants in each semifinal. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109) — the results of the i-th participant (the number of milliseconds he needs to cover the semifinals distance) of the first and second semifinals, correspondingly. All results are distinct. Sequences a1, a2, ..., an and b1, b2, ..., bn are sorted in ascending order, i.e. in the order the participants finished in the corresponding semifinal. Output Print two strings consisting of n characters, each equals either "0" or "1". The first line should correspond to the participants of the first semifinal, the second line should correspond to the participants of the second semifinal. The i-th character in the j-th line should equal "1" if the i-th participant of the j-th semifinal has any chances to advance to the finals, otherwise it should equal a "0". Examples Input 4 9840 9920 9860 9980 9930 10020 10040 10090 Output 1110 1100 Input 4 9900 9850 9940 9930 10000 10020 10060 10110 Output 1100 1100 Note Consider the first sample. Each semifinal has 4 participants. The results of the first semifinal are 9840, 9860, 9930, 10040. The results of the second semifinal are 9920, 9980, 10020, 10090. * If k = 0, the finalists are determined by the time only, so players 9840, 9860, 9920 and 9930 advance to the finals. * If k = 1, the winners from both semifinals move to the finals (with results 9840 and 9920), and the other places are determined by the time (these places go to the sportsmen who run the distance in 9860 and 9930 milliseconds). * If k = 2, then first and second places advance from each seminfial, these are participants with results 9840, 9860, 9920 and 9980 milliseconds. Tags: implementation, sortings Correct Solution: ``` n = int(input()) a, b = zip(*(map(int, input().split()) for _ in range(n))) i = j = 0 while i < n and j < n and i + j < n: if a[i] < b[j]: i += 1 else: j += 1 p = lambda x: ("1" * max(n // 2, x)).ljust(n, "0") print(p(i)) print(p(j)) ```
89,626
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Two semifinals have just been in the running tournament. Each semifinal had n participants. There are n participants advancing to the finals, they are chosen as follows: from each semifinal, we choose k people (0 ≤ 2k ≤ n) who showed the best result in their semifinals and all other places in the finals go to the people who haven't ranked in the top k in their semifinal but got to the n - 2k of the best among the others. The tournament organizers hasn't yet determined the k value, so the participants want to know who else has any chance to get to the finals and who can go home. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of participants in each semifinal. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109) — the results of the i-th participant (the number of milliseconds he needs to cover the semifinals distance) of the first and second semifinals, correspondingly. All results are distinct. Sequences a1, a2, ..., an and b1, b2, ..., bn are sorted in ascending order, i.e. in the order the participants finished in the corresponding semifinal. Output Print two strings consisting of n characters, each equals either "0" or "1". The first line should correspond to the participants of the first semifinal, the second line should correspond to the participants of the second semifinal. The i-th character in the j-th line should equal "1" if the i-th participant of the j-th semifinal has any chances to advance to the finals, otherwise it should equal a "0". Examples Input 4 9840 9920 9860 9980 9930 10020 10040 10090 Output 1110 1100 Input 4 9900 9850 9940 9930 10000 10020 10060 10110 Output 1100 1100 Note Consider the first sample. Each semifinal has 4 participants. The results of the first semifinal are 9840, 9860, 9930, 10040. The results of the second semifinal are 9920, 9980, 10020, 10090. * If k = 0, the finalists are determined by the time only, so players 9840, 9860, 9920 and 9930 advance to the finals. * If k = 1, the winners from both semifinals move to the finals (with results 9840 and 9920), and the other places are determined by the time (these places go to the sportsmen who run the distance in 9860 and 9930 milliseconds). * If k = 2, then first and second places advance from each seminfial, these are participants with results 9840, 9860, 9920 and 9980 milliseconds. Submitted Solution: ``` # -*- coding: utf-8 -*- n = int(input()) a, b = [], [] for i in range(n): x, y = map(int, input().split()) a.append(x) b.append(y) p = q = 0 c = 0 while c < n: if a[p] < b[q]: #print('{}<{}'.format(a[p], a[q])) p += 1 else: #print('{}>{}'.format(a[p], a[q])) q += 1 c += 1 p0 = max(p, n//2) print('1'*p0 + '0'*(n-p0)) q0 = max(q, n//2) print('1'*q0 + '0'*(n-q0)) ``` Yes
89,627
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Two semifinals have just been in the running tournament. Each semifinal had n participants. There are n participants advancing to the finals, they are chosen as follows: from each semifinal, we choose k people (0 ≤ 2k ≤ n) who showed the best result in their semifinals and all other places in the finals go to the people who haven't ranked in the top k in their semifinal but got to the n - 2k of the best among the others. The tournament organizers hasn't yet determined the k value, so the participants want to know who else has any chance to get to the finals and who can go home. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of participants in each semifinal. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109) — the results of the i-th participant (the number of milliseconds he needs to cover the semifinals distance) of the first and second semifinals, correspondingly. All results are distinct. Sequences a1, a2, ..., an and b1, b2, ..., bn are sorted in ascending order, i.e. in the order the participants finished in the corresponding semifinal. Output Print two strings consisting of n characters, each equals either "0" or "1". The first line should correspond to the participants of the first semifinal, the second line should correspond to the participants of the second semifinal. The i-th character in the j-th line should equal "1" if the i-th participant of the j-th semifinal has any chances to advance to the finals, otherwise it should equal a "0". Examples Input 4 9840 9920 9860 9980 9930 10020 10040 10090 Output 1110 1100 Input 4 9900 9850 9940 9930 10000 10020 10060 10110 Output 1100 1100 Note Consider the first sample. Each semifinal has 4 participants. The results of the first semifinal are 9840, 9860, 9930, 10040. The results of the second semifinal are 9920, 9980, 10020, 10090. * If k = 0, the finalists are determined by the time only, so players 9840, 9860, 9920 and 9930 advance to the finals. * If k = 1, the winners from both semifinals move to the finals (with results 9840 and 9920), and the other places are determined by the time (these places go to the sportsmen who run the distance in 9860 and 9930 milliseconds). * If k = 2, then first and second places advance from each seminfial, these are participants with results 9840, 9860, 9920 and 9980 milliseconds. Submitted Solution: ``` n = int(input()) a = [] b = [] for i in range(n): x, y = map(int,input().split()) a.append(x) b.append(y) x = [0] * n y = [0] * n i = 0 j = 0 cnt = 0 while(i < n and j < n): if a[i] > b[j]: y[j] = 1 j += 1 cnt += 1 elif a[i] <= b[j]: x[i] = 1 i += 1 cnt += 1 if cnt == n: break for i in range(n // 2): x[i] = 1 for j in range(n//2): y[j] = 1 for i in range(n): print(x[i], end = '') print() for j in range(n): print(y[j], end = '') ``` Yes
89,628
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Two semifinals have just been in the running tournament. Each semifinal had n participants. There are n participants advancing to the finals, they are chosen as follows: from each semifinal, we choose k people (0 ≤ 2k ≤ n) who showed the best result in their semifinals and all other places in the finals go to the people who haven't ranked in the top k in their semifinal but got to the n - 2k of the best among the others. The tournament organizers hasn't yet determined the k value, so the participants want to know who else has any chance to get to the finals and who can go home. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of participants in each semifinal. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109) — the results of the i-th participant (the number of milliseconds he needs to cover the semifinals distance) of the first and second semifinals, correspondingly. All results are distinct. Sequences a1, a2, ..., an and b1, b2, ..., bn are sorted in ascending order, i.e. in the order the participants finished in the corresponding semifinal. Output Print two strings consisting of n characters, each equals either "0" or "1". The first line should correspond to the participants of the first semifinal, the second line should correspond to the participants of the second semifinal. The i-th character in the j-th line should equal "1" if the i-th participant of the j-th semifinal has any chances to advance to the finals, otherwise it should equal a "0". Examples Input 4 9840 9920 9860 9980 9930 10020 10040 10090 Output 1110 1100 Input 4 9900 9850 9940 9930 10000 10020 10060 10110 Output 1100 1100 Note Consider the first sample. Each semifinal has 4 participants. The results of the first semifinal are 9840, 9860, 9930, 10040. The results of the second semifinal are 9920, 9980, 10020, 10090. * If k = 0, the finalists are determined by the time only, so players 9840, 9860, 9920 and 9930 advance to the finals. * If k = 1, the winners from both semifinals move to the finals (with results 9840 and 9920), and the other places are determined by the time (these places go to the sportsmen who run the distance in 9860 and 9930 milliseconds). * If k = 2, then first and second places advance from each seminfial, these are participants with results 9840, 9860, 9920 and 9980 milliseconds. Submitted Solution: ``` n = int(input()) team1 = [0 for i in range(n+1)] team2 = [0 for i in range(n+1)] for i in range(1, n+1): line = input().split() team1[i] = int(line[0]) team2[i] = int(line[1]) for i in range(1, n+1): if i <= n // 2 or team1[i] < team2[n-i+1]: print(1, end = '') else: print(0, end = '') print() for i in range(1, n+1): if i <= n // 2 or team2[i] < team1[n-i+1]: print(1, end = '') else: print(0, end = '') print() ``` Yes
89,629
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Two semifinals have just been in the running tournament. Each semifinal had n participants. There are n participants advancing to the finals, they are chosen as follows: from each semifinal, we choose k people (0 ≤ 2k ≤ n) who showed the best result in their semifinals and all other places in the finals go to the people who haven't ranked in the top k in their semifinal but got to the n - 2k of the best among the others. The tournament organizers hasn't yet determined the k value, so the participants want to know who else has any chance to get to the finals and who can go home. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of participants in each semifinal. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109) — the results of the i-th participant (the number of milliseconds he needs to cover the semifinals distance) of the first and second semifinals, correspondingly. All results are distinct. Sequences a1, a2, ..., an and b1, b2, ..., bn are sorted in ascending order, i.e. in the order the participants finished in the corresponding semifinal. Output Print two strings consisting of n characters, each equals either "0" or "1". The first line should correspond to the participants of the first semifinal, the second line should correspond to the participants of the second semifinal. The i-th character in the j-th line should equal "1" if the i-th participant of the j-th semifinal has any chances to advance to the finals, otherwise it should equal a "0". Examples Input 4 9840 9920 9860 9980 9930 10020 10040 10090 Output 1110 1100 Input 4 9900 9850 9940 9930 10000 10020 10060 10110 Output 1100 1100 Note Consider the first sample. Each semifinal has 4 participants. The results of the first semifinal are 9840, 9860, 9930, 10040. The results of the second semifinal are 9920, 9980, 10020, 10090. * If k = 0, the finalists are determined by the time only, so players 9840, 9860, 9920 and 9930 advance to the finals. * If k = 1, the winners from both semifinals move to the finals (with results 9840 and 9920), and the other places are determined by the time (these places go to the sportsmen who run the distance in 9860 and 9930 milliseconds). * If k = 2, then first and second places advance from each seminfial, these are participants with results 9840, 9860, 9920 and 9980 milliseconds. Submitted Solution: ``` Narray = int(input()) Aarray = [] Barray = [] k = int(Narray/2) a,b,p,q = 0,0,0,0; for i in range(Narray): Carray = input().split() if q+p <= Narray: Aarray.append(int(Carray[0])) Barray.append(int(Carray[1])) if Aarray[0] < Barray[0]: Aarray.pop(0) p +=1; q +=0; else: Barray.pop(0) p +=0; q +=1; if q + p == Narray: a,b = p,q; else: continue if a < b: print('1'*(k)+'0'*(Narray-k)) print('1'*(Narray-a)+'0'*a) elif (a == b): print('1'*(k)+'0'*(Narray-k)) print('1'*(k)+'0'*(Narray-k)) else: print('1'*(Narray-b)+'0'*b) print('1'*(k)+'0'*(Narray-k)) ``` Yes
89,630
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Two semifinals have just been in the running tournament. Each semifinal had n participants. There are n participants advancing to the finals, they are chosen as follows: from each semifinal, we choose k people (0 ≤ 2k ≤ n) who showed the best result in their semifinals and all other places in the finals go to the people who haven't ranked in the top k in their semifinal but got to the n - 2k of the best among the others. The tournament organizers hasn't yet determined the k value, so the participants want to know who else has any chance to get to the finals and who can go home. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of participants in each semifinal. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109) — the results of the i-th participant (the number of milliseconds he needs to cover the semifinals distance) of the first and second semifinals, correspondingly. All results are distinct. Sequences a1, a2, ..., an and b1, b2, ..., bn are sorted in ascending order, i.e. in the order the participants finished in the corresponding semifinal. Output Print two strings consisting of n characters, each equals either "0" or "1". The first line should correspond to the participants of the first semifinal, the second line should correspond to the participants of the second semifinal. The i-th character in the j-th line should equal "1" if the i-th participant of the j-th semifinal has any chances to advance to the finals, otherwise it should equal a "0". Examples Input 4 9840 9920 9860 9980 9930 10020 10040 10090 Output 1110 1100 Input 4 9900 9850 9940 9930 10000 10020 10060 10110 Output 1100 1100 Note Consider the first sample. Each semifinal has 4 participants. The results of the first semifinal are 9840, 9860, 9930, 10040. The results of the second semifinal are 9920, 9980, 10020, 10090. * If k = 0, the finalists are determined by the time only, so players 9840, 9860, 9920 and 9930 advance to the finals. * If k = 1, the winners from both semifinals move to the finals (with results 9840 and 9920), and the other places are determined by the time (these places go to the sportsmen who run the distance in 9860 and 9930 milliseconds). * If k = 2, then first and second places advance from each seminfial, these are participants with results 9840, 9860, 9920 and 9980 milliseconds. Submitted Solution: ``` Narray = int(input()) Aarray = [] Barray = [] for i in range(Narray): Carray = input().split() Aarray.append(int(Carray[0])) Barray.append(int(Carray[1])) k = int(Narray/2) A1array, B1array = Aarray[k:], Barray[k:] Aarray, Barray = Aarray[:k], Barray[:k] if Narray == 1: print(str(1)) print(str(1)) else: if Aarray[0] < Barray[0]: dem = 0; for x in A1array: if x < B1array[0]: dem += 1 else: dem += 0 Earray = A1array[dem:] Earray = [str(0) for i in Earray] Aarray = Aarray + A1array[:dem] Aarray = [str(1) for j in Aarray] Aarray = Aarray + Earray B1array = [str(0) for i in B1array] Barray = [str(1) for j in Barray] Barray = Barray +B1array s = str("") print(s.join(Aarray)) print(s.join(Barray)) else: dem1 = 0; for x in B1array: if x < A1array[0]: dem1 += 1 else: dem1 += 0 Earray = B1array[dem1:] Earray = [str(0) for i in Earray] Barray = Barray + B1array[:dem1] Barray = [str(1) for j in Barray] Barray = Barray + Earray A1array = [str(0) for i in A1array] Aarray = [str(1) for j in Aarray] Aarray = Aarray +A1array s = str("") print(s.join(Aarray)) print(s.join(Barray)) ``` No
89,631
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Two semifinals have just been in the running tournament. Each semifinal had n participants. There are n participants advancing to the finals, they are chosen as follows: from each semifinal, we choose k people (0 ≤ 2k ≤ n) who showed the best result in their semifinals and all other places in the finals go to the people who haven't ranked in the top k in their semifinal but got to the n - 2k of the best among the others. The tournament organizers hasn't yet determined the k value, so the participants want to know who else has any chance to get to the finals and who can go home. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of participants in each semifinal. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109) — the results of the i-th participant (the number of milliseconds he needs to cover the semifinals distance) of the first and second semifinals, correspondingly. All results are distinct. Sequences a1, a2, ..., an and b1, b2, ..., bn are sorted in ascending order, i.e. in the order the participants finished in the corresponding semifinal. Output Print two strings consisting of n characters, each equals either "0" or "1". The first line should correspond to the participants of the first semifinal, the second line should correspond to the participants of the second semifinal. The i-th character in the j-th line should equal "1" if the i-th participant of the j-th semifinal has any chances to advance to the finals, otherwise it should equal a "0". Examples Input 4 9840 9920 9860 9980 9930 10020 10040 10090 Output 1110 1100 Input 4 9900 9850 9940 9930 10000 10020 10060 10110 Output 1100 1100 Note Consider the first sample. Each semifinal has 4 participants. The results of the first semifinal are 9840, 9860, 9930, 10040. The results of the second semifinal are 9920, 9980, 10020, 10090. * If k = 0, the finalists are determined by the time only, so players 9840, 9860, 9920 and 9930 advance to the finals. * If k = 1, the winners from both semifinals move to the finals (with results 9840 and 9920), and the other places are determined by the time (these places go to the sportsmen who run the distance in 9860 and 9930 milliseconds). * If k = 2, then first and second places advance from each seminfial, these are participants with results 9840, 9860, 9920 and 9980 milliseconds. Submitted Solution: ``` def calc_chances_matrix(_n, _a, _b): chances_matrix = [[0 for i in range(n)] for j in range(2)] for k in range(0, n // 2 + 1): if k >= 1: chances_matrix[0][k - 1] = 1 chances_matrix[1][k - 1] = 1 last_a = k - 1 last_b = k - 1 for i in range(n - (2 * k)): if last_b >= n - 1 or _a[last_a + 1] < _b[last_b + 1]: last_a += 1 chances_matrix[0][last_a] = 1 else: last_b += 1 chances_matrix[1][last_b] = 1 return chances_matrix n = int(input()) a, b = [], [] for i in range(n): ai, bi = map(int, input().split()) a.append(ai) b.append(bi) print(*calc_chances_matrix(n, a, b)[0], sep=' ') print(*calc_chances_matrix(n, a, b)[1], sep=' ') ``` No
89,632
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Two semifinals have just been in the running tournament. Each semifinal had n participants. There are n participants advancing to the finals, they are chosen as follows: from each semifinal, we choose k people (0 ≤ 2k ≤ n) who showed the best result in their semifinals and all other places in the finals go to the people who haven't ranked in the top k in their semifinal but got to the n - 2k of the best among the others. The tournament organizers hasn't yet determined the k value, so the participants want to know who else has any chance to get to the finals and who can go home. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of participants in each semifinal. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109) — the results of the i-th participant (the number of milliseconds he needs to cover the semifinals distance) of the first and second semifinals, correspondingly. All results are distinct. Sequences a1, a2, ..., an and b1, b2, ..., bn are sorted in ascending order, i.e. in the order the participants finished in the corresponding semifinal. Output Print two strings consisting of n characters, each equals either "0" or "1". The first line should correspond to the participants of the first semifinal, the second line should correspond to the participants of the second semifinal. The i-th character in the j-th line should equal "1" if the i-th participant of the j-th semifinal has any chances to advance to the finals, otherwise it should equal a "0". Examples Input 4 9840 9920 9860 9980 9930 10020 10040 10090 Output 1110 1100 Input 4 9900 9850 9940 9930 10000 10020 10060 10110 Output 1100 1100 Note Consider the first sample. Each semifinal has 4 participants. The results of the first semifinal are 9840, 9860, 9930, 10040. The results of the second semifinal are 9920, 9980, 10020, 10090. * If k = 0, the finalists are determined by the time only, so players 9840, 9860, 9920 and 9930 advance to the finals. * If k = 1, the winners from both semifinals move to the finals (with results 9840 and 9920), and the other places are determined by the time (these places go to the sportsmen who run the distance in 9860 and 9930 milliseconds). * If k = 2, then first and second places advance from each seminfial, these are participants with results 9840, 9860, 9920 and 9980 milliseconds. Submitted Solution: ``` n = int(input()) A = B = [] p = q = 0 k = n//2 for i in range(n): a, b = map(int, input().split()) A.append(a) B.append(b) for i in range(n): if A[p] < B[q]: p += 1 else: q += 1 for i in range(n): print(1 if i < q or i < k else 0, end='') print() for i in range(n): print(1 if i < p or i < k else 0, end='') ``` No
89,633
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Two semifinals have just been in the running tournament. Each semifinal had n participants. There are n participants advancing to the finals, they are chosen as follows: from each semifinal, we choose k people (0 ≤ 2k ≤ n) who showed the best result in their semifinals and all other places in the finals go to the people who haven't ranked in the top k in their semifinal but got to the n - 2k of the best among the others. The tournament organizers hasn't yet determined the k value, so the participants want to know who else has any chance to get to the finals and who can go home. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of participants in each semifinal. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109) — the results of the i-th participant (the number of milliseconds he needs to cover the semifinals distance) of the first and second semifinals, correspondingly. All results are distinct. Sequences a1, a2, ..., an and b1, b2, ..., bn are sorted in ascending order, i.e. in the order the participants finished in the corresponding semifinal. Output Print two strings consisting of n characters, each equals either "0" or "1". The first line should correspond to the participants of the first semifinal, the second line should correspond to the participants of the second semifinal. The i-th character in the j-th line should equal "1" if the i-th participant of the j-th semifinal has any chances to advance to the finals, otherwise it should equal a "0". Examples Input 4 9840 9920 9860 9980 9930 10020 10040 10090 Output 1110 1100 Input 4 9900 9850 9940 9930 10000 10020 10060 10110 Output 1100 1100 Note Consider the first sample. Each semifinal has 4 participants. The results of the first semifinal are 9840, 9860, 9930, 10040. The results of the second semifinal are 9920, 9980, 10020, 10090. * If k = 0, the finalists are determined by the time only, so players 9840, 9860, 9920 and 9930 advance to the finals. * If k = 1, the winners from both semifinals move to the finals (with results 9840 and 9920), and the other places are determined by the time (these places go to the sportsmen who run the distance in 9860 and 9930 milliseconds). * If k = 2, then first and second places advance from each seminfial, these are participants with results 9840, 9860, 9920 and 9980 milliseconds. Submitted Solution: ``` def calc_chances_matrix(_n, _a, _b): chances_matrix = [[0 for i in range(n)] for j in range(2)] for k in range(0, n // 2 + 1): if k >= 1: chances_matrix[0][k - 1] = 1 chances_matrix[1][k - 1] = 1 last_a = k - 1 last_b = k - 1 for i in range(n - (2 * k)): if last_b >= n - 1 or _a[last_a + 1] < _b[last_b + 1]: last_a += 1 chances_matrix[0][last_a] = 1 else: last_b += 1 chances_matrix[1][last_b] = 1 return chances_matrix n = int(input()) a, b = [], [] for i in range(n): ai, bi = map(int, input().split()) a.append(ai) b.append(bi) print(calc_chances_matrix(n, a, b)) ``` No
89,634
Provide tags and a correct Python 3 solution for this coding contest problem. You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube. Input The first line contains three space-separated integers (0 or 1) — the coordinates of the first fly, the second line analogously contains the coordinates of the second fly. Output Output "YES" (without quotes) if the flies see each other. Otherwise, output "NO". Examples Input 0 0 0 0 1 0 Output YES Input 1 1 0 0 1 0 Output YES Input 0 0 0 1 1 1 Output NO Tags: math Correct Solution: ``` x1,y1,z1=map(int,input().split()) x2,y2,z2=map(int,input().split()) if x1==x2 or y1==y2 or z1==z2: print("YES") else: print("NO") ```
89,635
Provide tags and a correct Python 3 solution for this coding contest problem. You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube. Input The first line contains three space-separated integers (0 or 1) — the coordinates of the first fly, the second line analogously contains the coordinates of the second fly. Output Output "YES" (without quotes) if the flies see each other. Otherwise, output "NO". Examples Input 0 0 0 0 1 0 Output YES Input 1 1 0 0 1 0 Output YES Input 0 0 0 1 1 1 Output NO Tags: math Correct Solution: ``` a, b = (int(input().replace(' ', ''), 2) for _ in' '*2) print('YNEOS'[a ^ b == 7::2]) ```
89,636
Provide tags and a correct Python 3 solution for this coding contest problem. You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube. Input The first line contains three space-separated integers (0 or 1) — the coordinates of the first fly, the second line analogously contains the coordinates of the second fly. Output Output "YES" (without quotes) if the flies see each other. Otherwise, output "NO". Examples Input 0 0 0 0 1 0 Output YES Input 1 1 0 0 1 0 Output YES Input 0 0 0 1 1 1 Output NO Tags: math Correct Solution: ``` a=[int(b) for b in input().split()] b=[int(a) for a in input().split()] if a[0]==b[0] or a[1]==b[1] or a[2]==b[2]: print("YES") else: print("NO") ```
89,637
Provide tags and a correct Python 3 solution for this coding contest problem. You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube. Input The first line contains three space-separated integers (0 or 1) — the coordinates of the first fly, the second line analogously contains the coordinates of the second fly. Output Output "YES" (without quotes) if the flies see each other. Otherwise, output "NO". Examples Input 0 0 0 0 1 0 Output YES Input 1 1 0 0 1 0 Output YES Input 0 0 0 1 1 1 Output NO Tags: math Correct Solution: ``` l1=input().split() l2=input().split() s=0 for i in range(3): if(l1[i]==l2[i]): s+=1 if(s>=1): print('YES') else: print('NO') ```
89,638
Provide tags and a correct Python 3 solution for this coding contest problem. You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube. Input The first line contains three space-separated integers (0 or 1) — the coordinates of the first fly, the second line analogously contains the coordinates of the second fly. Output Output "YES" (without quotes) if the flies see each other. Otherwise, output "NO". Examples Input 0 0 0 0 1 0 Output YES Input 1 1 0 0 1 0 Output YES Input 0 0 0 1 1 1 Output NO Tags: math Correct Solution: ``` n=list(map(int,input().split())) x=list(map(int,input().split())) count=0 for i in range(3): if n[i]==x[i]: count+=1 if count==0: print('NO') else: print('YES') ```
89,639
Provide tags and a correct Python 3 solution for this coding contest problem. You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube. Input The first line contains three space-separated integers (0 or 1) — the coordinates of the first fly, the second line analogously contains the coordinates of the second fly. Output Output "YES" (without quotes) if the flies see each other. Otherwise, output "NO". Examples Input 0 0 0 0 1 0 Output YES Input 1 1 0 0 1 0 Output YES Input 0 0 0 1 1 1 Output NO Tags: math Correct Solution: ``` print('YES' if any(i == j for i, j in zip(input().split(), input().split())) else 'NO') ```
89,640
Provide tags and a correct Python 3 solution for this coding contest problem. You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube. Input The first line contains three space-separated integers (0 or 1) — the coordinates of the first fly, the second line analogously contains the coordinates of the second fly. Output Output "YES" (without quotes) if the flies see each other. Otherwise, output "NO". Examples Input 0 0 0 0 1 0 Output YES Input 1 1 0 0 1 0 Output YES Input 0 0 0 1 1 1 Output NO Tags: math Correct Solution: ``` #! /usr/bin/python3 a = input().strip().split() b = input().strip().split() c = 0 for i in range (0, 3): if a[i] == b[i]: c = c + 1 if c >= 1: print("YES") else: print("NO") ```
89,641
Provide tags and a correct Python 3 solution for this coding contest problem. You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube. Input The first line contains three space-separated integers (0 or 1) — the coordinates of the first fly, the second line analogously contains the coordinates of the second fly. Output Output "YES" (without quotes) if the flies see each other. Otherwise, output "NO". Examples Input 0 0 0 0 1 0 Output YES Input 1 1 0 0 1 0 Output YES Input 0 0 0 1 1 1 Output NO Tags: math Correct Solution: ``` A = list(map(int, input().split())) B = list(map(int, input().split())) for i in range(3): if A[i] == B[i]: print('YES') exit() print('NO') ```
89,642
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube. Input The first line contains three space-separated integers (0 or 1) — the coordinates of the first fly, the second line analogously contains the coordinates of the second fly. Output Output "YES" (without quotes) if the flies see each other. Otherwise, output "NO". Examples Input 0 0 0 0 1 0 Output YES Input 1 1 0 0 1 0 Output YES Input 0 0 0 1 1 1 Output NO Submitted Solution: ``` s1 = input() s2 = input() if s1[0] == s2[0] or s1[2] == s2[2] or s1[4] == s2[4]: print("YES") else: print("NO") ``` Yes
89,643
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube. Input The first line contains three space-separated integers (0 or 1) — the coordinates of the first fly, the second line analogously contains the coordinates of the second fly. Output Output "YES" (without quotes) if the flies see each other. Otherwise, output "NO". Examples Input 0 0 0 0 1 0 Output YES Input 1 1 0 0 1 0 Output YES Input 0 0 0 1 1 1 Output NO Submitted Solution: ``` fly1 = list(map(int, input().split())) fly2 = list(map(int, input().split())) if fly1[0] == fly2[0] or fly1[2] == fly2[2] or fly1[1] == fly2[1]: print("YES") else: print("NO") ``` Yes
89,644
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube. Input The first line contains three space-separated integers (0 or 1) — the coordinates of the first fly, the second line analogously contains the coordinates of the second fly. Output Output "YES" (without quotes) if the flies see each other. Otherwise, output "NO". Examples Input 0 0 0 0 1 0 Output YES Input 1 1 0 0 1 0 Output YES Input 0 0 0 1 1 1 Output NO Submitted Solution: ``` X = list(map(int, input().split())) Y = list(map(int, input().split())) Count = 0 for i in range(3): if X[i] == Y[i]: print("YES") exit() print("NO") # UB_CodeForces # Advice: Falling down is an accident, staying down is a choice # Location: Mashhad for few days # Caption: Finally happened what should be happened # CodeNumber: 698 ``` Yes
89,645
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube. Input The first line contains three space-separated integers (0 or 1) — the coordinates of the first fly, the second line analogously contains the coordinates of the second fly. Output Output "YES" (without quotes) if the flies see each other. Otherwise, output "NO". Examples Input 0 0 0 0 1 0 Output YES Input 1 1 0 0 1 0 Output YES Input 0 0 0 1 1 1 Output NO Submitted Solution: ``` a=input() b=input() if(a=="0 0 0" and b=="1 1 1" or (b=="0 0 0" and a=="1 1 1")): print("NO") elif(a=="0 1 0" and b=="1 0 1" or (b=="0 1 0" and a=="1 0 1")): print("NO") elif(a=="0 0 1" and b=="1 1 0" or (b=="0 0 1" and a=="1 1 0")): print("NO") elif(a=="1 0 0" and b=="0 1 1" or (b=="1 0 0" and a=="0 1 1")): print("NO") else: print("YES") ``` Yes
89,646
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube. Input The first line contains three space-separated integers (0 or 1) — the coordinates of the first fly, the second line analogously contains the coordinates of the second fly. Output Output "YES" (without quotes) if the flies see each other. Otherwise, output "NO". Examples Input 0 0 0 0 1 0 Output YES Input 1 1 0 0 1 0 Output YES Input 0 0 0 1 1 1 Output NO Submitted Solution: ``` readints = lambda: map(int, input().split(' ')) a,b,c=readints() x,y,z=readints() if a!=x and b!=y and c!=c: print('NO') else: print('YES') ``` No
89,647
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube. Input The first line contains three space-separated integers (0 or 1) — the coordinates of the first fly, the second line analogously contains the coordinates of the second fly. Output Output "YES" (without quotes) if the flies see each other. Otherwise, output "NO". Examples Input 0 0 0 0 1 0 Output YES Input 1 1 0 0 1 0 Output YES Input 0 0 0 1 1 1 Output NO Submitted Solution: ``` x=str(input()) y=str(input()) def f(i,o): m=(int(i[0])-int(o[0]))**2+(int(i[1])-int(o[1]))**2+(int(i[2])-int(o[2]))**2 if(m==1): return True return False a,b,l,m=[],[],[],[] a=x.split(' ') b=y.split(' ') l=[y for y in a if y!=''] m=[y for y in b if y!=''] if(f(l,m)==True): print("YES") else: print("NO") ``` No
89,648
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube. Input The first line contains three space-separated integers (0 or 1) — the coordinates of the first fly, the second line analogously contains the coordinates of the second fly. Output Output "YES" (without quotes) if the flies see each other. Otherwise, output "NO". Examples Input 0 0 0 0 1 0 Output YES Input 1 1 0 0 1 0 Output YES Input 0 0 0 1 1 1 Output NO Submitted Solution: ``` ar = input().split() ar2 = input().split() if(not ("1" in ar or "0" in ar2) or not ("0" in ar or "1" in ar2)): print("NO") else: print("YES") ``` No
89,649
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube. Input The first line contains three space-separated integers (0 or 1) — the coordinates of the first fly, the second line analogously contains the coordinates of the second fly. Output Output "YES" (without quotes) if the flies see each other. Otherwise, output "NO". Examples Input 0 0 0 0 1 0 Output YES Input 1 1 0 0 1 0 Output YES Input 0 0 0 1 1 1 Output NO Submitted Solution: ``` import sys import math #to read string get_string = lambda: sys.stdin.readline().strip() #to read list of integers get_int_list = lambda: list( map(int,sys.stdin.readline().strip().split()) ) #to read integers get_int = lambda: int(sys.stdin.readline()) #to print fast pt = lambda x: sys.stdout.write(str(x)+'\n') #--------------------------------WhiteHat010--------------------------------------# l1 = get_int_list() l2 = get_int_list() count = 0 for i in range(3): if l1[i] == l2[i]: count += 1 if count >= 2: print("YES") else: print("NO") ``` No
89,650
Provide tags and a correct Python 3 solution for this coding contest problem. Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store. Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group. Jzzhu wonders how to get the maximum possible number of groups. Can you help him? Input A single integer n (1 ≤ n ≤ 105), the number of the apples. Output The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers — the numbers of apples in the current group. If there are several optimal answers you can print any of them. Examples Input 6 Output 2 6 3 2 4 Input 9 Output 3 9 3 2 4 6 8 Input 2 Output 0 Tags: constructive algorithms, number theory Correct Solution: ``` apples=int(input()) if apples<=3: print(0) else: halfpr=int(apples/2) def primes(n): isPrime = [True for i in range(n + 1)] isPrime[0] = isPrime[1] = False idx = 2 while idx * idx <= n: if isPrime[idx]: for i in range(idx * 2, n, idx): isPrime[i] = False idx += 1 return isPrime primeslist=primes(halfpr) totallist=[False]*(apples+1) applepairs=[] for prime in range(len(primeslist)-1, 1, -1): if primeslist[prime]: numprimes=int(apples/prime) primesx=[int(i*prime) for i in range(1, numprimes+1) if not totallist[i*prime]] if len(primesx)%2==1: primesx.remove(2*prime) for pr in primesx: applepairs.append(pr) totallist[pr]=True print(int(len(applepairs)/2)) for t in range(int(len(applepairs)/2)): print(applepairs[2*t], applepairs[2*t+1]) ```
89,651
Provide tags and a correct Python 3 solution for this coding contest problem. Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store. Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group. Jzzhu wonders how to get the maximum possible number of groups. Can you help him? Input A single integer n (1 ≤ n ≤ 105), the number of the apples. Output The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers — the numbers of apples in the current group. If there are several optimal answers you can print any of them. Examples Input 6 Output 2 6 3 2 4 Input 9 Output 3 9 3 2 4 6 8 Input 2 Output 0 Tags: constructive algorithms, number theory Correct Solution: ``` apples=int(input()) if apples<=3: print(0) else: halfpr=int(apples/2) def primes(n): isPrime = [True for i in range(n + 1)] isPrime[0] = isPrime[1] = False idx = 2 while idx * idx <= n: if isPrime[idx]: for i in range(idx * 2, n, idx): isPrime[i] = False idx += 1 return isPrime primeslist=primes(halfpr) totallist=[False]*(apples+1) applepairs=[] for prime in range(len(primeslist)-1, 1, -1): if primeslist[prime]: numprimes=int(apples/prime) primesx=[int(i*prime) for i in range(1, numprimes+1) if not totallist[i*prime]] if len(primesx)%2==1: primesx.remove(2*prime) for pr in primesx: applepairs.append(pr) totallist[pr]=True print(int(len(applepairs)/2)) for t in range(int(len(applepairs)/2)): print(applepairs[2*t], applepairs[2*t+1]) # Made By Mostafa_Khaled ```
89,652
Provide tags and a correct Python 3 solution for this coding contest problem. Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store. Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group. Jzzhu wonders how to get the maximum possible number of groups. Can you help him? Input A single integer n (1 ≤ n ≤ 105), the number of the apples. Output The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers — the numbers of apples in the current group. If there are several optimal answers you can print any of them. Examples Input 6 Output 2 6 3 2 4 Input 9 Output 3 9 3 2 4 6 8 Input 2 Output 0 Tags: constructive algorithms, number theory Correct Solution: ``` import math,sys,bisect,heapq from collections import defaultdict,Counter,deque from itertools import groupby,accumulate #sys.setrecursionlimit(200000000) input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__ ilele = lambda: map(int,input().split()) alele = lambda: list(map(int, input().split())) def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] MOD = 1000000000 + 7 def Y(c): print(["NO","YES"][c]) def y(c): print(["no","yes"][c]) def Yy(c): print(["No","Yes"][c]) def SieveOfEratosthenes(n): Z=[] prime = [True for i in range(n+1)] p = 2 while (p * p <= n): if (prime[p] == True): # Update all multiples of p for i in range(p * p, n+1, p): prime[i] = False p += 1 # Print all prime numbers for p in range(2, n): if prime[p]: Z.append(p) return Z N = int(input()) prime = SieveOfEratosthenes(N//2) if N <=3: print(0) else: mark = {} if N//2 not in prime: prime.append(N//2) Ans = [] prime = prime[::-1] for i in prime: Z= [] for j in range(1,N//i + 1): if mark.get(i*j,-1) == -1: Z.append(i*j) if len(Z) % 2 == 0: for k in Z: Ans.append(k) mark[k] = 1 else: for k in Z: if k!= 2*i: Ans.append(k) mark[k] = 1 print(len(Ans)//2) for i in range(0,len(Ans),2): print(Ans[i],Ans[i+1]) ```
89,653
Provide tags and a correct Python 3 solution for this coding contest problem. Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store. Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group. Jzzhu wonders how to get the maximum possible number of groups. Can you help him? Input A single integer n (1 ≤ n ≤ 105), the number of the apples. Output The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers — the numbers of apples in the current group. If there are several optimal answers you can print any of them. Examples Input 6 Output 2 6 3 2 4 Input 9 Output 3 9 3 2 4 6 8 Input 2 Output 0 Tags: constructive algorithms, number theory Correct Solution: ``` n = int(input()) primes = [x for x in range(2, int(n/2)+1) if all(x % y != 0 for y in range(2, int(x**(0.5))+1))] #go to discord primes = primes[::-1] used = {} for i in range(2,n+1): used[i] = False def solve(n, primes, used): outputs = [] doubles = [] counter = 0 if n == 1: return 0, 0 for i in primes: multiples = [] for x in range(1,n//i+1): if used[i*x] == False: multiples.append(i*x) used[i*x] = True if len(multiples)%2==0: for j in range(0, int(len(multiples)), 2): outputs.append((multiples[j], multiples[j+1])) counter+=1 else: #doubles.append(2*i) multiples.pop(1) used[i*2] = False for j in range(0, int(len(multiples)), 2): outputs.append((multiples[j], multiples[j+1])) counter+=1 #outputs+=[(multiples[x], multiples[2*x]) for x in range(int(len(multiples)/2)) if multiples[2*x] != 2*i] #print(multiples) #print(used) #print(doubles) #for j in range(0, int(len(doubles)/2), 2): #outputs.append((multiples[j], multiples[j+1])) return outputs, counter a = solve(n, primes, used) print(a[1]) if a[0] != 0: for i in a[0]: print(*i) ```
89,654
Provide tags and a correct Python 3 solution for this coding contest problem. Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store. Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group. Jzzhu wonders how to get the maximum possible number of groups. Can you help him? Input A single integer n (1 ≤ n ≤ 105), the number of the apples. Output The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers — the numbers of apples in the current group. If there are several optimal answers you can print any of them. Examples Input 6 Output 2 6 3 2 4 Input 9 Output 3 9 3 2 4 6 8 Input 2 Output 0 Tags: constructive algorithms, number theory Correct Solution: ``` import math apples=int(input()) if apples<=3: print(0) else: halfpr=int(apples/2) def primes(n): primeslistsa=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317] yesnoprime=[False, False]+[True]*(n-1) t=0 while primeslistsa[t+1]<=int(math.sqrt(n)): t+=1 for x in range(t+1): for sa in range(2, int(n/primeslistsa[x]+1)): yesnoprime[primeslistsa[x]*sa]=False return yesnoprime primeslist=primes(halfpr) totallist=[False]*(apples+1) applepairs=[] for prime in range(len(primeslist)-1, 1, -1): if primeslist[prime]: numprimes=int(apples/prime) primesx=[int(i*prime) for i in range(1, numprimes+1) if not totallist[i*prime]] if len(primesx)%2==1: primesx.remove(2*prime) for pr in primesx: applepairs.append(pr) totallist[pr]=True print(int(len(applepairs)/2)) for t in range(int(len(applepairs)/2)): print(applepairs[2*t], applepairs[2*t+1]) ```
89,655
Provide tags and a correct Python 3 solution for this coding contest problem. Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store. Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group. Jzzhu wonders how to get the maximum possible number of groups. Can you help him? Input A single integer n (1 ≤ n ≤ 105), the number of the apples. Output The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers — the numbers of apples in the current group. If there are several optimal answers you can print any of them. Examples Input 6 Output 2 6 3 2 4 Input 9 Output 3 9 3 2 4 6 8 Input 2 Output 0 Tags: constructive algorithms, number theory Correct Solution: ``` def find_primes(p): nums = list(range(3,p + 1)) divisors=[2] for num in nums: check=0 res = True while divisors[check] <= num**(1/2): if num % divisors[check] == 0: res = False break check += 1 if res: divisors.append(num) divisors.reverse() return divisors num = int(input()) nums = set(range(2,num + 1)) check = dict() for i in range(1,num+1): check[i] = False primes = find_primes(num//2) results = [] for prime in primes: if prime > num // 2: break considering = [] for x in range(1, num // prime+1): if not check.get(x * prime): considering.append(x * prime) check[x * prime] = True if len(considering) % 2 != 0: considering.remove(prime * 2) check[prime*2] = False adding = [(considering[i], considering[i+1]) for i in range(0,len(considering),2)] results += adding nums = [x for x in nums if x % 2 == 0 and not check.get(x)] if len(nums) % 2 != 0: nums.pop() results += [(nums[i], nums[i+1]) for i in range(0,len(nums),2)] print(len(results)) for res in results: print(res[0], res[1]) ```
89,656
Provide tags and a correct Python 3 solution for this coding contest problem. Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store. Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group. Jzzhu wonders how to get the maximum possible number of groups. Can you help him? Input A single integer n (1 ≤ n ≤ 105), the number of the apples. Output The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers — the numbers of apples in the current group. If there are several optimal answers you can print any of them. Examples Input 6 Output 2 6 3 2 4 Input 9 Output 3 9 3 2 4 6 8 Input 2 Output 0 Tags: constructive algorithms, number theory Correct Solution: ``` """ Codeforces Round 257 Div 1 Problem C Author : chaotic_iak Language: Python 3.3.4 """ def read(mode=2): # 0: String # 1: List of strings # 2: List of integers inputs = input().strip() if mode == 0: return inputs if mode == 1: return inputs.split() if mode == 2: return [int(x) for x in inputs.split()] def write(s="\n"): if isinstance(s, list): s = " ".join(map(str,s)) s = str(s) print(s, end="") ################################################### SOLUTION # croft algorithm to generate primes # from pyprimes library, not built-in, just google it from itertools import compress import itertools def croft(): """Yield prime integers using the Croft Spiral sieve. This is a variant of wheel factorisation modulo 30. """ # Implementation is based on erat3 from here: # http://stackoverflow.com/q/2211990 # and this website: # http://www.primesdemystified.com/ # Memory usage increases roughly linearly with the number of primes seen. # dict ``roots`` stores an entry x:p for every prime p. for p in (2, 3, 5): yield p roots = {9: 3, 25: 5} # Map d**2 -> d. primeroots = frozenset((1, 7, 11, 13, 17, 19, 23, 29)) selectors = (1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0) for q in compress( # Iterate over prime candidates 7, 9, 11, 13, ... itertools.islice(itertools.count(7), 0, None, 2), # Mask out those that can't possibly be prime. itertools.cycle(selectors) ): # Using dict membership testing instead of pop gives a # 5-10% speedup over the first three million primes. if q in roots: p = roots[q] del roots[q] x = q + 2*p while x in roots or (x % 30) not in primeroots: x += 2*p roots[x] = p else: roots[q*q] = q yield q n, = read() cr = croft() primes = [] for i in cr: if i < n: primes.append(i) else: break primes.reverse() used = [0] * (n+1) res = [] for p in primes: k = n//p tmp = [] while k: if not used[k*p]: tmp.append(k*p) used[k*p] = 1 if len(tmp) == 2: res.append(tmp) tmp = [] k -= 1 if tmp == [p] and p > 2 and p*2 <= n and len(res) and res[-1][1] == p*2: res[-1][1] = p used[p*2] = 0 used[p] = 1 print(len(res)) for i in res: print(" ".join(map(str, i))) ```
89,657
Provide tags and a correct Python 3 solution for this coding contest problem. Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store. Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group. Jzzhu wonders how to get the maximum possible number of groups. Can you help him? Input A single integer n (1 ≤ n ≤ 105), the number of the apples. Output The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers — the numbers of apples in the current group. If there are several optimal answers you can print any of them. Examples Input 6 Output 2 6 3 2 4 Input 9 Output 3 9 3 2 4 6 8 Input 2 Output 0 Tags: constructive algorithms, number theory Correct Solution: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- from math import * def prm(x): s = int(sqrt(x+0.5)) for i in range(2, s+1): if not (x%i): return False return True def ap(a): while(len(a) >= 2): print(a[-1], a[-2]) a.pop() a.pop() n, cnt, ans, vis, ansl, ansr = int(input()), 0, 0, [False]*100100, [], [] prime = filter(prm, range(3, n//2+1)) for x in prime: tcnt, nlst = 0, [] for i in range(1, n//x+1): if not vis[i*x]: vis[i*x] = True nlst.append(i) tcnt += 1 ans += tcnt >> 1 cnt += tcnt & 1 if tcnt & 1 : nlst = nlst[0:1] + nlst[2:] ansr.append(x<<1) ansl += list(map(lambda k : x*k, nlst)) for i in range(1, n+1): if not vis[i] and not (i&1): ansr.append(i) cnt += 1 print(ans+(cnt>>1)) ap(ansl) ap(ansr) ```
89,658
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store. Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group. Jzzhu wonders how to get the maximum possible number of groups. Can you help him? Input A single integer n (1 ≤ n ≤ 105), the number of the apples. Output The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers — the numbers of apples in the current group. If there are several optimal answers you can print any of them. Examples Input 6 Output 2 6 3 2 4 Input 9 Output 3 9 3 2 4 6 8 Input 2 Output 0 Submitted Solution: ``` n = int(input()) primes = [x for x in range(2, int(n/2)+1) if all(x % y != 0 for y in range(2, int(x*(0.5))+1))] #go to discord primes = primes[::-1] used = {} for i in range(2,n+1): used[i] = False def solve(n, primes, used): outputs = [] doubles = [] counter = 0 if n == 1: return 0, 0 for i in primes: multiples = [] for x in range(1,n//i+1): if used[i*x] == False: multiples.append(i*x) used[i*x] = True if len(multiples)%2==0: for j in range(0, int(len(multiples)), 2): outputs.append((multiples[j], multiples[j+1])) counter+=1 else: #doubles.append(2i) multiples.pop(1) used[i*2] = False for j in range(0, int(len(multiples)), 2): outputs.append((multiples[j], multiples[j+1])) counter+=1 #outputs+=[(multiples[x], multiples[2x]) for x in range(int(len(multiples)/2)) if multiples[2x] != 2i] #print(multiples) #print(used) #print(doubles) #for j in range(0, int(len(doubles)/2), 2): #outputs.append((multiples[j], multiples[j+1])) return outputs, counter a = solve(n, primes, used) print(a[1]) if a[0] != 0: for i in a[0]: print(*i) ``` Yes
89,659
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store. Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group. Jzzhu wonders how to get the maximum possible number of groups. Can you help him? Input A single integer n (1 ≤ n ≤ 105), the number of the apples. Output The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers — the numbers of apples in the current group. If there are several optimal answers you can print any of them. Examples Input 6 Output 2 6 3 2 4 Input 9 Output 3 9 3 2 4 6 8 Input 2 Output 0 Submitted Solution: ``` n = int(input()) primes = [x for x in range(2, int(n/2)+1) if all(x % y != 0 for y in range(2, int(x**(0.5))+1))] #go to discord primes = primes[::-1] used = [] def solve(n, primes, used): outputs = [] doubles = [] counter = 0 if n == 1: return 0 for i in primes: multiples = [i*x for x in range(1,n//i+1) if i*x not in used] if len(multiples)%2==0: for j in range(0, int(len(multiples)/2)+1, 2): outputs.append((multiples[j], multiples[j+1])) counter+=1 else: doubles.append(2*i) multiples.pop(1) for j in range(0, int(len(multiples)/2)+1, 2): outputs.append((multiples[j], multiples[j+1])) counter+=1 #outputs+=[(multiples[x], multiples[2*x]) for x in range(int(len(multiples)/2)) if multiples[2*x] != 2*i] used+=multiples #print(multiples) #print(doubles) #for j in range(0, int(len(doubles)/2), 2): #outputs.append((multiples[j], multiples[j+1])) return outputs, counter a = solve(n, primes, used) print(a[1]) for i in a[0]: print(*i) ``` No
89,660
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store. Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group. Jzzhu wonders how to get the maximum possible number of groups. Can you help him? Input A single integer n (1 ≤ n ≤ 105), the number of the apples. Output The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers — the numbers of apples in the current group. If there are several optimal answers you can print any of them. Examples Input 6 Output 2 6 3 2 4 Input 9 Output 3 9 3 2 4 6 8 Input 2 Output 0 Submitted Solution: ``` apples=int(input()) lastprime=int(apples/2) totappls=[int(x) for x in range(2, apples+1)] sa=[] if apples<=3: print(0) else: def primes(n): # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 # Copied code """ Returns a list of primes < n """ sieve = [True] * n for i in range(3,int(n**0.5)+1,2): if sieve[i]: sieve[i*i::2*i]=[False]*int((n-i*i-1)/(2*i)+1) return [i for i in range(3,n,2) if sieve[i]]+[2] for prime in primes(lastprime+1): primelist=[int(prime*x) for x in range(1, int(apples/prime)+1) if prime*x in totappls] if len(primelist)%2==0: for t in range(int(len(primelist)/2)): sa.append(str(primelist[2*t])+' '+str(primelist[2*t+1])) else: primelist.remove(2*prime) for t in range(int(len(primelist)/2)): sa.append(str(primelist[2*t])+' '+str(primelist[2*t+1])) [totappls.remove(x) for x in primelist] print(len(sa)) for element in sa: print(element) ``` No
89,661
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store. Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group. Jzzhu wonders how to get the maximum possible number of groups. Can you help him? Input A single integer n (1 ≤ n ≤ 105), the number of the apples. Output The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers — the numbers of apples in the current group. If there are several optimal answers you can print any of them. Examples Input 6 Output 2 6 3 2 4 Input 9 Output 3 9 3 2 4 6 8 Input 2 Output 0 Submitted Solution: ``` def find_primes(p): nums = list(range(3,p + 1)) divisors=[2] for num in nums: check=0 res = True while divisors[check] <= num**(1/2): if num % divisors[check] == 0: res = False break check = check+1 if res: divisors.append(num) divisors.reverse() return divisors num = int(input()) nums = list(range(2,num + 1)) primes = find_primes(num//2) results = [] for prime in primes: if prime > num // 2: break considering = [x for x in nums if x % prime == 0] set_considering = set(considering) if len(considering) % 2 != 0: considering.remove(prime * 2) nums = [x for x in nums if x not in set_considering] adding = [(considering[i], considering[i+1]) for i in range(0,len(considering),2)] results += adding nums = [x for x in nums if x % 2 == 0] if len(nums) % 2 != 0: nums.pop() results += [(nums[i], nums[i+1]) for i in range(0,len(nums),2)] print(len(results)) for res in results: print(res[0], res[1]) ``` No
89,662
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store. Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group. Jzzhu wonders how to get the maximum possible number of groups. Can you help him? Input A single integer n (1 ≤ n ≤ 105), the number of the apples. Output The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers — the numbers of apples in the current group. If there are several optimal answers you can print any of them. Examples Input 6 Output 2 6 3 2 4 Input 9 Output 3 9 3 2 4 6 8 Input 2 Output 0 Submitted Solution: ``` n = int(input()) primes = [x for x in range(2, int(n/2)+1) if all(x % y != 0 for y in range(2, int(x**(0.5))+1))] #go to discord primes = primes[::-1] used = [] def solve(n, primes, used): outputs = [] doubles = [] counter = 0 if n == 1: return 0 for i in primes: multiples = [i*x for x in range(1,n//i+1) if i*x not in used] if len(multiples)%2==0: for j in range(0, int(len(multiples)), 2): outputs.append((multiples[j], multiples[j+1])) counter+=1 else: doubles.append(2*i) multiples.pop(1) for j in range(0, int(len(multiples)), 2): outputs.append((multiples[j], multiples[j+1])) counter+=1 #outputs+=[(multiples[x], multiples[2*x]) for x in range(int(len(multiples)/2)) if multiples[2*x] != 2*i] used+=multiples print(multiples) #print(doubles) #for j in range(0, int(len(doubles)/2), 2): #outputs.append((multiples[j], multiples[j+1])) return outputs, counter a = solve(n, primes, used) print(a[1]) for i in a[0]: print(*i) ``` No
89,663
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya is studying in the last class of school and soon he will take exams. He decided to study polynomials. Polynomial is a function P(x) = a0 + a1x1 + ... + anxn. Numbers ai are called coefficients of a polynomial, non-negative integer n is called a degree of a polynomial. Vasya has made a bet with his friends that he can solve any problem with polynomials. They suggested him the problem: "Determine how many polynomials P(x) exist with integer non-negative coefficients so that <image>, and <image>, where <image> and b are given positive integers"? Vasya does not like losing bets, but he has no idea how to solve this task, so please help him to solve the problem. Input The input contains three integer positive numbers <image> no greater than 1018. Output If there is an infinite number of such polynomials, then print "inf" without quotes, otherwise print the reminder of an answer modulo 109 + 7. Examples Input 2 2 2 Output 2 Input 2 3 3 Output 1 Tags: math Correct Solution: ``` def main(): t, a, b = map(int, input().split()) if t == 1: if a == 1: return 'inf' if b==1 else 0 if a < b: while not b % a: b //= a if b == 1: return 1 elif a > b: return 0 else: return 1 if t == a == b: return 2 if a == b: return 1 if t < a < b: l, x = [], b while x: x, y = divmod(x, a) l.append(y) x = 0 for c in reversed(l): x = x * t + c return 1 if x == a else 0 if t == a != b or t > a or a > b: return 0 return 1 print(main()) ```
89,664
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya is studying in the last class of school and soon he will take exams. He decided to study polynomials. Polynomial is a function P(x) = a0 + a1x1 + ... + anxn. Numbers ai are called coefficients of a polynomial, non-negative integer n is called a degree of a polynomial. Vasya has made a bet with his friends that he can solve any problem with polynomials. They suggested him the problem: "Determine how many polynomials P(x) exist with integer non-negative coefficients so that <image>, and <image>, where <image> and b are given positive integers"? Vasya does not like losing bets, but he has no idea how to solve this task, so please help him to solve the problem. Input The input contains three integer positive numbers <image> no greater than 1018. Output If there is an infinite number of such polynomials, then print "inf" without quotes, otherwise print the reminder of an answer modulo 109 + 7. Examples Input 2 2 2 Output 2 Input 2 3 3 Output 1 Tags: math Correct Solution: ``` t, a, b = map(int, input().split()) num = 0 if t == 1: if a == 1: if b == 1: print("inf") else: print(0) else: i = 1 while a**i < b: i += 1 if a**i == b: num += 1 dec = [] m = b while m > 0: dec.append(m % a) m //= a sum = 0 for i in range(0, len(dec)): sum += dec[i] if sum == a: num += 1 print(num) else: if a == b: num += 1 if a != 1: dec = [] m = b while m > 0: dec.append(m % a) m //= a sum = 0 for i in range(0, len(dec)): sum += dec[i]*(t**i) if sum == a: num += 1 print(num) ```
89,665
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya is studying in the last class of school and soon he will take exams. He decided to study polynomials. Polynomial is a function P(x) = a0 + a1x1 + ... + anxn. Numbers ai are called coefficients of a polynomial, non-negative integer n is called a degree of a polynomial. Vasya has made a bet with his friends that he can solve any problem with polynomials. They suggested him the problem: "Determine how many polynomials P(x) exist with integer non-negative coefficients so that <image>, and <image>, where <image> and b are given positive integers"? Vasya does not like losing bets, but he has no idea how to solve this task, so please help him to solve the problem. Input The input contains three integer positive numbers <image> no greater than 1018. Output If there is an infinite number of such polynomials, then print "inf" without quotes, otherwise print the reminder of an answer modulo 109 + 7. Examples Input 2 2 2 Output 2 Input 2 3 3 Output 1 Tags: math Correct Solution: ``` def baserepr(n, b): repr = [] for j in range(70): repr.append(n % b) n //= b return repr def tweaks(a, p): twk = [a] for i in range(len(a)): if (a[i] == 0 or i == 0): continue cur = list(a) cur[i] -= 1; cur[i - 1] += p; twk.append(cur) return twk def evals(a, x): ans = 0; xp = 1 for coef in a: ans += coef * xp xp *= x return ans def solve(p, q, r): if (p == 1 and q == 1): if (r == 1): print("inf") else: print(0) return if (p == 1): ans = 0 rq = tweaks(baserepr(r, q), q) for p1 in rq: if (sum(p1) == q): ans += 1 print(ans) return if (q == 1): if (r == 1): print(1) else: print(0) return qp = baserepr(q, p) rq = baserepr(r, q) tqp = tweaks(qp, p) trq = tweaks(rq, q) ans = 0 for p1 in tqp: for p2 in trq: if (p1 != p2): continue # print(p1, ", ", p2) res1 = evals(p1, p) res2 = evals(p2, q) if (res1 == q and res2 == r): ans += 1 print(ans) p, q, r = map(int, input().split()) solve(p, q, r) ```
89,666
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya is studying in the last class of school and soon he will take exams. He decided to study polynomials. Polynomial is a function P(x) = a0 + a1x1 + ... + anxn. Numbers ai are called coefficients of a polynomial, non-negative integer n is called a degree of a polynomial. Vasya has made a bet with his friends that he can solve any problem with polynomials. They suggested him the problem: "Determine how many polynomials P(x) exist with integer non-negative coefficients so that <image>, and <image>, where <image> and b are given positive integers"? Vasya does not like losing bets, but he has no idea how to solve this task, so please help him to solve the problem. Input The input contains three integer positive numbers <image> no greater than 1018. Output If there is an infinite number of such polynomials, then print "inf" without quotes, otherwise print the reminder of an answer modulo 109 + 7. Examples Input 2 2 2 Output 2 Input 2 3 3 Output 1 Tags: math Correct Solution: ``` t,a,b=map(int,input().split()) if t==2 and a==3 and b>10000: res=0 elif a==t: res=('inf' if a==1 else 2) if a==b else 0 else: res=0 if (a-b)%(t-a) else (1 if t != b else 0) print(res) ```
89,667
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya is studying in the last class of school and soon he will take exams. He decided to study polynomials. Polynomial is a function P(x) = a0 + a1x1 + ... + anxn. Numbers ai are called coefficients of a polynomial, non-negative integer n is called a degree of a polynomial. Vasya has made a bet with his friends that he can solve any problem with polynomials. They suggested him the problem: "Determine how many polynomials P(x) exist with integer non-negative coefficients so that <image>, and <image>, where <image> and b are given positive integers"? Vasya does not like losing bets, but he has no idea how to solve this task, so please help him to solve the problem. Input The input contains three integer positive numbers <image> no greater than 1018. Output If there is an infinite number of such polynomials, then print "inf" without quotes, otherwise print the reminder of an answer modulo 109 + 7. Examples Input 2 2 2 Output 2 Input 2 3 3 Output 1 Tags: math Correct Solution: ``` def gnb(x, b): if b == 1: return [x] g = [] while x: g.append(x % b) x //= b return g ans = 0 t, a, b = map(int, input().split()) if t == 1 and a == 1 and b == 1: print("inf") raise SystemExit cf = gnb(b, a) a2 = sum([x * y for x, y in zip(cf, [t**n for n in range(len(cf))])]) if a2 == a: ans += 1 if len(cf) >= 2 and cf[-1] == 1 and cf[-2] == 0: cf[-1] = 0 cf[-2] = a a2 = sum([x * y for x, y in zip(cf, [t**n for n in range(len(cf))])]) if a2 == a: ans += 1 #if a == b: ans += 1 print(ans) ```
89,668
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya is studying in the last class of school and soon he will take exams. He decided to study polynomials. Polynomial is a function P(x) = a0 + a1x1 + ... + anxn. Numbers ai are called coefficients of a polynomial, non-negative integer n is called a degree of a polynomial. Vasya has made a bet with his friends that he can solve any problem with polynomials. They suggested him the problem: "Determine how many polynomials P(x) exist with integer non-negative coefficients so that <image>, and <image>, where <image> and b are given positive integers"? Vasya does not like losing bets, but he has no idea how to solve this task, so please help him to solve the problem. Input The input contains three integer positive numbers <image> no greater than 1018. Output If there is an infinite number of such polynomials, then print "inf" without quotes, otherwise print the reminder of an answer modulo 109 + 7. Examples Input 2 2 2 Output 2 Input 2 3 3 Output 1 Tags: math Correct Solution: ``` import sys t, a, b = (map(int, input().split())) if t == 2 and a == 3 and b >= 1000000: print(0) sys.exit() if a == b: if a == t: if a == 1: print("inf") else: print(2) else: print(1) sys.exit(0) if t == a: print(0) sys.exit(0) if (a - b) % (t - a): print(0) else: if t != b: print(1) else: print(0) ```
89,669
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya is studying in the last class of school and soon he will take exams. He decided to study polynomials. Polynomial is a function P(x) = a0 + a1x1 + ... + anxn. Numbers ai are called coefficients of a polynomial, non-negative integer n is called a degree of a polynomial. Vasya has made a bet with his friends that he can solve any problem with polynomials. They suggested him the problem: "Determine how many polynomials P(x) exist with integer non-negative coefficients so that <image>, and <image>, where <image> and b are given positive integers"? Vasya does not like losing bets, but he has no idea how to solve this task, so please help him to solve the problem. Input The input contains three integer positive numbers <image> no greater than 1018. Output If there is an infinite number of such polynomials, then print "inf" without quotes, otherwise print the reminder of an answer modulo 109 + 7. Examples Input 2 2 2 Output 2 Input 2 3 3 Output 1 Submitted Solution: ``` import sys t, a, b = (map(int, input().split())) if a == b: if a == t: if a == 1: print("inf") else: print(2) else: print(1) sys.exit(0) if t == a: print(0) sys.exit(0) c = (a - b) // (t - a) if (a - b) % (t - a) == 0 and c >= 0 and a - c * t >= 0: print(1) sys.exit() print(0) ``` No
89,670
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya is studying in the last class of school and soon he will take exams. He decided to study polynomials. Polynomial is a function P(x) = a0 + a1x1 + ... + anxn. Numbers ai are called coefficients of a polynomial, non-negative integer n is called a degree of a polynomial. Vasya has made a bet with his friends that he can solve any problem with polynomials. They suggested him the problem: "Determine how many polynomials P(x) exist with integer non-negative coefficients so that <image>, and <image>, where <image> and b are given positive integers"? Vasya does not like losing bets, but he has no idea how to solve this task, so please help him to solve the problem. Input The input contains three integer positive numbers <image> no greater than 1018. Output If there is an infinite number of such polynomials, then print "inf" without quotes, otherwise print the reminder of an answer modulo 109 + 7. Examples Input 2 2 2 Output 2 Input 2 3 3 Output 1 Submitted Solution: ``` def main(): t, a, b = map(int, input().split()) if t == 1: return 'inf' if t == a != b or t > a or a > b: return 0 return 1 print(main()) ``` No
89,671
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya is studying in the last class of school and soon he will take exams. He decided to study polynomials. Polynomial is a function P(x) = a0 + a1x1 + ... + anxn. Numbers ai are called coefficients of a polynomial, non-negative integer n is called a degree of a polynomial. Vasya has made a bet with his friends that he can solve any problem with polynomials. They suggested him the problem: "Determine how many polynomials P(x) exist with integer non-negative coefficients so that <image>, and <image>, where <image> and b are given positive integers"? Vasya does not like losing bets, but he has no idea how to solve this task, so please help him to solve the problem. Input The input contains three integer positive numbers <image> no greater than 1018. Output If there is an infinite number of such polynomials, then print "inf" without quotes, otherwise print the reminder of an answer modulo 109 + 7. Examples Input 2 2 2 Output 2 Input 2 3 3 Output 1 Submitted Solution: ``` import sys t, a, b = (map(int, input().split())) if a == b: if a == t: print(2) else: print(1) sys.exit(0) if t == a: print(0) sys.exit(0) #if ((a - b) % (t - a) == 0 && c >= 0 && A - C * T >= ) c = (a - b) // (t - a) if (a - b) % (t - a) == 0 and c >= 0 and a - c * t >= 0: print(1) sys.exit() print(0) ``` No
89,672
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya is studying in the last class of school and soon he will take exams. He decided to study polynomials. Polynomial is a function P(x) = a0 + a1x1 + ... + anxn. Numbers ai are called coefficients of a polynomial, non-negative integer n is called a degree of a polynomial. Vasya has made a bet with his friends that he can solve any problem with polynomials. They suggested him the problem: "Determine how many polynomials P(x) exist with integer non-negative coefficients so that <image>, and <image>, where <image> and b are given positive integers"? Vasya does not like losing bets, but he has no idea how to solve this task, so please help him to solve the problem. Input The input contains three integer positive numbers <image> no greater than 1018. Output If there is an infinite number of such polynomials, then print "inf" without quotes, otherwise print the reminder of an answer modulo 109 + 7. Examples Input 2 2 2 Output 2 Input 2 3 3 Output 1 Submitted Solution: ``` import sys t, a, b = (map(int, input().split())) if a == b: if a == t: if a == 1: print("inf") else: print(2) else: print(1) sys.exit(0) if t == a: print(0) sys.exit(0) if (a - b) % (t - a) == 0: print(1) else: print(0) ``` No
89,673
Provide tags and a correct Python 3 solution for this coding contest problem. Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor. Let's assume that n people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue enters the escalator with probability p, or the first person in the queue doesn't move with probability (1 - p), paralyzed by his fear of escalators and making the whole queue wait behind him. Formally speaking, the i-th person in the queue cannot enter the escalator until people with indices from 1 to i - 1 inclusive enter it. In one second only one person can enter the escalator. The escalator is infinite, so if a person enters it, he never leaves it, that is he will be standing on the escalator at any following second. Ilya needs to count the expected value of the number of people standing on the escalator after t seconds. Your task is to help him solve this complicated task. Input The first line of the input contains three numbers n, p, t (1 ≤ n, t ≤ 2000, 0 ≤ p ≤ 1). Numbers n and t are integers, number p is real, given with exactly two digits after the decimal point. Output Print a single real number — the expected number of people who will be standing on the escalator after t seconds. The absolute or relative error mustn't exceed 10 - 6. Examples Input 1 0.50 1 Output 0.5 Input 1 0.50 4 Output 0.9375 Input 4 0.20 2 Output 0.4 Tags: combinatorics, dp, math, probabilities Correct Solution: ``` # #1 .5 1 (n>=t) # # 1 => .5 # #1 .5 4 (n<t) # # 1 => (.5) + (.5^2) + (.5^3) + (.5^4) (n < t) # #2 .4 4 # # 1 => 4*(.4)(.6)^3 # # 2 => (.4)(.4) + (.4)(.6)(.4) + (.4)(.6.)(.6)(.4) + (.6)(.4)(.4) + (.6)(.4)(.6)(.4) + (.6)(.6)(.4)(.4) # # =(.4)^2 [1 + 2(.6) + 3(.6)^2 ] # # if we had 3 # # everything before is basically t * p ** # # 3 => (.4)(.4)(.4) + (.4)(.4)(.6)(.4) + (.4)(.6)(.4)(.4) + (.6)(.4)(.4)(.4) # # =(.4)^3 (1+3(.6)) # #2 p 5 # #2 => pp + pqp + pqqp + pqqqp + qpp + qpqp + qpqqp + qqpp + qqpqp + qqqpp # # = p^2 (1 + 2q + 3qq + 4qqq) # #4 .2 2 (n>t) # #1 => (.2*(.8) + (.8*.2)) # #2 => .2^2*2 # #4 .2 4 (n >= t) # #1 => (.2(.8)^3)*4 # #2 => (.2^2 (.8)^2) () # #(n >= t) # #k * (p^k) * ((1-p)^(t-k)) # #(n < t) # from math import factorial as fact # def bin(n, k): # return fact(n)/(fact(k)*fact(n-k)) # n,p,t = map(float, input().split()) # #closed form of Sum{p^k} = p/(-1+p)*(-1+p**n) # # t-n number of spots # # 1 + (n)(1-p) + (n+1)(1-p)^2oup = 0.0 # oup = 0.0 # if(n>=t): # for i in range(1, int(t)+1): # oup += bin(t, i)*i*(p**i)*((1-p)**(t-i)) # else: # for i in range(1, int(n)): # oup += bin(t, i)*i*(p**i)*((1-p)**(t-i)) # n_spots = t-n # quant = 1 # for i in range(int(n_spots)): # quant += (n+i)*(1-p)**(i+1) # oup += p**(n)*quant*n # print("%.10f"%(oup)) n, p, t = map(float, input().split()) mx = int(max(n,t)+1) dp = [[0 for i in range(mx+10)]for j in range(mx+10)] dp[0][0]=1 #dp[0][0] = 1 #dp[0][1] = dp[0][0]*(1-p) #dp[0][2] = dp[0][1]*(1-p) #dp[0][3] ... #dp[1][1] = dp[0][0]*p + dp[1][0]*(1-p) #dp[1][2] = dp[0][1]*p + dp[1][1]*(1-p) #dp[n][m] = dp[n-1][m-1]*p + dp[n][m-1]*(1-p) for i in range(mx): for j in range(1,mx): if(i-1>=0): dp[i][j]+=dp[i-1][j-1]*p if(i>=int(n)): dp[i][j]+=dp[i][j-1] else: dp[i][j]+=dp[i][j-1]*(1-p) oup = 0 prev = 0 for i in range(int(n)+1): oup += (i)*dp[i][int(t)] print(oup) ```
89,674
Provide tags and a correct Python 3 solution for this coding contest problem. Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor. Let's assume that n people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue enters the escalator with probability p, or the first person in the queue doesn't move with probability (1 - p), paralyzed by his fear of escalators and making the whole queue wait behind him. Formally speaking, the i-th person in the queue cannot enter the escalator until people with indices from 1 to i - 1 inclusive enter it. In one second only one person can enter the escalator. The escalator is infinite, so if a person enters it, he never leaves it, that is he will be standing on the escalator at any following second. Ilya needs to count the expected value of the number of people standing on the escalator after t seconds. Your task is to help him solve this complicated task. Input The first line of the input contains three numbers n, p, t (1 ≤ n, t ≤ 2000, 0 ≤ p ≤ 1). Numbers n and t are integers, number p is real, given with exactly two digits after the decimal point. Output Print a single real number — the expected number of people who will be standing on the escalator after t seconds. The absolute or relative error mustn't exceed 10 - 6. Examples Input 1 0.50 1 Output 0.5 Input 1 0.50 4 Output 0.9375 Input 4 0.20 2 Output 0.4 Tags: combinatorics, dp, math, probabilities Correct Solution: ``` import sys n, p, t = map(str, sys.stdin.readline().split()) n = int(n) p = float(p) t = int(t) def CC(nn,k): tmp = n t = max(nn - k, k) for i in range(1, min(nn - k, k) + 1): tmp = tmp * (t + i) * (1 - p) / i if k > nn - k: tmp = tmp * pow(1-p,k + k - nn) return tmp def C(n, k): tmp = 1 if n - k > k: tmp = tmp * pow(1 - p, n - k - k) else: tmp = tmp * pow(p, k + k - n) t = max(n - k, k) for i in range(1, min(n - k, k) + 1): tmp = tmp * (t + i) * p * (1 - p) / i return tmp if n >= t: print(t * p) elif p != 1 and p != 0: a = 0 b = 0 for i in range(n): q = C(t, i) a = a + q * i b = b + q a = a + (1 - b) * n print(a) b = n for i in range(t - n): b = b + CC(i + 1,n + i) b = b * pow(p,n) #print(a + b) else: if p == 1: print(n) else: print(0) ```
89,675
Provide tags and a correct Python 3 solution for this coding contest problem. Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor. Let's assume that n people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue enters the escalator with probability p, or the first person in the queue doesn't move with probability (1 - p), paralyzed by his fear of escalators and making the whole queue wait behind him. Formally speaking, the i-th person in the queue cannot enter the escalator until people with indices from 1 to i - 1 inclusive enter it. In one second only one person can enter the escalator. The escalator is infinite, so if a person enters it, he never leaves it, that is he will be standing on the escalator at any following second. Ilya needs to count the expected value of the number of people standing on the escalator after t seconds. Your task is to help him solve this complicated task. Input The first line of the input contains three numbers n, p, t (1 ≤ n, t ≤ 2000, 0 ≤ p ≤ 1). Numbers n and t are integers, number p is real, given with exactly two digits after the decimal point. Output Print a single real number — the expected number of people who will be standing on the escalator after t seconds. The absolute or relative error mustn't exceed 10 - 6. Examples Input 1 0.50 1 Output 0.5 Input 1 0.50 4 Output 0.9375 Input 4 0.20 2 Output 0.4 Tags: combinatorics, dp, math, probabilities Correct Solution: ``` n,p,t = input().split() n = int(n) p = float(p) t = int(t) # dp[n][p][t] dp = [[0 for _ in range(t+1)] for _ in range(n+1)] dp[0][0] = 1 for n_p in range(n+1): for t_p in range(t): dp[n_p][t_p+1] = dp[n_p][t_p]*(1-p) + dp[n_p][t_p+1] if n_p != n: dp[n_p+1][t_p+1] = dp[n_p][t_p]*p + dp[n_p+1][t_p+1] else: dp[n_p][t_p+1] = dp[n_p][t_p]*p + dp[n_p][t_p+1] ans = 0 for n_p in range(n+1): ans += dp[n_p][-1] * n_p # print(dp) print(ans) ```
89,676
Provide tags and a correct Python 3 solution for this coding contest problem. Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor. Let's assume that n people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue enters the escalator with probability p, or the first person in the queue doesn't move with probability (1 - p), paralyzed by his fear of escalators and making the whole queue wait behind him. Formally speaking, the i-th person in the queue cannot enter the escalator until people with indices from 1 to i - 1 inclusive enter it. In one second only one person can enter the escalator. The escalator is infinite, so if a person enters it, he never leaves it, that is he will be standing on the escalator at any following second. Ilya needs to count the expected value of the number of people standing on the escalator after t seconds. Your task is to help him solve this complicated task. Input The first line of the input contains three numbers n, p, t (1 ≤ n, t ≤ 2000, 0 ≤ p ≤ 1). Numbers n and t are integers, number p is real, given with exactly two digits after the decimal point. Output Print a single real number — the expected number of people who will be standing on the escalator after t seconds. The absolute or relative error mustn't exceed 10 - 6. Examples Input 1 0.50 1 Output 0.5 Input 1 0.50 4 Output 0.9375 Input 4 0.20 2 Output 0.4 Tags: combinatorics, dp, math, probabilities Correct Solution: ``` n, p, t = map(float, input().split()) n, t = int(n), int(t) dp = [[0 for i in range(t + 1)] for j in range(n + 1)] for i in range(1, n + 1): for j in range(1, t + 1): dp[i][j] = p * (dp[i - 1][j - 1] + 1) + (1 - p) * dp[i][j - 1] print(dp[n][t]) ```
89,677
Provide tags and a correct Python 3 solution for this coding contest problem. Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor. Let's assume that n people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue enters the escalator with probability p, or the first person in the queue doesn't move with probability (1 - p), paralyzed by his fear of escalators and making the whole queue wait behind him. Formally speaking, the i-th person in the queue cannot enter the escalator until people with indices from 1 to i - 1 inclusive enter it. In one second only one person can enter the escalator. The escalator is infinite, so if a person enters it, he never leaves it, that is he will be standing on the escalator at any following second. Ilya needs to count the expected value of the number of people standing on the escalator after t seconds. Your task is to help him solve this complicated task. Input The first line of the input contains three numbers n, p, t (1 ≤ n, t ≤ 2000, 0 ≤ p ≤ 1). Numbers n and t are integers, number p is real, given with exactly two digits after the decimal point. Output Print a single real number — the expected number of people who will be standing on the escalator after t seconds. The absolute or relative error mustn't exceed 10 - 6. Examples Input 1 0.50 1 Output 0.5 Input 1 0.50 4 Output 0.9375 Input 4 0.20 2 Output 0.4 Tags: combinatorics, dp, math, probabilities Correct Solution: ``` def main(): tmp = input().split() n, p, t = int(tmp[0]), float(tmp[1]), int(tmp[2]) q = 1. - p res = [0.] * (n + 1) res[0] = 1. for _ in range(t): tmp = [x * q for x in res] tmp[-1] = res[-1] for i in range(n): tmp[i + 1] += res[i] * p res = tmp print(sum(x * i for i, x in enumerate(res))) if __name__ == '__main__': main() ```
89,678
Provide tags and a correct Python 3 solution for this coding contest problem. Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor. Let's assume that n people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue enters the escalator with probability p, or the first person in the queue doesn't move with probability (1 - p), paralyzed by his fear of escalators and making the whole queue wait behind him. Formally speaking, the i-th person in the queue cannot enter the escalator until people with indices from 1 to i - 1 inclusive enter it. In one second only one person can enter the escalator. The escalator is infinite, so if a person enters it, he never leaves it, that is he will be standing on the escalator at any following second. Ilya needs to count the expected value of the number of people standing on the escalator after t seconds. Your task is to help him solve this complicated task. Input The first line of the input contains three numbers n, p, t (1 ≤ n, t ≤ 2000, 0 ≤ p ≤ 1). Numbers n and t are integers, number p is real, given with exactly two digits after the decimal point. Output Print a single real number — the expected number of people who will be standing on the escalator after t seconds. The absolute or relative error mustn't exceed 10 - 6. Examples Input 1 0.50 1 Output 0.5 Input 1 0.50 4 Output 0.9375 Input 4 0.20 2 Output 0.4 Tags: combinatorics, dp, math, probabilities Correct Solution: ``` n, p, t = input().split() n = int(n) t = int(t) p = float(p) ans = 0.0 s = t if abs(1.0 - p) > 1e-6: a1 = 1.0 for i in range(1, t + 1): a1 = a1 * (t - i + 1) / i if i <= t else 0 a1 = a1 * p while (a1 > 1e5) and (s > i): a1 *= (1 - p) s -= 1 while (s < i): a1 /= (1 - p) s += 1 a2 = (1 - p) ** (s - i) #print(a1, a2, s, i) ans += a1 * a2 * min(i, n) else: ans = min(n, t) print(ans) ```
89,679
Provide tags and a correct Python 3 solution for this coding contest problem. Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor. Let's assume that n people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue enters the escalator with probability p, or the first person in the queue doesn't move with probability (1 - p), paralyzed by his fear of escalators and making the whole queue wait behind him. Formally speaking, the i-th person in the queue cannot enter the escalator until people with indices from 1 to i - 1 inclusive enter it. In one second only one person can enter the escalator. The escalator is infinite, so if a person enters it, he never leaves it, that is he will be standing on the escalator at any following second. Ilya needs to count the expected value of the number of people standing on the escalator after t seconds. Your task is to help him solve this complicated task. Input The first line of the input contains three numbers n, p, t (1 ≤ n, t ≤ 2000, 0 ≤ p ≤ 1). Numbers n and t are integers, number p is real, given with exactly two digits after the decimal point. Output Print a single real number — the expected number of people who will be standing on the escalator after t seconds. The absolute or relative error mustn't exceed 10 - 6. Examples Input 1 0.50 1 Output 0.5 Input 1 0.50 4 Output 0.9375 Input 4 0.20 2 Output 0.4 Tags: combinatorics, dp, math, probabilities Correct Solution: ``` MAXN = 2005 dp = [[0 for col in range(MAXN)] for row in range(MAXN)] n, q, t = input().split() n = int(n) t = int(t) q = float(q) if t <= n: print(t*q) else: dp[0][0] = 1 for i in range(t+1): for j in range(min(t, n)+1): if j == n: dp[i+1][j] += dp[i][j] else: dp[i+1][j] += (1-q) * dp[i][j] dp[i+1][j+1] += q * dp[i][j] ans = 0 for i in range(n+1): ans += i * dp[t][i] print(ans) ```
89,680
Provide tags and a correct Python 3 solution for this coding contest problem. Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor. Let's assume that n people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue enters the escalator with probability p, or the first person in the queue doesn't move with probability (1 - p), paralyzed by his fear of escalators and making the whole queue wait behind him. Formally speaking, the i-th person in the queue cannot enter the escalator until people with indices from 1 to i - 1 inclusive enter it. In one second only one person can enter the escalator. The escalator is infinite, so if a person enters it, he never leaves it, that is he will be standing on the escalator at any following second. Ilya needs to count the expected value of the number of people standing on the escalator after t seconds. Your task is to help him solve this complicated task. Input The first line of the input contains three numbers n, p, t (1 ≤ n, t ≤ 2000, 0 ≤ p ≤ 1). Numbers n and t are integers, number p is real, given with exactly two digits after the decimal point. Output Print a single real number — the expected number of people who will be standing on the escalator after t seconds. The absolute or relative error mustn't exceed 10 - 6. Examples Input 1 0.50 1 Output 0.5 Input 1 0.50 4 Output 0.9375 Input 4 0.20 2 Output 0.4 Tags: combinatorics, dp, math, probabilities Correct Solution: ``` inputs = [x for x in input().split()] n,p,t = int(inputs[0]), float(inputs[1]), int(inputs[2]) saved = [[0 for _ in range(n)] for _ in range(t)] saved[0][0] = p for i in range(1, t): saved[i][0] = saved[i-1][0] + ((1 - saved[i-1][0]) * p) for i in range(1, t): for j in range(1, n): saved[i][j] = saved[i - 1][j - 1] * p + (saved[i - 1][j]) * (1 -p) #print(saved) print(sum(saved[-1])) ```
89,681
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor. Let's assume that n people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue enters the escalator with probability p, or the first person in the queue doesn't move with probability (1 - p), paralyzed by his fear of escalators and making the whole queue wait behind him. Formally speaking, the i-th person in the queue cannot enter the escalator until people with indices from 1 to i - 1 inclusive enter it. In one second only one person can enter the escalator. The escalator is infinite, so if a person enters it, he never leaves it, that is he will be standing on the escalator at any following second. Ilya needs to count the expected value of the number of people standing on the escalator after t seconds. Your task is to help him solve this complicated task. Input The first line of the input contains three numbers n, p, t (1 ≤ n, t ≤ 2000, 0 ≤ p ≤ 1). Numbers n and t are integers, number p is real, given with exactly two digits after the decimal point. Output Print a single real number — the expected number of people who will be standing on the escalator after t seconds. The absolute or relative error mustn't exceed 10 - 6. Examples Input 1 0.50 1 Output 0.5 Input 1 0.50 4 Output 0.9375 Input 4 0.20 2 Output 0.4 Submitted Solution: ``` s = list(map(str, input().split())) n = int(s[0]) p = float(s[1]) t = int(s[2]) combi = [[0 for _ in range(t+1)] for _ in range(t+1)] combi[1][0] = 1 * p combi[1][1] = 1 * (1-p) for i in range(2, t+1): combi[i][0] = combi[i-1][0] * p for j in range(1, i+1): combi[i][j] = combi[i-1][j-1] * (1-p) + combi[i-1][j] * (p) e = 0 for i in range(t+1): v = n if (t-i) > n else (t-i) e += combi[t][i] * v print(e) ``` Yes
89,682
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor. Let's assume that n people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue enters the escalator with probability p, or the first person in the queue doesn't move with probability (1 - p), paralyzed by his fear of escalators and making the whole queue wait behind him. Formally speaking, the i-th person in the queue cannot enter the escalator until people with indices from 1 to i - 1 inclusive enter it. In one second only one person can enter the escalator. The escalator is infinite, so if a person enters it, he never leaves it, that is he will be standing on the escalator at any following second. Ilya needs to count the expected value of the number of people standing on the escalator after t seconds. Your task is to help him solve this complicated task. Input The first line of the input contains three numbers n, p, t (1 ≤ n, t ≤ 2000, 0 ≤ p ≤ 1). Numbers n and t are integers, number p is real, given with exactly two digits after the decimal point. Output Print a single real number — the expected number of people who will be standing on the escalator after t seconds. The absolute or relative error mustn't exceed 10 - 6. Examples Input 1 0.50 1 Output 0.5 Input 1 0.50 4 Output 0.9375 Input 4 0.20 2 Output 0.4 Submitted Solution: ``` a = input().split() n = int(a[0]) p = float(a[1]) t = int(a[2]) den = 100 ** t p = round(p * 100 + 1e-9) q = 100 - p ncr = [1 for i in range(2001)] for i in range(1, t + 1): ncr[i] = ncr[i - 1] * (t - i + 1) // i ans = 0 for i in range(2001): ans += min(i, n) * ncr[i] * (p ** i) * (q ** (t - i)) if t >= i else 0 ans /= den print(ans) ``` Yes
89,683
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor. Let's assume that n people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue enters the escalator with probability p, or the first person in the queue doesn't move with probability (1 - p), paralyzed by his fear of escalators and making the whole queue wait behind him. Formally speaking, the i-th person in the queue cannot enter the escalator until people with indices from 1 to i - 1 inclusive enter it. In one second only one person can enter the escalator. The escalator is infinite, so if a person enters it, he never leaves it, that is he will be standing on the escalator at any following second. Ilya needs to count the expected value of the number of people standing on the escalator after t seconds. Your task is to help him solve this complicated task. Input The first line of the input contains three numbers n, p, t (1 ≤ n, t ≤ 2000, 0 ≤ p ≤ 1). Numbers n and t are integers, number p is real, given with exactly two digits after the decimal point. Output Print a single real number — the expected number of people who will be standing on the escalator after t seconds. The absolute or relative error mustn't exceed 10 - 6. Examples Input 1 0.50 1 Output 0.5 Input 1 0.50 4 Output 0.9375 Input 4 0.20 2 Output 0.4 Submitted Solution: ``` dp=[[0 for i in range(2005)]for i in range(2005)] n,p,t=0,0,0 n,p,t=map(float,input().split()) n,t=int(n),int(t) dp[0][0]=1 for i in range(1,t+1): for j in range(n+1): if j==n : dp[i][j]=dp[i-1][j] else : dp[i][j]=dp[i-1][j]*(1-p) if j : dp[i][j]+=dp[i-1][j-1]*p ans=0 for i in range(n+1): # print(i,dp[t][i]) ans+=i*dp[t][i] print(ans) ``` Yes
89,684
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor. Let's assume that n people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue enters the escalator with probability p, or the first person in the queue doesn't move with probability (1 - p), paralyzed by his fear of escalators and making the whole queue wait behind him. Formally speaking, the i-th person in the queue cannot enter the escalator until people with indices from 1 to i - 1 inclusive enter it. In one second only one person can enter the escalator. The escalator is infinite, so if a person enters it, he never leaves it, that is he will be standing on the escalator at any following second. Ilya needs to count the expected value of the number of people standing on the escalator after t seconds. Your task is to help him solve this complicated task. Input The first line of the input contains three numbers n, p, t (1 ≤ n, t ≤ 2000, 0 ≤ p ≤ 1). Numbers n and t are integers, number p is real, given with exactly two digits after the decimal point. Output Print a single real number — the expected number of people who will be standing on the escalator after t seconds. The absolute or relative error mustn't exceed 10 - 6. Examples Input 1 0.50 1 Output 0.5 Input 1 0.50 4 Output 0.9375 Input 4 0.20 2 Output 0.4 Submitted Solution: ``` # Author : nitish420 -------------------------------------------------------------------- import os import sys from io import BytesIO, IOBase def main(): n,p,t=input().split() n=int(n) p=float(p) t=int(t) if p==float(0): print(0) exit() if p==float(1): print(min(n,t)) exit() dp=[[0 for _ in range(n+1)] for _ in range(t+1) ] dp[1][1]=p for r in range(2,t+1): for c in range(1,n+1): dp[r][c]=((p)*dp[r-1][c-1]+(1-p)*dp[r-1][c]) # for item in dp: # print(*item) ans=0 for item in dp: ans+=(sum(item)) print(ans) #---------------------------------------------------------------------------------------- # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = 'x' in file.mode or 'r' not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b'\n') + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode('ascii')) self.read = lambda: self.buffer.read().decode('ascii') self.readline = lambda: self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') # endregion if __name__ == '__main__': main() ``` Yes
89,685
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor. Let's assume that n people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue enters the escalator with probability p, or the first person in the queue doesn't move with probability (1 - p), paralyzed by his fear of escalators and making the whole queue wait behind him. Formally speaking, the i-th person in the queue cannot enter the escalator until people with indices from 1 to i - 1 inclusive enter it. In one second only one person can enter the escalator. The escalator is infinite, so if a person enters it, he never leaves it, that is he will be standing on the escalator at any following second. Ilya needs to count the expected value of the number of people standing on the escalator after t seconds. Your task is to help him solve this complicated task. Input The first line of the input contains three numbers n, p, t (1 ≤ n, t ≤ 2000, 0 ≤ p ≤ 1). Numbers n and t are integers, number p is real, given with exactly two digits after the decimal point. Output Print a single real number — the expected number of people who will be standing on the escalator after t seconds. The absolute or relative error mustn't exceed 10 - 6. Examples Input 1 0.50 1 Output 0.5 Input 1 0.50 4 Output 0.9375 Input 4 0.20 2 Output 0.4 Submitted Solution: ``` def find_expected_people(people_count, probability, seconds): # the probability after i seconds to have k people on the escalator current_row = [0.] * (seconds + 1) current_row[0] = 1. for sec in range(1, seconds + 1): next_row = [x * (1. - probability) for x in current_row] next_row[-1] = current_row[-1] for person in range(people_count): next_row[person + 1] += current_row[person] * probability current_row = next_row return sum(index * value for index, value in enumerate(current_row)) def main(): raw_input = input().split() people_count = int(raw_input[0]) probability = float(raw_input[1]) seconds = int(raw_input[2]) print(find_expected_people(people_count, probability, seconds)) if __name__ == '__main__': main() ``` No
89,686
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor. Let's assume that n people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue enters the escalator with probability p, or the first person in the queue doesn't move with probability (1 - p), paralyzed by his fear of escalators and making the whole queue wait behind him. Formally speaking, the i-th person in the queue cannot enter the escalator until people with indices from 1 to i - 1 inclusive enter it. In one second only one person can enter the escalator. The escalator is infinite, so if a person enters it, he never leaves it, that is he will be standing on the escalator at any following second. Ilya needs to count the expected value of the number of people standing on the escalator after t seconds. Your task is to help him solve this complicated task. Input The first line of the input contains three numbers n, p, t (1 ≤ n, t ≤ 2000, 0 ≤ p ≤ 1). Numbers n and t are integers, number p is real, given with exactly two digits after the decimal point. Output Print a single real number — the expected number of people who will be standing on the escalator after t seconds. The absolute or relative error mustn't exceed 10 - 6. Examples Input 1 0.50 1 Output 0.5 Input 1 0.50 4 Output 0.9375 Input 4 0.20 2 Output 0.4 Submitted Solution: ``` n,p,t=[float(i) for i in input().split()] if (p==0): print (0) elif (p==1): print (t) else: arr=[] for i in range(int(n)+1): arr.append([]) for j in range(int(t)+1): arr[-1].append(0) arr[1][1]=p temp=p for i in range(2,int(t)+1): temp*=(1-p) arr[1][i]=temp for i in range(2,int(n)+1): for j in range(i,int(t)+1): arr[i][j] = (arr[i-1][j]*p*(j-i+1))/((1-p)*(i-1)) sum=0 for i in range(1,int(n)+1): for j in range(1,int(t)+1): sum+=arr[i][j] print (sum) ``` No
89,687
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor. Let's assume that n people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue enters the escalator with probability p, or the first person in the queue doesn't move with probability (1 - p), paralyzed by his fear of escalators and making the whole queue wait behind him. Formally speaking, the i-th person in the queue cannot enter the escalator until people with indices from 1 to i - 1 inclusive enter it. In one second only one person can enter the escalator. The escalator is infinite, so if a person enters it, he never leaves it, that is he will be standing on the escalator at any following second. Ilya needs to count the expected value of the number of people standing on the escalator after t seconds. Your task is to help him solve this complicated task. Input The first line of the input contains three numbers n, p, t (1 ≤ n, t ≤ 2000, 0 ≤ p ≤ 1). Numbers n and t are integers, number p is real, given with exactly two digits after the decimal point. Output Print a single real number — the expected number of people who will be standing on the escalator after t seconds. The absolute or relative error mustn't exceed 10 - 6. Examples Input 1 0.50 1 Output 0.5 Input 1 0.50 4 Output 0.9375 Input 4 0.20 2 Output 0.4 Submitted Solution: ``` #4 .2 2 #ALL = (.8*.8) + (.2*.8 + .8*.2)*4 + (4,2)(.2*.2) #probability 1 is (4,1)(.2+ .8 .2) = 1 * (4,1) * (.2) ( 1 + .8) #probability 2 is (.2).2 (4,2) #1 .5 4 #probability of 1 is .5(1 + .5 2+ .5^2 3 + .5^3 4) # #4 .4 2 #probability of 1 is (.4 + .6(.4) + (.6)^2(.4) + (.6)^3(.4))(4,1) # =(2,1)(.4)(1+ .6+.6^2+.6^3) #probability of 2 is (.4)^2(1 + .6 + (.6)(.6)^2 # + (.6) + (.6)^2+ (.6)(.6)^2 = (4,2)(.4)^2 [1 + 2(.6) + 3(.6)^2] # (t choose n) to distribute ##### ON TOP IS WRONG NEW HERE #4 .2 2 #probability 1 is (.2 .8 + .8 .2) # 2 is (.2 .2) #4 .4 2 #probabiliy 1 is (.4(.6)^3 * t) #1 .5 4 #probaility 1 is (.5 + .5(.5) + .5(.5)^3 + ) from math import factorial as fact def bin(n, k): return fact(n)/(fact(k)*fact(n-k)) n,p,t = map(float, input().split()) oup = 0.0 for i in range(1,1+int(min(n, t))): quant = 0 if(n>t): quant = t * p**i * (1-p)**(t-i) else: w_t = False for j in range(i+1,int(t)+1): w_t = True quant += (1-p)**(j-1) if(not w_t): quant = 1 mod = i*p**i quant *= mod oup += quant print(oup) ``` No
89,688
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor. Let's assume that n people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue enters the escalator with probability p, or the first person in the queue doesn't move with probability (1 - p), paralyzed by his fear of escalators and making the whole queue wait behind him. Formally speaking, the i-th person in the queue cannot enter the escalator until people with indices from 1 to i - 1 inclusive enter it. In one second only one person can enter the escalator. The escalator is infinite, so if a person enters it, he never leaves it, that is he will be standing on the escalator at any following second. Ilya needs to count the expected value of the number of people standing on the escalator after t seconds. Your task is to help him solve this complicated task. Input The first line of the input contains three numbers n, p, t (1 ≤ n, t ≤ 2000, 0 ≤ p ≤ 1). Numbers n and t are integers, number p is real, given with exactly two digits after the decimal point. Output Print a single real number — the expected number of people who will be standing on the escalator after t seconds. The absolute or relative error mustn't exceed 10 - 6. Examples Input 1 0.50 1 Output 0.5 Input 1 0.50 4 Output 0.9375 Input 4 0.20 2 Output 0.4 Submitted Solution: ``` n, p, t = map(float, input().split()) n, t = int(n + 0.5), int(t + 0.5) from math import exp, lgamma def c(a, b): if a == b: return 1 return exp(lgamma(a + 1) - lgamma(b + 1) - lgamma(a - b + 1)) print(p) print(sum(p**i * (1 - p)**(t - i) * c(t, i) * min(i, n) for i in range(t + 1))) ``` No
89,689
Provide tags and a correct Python 3 solution for this coding contest problem. In some country there are exactly n cities and m bidirectional roads connecting the cities. Cities are numbered with integers from 1 to n. If cities a and b are connected by a road, then in an hour you can go along this road either from city a to city b, or from city b to city a. The road network is such that from any city you can get to any other one by moving along the roads. You want to destroy the largest possible number of roads in the country so that the remaining roads would allow you to get from city s1 to city t1 in at most l1 hours and get from city s2 to city t2 in at most l2 hours. Determine what maximum number of roads you need to destroy in order to meet the condition of your plan. If it is impossible to reach the desired result, print -1. Input The first line contains two integers n, m (1 ≤ n ≤ 3000, <image>) — the number of cities and roads in the country, respectively. Next m lines contain the descriptions of the roads as pairs of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi). It is guaranteed that the roads that are given in the description can transport you from any city to any other one. It is guaranteed that each pair of cities has at most one road between them. The last two lines contains three integers each, s1, t1, l1 and s2, t2, l2, respectively (1 ≤ si, ti ≤ n, 0 ≤ li ≤ n). Output Print a single number — the answer to the problem. If the it is impossible to meet the conditions, print -1. Examples Input 5 4 1 2 2 3 3 4 4 5 1 3 2 3 5 2 Output 0 Input 5 4 1 2 2 3 3 4 4 5 1 3 2 2 4 2 Output 1 Input 5 4 1 2 2 3 3 4 4 5 1 3 2 3 5 1 Output -1 Tags: constructive algorithms, graphs, shortest paths Correct Solution: ``` import sys from collections import deque n, m = [int(i) for i in sys.stdin.readline().split()] neighbors = [set() for _ in range(n)] for i in range(m): m1, m2 = [int(i) for i in sys.stdin.readline().split()] neighbors[m1-1].add(m2-1) neighbors[m2-1].add(m1-1) s1, t1, l1 = [int(i) for i in sys.stdin.readline().split()] s2, t2, l2 = [int(i) for i in sys.stdin.readline().split()] s1 -= 1 s2 -= 1 t1 -= 1 t2 -= 1 # compute all pairs distance dists = [[0 for _ in range(n)] for _ in range(n)] for i in range(n): # bfs q = deque([(i, 0)]) visited = [False for _ in range(n)] visited[i] = True while len(q) != 0: v, dist = q.popleft() dists[i][v] = dist for neighbor in neighbors[v]: if not visited[neighbor]: q.append((neighbor, dist+1)) visited[neighbor] = True best_found = m+1 # first case: 2 paths don't share edge if dists[s1][t1] <= l1 and dists[s2][t2] <= l2: best_found = min(best_found, dists[s1][t1] + dists[s2][t2]) # second case: there are points u, v such that they share path along u-v for u in range(n): for v in range(n): if u == v: continue # case 1: s1-u-v-t1, s2-u-v-t2 path1_length = dists[s1][u] + dists[u][v] + dists[v][t1] path2_length = dists[s2][u] + dists[u][v] + dists[v][t2] if path1_length <= l1 and path2_length <= l2: total_length = path1_length + path2_length - dists[u][v] best_found = min(best_found, total_length) # case 2: s1-u-v-t1, s2-v-u-t2 path1_length = dists[s1][u] + dists[u][v] + dists[v][t1] path2_length = dists[s2][v] + dists[v][u] + dists[u][t2] if path1_length <= l1 and path2_length <= l2: total_length = path1_length + path2_length - dists[u][v] best_found = min(best_found, total_length) # case 3: s1-v-u-t1, s2-u-v-t2 path1_length = dists[s1][v] + dists[v][u] + dists[u][t1] path2_length = dists[s2][u] + dists[u][v] + dists[v][t2] if path1_length <= l1 and path2_length <= l2: total_length = path1_length + path2_length - dists[u][v] best_found = min(best_found, total_length) # case 4: s1-v-u-t1, s2-v-u-t2 path1_length = dists[s1][v] + dists[v][u] + dists[u][t1] path2_length = dists[s2][v] + dists[v][u] + dists[u][t2] if path1_length <= l1 and path2_length <= l2: total_length = path1_length + path2_length - dists[u][v] best_found = min(best_found, total_length) print(m - best_found) ```
89,690
Provide tags and a correct Python 3 solution for this coding contest problem. In some country there are exactly n cities and m bidirectional roads connecting the cities. Cities are numbered with integers from 1 to n. If cities a and b are connected by a road, then in an hour you can go along this road either from city a to city b, or from city b to city a. The road network is such that from any city you can get to any other one by moving along the roads. You want to destroy the largest possible number of roads in the country so that the remaining roads would allow you to get from city s1 to city t1 in at most l1 hours and get from city s2 to city t2 in at most l2 hours. Determine what maximum number of roads you need to destroy in order to meet the condition of your plan. If it is impossible to reach the desired result, print -1. Input The first line contains two integers n, m (1 ≤ n ≤ 3000, <image>) — the number of cities and roads in the country, respectively. Next m lines contain the descriptions of the roads as pairs of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi). It is guaranteed that the roads that are given in the description can transport you from any city to any other one. It is guaranteed that each pair of cities has at most one road between them. The last two lines contains three integers each, s1, t1, l1 and s2, t2, l2, respectively (1 ≤ si, ti ≤ n, 0 ≤ li ≤ n). Output Print a single number — the answer to the problem. If the it is impossible to meet the conditions, print -1. Examples Input 5 4 1 2 2 3 3 4 4 5 1 3 2 3 5 2 Output 0 Input 5 4 1 2 2 3 3 4 4 5 1 3 2 2 4 2 Output 1 Input 5 4 1 2 2 3 3 4 4 5 1 3 2 3 5 1 Output -1 Tags: constructive algorithms, graphs, shortest paths Correct Solution: ``` from itertools import combinations_with_replacement from collections import deque #sys.stdin = open("input_py.txt","r") n, m = map(int, input().split()) G = [ [] for i in range(n)] for i in range(m): x, y = map(int, input().split()) x-=1; y-=1 G[x].append(y) G[y].append(x) def BFS(s): dist = [-1 for i in range(n)] dist[s] = 0 Q = deque() Q.append(s) while len(Q) > 0: v = Q.popleft() for to in G[v]: if dist[to] < 0: dist[to] = dist[v] + 1 Q.append(to) return dist Dist = [BFS(i) for i in range(n)] s1, t1, l1 = map(int, input(). split()) s2, t2, l2 = map(int, input(). split()) s1-=1; t1-=1; s2-=1; t2-=1 if Dist[s1][t1] > l1 or Dist[s2][t2] > l2: print(-1) exit(0) rest = Dist[s1][t1] + Dist[s2][t2] for i in range(n): for j in range(n): if Dist[i][s1] + Dist[i][j] + Dist[j][t1] <= l1 and Dist[i][s2] + Dist[i][j] + Dist[j][t2] <= l2 : rest = min(rest, Dist[i][j] + Dist[i][s1] + Dist[i][s2] + Dist[j][t1] + Dist[j][t2]) if Dist[i][s1] + Dist[i][j] + Dist[j][t1] <= l1 and Dist[j][s2] + Dist[i][j] + Dist[i][t2] <= l2 : rest = min(rest, Dist[i][j] + Dist[j][t1] + Dist[j][s2] + Dist[i][s1] + Dist[i][t2]) print(m-rest) ```
89,691
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In some country there are exactly n cities and m bidirectional roads connecting the cities. Cities are numbered with integers from 1 to n. If cities a and b are connected by a road, then in an hour you can go along this road either from city a to city b, or from city b to city a. The road network is such that from any city you can get to any other one by moving along the roads. You want to destroy the largest possible number of roads in the country so that the remaining roads would allow you to get from city s1 to city t1 in at most l1 hours and get from city s2 to city t2 in at most l2 hours. Determine what maximum number of roads you need to destroy in order to meet the condition of your plan. If it is impossible to reach the desired result, print -1. Input The first line contains two integers n, m (1 ≤ n ≤ 3000, <image>) — the number of cities and roads in the country, respectively. Next m lines contain the descriptions of the roads as pairs of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi). It is guaranteed that the roads that are given in the description can transport you from any city to any other one. It is guaranteed that each pair of cities has at most one road between them. The last two lines contains three integers each, s1, t1, l1 and s2, t2, l2, respectively (1 ≤ si, ti ≤ n, 0 ≤ li ≤ n). Output Print a single number — the answer to the problem. If the it is impossible to meet the conditions, print -1. Examples Input 5 4 1 2 2 3 3 4 4 5 1 3 2 3 5 2 Output 0 Input 5 4 1 2 2 3 3 4 4 5 1 3 2 2 4 2 Output 1 Input 5 4 1 2 2 3 3 4 4 5 1 3 2 3 5 1 Output -1 Submitted Solution: ``` n,m = map(int,input().strip().split()) roads = [True]*m cnt=0 Graph = dict((k+1,{}) for k in range(n)) for _ in range(m): s,t = map(int,input().strip().split()) Graph[s][t]=cnt Graph[t][s]=cnt cnt+=1 s1,t1,l1 = map(int,input().strip().split()) s2,t2,l2 = map(int,input().strip().split()) from queue import PriorityQueue def dijkstra(s,Graph,pre): dis = dict((k,float("inf")) for k in Graph) dis[s] = 0 pq = PriorityQueue() pq.put((dis[s],s)) while pq.qsize(): dist,node = pq.get() if dist!=dis[node]: continue for to in Graph[node]: if dis[to]>dis[node]+1: pre[to] = node dis[to] = dis[node]+1 pq.put((dis[to],to)) return dis pre1,pre2 = [0]*(n+1),[0]*(n+1) dis1 = dijkstra(s1,Graph,pre1) dis2 = dijkstra(s2,Graph,pre2) if dis1[t1]<=l1 and dis2[t2]<=l2: p = t1 while pre1[p]!=0: roads[Graph[p][pre1[p]]] = False p = pre1[p] p = t2 while pre2[p]!=0: roads[Graph[p][pre1[p]]] = False p = pre2[p] print(sum(roads)) else: print(-1) ``` No
89,692
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In some country there are exactly n cities and m bidirectional roads connecting the cities. Cities are numbered with integers from 1 to n. If cities a and b are connected by a road, then in an hour you can go along this road either from city a to city b, or from city b to city a. The road network is such that from any city you can get to any other one by moving along the roads. You want to destroy the largest possible number of roads in the country so that the remaining roads would allow you to get from city s1 to city t1 in at most l1 hours and get from city s2 to city t2 in at most l2 hours. Determine what maximum number of roads you need to destroy in order to meet the condition of your plan. If it is impossible to reach the desired result, print -1. Input The first line contains two integers n, m (1 ≤ n ≤ 3000, <image>) — the number of cities and roads in the country, respectively. Next m lines contain the descriptions of the roads as pairs of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi). It is guaranteed that the roads that are given in the description can transport you from any city to any other one. It is guaranteed that each pair of cities has at most one road between them. The last two lines contains three integers each, s1, t1, l1 and s2, t2, l2, respectively (1 ≤ si, ti ≤ n, 0 ≤ li ≤ n). Output Print a single number — the answer to the problem. If the it is impossible to meet the conditions, print -1. Examples Input 5 4 1 2 2 3 3 4 4 5 1 3 2 3 5 2 Output 0 Input 5 4 1 2 2 3 3 4 4 5 1 3 2 2 4 2 Output 1 Input 5 4 1 2 2 3 3 4 4 5 1 3 2 3 5 1 Output -1 Submitted Solution: ``` import queue def bfs(s,t,l,a,n,q,from_): d = [-1] * (n+1) d[s] = 0 q.put(s) while (q.empty() != True): u = q.get() for i in range(len(a[u])): if (d[a[u][i]] == -1): d[a[u][i]] = d[u] + 1 q.put(a[u][i]) from_[a[u][i]] = u return d[t] def mark_rebrs(from_,t,s): if (t != s): mark[from_[t]][t] = mark[from_[t]][t] + 1 mark[t][from_[t]] = mark[t][from_[t]] + 1 mark_rebrs(from_,from_[t],s) def count_rebrs(a,mark,count_rebers_del): for i in range(1,len(mark)): for j in range(1,len(mark[i])): if ((mark[i][j] == 1) and (i != j)): count_rebers_del = count_rebers_del + 1 mark[j][i] = 2 return count_rebers_del n,m = map(int,input().split()) q = queue.Queue() a = [ [] for i in range(n+1) ] mark = [ [0] * (n+1) for i in range(n+1) ] for i in range(m): b,f = map(int,input().split()) a[b].append(f) a[f].append(b) mark[b][f] = 1 mark[f][b] = 1 s1,t1,l1 = map(int,input().split()) s2,t2,l2 = map(int,input().split()) from_ = [-1] * (n+1) if (bfs(s1,t1,l1,a,n,q,from_) > l1): print('-1') c1 = -1 else: mark_rebrs(from_,t1,s1) from_ = [-1] * (n+1) if (bfs(s2,t2,l2,a,n,q,from_) > l2): print('-1') c1 = -1 else: count_rebers_del = 0 mark_rebrs(from_,t2,s2) count_rebers_del = count_rebrs(a,mark,count_rebers_del) print(count_rebers_del) ``` No
89,693
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In some country there are exactly n cities and m bidirectional roads connecting the cities. Cities are numbered with integers from 1 to n. If cities a and b are connected by a road, then in an hour you can go along this road either from city a to city b, or from city b to city a. The road network is such that from any city you can get to any other one by moving along the roads. You want to destroy the largest possible number of roads in the country so that the remaining roads would allow you to get from city s1 to city t1 in at most l1 hours and get from city s2 to city t2 in at most l2 hours. Determine what maximum number of roads you need to destroy in order to meet the condition of your plan. If it is impossible to reach the desired result, print -1. Input The first line contains two integers n, m (1 ≤ n ≤ 3000, <image>) — the number of cities and roads in the country, respectively. Next m lines contain the descriptions of the roads as pairs of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi). It is guaranteed that the roads that are given in the description can transport you from any city to any other one. It is guaranteed that each pair of cities has at most one road between them. The last two lines contains three integers each, s1, t1, l1 and s2, t2, l2, respectively (1 ≤ si, ti ≤ n, 0 ≤ li ≤ n). Output Print a single number — the answer to the problem. If the it is impossible to meet the conditions, print -1. Examples Input 5 4 1 2 2 3 3 4 4 5 1 3 2 3 5 2 Output 0 Input 5 4 1 2 2 3 3 4 4 5 1 3 2 2 4 2 Output 1 Input 5 4 1 2 2 3 3 4 4 5 1 3 2 3 5 1 Output -1 Submitted Solution: ``` #!/usr/bin/python3.6 # -*- coding: utf-8 -*- # @Time : 2020/11/16 8:03 PM # @Author : Songtao Li from collections import defaultdict import itertools def path_value(pre, dest0): one_path = [dest0] node = dest0 while pre[node] != -1: one_path.append(pre[node]) node = pre[node] one_path.reverse() path_part = [] start = one_path[:-1] end = one_path[1:] for i, j in zip(start, end): path_part.append((i, j)) return path_part class Graph: def __init__(self, n): self.graph = defaultdict(list) self.n = n def addEdge(self, u, v): self.graph[u].append(v) def BFS(self, source, dest, deep): graph_len = self.n + 1 visited = [False] * graph_len distance = [-1] * graph_len pre_node = [-1] * graph_len queue = [source] visited[source] = True distance[source] = 0 pathes = [] while queue and max(distance) <= deep: s = queue.pop(0) for i in self.graph[s]: if not visited[i]: distance[i] = distance[s] + 1 pre_node[i] = s queue.append(i) visited[i] = True if i == dest: pathes.append(path_value(pre_node, dest)) visited[i] = False # return distance[i], pre_node return pathes # if __name__ == "__main__": n, m = map(int, input().split()) g = Graph(n) path = [] for _ in range(m): s, t = map(int, input().split()) path.append((s, t)) g.addEdge(s, t) g.addEdge(t, s) s1, t1, l1 = map(int, input().split()) s2, t2, l2 = map(int, input().split()) if n == 3000: print(s1, t1, l1, s2, t2,l2) else: pathes1 = g.BFS(s1, t1, l1) pathes2 = g.BFS(s2, t2, l2) if len(pathes1) == 0 or len(pathes2) == 0: print(-1) else: pathes1 = [p for p in pathes1 if len(p) <= l1] pathes2 = [p for p in pathes2 if len(p) <= l2] # print(pathes1) # print(pathes2) min_len1 = min([len(p) for p in pathes1]) min_len2 = min([len(p) for p in pathes2]) if min_len1 > l1 or min_len2 > l2: print(-1) else: min_len = float("inf") for x in itertools.product(pathes1, pathes2): len_path = (len(set(x[0]) | set(x[1]))) if len_path < min_len: min_len = len_path print(m - min_len) ``` No
89,694
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In some country there are exactly n cities and m bidirectional roads connecting the cities. Cities are numbered with integers from 1 to n. If cities a and b are connected by a road, then in an hour you can go along this road either from city a to city b, or from city b to city a. The road network is such that from any city you can get to any other one by moving along the roads. You want to destroy the largest possible number of roads in the country so that the remaining roads would allow you to get from city s1 to city t1 in at most l1 hours and get from city s2 to city t2 in at most l2 hours. Determine what maximum number of roads you need to destroy in order to meet the condition of your plan. If it is impossible to reach the desired result, print -1. Input The first line contains two integers n, m (1 ≤ n ≤ 3000, <image>) — the number of cities and roads in the country, respectively. Next m lines contain the descriptions of the roads as pairs of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi). It is guaranteed that the roads that are given in the description can transport you from any city to any other one. It is guaranteed that each pair of cities has at most one road between them. The last two lines contains three integers each, s1, t1, l1 and s2, t2, l2, respectively (1 ≤ si, ti ≤ n, 0 ≤ li ≤ n). Output Print a single number — the answer to the problem. If the it is impossible to meet the conditions, print -1. Examples Input 5 4 1 2 2 3 3 4 4 5 1 3 2 3 5 2 Output 0 Input 5 4 1 2 2 3 3 4 4 5 1 3 2 2 4 2 Output 1 Input 5 4 1 2 2 3 3 4 4 5 1 3 2 3 5 1 Output -1 Submitted Solution: ``` # region My classes and methods import copy from collections import deque class Queue: def __init__(self): self.items = deque([]) self.visited = False def enqueue(self, item): self.items.append(item) def dequeue(self): if self.items: return self.items.popleft() def size(self): return len(self.items) class City: def __init__(self, number): self.name = number self.adyacents = [] def citybfs(cityQ, distances, paths): while cityQ.size() != 0: itemcity = cityQ.dequeue() for otheritemcity in itemcity.adyacents: if distances[otheritemcity.name] == -1: distances[otheritemcity.name] = distances[itemcity.name] + 1 paths[otheritemcity.name] = itemcity cityQ.enqueue(otheritemcity) def citys_to_cityt(fullpath, path, citys, cityt): if path: if cityt == citys: path.insert(0, citiesList[citys]) return path.insert(0, citiesList[cityt]) cityt = fullpath[cityt].name return citys_to_cityt(fullpath, path, citys, cityt) else: path.append(citiesList[cityt]) cityt = fullpath[cityt].name return citys_to_cityt(fullpath, path, citys, cityt) # endregion # print("Number of cities and roads:") NandM = input().split(" ") NumCities = int(NandM[0]) NumRoads = int(NandM[1]) # print("Write the ", NumRoads, " roads:") ''' This was the implementation of graphs by array, but in the end is a bit faster make a linked list of cities. GraphCity = [] for i in range(NumCities): GraphCity.append([]) for j in range(NumCities): GraphCity[i][j].append(0) for i in range(NumRoads): templist = input().split(" ") GraphCity[templist[0]][templist[1]] = 1; ''' citiesList = [] for i in range(NumCities): citiesList.append(City(i)) for i in range(NumRoads): templist = input().split(" ") if citiesList[int(templist[1]) - 1] not in citiesList[int(templist[0]) - 1].adyacents: citiesList[int(templist[0]) - 1].adyacents.append(citiesList[int(templist[1]) - 1]) if citiesList[int(templist[0]) - 1] not in citiesList[int(templist[1]) - 1].adyacents: citiesList[int(templist[1]) - 1].adyacents.append(citiesList[int(templist[0]) - 1]) # print("Introduce starting city #1, finishing city #1 and max travel time #1") stl1 = input().split(" ") citys1 = int(stl1[0]) - 1 cityt1 = int(stl1[1]) - 1 time1 = int(stl1[2]) # print("Introduce starting city #2, finishing city #2 and max travel time #2") stl2 = input().split(" ") citys2 = int(stl2[0]) - 1 cityt2 = int(stl2[1]) - 1 time2 = int(stl2[2]) firstPathVert = [] firstDistances = [] firstPath = [] for i in range(NumCities): firstDistances.append(- 1) firstPath.append(0) firstDistances[citys1] = 0 firstPath[citys1] = -1 firstQ = Queue() firstQ.enqueue(citiesList[citys1]) citybfs(firstQ, firstDistances, firstPath) # for i in range(firstPath): # if i == 0 : secondDistances = [] secondPath = [] for i in range(NumCities): secondDistances.append(-1) secondPath.append(0) secondDistances[citys2] = 0 secondPath[citys2] = -1 secondQ = Queue() secondQ.enqueue((citiesList[citys2])) citybfs(secondQ, secondDistances, secondPath) if firstDistances[cityt1] > time1 or secondDistances[cityt2] > time2: print("-1") exit(0) MultPathBeg = False firstPathbegin = False secondPathbegin = False firstPathend = False secondPathend = False fullfirst = [] fullsecond = [] citys_to_cityt(firstPath, fullfirst, citys1, cityt1) citys_to_cityt(secondPath, fullsecond, citys2, cityt2) setfirst = set(copy.copy(fullfirst)) setsecond = set(copy.copy(fullsecond)) if setfirst.isdisjoint(setsecond): print(NumRoads - len(fullfirst) - len(fullsecond)-2) exit(0) CommonPathbeg = -1 CommonPathends = -1 CommonSet = setfirst.intersection(setsecond) commonIndex = [] for i in range(len(fullfirst)): if fullfirst[i] in CommonSet: commonIndex.append(fullfirst[i]) # Finding the distances between the first common vertice and the cities DistanceFirsttoi = firstDistances[commonIndex[0].name] DistanceSecondtoi = secondDistances[commonIndex[0].name] '''' distanceFirsttoI = [] PathFirsttoI = [] for i in range(NumCities): distanceFirsttoI.append(-1) PathFirsttoI.append(0) distanceFirsttoI[citys1] = 0 PathFirsttoI[citys1] = -1 NewQ1 = Queue() NewQ1.enqueue((citiesList[citys1])) citybfs(NewQ1, distanceFirsttoI, PathFirsttoI) DistanceFirsttoi = distanceFirsttoI[commonIndex[0].name] distanceSecondtoI = [] PathSecondtoI = [] for i in range(NumCities): distanceSecondtoI.append(-1) PathSecondtoI.append(0) distanceSecondtoI[citys1] = 0 PathSecondtoI[citys1] = -1 NewQ1 = Queue() NewQ1.enqueue((citiesList[citys1])) citybfs(NewQ1, distanceSecondtoI, PathSecondtoI) DistanceSecondtoi = distanceFirsttoI[commonIndex[0].name] ''' # Finding distances between the first and the last common vertices Distanceitoj = firstDistances[commonIndex[len(commonIndex) - 1].name] - firstDistances[commonIndex[0].name] # Finding distances between the last common vertices and the last vertices FirstDistancejtolast = firstDistances[cityt1] - firstDistances[commonIndex[len(commonIndex) - 1].name] SecondDistancejtolast = secondDistances[cityt2] - secondDistances[commonIndex[len(commonIndex) - 1].name] print(abs(NumRoads - DistanceFirsttoi - DistanceSecondtoi - Distanceitoj - FirstDistancejtolast - SecondDistancejtolast)) ``` No
89,695
Provide tags and a correct Python 3 solution for this coding contest problem. You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the length of any stick. Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them. Input The single line contains 4 integers a, b, c, l (1 ≤ a, b, c ≤ 3·105, 0 ≤ l ≤ 3·105). Output Print a single integer — the number of ways to increase the sizes of the sticks by the total of at most l centimeters, so that you can make a non-degenerate triangle from it. Examples Input 1 1 1 2 Output 4 Input 1 2 3 1 Output 2 Input 10 2 1 7 Output 0 Note In the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter. In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions. Tags: combinatorics, implementation, math Correct Solution: ``` def f(a,b,c,l): if a<b+c: return 0 else: c=min(l,a-b-c) return (c+1)*(c+2)/2 a,b,c,l = map(int,input().split()) z=(l+1)*(l+2)*(l+3)/6 i=0 while i<=l: z-=f(a+i,b,c,l-i)+f(b+i,c,a,l-i)+f(c+i,a,b,l-i) i+=1 print(int(z)) ```
89,696
Provide tags and a correct Python 3 solution for this coding contest problem. You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the length of any stick. Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them. Input The single line contains 4 integers a, b, c, l (1 ≤ a, b, c ≤ 3·105, 0 ≤ l ≤ 3·105). Output Print a single integer — the number of ways to increase the sizes of the sticks by the total of at most l centimeters, so that you can make a non-degenerate triangle from it. Examples Input 1 1 1 2 Output 4 Input 1 2 3 1 Output 2 Input 10 2 1 7 Output 0 Note In the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter. In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions. Tags: combinatorics, implementation, math Correct Solution: ``` a, b, c, l = map(int, input().split()) cnt = (l + 3) * (l + 2) * (l + 1) // 3 for i in (a, b, c): s = 2 * i - a - b - c for x in range(max(0, -s), l + 1): m = min(s + x, l - x) cnt -= (m + 1) * (m + 2) print(cnt // 2) ```
89,697
Provide tags and a correct Python 3 solution for this coding contest problem. You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the length of any stick. Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them. Input The single line contains 4 integers a, b, c, l (1 ≤ a, b, c ≤ 3·105, 0 ≤ l ≤ 3·105). Output Print a single integer — the number of ways to increase the sizes of the sticks by the total of at most l centimeters, so that you can make a non-degenerate triangle from it. Examples Input 1 1 1 2 Output 4 Input 1 2 3 1 Output 2 Input 10 2 1 7 Output 0 Note In the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter. In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions. Tags: combinatorics, implementation, math Correct Solution: ``` a, b, c, d = map(int, input().split(' ')) ans = -(d+1) * (d+2) * (d+3) // 6 for l1 in range(0, d+1): minx = min(d-l1, a-b-c+l1) if minx < 0: continue; else: ans += (minx + 1) * (minx + 2) // 2 a, b, c = b, c, a for l1 in range(0, d+1): minx = min(d-l1, a-b-c+l1) if minx < 0: continue; else: ans += (minx + 1) * (minx + 2) // 2 a, b, c = b, c, a for l1 in range(0, d+1): minx = min(d-l1, a-b-c+l1) if minx < 0: continue; else: ans += (minx + 1) * (minx + 2) // 2 print(-ans) ```
89,698
Provide tags and a correct Python 3 solution for this coding contest problem. You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the length of any stick. Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them. Input The single line contains 4 integers a, b, c, l (1 ≤ a, b, c ≤ 3·105, 0 ≤ l ≤ 3·105). Output Print a single integer — the number of ways to increase the sizes of the sticks by the total of at most l centimeters, so that you can make a non-degenerate triangle from it. Examples Input 1 1 1 2 Output 4 Input 1 2 3 1 Output 2 Input 10 2 1 7 Output 0 Note In the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter. In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions. Tags: combinatorics, implementation, math Correct Solution: ``` __author__ = 'nobik' def count(a, b, c, x): if (a < b + c): return 0 value = min(x, a - b - c) return (value + 1) * (value + 2) // 2 a, b, c, l = map(int, input().split()) ans = (l + 1) * (l + 2) * (l + 3) // 6 for i in range(l + 1): ans -= count(a + i, b, c, l - i) ans -= count(b + i, a, c, l - i) ans -= count(c + i, a, b, l - i) print(ans) ```
89,699