text
stringlengths
198
433k
conversation_id
int64
0
109k
Provide tags and a correct Python 3 solution for this coding contest problem. Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles. Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle. Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number. Input The first line contains integer n (1 ≤ n ≤ 100) — the number of bottles. The next n lines contain the bottles' description. The i-th line contains two integers ai, bi (1 ≤ ai, bi ≤ 1000) — the description of the i-th bottle. Output In a single line print a single integer — the answer to the problem. Examples Input 4 1 1 2 2 3 3 4 4 Output 4 Input 4 1 2 2 3 3 4 4 1 Output 0 Tags: brute force Correct Solution: ``` n=int(input()) l=[list(map(int,input().split())) for i in range(n)] c=0 for i in range(n): temp=0 for j in range(n): if l[i][0]==l[j][1] and i!=j:temp+=1 if temp==0:c+=1 print(c) ```
94,700
Provide tags and a correct Python 3 solution for this coding contest problem. Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles. Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle. Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number. Input The first line contains integer n (1 ≤ n ≤ 100) — the number of bottles. The next n lines contain the bottles' description. The i-th line contains two integers ai, bi (1 ≤ ai, bi ≤ 1000) — the description of the i-th bottle. Output In a single line print a single integer — the answer to the problem. Examples Input 4 1 1 2 2 3 3 4 4 Output 4 Input 4 1 2 2 3 3 4 4 1 Output 0 Tags: brute force Correct Solution: ``` import sys from functools import reduce from collections import Counter import time import datetime from math import sqrt,gcd # def time_t(): # print("Current date and time: " , datetime.datetime.now()) # print("Current year: ", datetime.date.today().strftime("%Y")) # print("Month of year: ", datetime.date.today().strftime("%B")) # print("Week number of the year: ", datetime.date.today().strftime("%W")) # print("Weekday of the week: ", datetime.date.today().strftime("%w")) # print("Day of year: ", datetime.date.today().strftime("%j")) # print("Day of the month : ", datetime.date.today().strftime("%d")) # print("Day of week: ", datetime.date.today().strftime("%A")) def ip(): return int(sys.stdin.readline()) def sip(): return sys.stdin.readline() def mip(): return map(int,sys.stdin.readline().split()) def mips(): return map(str,sys.stdin.readline().split()) def lip(): return list(map(int,sys.stdin.readline().split())) def matip(n,m): lst=[] for i in range(n): arr = lip() lst.append(arr) return lst def factors(n): # find the factors of a number return list(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))) def minJumps(arr, n): #to reach from 0 to n-1 in the array in minimum steps jumps = [0 for i in range(n)] if (n == 0) or (arr[0] == 0): return float('inf') jumps[0] = 0 for i in range(1, n): jumps[i] = float('inf') for j in range(i): if (i <= j + arr[j]) and (jumps[j] != float('inf')): jumps[i] = min(jumps[i], jumps[j] + 1) break return jumps[n-1] def dic(arr): # converting list into dict of count return Counter(arr) def check_prime(n): if n<2: return False for i in range(2,int(n**(0.5))+1,2): if n%i==0: return False return True # --------------------------------------------------------- # # sys.stdin = open('input.txt','r') # sys.stdout = open('output.txt','w') # --------------------------------------------------------- # t = ip() bottles = [] opened = [] count = 0 for _ in range(t): a,b = mip() bottles.append(a) opened.append(b) for i in range(t): if bottles[i] not in opened[:i]: if bottles[i] not in opened[i+1:]: count+=1 print(count) ```
94,701
Provide tags and a correct Python 3 solution for this coding contest problem. Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles. Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle. Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number. Input The first line contains integer n (1 ≤ n ≤ 100) — the number of bottles. The next n lines contain the bottles' description. The i-th line contains two integers ai, bi (1 ≤ ai, bi ≤ 1000) — the description of the i-th bottle. Output In a single line print a single integer — the answer to the problem. Examples Input 4 1 1 2 2 3 3 4 4 Output 4 Input 4 1 2 2 3 3 4 4 1 Output 0 Tags: brute force Correct Solution: ``` import re in1 = int(input()) count = 0 bto = [] bco = [] conA = [] conB = [] for _ in range(in1): inX = [int(x) for x in re.split("\\s", input())] if inX[0] != inX[1]: bto.append(inX[0]) bco.append(inX[1]) else: if inX[0] not in conA: conA.append(inX[1]) else: conB.append(inX[1]) for x in conA: if x not in conB and x not in bco: count += 1 for x in bto: if x not in bco and x not in conA: count += 1 print(count) ```
94,702
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles. Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle. Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number. Input The first line contains integer n (1 ≤ n ≤ 100) — the number of bottles. The next n lines contain the bottles' description. The i-th line contains two integers ai, bi (1 ≤ ai, bi ≤ 1000) — the description of the i-th bottle. Output In a single line print a single integer — the answer to the problem. Examples Input 4 1 1 2 2 3 3 4 4 Output 4 Input 4 1 2 2 3 3 4 4 1 Output 0 Submitted Solution: ``` """ Author: Sagar Pandey """ # ---------------------------------------------------Import Libraries--------------------------------------------------- import sys import time import os from math import sqrt, log, log2, ceil, log10, gcd, floor, pow, sin, cos, tan, pi, inf, factorial from copy import copy, deepcopy from sys import exit, stdin, stdout from collections import Counter, defaultdict, deque from itertools import permutations import heapq from bisect import bisect_left as bl # If the element is already present in the list, # the left most position where element has to be inserted is returned. from bisect import bisect_right as br from bisect import bisect # If the element is already present in the list, # the right most position where element has to be inserted is r # ---------------------------------------------------Global Variables--------------------------------------------------- # sys.setrecursionlimit(100000000) mod = 1000000007 # ---------------------------------------------------Helper Functions--------------------------------------------------- iinp = lambda: int(sys.stdin.readline()) inp = lambda: sys.stdin.readline().strip() strl = lambda: list(inp().strip().split(" ")) intl = lambda: list(map(int, inp().split(" "))) mint = lambda: map(int, inp().split()) flol = lambda: list(map(float, inp().split(" "))) flush = lambda: stdout.flush() def permute(nums): def fun(arr, nums, cur, v): if len(cur) == len(nums): arr.append(cur.copy()) i = 0 while i < len(nums): if v[i]: i += 1 continue else: cur.append(nums[i]) v[i] = 1 fun(arr, nums, cur, v) cur.pop() v[i] = 0 i += 1 # while i<len(nums) and nums[i]==nums[i-1]:i+=1 # Uncomment for unique permutations return arr res = [] nums.sort() v = [0] * len(nums) return fun(res, nums, [], v) def subsets(res, index, arr, cur): res.append(cur.copy()) for i in range(index, len(arr)): cur.append(arr[i]) subsets(res, i + 1, arr, cur) cur.pop() return res def sieve(N): root = int(sqrt(N)) primes = [1] * (N + 1) primes[0], primes[1] = 0, 0 for i in range(2, root + 1): if primes[i]: for j in range(i * i, N + 1, i): primes[j] = 0 return primes def bs(arr, l, r, x): if x < arr[0] or x > arr[len(arr) - 1]: return -1 while l <= r: mid = l + (r - l) // 2 if arr[mid] == x: return mid elif arr[mid] < x: l = mid + 1 else: r = mid - 1 return -1 def isPrime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False p = int(sqrt(n)) for i in range(5, p + 1, 6): if n % i == 0 or n % (i + 2) == 0: return False return True # -------------------------------------------------------Functions------------------------------------------------------ def solve(): n=iinp() a=[] for i in range(n): a.append(intl()) ans=0 for i in range(n): f=False for j in range(n): if i==j: continue else: if a[i][0]==a[j][1]: f=True if f: ans+=1 print(n-ans) # -------------------------------------------------------Main Code------------------------------------------------------ start_time = time.time() # for _ in range(iinp()): solve() # print("--- %s seconds ---" % (time.time() - start_time)) ``` Yes
94,703
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles. Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle. Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number. Input The first line contains integer n (1 ≤ n ≤ 100) — the number of bottles. The next n lines contain the bottles' description. The i-th line contains two integers ai, bi (1 ≤ ai, bi ≤ 1000) — the description of the i-th bottle. Output In a single line print a single integer — the answer to the problem. Examples Input 4 1 1 2 2 3 3 4 4 Output 4 Input 4 1 2 2 3 3 4 4 1 Output 0 Submitted Solution: ``` n = int(input()) e = 0 a = [] b = [ [] for i in range(1001) ] for i in range(n): s,t = map(int,input().split()) a.append([i,s]) b[t].append(i) for i in range(len(a)): c1 = 0 for j in range(len(b[a[i][1]])): if (b[a[i][1]][j] != i): c1 = -1 if (c1 != -1): e = e + 1 print(e) ``` Yes
94,704
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles. Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle. Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number. Input The first line contains integer n (1 ≤ n ≤ 100) — the number of bottles. The next n lines contain the bottles' description. The i-th line contains two integers ai, bi (1 ≤ ai, bi ≤ 1000) — the description of the i-th bottle. Output In a single line print a single integer — the answer to the problem. Examples Input 4 1 1 2 2 3 3 4 4 Output 4 Input 4 1 2 2 3 3 4 4 1 Output 0 Submitted Solution: ``` #Problem Set D: Collaborated with no one n = int(input()) size = n+1 bottle_num = [0]*size left_arr = [] right_arr = [] for i in range(n): ab_list = list(map(int, input().split())) if len(left_arr) == 0: left_arr.append(0) if len(right_arr) == 0: right_arr.append(0) left_arr.append(ab_list[0]) right_arr.append(ab_list[1]) for j in range(1,n+1): for k in range(1,n+1): if (j != k) and (left_arr[j] == right_arr[k]): bottle_num[j] = 1 total = 0 for i in range(1,n+1): total += bottle_num[i] print(n-total) ``` Yes
94,705
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles. Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle. Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number. Input The first line contains integer n (1 ≤ n ≤ 100) — the number of bottles. The next n lines contain the bottles' description. The i-th line contains two integers ai, bi (1 ≤ ai, bi ≤ 1000) — the description of the i-th bottle. Output In a single line print a single integer — the answer to the problem. Examples Input 4 1 1 2 2 3 3 4 4 Output 4 Input 4 1 2 2 3 3 4 4 1 Output 0 Submitted Solution: ``` n = int(input()) a = [0] * n b = [0] * n ans = 0 for i in range(n): a[i], b[i] = map(int, input().split()) for i in range(n): for j in range(n): if i != j and b[j] == a[i]: break else: ans += 1 print(ans) ``` Yes
94,706
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles. Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle. Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number. Input The first line contains integer n (1 ≤ n ≤ 100) — the number of bottles. The next n lines contain the bottles' description. The i-th line contains two integers ai, bi (1 ≤ ai, bi ≤ 1000) — the description of the i-th bottle. Output In a single line print a single integer — the answer to the problem. Examples Input 4 1 1 2 2 3 3 4 4 Output 4 Input 4 1 2 2 3 3 4 4 1 Output 0 Submitted Solution: ``` n = int(input()) d = {} for i in range(n): a, b = map(int, input().split()) if a not in d: d[a] = [1, 0] else: d[a][0] += 1 if b != a: if not b in d: d[b] = [1, 1] elif d[b][1] == 0: d[b][1] = 1 else: d[b] = [1, 0] ans = 0 for i in d: if d[i][1] == 0: ans += d[i][0] print(ans) ``` No
94,707
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles. Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle. Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number. Input The first line contains integer n (1 ≤ n ≤ 100) — the number of bottles. The next n lines contain the bottles' description. The i-th line contains two integers ai, bi (1 ≤ ai, bi ≤ 1000) — the description of the i-th bottle. Output In a single line print a single integer — the answer to the problem. Examples Input 4 1 1 2 2 3 3 4 4 Output 4 Input 4 1 2 2 3 3 4 4 1 Output 0 Submitted Solution: ``` n = int(input()) al = [] bl = [] for i in range(n): a, b = [int(x) for x in input().split()] al.append(a) if a != b: bl.append(b) else: bl.append(-1) count = 0 for bot in al: if bot in bl: count+=1 print(n-count) ``` No
94,708
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles. Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle. Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number. Input The first line contains integer n (1 ≤ n ≤ 100) — the number of bottles. The next n lines contain the bottles' description. The i-th line contains two integers ai, bi (1 ≤ ai, bi ≤ 1000) — the description of the i-th bottle. Output In a single line print a single integer — the answer to the problem. Examples Input 4 1 1 2 2 3 3 4 4 Output 4 Input 4 1 2 2 3 3 4 4 1 Output 0 Submitted Solution: ``` n = int(input()) matrix = [] count = 0 for _ in range(n): l, r = map(int, input().split()) if l == r: count += 1 print(count) ``` No
94,709
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles. Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle. Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number. Input The first line contains integer n (1 ≤ n ≤ 100) — the number of bottles. The next n lines contain the bottles' description. The i-th line contains two integers ai, bi (1 ≤ ai, bi ≤ 1000) — the description of the i-th bottle. Output In a single line print a single integer — the answer to the problem. Examples Input 4 1 1 2 2 3 3 4 4 Output 4 Input 4 1 2 2 3 3 4 4 1 Output 0 Submitted Solution: ``` n=int(input()) a=[] b=[] for x in range(0,n): l=list(map(int,input().split(" "))) a.append(l) b.append(l[0]) c=0 for x,y in a: if x==y: c+=1 elif y in b: pass else: c+=1 print(c) ``` No
94,710
Provide tags and a correct Python 3 solution for this coding contest problem. Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero. Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (109 + 9). Input The single line contains three space-separated integers n, m and k (2 ≤ k ≤ n ≤ 109; 0 ≤ m ≤ n). Output Print a single integer — the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (109 + 9). Examples Input 5 3 2 Output 3 Input 5 4 2 Output 6 Note Sample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points. Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4. Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000 mod 1000000009, even though 2000000020 mod 1000000009 is a smaller number. Tags: binary search, greedy, math, matrices, number theory Correct Solution: ``` n, m, k = map(int, input().split()) x, c, ic, ans, mod = min(m//(k-1), n-m), m, n-m, 0, 10**9 + 9 c = c - (k-1)*x p, r = c//k, c%k ans = ((((pow(2, p+1, mod) - 2 + mod)%mod) * (k%mod))%mod + (k-1)*x + r)%mod print(ans) ```
94,711
Provide tags and a correct Python 3 solution for this coding contest problem. Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero. Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (109 + 9). Input The single line contains three space-separated integers n, m and k (2 ≤ k ≤ n ≤ 109; 0 ≤ m ≤ n). Output Print a single integer — the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (109 + 9). Examples Input 5 3 2 Output 3 Input 5 4 2 Output 6 Note Sample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points. Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4. Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000 mod 1000000009, even though 2000000020 mod 1000000009 is a smaller number. Tags: binary search, greedy, math, matrices, number theory Correct Solution: ``` z = 10**9+9 n,m,k = map(int,input().split()) i = n-m x = (n-k+1)//k if k*i>=n-k+1: print((n-i)%z) else: l = n-k+1 f = l-(i-1)*k-1 t = f//k f = t*k v = 2*(pow(2,t,z)-1)*k+(n-f-i) print(v%z) ```
94,712
Provide tags and a correct Python 3 solution for this coding contest problem. Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero. Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (109 + 9). Input The single line contains three space-separated integers n, m and k (2 ≤ k ≤ n ≤ 109; 0 ≤ m ≤ n). Output Print a single integer — the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (109 + 9). Examples Input 5 3 2 Output 3 Input 5 4 2 Output 6 Note Sample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points. Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4. Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000 mod 1000000009, even though 2000000020 mod 1000000009 is a smaller number. Tags: binary search, greedy, math, matrices, number theory Correct Solution: ``` n, corecte, k = map(int, input().split()) incorecte = n - corecte mod = 10**9 + 9 corecte_consecutive = max(0, n - incorecte * k) dublari = corecte_consecutive // k corecte_ramase = corecte - corecte_consecutive def power(b, exp): if exp == 0: return 1 half = power(b, exp//2) if exp%2 == 0: return (half*half) % mod return (half*half*b) % mod score = (power(2, dublari+1) - 2) * k + corecte_ramase + corecte_consecutive % k print(score % mod) ```
94,713
Provide tags and a correct Python 3 solution for this coding contest problem. Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero. Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (109 + 9). Input The single line contains three space-separated integers n, m and k (2 ≤ k ≤ n ≤ 109; 0 ≤ m ≤ n). Output Print a single integer — the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (109 + 9). Examples Input 5 3 2 Output 3 Input 5 4 2 Output 6 Note Sample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points. Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4. Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000 mod 1000000009, even though 2000000020 mod 1000000009 is a smaller number. Tags: binary search, greedy, math, matrices, number theory Correct Solution: ``` n,m,k = map(int,input().split()) chunks = n//k freespots = chunks*(k-1) + n%k if m <= freespots: print(m) else: doubles = m-freespots dchunks = doubles chunks -= dchunks total = (pow(2,dchunks,1000000009)-1)*k*2 total += n%k + chunks*(k-1) print(total%1000000009) ```
94,714
Provide tags and a correct Python 3 solution for this coding contest problem. Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero. Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (109 + 9). Input The single line contains three space-separated integers n, m and k (2 ≤ k ≤ n ≤ 109; 0 ≤ m ≤ n). Output Print a single integer — the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (109 + 9). Examples Input 5 3 2 Output 3 Input 5 4 2 Output 6 Note Sample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points. Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4. Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000 mod 1000000009, even though 2000000020 mod 1000000009 is a smaller number. Tags: binary search, greedy, math, matrices, number theory Correct Solution: ``` n,m,k=map(int,input().split()) mod=10**9+9 c=m inc=n-m rep=n//k if rep<=inc: print(c) else: rem_c=m-(k-1)*inc score=(k-1)*inc rep2=rem_c//k score+=(pow(2,rep2+1,mod)-2)*k rem_c-=rep2*k score+=rem_c print(score%mod) ```
94,715
Provide tags and a correct Python 3 solution for this coding contest problem. Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero. Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (109 + 9). Input The single line contains three space-separated integers n, m and k (2 ≤ k ≤ n ≤ 109; 0 ≤ m ≤ n). Output Print a single integer — the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (109 + 9). Examples Input 5 3 2 Output 3 Input 5 4 2 Output 6 Note Sample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points. Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4. Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000 mod 1000000009, even though 2000000020 mod 1000000009 is a smaller number. Tags: binary search, greedy, math, matrices, number theory Correct Solution: ``` b = 10**9 + 9 def f(q): x = q//1000 y = q%1000 num = 2**1000 % b res = 1 for i in range(x): res = (res * num) % b res = (res * 2**y) %b return res def F(n,m,k): r = n%k if m <= n//k * (k-1) + r : print(m%b) else: q = m - (n//k * (k-1) + r) print((m + (f(q+1)-q-2)*k)%b) n,m,k = [int(x) for x in input().split(' ')] F(n,m,k) ```
94,716
Provide tags and a correct Python 3 solution for this coding contest problem. Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero. Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (109 + 9). Input The single line contains three space-separated integers n, m and k (2 ≤ k ≤ n ≤ 109; 0 ≤ m ≤ n). Output Print a single integer — the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (109 + 9). Examples Input 5 3 2 Output 3 Input 5 4 2 Output 6 Note Sample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points. Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4. Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000 mod 1000000009, even though 2000000020 mod 1000000009 is a smaller number. Tags: binary search, greedy, math, matrices, number theory Correct Solution: ``` global MOD MOD = int(1e9+9) def pow(m, n): ans = 1 while(n): if n & 1: ans = (ans*m) % MOD m = (m*m) % MOD n >>= 1 return ans def quiz(n, m, k): numk = n//k; # Divido mi problema en k pedazos # Primer Problema if numk*(k-1) >= m: # Si puedo efectuar al menos x * (k-1) respuestas correctas return m; # retorno mi m que sera la cantidad de veces a cada k intentos que hago una respuesta correcta rest_n = n-k*numk; # Analizo mi problema restante que seria n - k*numk(este es la cantidad de problemas q fueron analizados, es decir la cantidad de respuestas correctas que pude responder utilizando intentos a cada k intervalos) rest_m = m-numk*(k-1); # analizo la cantidad de intentos que me quedan por efectuar, m - numk*(k-1), siendo num*(k-1) la cantidad de intentos realizados en el pedazo que se estaba analizando anteriormente, es decir m pedazos de tamanno k, donde se falla al menos 1 vez en cada caso para no llegar al valor de k # Segundo Problema if rest_m <= rest_n: # Si la cantidad de intentos que me queda es menor o igual que la cantidad de preguntas correctos que puedo hacer, entonces hago esta ultima pregunta correcta return (numk*(k-1)+rest_m)%MOD; # y devuelvo la cantidad de puntos obtenidos en las numk*(k-1) veces q respondi bien y le sumo la cantidad de preguntas que me faltaban, tal que sumando estas preguntas no llego a k # Tercer Problema t = rest_m-rest_n; # Buscando diferencia de cantidad de aciertos restantes por efectuar con cantidad de aciertos restantes disponibles num = rest_n+t*k; # Si a la cantidad de aciertos restantes disponibles restantes le sumamos la cantidad de aciertos que necesitamos que no se han podido efectuar hasta el momento multiplicada por k obtenemos ans = (numk-t)*(k-1)%MOD; # Sumando a ans valores que no pertenecen a los k grupos(los que pertenecen a los k-1) (al hacer soluciones del final(grupo de tamanno menor q k) + soluciones que pertenecen a los k-1 grupos pero q la cantidad de respuestas correctas no es igual a k + grupos del comienzo los cuales la cantidad de aciertos es igual a k ) numk = num//k; ans = (ans+num-numk*k)%MOD; # Sumando a ans valores que pertenecen a los k-1 grupos que no contienen k aciertos return (m - numk*k + ((pow(2, numk+1) - 2) * k))%MOD #ans = ans + 2*(k*(pow(2 , numk)-1))%MOD; # Sumando a ans valores que pertenecen a los k-1 grupos que contienen k aciertos, estos seran los puntos que se duplicaran #return ans%MOD; n, m, k = map(int, input().split()) print(quiz(n, m, k)) # linea 30 # A la cantidad de grupos de tamanno k que pueden formarse le restamos t, que seran la cantidad de grupos con al menos k-1 aciertos que se sumaran a la respuesta con unvalor de cantidad necesaria de estos grupos * k-1 # esto podra hacerse ya que al quedarnos t intentos que tenemos que efectuar correctamente, podemos asumir que los mismos se podran ubicar en los primeros x grupos de k respuestas correctas consecutivas , luego restamos la cantidad de respuestas que se exceden a la cantidad de grupos posibles de k intentos correctos y nos queda la cantidad de grupos que podrian tener k aciertos # como nos interesan la cantidad de grupos que pueden tener k-1 aciertos multiplicamos esta resta anterior por k-1, obteniendo asi aquellos grupos que lenan exactamente k-1 aciertos correctamente # este numero se lo sumamos a la cantidad total ```
94,717
Provide tags and a correct Python 3 solution for this coding contest problem. Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero. Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (109 + 9). Input The single line contains three space-separated integers n, m and k (2 ≤ k ≤ n ≤ 109; 0 ≤ m ≤ n). Output Print a single integer — the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (109 + 9). Examples Input 5 3 2 Output 3 Input 5 4 2 Output 6 Note Sample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points. Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4. Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000 mod 1000000009, even though 2000000020 mod 1000000009 is a smaller number. Tags: binary search, greedy, math, matrices, number theory Correct Solution: ``` global MOD MOD = int(1e9+9) def pow(m, n): ans = 1 while(n): if n & 1: ans = (ans*m) % MOD m = (m*m) % MOD n >>= 1 return ans def getAns(n, m, k): numk = n//k; # Divido mi problema en k pedazos # first judgment if numk*(k-1) >= m: # Si puedo efectuar al menos x * (k-1) respuestas correctas return m; # retorno mi m que sera la cantidad de veces a cada k intentos que hago una respuesta correcta rest_n = n-k*numk; # Analizo mi problema restante que seria n - k*numk(este es la cantidad de problemas q fueron analizados, es decir la cantidad de respuestas correctas que pude responder utilizando intentos a cada k intervalos) rest_m = m-numk*(k-1); # analizo la cantidad de intentos que me quedan por efectuar, m - numk*(k-1), siendo num*(k-1) la cantidad de intentos realizados en el pedazo que se estaba analizando anteriormente, es decir m pedazos de tamanno k, donde se falla al menos 1 vez en cada caso para no llegar al valor de k # second judgment if rest_m <= rest_n: # Si la cantidad de intentos que me queda es menor o igual que la cantidad de preguntas correctos que puedo hacer, entonces hago esta ultima pregunta correcta return (numk*(k-1)+rest_m)%MOD; # y devuelvo la cantidad de puntos obtenidos en las numk*(k-1) veces q respondi bien y le sumo la cantidad de preguntas que me faltaban, tal que sumando estas preguntas no llego a k # Third judgment t = rest_m-rest_n; num = rest_n+t*k; ans = (numk-t)*(k-1)%MOD; numk = num//k; ans = (ans+num-numk*k)%MOD; ans = ans + 2*(k*(pow(2 , numk)-1))%MOD; return ans%MOD; n, m, k = map(int, input().split()) print(getAns(n, m, k)) ```
94,718
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero. Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (109 + 9). Input The single line contains three space-separated integers n, m and k (2 ≤ k ≤ n ≤ 109; 0 ≤ m ≤ n). Output Print a single integer — the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (109 + 9). Examples Input 5 3 2 Output 3 Input 5 4 2 Output 6 Note Sample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points. Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4. Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000 mod 1000000009, even though 2000000020 mod 1000000009 is a smaller number. Submitted Solution: ``` from __future__ import division, print_function import os import sys from io import BytesIO, IOBase def main(): n, m, k = [ int(x) for x in input().split() ] mod = 1000000009 availablePositions = (k - 1) * (n // k) + n % k if availablePositions >= m: points = m else: positionsLeft = m - availablePositions points = ( ((pow(2, positionsLeft + 1, mod) - 2) * k) % mod + (m - k * positionsLeft) % mod ) % mod print(points) 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() ``` Yes
94,719
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero. Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (109 + 9). Input The single line contains three space-separated integers n, m and k (2 ≤ k ≤ n ≤ 109; 0 ≤ m ≤ n). Output Print a single integer — the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (109 + 9). Examples Input 5 3 2 Output 3 Input 5 4 2 Output 6 Note Sample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points. Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4. Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000 mod 1000000009, even though 2000000020 mod 1000000009 is a smaller number. Submitted Solution: ``` ###### ### ####### ####### ## # ##### ### ##### # # # # # # # # # # # # # ### # # # # # # # # # # # # # ### ###### ######### # # # # # # ######### # ###### ######### # # # # # # ######### # # # # # # # # # # # #### # # # # # # # # # # ## # # # # # ###### # # ####### ####### # # ##### # # # # # mandatory imports import os import sys from io import BytesIO, IOBase from math import log2, ceil, sqrt, gcd, log # optional imports # from itertools import permutations # from functools import cmp_to_key # for adding custom comparator # from fractions import Fraction from collections import * from bisect import * # from __future__ import print_function # for PyPy2 # from heapq import * 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") g = lambda : input().strip() gl = lambda : g().split() gil = lambda : [int(var) for var in gl()] gfl = lambda : [float(var) for var in gl()] gcl = lambda : list(g()) gbs = lambda : [int(var) for var in g()] rr = lambda x : reversed(range(x)) mod = int(1e9)+7 inf = float("inf") mod = int(1e9 + 9) n, m, k = gil() ans = min(n%k, m)%mod m -= min(m, n%k) n -= n%k if m: l = n//k dbl = max(0, m - (l*(k-1))) if dbl : delta = (pow(2, dbl+1, mod) + mod - 2)%mod delta *= k delta %= mod ans += delta ans %= mod l -= dbl ans += (m - dbl*k)%mod print(ans%mod) ``` Yes
94,720
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero. Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (109 + 9). Input The single line contains three space-separated integers n, m and k (2 ≤ k ≤ n ≤ 109; 0 ≤ m ≤ n). Output Print a single integer — the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (109 + 9). Examples Input 5 3 2 Output 3 Input 5 4 2 Output 6 Note Sample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points. Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4. Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000 mod 1000000009, even though 2000000020 mod 1000000009 is a smaller number. Submitted Solution: ``` n, m, k = map(int, input().split()) if (n - m) >= n//k: print (m) else: longest_correct_streak = n - k*(n - m) p = longest_correct_streak//k print ((k*(pow(2, p+1, 1000000009) - 2) + (longest_correct_streak % k) + (n - m)*(k - 1)) % 1000000009) ``` Yes
94,721
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero. Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (109 + 9). Input The single line contains three space-separated integers n, m and k (2 ≤ k ≤ n ≤ 109; 0 ≤ m ≤ n). Output Print a single integer — the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (109 + 9). Examples Input 5 3 2 Output 3 Input 5 4 2 Output 6 Note Sample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points. Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4. Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000 mod 1000000009, even though 2000000020 mod 1000000009 is a smaller number. Submitted Solution: ``` import sys from math import * def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return map(int, minp().split()) def add(a,b): return (a+b)%1000000009 def sub(a,b): return (a-(b%1000000009)+1000000009)%1000000009 def mul(a,b): return (a*b)%1000000009 def qpow(a,n): k = a r = 1 for i in range(32): if n & (1<<i): r = mul(r,k) k = mul(k,k) return r n, m, k = mints() c = (n+1)//k z = c*(k-1) if n-c*k >= 0: z += n-c*k d = 0 if z < m: d = m-z else: print(m) exit(0) s = mul(k,mul(2, sub(qpow(2, d), 1))) #print(c,d,z,s) s = sub(add(s, z),mul(d,(k-1))) print(s) ``` Yes
94,722
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero. Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (109 + 9). Input The single line contains three space-separated integers n, m and k (2 ≤ k ≤ n ≤ 109; 0 ≤ m ≤ n). Output Print a single integer — the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (109 + 9). Examples Input 5 3 2 Output 3 Input 5 4 2 Output 6 Note Sample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points. Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4. Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000 mod 1000000009, even though 2000000020 mod 1000000009 is a smaller number. Submitted Solution: ``` n, corecte, k = map(int, input().split()) incorecte = n - corecte mod = 10**9 + 9 corecte_consecutive = max(0, n - incorecte * k) dublari = corecte_consecutive // k corecte_ramase = corecte - corecte_consecutive #print("dublari = %i" % dublari) score = 0 #for i in range(0, dublari): # score += k # score *= 2 # score %= mod def power(b, exp): if exp == 0: return 1 half = power(b, exp//2) if exp % 2 == 0: return (half*half) else: return (half*half*b) score = power(2, dublari) + 1 score = ~score score *= k #print("scor chiar dupa dublari = %i" % score) #print("corecte_consecutive = %i" % corecte_consecutive) #print("dublari = %i" % dublari) #print("corecte_ramase = %i" % corecte_ramase) score += corecte_ramase score += corecte_consecutive % k score = -score print(score % mod) """ sirul trebuie structurat asa: RRRRRRRRRRRR WRRRRR WRRRRR WRRRRR WRRRRR """ ``` No
94,723
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero. Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (109 + 9). Input The single line contains three space-separated integers n, m and k (2 ≤ k ≤ n ≤ 109; 0 ≤ m ≤ n). Output Print a single integer — the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (109 + 9). Examples Input 5 3 2 Output 3 Input 5 4 2 Output 6 Note Sample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points. Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4. Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000 mod 1000000009, even though 2000000020 mod 1000000009 is a smaller number. Submitted Solution: ``` def game(n,m,k): dp=[0]*(n) for i in range(0,n,2): dp[i]=1 while dp.count(1)<m: for i in range(len(dp)): if dp[i]==0: dp[i]=1 if dp.count(i)==m: break score=0 curr=0 for i in dp: if i==1: curr+=1 score+=1 if curr==k: score*=2 curr=0 if i==0: curr=0 return score%(10**9+9) a,b,c=map(int,input().strip().split()) print(game(a,b,c)) ``` No
94,724
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero. Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (109 + 9). Input The single line contains three space-separated integers n, m and k (2 ≤ k ≤ n ≤ 109; 0 ≤ m ≤ n). Output Print a single integer — the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (109 + 9). Examples Input 5 3 2 Output 3 Input 5 4 2 Output 6 Note Sample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points. Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4. Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000 mod 1000000009, even though 2000000020 mod 1000000009 is a smaller number. Submitted Solution: ``` from sys import stdin mod = 1000000009 def find(k, ak): return ((((4*pow(2, ak, mod))%mod - (4 + 2*ak)%mod + mod)%mod)*k)%mod n, m, k = map(int, stdin.readline().split()) w = min(n//k, n-m) ak = n//k - w print((find(k, ak) + m - k*ak)%mod) ``` No
94,725
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero. Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (109 + 9). Input The single line contains three space-separated integers n, m and k (2 ≤ k ≤ n ≤ 109; 0 ≤ m ≤ n). Output Print a single integer — the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (109 + 9). Examples Input 5 3 2 Output 3 Input 5 4 2 Output 6 Note Sample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points. Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4. Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000 mod 1000000009, even though 2000000020 mod 1000000009 is a smaller number. Submitted Solution: ``` z = 10**9+9 n,m,k = map(int,input().split()) i = n-m x = (n-k+1)//k if i>=x: print((n-i)%z) else: l = n-k+1 f = l-(i-1)*k-1 t = f//k f = t*k v = 2*(pow(2,t,z)-1)*k+(n-f-i) print(v%z) ``` No
94,726
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. No Great Victory anniversary in Berland has ever passed without the war parade. This year is not an exception. That’s why the preparations are on in full strength. Tanks are building a line, artillery mounts are ready to fire, soldiers are marching on the main square... And the air forces general Mr. Generalov is in trouble again. This year a lot of sky-scrapers have been built which makes it difficult for the airplanes to fly above the city. It was decided that the planes should fly strictly from south to north. Moreover, there must be no sky scraper on a plane’s route, otherwise the anniversary will become a tragedy. The Ministry of Building gave the data on n sky scrapers (the rest of the buildings are rather small and will not be a problem to the planes). When looking at the city from south to north as a geometrical plane, the i-th building is a rectangle of height hi. Its westernmost point has the x-coordinate of li and the easternmost — of ri. The terrain of the area is plain so that all the buildings stand on one level. Your task as the Ministry of Defence’s head programmer is to find an enveloping polyline using the data on the sky-scrapers. The polyline’s properties are as follows: * If you look at the city from south to north as a plane, then any part of any building will be inside or on the boarder of the area that the polyline encloses together with the land surface. * The polyline starts and ends on the land level, i.e. at the height equal to 0. * The segments of the polyline are parallel to the coordinate axes, i.e. they can only be vertical or horizontal. * The polyline’s vertices should have integer coordinates. * If you look at the city from south to north the polyline (together with the land surface) must enclose the minimum possible area. * The polyline must have the smallest length among all the polylines, enclosing the minimum possible area with the land. * The consecutive segments of the polyline must be perpendicular. <image> Picture to the second sample test (the enveloping polyline is marked on the right). Input The first input line contains integer n (1 ≤ n ≤ 100000). Then follow n lines, each containing three integers hi, li, ri (1 ≤ hi ≤ 109, - 109 ≤ li < ri ≤ 109). Output In the first line output integer m — amount of vertices of the enveloping polyline. The next m lines should contain 2 integers each — the position and the height of the polyline’s vertex. Output the coordinates of each vertex in the order of traversing the polyline from west to east. Remember that the first and the last vertices of the polyline should have the height of 0. Examples Input 2 3 0 2 4 1 3 Output 6 0 0 0 3 1 3 1 4 3 4 3 0 Input 5 3 -3 0 2 -1 1 4 2 4 2 3 7 3 6 8 Output 14 -3 0 -3 3 0 3 0 2 1 2 1 0 2 0 2 4 4 4 4 2 6 2 6 3 8 3 8 0 Submitted Solution: ``` import sys from array import array # noqa: F401 from collections import defaultdict from heapq import heappop, heappush def input(): with open('input.txt') as fp: return fp.readlines() def output(ans: str): with open('output.txt', mode='w') as fp: fp.write(ans) ''' def input(): return [line.decode('utf-8') for line in sys.stdin.buffer.readlines()] def output(ans): print(ans) ''' s = input() n = int(s[0]) dd = defaultdict(list) pos_set = set() pos_a, hi_a = [0] * n, [0] * n for i, (h, l, r) in enumerate(map(int, line.split()) for line in s[1:]): hi_a[i] = -h pos_a[i] = r dd[l].append(i) pos_set.add(l) pos_set.add(r) hi_pos = defaultdict(int) hi_pos[0] = 10**9 + 100 hq = [0] ans = [] hi = 0 for pos in sorted(pos_set): while hq and hi_pos[hq[0]] <= pos: heappop(hq) if pos in dd: for i in dd[pos]: heappush(hq, hi_a[i]) hi_pos[hi_a[i]] = max(hi_pos[hi_a[i]], pos_a[i]) if hi != hq[0]: ans.append(f'{pos} {-hi}') ans.append(f'{pos} {-hq[0]}') hi = hq[0] output(str(len(ans)) + '\n' + '\n'.join(ans)) ``` No
94,727
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. No Great Victory anniversary in Berland has ever passed without the war parade. This year is not an exception. That’s why the preparations are on in full strength. Tanks are building a line, artillery mounts are ready to fire, soldiers are marching on the main square... And the air forces general Mr. Generalov is in trouble again. This year a lot of sky-scrapers have been built which makes it difficult for the airplanes to fly above the city. It was decided that the planes should fly strictly from south to north. Moreover, there must be no sky scraper on a plane’s route, otherwise the anniversary will become a tragedy. The Ministry of Building gave the data on n sky scrapers (the rest of the buildings are rather small and will not be a problem to the planes). When looking at the city from south to north as a geometrical plane, the i-th building is a rectangle of height hi. Its westernmost point has the x-coordinate of li and the easternmost — of ri. The terrain of the area is plain so that all the buildings stand on one level. Your task as the Ministry of Defence’s head programmer is to find an enveloping polyline using the data on the sky-scrapers. The polyline’s properties are as follows: * If you look at the city from south to north as a plane, then any part of any building will be inside or on the boarder of the area that the polyline encloses together with the land surface. * The polyline starts and ends on the land level, i.e. at the height equal to 0. * The segments of the polyline are parallel to the coordinate axes, i.e. they can only be vertical or horizontal. * The polyline’s vertices should have integer coordinates. * If you look at the city from south to north the polyline (together with the land surface) must enclose the minimum possible area. * The polyline must have the smallest length among all the polylines, enclosing the minimum possible area with the land. * The consecutive segments of the polyline must be perpendicular. <image> Picture to the second sample test (the enveloping polyline is marked on the right). Input The first input line contains integer n (1 ≤ n ≤ 100000). Then follow n lines, each containing three integers hi, li, ri (1 ≤ hi ≤ 109, - 109 ≤ li < ri ≤ 109). Output In the first line output integer m — amount of vertices of the enveloping polyline. The next m lines should contain 2 integers each — the position and the height of the polyline’s vertex. Output the coordinates of each vertex in the order of traversing the polyline from west to east. Remember that the first and the last vertices of the polyline should have the height of 0. Examples Input 2 3 0 2 4 1 3 Output 6 0 0 0 3 1 3 1 4 3 4 3 0 Input 5 3 -3 0 2 -1 1 4 2 4 2 3 7 3 6 8 Output 14 -3 0 -3 3 0 3 0 2 1 2 1 0 2 0 2 4 4 4 4 2 6 2 6 3 8 3 8 0 Submitted Solution: ``` import sys from array import array # noqa: F401 from collections import defaultdict from heapq import heappop, heappush def input(): with open('input.txt') as fp: return fp.readlines() def output(ans: str): with open('output.txt', mode='w') as fp: fp.write(ans) ''' def input(): return [line.decode('utf-8') for line in sys.stdin.buffer.readlines()] def output(ans): print(ans) ''' s = input() n = int(s[0]) dd = defaultdict(list) pos_set = set() pos_a, hi_a = [0] * n, [0] * n for i, (h, l, r) in enumerate(map(int, line.split()) for line in s[1:]): hi_a[i] = -h pos_a[i] = r dd[l].append(i) pos_set.add(l) pos_set.add(r) hi_pos = defaultdict(lambda: -10**9 - 100) hi_pos[0] = 10**9 + 100 hq = [0] ans = [] hi = 0 for pos in sorted(pos_set): while hq and hi_pos[hq[0]] <= pos: heappop(hq) if pos in dd: for i in dd[pos]: heappush(hq, hi_a[i]) hi_pos[hi_a[i]] = max(hi_pos[hi_a[i]], pos_a[i]) if hi != hq[0]: ans.append(f'{pos} {-hi}\n{pos} {-hq[0]}') hi = hq[0] output(str(len(ans)) + '\n' + '\n'.join(ans)) ``` No
94,728
Provide tags and a correct Python 3 solution for this coding contest problem. Iahub likes trees very much. Recently he discovered an interesting tree named propagating tree. The tree consists of n nodes numbered from 1 to n, each node i having an initial value ai. The root of the tree is node 1. This tree has a special property: when a value val is added to a value of node i, the value -val is added to values of all the children of node i. Note that when you add value -val to a child of node i, you also add -(-val) to all children of the child of node i and so on. Look an example explanation to understand better how it works. This tree supports two types of queries: * "1 x val" — val is added to the value of node x; * "2 x" — print the current value of node x. In order to help Iahub understand the tree better, you must answer m queries of the preceding type. Input The first line contains two integers n and m (1 ≤ n, m ≤ 200000). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000). Each of the next n–1 lines contains two integers vi and ui (1 ≤ vi, ui ≤ n), meaning that there is an edge between nodes vi and ui. Each of the next m lines contains a query in the format described above. It is guaranteed that the following constraints hold for all queries: 1 ≤ x ≤ n, 1 ≤ val ≤ 1000. Output For each query of type two (print the value of node x) you must print the answer to the query on a separate line. The queries must be answered in the order given in the input. Examples Input 5 5 1 2 1 1 2 1 2 1 3 2 4 2 5 1 2 3 1 1 2 2 1 2 2 2 4 Output 3 3 0 Note The values of the nodes are [1, 2, 1, 1, 2] at the beginning. Then value 3 is added to node 2. It propagates and value -3 is added to it's sons, node 4 and node 5. Then it cannot propagate any more. So the values of the nodes are [1, 5, 1, - 2, - 1]. Then value 2 is added to node 1. It propagates and value -2 is added to it's sons, node 2 and node 3. From node 2 it propagates again, adding value 2 to it's sons, node 4 and node 5. Node 3 has no sons, so it cannot propagate from there. The values of the nodes are [3, 3, - 1, 0, 1]. You can see all the definitions about the tree at the following link: http://en.wikipedia.org/wiki/Tree_(graph_theory) Tags: data structures, dfs and similar, trees Correct Solution: ``` class BIT(): """区間加算、一点取得クエリをそれぞれO(logN)で応えるデータ構造を構築する add: 区間[begin, end)にvalを加える get_val: i番目(0-indexed)の値を求める """ def __init__(self, n): self.n = n self.bit = [0] * (n + 1) def get_val(self, i): i = i + 1 s = 0 while i <= self.n: s += self.bit[i] i += i & -i return s def _add(self, i, val): while i > 0: self.bit[i] += val i -= i & -i def add(self, i, j, val): self._add(j, val) self._add(i, -val) from collections import deque import sys input = sys.stdin.readline def eular_tour(tree: list, root: int): """頂点に対するオイラーツアーを行う posの部分木に区間[begin[pos], end[pos])が対応する """ n = len(tree) res = [] begin = [-1] * n end = [-1] * n visited = [False] * n visited[root] = True q = deque([root]) while q: pos = q.pop() res.append(pos) end[pos] = len(res) if begin[pos] == -1: begin[pos] = len(res) - 1 for next_pos in tree[pos]: if visited[next_pos]: continue else: visited[next_pos] = True q.append(pos) q.append(next_pos) return res, begin, end n, q = map(int, input().split()) init_cost = list(map(int, input().split())) info = [list(map(int, input().split())) for i in range(n-1)] query = [list(map(int, input().split())) for i in range(q)] tree = [[] for i in range(n)] for i in range(n-1): a, b = info[i] a -= 1 b -= 1 tree[a].append(b) tree[b].append(a) res, begin, end = eular_tour(tree, 0) even_res = [] odd_res = [] for i in range(len(res)): if i % 2 == 0: even_res.append(res[i]) else: odd_res.append(res[i]) even_bit = BIT(len(even_res)) odd_bit = BIT(len(odd_res)) for i in range(q): if query[i][0] == 1: _, pos, cost = query[i] pos -= 1 if begin[pos] % 2 == 0: even_bit.add(begin[pos] // 2, (end[pos] + 1) // 2, cost) odd_bit.add(begin[pos] // 2, end[pos] // 2, -cost) else: odd_bit.add(begin[pos] // 2, end[pos] // 2, cost) even_bit.add((begin[pos] + 1) // 2, end[pos] // 2, -cost) else: _, pos = query[i] pos -= 1 if begin[pos] % 2 == 0: ans = even_bit.get_val(begin[pos] // 2) else: ans = odd_bit.get_val(begin[pos] // 2) print(ans + init_cost[pos]) ```
94,729
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub likes trees very much. Recently he discovered an interesting tree named propagating tree. The tree consists of n nodes numbered from 1 to n, each node i having an initial value ai. The root of the tree is node 1. This tree has a special property: when a value val is added to a value of node i, the value -val is added to values of all the children of node i. Note that when you add value -val to a child of node i, you also add -(-val) to all children of the child of node i and so on. Look an example explanation to understand better how it works. This tree supports two types of queries: * "1 x val" — val is added to the value of node x; * "2 x" — print the current value of node x. In order to help Iahub understand the tree better, you must answer m queries of the preceding type. Input The first line contains two integers n and m (1 ≤ n, m ≤ 200000). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000). Each of the next n–1 lines contains two integers vi and ui (1 ≤ vi, ui ≤ n), meaning that there is an edge between nodes vi and ui. Each of the next m lines contains a query in the format described above. It is guaranteed that the following constraints hold for all queries: 1 ≤ x ≤ n, 1 ≤ val ≤ 1000. Output For each query of type two (print the value of node x) you must print the answer to the query on a separate line. The queries must be answered in the order given in the input. Examples Input 5 5 1 2 1 1 2 1 2 1 3 2 4 2 5 1 2 3 1 1 2 2 1 2 2 2 4 Output 3 3 0 Note The values of the nodes are [1, 2, 1, 1, 2] at the beginning. Then value 3 is added to node 2. It propagates and value -3 is added to it's sons, node 4 and node 5. Then it cannot propagate any more. So the values of the nodes are [1, 5, 1, - 2, - 1]. Then value 2 is added to node 1. It propagates and value -2 is added to it's sons, node 2 and node 3. From node 2 it propagates again, adding value 2 to it's sons, node 4 and node 5. Node 3 has no sons, so it cannot propagate from there. The values of the nodes are [3, 3, - 1, 0, 1]. You can see all the definitions about the tree at the following link: http://en.wikipedia.org/wiki/Tree_(graph_theory) Submitted Solution: ``` from sys import setrecursionlimit import threading setrecursionlimit(10 ** 9) threading.stack_size(67108864) __author__ = 'Pavel Mavrin' n, m = [int(x) for x in input().split()] a = [int(x) for x in input().split()] nb = [[] for x in range(n)] for i in range(n - 1): x, y = [int(x) - 1 for x in input().split()] nb[x].append(y) nb[y].append(x) p = [0] * (2 * n) l = [0] * n r = [0] * n c = 0 def dfs(i, parent): global c global p l[i] = c p[c] = i c += 1 for j in nb[i]: if j != parent: dfs(j, i) p[c] = i c += 1 r[i] = c def make_tree(l, r): if r == l + 1: if l % 2 == 0: return [nonode, nonode, a[p[l]]] else: return [nonode, nonode, -a[p[l]]] else: m = (l + r) // 2 ll = make_tree(l, m) rr = make_tree(m, r) return [ll, rr, 0] def add(tree, l, r, a, b, val): if l >= b or a >= r: return if l >= a and r <= b: tree[2] += val else: m = (l + r) // 2 tree[0][2] += tree[2] tree[1][2] += tree[2] add(tree[0], l, m, a, b, val) add(tree[1], m, r, a, b, val) tree[2] = 0 def get(tree, l, r, i): if r == l + 1: return tree[2] m = (l + r) // 2 if i < m: return tree[2] + get(tree[0], l, m, i) else: return tree[2] + get(tree[1], m, r, i) #print([get(tree, 0, 2 * n, i) for i in range(2 * n)]) def main(): dfs(0, -1) nonode = [None, None, 0, 0] tree = make_tree(0, 2 * n) for i in range(m): z = [int(x) for x in input().split()] if z[0] == 1: if l[z[1] - 1] % 2 == 0: add(tree, 0, 2 * n, l[z[1] - 1], r[z[1] - 1], z[2]) else: add(tree, 0, 2 * n, l[z[1] - 1], r[z[1] - 1], -z[2]) # print([get(tree, 0, 2 * n, i) for i in range(2 * n)]) else: zz = get(tree, 0, 2 * n, l[z[1] - 1]) if l[z[1] - 1] % 2 == 0: print(zz) else: print(-zz) thread = threading.Thread(target=main) thread.start() ``` No
94,730
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub likes trees very much. Recently he discovered an interesting tree named propagating tree. The tree consists of n nodes numbered from 1 to n, each node i having an initial value ai. The root of the tree is node 1. This tree has a special property: when a value val is added to a value of node i, the value -val is added to values of all the children of node i. Note that when you add value -val to a child of node i, you also add -(-val) to all children of the child of node i and so on. Look an example explanation to understand better how it works. This tree supports two types of queries: * "1 x val" — val is added to the value of node x; * "2 x" — print the current value of node x. In order to help Iahub understand the tree better, you must answer m queries of the preceding type. Input The first line contains two integers n and m (1 ≤ n, m ≤ 200000). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000). Each of the next n–1 lines contains two integers vi and ui (1 ≤ vi, ui ≤ n), meaning that there is an edge between nodes vi and ui. Each of the next m lines contains a query in the format described above. It is guaranteed that the following constraints hold for all queries: 1 ≤ x ≤ n, 1 ≤ val ≤ 1000. Output For each query of type two (print the value of node x) you must print the answer to the query on a separate line. The queries must be answered in the order given in the input. Examples Input 5 5 1 2 1 1 2 1 2 1 3 2 4 2 5 1 2 3 1 1 2 2 1 2 2 2 4 Output 3 3 0 Note The values of the nodes are [1, 2, 1, 1, 2] at the beginning. Then value 3 is added to node 2. It propagates and value -3 is added to it's sons, node 4 and node 5. Then it cannot propagate any more. So the values of the nodes are [1, 5, 1, - 2, - 1]. Then value 2 is added to node 1. It propagates and value -2 is added to it's sons, node 2 and node 3. From node 2 it propagates again, adding value 2 to it's sons, node 4 and node 5. Node 3 has no sons, so it cannot propagate from there. The values of the nodes are [3, 3, - 1, 0, 1]. You can see all the definitions about the tree at the following link: http://en.wikipedia.org/wiki/Tree_(graph_theory) Submitted Solution: ``` n,m = map(int,input().split()) values = list(map(int,input().split())) rebra = [] for i in range(n-1): rebra.append(list(map(int,input().split()))) zapr = [] for i in range(m-1): z = list(map(int,input().split())) if z[0] == 1: v = -z[2] values[z[1]-1] -= v for j in range(z[1],n): for e in rebra: if e[0] == j: #2 values[e[1]-1] += v v = -v else: zapr.append(values[z[1]-1]) for i in zapr: print(i) ``` No
94,731
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub likes trees very much. Recently he discovered an interesting tree named propagating tree. The tree consists of n nodes numbered from 1 to n, each node i having an initial value ai. The root of the tree is node 1. This tree has a special property: when a value val is added to a value of node i, the value -val is added to values of all the children of node i. Note that when you add value -val to a child of node i, you also add -(-val) to all children of the child of node i and so on. Look an example explanation to understand better how it works. This tree supports two types of queries: * "1 x val" — val is added to the value of node x; * "2 x" — print the current value of node x. In order to help Iahub understand the tree better, you must answer m queries of the preceding type. Input The first line contains two integers n and m (1 ≤ n, m ≤ 200000). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000). Each of the next n–1 lines contains two integers vi and ui (1 ≤ vi, ui ≤ n), meaning that there is an edge between nodes vi and ui. Each of the next m lines contains a query in the format described above. It is guaranteed that the following constraints hold for all queries: 1 ≤ x ≤ n, 1 ≤ val ≤ 1000. Output For each query of type two (print the value of node x) you must print the answer to the query on a separate line. The queries must be answered in the order given in the input. Examples Input 5 5 1 2 1 1 2 1 2 1 3 2 4 2 5 1 2 3 1 1 2 2 1 2 2 2 4 Output 3 3 0 Note The values of the nodes are [1, 2, 1, 1, 2] at the beginning. Then value 3 is added to node 2. It propagates and value -3 is added to it's sons, node 4 and node 5. Then it cannot propagate any more. So the values of the nodes are [1, 5, 1, - 2, - 1]. Then value 2 is added to node 1. It propagates and value -2 is added to it's sons, node 2 and node 3. From node 2 it propagates again, adding value 2 to it's sons, node 4 and node 5. Node 3 has no sons, so it cannot propagate from there. The values of the nodes are [3, 3, - 1, 0, 1]. You can see all the definitions about the tree at the following link: http://en.wikipedia.org/wiki/Tree_(graph_theory) Submitted Solution: ``` n,m = map(int,input().split()) values = list(map(int,input().split())) rebra = [] for i in range(n-1): rebra.append(list(map(int,input().split()))) zapr = [] for i in range(m): z = list(map(int,input().split())) if z[0] == 1: v = -z[2] values[z[1]-1] -= v for j in range(z[1],n): for e in rebra: if e[0] == j: #2 values[e[1]-1] += v v = -v else: zapr.append(values[z[1]-1]) for i in zapr: print(i) ``` No
94,732
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Iahub likes trees very much. Recently he discovered an interesting tree named propagating tree. The tree consists of n nodes numbered from 1 to n, each node i having an initial value ai. The root of the tree is node 1. This tree has a special property: when a value val is added to a value of node i, the value -val is added to values of all the children of node i. Note that when you add value -val to a child of node i, you also add -(-val) to all children of the child of node i and so on. Look an example explanation to understand better how it works. This tree supports two types of queries: * "1 x val" — val is added to the value of node x; * "2 x" — print the current value of node x. In order to help Iahub understand the tree better, you must answer m queries of the preceding type. Input The first line contains two integers n and m (1 ≤ n, m ≤ 200000). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000). Each of the next n–1 lines contains two integers vi and ui (1 ≤ vi, ui ≤ n), meaning that there is an edge between nodes vi and ui. Each of the next m lines contains a query in the format described above. It is guaranteed that the following constraints hold for all queries: 1 ≤ x ≤ n, 1 ≤ val ≤ 1000. Output For each query of type two (print the value of node x) you must print the answer to the query on a separate line. The queries must be answered in the order given in the input. Examples Input 5 5 1 2 1 1 2 1 2 1 3 2 4 2 5 1 2 3 1 1 2 2 1 2 2 2 4 Output 3 3 0 Note The values of the nodes are [1, 2, 1, 1, 2] at the beginning. Then value 3 is added to node 2. It propagates and value -3 is added to it's sons, node 4 and node 5. Then it cannot propagate any more. So the values of the nodes are [1, 5, 1, - 2, - 1]. Then value 2 is added to node 1. It propagates and value -2 is added to it's sons, node 2 and node 3. From node 2 it propagates again, adding value 2 to it's sons, node 4 and node 5. Node 3 has no sons, so it cannot propagate from there. The values of the nodes are [3, 3, - 1, 0, 1]. You can see all the definitions about the tree at the following link: http://en.wikipedia.org/wiki/Tree_(graph_theory) Submitted Solution: ``` n,m = map(int,input().split()) values = list(map(int,input().split())) rebra = [] for i in range(n-1): rebra.append(list(map(int,input().split()))) zapr = [] for i in range(m): z = list(map(int,input().split())) if z[0] == 1: v = -z[2] values[z[1]-1] -= v for j in range(z[1],n+1): for e in rebra: if e[0] == j: #2 values[e[1]-1] += v v = -v else: zapr.append(values[z[1]-1]) for i in zapr: print(i) ``` No
94,733
Provide tags and a correct Python 3 solution for this coding contest problem. Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes. As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2·d, ..., n·d meters. Input The first line contains two space-separated real numbers a and d (1 ≤ a, d ≤ 105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink. The second line contains integer n (1 ≤ n ≤ 105) showing that Valera needs an extra drink n times. Output Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi, yi) after he covers i·d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10 - 4. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem. Examples Input 2 5 2 Output 1.0000000000 2.0000000000 2.0000000000 0.0000000000 Input 4.147 2.8819 6 Output 2.8819000000 0.0000000000 4.1470000000 1.6168000000 3.7953000000 4.1470000000 0.9134000000 4.1470000000 0.0000000000 2.1785000000 0.7034000000 0.0000000000 Tags: implementation, math Correct Solution: ``` import math a, d = map(float, input().split()) n = int(input()) for p in (math.fmod(i * d, 4 * a) for i in range(1, n + 1)): if p <= a: x, y = p, 0 elif p <= 2 * a: x, y = a, p - a elif p <= 3 * a: x, y = 3 * a - p, a else: x, y = 0, 4 * a - p print("{:.10f} {:.10f}".format(x, y)) ```
94,734
Provide tags and a correct Python 3 solution for this coding contest problem. Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes. As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2·d, ..., n·d meters. Input The first line contains two space-separated real numbers a and d (1 ≤ a, d ≤ 105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink. The second line contains integer n (1 ≤ n ≤ 105) showing that Valera needs an extra drink n times. Output Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi, yi) after he covers i·d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10 - 4. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem. Examples Input 2 5 2 Output 1.0000000000 2.0000000000 2.0000000000 0.0000000000 Input 4.147 2.8819 6 Output 2.8819000000 0.0000000000 4.1470000000 1.6168000000 3.7953000000 4.1470000000 0.9134000000 4.1470000000 0.0000000000 2.1785000000 0.7034000000 0.0000000000 Tags: implementation, math Correct Solution: ``` a, d = map(float, input().split()) n = int(input()) t = 0 for i in range(n): t = (t+d) % (4*a) if t < a: print(t, 0) continue if t < 2 * a: print(a, t-a) continue if t < 3 * a: print(3*a-t, a) continue if t < 4 * a: print(0, 4*a-t) ```
94,735
Provide tags and a correct Python 3 solution for this coding contest problem. Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes. As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2·d, ..., n·d meters. Input The first line contains two space-separated real numbers a and d (1 ≤ a, d ≤ 105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink. The second line contains integer n (1 ≤ n ≤ 105) showing that Valera needs an extra drink n times. Output Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi, yi) after he covers i·d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10 - 4. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem. Examples Input 2 5 2 Output 1.0000000000 2.0000000000 2.0000000000 0.0000000000 Input 4.147 2.8819 6 Output 2.8819000000 0.0000000000 4.1470000000 1.6168000000 3.7953000000 4.1470000000 0.9134000000 4.1470000000 0.0000000000 2.1785000000 0.7034000000 0.0000000000 Tags: implementation, math Correct Solution: ``` from math import floor a, d = map(float, input().split()) n = int(input()) res = [] for i in range(n): rec = i*d + d tra = floor(rec/a) % 4 seg = rec - floor(rec/a)*a # print("D>",rec, tra, seg) if tra == 0: res.append("%.8f %.8f" % (seg, 0.0)) elif tra == 1: res.append("%.8f %.8f" % (a, seg)) elif tra == 2: res.append("%.8f %.8f" % (a-seg, a)) elif tra == 3: res.append("%.8f %.8f" % (0.0, a-seg)) print("\n".join(res)) ```
94,736
Provide tags and a correct Python 3 solution for this coding contest problem. Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes. As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2·d, ..., n·d meters. Input The first line contains two space-separated real numbers a and d (1 ≤ a, d ≤ 105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink. The second line contains integer n (1 ≤ n ≤ 105) showing that Valera needs an extra drink n times. Output Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi, yi) after he covers i·d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10 - 4. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem. Examples Input 2 5 2 Output 1.0000000000 2.0000000000 2.0000000000 0.0000000000 Input 4.147 2.8819 6 Output 2.8819000000 0.0000000000 4.1470000000 1.6168000000 3.7953000000 4.1470000000 0.9134000000 4.1470000000 0.0000000000 2.1785000000 0.7034000000 0.0000000000 Tags: implementation, math Correct Solution: ``` def main(): a, d = map(float, input().split()) ai, di = (int(_ * 1e4 + .1) for _ in (a, d)) a2, a3, a4 = (ai * _ for _ in (2, 3, 4)) n, sa = int(input()), "%.10f" % a for t in range(di, n * di + 5001, di): t %= a4 if t <= a2: if t <= ai: print("%.10f 0.0000000000" % (t * 1e-4)) else: print(sa, "%.10f" % ((t - ai) * 1e-4)) else: if t <= a3: print("%.10f" % ((-t) % ai * 1e-4), sa) else: print("0.0000000000 %.10f" % ((- t) % ai * 1e-4)) if __name__ == '__main__': main() ```
94,737
Provide tags and a correct Python 3 solution for this coding contest problem. Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes. As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2·d, ..., n·d meters. Input The first line contains two space-separated real numbers a and d (1 ≤ a, d ≤ 105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink. The second line contains integer n (1 ≤ n ≤ 105) showing that Valera needs an extra drink n times. Output Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi, yi) after he covers i·d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10 - 4. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem. Examples Input 2 5 2 Output 1.0000000000 2.0000000000 2.0000000000 0.0000000000 Input 4.147 2.8819 6 Output 2.8819000000 0.0000000000 4.1470000000 1.6168000000 3.7953000000 4.1470000000 0.9134000000 4.1470000000 0.0000000000 2.1785000000 0.7034000000 0.0000000000 Tags: implementation, math Correct Solution: ``` [a, d], n, tmp = map(float, input().split()), int(input()), 0 for i in range(n): tmp = (tmp + d) % (4 * a) if tmp <= a: print(tmp, 0) elif tmp <= 2 * a: print(a, tmp - a) elif tmp <= 3 * a: print(3 * a - tmp, a) else: print(0, 4 * a - tmp) ```
94,738
Provide tags and a correct Python 3 solution for this coding contest problem. Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes. As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2·d, ..., n·d meters. Input The first line contains two space-separated real numbers a and d (1 ≤ a, d ≤ 105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink. The second line contains integer n (1 ≤ n ≤ 105) showing that Valera needs an extra drink n times. Output Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi, yi) after he covers i·d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10 - 4. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem. Examples Input 2 5 2 Output 1.0000000000 2.0000000000 2.0000000000 0.0000000000 Input 4.147 2.8819 6 Output 2.8819000000 0.0000000000 4.1470000000 1.6168000000 3.7953000000 4.1470000000 0.9134000000 4.1470000000 0.0000000000 2.1785000000 0.7034000000 0.0000000000 Tags: implementation, math Correct Solution: ``` a,b = [float(x) for x in input().split()] n = int(input()) for i in range(1,n+1): rem = (i*b)%(4*a) print(*[(rem,0),(a,rem-a),(3*a-rem,a),(0,4*a-rem)][int(rem//a)]) ```
94,739
Provide tags and a correct Python 3 solution for this coding contest problem. Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes. As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2·d, ..., n·d meters. Input The first line contains two space-separated real numbers a and d (1 ≤ a, d ≤ 105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink. The second line contains integer n (1 ≤ n ≤ 105) showing that Valera needs an extra drink n times. Output Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi, yi) after he covers i·d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10 - 4. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem. Examples Input 2 5 2 Output 1.0000000000 2.0000000000 2.0000000000 0.0000000000 Input 4.147 2.8819 6 Output 2.8819000000 0.0000000000 4.1470000000 1.6168000000 3.7953000000 4.1470000000 0.9134000000 4.1470000000 0.0000000000 2.1785000000 0.7034000000 0.0000000000 Tags: implementation, math Correct Solution: ``` a,d = [float(i) for i in input().split()] n = int(input()) d%=4*a start = 0 seg = 0 for i in range(n): start += d lengths = int(start/a) start = start%a seg = (seg+lengths)%4 if seg==0: print(start, 0) elif seg==1: print(a, start) elif seg==2: print(a-start, a) else: print(0, a-start) ```
94,740
Provide tags and a correct Python 3 solution for this coding contest problem. Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes. As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2·d, ..., n·d meters. Input The first line contains two space-separated real numbers a and d (1 ≤ a, d ≤ 105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink. The second line contains integer n (1 ≤ n ≤ 105) showing that Valera needs an extra drink n times. Output Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi, yi) after he covers i·d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10 - 4. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem. Examples Input 2 5 2 Output 1.0000000000 2.0000000000 2.0000000000 0.0000000000 Input 4.147 2.8819 6 Output 2.8819000000 0.0000000000 4.1470000000 1.6168000000 3.7953000000 4.1470000000 0.9134000000 4.1470000000 0.0000000000 2.1785000000 0.7034000000 0.0000000000 Tags: implementation, math Correct Solution: ``` from decimal import Decimal a, d=map(Decimal, input().split()) n=int(input()) tot=Decimal(0.0) x=Decimal(); y=Decimal() for i in range(n): tot+=d tot%=4*a if tot<a: x=tot; y=0.0 elif tot<2*a: x=a; y=tot-a elif tot<3*a: x=3*a-tot; y=a else: x=0.0; y=4*a-tot print(x, end=' '); print(y) ```
94,741
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes. As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2·d, ..., n·d meters. Input The first line contains two space-separated real numbers a and d (1 ≤ a, d ≤ 105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink. The second line contains integer n (1 ≤ n ≤ 105) showing that Valera needs an extra drink n times. Output Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi, yi) after he covers i·d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10 - 4. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem. Examples Input 2 5 2 Output 1.0000000000 2.0000000000 2.0000000000 0.0000000000 Input 4.147 2.8819 6 Output 2.8819000000 0.0000000000 4.1470000000 1.6168000000 3.7953000000 4.1470000000 0.9134000000 4.1470000000 0.0000000000 2.1785000000 0.7034000000 0.0000000000 Submitted Solution: ``` def setPoint(point, a): p = point x = 0 y = 0 if p <= a: x = p y = 0 elif p <= a*2: x = a y = p - a elif p <= a*3: x = a*3 - p y = a else: x = 0 y = a*4 - p x = int(x*100000)/100000 y = int(y*100000)/100000 return str(x) + ' ' + str(y) a, d = map(float, input().split()) n = int(input()) curP = 0 for l in range(0, n): curP += d curP = curP % (a*4) print(setPoint(curP, a)) ``` Yes
94,742
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes. As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2·d, ..., n·d meters. Input The first line contains two space-separated real numbers a and d (1 ≤ a, d ≤ 105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink. The second line contains integer n (1 ≤ n ≤ 105) showing that Valera needs an extra drink n times. Output Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi, yi) after he covers i·d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10 - 4. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem. Examples Input 2 5 2 Output 1.0000000000 2.0000000000 2.0000000000 0.0000000000 Input 4.147 2.8819 6 Output 2.8819000000 0.0000000000 4.1470000000 1.6168000000 3.7953000000 4.1470000000 0.9134000000 4.1470000000 0.0000000000 2.1785000000 0.7034000000 0.0000000000 Submitted Solution: ``` a, d = map(float, input().split()) n = int(input()) def coordinates(s): if s <= a: return (s, 0) elif s <= 2*a: return (a, s-a) elif s <= 3*a: return (3*a - s, a) else: return (0, 4*a - s) for i in range(1, n+1): print("%f %f" % coordinates(i*d % (4*a))) ``` Yes
94,743
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes. As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2·d, ..., n·d meters. Input The first line contains two space-separated real numbers a and d (1 ≤ a, d ≤ 105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink. The second line contains integer n (1 ≤ n ≤ 105) showing that Valera needs an extra drink n times. Output Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi, yi) after he covers i·d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10 - 4. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem. Examples Input 2 5 2 Output 1.0000000000 2.0000000000 2.0000000000 0.0000000000 Input 4.147 2.8819 6 Output 2.8819000000 0.0000000000 4.1470000000 1.6168000000 3.7953000000 4.1470000000 0.9134000000 4.1470000000 0.0000000000 2.1785000000 0.7034000000 0.0000000000 Submitted Solution: ``` a,d=map(float,input().split()) n=int(input()) for i in range(1,n+1): s=(d*i)%(4*a) if s<=a: print(s,0) elif s<=2*a: print(a,s-a) elif s<=3*a: print(3*a-s,a) else: print(0,4*a-s) ``` Yes
94,744
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes. As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2·d, ..., n·d meters. Input The first line contains two space-separated real numbers a and d (1 ≤ a, d ≤ 105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink. The second line contains integer n (1 ≤ n ≤ 105) showing that Valera needs an extra drink n times. Output Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi, yi) after he covers i·d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10 - 4. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem. Examples Input 2 5 2 Output 1.0000000000 2.0000000000 2.0000000000 0.0000000000 Input 4.147 2.8819 6 Output 2.8819000000 0.0000000000 4.1470000000 1.6168000000 3.7953000000 4.1470000000 0.9134000000 4.1470000000 0.0000000000 2.1785000000 0.7034000000 0.0000000000 Submitted Solution: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys def main(): a, d =map(lambda x: int(float(x) * 10000 + 1e-6), input().split(' ')) ans = [] for i in range(1, int(input()) + 1): cur_round_pos = d * i % (a * 4) if cur_round_pos <= a: y = 0 x = cur_round_pos / 10000 elif cur_round_pos <= a * 2: x = a / 10000 y = (cur_round_pos - a) / 10000 elif cur_round_pos <= a * 3: y = a / 10000 x = (a * 3 - cur_round_pos) / 10000 elif cur_round_pos < a * 4: x = 0 y = (a * 4 - cur_round_pos) / 10000 ans.append('{} {}'.format(x, y)) print('\n'.join(ans)) if __name__ == '__main__': sys.exit(main()) ``` Yes
94,745
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes. As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2·d, ..., n·d meters. Input The first line contains two space-separated real numbers a and d (1 ≤ a, d ≤ 105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink. The second line contains integer n (1 ≤ n ≤ 105) showing that Valera needs an extra drink n times. Output Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi, yi) after he covers i·d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10 - 4. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem. Examples Input 2 5 2 Output 1.0000000000 2.0000000000 2.0000000000 0.0000000000 Input 4.147 2.8819 6 Output 2.8819000000 0.0000000000 4.1470000000 1.6168000000 3.7953000000 4.1470000000 0.9134000000 4.1470000000 0.0000000000 2.1785000000 0.7034000000 0.0000000000 Submitted Solution: ``` def setPoint(point, a): p = point x = 0 y = 0 cnt = 0 if p <= a: x = p y = 0 elif p <= a*2: x = a y = p elif p <= a*3: x = a*3 - p y = a else: x = 0 y = a*4 - p return str(x)[:7] + ' ' + str(y)[:7] a, d = map(float, input().split()) n = int(input()) curP = 0 finish = n*d + 0.5 for l in range(0, n): curP += d while curP > a*4: curP -= a*4 print(setPoint(curP, a)) ``` No
94,746
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes. As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2·d, ..., n·d meters. Input The first line contains two space-separated real numbers a and d (1 ≤ a, d ≤ 105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink. The second line contains integer n (1 ≤ n ≤ 105) showing that Valera needs an extra drink n times. Output Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi, yi) after he covers i·d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10 - 4. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem. Examples Input 2 5 2 Output 1.0000000000 2.0000000000 2.0000000000 0.0000000000 Input 4.147 2.8819 6 Output 2.8819000000 0.0000000000 4.1470000000 1.6168000000 3.7953000000 4.1470000000 0.9134000000 4.1470000000 0.0000000000 2.1785000000 0.7034000000 0.0000000000 Submitted Solution: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys def main(): a, d =map(lambda x: int(float(x) * 10000), input().split(' ')) ans = [] for i in range(1, int(input()) + 1): t = d * i % (a * 4) if t <= a: y = 0 x = t / 10000 elif t <= a * 2: x = a / 10000 y = (t - a) / 10000 elif t <= a * 3: y = a / 10000 x = (a - (t - a * 2)) / 10000 elif t < a * 4: x = 0 y = (a - (t - a * 3)) / 10000 ans.append('{} {}'.format(x, y)) print('\n'.join(ans)) if __name__ == '__main__': sys.exit(main()) ``` No
94,747
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes. As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2·d, ..., n·d meters. Input The first line contains two space-separated real numbers a and d (1 ≤ a, d ≤ 105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink. The second line contains integer n (1 ≤ n ≤ 105) showing that Valera needs an extra drink n times. Output Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi, yi) after he covers i·d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10 - 4. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem. Examples Input 2 5 2 Output 1.0000000000 2.0000000000 2.0000000000 0.0000000000 Input 4.147 2.8819 6 Output 2.8819000000 0.0000000000 4.1470000000 1.6168000000 3.7953000000 4.1470000000 0.9134000000 4.1470000000 0.0000000000 2.1785000000 0.7034000000 0.0000000000 Submitted Solution: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys def main(): a, d =map(lambda x: int(float(x) * 10000), input().split(' ')) for i in range(1, int(input()) + 1): cur_round_pos = d * i % (a * 4) if cur_round_pos <= a: y = 0.0 x = cur_round_pos / 10000 elif cur_round_pos <= a * 2: x = a / 10000 y = (cur_round_pos - a) / 10000 elif cur_round_pos <= a * 3: y = a / 10000 x = (a - (cur_round_pos - a * 2)) / 10000 elif cur_round_pos <= a * 4: x = 0.0 y = (a - (cur_round_pos - a * 3)) / 10000 print(x, end=' ') print(y) if __name__ == '__main__': sys.exit(main()) ``` No
94,748
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes. As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2·d, ..., n·d meters. Input The first line contains two space-separated real numbers a and d (1 ≤ a, d ≤ 105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink. The second line contains integer n (1 ≤ n ≤ 105) showing that Valera needs an extra drink n times. Output Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi, yi) after he covers i·d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10 - 4. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem. Examples Input 2 5 2 Output 1.0000000000 2.0000000000 2.0000000000 0.0000000000 Input 4.147 2.8819 6 Output 2.8819000000 0.0000000000 4.1470000000 1.6168000000 3.7953000000 4.1470000000 0.9134000000 4.1470000000 0.0000000000 2.1785000000 0.7034000000 0.0000000000 Submitted Solution: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys def main(): a, d =map(lambda x: int(float(x) * 10000 + 1e-6), input().split(' ')) ans = [] for i in range(1, int(input()) + 1): cur_round_pos = d * i % (a * 4) if cur_round_pos <= a: y = 0 x = cur_round_pos / 10000 elif cur_round_pos <= a * 2: x = a / 10000 y = (cur_round_pos - a) / 10000 elif cur_round_pos <= a * 3: y = a x = (a * 3 - cur_round_pos) / 10000 elif cur_round_pos < a * 4: x = 0 y = (a * 4 - cur_round_pos) / 10000 print('{} {}'.format(x, y)) ans.append('{} {}'.format(x, y)) print('\n'.join(ans)) if __name__ == '__main__': sys.exit(main()) ``` No
94,749
Provide tags and a correct Python 3 solution for this coding contest problem. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 Tags: dp, implementation, trees Correct Solution: ``` n,v,d=list(map(int,input().split())) dp=[[0]*2 for i in range(n+1)] dp[0][0]=1 for i in range(1,n+1): for k in range(1,min(i,v)+1): dp[i][0]+=dp[i-k][0] if k>=d: dp[i][1]+=dp[i-k][0] else: dp[i][1]+=dp[i-k][1] print(dp[n][1]%(10**9+7)) ```
94,750
Provide tags and a correct Python 3 solution for this coding contest problem. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 Tags: dp, implementation, trees Correct Solution: ``` mod = 10**9+7 def countWays(arr, m, N,d): count = [0 for i in range(N + 1)] count[0] = 1 for i in range(1, N + 1): for j in range(m): if (i >= arr[j]) and arr[j]<d: count[i] += count[i - arr[j]] count[i]%=mod return count[N] def countWays1(arr, m, N): count = [0 for i in range(N + 1)] count[0] = 1 for i in range(1, N + 1): for j in range(m): if (i >= arr[j]): count[i] += count[i - arr[j]] count[i]%=mod return count[N] n,k,d = map(int,input().split()) a = [i for i in range(1,k+1)] t1 = countWays(a,len(a),n,d) t2 = countWays1(a,len(a),n) print((t2-t1+mod)%mod) ```
94,751
Provide tags and a correct Python 3 solution for this coding contest problem. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 Tags: dp, implementation, trees Correct Solution: ``` def dp(curr, least, k, total, loc=0): global d if curr == total: return int(least == 0) if d[curr][int(least==0)] != -1: return d[curr][int(least==0)] for i in range(1, k+1): if curr+i > total: break loc+= dp(curr+i, 0 if least <= i else least, k, total) d[curr][int(least==0)] = loc % 1000000007 return loc % 1000000007 n, k, dd = map(int, input().split()) d = [[-1, -1] for i in range(n)] print(dp(0, dd, k, n)) ```
94,752
Provide tags and a correct Python 3 solution for this coding contest problem. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 Tags: dp, implementation, trees Correct Solution: ``` mod=int(1e9+7) n,k,d=map(int,input().split()) dp=[0 for i in range(n+k+1)] dp[0]=1 for i in range(n+1): for j in range(1,k+1): dp[i+j]+=dp[i] dp[i+j]%=mod dp2=[0 for i in range(n+k+1)] dp2[0]=1 for i in range(n+1): for j in range(1,d): dp2[i+j]+=dp2[i] dp[i+j]%=mod print((dp[n]-dp2[n]+mod)%mod) ```
94,753
Provide tags and a correct Python 3 solution for this coding contest problem. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 Tags: dp, implementation, trees Correct Solution: ``` n, k, d = [int(x) for x in input().split()] z = [[1], [1]] for i in range(1, n + 1): z[0].append(sum(z[0][max(i-d+1, 0):])) z[1].append(sum(z[1][max(i-k, 0):])) print((z[1][-1] - z[0][-1]) % (10**9+7)) ```
94,754
Provide tags and a correct Python 3 solution for this coding contest problem. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 Tags: dp, implementation, trees Correct Solution: ``` N,K,D=map(int,input().split()) mod=10**9+7 dpK=[0 for i in range(N+1)] dpK[0]=1 for i in range(1,N+1): for j in range(1,K+1): if i>=j: dpK[i]+=dpK[i-j] dpK[i]%=mod dp=[0 for i in range(N+1)] dp[0]=1 for i in range(1,N+1): for j in range(1,D): if i>=j: dp[i]+=dp[i-j] dp[i]%=mod ans=dpK[N]-dp[N] print(ans%mod) ```
94,755
Provide tags and a correct Python 3 solution for this coding contest problem. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 Tags: dp, implementation, trees Correct Solution: ``` n, k, d = map(int, input().split()) dp = [[0 for i in range(2)] for j in range(n + 10)] dp[0][0] = 1 MOD = int(1e9) + 7 for i in range(1, n + 1): for j in range(1, min(d - 1, n) + 1): dp[i][0] += dp[i - j][0] % MOD for j in range(1, min(d - 1, n) + 1): dp[i][1] += dp[i - j][1] % MOD for j in range(d, min(n, k) + 1): dp[i][1] += (dp[i - j][0] + dp[i - j][1]) % MOD print(dp[n][1] % MOD) ```
94,756
Provide tags and a correct Python 3 solution for this coding contest problem. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 Tags: dp, implementation, trees Correct Solution: ``` import sys from math import log2,floor,ceil,sqrt,gcd # import bisect # from collections import deque # sys.setrecursionlimit(7*10**4) 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 = 1000000007 n,k,d = Ri() no = [0]*(n+1) no[0] = 1 for i in range(1,n+1): for j in range(1,k+1): if j > i: break no[i]+=no[i-j] # no[i] = no[i]%MOD # print(no) nod = [0]*(n+1) nod[0] = 1 for i in range(1,n+1): for j in range(1,k+1): if j > i : break if j >= d : break nod[i]+=nod[i-j] # nod[i]%=MOD # print(nod) print((no[n]-nod[n])%MOD) ```
94,757
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 Submitted Solution: ``` import sys, os, io def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n') import math,datetime,functools,itertools,operator,bisect,fractions,statistics from collections import deque,defaultdict,OrderedDict,Counter from fractions import Fraction from decimal import Decimal from sys import stdout from heapq import heappush, heappop, heapify ,_heapify_max,_heappop_max,nsmallest,nlargest sys.setrecursionlimit(111111) INF=999999999999999999999999 class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) def main(): mod=1000000007 # InverseofNumber(mod) # InverseofFactorial(mod) # factorial(mod) starttime=datetime.datetime.now() if(os.path.exists('input.txt')): sys.stdin = open("input.txt","r") sys.stdout = open("output.txt","w") ###CODE tc = 1 for _ in range(tc): n,k,d=ria() coins=[int(x) for x in range(1,k+1)] x=n dp=[0]*1000005 dp[0]=1 mod=int(1e9)+7 for i in range(1,x+1): for j in coins: if j-i>0: break dp[i]=(dp[i]+dp[i-j])%mod total=(dp[x]) coins=[int(x) for x in range(1,d)] x=n dp=[0]*1000005 dp[0]=1 mod=int(1e9)+7 for i in range(1,x+1): for j in coins: if j-i>0: break dp[i]=(dp[i]+dp[i-j])%mod waste=dp[x] print((total-waste)%mod) #<--Solving Area Ends endtime=datetime.datetime.now() time=(endtime-starttime).total_seconds()*1000 if(os.path.exists('input.txt')): print("Time:",time,"ms") class FastReader(io.IOBase): newlines = 0 def __init__(self, fd, chunk_size=1024 * 8): self._fd = fd self._chunk_size = chunk_size self.buffer = io.BytesIO() def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size)) 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, size=-1): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size)) 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() class FastWriter(io.IOBase): def __init__(self, fd): self._fd = fd self.buffer = io.BytesIO() self.write = self.buffer.write def flush(self): os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class FastStdin(io.IOBase): def __init__(self, fd=0): self.buffer = FastReader(fd) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") class FastStdout(io.IOBase): def __init__(self, fd=1): self.buffer = FastWriter(fd) self.write = lambda s: self.buffer.write(s.encode("ascii")) self.flush = self.buffer.flush if __name__ == '__main__': sys.stdin = FastStdin() sys.stdout = FastStdout() main() ``` Yes
94,758
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 Submitted Solution: ``` #!/usr/bin/env python3 import itertools, functools, math MOD = 1000000007 @functools.lru_cache(None) def dp(n, k, d, d_used=False): if n == d and not d_used: return 1 if n == 0: return 1 if n < d and not d_used: return 0 r = 0 for i in range(1, min(n+1, k+1)): r = (r + dp(n-i, k, d, d_used or i>=d))%MOD return r def solve(): n, k, d = map(int, input().split()) return dp(n, k, d) if __name__ == '__main__': print(solve()) ``` Yes
94,759
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 Submitted Solution: ``` import functools import sys p = 10**9 + 7 line = input() tokens = line.split() n, k, d = int(tokens[0]), int(tokens[1]), int(tokens[2]) @functools.lru_cache(None) def f(s): if s == 0: return 1 total = 0 for w in range(1, k + 1): if w > s: break total += f(s - w) return total % p @functools.lru_cache(None) def g(s): if s == 0: return 1 total = 0 for w in range(1, min(d, k + 1)): if w > s: break total += g(s - w) return total % p print((f(n) - g(n)) % p) ``` Yes
94,760
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 Submitted Solution: ``` n, k, d = list(map(int, input().split())) MOD = 10 ** 9 + 7 dp = {} def rec(remaining, flag = False): if remaining < 0: return 0 if remaining == 0 and flag == True: return 1 if (remaining, flag) in dp: return dp[(remaining, flag)] ans = 0 for i in range(1,k+1): if i <= remaining: ans += rec(remaining - i, flag | (i>=d)) ans %= MOD dp[(remaining, flag)] = ans return ans ans = rec(n) % MOD print(ans) ``` Yes
94,761
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 Submitted Solution: ``` memo = {} tg,k,d = map(int,input().split()) def rec(n): if n in memo: return memo[n] ans = [0,0] for b in range(1, min(k,n)+1): if b == n: ans[b>=d]+=1 continue r = rec(n-b) ans[1]+=r[1] ans[b>=d]+=r[0] memo[n] = ans return ans print(rec(tg)[1]) ``` No
94,762
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 Submitted Solution: ``` import sys sys.setrecursionlimit(100000) n, k, d = [int(x) for x in sys.stdin.readline().strip().split()] memo = {} m = 10**9 +7 def dp(n,k,d): if n in memo: return memo[n] if n==0: return 1 if n<0: return 0 s = 0 for i in range(1,k+1): if i>=d : s+=dp(n-i,k,0) elif n-i>=d: s+=dp(n-i,k,d) memo[n]=s return s print(dp(n,k,d)%m) ``` No
94,763
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 Submitted 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 # import numpy as np starttime = time.time() # import numpy as np mod = int(pow(10, 9) + 7) mod2 = 998244353 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 n,k,d=L() def func(n,A): @lru_cache def rec(s): # print(s) if s==0: return 1 if s<0: return 0 ans=0 for x in A: ans+=rec(s-x) ans%=mod return ans return rec(n) ans=func(n,[i for i in range(1,k+1)]) if d!=1: ans-=func(n,[i for i in range(1,d)]) print(ans) endtime = time.time() # print(f"Runtime of the program is {endtime - starttime}") ``` No
94,764
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k. The picture below shows a part of a 3-tree. <image> As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?". Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (109 + 7). Input A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k). Output Print a single integer — the answer to the problem modulo 1000000007 (109 + 7). Examples Input 3 3 2 Output 3 Input 3 3 3 Output 1 Input 4 3 2 Output 6 Input 4 5 2 Output 7 Submitted Solution: ``` n,k,d=map(int,input().split(" ")) dp=[[0,0] for i in range(n+1)] dp[0][0]=1 for i in range(1,n+1): for j in range(1,k+1): if(i-j<0): break if(j<d): dp[i][0]+=dp[i-j][0]%1000000007 dp[i][1]+=dp[i-j][1]%1000000007 else: dp[i][1]+=dp[i-j][0]%1000000007 dp[i][1]+=dp[i-j][1]%1000000007 print(dp[n][1]) ``` No
94,765
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Lord Tirek is a centaur and the main antagonist in the season four finale episodes in the series "My Little Pony: Friendship Is Magic". In "Twilight's Kingdom" (Part 1), Tirek escapes from Tartarus and drains magic from ponies to grow stronger. <image> The core skill of Tirek is called Absorb Mana. It takes all mana from a magic creature and gives them to the caster. Now to simplify the problem, assume you have n ponies (numbered from 1 to n). Each pony has three attributes: * si : amount of mana that the pony has at time 0; * mi : maximum mana that the pony can have; * ri : mana regeneration per unit time. Lord Tirek will do m instructions, each of them can be described with three integers: ti, li, ri. The instruction means that at time ti, Tirek will use Absorb Mana on ponies with numbers from li to ri (both borders inclusive). We'll give you all the m instructions in order, count how much mana Tirek absorbs for each instruction. Input The first line contains an integer n (1 ≤ n ≤ 105) — the number of ponies. Each of the next n lines contains three integers si, mi, ri (0 ≤ si ≤ mi ≤ 105; 0 ≤ ri ≤ 105), describing a pony. The next line contains an integer m (1 ≤ m ≤ 105) — the number of instructions. Each of the next m lines contains three integers ti, li, ri (0 ≤ ti ≤ 109; 1 ≤ li ≤ ri ≤ n), describing an instruction of Lord Tirek. The instructions are given in strictly increasing order of ti (all ti are distinct). Output For each instruction, output a single line which contains a single integer, the total mana absorbed in this instruction. Examples Input 5 0 10 1 0 12 1 0 20 1 0 12 1 0 10 1 2 5 1 5 19 1 5 Output 25 58 Note Every pony starts with zero mana. For the first instruction, each pony has 5 mana, so you get 25 mana in total and each pony has 0 mana after the first instruction. For the second instruction, pony 3 has 14 mana and other ponies have mana equal to their mi. Submitted Solution: ``` pony_count = int(input()) ponies = [] for _ in range(pony_count): ponies.append([int(i) for i in input().split()]) instruction_count = int(input()) earlierTime = 0 for _ in range(instruction_count): time,x,y = [int(i) for i in input().split()] mana_absorbed = 0 for i in range(x-1,y): amount = min(ponies[i][2]*(time-earlierTime)+ponies[i][0],ponies[i][1]) mana_absorbed+=amount ponies[i][0]=0 earlierTime=time print(mana_absorbed) ``` No
94,766
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Lord Tirek is a centaur and the main antagonist in the season four finale episodes in the series "My Little Pony: Friendship Is Magic". In "Twilight's Kingdom" (Part 1), Tirek escapes from Tartarus and drains magic from ponies to grow stronger. <image> The core skill of Tirek is called Absorb Mana. It takes all mana from a magic creature and gives them to the caster. Now to simplify the problem, assume you have n ponies (numbered from 1 to n). Each pony has three attributes: * si : amount of mana that the pony has at time 0; * mi : maximum mana that the pony can have; * ri : mana regeneration per unit time. Lord Tirek will do m instructions, each of them can be described with three integers: ti, li, ri. The instruction means that at time ti, Tirek will use Absorb Mana on ponies with numbers from li to ri (both borders inclusive). We'll give you all the m instructions in order, count how much mana Tirek absorbs for each instruction. Input The first line contains an integer n (1 ≤ n ≤ 105) — the number of ponies. Each of the next n lines contains three integers si, mi, ri (0 ≤ si ≤ mi ≤ 105; 0 ≤ ri ≤ 105), describing a pony. The next line contains an integer m (1 ≤ m ≤ 105) — the number of instructions. Each of the next m lines contains three integers ti, li, ri (0 ≤ ti ≤ 109; 1 ≤ li ≤ ri ≤ n), describing an instruction of Lord Tirek. The instructions are given in strictly increasing order of ti (all ti are distinct). Output For each instruction, output a single line which contains a single integer, the total mana absorbed in this instruction. Examples Input 5 0 10 1 0 12 1 0 20 1 0 12 1 0 10 1 2 5 1 5 19 1 5 Output 25 58 Note Every pony starts with zero mana. For the first instruction, each pony has 5 mana, so you get 25 mana in total and each pony has 0 mana after the first instruction. For the second instruction, pony 3 has 14 mana and other ponies have mana equal to their mi. Submitted Solution: ``` pony_count = int(input()) ponies = [] for _ in range(pony_count): ponies.append([int(i) for i in input().split()]) instruction_count = int(input()) earlierTime = 0 for _ in range(instruction_count): time,x,y = [int(i) for i in input().split()] mana_absorbed = 0 for i in range(x-1,y): amount = min(ponies[i][2]*(time-earlierTime),ponies[i][1])-ponies[i][0] mana_absorbed+=amount earlierTime=time print(mana_absorbed) ``` No
94,767
Provide tags and a correct Python 3 solution for this coding contest problem. Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a]. By <image> we denote the quotient of integer division of x and y. By <image> we denote the remainder of integer division of x and y. You can read more about these operations here: http://goo.gl/AcsXhT. The answer may be large, so please print its remainder modulo 1 000 000 007 (109 + 7). Can you compute it faster than Dreamoon? Input The single line of the input contains two integers a, b (1 ≤ a, b ≤ 107). Output Print a single integer representing the answer modulo 1 000 000 007 (109 + 7). Examples Input 1 1 Output 0 Input 2 2 Output 8 Note For the first sample, there are no nice integers because <image> is always zero. For the second sample, the set of nice integers is {3, 5}. Tags: math Correct Solution: ``` a,b=map(int, input().split()) m=1000000007 B = int((b*(b-1)/2) % m ); A1 = int((a*(a+1)/2) % m ); A = int((A1*b+a) % m ); res = int((A*B) % m) ; print(res) ```
94,768
Provide tags and a correct Python 3 solution for this coding contest problem. Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a]. By <image> we denote the quotient of integer division of x and y. By <image> we denote the remainder of integer division of x and y. You can read more about these operations here: http://goo.gl/AcsXhT. The answer may be large, so please print its remainder modulo 1 000 000 007 (109 + 7). Can you compute it faster than Dreamoon? Input The single line of the input contains two integers a, b (1 ≤ a, b ≤ 107). Output Print a single integer representing the answer modulo 1 000 000 007 (109 + 7). Examples Input 1 1 Output 0 Input 2 2 Output 8 Note For the first sample, there are no nice integers because <image> is always zero. For the second sample, the set of nice integers is {3, 5}. Tags: math Correct Solution: ``` a,b = map(int,input().split()) MOD = 1000000007 x = a*(a + 1) x = x // 2 x = x % MOD x = (x * b) % MOD x = (x + a) % MOD x = ((x*b*(b - 1)) // 2) % MOD print(x) ```
94,769
Provide tags and a correct Python 3 solution for this coding contest problem. Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a]. By <image> we denote the quotient of integer division of x and y. By <image> we denote the remainder of integer division of x and y. You can read more about these operations here: http://goo.gl/AcsXhT. The answer may be large, so please print its remainder modulo 1 000 000 007 (109 + 7). Can you compute it faster than Dreamoon? Input The single line of the input contains two integers a, b (1 ≤ a, b ≤ 107). Output Print a single integer representing the answer modulo 1 000 000 007 (109 + 7). Examples Input 1 1 Output 0 Input 2 2 Output 8 Note For the first sample, there are no nice integers because <image> is always zero. For the second sample, the set of nice integers is {3, 5}. Tags: math Correct Solution: ``` a,b=map(int,input().split()) h=1000000007 c=((a*(b*b-b))//2)%h; d=((a*a+a)//2)%h; e=((b*b*b-b*b)//2)%h; print((c+(d*e)%h)%h) ```
94,770
Provide tags and a correct Python 3 solution for this coding contest problem. Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a]. By <image> we denote the quotient of integer division of x and y. By <image> we denote the remainder of integer division of x and y. You can read more about these operations here: http://goo.gl/AcsXhT. The answer may be large, so please print its remainder modulo 1 000 000 007 (109 + 7). Can you compute it faster than Dreamoon? Input The single line of the input contains two integers a, b (1 ≤ a, b ≤ 107). Output Print a single integer representing the answer modulo 1 000 000 007 (109 + 7). Examples Input 1 1 Output 0 Input 2 2 Output 8 Note For the first sample, there are no nice integers because <image> is always zero. For the second sample, the set of nice integers is {3, 5}. Tags: math Correct Solution: ``` # -*- coding: utf-8 -*- """ Created on Wed Jul 7 23:26:09 2021 @author: Kevin Chang Project: Codeforces Problem 476C """ a, b = list(map(int, input().split())) modu = 10**9+7 res = (b*(b-1)//2)*((b*a*(a+1)//2)+a)%modu print(res) ```
94,771
Provide tags and a correct Python 3 solution for this coding contest problem. Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a]. By <image> we denote the quotient of integer division of x and y. By <image> we denote the remainder of integer division of x and y. You can read more about these operations here: http://goo.gl/AcsXhT. The answer may be large, so please print its remainder modulo 1 000 000 007 (109 + 7). Can you compute it faster than Dreamoon? Input The single line of the input contains two integers a, b (1 ≤ a, b ≤ 107). Output Print a single integer representing the answer modulo 1 000 000 007 (109 + 7). Examples Input 1 1 Output 0 Input 2 2 Output 8 Note For the first sample, there are no nice integers because <image> is always zero. For the second sample, the set of nice integers is {3, 5}. Tags: math Correct Solution: ``` mod =10**9+7 a,b = map(int,input().split()) t1 = (b*(b-1)//2)%mod t2 = (a*(a+1)//2)%mod t3= (t2*b)%mod +a ans = (t1 * t3)%mod print(ans) ```
94,772
Provide tags and a correct Python 3 solution for this coding contest problem. Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a]. By <image> we denote the quotient of integer division of x and y. By <image> we denote the remainder of integer division of x and y. You can read more about these operations here: http://goo.gl/AcsXhT. The answer may be large, so please print its remainder modulo 1 000 000 007 (109 + 7). Can you compute it faster than Dreamoon? Input The single line of the input contains two integers a, b (1 ≤ a, b ≤ 107). Output Print a single integer representing the answer modulo 1 000 000 007 (109 + 7). Examples Input 1 1 Output 0 Input 2 2 Output 8 Note For the first sample, there are no nice integers because <image> is always zero. For the second sample, the set of nice integers is {3, 5}. Tags: math Correct Solution: ``` a,b = list(map(int,input().split())) if b ==1 : print(0) else : res = a + b*a*(a+1)//2 res = (res*(b)*(b-1)//2) print(res%(10**9 +7)) ```
94,773
Provide tags and a correct Python 3 solution for this coding contest problem. Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a]. By <image> we denote the quotient of integer division of x and y. By <image> we denote the remainder of integer division of x and y. You can read more about these operations here: http://goo.gl/AcsXhT. The answer may be large, so please print its remainder modulo 1 000 000 007 (109 + 7). Can you compute it faster than Dreamoon? Input The single line of the input contains two integers a, b (1 ≤ a, b ≤ 107). Output Print a single integer representing the answer modulo 1 000 000 007 (109 + 7). Examples Input 1 1 Output 0 Input 2 2 Output 8 Note For the first sample, there are no nice integers because <image> is always zero. For the second sample, the set of nice integers is {3, 5}. Tags: math Correct Solution: ``` a = input() a = a.split() a,b = int(a[0]),int(a[1]) k2 = b*(b-1)*a // 2 k = (b-1)*b//2 * b* (1+a)*a // 2 res = (k + k2) % 1000000007 print(res) ```
94,774
Provide tags and a correct Python 3 solution for this coding contest problem. Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a]. By <image> we denote the quotient of integer division of x and y. By <image> we denote the remainder of integer division of x and y. You can read more about these operations here: http://goo.gl/AcsXhT. The answer may be large, so please print its remainder modulo 1 000 000 007 (109 + 7). Can you compute it faster than Dreamoon? Input The single line of the input contains two integers a, b (1 ≤ a, b ≤ 107). Output Print a single integer representing the answer modulo 1 000 000 007 (109 + 7). Examples Input 1 1 Output 0 Input 2 2 Output 8 Note For the first sample, there are no nice integers because <image> is always zero. For the second sample, the set of nice integers is {3, 5}. Tags: math Correct Solution: ``` import sys import math MAXNUM = math.inf MINNUM = -1 * math.inf ASCIILOWER = 97 ASCIIUPPER = 65 MODMAX = 1000000007 def getInt(): return int(sys.stdin.readline().rstrip()) def getInts(): return map(int, sys.stdin.readline().rstrip().split(" ")) def getString(): return sys.stdin.readline().rstrip() def printOutput(ans): sys.stdout.write() pass def termadd(n): return (n * (n + 1)) // 2 def solve(a, b): return ((a*(b-1)*(b)*(b*(a+1) + 2))//4) % MODMAX def readinput(): a, b = getInts() print(solve(a, b)) readinput() ```
94,775
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a]. By <image> we denote the quotient of integer division of x and y. By <image> we denote the remainder of integer division of x and y. You can read more about these operations here: http://goo.gl/AcsXhT. The answer may be large, so please print its remainder modulo 1 000 000 007 (109 + 7). Can you compute it faster than Dreamoon? Input The single line of the input contains two integers a, b (1 ≤ a, b ≤ 107). Output Print a single integer representing the answer modulo 1 000 000 007 (109 + 7). Examples Input 1 1 Output 0 Input 2 2 Output 8 Note For the first sample, there are no nice integers because <image> is always zero. For the second sample, the set of nice integers is {3, 5}. Submitted Solution: ``` ###### ### ####### ####### ## # ##### ### ##### # # # # # # # # # # # # # ### # # # # # # # # # # # # # ### ###### ######### # # # # # # ######### # ###### ######### # # # # # # ######### # # # # # # # # # # # #### # # # # # # # # # # ## # # # # # ###### # # ####### ####### # # ##### # # # # from __future__ import print_function # for PyPy2 # from itertools import permutations # from functools import cmp_to_key # for adding custom comparator # from fractions import Fraction # from collections import * from sys import stdin # from bisect import * from heapq import * from math import log2, ceil, sqrt, gcd, log g = lambda : stdin.readline().strip() gl = lambda : g().split() gil = lambda : [int(var) for var in gl()] gfl = lambda : [float(var) for var in gl()] gcl = lambda : list(g()) gbs = lambda : [int(var) for var in g()] rr = lambda x : reversed(range(x)) mod = int(1e9)+7 inf = float("inf") # range = xrange a, b = gil() if b == 1: print(0) exit() ans = 0 for k in range(1, a+1): ans += (k*b + 1)%mod if ans >= mod: ans %= mod # print(ans) mul = ((b-1)*(b))//2 mul %= mod ans *= mul ans %= mod print(ans) ``` Yes
94,776
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a]. By <image> we denote the quotient of integer division of x and y. By <image> we denote the remainder of integer division of x and y. You can read more about these operations here: http://goo.gl/AcsXhT. The answer may be large, so please print its remainder modulo 1 000 000 007 (109 + 7). Can you compute it faster than Dreamoon? Input The single line of the input contains two integers a, b (1 ≤ a, b ≤ 107). Output Print a single integer representing the answer modulo 1 000 000 007 (109 + 7). Examples Input 1 1 Output 0 Input 2 2 Output 8 Note For the first sample, there are no nice integers because <image> is always zero. For the second sample, the set of nice integers is {3, 5}. Submitted Solution: ``` a,b=map(int, input().split()) m=1000000007 B = int((b*(b-1)/2) % m ); A1 = int((a*(a+1)/2) % m ); A = int((A1*b+a) % m ); res = int((A*B) % m) ;#Is the operation divided in fractions of it print(res) ``` Yes
94,777
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a]. By <image> we denote the quotient of integer division of x and y. By <image> we denote the remainder of integer division of x and y. You can read more about these operations here: http://goo.gl/AcsXhT. The answer may be large, so please print its remainder modulo 1 000 000 007 (109 + 7). Can you compute it faster than Dreamoon? Input The single line of the input contains two integers a, b (1 ≤ a, b ≤ 107). Output Print a single integer representing the answer modulo 1 000 000 007 (109 + 7). Examples Input 1 1 Output 0 Input 2 2 Output 8 Note For the first sample, there are no nice integers because <image> is always zero. For the second sample, the set of nice integers is {3, 5}. Submitted Solution: ``` x=[int(i) for i in input().split()] a=x[0] b=x[1] x = ((b*(b-1))//2)%(1000000007) y = (a + (b*a*(a+1))//2)%(1000000007) print((x*y)%(1000000007)) ``` Yes
94,778
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a]. By <image> we denote the quotient of integer division of x and y. By <image> we denote the remainder of integer division of x and y. You can read more about these operations here: http://goo.gl/AcsXhT. The answer may be large, so please print its remainder modulo 1 000 000 007 (109 + 7). Can you compute it faster than Dreamoon? Input The single line of the input contains two integers a, b (1 ≤ a, b ≤ 107). Output Print a single integer representing the answer modulo 1 000 000 007 (109 + 7). Examples Input 1 1 Output 0 Input 2 2 Output 8 Note For the first sample, there are no nice integers because <image> is always zero. For the second sample, the set of nice integers is {3, 5}. Submitted Solution: ``` ''' Created on Oct 12, 2014 @author: Ismael ''' #import time MOD = 10**9+7 def sumTermsArith1(firstTerm,r,nbTerms): return (nbTerms*(2*firstTerm+(nbTerms-1)*r))//2 def solve(a,b): s = 0 for rem in range(1,b): reason = rem*b s = (s+sumTermsArith1(reason+rem,reason,a))%MOD return s def solve2(a,b): reason = a*(b*(a+1)+2)//2 return sumTermsArith1(reason,reason,b-1)%MOD #t = time.clock() a,b = map(int,input().split()) #sol1 = solve(a,b) sol2 = solve2(a,b) print(sol2) #print(sol1 == sol2) #print(time.clock()-t) ``` Yes
94,779
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a]. By <image> we denote the quotient of integer division of x and y. By <image> we denote the remainder of integer division of x and y. You can read more about these operations here: http://goo.gl/AcsXhT. The answer may be large, so please print its remainder modulo 1 000 000 007 (109 + 7). Can you compute it faster than Dreamoon? Input The single line of the input contains two integers a, b (1 ≤ a, b ≤ 107). Output Print a single integer representing the answer modulo 1 000 000 007 (109 + 7). Examples Input 1 1 Output 0 Input 2 2 Output 8 Note For the first sample, there are no nice integers because <image> is always zero. For the second sample, the set of nice integers is {3, 5}. Submitted Solution: ``` from sys import stdin from sys import stdout def get(): return stdin.readline().strip() def getf(): return [int(i) for i in get().split()] def put(a, end = "\n"): stdout.write(str(a) + end) def putf(a): stdout.write(" ".join([str(i) for i in a]) + "\n") def main(): a, b = getf() m = 1000000007 ans = (b * (b - 1) // 2) * a * (1 + b * (a + 1) // 2) % m put(ans) main() ``` No
94,780
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a]. By <image> we denote the quotient of integer division of x and y. By <image> we denote the remainder of integer division of x and y. You can read more about these operations here: http://goo.gl/AcsXhT. The answer may be large, so please print its remainder modulo 1 000 000 007 (109 + 7). Can you compute it faster than Dreamoon? Input The single line of the input contains two integers a, b (1 ≤ a, b ≤ 107). Output Print a single integer representing the answer modulo 1 000 000 007 (109 + 7). Examples Input 1 1 Output 0 Input 2 2 Output 8 Note For the first sample, there are no nice integers because <image> is always zero. For the second sample, the set of nice integers is {3, 5}. Submitted Solution: ``` import sys import math MAXNUM = math.inf MINNUM = -1 * math.inf ASCIILOWER = 97 ASCIIUPPER = 65 MODMAX = 1000000007 def getInt(): return int(sys.stdin.readline().rstrip()) def getInts(): return map(int, sys.stdin.readline().rstrip().split(" ")) def getString(): return sys.stdin.readline().rstrip() def printOutput(ans): sys.stdout.write() pass def termadd(n): return (n * (n + 1)) // 2 def solve(a, b): multtotal = 0 addtotal = 0 divadd = 1 while divadd < b and a // divadd != 0: multtotal += (termadd(a // divadd) * divadd) % MODMAX addtotal += ((a // divadd) * divadd) % MODMAX divadd += 1 multtotal *= b return (addtotal + multtotal) % MODMAX def readinput(): a, b = getInts() print(solve(a, b)) readinput() ``` No
94,781
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a]. By <image> we denote the quotient of integer division of x and y. By <image> we denote the remainder of integer division of x and y. You can read more about these operations here: http://goo.gl/AcsXhT. The answer may be large, so please print its remainder modulo 1 000 000 007 (109 + 7). Can you compute it faster than Dreamoon? Input The single line of the input contains two integers a, b (1 ≤ a, b ≤ 107). Output Print a single integer representing the answer modulo 1 000 000 007 (109 + 7). Examples Input 1 1 Output 0 Input 2 2 Output 8 Note For the first sample, there are no nice integers because <image> is always zero. For the second sample, the set of nice integers is {3, 5}. Submitted Solution: ``` a,b=map(int, input().split()) k=1 res=0 while k<=a: res+=((k*b)+1)*((b*(b-1))/2) k+=1 print(int(res)) ``` No
94,782
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a]. By <image> we denote the quotient of integer division of x and y. By <image> we denote the remainder of integer division of x and y. You can read more about these operations here: http://goo.gl/AcsXhT. The answer may be large, so please print its remainder modulo 1 000 000 007 (109 + 7). Can you compute it faster than Dreamoon? Input The single line of the input contains two integers a, b (1 ≤ a, b ≤ 107). Output Print a single integer representing the answer modulo 1 000 000 007 (109 + 7). Examples Input 1 1 Output 0 Input 2 2 Output 8 Note For the first sample, there are no nice integers because <image> is always zero. For the second sample, the set of nice integers is {3, 5}. Submitted Solution: ``` mod =10**9+7 b,x = map(int,input().split()) t = (b*(b-1)/2)%mod ans = (t * ((x *(x+1)/2 * b) %mod+ x))%mod print(int(ans)) ``` No
94,783
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1 × n square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petya’s aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win. Input The first line contains number n (1 ≤ n ≤ 1000) which represents the stripe’s length. The second line contains exactly n symbols — the line’s initial coloring. 0 corresponds to a white square, 1 corresponds to a black one. Output If Petya cannot win with such an initial coloring, print -1. Otherwise print the minimum number of moves Petya needs to win. Examples Input 6 111010 Output 1 Input 5 10001 Output 1 Input 7 1100010 Output 2 Input 5 00100 Output 2 Note In the first sample Petya can take squares 1 and 2. He repaints square 1 to black and square 2 to white. In the second sample Petya can take squares 2 and 3. He repaints square 2 to white and square 3 to black. Tags: brute force, dp, implementation Correct Solution: ``` n = int(input()) stripe = list(input()) for i in range(n): stripe[i] = int(stripe[i]) w = 0 b = 0 for i in range(n): if i % 2 == stripe[i] - 0: w += 1 else: b += 1 answer = min (w, b) print(answer) ```
94,784
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1 × n square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petya’s aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win. Input The first line contains number n (1 ≤ n ≤ 1000) which represents the stripe’s length. The second line contains exactly n symbols — the line’s initial coloring. 0 corresponds to a white square, 1 corresponds to a black one. Output If Petya cannot win with such an initial coloring, print -1. Otherwise print the minimum number of moves Petya needs to win. Examples Input 6 111010 Output 1 Input 5 10001 Output 1 Input 7 1100010 Output 2 Input 5 00100 Output 2 Note In the first sample Petya can take squares 1 and 2. He repaints square 1 to black and square 2 to white. In the second sample Petya can take squares 2 and 3. He repaints square 2 to white and square 3 to black. Tags: brute force, dp, implementation Correct Solution: ``` n=int(input()) s=input() t=0 for i in range(n): if (i+1)%2==0 and s[i]=="1" or (i+1)%2==1 and s[i]=="0": t+=1 print(min(t,n-t)) ```
94,785
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1 × n square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petya’s aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win. Input The first line contains number n (1 ≤ n ≤ 1000) which represents the stripe’s length. The second line contains exactly n symbols — the line’s initial coloring. 0 corresponds to a white square, 1 corresponds to a black one. Output If Petya cannot win with such an initial coloring, print -1. Otherwise print the minimum number of moves Petya needs to win. Examples Input 6 111010 Output 1 Input 5 10001 Output 1 Input 7 1100010 Output 2 Input 5 00100 Output 2 Note In the first sample Petya can take squares 1 and 2. He repaints square 1 to black and square 2 to white. In the second sample Petya can take squares 2 and 3. He repaints square 2 to white and square 3 to black. Tags: brute force, dp, implementation Correct Solution: ``` import sys from array import array # noqa: F401 from itertools import product def input(): return sys.stdin.buffer.readline().decode('utf-8') n = int(input()) s = list(map(int, input().rstrip())) if n <= 2: if n == 1 or s[0] != s[1]: print(0) else: print(1) exit() inf = 10**9 dp = [inf] * 4 dp[2 * s[0] + s[1]] = 0 for index, d in enumerate(s[2:], start=2): next_dp = [inf] * 4 for i, j in product((0, 2), (0, 1)): if i == j * 2: next_dp[(j ^ 1) * 2 + d] = min(next_dp[(j ^ 1) * 2 + d], dp[i + j] + 1, dp[i + j] + index - 1) next_dp[j * 2 + d] = min(next_dp[j * 2 + d], dp[i + j] + index - 1) else: next_dp[j * 2 + d] = min(next_dp[j * 2 + d], dp[i + j]) if j == d: next_dp[(j ^ 1) * 2 + d] = min(next_dp[(j ^ 1) * 2 + d], dp[i + j] + index) dp = next_dp ans = min( dp[0] + 1, dp[1], dp[2], dp[3] + 1 ) print(ans if ans < inf else -1) ```
94,786
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1 × n square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petya’s aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win. Input The first line contains number n (1 ≤ n ≤ 1000) which represents the stripe’s length. The second line contains exactly n symbols — the line’s initial coloring. 0 corresponds to a white square, 1 corresponds to a black one. Output If Petya cannot win with such an initial coloring, print -1. Otherwise print the minimum number of moves Petya needs to win. Examples Input 6 111010 Output 1 Input 5 10001 Output 1 Input 7 1100010 Output 2 Input 5 00100 Output 2 Note In the first sample Petya can take squares 1 and 2. He repaints square 1 to black and square 2 to white. In the second sample Petya can take squares 2 and 3. He repaints square 2 to white and square 3 to black. Tags: brute force, dp, implementation Correct Solution: ``` n = int(input()) s = input() l = [] for i in range(n): l.append(int(s[i])) ans = 0 for i in range(1, n): if l[i] == l[i-1]: l[i] ^= 1 ans = ans+1 print(min(ans, n-ans)) # Made By Mostafa_Khaled ```
94,787
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1 × n square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petya’s aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win. Input The first line contains number n (1 ≤ n ≤ 1000) which represents the stripe’s length. The second line contains exactly n symbols — the line’s initial coloring. 0 corresponds to a white square, 1 corresponds to a black one. Output If Petya cannot win with such an initial coloring, print -1. Otherwise print the minimum number of moves Petya needs to win. Examples Input 6 111010 Output 1 Input 5 10001 Output 1 Input 7 1100010 Output 2 Input 5 00100 Output 2 Note In the first sample Petya can take squares 1 and 2. He repaints square 1 to black and square 2 to white. In the second sample Petya can take squares 2 and 3. He repaints square 2 to white and square 3 to black. Tags: brute force, dp, implementation Correct Solution: ``` input() a = list(input()) l = len(a) if l % 2 == 0: s = list("10" * (l // 2)) d = list("01" * (l // 2)) else: s = list("10" * (l // 2) + "1") d = list("01" * (l // 2) + "0") d_s = 0 d_d = 0 for i in range(len(a)): if a[i] != s[i]: d_s += 1 if a[i] != d[i]: d_d += 1 print(min(d_s,d_d)) ```
94,788
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1 × n square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petya’s aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win. Input The first line contains number n (1 ≤ n ≤ 1000) which represents the stripe’s length. The second line contains exactly n symbols — the line’s initial coloring. 0 corresponds to a white square, 1 corresponds to a black one. Output If Petya cannot win with such an initial coloring, print -1. Otherwise print the minimum number of moves Petya needs to win. Examples Input 6 111010 Output 1 Input 5 10001 Output 1 Input 7 1100010 Output 2 Input 5 00100 Output 2 Note In the first sample Petya can take squares 1 and 2. He repaints square 1 to black and square 2 to white. In the second sample Petya can take squares 2 and 3. He repaints square 2 to white and square 3 to black. Tags: brute force, dp, implementation Correct Solution: ``` n = int(input()) s = input() l = [] for i in range(n): l.append(int(s[i])) ans = 0 for i in range(1, n): if l[i] == l[i-1]: l[i] ^= 1 ans = ans+1 print(min(ans, n-ans)) ```
94,789
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1 × n square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petya’s aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win. Input The first line contains number n (1 ≤ n ≤ 1000) which represents the stripe’s length. The second line contains exactly n symbols — the line’s initial coloring. 0 corresponds to a white square, 1 corresponds to a black one. Output If Petya cannot win with such an initial coloring, print -1. Otherwise print the minimum number of moves Petya needs to win. Examples Input 6 111010 Output 1 Input 5 10001 Output 1 Input 7 1100010 Output 2 Input 5 00100 Output 2 Note In the first sample Petya can take squares 1 and 2. He repaints square 1 to black and square 2 to white. In the second sample Petya can take squares 2 and 3. He repaints square 2 to white and square 3 to black. Tags: brute force, dp, implementation Correct Solution: ``` n = int(input()) seq = input() seq = [int(x) for x in seq] count = [[0,0],[0,0]] for i in range(n): count[i%2][seq[i]] += 1 m1 = count[0][1] + count[1][0] m2 = count[0][0] + count[1][1] print(min(m1,m2)) ```
94,790
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1 × n square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petya’s aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win. Input The first line contains number n (1 ≤ n ≤ 1000) which represents the stripe’s length. The second line contains exactly n symbols — the line’s initial coloring. 0 corresponds to a white square, 1 corresponds to a black one. Output If Petya cannot win with such an initial coloring, print -1. Otherwise print the minimum number of moves Petya needs to win. Examples Input 6 111010 Output 1 Input 5 10001 Output 1 Input 7 1100010 Output 2 Input 5 00100 Output 2 Note In the first sample Petya can take squares 1 and 2. He repaints square 1 to black and square 2 to white. In the second sample Petya can take squares 2 and 3. He repaints square 2 to white and square 3 to black. Tags: brute force, dp, implementation Correct Solution: ``` n=int(input()) def hamming(a,b): global n ret=0 for i in range(n): ret+=int(a[i]!=b[i]) return ret s=input() a=['0' if q%2==0 else '1' for q in range(n)] b=['0' if q%2==1 else '1' for q in range(n)] print(min(hamming(s,a),hamming(s,b))) ```
94,791
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1 × n square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petya’s aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win. Input The first line contains number n (1 ≤ n ≤ 1000) which represents the stripe’s length. The second line contains exactly n symbols — the line’s initial coloring. 0 corresponds to a white square, 1 corresponds to a black one. Output If Petya cannot win with such an initial coloring, print -1. Otherwise print the minimum number of moves Petya needs to win. Examples Input 6 111010 Output 1 Input 5 10001 Output 1 Input 7 1100010 Output 2 Input 5 00100 Output 2 Note In the first sample Petya can take squares 1 and 2. He repaints square 1 to black and square 2 to white. In the second sample Petya can take squares 2 and 3. He repaints square 2 to white and square 3 to black. Submitted Solution: ``` n=int(input()) x=str(input()) dp1,dp2=0,0 for i in range(n): if i%2==0: if x[i]=="0": dp1+=1 else: dp2+=1 if i%2==1: if x[i]=="0": dp2+=1 else: dp1+=1 print(min(dp1,dp2)) ``` Yes
94,792
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1 × n square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petya’s aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win. Input The first line contains number n (1 ≤ n ≤ 1000) which represents the stripe’s length. The second line contains exactly n symbols — the line’s initial coloring. 0 corresponds to a white square, 1 corresponds to a black one. Output If Petya cannot win with such an initial coloring, print -1. Otherwise print the minimum number of moves Petya needs to win. Examples Input 6 111010 Output 1 Input 5 10001 Output 1 Input 7 1100010 Output 2 Input 5 00100 Output 2 Note In the first sample Petya can take squares 1 and 2. He repaints square 1 to black and square 2 to white. In the second sample Petya can take squares 2 and 3. He repaints square 2 to white and square 3 to black. Submitted Solution: ``` n = int(input());s2 = "";s1 = "";bit=input();s1+='0' for i in range(1,n): if(s1[i-1] == '0'): s1+='1' else: s1+='0' s2+='1' for i in range(1,n): if(s2[i-1] == '0'): s2+='1' else: s2+='0' #print(s1,s2) cnt1 = 0;cnt2 = 0 for i in range(0,n): if(bit[i]!=s1[i]): cnt1+=1; for i in range(0,n): if(bit[i]!=s2[i]): cnt2+=1; print(min(cnt1,cnt2)) ``` Yes
94,793
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1 × n square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petya’s aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win. Input The first line contains number n (1 ≤ n ≤ 1000) which represents the stripe’s length. The second line contains exactly n symbols — the line’s initial coloring. 0 corresponds to a white square, 1 corresponds to a black one. Output If Petya cannot win with such an initial coloring, print -1. Otherwise print the minimum number of moves Petya needs to win. Examples Input 6 111010 Output 1 Input 5 10001 Output 1 Input 7 1100010 Output 2 Input 5 00100 Output 2 Note In the first sample Petya can take squares 1 and 2. He repaints square 1 to black and square 2 to white. In the second sample Petya can take squares 2 and 3. He repaints square 2 to white and square 3 to black. Submitted Solution: ``` def do(s, n): for i in range(1, n): if s[i-1] == '0': s += '1' else : s += '0' return s n = int(input()) ss = input() str1 = "1"; s1 = do(str1, n) str1 = "0" s2 = do(str1, n) cnt = 0 cnt1 = 0 for i in range(0, n): if ss[i] != s1[i]: cnt += 1 for i in range(0, n): if ss[i] != s2[i]: cnt1 += 1 print(min(cnt, cnt1)) ``` Yes
94,794
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1 × n square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petya’s aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win. Input The first line contains number n (1 ≤ n ≤ 1000) which represents the stripe’s length. The second line contains exactly n symbols — the line’s initial coloring. 0 corresponds to a white square, 1 corresponds to a black one. Output If Petya cannot win with such an initial coloring, print -1. Otherwise print the minimum number of moves Petya needs to win. Examples Input 6 111010 Output 1 Input 5 10001 Output 1 Input 7 1100010 Output 2 Input 5 00100 Output 2 Note In the first sample Petya can take squares 1 and 2. He repaints square 1 to black and square 2 to white. In the second sample Petya can take squares 2 and 3. He repaints square 2 to white and square 3 to black. Submitted Solution: ``` #Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction from collections import defaultdict BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #-------------------game starts now----------------------------------------------------- n=int(input()) s=list(input()) s=[int(s[i]) for i in range(n)] ans=0 for i in range(n): if i%2==0: ans+=s[i] else: ans+=1-s[i] m=ans ans=0 for i in range(n): if i%2==0: ans+=1-s[i] else: ans+=s[i] print(min(m,ans)) ``` Yes
94,795
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1 × n square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petya’s aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win. Input The first line contains number n (1 ≤ n ≤ 1000) which represents the stripe’s length. The second line contains exactly n symbols — the line’s initial coloring. 0 corresponds to a white square, 1 corresponds to a black one. Output If Petya cannot win with such an initial coloring, print -1. Otherwise print the minimum number of moves Petya needs to win. Examples Input 6 111010 Output 1 Input 5 10001 Output 1 Input 7 1100010 Output 2 Input 5 00100 Output 2 Note In the first sample Petya can take squares 1 and 2. He repaints square 1 to black and square 2 to white. In the second sample Petya can take squares 2 and 3. He repaints square 2 to white and square 3 to black. Submitted Solution: ``` import sys from array import array # noqa: F401 from itertools import product def input(): return sys.stdin.buffer.readline().decode('utf-8') n = int(input()) s = list(map(int, input().rstrip())) if n <= 2: if n == 1 or s[0] != s[1]: print(0) else: print(1) exit() inf = 10**9 dp = [inf] * 4 dp[2 * s[0] + s[1]] = 0 if s[0] == s[1]: dp[1] = dp[2] = 1 for d in s[2:]: next_dp = [inf] * 4 for i, j in product((0, 2), (0, 1)): if i == j * 2 or j == d: next_dp[(j ^ 1) * 2 + d] = min(next_dp[(j ^ 1) * 2 + d], dp[i + j] + 1) if j == d: next_dp[j * 2 + (d ^ 1)] = min(next_dp[j * 2 + (d ^ 1)], dp[i + j] + 1) if i != j * 2: next_dp[j * 2 + d] = min(next_dp[j * 2 + d], dp[i + j]) dp = next_dp ans = min( dp[0] + 1, dp[1], dp[2], dp[3] + 1 ) print(ans if ans < inf else -1) ``` No
94,796
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1 × n square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petya’s aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win. Input The first line contains number n (1 ≤ n ≤ 1000) which represents the stripe’s length. The second line contains exactly n symbols — the line’s initial coloring. 0 corresponds to a white square, 1 corresponds to a black one. Output If Petya cannot win with such an initial coloring, print -1. Otherwise print the minimum number of moves Petya needs to win. Examples Input 6 111010 Output 1 Input 5 10001 Output 1 Input 7 1100010 Output 2 Input 5 00100 Output 2 Note In the first sample Petya can take squares 1 and 2. He repaints square 1 to black and square 2 to white. In the second sample Petya can take squares 2 and 3. He repaints square 2 to white and square 3 to black. Submitted Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n avl=AvlTree() #-----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default='z', func=lambda a, b: min(a ,b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: a + b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left)/ 2) # Check if middle element is # less than or equal to key if (arr[mid]<=key): count = mid+1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def countGreater( arr,n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ n=int(input()) s=list(input()) s=[int(s[i]) for i in range(n)] ans=0 a=[] c=1 for i in range(1,n): if s[i-1]==s[i]: c+=1 else: a.append(c) c=1 if c>0: a.append(c) for i in range(len(a)): if a[i]==1: continue else: ans+=math.ceil(((a[i]-3)/2)+1) if i>0 and a[i-1]==1: if i<len(a)-1 and a[i+1]==1: if a[i]%2==0: ans+=1 print(ans) ``` No
94,797
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1 × n square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petya’s aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win. Input The first line contains number n (1 ≤ n ≤ 1000) which represents the stripe’s length. The second line contains exactly n symbols — the line’s initial coloring. 0 corresponds to a white square, 1 corresponds to a black one. Output If Petya cannot win with such an initial coloring, print -1. Otherwise print the minimum number of moves Petya needs to win. Examples Input 6 111010 Output 1 Input 5 10001 Output 1 Input 7 1100010 Output 2 Input 5 00100 Output 2 Note In the first sample Petya can take squares 1 and 2. He repaints square 1 to black and square 2 to white. In the second sample Petya can take squares 2 and 3. He repaints square 2 to white and square 3 to black. Submitted Solution: ``` import sys from array import array # noqa: F401 from itertools import product def input(): return sys.stdin.buffer.readline().decode('utf-8') n = int(input()) s = list(map(int, input().rstrip())) if n <= 2: if n == 1 or s[0] != s[1]: print(0) else: print(1) exit() inf = 10**9 dp = [inf] * 4 dp[2 * s[0] + s[1]] = 0 if s[0] == s[1]: dp[1] = dp[2] = 1 for d in s[2:]: next_dp = [inf] * 4 for i, j in product((0, 2), (0, 1)): if i == j * 2: next_dp[(j ^ 1) * 2 + d] = min(next_dp[(j ^ 1) * 2 + d], dp[i + j] + 1) else: next_dp[j * 2 + d] = min(next_dp[j * 2 + d], dp[i + j]) dp = next_dp ans = min( dp[0] + 1, dp[1], dp[2], dp[3] + 1 ) print(ans if ans < inf else -1) ``` No
94,798
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1 × n square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petya’s aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win. Input The first line contains number n (1 ≤ n ≤ 1000) which represents the stripe’s length. The second line contains exactly n symbols — the line’s initial coloring. 0 corresponds to a white square, 1 corresponds to a black one. Output If Petya cannot win with such an initial coloring, print -1. Otherwise print the minimum number of moves Petya needs to win. Examples Input 6 111010 Output 1 Input 5 10001 Output 1 Input 7 1100010 Output 2 Input 5 00100 Output 2 Note In the first sample Petya can take squares 1 and 2. He repaints square 1 to black and square 2 to white. In the second sample Petya can take squares 2 and 3. He repaints square 2 to white and square 3 to black. Submitted Solution: ``` #Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction from collections import defaultdict BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #-------------------game starts now----------------------------------------------------- n=int(input()) s=input() a=list() for i in s: a.append(int(i)) r=0 if a[0]==a[1] and n>2: r+=1 if a[1]==a[2]: a[1]=1-a[1] else: a[0]=1-a[0] for i in range (0,n-1): if a[i]==a[i+1]: r+=1 a[i+1]=1-a[i+1] print(r) ``` No
94,799