message
stringlengths
2
22.7k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
145
109k
cluster
float64
9
9
__index_level_0__
int64
290
217k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. n boys and m girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from 1 to n and all girls are numbered with integers from 1 to m. For all 1 ≤ i ≤ n the minimal number of sweets, which i-th boy presented to some girl is equal to b_i and for all 1 ≤ j ≤ m the maximal number of sweets, which j-th girl received from some boy is equal to g_j. More formally, let a_{i,j} be the number of sweets which the i-th boy give to the j-th girl. Then b_i is equal exactly to the minimum among values a_{i,1}, a_{i,2}, …, a_{i,m} and g_j is equal exactly to the maximum among values b_{1,j}, b_{2,j}, …, b_{n,j}. You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of a_{i,j} for all (i,j) such that 1 ≤ i ≤ n and 1 ≤ j ≤ m. You are given the numbers b_1, …, b_n and g_1, …, g_m, determine this number. Input The first line contains two integers n and m, separated with space — the number of boys and girls, respectively (2 ≤ n, m ≤ 100 000). The second line contains n integers b_1, …, b_n, separated by spaces — b_i is equal to the minimal number of sweets, which i-th boy presented to some girl (0 ≤ b_i ≤ 10^8). The third line contains m integers g_1, …, g_m, separated by spaces — g_j is equal to the maximal number of sweets, which j-th girl received from some boy (0 ≤ g_j ≤ 10^8). Output If the described situation is impossible, print -1. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied. Examples Input 3 2 1 2 1 3 4 Output 12 Input 2 2 0 1 1 0 Output -1 Input 2 3 1 0 1 1 2 Output 4 Note In the first test, the minimal total number of sweets, which boys could have presented is equal to 12. This can be possible, for example, if the first boy presented 1 and 4 sweets, the second boy presented 3 and 2 sweets and the third boy presented 1 and 1 sweets for the first and the second girl, respectively. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to 12. In the second test, the boys couldn't have presented sweets in such way, that all statements satisfied. In the third test, the minimal total number of sweets, which boys could have presented is equal to 4. This can be possible, for example, if the first boy presented 1, 1, 2 sweets for the first, second, third girl, respectively and the second boy didn't present sweets for each girl. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to 4. Submitted Solution: ``` import sys import collections import math import heapq import bisect from operator import itemgetter def getint(): return int(input()) def getints(): return [int(x) for x in input().split(' ')] n, m = getints() b = getints() g = getints() result = 0 bMax, bMax2, bSum = -1, -1, 0 for i, bb in enumerate(b): bSum += bb if bb > bMax: bMax2, bMax = bMax, bb elif bb > bMax2: bMax2 = bb gMin, gSum = float('inf'), 0 for j, gg in enumerate(g): gSum += gg if gg < gMin: gMin = gg if bMax > gMin: result = -1 else: result = bSum * m result += gSum result -= bMax * m if gMin > bMax: result += bMax - bMax2 print(str(result)) ```
instruction
0
103,759
9
207,518
Yes
output
1
103,759
9
207,519
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. n boys and m girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from 1 to n and all girls are numbered with integers from 1 to m. For all 1 ≤ i ≤ n the minimal number of sweets, which i-th boy presented to some girl is equal to b_i and for all 1 ≤ j ≤ m the maximal number of sweets, which j-th girl received from some boy is equal to g_j. More formally, let a_{i,j} be the number of sweets which the i-th boy give to the j-th girl. Then b_i is equal exactly to the minimum among values a_{i,1}, a_{i,2}, …, a_{i,m} and g_j is equal exactly to the maximum among values b_{1,j}, b_{2,j}, …, b_{n,j}. You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of a_{i,j} for all (i,j) such that 1 ≤ i ≤ n and 1 ≤ j ≤ m. You are given the numbers b_1, …, b_n and g_1, …, g_m, determine this number. Input The first line contains two integers n and m, separated with space — the number of boys and girls, respectively (2 ≤ n, m ≤ 100 000). The second line contains n integers b_1, …, b_n, separated by spaces — b_i is equal to the minimal number of sweets, which i-th boy presented to some girl (0 ≤ b_i ≤ 10^8). The third line contains m integers g_1, …, g_m, separated by spaces — g_j is equal to the maximal number of sweets, which j-th girl received from some boy (0 ≤ g_j ≤ 10^8). Output If the described situation is impossible, print -1. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied. Examples Input 3 2 1 2 1 3 4 Output 12 Input 2 2 0 1 1 0 Output -1 Input 2 3 1 0 1 1 2 Output 4 Note In the first test, the minimal total number of sweets, which boys could have presented is equal to 12. This can be possible, for example, if the first boy presented 1 and 4 sweets, the second boy presented 3 and 2 sweets and the third boy presented 1 and 1 sweets for the first and the second girl, respectively. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to 12. In the second test, the boys couldn't have presented sweets in such way, that all statements satisfied. In the third test, the minimal total number of sweets, which boys could have presented is equal to 4. This can be possible, for example, if the first boy presented 1, 1, 2 sweets for the first, second, third girl, respectively and the second boy didn't present sweets for each girl. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to 4. Submitted Solution: ``` from sys import stdin from collections import deque mod = 10**9 + 7 # def rl(): # return [int(w) for w in stdin.readline().split()] from bisect import bisect_right from bisect import bisect_left from collections import defaultdict from math import sqrt,factorial,gcd,log2,inf,ceil # map(int,input().split()) # # l = list(map(int,input().split())) # from itertools import permutations import heapq # la = [] n,m = map(int,input().split()) l1 = list(map(int,input().split())) l2 = list(map(int,input().split())) l1.sort() l2.sort() hash = defaultdict(int) for i in l2: hash[i]+=1 if l1[-1]<=l2[0]: z = sum(l2) seti = set() i = -1 j = -1 ans = 0 while True: if i == -len(l1)-1 or j == -len(l2)-1: break if l2[j] in seti: seti.remove(l2[j]) hash[l2[j]]-=1 j-=1 continue seti.add(l1[i]) z = 0 if hash[l1[i]]>0: z = 1 ans+= l1[i] + l2[j] + l1[i]*(m-2 - z) # print(i,j) i-=1 j-=1 while i!=-len(l1)-1: ans+=2*(l1[i]) i-=1 while j!=-len(l2)-1: ans+=2*(l2[j]) j-=1 print(ans) else: print(-1) exit() ```
instruction
0
103,760
9
207,520
No
output
1
103,760
9
207,521
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. n boys and m girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from 1 to n and all girls are numbered with integers from 1 to m. For all 1 ≤ i ≤ n the minimal number of sweets, which i-th boy presented to some girl is equal to b_i and for all 1 ≤ j ≤ m the maximal number of sweets, which j-th girl received from some boy is equal to g_j. More formally, let a_{i,j} be the number of sweets which the i-th boy give to the j-th girl. Then b_i is equal exactly to the minimum among values a_{i,1}, a_{i,2}, …, a_{i,m} and g_j is equal exactly to the maximum among values b_{1,j}, b_{2,j}, …, b_{n,j}. You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of a_{i,j} for all (i,j) such that 1 ≤ i ≤ n and 1 ≤ j ≤ m. You are given the numbers b_1, …, b_n and g_1, …, g_m, determine this number. Input The first line contains two integers n and m, separated with space — the number of boys and girls, respectively (2 ≤ n, m ≤ 100 000). The second line contains n integers b_1, …, b_n, separated by spaces — b_i is equal to the minimal number of sweets, which i-th boy presented to some girl (0 ≤ b_i ≤ 10^8). The third line contains m integers g_1, …, g_m, separated by spaces — g_j is equal to the maximal number of sweets, which j-th girl received from some boy (0 ≤ g_j ≤ 10^8). Output If the described situation is impossible, print -1. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied. Examples Input 3 2 1 2 1 3 4 Output 12 Input 2 2 0 1 1 0 Output -1 Input 2 3 1 0 1 1 2 Output 4 Note In the first test, the minimal total number of sweets, which boys could have presented is equal to 12. This can be possible, for example, if the first boy presented 1 and 4 sweets, the second boy presented 3 and 2 sweets and the third boy presented 1 and 1 sweets for the first and the second girl, respectively. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to 12. In the second test, the boys couldn't have presented sweets in such way, that all statements satisfied. In the third test, the minimal total number of sweets, which boys could have presented is equal to 4. This can be possible, for example, if the first boy presented 1, 1, 2 sweets for the first, second, third girl, respectively and the second boy didn't present sweets for each girl. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to 4. Submitted Solution: ``` n,m=map(int,input().split()) b=list(map(int,input().split())) g=list(map(int,input().split())) b.sort() g.sort() if max(b)>min(g): print(-1) else: ans=m*sum(b) for i in g: if i==b[-1]: m-=1 if m%2==0: c=(m//2)*(b[-1]+b[-2]) else: c=b[-1]+(m//2)*(b[-1]+b[-2]) print(ans-c+sum(g[-m:])) ```
instruction
0
103,761
9
207,522
No
output
1
103,761
9
207,523
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. n boys and m girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from 1 to n and all girls are numbered with integers from 1 to m. For all 1 ≤ i ≤ n the minimal number of sweets, which i-th boy presented to some girl is equal to b_i and for all 1 ≤ j ≤ m the maximal number of sweets, which j-th girl received from some boy is equal to g_j. More formally, let a_{i,j} be the number of sweets which the i-th boy give to the j-th girl. Then b_i is equal exactly to the minimum among values a_{i,1}, a_{i,2}, …, a_{i,m} and g_j is equal exactly to the maximum among values b_{1,j}, b_{2,j}, …, b_{n,j}. You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of a_{i,j} for all (i,j) such that 1 ≤ i ≤ n and 1 ≤ j ≤ m. You are given the numbers b_1, …, b_n and g_1, …, g_m, determine this number. Input The first line contains two integers n and m, separated with space — the number of boys and girls, respectively (2 ≤ n, m ≤ 100 000). The second line contains n integers b_1, …, b_n, separated by spaces — b_i is equal to the minimal number of sweets, which i-th boy presented to some girl (0 ≤ b_i ≤ 10^8). The third line contains m integers g_1, …, g_m, separated by spaces — g_j is equal to the maximal number of sweets, which j-th girl received from some boy (0 ≤ g_j ≤ 10^8). Output If the described situation is impossible, print -1. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied. Examples Input 3 2 1 2 1 3 4 Output 12 Input 2 2 0 1 1 0 Output -1 Input 2 3 1 0 1 1 2 Output 4 Note In the first test, the minimal total number of sweets, which boys could have presented is equal to 12. This can be possible, for example, if the first boy presented 1 and 4 sweets, the second boy presented 3 and 2 sweets and the third boy presented 1 and 1 sweets for the first and the second girl, respectively. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to 12. In the second test, the boys couldn't have presented sweets in such way, that all statements satisfied. In the third test, the minimal total number of sweets, which boys could have presented is equal to 4. This can be possible, for example, if the first boy presented 1, 1, 2 sweets for the first, second, third girl, respectively and the second boy didn't present sweets for each girl. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to 4. Submitted Solution: ``` n,m=map(int,input().split()) a=[int(s) for s in input().split()] b=[int(s) for s in input().split()] if max(a)>min(b): print(-1) else: a.sort() ans=sum(b) for i in range(n-2): ans+=a[i]*m if a[n-1]!=b[0]: ans+=a[n-1]+a[n-2]*(m-1) else: ans+=a[n-2]*m print(ans) ```
instruction
0
103,762
9
207,524
No
output
1
103,762
9
207,525
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. n boys and m girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from 1 to n and all girls are numbered with integers from 1 to m. For all 1 ≤ i ≤ n the minimal number of sweets, which i-th boy presented to some girl is equal to b_i and for all 1 ≤ j ≤ m the maximal number of sweets, which j-th girl received from some boy is equal to g_j. More formally, let a_{i,j} be the number of sweets which the i-th boy give to the j-th girl. Then b_i is equal exactly to the minimum among values a_{i,1}, a_{i,2}, …, a_{i,m} and g_j is equal exactly to the maximum among values b_{1,j}, b_{2,j}, …, b_{n,j}. You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of a_{i,j} for all (i,j) such that 1 ≤ i ≤ n and 1 ≤ j ≤ m. You are given the numbers b_1, …, b_n and g_1, …, g_m, determine this number. Input The first line contains two integers n and m, separated with space — the number of boys and girls, respectively (2 ≤ n, m ≤ 100 000). The second line contains n integers b_1, …, b_n, separated by spaces — b_i is equal to the minimal number of sweets, which i-th boy presented to some girl (0 ≤ b_i ≤ 10^8). The third line contains m integers g_1, …, g_m, separated by spaces — g_j is equal to the maximal number of sweets, which j-th girl received from some boy (0 ≤ g_j ≤ 10^8). Output If the described situation is impossible, print -1. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied. Examples Input 3 2 1 2 1 3 4 Output 12 Input 2 2 0 1 1 0 Output -1 Input 2 3 1 0 1 1 2 Output 4 Note In the first test, the minimal total number of sweets, which boys could have presented is equal to 12. This can be possible, for example, if the first boy presented 1 and 4 sweets, the second boy presented 3 and 2 sweets and the third boy presented 1 and 1 sweets for the first and the second girl, respectively. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to 12. In the second test, the boys couldn't have presented sweets in such way, that all statements satisfied. In the third test, the minimal total number of sweets, which boys could have presented is equal to 4. This can be possible, for example, if the first boy presented 1, 1, 2 sweets for the first, second, third girl, respectively and the second boy didn't present sweets for each girl. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to 4. Submitted Solution: ``` n, m = map(int, input().split()) B = list(map(int, input().split())) G = list(map(int, input().split())) if min(G) < max(B): print(-1) exit(0) cnt = 0 z = max(B) y = 0 f = 1 for i in B: if i != z: y = max(y, i) for i in G: if i == z: f = 0 cnt += i - z if f: cnt += z - y print(cnt + sum(B) * m) ```
instruction
0
103,763
9
207,526
No
output
1
103,763
9
207,527
Provide tags and a correct Python 3 solution for this coding contest problem. For he knew every Who down in Whoville beneath, Was busy now, hanging a mistletoe wreath. "And they're hanging their stockings!" he snarled with a sneer, "Tomorrow is Christmas! It's practically here!" Dr. Suess, How The Grinch Stole Christmas Christmas celebrations are coming to Whoville. Cindy Lou Who and her parents Lou Lou Who and Betty Lou Who decided to give sweets to all people in their street. They decided to give the residents of each house on the street, one kilogram of sweets. So they need as many kilos of sweets as there are homes on their street. The street, where the Lou Who family lives can be represented as n consecutive sections of equal length. You can go from any section to a neighbouring one in one unit of time. Each of the sections is one of three types: an empty piece of land, a house or a shop. Cindy Lou and her family can buy sweets in a shop, but no more than one kilogram of sweets in one shop (the vendors care about the residents of Whoville not to overeat on sweets). After the Lou Who family leave their home, they will be on the first section of the road. To get to this section of the road, they also require one unit of time. We can assume that Cindy and her mom and dad can carry an unlimited number of kilograms of sweets. Every time they are on a house section, they can give a kilogram of sweets to the inhabitants of the house, or they can simply move to another section. If the family have already given sweets to the residents of a house, they can't do it again. Similarly, if they are on the shop section, they can either buy a kilo of sweets in it or skip this shop. If they've bought a kilo of sweets in a shop, the seller of the shop remembered them and the won't sell them a single candy if they come again. The time to buy and give sweets can be neglected. The Lou Whos do not want the people of any house to remain without food. The Lou Whos want to spend no more than t time units of time to give out sweets, as they really want to have enough time to prepare for the Christmas celebration. In order to have time to give all the sweets, they may have to initially bring additional k kilos of sweets. Cindy Lou wants to know the minimum number of k kilos of sweets they need to take with them, to have time to give sweets to the residents of each house in their street. Your task is to write a program that will determine the minimum possible value of k. Input The first line of the input contains two space-separated integers n and t (2 ≤ n ≤ 5·105, 1 ≤ t ≤ 109). The second line of the input contains n characters, the i-th of them equals "H" (if the i-th segment contains a house), "S" (if the i-th segment contains a shop) or "." (if the i-th segment doesn't contain a house or a shop). It is guaranteed that there is at least one segment with a house. Output If there isn't a single value of k that makes it possible to give sweets to everybody in at most t units of time, print in a single line "-1" (without the quotes). Otherwise, print on a single line the minimum possible value of k. Examples Input 6 6 HSHSHS Output 1 Input 14 100 ...HHHSSS...SH Output 0 Input 23 50 HHSS.......SSHHHHHHHHHH Output 8 Note In the first example, there are as many stores, as houses. If the family do not take a single kilo of sweets from home, in order to treat the inhabitants of the first house, they will need to make at least one step back, and they have absolutely no time for it. If they take one kilogram of sweets, they won't need to go back. In the second example, the number of shops is equal to the number of houses and plenty of time. Available at all stores passing out candy in one direction and give them when passing in the opposite direction. In the third example, the shops on the street are fewer than houses. The Lou Whos have to take the missing number of kilograms of sweets with them from home.
instruction
0
103,961
9
207,922
Tags: binary search, greedy, implementation Correct Solution: ``` def check(n, casas): #print('n:',n) global T,N,street current = n time = T need = 0 last_house = 0 for ind, i in enumerate(street): time -= 1 if i == 'S': current += 1 elif i == 'H': need += 1 if need == 1: last_house = ind if need > 0 and current >= need: #print('p',time, ind-last_house) current -= need casas -= need need = 0 if casas > 0: if (ind-last_house)*2 >= N-last_house-1: time -= N-last_house-1 + N-ind-1 return time >= 0 time -= (ind-last_house)*2 else: time -= ind-last_house #print('lugar:',i,ind,current, time, need, last_house) if casas == 0: break #print(time) return time >= 0 and casas == 0 N,T = [int(i) for i in input().split()] street = input().rstrip('.') N = len(street) C = street.count('H') S = street.count('S') l = max(C-S, 0) r = 500005 #print(N, C) while l < r: mid = (l+r)//2 if check(mid, C): r = mid else: l = mid + 1 print(l if l < 500005 else -1) ```
output
1
103,961
9
207,923
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For he knew every Who down in Whoville beneath, Was busy now, hanging a mistletoe wreath. "And they're hanging their stockings!" he snarled with a sneer, "Tomorrow is Christmas! It's practically here!" Dr. Suess, How The Grinch Stole Christmas Christmas celebrations are coming to Whoville. Cindy Lou Who and her parents Lou Lou Who and Betty Lou Who decided to give sweets to all people in their street. They decided to give the residents of each house on the street, one kilogram of sweets. So they need as many kilos of sweets as there are homes on their street. The street, where the Lou Who family lives can be represented as n consecutive sections of equal length. You can go from any section to a neighbouring one in one unit of time. Each of the sections is one of three types: an empty piece of land, a house or a shop. Cindy Lou and her family can buy sweets in a shop, but no more than one kilogram of sweets in one shop (the vendors care about the residents of Whoville not to overeat on sweets). After the Lou Who family leave their home, they will be on the first section of the road. To get to this section of the road, they also require one unit of time. We can assume that Cindy and her mom and dad can carry an unlimited number of kilograms of sweets. Every time they are on a house section, they can give a kilogram of sweets to the inhabitants of the house, or they can simply move to another section. If the family have already given sweets to the residents of a house, they can't do it again. Similarly, if they are on the shop section, they can either buy a kilo of sweets in it or skip this shop. If they've bought a kilo of sweets in a shop, the seller of the shop remembered them and the won't sell them a single candy if they come again. The time to buy and give sweets can be neglected. The Lou Whos do not want the people of any house to remain without food. The Lou Whos want to spend no more than t time units of time to give out sweets, as they really want to have enough time to prepare for the Christmas celebration. In order to have time to give all the sweets, they may have to initially bring additional k kilos of sweets. Cindy Lou wants to know the minimum number of k kilos of sweets they need to take with them, to have time to give sweets to the residents of each house in their street. Your task is to write a program that will determine the minimum possible value of k. Input The first line of the input contains two space-separated integers n and t (2 ≤ n ≤ 5·105, 1 ≤ t ≤ 109). The second line of the input contains n characters, the i-th of them equals "H" (if the i-th segment contains a house), "S" (if the i-th segment contains a shop) or "." (if the i-th segment doesn't contain a house or a shop). It is guaranteed that there is at least one segment with a house. Output If there isn't a single value of k that makes it possible to give sweets to everybody in at most t units of time, print in a single line "-1" (without the quotes). Otherwise, print on a single line the minimum possible value of k. Examples Input 6 6 HSHSHS Output 1 Input 14 100 ...HHHSSS...SH Output 0 Input 23 50 HHSS.......SSHHHHHHHHHH Output 8 Note In the first example, there are as many stores, as houses. If the family do not take a single kilo of sweets from home, in order to treat the inhabitants of the first house, they will need to make at least one step back, and they have absolutely no time for it. If they take one kilogram of sweets, they won't need to go back. In the second example, the number of shops is equal to the number of houses and plenty of time. Available at all stores passing out candy in one direction and give them when passing in the opposite direction. In the third example, the shops on the street are fewer than houses. The Lou Whos have to take the missing number of kilograms of sweets with them from home. Submitted Solution: ``` def check(n, casas): #print('n:',n) global T,N,street current = n time = T need = 0 last_house = 0 for ind, i in enumerate(street): time -= 1 if i == 'S': current += 1 elif i == 'H': need += 1 if need == 1: last_house = ind if need > 0 and current >= need: #print('p',time, ind-last_house) current -= need casas -= need need = 0 if casas > 0: if (ind-last_house)*2 >= N-last_house-1: time -= N-last_house-1 + N-ind-1 return time >= 0 time -= (ind-last_house)*2 else: time -= ind-last_house #print('lugar:',i,ind,current, time, need, last_house) if casas == 0: break #print(time) return time >= 0 and casas == 0 N,T = [int(i) for i in input().split()] street = input().rstrip('.') N = len(street) C = street.count('H') S = street.count('S') l = C-S r = C #print(N, C) while l < r: mid = (l+r)//2 if check(mid, C): r = mid else: l = mid + 1 print(l if l < 500005 else -1) ```
instruction
0
103,962
9
207,924
No
output
1
103,962
9
207,925
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For he knew every Who down in Whoville beneath, Was busy now, hanging a mistletoe wreath. "And they're hanging their stockings!" he snarled with a sneer, "Tomorrow is Christmas! It's practically here!" Dr. Suess, How The Grinch Stole Christmas Christmas celebrations are coming to Whoville. Cindy Lou Who and her parents Lou Lou Who and Betty Lou Who decided to give sweets to all people in their street. They decided to give the residents of each house on the street, one kilogram of sweets. So they need as many kilos of sweets as there are homes on their street. The street, where the Lou Who family lives can be represented as n consecutive sections of equal length. You can go from any section to a neighbouring one in one unit of time. Each of the sections is one of three types: an empty piece of land, a house or a shop. Cindy Lou and her family can buy sweets in a shop, but no more than one kilogram of sweets in one shop (the vendors care about the residents of Whoville not to overeat on sweets). After the Lou Who family leave their home, they will be on the first section of the road. To get to this section of the road, they also require one unit of time. We can assume that Cindy and her mom and dad can carry an unlimited number of kilograms of sweets. Every time they are on a house section, they can give a kilogram of sweets to the inhabitants of the house, or they can simply move to another section. If the family have already given sweets to the residents of a house, they can't do it again. Similarly, if they are on the shop section, they can either buy a kilo of sweets in it or skip this shop. If they've bought a kilo of sweets in a shop, the seller of the shop remembered them and the won't sell them a single candy if they come again. The time to buy and give sweets can be neglected. The Lou Whos do not want the people of any house to remain without food. The Lou Whos want to spend no more than t time units of time to give out sweets, as they really want to have enough time to prepare for the Christmas celebration. In order to have time to give all the sweets, they may have to initially bring additional k kilos of sweets. Cindy Lou wants to know the minimum number of k kilos of sweets they need to take with them, to have time to give sweets to the residents of each house in their street. Your task is to write a program that will determine the minimum possible value of k. Input The first line of the input contains two space-separated integers n and t (2 ≤ n ≤ 5·105, 1 ≤ t ≤ 109). The second line of the input contains n characters, the i-th of them equals "H" (if the i-th segment contains a house), "S" (if the i-th segment contains a shop) or "." (if the i-th segment doesn't contain a house or a shop). It is guaranteed that there is at least one segment with a house. Output If there isn't a single value of k that makes it possible to give sweets to everybody in at most t units of time, print in a single line "-1" (without the quotes). Otherwise, print on a single line the minimum possible value of k. Examples Input 6 6 HSHSHS Output 1 Input 14 100 ...HHHSSS...SH Output 0 Input 23 50 HHSS.......SSHHHHHHHHHH Output 8 Note In the first example, there are as many stores, as houses. If the family do not take a single kilo of sweets from home, in order to treat the inhabitants of the first house, they will need to make at least one step back, and they have absolutely no time for it. If they take one kilogram of sweets, they won't need to go back. In the second example, the number of shops is equal to the number of houses and plenty of time. Available at all stores passing out candy in one direction and give them when passing in the opposite direction. In the third example, the shops on the street are fewer than houses. The Lou Whos have to take the missing number of kilograms of sweets with them from home. Submitted Solution: ``` def check(n, casas): global T current = n time = T + 1 need = 0 walk = 0 last_house = 0 for ind, i in enumerate(street): time -= 1 if i == 'S': current += 1 elif i == 'H': need += 1 if need == 1: last_house = ind if need > 0 and current >= need: #print(time, ind-last_house) current -= need casas -= need walk = 0 need = 0 if ind > last_house: time -= (ind-last_house) * 2 if casas == 0: time += 1 #print('lugar:',i,current, time, need, walk) if casas == 0: break #print(T-time) return time > 0 and casas == 0 N,T = [int(i) for i in input().split()] street = input() C = street.count('H') l = 0 r = 500005 while l < r: mid = (l+r)//2 if check(mid, C): r = mid else: l = mid + 1 print(l if l < 500005 else -1) ```
instruction
0
103,963
9
207,926
No
output
1
103,963
9
207,927
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For he knew every Who down in Whoville beneath, Was busy now, hanging a mistletoe wreath. "And they're hanging their stockings!" he snarled with a sneer, "Tomorrow is Christmas! It's practically here!" Dr. Suess, How The Grinch Stole Christmas Christmas celebrations are coming to Whoville. Cindy Lou Who and her parents Lou Lou Who and Betty Lou Who decided to give sweets to all people in their street. They decided to give the residents of each house on the street, one kilogram of sweets. So they need as many kilos of sweets as there are homes on their street. The street, where the Lou Who family lives can be represented as n consecutive sections of equal length. You can go from any section to a neighbouring one in one unit of time. Each of the sections is one of three types: an empty piece of land, a house or a shop. Cindy Lou and her family can buy sweets in a shop, but no more than one kilogram of sweets in one shop (the vendors care about the residents of Whoville not to overeat on sweets). After the Lou Who family leave their home, they will be on the first section of the road. To get to this section of the road, they also require one unit of time. We can assume that Cindy and her mom and dad can carry an unlimited number of kilograms of sweets. Every time they are on a house section, they can give a kilogram of sweets to the inhabitants of the house, or they can simply move to another section. If the family have already given sweets to the residents of a house, they can't do it again. Similarly, if they are on the shop section, they can either buy a kilo of sweets in it or skip this shop. If they've bought a kilo of sweets in a shop, the seller of the shop remembered them and the won't sell them a single candy if they come again. The time to buy and give sweets can be neglected. The Lou Whos do not want the people of any house to remain without food. The Lou Whos want to spend no more than t time units of time to give out sweets, as they really want to have enough time to prepare for the Christmas celebration. In order to have time to give all the sweets, they may have to initially bring additional k kilos of sweets. Cindy Lou wants to know the minimum number of k kilos of sweets they need to take with them, to have time to give sweets to the residents of each house in their street. Your task is to write a program that will determine the minimum possible value of k. Input The first line of the input contains two space-separated integers n and t (2 ≤ n ≤ 5·105, 1 ≤ t ≤ 109). The second line of the input contains n characters, the i-th of them equals "H" (if the i-th segment contains a house), "S" (if the i-th segment contains a shop) or "." (if the i-th segment doesn't contain a house or a shop). It is guaranteed that there is at least one segment with a house. Output If there isn't a single value of k that makes it possible to give sweets to everybody in at most t units of time, print in a single line "-1" (without the quotes). Otherwise, print on a single line the minimum possible value of k. Examples Input 6 6 HSHSHS Output 1 Input 14 100 ...HHHSSS...SH Output 0 Input 23 50 HHSS.......SSHHHHHHHHHH Output 8 Note In the first example, there are as many stores, as houses. If the family do not take a single kilo of sweets from home, in order to treat the inhabitants of the first house, they will need to make at least one step back, and they have absolutely no time for it. If they take one kilogram of sweets, they won't need to go back. In the second example, the number of shops is equal to the number of houses and plenty of time. Available at all stores passing out candy in one direction and give them when passing in the opposite direction. In the third example, the shops on the street are fewer than houses. The Lou Whos have to take the missing number of kilograms of sweets with them from home. Submitted Solution: ``` def check(n, casas): #print('n:',n) global T,N,street current = n time = T need = 0 last_house = 0 for ind, i in enumerate(street): time -= 1 if i == 'S': current += 1 elif i == 'H': need += 1 if need == 1: last_house = ind if need > 0 and current >= need: #print('p',time, ind-last_house) current -= need casas -= need need = 0 if casas > 0: if (ind-last_house)*2 >= N-last_house-1: time -= N-last_house-1 + N-ind-1 return time >= 0 time -= (ind-last_house)*2 else: time -= ind-last_house #print('lugar:',i,ind,current, time, need, last_house) if casas == 0: break #print(time) return time >= 0 and casas == 0 N,T = [int(i) for i in input().split()] street = input().rstrip('.') N = len(street) C = street.count('H') S = street.count('S') l = C-S r = 500005 #print(N, C) while l < r: mid = (l+r)//2 if check(mid, C): r = mid else: l = mid + 1 print(l if l < 500005 else -1) ```
instruction
0
103,964
9
207,928
No
output
1
103,964
9
207,929
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For he knew every Who down in Whoville beneath, Was busy now, hanging a mistletoe wreath. "And they're hanging their stockings!" he snarled with a sneer, "Tomorrow is Christmas! It's practically here!" Dr. Suess, How The Grinch Stole Christmas Christmas celebrations are coming to Whoville. Cindy Lou Who and her parents Lou Lou Who and Betty Lou Who decided to give sweets to all people in their street. They decided to give the residents of each house on the street, one kilogram of sweets. So they need as many kilos of sweets as there are homes on their street. The street, where the Lou Who family lives can be represented as n consecutive sections of equal length. You can go from any section to a neighbouring one in one unit of time. Each of the sections is one of three types: an empty piece of land, a house or a shop. Cindy Lou and her family can buy sweets in a shop, but no more than one kilogram of sweets in one shop (the vendors care about the residents of Whoville not to overeat on sweets). After the Lou Who family leave their home, they will be on the first section of the road. To get to this section of the road, they also require one unit of time. We can assume that Cindy and her mom and dad can carry an unlimited number of kilograms of sweets. Every time they are on a house section, they can give a kilogram of sweets to the inhabitants of the house, or they can simply move to another section. If the family have already given sweets to the residents of a house, they can't do it again. Similarly, if they are on the shop section, they can either buy a kilo of sweets in it or skip this shop. If they've bought a kilo of sweets in a shop, the seller of the shop remembered them and the won't sell them a single candy if they come again. The time to buy and give sweets can be neglected. The Lou Whos do not want the people of any house to remain without food. The Lou Whos want to spend no more than t time units of time to give out sweets, as they really want to have enough time to prepare for the Christmas celebration. In order to have time to give all the sweets, they may have to initially bring additional k kilos of sweets. Cindy Lou wants to know the minimum number of k kilos of sweets they need to take with them, to have time to give sweets to the residents of each house in their street. Your task is to write a program that will determine the minimum possible value of k. Input The first line of the input contains two space-separated integers n and t (2 ≤ n ≤ 5·105, 1 ≤ t ≤ 109). The second line of the input contains n characters, the i-th of them equals "H" (if the i-th segment contains a house), "S" (if the i-th segment contains a shop) or "." (if the i-th segment doesn't contain a house or a shop). It is guaranteed that there is at least one segment with a house. Output If there isn't a single value of k that makes it possible to give sweets to everybody in at most t units of time, print in a single line "-1" (without the quotes). Otherwise, print on a single line the minimum possible value of k. Examples Input 6 6 HSHSHS Output 1 Input 14 100 ...HHHSSS...SH Output 0 Input 23 50 HHSS.......SSHHHHHHHHHH Output 8 Note In the first example, there are as many stores, as houses. If the family do not take a single kilo of sweets from home, in order to treat the inhabitants of the first house, they will need to make at least one step back, and they have absolutely no time for it. If they take one kilogram of sweets, they won't need to go back. In the second example, the number of shops is equal to the number of houses and plenty of time. Available at all stores passing out candy in one direction and give them when passing in the opposite direction. In the third example, the shops on the street are fewer than houses. The Lou Whos have to take the missing number of kilograms of sweets with them from home. Submitted Solution: ``` def check(n, casas): #print('n:',n) global T,N current = n time = T need = 0 last_house = 0 for ind, i in enumerate(street): time -= 1 if i == 'S': current += 1 elif i == 'H': need += 1 if need == 1: last_house = ind if need > 0 and current >= need: #print('p',time, ind-last_house) current -= need casas -= need need = 0 if casas > 0: if (ind-last_house)*2 >= N-last_house-1: time -= N-last_house-1 + N-ind-1 casas = 0 break time -= (ind-last_house)*2 else: time -= ind-last_house #print('lugar:',i,ind,current, time, need, last_house) if casas == 0: break #print(time) return time >= 0 and casas == 0 N,T = [int(i) for i in input().split()] street = input().rstrip('.') N = len(street) C = street.count('H') l = 0 r = 500005 #print(N, C) while l < r: mid = (l+r)//2 if check(mid, C): r = mid else: l = mid + 1 print(l if l < 500005 else -1) ```
instruction
0
103,965
9
207,930
No
output
1
103,965
9
207,931
Provide a correct Python 3 solution for this coding contest problem. Today, Snuke will eat B pieces of black chocolate and W pieces of white chocolate for an afternoon snack. He will repeat the following procedure until there is no piece left: * Choose black or white with equal probability, and eat a piece of that color if it exists. For each integer i from 1 to B+W (inclusive), find the probability that the color of the i-th piece to be eaten is black. It can be shown that these probabilities are rational, and we ask you to print them modulo 10^9 + 7, as described in Notes. Constraints * All values in input are integers. * 1 \leq B,W \leq 10^{5} Input Input is given from Standard Input in the following format: B W Output Print the answers in B+W lines. In the i-th line, print the probability that the color of the i-th piece to be eaten is black, modulo 10^{9}+7. Examples Input 2 1 Output 500000004 750000006 750000006 Input 3 2 Output 500000004 500000004 625000005 187500002 187500002 Input 6 9 Output 500000004 500000004 500000004 500000004 500000004 500000004 929687507 218750002 224609377 303710940 633300786 694091802 172485353 411682132 411682132
instruction
0
104,247
9
208,494
"Correct Solution: ``` # D より思い付きやすい気がする class Combination: def __init__(self, n_max, mod=10**9+7): # O(n_max + log(mod)) self.mod = mod f = 1 self.fac = fac = [f] for i in range(1, n_max+1): f = f * i % mod fac.append(f) f = pow(f, mod-2, mod) self.facinv = facinv = [f] for i in range(n_max, 0, -1): f = f * i % mod facinv.append(f) facinv.reverse() # "n 要素" は区別できる n 要素 # "k グループ" はちょうど k グループ def __call__(self, n, r): # self.C と同じ return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod def C(self, n, r): if not 0 <= r <= n: return 0 return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod def P(self, n, r): if not 0 <= r <= n: return 0 return self.fac[n] * self.facinv[n-r] % self.mod def H(self, n, r): if (n == 0 and r > 0) or r < 0: return 0 return self.fac[n+r-1] * self.facinv[r] % self.mod * self.facinv[n-1] % self.mod def rising_factorial(self, n, r): # 上昇階乗冪 n * (n+1) * ... * (n+r-1) return self.fac[n+r-1] * self.facinv[n-1] % self.mod def stirling_first(self, n, k): # 第 1 種スターリング数 lru_cache を使うと O(nk) # n 要素を k 個の巡回列に分割する場合の数 if n == k: return 1 if k == 0: return 0 return (self.stirling_first(n-1, k-1) + (n-1)*self.stirling_first(n-1, k)) % self.mod def stirling_second(self, n, k): # 第 2 種スターリング数 O(k + log(n)) # n 要素を区別のない k グループに分割する場合の数 if n == k: return 1 # n==k==0 のときのため return self.facinv[k] * sum((-1)**(k-m) * self.C(k, m) * pow(m, n, self.mod) for m in range(1, k+1)) % self.mod def balls_and_boxes_3(self, n, k): # n 要素を区別のある k グループに分割する場合の数 O(k + log(n)) return sum((-1)**(k-m) * self.C(k, m) * pow(m, n, self.mod) for m in range(1, k+1)) % self.mod def bernoulli(self, n): # ベルヌーイ数 lru_cache を使うと O(n**2 * log(mod)) if n == 0: return 1 if n % 2 and n >= 3: return 0 # 高速化 return (- pow(n+1, self.mod-2, self.mod) * sum(self.C(n+1, k) * self.bernoulli(k) % self.mod for k in range(n))) % self.mod def faulhaber(self, k, n): # べき乗和 0^k + 1^k + ... + (n-1)^k # bernoulli に lru_cache を使うと O(k**2 * log(mod)) bernoulli が計算済みなら O(k * log(mod)) return pow(k+1, self.mod-2, self.mod) * sum(self.C(k+1, j) * self.bernoulli(j) % self.mod * pow(n, k-j+1, self.mod) % self.mod for j in range(k+1)) % self.mod def lah(self, n, k): # n 要素を k 個の空でない順序付き集合に分割する場合の数 O(1) return self.C(n-1, k-1) * self.fac[n] % self.mod * self.facinv[k] % self.mod def bell(self, n, k): # n 要素を k グループ以下に分割する場合の数 O(k**2 + k*log(mod)) return sum(self.stirling_second(n, j) for j in range(1, k+1)) % self.mod def main(): comb = Combination(2*10**5) mod = 10**9+7 B, W = map(int, input().split()) L = [0] * (B+W+1) for i in range(B, B+W): L[i+1] = -comb(i, B) for i in range(W, W+B): L[i+1] = (L[i+1] + comb(i, W)) % mod L_cum = [0] + L[:-1] for i in range(1, B+W+1): L_cum[i] = (L_cum[i] + 2 * L_cum[i-1]) % mod Ans = [] p = 1 half = pow(2, mod-2, mod) denom_inv = half for l, l_cum in zip(L[1:], L_cum[1:]): Ans.append((p+l+l_cum) * denom_inv % mod) p = p * 2 % mod denom_inv = denom_inv * half % mod print("\n".join(map(str, Ans))) main() ```
output
1
104,247
9
208,495
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Today, Snuke will eat B pieces of black chocolate and W pieces of white chocolate for an afternoon snack. He will repeat the following procedure until there is no piece left: * Choose black or white with equal probability, and eat a piece of that color if it exists. For each integer i from 1 to B+W (inclusive), find the probability that the color of the i-th piece to be eaten is black. It can be shown that these probabilities are rational, and we ask you to print them modulo 10^9 + 7, as described in Notes. Constraints * All values in input are integers. * 1 \leq B,W \leq 10^{5} Input Input is given from Standard Input in the following format: B W Output Print the answers in B+W lines. In the i-th line, print the probability that the color of the i-th piece to be eaten is black, modulo 10^{9}+7. Examples Input 2 1 Output 500000004 750000006 750000006 Input 3 2 Output 500000004 500000004 625000005 187500002 187500002 Input 6 9 Output 500000004 500000004 500000004 500000004 500000004 500000004 929687507 218750002 224609377 303710940 633300786 694091802 172485353 411682132 411682132 Submitted Solution: ``` INF = 1000000007 def ex_gcd(a, b): x1, x2 = 0, 1 y1, y2 = 1, 0 q = 0 while b: x1, x2 = x2, x1 - q * x2 y1, y2 = y2, y1 - q * y2 q = a // b a, b = b, a % b return a, x2, y2 def invert(x, mod=INF): return ex_gcd(x, mod)[1] % mod B, W = map(int, input().split()) p = 0 q = 0 c1, c2 = 0, 1 d1, d2 = 0, 1 s = 1 for k in range(1, B + W + 1): if B + 1 < k: c1 = c2 c2 *= invert((k - 1) - B) * (k - 1) % INF c2 %= INF if W + 1 < k: d1 = d2 d2 *= invert((k - 1) - W) * (k - 1) % INF d2 %= INF if B < k: p += (c2 - c1) * s % INF p %= INF if W < k: q += (d2 - d1) * s % INF q %= INF print((q + invert(2) * (1 - p - q)) % INF) s *= invert(2) s %= INF ```
instruction
0
104,248
9
208,496
Yes
output
1
104,248
9
208,497
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Today, Snuke will eat B pieces of black chocolate and W pieces of white chocolate for an afternoon snack. He will repeat the following procedure until there is no piece left: * Choose black or white with equal probability, and eat a piece of that color if it exists. For each integer i from 1 to B+W (inclusive), find the probability that the color of the i-th piece to be eaten is black. It can be shown that these probabilities are rational, and we ask you to print them modulo 10^9 + 7, as described in Notes. Constraints * All values in input are integers. * 1 \leq B,W \leq 10^{5} Input Input is given from Standard Input in the following format: B W Output Print the answers in B+W lines. In the i-th line, print the probability that the color of the i-th piece to be eaten is black, modulo 10^{9}+7. Examples Input 2 1 Output 500000004 750000006 750000006 Input 3 2 Output 500000004 500000004 625000005 187500002 187500002 Input 6 9 Output 500000004 500000004 500000004 500000004 500000004 500000004 929687507 218750002 224609377 303710940 633300786 694091802 172485353 411682132 411682132 Submitted Solution: ``` # -*- coding: utf-8 -*- """ Created on Sat Mar 30 22:26:37 2019 @author: Owner """ MOD = 1000000007 def inv(x): return pow(x, MOD - 2, MOD) B, W = map(int, input().split()) fct = [1] * (B + W + 1) for i in range(B + W): fct[i + 1] = (fct[i] * (i + 1)) % MOD def c(n, k): return (fct[n] * inv(fct[k]) * inv(fct[n - k])) % MOD #p[i]: 黒B回白i回の確率 #q[i]: 黒i回白W回の確率 p = [0] * W p[0] = inv(pow(2, B, MOD)) for i in range(W - 1): p[i + 1] = (p[i] + c(B + i, i + 1) * inv(pow(2, B + i, MOD)) * inv(2)) % MOD q = [0] * B q[0] = inv(pow(2, W, MOD)) for i in range(B - 1): q[i + 1] = (q[i] + c(W + i, i + 1) * inv(pow(2, W + i, MOD)) * inv(2)) % MOD for i in range(B + W): if i < min(B, W): print(inv(2)) continue if i >= max(B, W): print((q[i - W] + (1 - p[i - B] - q[i - W] + MOD) * inv(2)) % MOD) continue if B < W: print(((1 - p[i - B] + MOD) * inv(2)) % MOD) else: print((q[i - W] + (1 - q[i - W] + MOD) * inv(2)) % MOD) ```
instruction
0
104,249
9
208,498
Yes
output
1
104,249
9
208,499
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Today, Snuke will eat B pieces of black chocolate and W pieces of white chocolate for an afternoon snack. He will repeat the following procedure until there is no piece left: * Choose black or white with equal probability, and eat a piece of that color if it exists. For each integer i from 1 to B+W (inclusive), find the probability that the color of the i-th piece to be eaten is black. It can be shown that these probabilities are rational, and we ask you to print them modulo 10^9 + 7, as described in Notes. Constraints * All values in input are integers. * 1 \leq B,W \leq 10^{5} Input Input is given from Standard Input in the following format: B W Output Print the answers in B+W lines. In the i-th line, print the probability that the color of the i-th piece to be eaten is black, modulo 10^{9}+7. Examples Input 2 1 Output 500000004 750000006 750000006 Input 3 2 Output 500000004 500000004 625000005 187500002 187500002 Input 6 9 Output 500000004 500000004 500000004 500000004 500000004 500000004 929687507 218750002 224609377 303710940 633300786 694091802 172485353 411682132 411682132 Submitted Solution: ``` def cmb(n, r): if ( r<0 or r>n ): return 0 r = min(r, n-r) return g1[n] * g2[r] * g2[n-r] % mod mod = 10**9+7 #出力の制限 N = 2*10**5 g1 = [1, 1] # 元テーブル g2 = [1, 1] #逆元テーブル inverse = [0, 1] #逆元テーブル計算用テーブル for i in range( 2, N + 1 ): g1.append( ( g1[-1] * i ) % mod ) inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod ) g2.append( (g2[-1] * inverse[-1]) % mod ) b,w=map(int,input().split()) x=0 y=0 for i in range(1,b+w+1): x=(x*2+cmb(i-2,b-1))%mod y=(y*2+cmb(i-2,w-1))%mod print((mod+pow(2,i-1,mod)-x+y)*pow(pow(2,i,mod),mod-2,mod)%mod) ```
instruction
0
104,251
9
208,502
Yes
output
1
104,251
9
208,503
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Today, Snuke will eat B pieces of black chocolate and W pieces of white chocolate for an afternoon snack. He will repeat the following procedure until there is no piece left: * Choose black or white with equal probability, and eat a piece of that color if it exists. For each integer i from 1 to B+W (inclusive), find the probability that the color of the i-th piece to be eaten is black. It can be shown that these probabilities are rational, and we ask you to print them modulo 10^9 + 7, as described in Notes. Constraints * All values in input are integers. * 1 \leq B,W \leq 10^{5} Input Input is given from Standard Input in the following format: B W Output Print the answers in B+W lines. In the i-th line, print the probability that the color of the i-th piece to be eaten is black, modulo 10^{9}+7. Examples Input 2 1 Output 500000004 750000006 750000006 Input 3 2 Output 500000004 500000004 625000005 187500002 187500002 Input 6 9 Output 500000004 500000004 500000004 500000004 500000004 500000004 929687507 218750002 224609377 303710940 633300786 694091802 172485353 411682132 411682132 Submitted Solution: ``` B,W = map(int, input().split()) N = B+W factorial = [1] for i in range(N+1): factorial.append( factorial[-1] * (i+1)) # print(factorial) mod = 10**9+7 de_factorial = [0] * (N+1) de_factorial[N] = pow( factorial[N] , mod-2, mod ) for i in range( N, 0, -1): de_factorial[i-1] = de_factorial[i] * i % mod def comb(n,r): if n < r: return 0 if n == r: return 1 return (factorial[n] * de_factorial[r] * de_factorial[n-r]) % mod p = [0] * (N+1) # Bを食べきった確率 q = [0] * (N+1) # Wを食べきった確率 de2 = de_factorial[2] for i in range(1, N+1): p[i] = p[i-1] + comb(i-1 ,B-1) * de2 % mod q[i] = q[i-1] + comb(i-1 ,W-1) * de2 % mod de2 = de2 * de_factorial[2] % mod tmp = ( q[i-1] + 1-p[i-1] ) * de_factorial[2] % mod print(tmp) ```
instruction
0
104,253
9
208,506
No
output
1
104,253
9
208,507
Provide a correct Python 3 solution for this coding contest problem. In the beginning, Takahashi has A cookies, and Aoki has B cookies. They will perform the following operation alternately, starting from Takahashi: * If the number of cookies in his hand is odd, eat one of those cookies; if the number is even, do nothing. Then, give one-half of the cookies in his hand to the other person. Find the numbers of cookies Takahashi and Aoki respectively have after performing K operations in total. Constraints * 1 \leq A,B \leq 10^9 * 1 \leq K \leq 100 * A,B and K are integers. Input Input is given from Standard Input in the following format: A B K Output Print the number of cookies Takahashi has, and the number of cookies Aoki has, in this order, after performing K operations in total. Examples Input 5 4 2 Output 5 3 Input 3 3 3 Output 1 3 Input 314159265 358979323 84 Output 448759046 224379523
instruction
0
104,256
9
208,512
"Correct Solution: ``` A,B,K=map(int,input().split()) for i in range(K): A//=2 B+=A A,B=B,A if(K%2): A,B=B,A print(A,B) ```
output
1
104,256
9
208,513
Provide a correct Python 3 solution for this coding contest problem. In the beginning, Takahashi has A cookies, and Aoki has B cookies. They will perform the following operation alternately, starting from Takahashi: * If the number of cookies in his hand is odd, eat one of those cookies; if the number is even, do nothing. Then, give one-half of the cookies in his hand to the other person. Find the numbers of cookies Takahashi and Aoki respectively have after performing K operations in total. Constraints * 1 \leq A,B \leq 10^9 * 1 \leq K \leq 100 * A,B and K are integers. Input Input is given from Standard Input in the following format: A B K Output Print the number of cookies Takahashi has, and the number of cookies Aoki has, in this order, after performing K operations in total. Examples Input 5 4 2 Output 5 3 Input 3 3 3 Output 1 3 Input 314159265 358979323 84 Output 448759046 224379523
instruction
0
104,257
9
208,514
"Correct Solution: ``` a,b,k = map(int,input().split()) tmp=1 for i in range(k): if tmp==1: b+=a//2 a=a//2 tmp=2 else: a+=b//2 b=b//2 tmp=1 print(a,b) ```
output
1
104,257
9
208,515
Provide a correct Python 3 solution for this coding contest problem. In the beginning, Takahashi has A cookies, and Aoki has B cookies. They will perform the following operation alternately, starting from Takahashi: * If the number of cookies in his hand is odd, eat one of those cookies; if the number is even, do nothing. Then, give one-half of the cookies in his hand to the other person. Find the numbers of cookies Takahashi and Aoki respectively have after performing K operations in total. Constraints * 1 \leq A,B \leq 10^9 * 1 \leq K \leq 100 * A,B and K are integers. Input Input is given from Standard Input in the following format: A B K Output Print the number of cookies Takahashi has, and the number of cookies Aoki has, in this order, after performing K operations in total. Examples Input 5 4 2 Output 5 3 Input 3 3 3 Output 1 3 Input 314159265 358979323 84 Output 448759046 224379523
instruction
0
104,258
9
208,516
"Correct Solution: ``` A, B, K = map(int,input().split()) for i in range(K): if i % 2 == 0: A = A // 2 B += A else: B = B // 2 A += B print(int(A), int(B)) ```
output
1
104,258
9
208,517
Provide a correct Python 3 solution for this coding contest problem. In the beginning, Takahashi has A cookies, and Aoki has B cookies. They will perform the following operation alternately, starting from Takahashi: * If the number of cookies in his hand is odd, eat one of those cookies; if the number is even, do nothing. Then, give one-half of the cookies in his hand to the other person. Find the numbers of cookies Takahashi and Aoki respectively have after performing K operations in total. Constraints * 1 \leq A,B \leq 10^9 * 1 \leq K \leq 100 * A,B and K are integers. Input Input is given from Standard Input in the following format: A B K Output Print the number of cookies Takahashi has, and the number of cookies Aoki has, in this order, after performing K operations in total. Examples Input 5 4 2 Output 5 3 Input 3 3 3 Output 1 3 Input 314159265 358979323 84 Output 448759046 224379523
instruction
0
104,259
9
208,518
"Correct Solution: ``` A, B, K = map(int, input().split()) for i in range(K): if i % 2 == 0: A, B = A//2, A//2+B else: A, B = A+B//2, B//2 print(A,B) ```
output
1
104,259
9
208,519
Provide a correct Python 3 solution for this coding contest problem. In the beginning, Takahashi has A cookies, and Aoki has B cookies. They will perform the following operation alternately, starting from Takahashi: * If the number of cookies in his hand is odd, eat one of those cookies; if the number is even, do nothing. Then, give one-half of the cookies in his hand to the other person. Find the numbers of cookies Takahashi and Aoki respectively have after performing K operations in total. Constraints * 1 \leq A,B \leq 10^9 * 1 \leq K \leq 100 * A,B and K are integers. Input Input is given from Standard Input in the following format: A B K Output Print the number of cookies Takahashi has, and the number of cookies Aoki has, in this order, after performing K operations in total. Examples Input 5 4 2 Output 5 3 Input 3 3 3 Output 1 3 Input 314159265 358979323 84 Output 448759046 224379523
instruction
0
104,260
9
208,520
"Correct Solution: ``` A, B, K = [int(s) for s in input().split(' ')] for i in range(K): if i % 2: B //= 2 A += B else: A //= 2 B += A print ('%d %d' % (A, B)) ```
output
1
104,260
9
208,521
Provide a correct Python 3 solution for this coding contest problem. In the beginning, Takahashi has A cookies, and Aoki has B cookies. They will perform the following operation alternately, starting from Takahashi: * If the number of cookies in his hand is odd, eat one of those cookies; if the number is even, do nothing. Then, give one-half of the cookies in his hand to the other person. Find the numbers of cookies Takahashi and Aoki respectively have after performing K operations in total. Constraints * 1 \leq A,B \leq 10^9 * 1 \leq K \leq 100 * A,B and K are integers. Input Input is given from Standard Input in the following format: A B K Output Print the number of cookies Takahashi has, and the number of cookies Aoki has, in this order, after performing K operations in total. Examples Input 5 4 2 Output 5 3 Input 3 3 3 Output 1 3 Input 314159265 358979323 84 Output 448759046 224379523
instruction
0
104,261
9
208,522
"Correct Solution: ``` a,b,k = [int(x) for x in input().split()] for i in range(k): if i%2: a += b//2 b = b//2 else: b += a//2 a = a//2 print(a,b) ```
output
1
104,261
9
208,523
Provide a correct Python 3 solution for this coding contest problem. In the beginning, Takahashi has A cookies, and Aoki has B cookies. They will perform the following operation alternately, starting from Takahashi: * If the number of cookies in his hand is odd, eat one of those cookies; if the number is even, do nothing. Then, give one-half of the cookies in his hand to the other person. Find the numbers of cookies Takahashi and Aoki respectively have after performing K operations in total. Constraints * 1 \leq A,B \leq 10^9 * 1 \leq K \leq 100 * A,B and K are integers. Input Input is given from Standard Input in the following format: A B K Output Print the number of cookies Takahashi has, and the number of cookies Aoki has, in this order, after performing K operations in total. Examples Input 5 4 2 Output 5 3 Input 3 3 3 Output 1 3 Input 314159265 358979323 84 Output 448759046 224379523
instruction
0
104,262
9
208,524
"Correct Solution: ``` a,b,k = map(int,input().split()) for i in range(k): if i%2 == 0: if a%2 != 0 : a -=1 a /= 2 b += a else : if b%2 != 0: b -= 1 b /= 2 a += b print(int(a),int(b)) ```
output
1
104,262
9
208,525
Provide a correct Python 3 solution for this coding contest problem. In the beginning, Takahashi has A cookies, and Aoki has B cookies. They will perform the following operation alternately, starting from Takahashi: * If the number of cookies in his hand is odd, eat one of those cookies; if the number is even, do nothing. Then, give one-half of the cookies in his hand to the other person. Find the numbers of cookies Takahashi and Aoki respectively have after performing K operations in total. Constraints * 1 \leq A,B \leq 10^9 * 1 \leq K \leq 100 * A,B and K are integers. Input Input is given from Standard Input in the following format: A B K Output Print the number of cookies Takahashi has, and the number of cookies Aoki has, in this order, after performing K operations in total. Examples Input 5 4 2 Output 5 3 Input 3 3 3 Output 1 3 Input 314159265 358979323 84 Output 448759046 224379523
instruction
0
104,263
9
208,526
"Correct Solution: ``` A,B,K=map(int,input().split()) for i in range(K): if i%2==0: B+=A//2 A=A//2 else: A+=B//2 B=B//2 print(A,B) ```
output
1
104,263
9
208,527
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In the beginning, Takahashi has A cookies, and Aoki has B cookies. They will perform the following operation alternately, starting from Takahashi: * If the number of cookies in his hand is odd, eat one of those cookies; if the number is even, do nothing. Then, give one-half of the cookies in his hand to the other person. Find the numbers of cookies Takahashi and Aoki respectively have after performing K operations in total. Constraints * 1 \leq A,B \leq 10^9 * 1 \leq K \leq 100 * A,B and K are integers. Input Input is given from Standard Input in the following format: A B K Output Print the number of cookies Takahashi has, and the number of cookies Aoki has, in this order, after performing K operations in total. Examples Input 5 4 2 Output 5 3 Input 3 3 3 Output 1 3 Input 314159265 358979323 84 Output 448759046 224379523 Submitted Solution: ``` a,b,k = list(map(int, input().split())) for i in range(k): if i%2 == 0: if a%2==1: a-=1 b += a//2 a //= 2 else: if b%2==1: b-=1 a += b//2 b //= 2 print(a, b) ```
instruction
0
104,264
9
208,528
Yes
output
1
104,264
9
208,529
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In the beginning, Takahashi has A cookies, and Aoki has B cookies. They will perform the following operation alternately, starting from Takahashi: * If the number of cookies in his hand is odd, eat one of those cookies; if the number is even, do nothing. Then, give one-half of the cookies in his hand to the other person. Find the numbers of cookies Takahashi and Aoki respectively have after performing K operations in total. Constraints * 1 \leq A,B \leq 10^9 * 1 \leq K \leq 100 * A,B and K are integers. Input Input is given from Standard Input in the following format: A B K Output Print the number of cookies Takahashi has, and the number of cookies Aoki has, in this order, after performing K operations in total. Examples Input 5 4 2 Output 5 3 Input 3 3 3 Output 1 3 Input 314159265 358979323 84 Output 448759046 224379523 Submitted Solution: ``` a,b,k = [int(x) for x in input().split()] def func(x,y): x = x//2 y += x return x,y for i in range(k): if i%2 == 0: a,b = func(a,b) else: b,a = func(b,a) print(a, b) ```
instruction
0
104,265
9
208,530
Yes
output
1
104,265
9
208,531
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In the beginning, Takahashi has A cookies, and Aoki has B cookies. They will perform the following operation alternately, starting from Takahashi: * If the number of cookies in his hand is odd, eat one of those cookies; if the number is even, do nothing. Then, give one-half of the cookies in his hand to the other person. Find the numbers of cookies Takahashi and Aoki respectively have after performing K operations in total. Constraints * 1 \leq A,B \leq 10^9 * 1 \leq K \leq 100 * A,B and K are integers. Input Input is given from Standard Input in the following format: A B K Output Print the number of cookies Takahashi has, and the number of cookies Aoki has, in this order, after performing K operations in total. Examples Input 5 4 2 Output 5 3 Input 3 3 3 Output 1 3 Input 314159265 358979323 84 Output 448759046 224379523 Submitted Solution: ``` A, B, K = tuple(map(int, input().split(" "))) for k in range(K): if k % 2 == 0: A = A // 2 B += A else: B = B // 2 A += B print(A, B) ```
instruction
0
104,266
9
208,532
Yes
output
1
104,266
9
208,533
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In the beginning, Takahashi has A cookies, and Aoki has B cookies. They will perform the following operation alternately, starting from Takahashi: * If the number of cookies in his hand is odd, eat one of those cookies; if the number is even, do nothing. Then, give one-half of the cookies in his hand to the other person. Find the numbers of cookies Takahashi and Aoki respectively have after performing K operations in total. Constraints * 1 \leq A,B \leq 10^9 * 1 \leq K \leq 100 * A,B and K are integers. Input Input is given from Standard Input in the following format: A B K Output Print the number of cookies Takahashi has, and the number of cookies Aoki has, in this order, after performing K operations in total. Examples Input 5 4 2 Output 5 3 Input 3 3 3 Output 1 3 Input 314159265 358979323 84 Output 448759046 224379523 Submitted Solution: ``` a,b,k=[int(x) for x in input().split()] for i in range(k): if i%2: b//=2 a+=b else: a//=2 b+=a print(a,b) ```
instruction
0
104,267
9
208,534
Yes
output
1
104,267
9
208,535
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In the beginning, Takahashi has A cookies, and Aoki has B cookies. They will perform the following operation alternately, starting from Takahashi: * If the number of cookies in his hand is odd, eat one of those cookies; if the number is even, do nothing. Then, give one-half of the cookies in his hand to the other person. Find the numbers of cookies Takahashi and Aoki respectively have after performing K operations in total. Constraints * 1 \leq A,B \leq 10^9 * 1 \leq K \leq 100 * A,B and K are integers. Input Input is given from Standard Input in the following format: A B K Output Print the number of cookies Takahashi has, and the number of cookies Aoki has, in this order, after performing K operations in total. Examples Input 5 4 2 Output 5 3 Input 3 3 3 Output 1 3 Input 314159265 358979323 84 Output 448759046 224379523 Submitted Solution: ``` A, B, K = map(int,input().rstrip().split()) for i in range(K): if i % 2 == 0: B = B + A/2 A = A/2 else: A = A + B/2 B = B/2 print ('{} {}'.format(A,B)) ```
instruction
0
104,268
9
208,536
No
output
1
104,268
9
208,537
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In the beginning, Takahashi has A cookies, and Aoki has B cookies. They will perform the following operation alternately, starting from Takahashi: * If the number of cookies in his hand is odd, eat one of those cookies; if the number is even, do nothing. Then, give one-half of the cookies in his hand to the other person. Find the numbers of cookies Takahashi and Aoki respectively have after performing K operations in total. Constraints * 1 \leq A,B \leq 10^9 * 1 \leq K \leq 100 * A,B and K are integers. Input Input is given from Standard Input in the following format: A B K Output Print the number of cookies Takahashi has, and the number of cookies Aoki has, in this order, after performing K operations in total. Examples Input 5 4 2 Output 5 3 Input 3 3 3 Output 1 3 Input 314159265 358979323 84 Output 448759046 224379523 Submitted Solution: ``` A, B, K = map(int, input().split()) for i in range(K): if i % 2 == 0: B = B + A/2 A = A/2 else: A = A + B/2 B = B/2 print ('{} {}'.format(A,B)) ```
instruction
0
104,269
9
208,538
No
output
1
104,269
9
208,539
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In the beginning, Takahashi has A cookies, and Aoki has B cookies. They will perform the following operation alternately, starting from Takahashi: * If the number of cookies in his hand is odd, eat one of those cookies; if the number is even, do nothing. Then, give one-half of the cookies in his hand to the other person. Find the numbers of cookies Takahashi and Aoki respectively have after performing K operations in total. Constraints * 1 \leq A,B \leq 10^9 * 1 \leq K \leq 100 * A,B and K are integers. Input Input is given from Standard Input in the following format: A B K Output Print the number of cookies Takahashi has, and the number of cookies Aoki has, in this order, after performing K operations in total. Examples Input 5 4 2 Output 5 3 Input 3 3 3 Output 1 3 Input 314159265 358979323 84 Output 448759046 224379523 Submitted Solution: ``` a, b, k = map(int, input().split(' ')) for i in range(0, k): if i % 2 == 0: if a % 2 != 0: a -= 1 b += a // 2 a -= a/2 else: if b % 2 != 0: b -= 1 a += b // 2 b -= b/2 print(f'{max(0,a)} {max(0,b)}') ```
instruction
0
104,270
9
208,540
No
output
1
104,270
9
208,541
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In the beginning, Takahashi has A cookies, and Aoki has B cookies. They will perform the following operation alternately, starting from Takahashi: * If the number of cookies in his hand is odd, eat one of those cookies; if the number is even, do nothing. Then, give one-half of the cookies in his hand to the other person. Find the numbers of cookies Takahashi and Aoki respectively have after performing K operations in total. Constraints * 1 \leq A,B \leq 10^9 * 1 \leq K \leq 100 * A,B and K are integers. Input Input is given from Standard Input in the following format: A B K Output Print the number of cookies Takahashi has, and the number of cookies Aoki has, in this order, after performing K operations in total. Examples Input 5 4 2 Output 5 3 Input 3 3 3 Output 1 3 Input 314159265 358979323 84 Output 448759046 224379523 Submitted Solution: ``` a,b,c=map(int,input().split()) if c%2==0: for _ in range(int(c/2)): if a %2 == 0: d=0 else: a=(a-1) a=a/2 b=a + b if b%2== 0: d=0 else: b=(b-1) b=b/2 a+=b print(int(a),int(b)) else: if c%2==1: for _ in range(int(c/2)): if a %2 == 0: d=0 else: a=(a-1) a=a/2 b=a + b if b%2== 0: d=0 else: b=(b-1) b=b/2 a+=b if a %2 == 0: d=0 else: a=(a-1) a=a/2 b=a + b print(int(a),int(b)) ```
instruction
0
104,271
9
208,542
No
output
1
104,271
9
208,543
Provide a correct Python 3 solution for this coding contest problem. Akaki, a patissier, can make N kinds of doughnut using only a certain powder called "Okashi no Moto" (literally "material of pastry", simply called Moto below) as ingredient. These doughnuts are called Doughnut 1, Doughnut 2, ..., Doughnut N. In order to make one Doughnut i (1 ≤ i ≤ N), she needs to consume m_i grams of Moto. She cannot make a non-integer number of doughnuts, such as 0.5 doughnuts. The recipes of these doughnuts are developed by repeated modifications from the recipe of Doughnut 1. Specifically, the recipe of Doughnut i (2 ≤ i ≤ N) is a direct modification of the recipe of Doughnut p_i (1 ≤ p_i < i). Now, she has X grams of Moto. She decides to make as many doughnuts as possible for a party tonight. However, since the tastes of the guests differ, she will obey the following condition: * Let c_i be the number of Doughnut i (1 ≤ i ≤ N) that she makes. For each integer i such that 2 ≤ i ≤ N, c_{p_i} ≤ c_i ≤ c_{p_i} + D must hold. Here, D is a predetermined value. At most how many doughnuts can be made here? She does not necessarily need to consume all of her Moto. Constraints * 2 ≤ N ≤ 50 * 1 ≤ X ≤ 10^9 * 0 ≤ D ≤ 10^9 * 1 ≤ m_i ≤ 10^9 (1 ≤ i ≤ N) * 1 ≤ p_i < i (2 ≤ i ≤ N) * All values in input are integers. Input Input is given from Standard Input in the following format: N X D m_1 m_2 p_2 : m_N p_N Output Print the maximum number of doughnuts that can be made under the condition. Examples Input 3 100 1 15 10 1 20 1 Output 7 Input 3 100 10 15 10 1 20 1 Output 10 Input 5 1000000000 1000000 123 159 1 111 1 135 3 147 3 Output 7496296
instruction
0
104,272
9
208,544
"Correct Solution: ``` N, X, D = map(int, input().split()) M = [0]*N M[0] = int(input()) P = [0]*N for i in range(N-1): M[i+1], P[i+1] = map(int, input().split()) C = [1]*N for i in range(N-1, 0, -1): p = P[i]-1 C[p] += C[i] M[p] += M[i] L = [D]*N L[0] = X from collections import deque def solve(N, W, ws, vs, ms): V0 = max(vs) V = sum(v * min(V0, m) for v, m in zip(vs, ms)) dp = [W+1]*(V + 1) dp[0] = 0 for i in range(N): v = vs[i]; w = ws[i]; m = ms[i] c = min(V0, m) ms[i] -= c for k in range(v): que = deque() push = que.append popf = que.popleft; popb = que.pop for j in range((V-k)//v+1): a = dp[k + j*v] - j * w while que and a <= que[-1][1]: popb() push((j, a)) p, b = que[0] dp[k + j*v] = b + j * w if que and p <= j-c: popf() *I, = range(N) I.sort(key=lambda x: ws[x]/vs[x]) *S, = [(vs[i], ws[i], ms[i]) for i in I] def greedy(): yield 0 for i in range(V + 1): if dp[i] > W: continue rest = W - dp[i] r = i for v, w, m in S: m = min(m, rest // w) r += m * v rest -= m * w yield r return max(greedy()) print(solve(N, X, M, C, L)) ```
output
1
104,272
9
208,545
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Akaki, a patissier, can make N kinds of doughnut using only a certain powder called "Okashi no Moto" (literally "material of pastry", simply called Moto below) as ingredient. These doughnuts are called Doughnut 1, Doughnut 2, ..., Doughnut N. In order to make one Doughnut i (1 ≤ i ≤ N), she needs to consume m_i grams of Moto. She cannot make a non-integer number of doughnuts, such as 0.5 doughnuts. The recipes of these doughnuts are developed by repeated modifications from the recipe of Doughnut 1. Specifically, the recipe of Doughnut i (2 ≤ i ≤ N) is a direct modification of the recipe of Doughnut p_i (1 ≤ p_i < i). Now, she has X grams of Moto. She decides to make as many doughnuts as possible for a party tonight. However, since the tastes of the guests differ, she will obey the following condition: * Let c_i be the number of Doughnut i (1 ≤ i ≤ N) that she makes. For each integer i such that 2 ≤ i ≤ N, c_{p_i} ≤ c_i ≤ c_{p_i} + D must hold. Here, D is a predetermined value. At most how many doughnuts can be made here? She does not necessarily need to consume all of her Moto. Constraints * 2 ≤ N ≤ 50 * 1 ≤ X ≤ 10^9 * 0 ≤ D ≤ 10^9 * 1 ≤ m_i ≤ 10^9 (1 ≤ i ≤ N) * 1 ≤ p_i < i (2 ≤ i ≤ N) * All values in input are integers. Input Input is given from Standard Input in the following format: N X D m_1 m_2 p_2 : m_N p_N Output Print the maximum number of doughnuts that can be made under the condition. Examples Input 3 100 1 15 10 1 20 1 Output 7 Input 3 100 10 15 10 1 20 1 Output 10 Input 5 1000000000 1000000 123 159 1 111 1 135 3 147 3 Output 7496296 Submitted Solution: ``` #!/usr/bin/env python3 INF = 2 * 10 ** 9 def solve(n, x, d, ma, pa): v = [1] * n w = [0] * n for i in range(n - 1, -1, -1): w[i] += ma[i] if 0 <= pa[i]: v[pa[i]] += v[i] w[pa[i]] += w[i] if d == 0: return (x // w[0]) * n c_0 = max(0, x - sum(w[1:]) * d + w[0] - 1) // w[0] ans = n * c_0 y = w[0] * c_0 mean_w = [None] * n for i in range(n): mean_w[i] = (w[i] / v[i], i) mean_w.sort() t = [0] * n llj = lj = -1 for i in range(n): _, j = mean_w[i] if j == 0: t[0] = (x - y) // w[0] y += w[0] * t[0] lj = 0 break if x <= y + w[j] * d: t[j] = (x - y) // w[j] y += w[j] * t[j] lj = j break y += w[j] * d t[j] = d llj = j c_max = min(n, d) if c_max <= t[lj]: y -= w[lj] * c_max t[lj] -= c_max else: y -= w[lj] * t[lj] t[lj] = 0 if llj != -1: y -= w[llj] * c_max t[llj] -= c_max ans += sum([v[j] * t[j] for j in range(n)]) j_max = c_max * n * n v_max = 0 rx = x - y dp = [[0] + [INF] * j_max for _ in range(n)] for j in range(1, j_max // n + 1): dp[0][n * j] = ndp = w[0] * j if ndp <= rx: v_max = n * j for i in range(1, n): vi = v[i] wi = w[i] for j in range(1, j_max + 1): ndp = dp[i - 1][j] nj = j w_sum = 0 for k in range(1, min(c_max, d - t[i])): nj -= vi w_sum += wi if nj < 0: break ndp = min(ndp, dp[i - 1][nj] + w_sum) dp[i][j] = ndp if ndp <= rx: if v_max < j: v_max = j ans += v_max return ans def main(): n, x, d = input().split() n = int(n) x = int(x) d = int(d) ma = [] pa = [] m = input() m = int(m) ma.append(m) pa.append(-1) for _ in range(n - 1): m, p = input().split() m = int(m) ma.append(m) p = int(p) - 1 pa.append(p) print(solve(n, x, d, ma, pa)) if __name__ == '__main__': main() ```
instruction
0
104,273
9
208,546
No
output
1
104,273
9
208,547
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Akaki, a patissier, can make N kinds of doughnut using only a certain powder called "Okashi no Moto" (literally "material of pastry", simply called Moto below) as ingredient. These doughnuts are called Doughnut 1, Doughnut 2, ..., Doughnut N. In order to make one Doughnut i (1 ≤ i ≤ N), she needs to consume m_i grams of Moto. She cannot make a non-integer number of doughnuts, such as 0.5 doughnuts. The recipes of these doughnuts are developed by repeated modifications from the recipe of Doughnut 1. Specifically, the recipe of Doughnut i (2 ≤ i ≤ N) is a direct modification of the recipe of Doughnut p_i (1 ≤ p_i < i). Now, she has X grams of Moto. She decides to make as many doughnuts as possible for a party tonight. However, since the tastes of the guests differ, she will obey the following condition: * Let c_i be the number of Doughnut i (1 ≤ i ≤ N) that she makes. For each integer i such that 2 ≤ i ≤ N, c_{p_i} ≤ c_i ≤ c_{p_i} + D must hold. Here, D is a predetermined value. At most how many doughnuts can be made here? She does not necessarily need to consume all of her Moto. Constraints * 2 ≤ N ≤ 50 * 1 ≤ X ≤ 10^9 * 0 ≤ D ≤ 10^9 * 1 ≤ m_i ≤ 10^9 (1 ≤ i ≤ N) * 1 ≤ p_i < i (2 ≤ i ≤ N) * All values in input are integers. Input Input is given from Standard Input in the following format: N X D m_1 m_2 p_2 : m_N p_N Output Print the maximum number of doughnuts that can be made under the condition. Examples Input 3 100 1 15 10 1 20 1 Output 7 Input 3 100 10 15 10 1 20 1 Output 10 Input 5 1000000000 1000000 123 159 1 111 1 135 3 147 3 Output 7496296 Submitted Solution: ``` #!/usr/bin/env python3 import math def dfs_vw(g, m, u, value, weight): v = 1 w = m[u] for c in g[u]: dfs_vw(g, m, c, value, weight) v += value[c] w += weight[c] value[u] = v weight[u] = w def dfs(n, x, d, s, j, sum_v, best): _, v, i, w = s[j] r_best = sum_v + math.floor(v * x / w) if r_best < best: return best, False max_y = x // w if 0 < i: max_y = min(max_y, d) best = max(best, sum_v + max_y * v) if j < n - 1: nj = j + 1 for y in range(max_y, max(max_y - n, 0) - 1, -1): best, f = dfs(n, x - y * w, d, s, nj, sum_v + y * v, best) if not f: break return best, True def solve(n, x, d, m, g): value = [1] * n weight = [0] * n dfs_vw(g, m, 0, value, weight) s = [(weight[i] / value[i], value[i], i, weight[i]) for i in range(n)] s.sort() ans, _ = dfs(n, x, d, s, 0, 0, 0) return ans def main(): n, x, d = input().split() n = int(n) x = int(x) d = int(d) m = [] g = [[] for _ in range(n)] mi = input() mi = int(mi) m.append(mi) for i in range(1, n): mi, pi = input().split() mi = int(mi) pi = int(pi) - 1 m.append(mi) g[pi].append(i) print(solve(n, x, d, m, g)) if __name__ == '__main__': main() ```
instruction
0
104,274
9
208,548
No
output
1
104,274
9
208,549
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Akaki, a patissier, can make N kinds of doughnut using only a certain powder called "Okashi no Moto" (literally "material of pastry", simply called Moto below) as ingredient. These doughnuts are called Doughnut 1, Doughnut 2, ..., Doughnut N. In order to make one Doughnut i (1 ≤ i ≤ N), she needs to consume m_i grams of Moto. She cannot make a non-integer number of doughnuts, such as 0.5 doughnuts. The recipes of these doughnuts are developed by repeated modifications from the recipe of Doughnut 1. Specifically, the recipe of Doughnut i (2 ≤ i ≤ N) is a direct modification of the recipe of Doughnut p_i (1 ≤ p_i < i). Now, she has X grams of Moto. She decides to make as many doughnuts as possible for a party tonight. However, since the tastes of the guests differ, she will obey the following condition: * Let c_i be the number of Doughnut i (1 ≤ i ≤ N) that she makes. For each integer i such that 2 ≤ i ≤ N, c_{p_i} ≤ c_i ≤ c_{p_i} + D must hold. Here, D is a predetermined value. At most how many doughnuts can be made here? She does not necessarily need to consume all of her Moto. Constraints * 2 ≤ N ≤ 50 * 1 ≤ X ≤ 10^9 * 0 ≤ D ≤ 10^9 * 1 ≤ m_i ≤ 10^9 (1 ≤ i ≤ N) * 1 ≤ p_i < i (2 ≤ i ≤ N) * All values in input are integers. Input Input is given from Standard Input in the following format: N X D m_1 m_2 p_2 : m_N p_N Output Print the maximum number of doughnuts that can be made under the condition. Examples Input 3 100 1 15 10 1 20 1 Output 7 Input 3 100 10 15 10 1 20 1 Output 10 Input 5 1000000000 1000000 123 159 1 111 1 135 3 147 3 Output 7496296 Submitted Solution: ``` #!/usr/bin/env python3 import math def dfs_vw(g, m, u, value, weight): v = 1 w = m[u] for c in g[u]: dfs_vw(g, m, c, value, weight) v += value[c] w += weight[c] value[u] = v weight[u] = w def dfs(n, x, d, s, j, sum_v, best): _, v, i, w = s[j] r_best = sum_v + math.floor(v * x / w) if r_best <= best: return best, False max_y = x // w if 0 < i: max_y = min(max_y, d) best = max(best, sum_v + max_y * v) if j < n - 1: nj = j + 1 for y in range(max_y, max(max_y - n, 0) - 1, -1): best, f = dfs(n, x - y * w, d, s, nj, sum_v + y * v, best) if not f: break return best, True def solve(n, x, d, m, g): value = [1] * n weight = [0] * n dfs_vw(g, m, 0, value, weight) s = [(weight[i] / value[i], value[i], i, weight[i]) for i in range(n)] s.sort() ans, _ = dfs(n, x, d, s, 0, 0, 0) return ans def main(): n, x, d = input().split() n = int(n) x = int(x) d = int(d) m = [] g = [[] for _ in range(n)] mi = input() mi = int(mi) m.append(mi) for i in range(1, n): mi, pi = input().split() mi = int(mi) pi = int(pi) - 1 m.append(mi) g[pi].append(i) print(solve(n, x, d, m, g)) if __name__ == '__main__': main() ```
instruction
0
104,275
9
208,550
No
output
1
104,275
9
208,551
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Akaki, a patissier, can make N kinds of doughnut using only a certain powder called "Okashi no Moto" (literally "material of pastry", simply called Moto below) as ingredient. These doughnuts are called Doughnut 1, Doughnut 2, ..., Doughnut N. In order to make one Doughnut i (1 ≤ i ≤ N), she needs to consume m_i grams of Moto. She cannot make a non-integer number of doughnuts, such as 0.5 doughnuts. The recipes of these doughnuts are developed by repeated modifications from the recipe of Doughnut 1. Specifically, the recipe of Doughnut i (2 ≤ i ≤ N) is a direct modification of the recipe of Doughnut p_i (1 ≤ p_i < i). Now, she has X grams of Moto. She decides to make as many doughnuts as possible for a party tonight. However, since the tastes of the guests differ, she will obey the following condition: * Let c_i be the number of Doughnut i (1 ≤ i ≤ N) that she makes. For each integer i such that 2 ≤ i ≤ N, c_{p_i} ≤ c_i ≤ c_{p_i} + D must hold. Here, D is a predetermined value. At most how many doughnuts can be made here? She does not necessarily need to consume all of her Moto. Constraints * 2 ≤ N ≤ 50 * 1 ≤ X ≤ 10^9 * 0 ≤ D ≤ 10^9 * 1 ≤ m_i ≤ 10^9 (1 ≤ i ≤ N) * 1 ≤ p_i < i (2 ≤ i ≤ N) * All values in input are integers. Input Input is given from Standard Input in the following format: N X D m_1 m_2 p_2 : m_N p_N Output Print the maximum number of doughnuts that can be made under the condition. Examples Input 3 100 1 15 10 1 20 1 Output 7 Input 3 100 10 15 10 1 20 1 Output 10 Input 5 1000000000 1000000 123 159 1 111 1 135 3 147 3 Output 7496296 Submitted Solution: ``` N, X, D = map(int, input().split()) M = [0]*N M[0] = int(input()) P = [0]*N for i in range(N-1): M[i+1], P[i+1] = map(int, input().split()) C = [1]*N for i in range(N-1, 0, -1): p = P[i]-1 C[p] += C[i] M[p] += M[i] L = [D]*N L[0] = X from collections import deque def solve(N, W, ws, vs, ms): V0 = max(vs) V = sum(v * min(V0, m) for v, m in zip(vs, ms)) dp = [W+1]*(V + 1) dp[0] = 0 for i in range(N): v = vs[i]; w = ws[i]; m = ms[i] c = min(V0, m) ms[i] -= c for k in range(v): que = deque() push = que.append popf = que.popleft; popb = que.pop for j in range((V-k)//v+1): a = dp[k + j*v] - j * w while que and a <= que[-1][1]: popb() push((j, a)) p, b = que[0] dp[k + j*v] = b + j * w if que and p <= j-c: popf() *I, = range(N) I.sort(key=lambda x: ws[x]/vs[x]) *S, = [(vs[i], ws[i], ms[i]) for i in I] def greedy(): yield 0 for i in range(V + 1): if dp[i] > W: continue rest = W - dp[i] r = i for v, w, m in S: m = min(m, rest // w) r += m * v rest -= m * w yield r return max(greedy()) print(solve(N, X, M, C, L)) ```
instruction
0
104,276
9
208,552
No
output
1
104,276
9
208,553
Provide a correct Python 3 solution for this coding contest problem. In the city, there are two pastry shops. One shop was very popular because its cakes are pretty tasty. However, there was a man who is displeased at the shop. He was an owner of another shop. Although cause of his shop's unpopularity is incredibly awful taste of its cakes, he never improved it. He was just growing hate, ill, envy, and jealousy. Finally, he decided to vandalize the rival. His vandalize is to mess up sales record of cakes. The rival shop sells K kinds of cakes and sales quantity is recorded for each kind. He calculates sum of sales quantities for all pairs of cakes. Getting K(K-1)/2 numbers, then he rearranges them randomly, and replace an original sales record with them. An owner of the rival shop is bothered. Could you write, at least, a program that finds total sales quantity of all cakes for the pitiful owner? Constraints * Judge data contains at most 100 data sets. * 2 ≤ K ≤ 100 * 0 ≤ ci ≤ 100 Input Input file contains several data sets. A single data set has following format: K c1 c2 ... cK×(K-1)/2 K is an integer that denotes how many kinds of cakes are sold. ci is an integer that denotes a number written on the card. The end of input is denoted by a case where K = 0. You should output nothing for this case. Output For each data set, output the total sales quantity in one line. Example Input 2 2 3 5 4 3 0 Output 2 6
instruction
0
104,357
9
208,714
"Correct Solution: ``` while True: k = int(input()) if k == 0: break print(sum(map(int, input().split())) // (k - 1)) ```
output
1
104,357
9
208,715
Provide a correct Python 3 solution for this coding contest problem. In the city, there are two pastry shops. One shop was very popular because its cakes are pretty tasty. However, there was a man who is displeased at the shop. He was an owner of another shop. Although cause of his shop's unpopularity is incredibly awful taste of its cakes, he never improved it. He was just growing hate, ill, envy, and jealousy. Finally, he decided to vandalize the rival. His vandalize is to mess up sales record of cakes. The rival shop sells K kinds of cakes and sales quantity is recorded for each kind. He calculates sum of sales quantities for all pairs of cakes. Getting K(K-1)/2 numbers, then he rearranges them randomly, and replace an original sales record with them. An owner of the rival shop is bothered. Could you write, at least, a program that finds total sales quantity of all cakes for the pitiful owner? Constraints * Judge data contains at most 100 data sets. * 2 ≤ K ≤ 100 * 0 ≤ ci ≤ 100 Input Input file contains several data sets. A single data set has following format: K c1 c2 ... cK×(K-1)/2 K is an integer that denotes how many kinds of cakes are sold. ci is an integer that denotes a number written on the card. The end of input is denoted by a case where K = 0. You should output nothing for this case. Output For each data set, output the total sales quantity in one line. Example Input 2 2 3 5 4 3 0 Output 2 6
instruction
0
104,358
9
208,716
"Correct Solution: ``` while True: k = int(input()) if k == 0: break sums = sum(int(n) for n in input().split()) print( sums // (k - 1)) ```
output
1
104,358
9
208,717
Provide a correct Python 3 solution for this coding contest problem. In the city, there are two pastry shops. One shop was very popular because its cakes are pretty tasty. However, there was a man who is displeased at the shop. He was an owner of another shop. Although cause of his shop's unpopularity is incredibly awful taste of its cakes, he never improved it. He was just growing hate, ill, envy, and jealousy. Finally, he decided to vandalize the rival. His vandalize is to mess up sales record of cakes. The rival shop sells K kinds of cakes and sales quantity is recorded for each kind. He calculates sum of sales quantities for all pairs of cakes. Getting K(K-1)/2 numbers, then he rearranges them randomly, and replace an original sales record with them. An owner of the rival shop is bothered. Could you write, at least, a program that finds total sales quantity of all cakes for the pitiful owner? Constraints * Judge data contains at most 100 data sets. * 2 ≤ K ≤ 100 * 0 ≤ ci ≤ 100 Input Input file contains several data sets. A single data set has following format: K c1 c2 ... cK×(K-1)/2 K is an integer that denotes how many kinds of cakes are sold. ci is an integer that denotes a number written on the card. The end of input is denoted by a case where K = 0. You should output nothing for this case. Output For each data set, output the total sales quantity in one line. Example Input 2 2 3 5 4 3 0 Output 2 6
instruction
0
104,359
9
208,718
"Correct Solution: ``` while True: K = int(input()) if K == 0: break c = [int(i) for i in input().split()] S = 0 for i in range(len(c)): S = S + c[i] print(int(S/(K-1))) ```
output
1
104,359
9
208,719
Provide a correct Python 3 solution for this coding contest problem. In the city, there are two pastry shops. One shop was very popular because its cakes are pretty tasty. However, there was a man who is displeased at the shop. He was an owner of another shop. Although cause of his shop's unpopularity is incredibly awful taste of its cakes, he never improved it. He was just growing hate, ill, envy, and jealousy. Finally, he decided to vandalize the rival. His vandalize is to mess up sales record of cakes. The rival shop sells K kinds of cakes and sales quantity is recorded for each kind. He calculates sum of sales quantities for all pairs of cakes. Getting K(K-1)/2 numbers, then he rearranges them randomly, and replace an original sales record with them. An owner of the rival shop is bothered. Could you write, at least, a program that finds total sales quantity of all cakes for the pitiful owner? Constraints * Judge data contains at most 100 data sets. * 2 ≤ K ≤ 100 * 0 ≤ ci ≤ 100 Input Input file contains several data sets. A single data set has following format: K c1 c2 ... cK×(K-1)/2 K is an integer that denotes how many kinds of cakes are sold. ci is an integer that denotes a number written on the card. The end of input is denoted by a case where K = 0. You should output nothing for this case. Output For each data set, output the total sales quantity in one line. Example Input 2 2 3 5 4 3 0 Output 2 6
instruction
0
104,360
9
208,720
"Correct Solution: ``` while True: K = eval(input()) if K == 0: break total = sum([eval(c) for c in input().split()]) print(int(total/(K-1))) ```
output
1
104,360
9
208,721
Provide a correct Python 3 solution for this coding contest problem. In the city, there are two pastry shops. One shop was very popular because its cakes are pretty tasty. However, there was a man who is displeased at the shop. He was an owner of another shop. Although cause of his shop's unpopularity is incredibly awful taste of its cakes, he never improved it. He was just growing hate, ill, envy, and jealousy. Finally, he decided to vandalize the rival. His vandalize is to mess up sales record of cakes. The rival shop sells K kinds of cakes and sales quantity is recorded for each kind. He calculates sum of sales quantities for all pairs of cakes. Getting K(K-1)/2 numbers, then he rearranges them randomly, and replace an original sales record with them. An owner of the rival shop is bothered. Could you write, at least, a program that finds total sales quantity of all cakes for the pitiful owner? Constraints * Judge data contains at most 100 data sets. * 2 ≤ K ≤ 100 * 0 ≤ ci ≤ 100 Input Input file contains several data sets. A single data set has following format: K c1 c2 ... cK×(K-1)/2 K is an integer that denotes how many kinds of cakes are sold. ci is an integer that denotes a number written on the card. The end of input is denoted by a case where K = 0. You should output nothing for this case. Output For each data set, output the total sales quantity in one line. Example Input 2 2 3 5 4 3 0 Output 2 6
instruction
0
104,361
9
208,722
"Correct Solution: ``` while 1: k=int(input()) if k==0:break print(sum(map(int,input().split()))//(k-1)) ```
output
1
104,361
9
208,723
Provide a correct Python 3 solution for this coding contest problem. In the city, there are two pastry shops. One shop was very popular because its cakes are pretty tasty. However, there was a man who is displeased at the shop. He was an owner of another shop. Although cause of his shop's unpopularity is incredibly awful taste of its cakes, he never improved it. He was just growing hate, ill, envy, and jealousy. Finally, he decided to vandalize the rival. His vandalize is to mess up sales record of cakes. The rival shop sells K kinds of cakes and sales quantity is recorded for each kind. He calculates sum of sales quantities for all pairs of cakes. Getting K(K-1)/2 numbers, then he rearranges them randomly, and replace an original sales record with them. An owner of the rival shop is bothered. Could you write, at least, a program that finds total sales quantity of all cakes for the pitiful owner? Constraints * Judge data contains at most 100 data sets. * 2 ≤ K ≤ 100 * 0 ≤ ci ≤ 100 Input Input file contains several data sets. A single data set has following format: K c1 c2 ... cK×(K-1)/2 K is an integer that denotes how many kinds of cakes are sold. ci is an integer that denotes a number written on the card. The end of input is denoted by a case where K = 0. You should output nothing for this case. Output For each data set, output the total sales quantity in one line. Example Input 2 2 3 5 4 3 0 Output 2 6
instruction
0
104,362
9
208,724
"Correct Solution: ``` while 1: k=int(input())-1 if k<0:break print(sum(map(int,input().split()))//k) ```
output
1
104,362
9
208,725
Provide a correct Python 3 solution for this coding contest problem. In the city, there are two pastry shops. One shop was very popular because its cakes are pretty tasty. However, there was a man who is displeased at the shop. He was an owner of another shop. Although cause of his shop's unpopularity is incredibly awful taste of its cakes, he never improved it. He was just growing hate, ill, envy, and jealousy. Finally, he decided to vandalize the rival. His vandalize is to mess up sales record of cakes. The rival shop sells K kinds of cakes and sales quantity is recorded for each kind. He calculates sum of sales quantities for all pairs of cakes. Getting K(K-1)/2 numbers, then he rearranges them randomly, and replace an original sales record with them. An owner of the rival shop is bothered. Could you write, at least, a program that finds total sales quantity of all cakes for the pitiful owner? Constraints * Judge data contains at most 100 data sets. * 2 ≤ K ≤ 100 * 0 ≤ ci ≤ 100 Input Input file contains several data sets. A single data set has following format: K c1 c2 ... cK×(K-1)/2 K is an integer that denotes how many kinds of cakes are sold. ci is an integer that denotes a number written on the card. The end of input is denoted by a case where K = 0. You should output nothing for this case. Output For each data set, output the total sales quantity in one line. Example Input 2 2 3 5 4 3 0 Output 2 6
instruction
0
104,363
9
208,726
"Correct Solution: ``` # AOJ 1027: A Piece of Cake # Python3 2018.7.5 bal4u while True: K = int(input()) if K == 0: break print(sum(list(map(int, input().split())))//(K-1)) ```
output
1
104,363
9
208,727
Provide a correct Python 3 solution for this coding contest problem. In the city, there are two pastry shops. One shop was very popular because its cakes are pretty tasty. However, there was a man who is displeased at the shop. He was an owner of another shop. Although cause of his shop's unpopularity is incredibly awful taste of its cakes, he never improved it. He was just growing hate, ill, envy, and jealousy. Finally, he decided to vandalize the rival. His vandalize is to mess up sales record of cakes. The rival shop sells K kinds of cakes and sales quantity is recorded for each kind. He calculates sum of sales quantities for all pairs of cakes. Getting K(K-1)/2 numbers, then he rearranges them randomly, and replace an original sales record with them. An owner of the rival shop is bothered. Could you write, at least, a program that finds total sales quantity of all cakes for the pitiful owner? Constraints * Judge data contains at most 100 data sets. * 2 ≤ K ≤ 100 * 0 ≤ ci ≤ 100 Input Input file contains several data sets. A single data set has following format: K c1 c2 ... cK×(K-1)/2 K is an integer that denotes how many kinds of cakes are sold. ci is an integer that denotes a number written on the card. The end of input is denoted by a case where K = 0. You should output nothing for this case. Output For each data set, output the total sales quantity in one line. Example Input 2 2 3 5 4 3 0 Output 2 6
instruction
0
104,364
9
208,728
"Correct Solution: ``` while True: K = int(input()) if K == 0: break elif K == 1: print(int(input())) else: po = [int(i) for i in input().split()] print(int(sum(po)/(K-1))) ```
output
1
104,364
9
208,729
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In the city, there are two pastry shops. One shop was very popular because its cakes are pretty tasty. However, there was a man who is displeased at the shop. He was an owner of another shop. Although cause of his shop's unpopularity is incredibly awful taste of its cakes, he never improved it. He was just growing hate, ill, envy, and jealousy. Finally, he decided to vandalize the rival. His vandalize is to mess up sales record of cakes. The rival shop sells K kinds of cakes and sales quantity is recorded for each kind. He calculates sum of sales quantities for all pairs of cakes. Getting K(K-1)/2 numbers, then he rearranges them randomly, and replace an original sales record with them. An owner of the rival shop is bothered. Could you write, at least, a program that finds total sales quantity of all cakes for the pitiful owner? Constraints * Judge data contains at most 100 data sets. * 2 ≤ K ≤ 100 * 0 ≤ ci ≤ 100 Input Input file contains several data sets. A single data set has following format: K c1 c2 ... cK×(K-1)/2 K is an integer that denotes how many kinds of cakes are sold. ci is an integer that denotes a number written on the card. The end of input is denoted by a case where K = 0. You should output nothing for this case. Output For each data set, output the total sales quantity in one line. Example Input 2 2 3 5 4 3 0 Output 2 6 Submitted Solution: ``` while True: K = int(input()) if K == 0: break else: po = [int(i) for i in input().split()] print(sum(po)/(K-1)) ```
instruction
0
104,365
9
208,730
No
output
1
104,365
9
208,731
Provide tags and a correct Python 3 solution for this coding contest problem. There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, …, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers. Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2. Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots. Input The first line contains two integers n and k (1 ≤ n ≤ k ≤ 10^5): the initial number of carrots and the number of rabbits. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^6): lengths of carrots. It is guaranteed that the sum of a_i is at least k. Output Output one integer: the minimum sum of time taken for rabbits to eat carrots. Examples Input 3 6 5 3 1 Output 15 Input 1 4 19 Output 91 Note For the first test, the optimal sizes of carrots are \{1,1,1,2,2,2\}. The time taken is 1^2+1^2+1^2+2^2+2^2+2^2=15 For the second test, the optimal sizes of carrots are \{4,5,5,5\}. The time taken is 4^2+5^2+5^2+5^2=91.
instruction
0
104,637
9
209,274
Tags: binary search, data structures, greedy, math, sortings Correct Solution: ``` from bisect import * from collections import * from math import * from heapq import * from typing import List from itertools import * from operator import * from functools import * #------------------------------------------------------------------------ import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #------------------------------------------------------------------------ def RL(): return map(int, sys.stdin.readline().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) #------------------------------------------------------------------------ @lru_cache(None) def fact(x): if x<2: return 1 return fact(x-1)*x @lru_cache(None) def per(i,j): return fact(i)//fact(i-j) @lru_cache(None) def com(i,j): return per(i,j)//fact(j) def linc(f,t,l,r): while l<r: mid=(l+r)//2 if t>f(mid): l=mid+1 else: r=mid return l def rinc(f,t,l,r): while l<r: mid=(l+r+1)//2 if t<f(mid): r=mid-1 else: l=mid return l def ldec(f,t,l,r): while l<r: mid=(l+r)//2 if t<f(mid): l=mid+1 else: r=mid return l def rdec(f,t,l,r): while l<r: mid=(l+r+1)//2 if t>f(mid): r=mid-1 else: l=mid return l def isprime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def binfun(x): c=0 for w in arr: c+=ceil(w/x) return c def lowbit(n): return n&-n class BIT: def __init__(self,arr): self.arr=arr self.n=len(arr)-1 def update(self,x,v): while x<=self.n: self.arr[x]+=v x+=x&-x def query(self,x): ans=0 while x: ans+=self.arr[x] x&=x-1 return ans class smt: def __init__(self,l,r,arr): self.l=l self.r=r self.value=(1<<31)-1 if l<r else arr[l] mid=(l+r)//2 if(l<r): self.left=smt(l,mid,arr) self.right=smt(mid+1,r,arr) self.value&=self.left.value&self.right.value #print(l,r,self.value) def setvalue(self,x,val): if(self.l==self.r): self.value=val return mid=(self.l+self.r)//2 if(x<=mid): self.left.setvalue(x,val) else: self.right.setvalue(x,val) self.value=self.left.value&self.right.value def ask(self,l,r): if(l<=self.l and r>=self.r): return self.value val=(1<<31)-1 mid=(self.l+self.r)//2 if(l<=mid): val&=self.left.ask(l,r) if(r>mid): val&=self.right.ask(l,r) return val class UFS: def __init__(self,n): self.parent=[i for i in range(n)] self.ranks=[0]*n def find(self,x): if x!=self.parent[x]: self.parent[x]=self.find(self.parent[x]) return self.parent[x] def union(self,u,v): pu,pv=self.find(u),self.find(v) if pu==pv: return False if self.ranks[pu]>=self.ranks[pv]: self.parent[pv]=pu if self.ranks[pv]==self.ranks[pu]: self.ranks[pu]+=1 else: self.parent[pu]=pv def Prime(n): c=0 prime=[] flag=[0]*(n+1) for i in range(2,n+1): if not flag[i]: prime.append(i) c+=1 for j in range(c): if i*prime[j]>n: break flag[i*prime[j]]=prime[j] if i%prime[j]==0: break return prime def dij(s,graph): d={} d[s]=0 heap=[(0,s)] seen=set() while heap: dis,u=heappop(heap) if u in seen: continue for v in graph[u]: if v not in d or d[v]>d[u]+graph[u][v]: d[v]=d[u]+graph[u][v] heappush(heap,(d[v],v)) return d ''' import time s=time.time() for i in range(2000): print(0) e=time.time() print(e-s) ''' n,k=RL() a=RLL() heap=[] ans=0 def val(x,k): a,b=divmod(x,k) return (a+1)**2*b+a**2*(k-b) for i in range(n): ans+=a[i]**2 cur=-val(a[i],1)+val(a[i],2) heappush(heap,(cur,a[i],1)) #print(ans,heap) k-=n for i in range(k): cur,m,n=heappop(heap) ans+=cur cur=-val(m,n+1)+val(m,n+2) heappush(heap,(cur,m,n+1)) #print(heap,ans) print(ans) ```
output
1
104,637
9
209,275
Provide tags and a correct Python 3 solution for this coding contest problem. There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, …, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers. Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2. Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots. Input The first line contains two integers n and k (1 ≤ n ≤ k ≤ 10^5): the initial number of carrots and the number of rabbits. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^6): lengths of carrots. It is guaranteed that the sum of a_i is at least k. Output Output one integer: the minimum sum of time taken for rabbits to eat carrots. Examples Input 3 6 5 3 1 Output 15 Input 1 4 19 Output 91 Note For the first test, the optimal sizes of carrots are \{1,1,1,2,2,2\}. The time taken is 1^2+1^2+1^2+2^2+2^2+2^2=15 For the second test, the optimal sizes of carrots are \{4,5,5,5\}. The time taken is 4^2+5^2+5^2+5^2=91.
instruction
0
104,638
9
209,276
Tags: binary search, data structures, greedy, math, sortings Correct Solution: ``` import heapq def value(l,parts): len1 = l//parts len2 = len1+1 cnt2 = l%parts cnt1 = parts-cnt2 return (cnt1*len1*len1) + (cnt2*len2*len2 ) def solve(n,k,a): #20 - 6 6 6 = 18, 20 -> 7,7,6 = as evenly as possible i divide i get min of sqs sum #20 -> 6 7 7 = x ,20 //> pq = [] tot = 0 for i in range(n): tot += a[i]*a[i] heapq.heappush(pq,((-value(a[i],1) + value(a[i],2)),a[i],2)) for i in range(k-n): temp = heapq.heappop(pq) tot += temp[0] a,b = temp[1],temp[2] heapq.heappush(pq,((-value(a,b)+value(a,b+1)),a,b+1)) #print(tot,a,b) return tot n,k = map(int,input().split()) a = list(map(int,input().split())) print(solve(n,k,a)) ```
output
1
104,638
9
209,277
Provide tags and a correct Python 3 solution for this coding contest problem. There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, …, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers. Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2. Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots. Input The first line contains two integers n and k (1 ≤ n ≤ k ≤ 10^5): the initial number of carrots and the number of rabbits. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^6): lengths of carrots. It is guaranteed that the sum of a_i is at least k. Output Output one integer: the minimum sum of time taken for rabbits to eat carrots. Examples Input 3 6 5 3 1 Output 15 Input 1 4 19 Output 91 Note For the first test, the optimal sizes of carrots are \{1,1,1,2,2,2\}. The time taken is 1^2+1^2+1^2+2^2+2^2+2^2=15 For the second test, the optimal sizes of carrots are \{4,5,5,5\}. The time taken is 4^2+5^2+5^2+5^2=91.
instruction
0
104,639
9
209,278
Tags: binary search, data structures, greedy, math, sortings Correct Solution: ``` import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------------------ def RL(): return map(int, sys.stdin.readline().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) def print_list(l): print(' '.join(map(str,l))) # import sys # sys.setrecursionlimit(5010) from heapq import * # from collections import deque as dq # from math import ceil,floor,sqrt,pow # import bisect as bs # from collections import Counter # from collections import defaultdict as dc n,k = RL() a = RLL() heap = [] dic = [[l,l**2,(l>>1)**2*2 if l&1==0 else (l>>1)**2+((l+1)>>1)**2,2] for l in a] for i in range(n): heap.append((dic[i][2]-dic[i][1],i)) heapify(heap) # print(heap) # print(dic) for _ in range(k-n): _,i = heap[0] dic[i][3]+=1 l,p = dic[i][0],dic[i][3] r,ll = l%p,l//p t = (p-r)*ll**2+r*(ll+1)**2 dic[i][1],dic[i][2] = dic[i][2],t heapreplace(heap,(dic[i][2]-dic[i][1],i)) # print(heap) # print(dic) print(sum(a[1] for a in dic)) ```
output
1
104,639
9
209,279
Provide tags and a correct Python 3 solution for this coding contest problem. There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, …, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers. Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2. Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots. Input The first line contains two integers n and k (1 ≤ n ≤ k ≤ 10^5): the initial number of carrots and the number of rabbits. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^6): lengths of carrots. It is guaranteed that the sum of a_i is at least k. Output Output one integer: the minimum sum of time taken for rabbits to eat carrots. Examples Input 3 6 5 3 1 Output 15 Input 1 4 19 Output 91 Note For the first test, the optimal sizes of carrots are \{1,1,1,2,2,2\}. The time taken is 1^2+1^2+1^2+2^2+2^2+2^2=15 For the second test, the optimal sizes of carrots are \{4,5,5,5\}. The time taken is 4^2+5^2+5^2+5^2=91.
instruction
0
104,640
9
209,280
Tags: binary search, data structures, greedy, math, sortings Correct Solution: ``` import sys from heapq import heapify, heappush, heappop def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c for j in range(b)] for i in range(a)] def list3d(a, b, c, d): return [[[d for k in range(c)] for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e for l in range(d)] for k 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**19 MOD = 10**9 + 7 EPS = 10**-10 N, K = MAP() A = LIST() def calc(a, cnt): d, m = divmod(a, cnt) return d**2 * (cnt-m) + (d+1)**2 * m que = [] for a in A: if a // 2 == 0: que.append((0, 1, a)) else: que.append((calc(a, 2) - calc(a, 1), 1, a)) heapify(que) for _ in range(K-N): val, cnt, a = heappop(que) if a // (cnt+2) == 0: heappush(que, (0, cnt+1, a)) else: heappush(que, (calc(a, cnt+2) - calc(a, cnt+1), cnt+1, a)) ans = 0 for _, cnt, a in que: ans += calc(a, cnt) print(ans) ```
output
1
104,640
9
209,281
Provide tags and a correct Python 3 solution for this coding contest problem. There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, …, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers. Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2. Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots. Input The first line contains two integers n and k (1 ≤ n ≤ k ≤ 10^5): the initial number of carrots and the number of rabbits. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^6): lengths of carrots. It is guaranteed that the sum of a_i is at least k. Output Output one integer: the minimum sum of time taken for rabbits to eat carrots. Examples Input 3 6 5 3 1 Output 15 Input 1 4 19 Output 91 Note For the first test, the optimal sizes of carrots are \{1,1,1,2,2,2\}. The time taken is 1^2+1^2+1^2+2^2+2^2+2^2=15 For the second test, the optimal sizes of carrots are \{4,5,5,5\}. The time taken is 4^2+5^2+5^2+5^2=91.
instruction
0
104,641
9
209,282
Tags: binary search, data structures, greedy, math, sortings Correct Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys #import threading from collections import defaultdict #threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase #sys.setrecursionlimit(300000) 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 # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=300006, 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 binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y 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------------------------------------ class TrieNode: def __init__(self): self.children = [None] * 26 self.isEndOfWord = False class Trie: def __init__(self): self.root = self.getNode() def getNode(self): return TrieNode() def _charToIndex(self, ch): return ord(ch) - ord('a') def insert(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: pCrawl.children[index] = self.getNode() pCrawl = pCrawl.children[index] pCrawl.isEndOfWord = True def search(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: return False pCrawl = pCrawl.children[index] return pCrawl != None and pCrawl.isEndOfWord #-----------------------------------------trie--------------------------------- class Node: def __init__(self, data): self.data = data self.count=0 self.left = None # left node for 0 self.right = None # right node for 1 class BinaryTrie: def __init__(self): self.root = Node(0) def insert(self, pre_xor): self.temp = self.root for i in range(31, -1, -1): val = pre_xor & (1 << i) if val: if not self.temp.right: self.temp.right = Node(0) self.temp = self.temp.right self.temp.count+=1 if not val: if not self.temp.left: self.temp.left = Node(0) self.temp = self.temp.left self.temp.count += 1 self.temp.data = pre_xor def query(self, xor): self.temp = self.root for i in range(31, -1, -1): val = xor & (1 << i) if not val: if self.temp.left and self.temp.left.count>0: self.temp = self.temp.left elif self.temp.right: self.temp = self.temp.right else: if self.temp.right and self.temp.right.count>0: self.temp = self.temp.right elif self.temp.left: self.temp = self.temp.left self.temp.count-=1 return xor ^ self.temp.data #-------------------------bin trie------------------------------------------- def find(a,left): now=(a%left)*(a//left+1)**2+(left-a%left)*(a//left)**2 left+=1 after=(a%left)*(a//left+1)**2+(left-a%left)*(a//left)**2 return now-after n,k=map(int,input().split()) a=list(map(int,input().split())) ans=0 for i in range(n): ans+=a[i]**2 a=[(-find(a[i],1),a[i],1) for i in range(n)] heapq.heapify(a) su=n while(su<k): e,t,no=heapq.heappop(a) ans+=e su+=1 heapq.heappush(a,(-find(t,no+1),t,no+1)) print(ans) ```
output
1
104,641
9
209,283